Statistics
| Branch: | Tag: | Revision:

amiro-os / core / src / aos_shell.c @ c18a848e

History | View | Annotate | Download (55 KB)

1
/*
2
AMiRo-OS is an operating system designed for the Autonomous Mini Robot (AMiRo) platform.
3
Copyright (C) 2016..2019  Thomas Schöpping et al.
4

5
This program is free software: you can redistribute it and/or modify
6
it under the terms of the GNU General Public License as published by
7
the Free Software Foundation, either version 3 of the License, or
8
(at your option) any later version.
9

10
This program is distributed in the hope that it will be useful,
11
but WITHOUT ANY WARRANTY; without even the implied warranty of
12
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13
GNU General Public License for more details.
14

15
You should have received a copy of the GNU General Public License
16
along with this program.  If not, see <http://www.gnu.org/licenses/>.
17
*/
18

    
19
/**
20
 * @file    aos_shell.c
21
 * @brief   Shell code.
22
 * @details Shell code as well as shell related channels and streams.
23
 *
24
 * @addtogroup aos_shell
25
 * @{
26
 */
27

    
28
#include <amiroos.h>
29
#include <string.h>
30

    
31
#if (AMIROOS_CFG_SHELL_ENABLE == true) || defined(__DOXYGEN__)
32

    
33
/******************************************************************************/
34
/* LOCAL DEFINITIONS                                                          */
35
/******************************************************************************/
36

    
37
/**
38
 * @brief   Event mask to be set on OS related events.
39
 */
40
#define AOS_SHELL_EVENTMASK_OS                  EVENT_MASK(0)
41

    
42
/**
43
 * @brief   Event mask to be set on a input event.
44
 */
45
#define AOS_SHELL_EVENTMASK_INPUT               EVENT_MASK(1)
46

    
47
/******************************************************************************/
48
/* EXPORTED VARIABLES                                                         */
49
/******************************************************************************/
50

    
51
/******************************************************************************/
52
/* LOCAL TYPES                                                                */
53
/******************************************************************************/
54

    
55
/*
56
 * forward declarations
57
 */
58
static size_t _channelwrite(void *instance, const uint8_t *bp, size_t n);
59
static size_t _channelread(void *instance, uint8_t *bp, size_t n);
60
static msg_t _channelput(void *instance, uint8_t b);
61
static msg_t _channelget(void *instance);
62
static msg_t _channelputt(void *instance, uint8_t b, sysinterval_t time);
63
static msg_t _channelgett(void *instance, sysinterval_t time);
64
static size_t _channelwritet(void *instance, const uint8_t *bp, size_t n, sysinterval_t time);
65
static size_t _channelreadt(void *instance, uint8_t *bp, size_t n, sysinterval_t time);
66
static msg_t _channelctl(void *instance, unsigned int operation, void *arg);
67
static size_t _streamwrite(void *instance, const uint8_t *bp, size_t n);
68
static size_t _stremread(void *instance, uint8_t *bp, size_t n);
69
static msg_t _streamput(void *instance, uint8_t b);
70
static msg_t _streamget(void *instance);
71

    
72
static const struct AosShellChannelVMT _channelvmt = {
73
  (size_t) 0,
74
  _channelwrite,
75
  _channelread,
76
  _channelput,
77
  _channelget,
78
  _channelputt,
79
  _channelgett,
80
  _channelwritet,
81
  _channelreadt,
82
  _channelctl,
83
};
84

    
85
static const struct AosShellStreamVMT _streamvmt = {
86
  (size_t) 0,
87
  _streamwrite,
88
  _stremread,
89
  _streamput,
90
  _streamget,
91
};
92

    
93
/**
94
 * @brief   Enumerator of special keyboard keys.
95
 */
96
typedef enum special_key {
97
  KEY_UNKNOWN,          /**< any/unknow key */
98
  KEY_AMBIGUOUS,        /**< key is ambiguous */
99
  KEY_TAB,              /**< tabulator key */
100
  KEY_ESCAPE,           /**< escape key */
101
  KEY_BACKSPACE,        /**< backspace key */
102
  KEY_INSERT,           /**< insert key */
103
  KEY_DELETE,           /**< delete key */
104
  KEY_HOME,             /**< home key */
105
  KEY_END,              /**< end key */
106
  KEY_PAGE_UP,          /**< page up key */
107
  KEY_PAGE_DOWN,        /**< page down key */
108
  KEY_ARROW_UP,         /**< arrow up key */
109
  KEY_ARROW_DOWN,       /**< arrow down key */
110
  KEY_ARROW_LEFT,       /**< arrow left key */
111
  KEY_ARROW_RIGHT,      /**< arrow right key */
112
  KEY_CTRL_ARROW_UP,    /**< CTRL + arrow up key */
113
  KEY_CTRL_ARROW_DOWN,  /**< CTRL + arrow down key */
114
  KEY_CTRL_ARROW_LEFT,  /**< CTRL + arrow left key */
115
  KEY_CTRL_ARROW_RIGHT, /**< CTRL + arrow right key */
116
} special_key_t;
117

    
118
/**
119
 * @brief   Enumerator for case (in)sensitive character matching.
120
 */
121
typedef enum charmatch {
122
  CHAR_MATCH_NOT    = 0,  /**< Characters do not match at all. */
123
  CHAR_MATCH_NCASE  = 1,  /**< Characters would match case insensitive. */
124
  CHAR_MATCH_CASE   = 2,  /**< Characters do match with case. */
125
} charmatch_t;
126

    
127
/******************************************************************************/
128
/* LOCAL VARIABLES                                                            */
129
/******************************************************************************/
130

    
131
/******************************************************************************/
132
/* LOCAL FUNCTIONS                                                            */
133
/******************************************************************************/
134

    
135
/**
136
 * @brief   Implementation of the BaseAsynchronous write() method (inherited from BaseSequentialStream).
137
 */
138
static size_t _channelwrite(void *instance, const uint8_t *bp, size_t n)
139
{
140
  if (((AosShellChannel*)instance)->flags & AOS_SHELLCHANNEL_OUTPUT_ENABLED) {
141
    return streamWrite(((AosShellChannel*)instance)->asyncchannel, bp, n);
142
  } else {
143
    return 0;
144
  }
145
}
146

    
147
/**
148
 * @brief   Implementation of the BaseAsynchronous read() method (inherited from BaseSequentialStream).
149
 */
150
static size_t _channelread(void *instance, uint8_t *bp, size_t n)
151
{
152
  if (((AosShellChannel*)instance)->flags & AOS_SHELLCHANNEL_INPUT_ENABLED) {
153
    return streamRead(((AosShellChannel*)instance)->asyncchannel, bp, n);
154
  } else {
155
    return 0;
156
  }
157
}
158

    
159
/**
160
 * @brief   Implementation of the BaseAsynchronous put() method (inherited from BaseSequentialStream).
161
 */
162
static msg_t _channelput(void *instance, uint8_t b)
163
{
164
  if (((AosShellChannel*)instance)->flags & AOS_SHELLCHANNEL_OUTPUT_ENABLED) {
165
    return streamPut(((AosShellChannel*)instance)->asyncchannel, b);
166
  } else {
167
    return MSG_RESET;
168
  }
169
}
170

    
171
/**
172
 * @brief   Implementation of the BaseAsynchronous get() method (inherited from BaseSequentialStream).
173
 */
174
static msg_t _channelget(void *instance)
175
{
176
  if (((AosShellChannel*)instance)->flags & AOS_SHELLCHANNEL_INPUT_ENABLED) {
177
    return streamGet(((AosShellChannel*)instance)->asyncchannel);
178
  } else {
179
    return MSG_RESET;
180
  }
181
}
182

    
183
/**
184
 * @brief   Implementation of the BaseAsynchronous putt() method.
185
 */
186
static msg_t _channelputt(void *instance, uint8_t b, sysinterval_t time)
187
{
188
  if (((AosShellChannel*)instance)->flags & AOS_SHELLCHANNEL_OUTPUT_ENABLED) {
189
    return chnPutTimeout(((AosShellChannel*)instance)->asyncchannel, b, time);
190
  } else {
191
    return MSG_RESET;
192
  }
193
}
194

    
195
/**
196
 * @brief   Implementation of the BaseAsynchronous gett() method.
197
 */
198
static msg_t _channelgett(void *instance, sysinterval_t time)
199
{
200
  if (((AosShellChannel*)instance)->flags & AOS_SHELLCHANNEL_INPUT_ENABLED) {
201
    return chnGetTimeout(((AosShellChannel*)instance)->asyncchannel, time);
202
  } else {
203
    return MSG_RESET;
204
  }
205
}
206

    
207
/**
208
 * @brief   Implementation of the BaseAsynchronous writet() method.
209
 */
210
static size_t _channelwritet(void *instance, const uint8_t *bp, size_t n, sysinterval_t time)
211
{
212
  if (((AosShellChannel*)instance)->flags & AOS_SHELLCHANNEL_OUTPUT_ENABLED) {
213
    return chnWriteTimeout(((AosShellChannel*)instance)->asyncchannel, bp, n, time);
214
  } else {
215
    return 0;
216
  }
217
}
218

    
219
/**
220
 * @brief   Implementation of the BaseAsynchronous readt() method.
221
 */
222
static size_t _channelreadt(void *instance, uint8_t *bp, size_t n, sysinterval_t time)
223
{
224
  if (((AosShellChannel*)instance)->flags & AOS_SHELLCHANNEL_INPUT_ENABLED) {
225
    return chnReadTimeout(((AosShellChannel*)instance)->asyncchannel, bp, n, time);
226
  } else {
227
    return 0;
228
  }
229
}
230

    
231
/**
232
 * @brief   Implementation of the BaseAsynchronousChannel ctl() method.
233
 */
234
static msg_t _channelctl(void *instance, unsigned int operation, void *arg)
235
{
236
  (void) instance;
237

    
238
  switch (operation) {
239
  case CHN_CTL_NOP:
240
    osalDbgCheck(arg == NULL);
241
    break;
242
  case CHN_CTL_INVALID:
243
    osalDbgAssert(false, "invalid CTL operation");
244
    break;
245
  default:
246
    break;
247
  }
248
  return MSG_OK;
249
}
250

    
251
static size_t _streamwrite(void *instance, const uint8_t *bp, size_t n)
252
{
253
  aosDbgCheck(instance != NULL);
254

    
255
  // local variables
256
  AosShellChannel* channel = ((AosShellStream*)instance)->channel;
257
  size_t bytes;
258
  size_t maxbytes = 0;
259

    
260
  // iterate through the list of channels
261
  while (channel != NULL) {
262
    bytes = streamWrite(channel, bp, n);
263
    maxbytes = (bytes > maxbytes) ? bytes : maxbytes;
264
    channel = channel->next;
265
  }
266

    
267
  return maxbytes;
268
}
269

    
270
static size_t _stremread(void *instance, uint8_t *bp, size_t n)
271
{
272
  (void)instance;
273
  (void)bp;
274
  (void)n;
275

    
276
  return 0;
277
}
278

    
279
static msg_t _streamput(void *instance, uint8_t b)
280
{
281
  aosDbgCheck(instance != NULL);
282

    
283
  // local variables
284
  AosShellChannel* channel = ((AosShellStream*)instance)->channel;
285
  msg_t ret = MSG_OK;
286

    
287
  // iterate through the list of channels
288
  while (channel != NULL) {
289
    msg_t ret_ = streamPut(channel, b);
290
    ret = (ret_ < ret) ? ret_ : ret;
291
    channel = channel->next;
292
  }
293

    
294
  return ret;
295
}
296

    
297
static msg_t _streamget(void *instance)
298
{
299
  (void)instance;
300

    
301
  return 0;
302
}
303

    
304
/**
305
 * @brief   Print the shell prompt
306
 * @details Depending on the configuration flags, the system uptime is printed before the prompt string.
307
 *
308
 * @param[in] shell   Pointer to the shell object.
309
 */
310
static void _printPrompt(aos_shell_t* shell)
311
{
312
  aosDbgCheck(shell != NULL);
313

    
314
  // print some time informattion before prompt if configured
315
  if (shell->config & (AOS_SHELL_CONFIG_PROMPT_UPTIME | AOS_SHELL_CONFIG_PROMPT_DATETIME)) {
316
    // printf the system uptime
317
    if ((shell->config & (AOS_SHELL_CONFIG_PROMPT_UPTIME | AOS_SHELL_CONFIG_PROMPT_DATETIME)) == AOS_SHELL_CONFIG_PROMPT_UPTIME) {
318
      // get current system uptime
319
      aos_timestamp_t uptime;
320
      aosSysGetUptime(&uptime);
321

    
322
      chprintf((BaseSequentialStream*)&shell->stream, "[%01u:%02u:%02u:%02u:%03u:%03u] ",
323
               (uint32_t)(uptime / MICROSECONDS_PER_DAY),
324
               (uint8_t)(uptime % MICROSECONDS_PER_DAY / MICROSECONDS_PER_HOUR),
325
               (uint8_t)(uptime % MICROSECONDS_PER_HOUR / MICROSECONDS_PER_MINUTE),
326
               (uint8_t)(uptime % MICROSECONDS_PER_MINUTE / MICROSECONDS_PER_SECOND),
327
               (uint16_t)(uptime % MICROSECONDS_PER_SECOND / MICROSECONDS_PER_MILLISECOND),
328
               (uint16_t)(uptime % MICROSECONDS_PER_MILLISECOND / MICROSECONDS_PER_MICROSECOND));
329
    }
330
#if (HAL_USE_RTC == TRUE)
331
    else if ((shell->config & (AOS_SHELL_CONFIG_PROMPT_UPTIME | AOS_SHELL_CONFIG_PROMPT_DATETIME)) == AOS_SHELL_CONFIG_PROMPT_DATETIME) {
332
      // get current RTC time
333
      struct tm dt;
334
      aosSysGetDateTime(&dt);
335
      chprintf((BaseSequentialStream*)&shell->stream, "[%02u-%02u-%04u|%02u:%02u:%02u] ",
336
               dt.tm_mday,
337
               dt.tm_mon + 1,
338
               dt.tm_year + 1900,
339
               dt.tm_hour,
340
               dt.tm_min,
341
               dt.tm_sec);
342
    }
343
#endif /* (HAL_USE_RTC == TRUE) */
344
    else {
345
      aosDbgAssert(false);
346
    }
347
  }
348

    
349
  // print the actual prompt string
350
  if (shell->prompt && !(shell->config & AOS_SHELL_CONFIG_PROMPT_MINIMAL)) {
351
    chprintf((BaseSequentialStream*)&shell->stream, "%s$ ", shell->prompt);
352
  } else {
353
    chprintf((BaseSequentialStream*)&shell->stream, "%>$ ");
354
  }
355

    
356
  return;
357
}
358

    
359
/**
360
 * @brief   Interprete a escape sequence
361
 * @details This function interpretes escape sequences (starting with ASCII
362
 *          "Escape" character 0x1B) according to the VT100 / VT52 ANSI escape
363
 *          sequence definitions.
364
 * @note    Only the most important escape sequences are implemented yet.
365
 *
366
 * @param[in] seq   Character sequence to interprete.
367
 *                  Must be terminated by NUL byte.
368
 *
369
 * @return          A @p special_key value.
370
 */
371
static special_key_t _interpreteEscapeSequence(const char seq[])
372
{
373
  // local variables
374
  char str[AOS_SHELL_ESCSEQUENCE_LENGTH];
375
  unsigned long strl = 0;
376
  const unsigned long seql = strlen(seq);
377
  bool ambiguous = false;
378

    
379
  // TAB
380
  /* not supported yet; use "\x09" instead */
381

    
382
  // BACKSPACE
383
  /* not supported yet; use "\x08" instead */
384

    
385
  // ESCAPE
386
  strncpy(str, "\x1B", AOS_SHELL_ESCSEQUENCE_LENGTH);
387
  strl = strlen(str);
388
  if (seql == strl && strncmp(seq, str, seql) == 0) {
389
    return KEY_ESCAPE;
390
  } else if(seql < strl && strncmp(seq, str, seql) == 0) {
391
    ambiguous = true;
392
  }
393

    
394
  // INSERT
395
  strncpy(str, "\x1B\x5B\x32\x7E", AOS_SHELL_ESCSEQUENCE_LENGTH);
396
  strl = strlen(str);
397
  if (seql == strl && strncmp(seq, str, seql) == 0) {
398
    return KEY_INSERT;
399
  } else if(seql < strl && strncmp(seq, str, seql) == 0) {
400
    ambiguous = true;
401
  }
402

    
403
  // DELETE
404
  strncpy(str, "\x1B\x5B\x33\x7E", AOS_SHELL_ESCSEQUENCE_LENGTH);
405
  strl = strlen(str);
406
  if (seql == strl && strncmp(seq, str, seql) == 0) {
407
    return KEY_DELETE;
408
  } else if(seql < strl && strncmp(seq, str, seql) == 0) {
409
    ambiguous = true;
410
  }
411

    
412
  // HOME
413
  strncpy(str, "\x1B\x5B\x48", AOS_SHELL_ESCSEQUENCE_LENGTH);
414
  strl = strlen(str);
415
  if (seql == strl && strncmp(seq, str, seql) == 0) {
416
    return KEY_HOME;
417
  } else if(seql < strl && strncmp(seq, str, seql) == 0) {
418
    ambiguous = true;
419
  }
420

    
421
  // END
422
  strncpy(str, "\x1B\x5B\x46", AOS_SHELL_ESCSEQUENCE_LENGTH);
423
  strl = strlen(str);
424
  if (seql == strl && strncmp(seq, str, seql) == 0) {
425
    return KEY_END;
426
  } else if(seql < strl && strncmp(seq, str, seql) == 0) {
427
    ambiguous = true;
428
  }
429

    
430
  // PAGE UP
431
  strncpy(str, "\x1B\x5B\x35\x7E", AOS_SHELL_ESCSEQUENCE_LENGTH);
432
  strl = strlen(str);
433
  if (seql == strl && strncmp(seq, str, seql) == 0) {
434
    return KEY_PAGE_UP;
435
  } else if(seql < strl && strncmp(seq, str, seql) == 0) {
436
    ambiguous = true;
437
  }
438

    
439
  // PAGE DOWN
440
  strncpy(str, "\x1B\x5B\x36\x7E", AOS_SHELL_ESCSEQUENCE_LENGTH);
441
  strl = strlen(str);
442
  if (seql == strl && strncmp(seq, str, seql) == 0) {
443
    return KEY_PAGE_DOWN;
444
  } else if(seql < strl && strncmp(seq, str, seql) == 0) {
445
    ambiguous = true;
446
  }
447

    
448
  // ARROW UP
449
  strncpy(str, "\x1B\x5B\x41", AOS_SHELL_ESCSEQUENCE_LENGTH);
450
  strl = strlen(str);
451
  if (seql == strl && strncmp(seq, str, seql) == 0) {
452
    return KEY_ARROW_UP;
453
  } else if(seql < strl && strncmp(seq, str, seql) == 0) {
454
    ambiguous = true;
455
  }
456

    
457
  // ARROW DOWN
458
  strncpy(str, "\x1B\x5B\x42", AOS_SHELL_ESCSEQUENCE_LENGTH);
459
  strl = strlen(str);
460
  if (seql == strl && strncmp(seq, str, seql) == 0) {
461
    return KEY_ARROW_DOWN;
462
  } else if (seql < strl && strncmp(seq, str, seql) == 0) {
463
    ambiguous = true;
464
  }
465

    
466
  // ARROW LEFT
467
  strncpy(str, "\x1B\x5B\x44", AOS_SHELL_ESCSEQUENCE_LENGTH);
468
  strl = strlen(str);
469
  if (seql == strl && strncmp(seq, str, seql) == 0) {
470
    return KEY_ARROW_LEFT;
471
  } else if (seql < strl && strncmp(seq, str, seql) == 0) {
472
    ambiguous = true;
473
  }
474

    
475
  // ARROW RIGHT
476
  strncpy(str, "\x1B\x5B\x43", AOS_SHELL_ESCSEQUENCE_LENGTH);
477
  strl = strlen(str);
478
  if (seql == strl && strncmp(seq, str, seql) == 0) {
479
    return KEY_ARROW_RIGHT;
480
  } else if (seql < strl && strncmp(seq, str, seql) == 0) {
481
    ambiguous = true;
482
  }
483

    
484
  // CTRL + ARROW UP
485
  strncpy(str, "\x1B\x5B\x31\x3B\x35\x41", AOS_SHELL_ESCSEQUENCE_LENGTH);
486
  strl = strlen(str);
487
  if (seql == strl && strncmp(seq, str, seql) == 0) {
488
    return KEY_CTRL_ARROW_UP;
489
  } else if(seql < strl && strncmp(seq, str, seql) == 0) {
490
    ambiguous = true;
491
  }
492

    
493
  // CTRL + ARROW DOWN
494
  strncpy(str, "\x1B\x5B\x31\x3B\x35\x42", AOS_SHELL_ESCSEQUENCE_LENGTH);
495
  strl = strlen(str);
496
  if (seql == strl && strncmp(seq, str, seql) == 0) {
497
    return KEY_CTRL_ARROW_DOWN;
498
  } else if(seql < strl && strncmp(seq, str, seql) == 0) {
499
    ambiguous = true;
500
  }
501

    
502
  // CTRL + ARROW LEFT
503
  strncpy(str, "\x1B\x5B\x31\x3B\x35\x44", AOS_SHELL_ESCSEQUENCE_LENGTH);
504
  strl = strlen(str);
505
  if (seql == strl && strncmp(seq, str, seql) == 0) {
506
    return KEY_CTRL_ARROW_LEFT;
507
  } else if(seql < strl && strncmp(seq, str, seql) == 0) {
508
    ambiguous = true;
509
  }
510

    
511
  // CTRL + ARROW RIGHT
512
  strncpy(str, "\x1B\x5B\x31\x3B\x35\x43", AOS_SHELL_ESCSEQUENCE_LENGTH);
513
  strl = strlen(str);
514
  if (seql == strl && strncmp(seq, str, seql) == 0) {
515
    return KEY_CTRL_ARROW_RIGHT;
516
  } else if(seql < strl && strncmp(seq, str, seql) == 0) {
517
    ambiguous = true;
518
  }
519

    
520
  return ambiguous ? KEY_AMBIGUOUS : KEY_UNKNOWN;
521
}
522

    
523
/**
524
 * @brief   Move the cursor in the terminal
525
 *
526
 * @param[in] shell   Pointer to the shell object.
527
 * @param[in] from    Starting position of the cursor.
528
 * @param[in] to      Target position to move the cursor to.
529
 *
530
 * @return            The number of positions moved.
531
 */
532
static int _moveCursor(aos_shell_t* shell, const size_t from, const size_t to)
533
{
534
  aosDbgCheck(shell != NULL);
535

    
536
  // local variables
537
  size_t pos = from;
538

    
539
  // move cursor left by printing backspaces
540
  while (pos > to) {
541
    streamPut(&shell->stream, '\b');
542
    --pos;
543
  }
544

    
545
  // move cursor right by printing line content
546
  while (pos < to) {
547
    streamPut(&shell->stream, (uint8_t)shell->input.line[pos]);
548
    ++pos;
549
  }
550

    
551
  return (int)pos - (int)from;
552
}
553

    
554
/**
555
 * @brief   Print content of the shell line
556
 *
557
 * @param[in] shell   Pointer to the shell object.
558
 * @param[in] from    First position to start printing from.
559
 * @param[in] to      Position after the last character to print.
560
 *
561
 * @return            Number of characters printed.
562
 */
563
static inline size_t _printLine(aos_shell_t* shell, const size_t from, const size_t to)
564
{
565
  aosDbgCheck(shell != NULL);
566

    
567
  // local variables
568
  size_t cnt;
569

    
570
  for (cnt = 0; from + cnt < to; ++cnt) {
571
    streamPut(&shell->stream, (uint8_t)shell->input.line[from + cnt]);
572
  }
573

    
574
  return cnt;
575
}
576

    
577
static int _readChar(aos_shell_t* shell, const char c) {
578
  aosDbgCheck(shell != NULL);
579

    
580
  // check whether input line is already full
581
  if (shell->inputdata.lineend + 1 >= shell->input.size) {
582
    return 0;
583
  } else {
584
    // clear old line content on first input
585
    if (shell->inputdata.noinput) {
586
      memset(shell->input.line, '\0', shell->input.size);
587
      shell->inputdata.noinput = false;
588
    }
589
    // overwrite content
590
    if (shell->config & AOS_SHELL_CONFIG_INPUT_OVERWRITE) {
591
      shell->input.line[shell->inputdata.cursorpos] = c;
592
      ++shell->inputdata.cursorpos;
593
      shell->inputdata.lineend = (shell->inputdata.cursorpos > shell->inputdata.lineend) ? shell->inputdata.cursorpos : shell->inputdata.lineend;
594
      streamPut(&shell->stream, (uint8_t)c);
595
    }
596
    // insert character
597
    else {
598
      memmove(&(shell->input.line[shell->inputdata.cursorpos+1]), &(shell->input.line[shell->inputdata.cursorpos]), shell->inputdata.lineend - shell->inputdata.cursorpos);
599
      shell->input.line[shell->inputdata.cursorpos] = c;
600
      ++shell->inputdata.lineend;
601
      _printLine(shell, shell->inputdata.cursorpos, shell->inputdata.lineend);
602
      ++shell->inputdata.cursorpos;
603
      _moveCursor(shell, shell->inputdata.lineend, shell->inputdata.cursorpos);
604
    }
605
    return 1;
606
  }
607
}
608

    
609
/**
610
 * @brief   Compare two characters.
611
 *
612
 * @param[in] lhs       First character to compare.
613
 * @param[in] rhs       Second character to compare.
614
 *
615
 * @return              How well the characters match.
616
 */
617
static inline charmatch_t _charcmp(char lhs, char rhs)
618
{
619
  // if lhs is a upper case letter and rhs is a lower case letter
620
  if (lhs >= 'A' && lhs <= 'Z' && rhs >= 'a' && rhs <= 'z') {
621
    return (lhs == (rhs - 'a' + 'A')) ? CHAR_MATCH_NCASE : CHAR_MATCH_NOT;
622
  }
623
  // if lhs is a lower case letter and rhs is a upper case letter
624
  else if (lhs >= 'a' && lhs <= 'z' && rhs >= 'A' && rhs <= 'Z') {
625
    return ((lhs - 'a' + 'A') == rhs) ? CHAR_MATCH_NCASE : CHAR_MATCH_NOT;
626
  }
627
  // default
628
  else {
629
    return (lhs == rhs) ? CHAR_MATCH_CASE : CHAR_MATCH_NOT;
630
  }
631
}
632

    
633
/**
634
 * @brief   Maps an character from ASCII to a modified custom encoding.
635
 * @details The custom character encoding is very similar to ASCII and has the following structure:
636
 *          0x00=NULL ... 0x40='@' (identically to ASCII)
637
 *          0x4A='a'; 0x4B='A'; 0x4C='b'; 0x4D='B' ... 0x73='z'; 0x74='Z' (custom letter order)
638
 *          0x75='[' ... 0x7A='`' (0x5B..0x60 is ASCII)
639
 *          0x7B='{' ... 0x7F=DEL (identically to ASCII)
640
 *
641
 * @param[in] c   Character to map to the custom encoding.
642
 *
643
 * @return    The customly encoded character.
644
 */
645
static inline char _mapAscii2Custom(const char c)
646
{
647
  if (c >= 'A' && c <= 'Z') {
648
    return ((c - 'A') * 2) + 'A' + 1;
649
  } else if (c > 'Z' && c < 'a') {
650
    return c + ('z' - 'a') + 1;
651
  } else if (c >= 'a' && c <= 'z') {
652
    return ((c - 'a') * 2) + 'A';
653
  } else {
654
    return c;
655
  }
656
}
657

    
658
/**
659
 * @brief   Compares two strings wrt letter case.
660
 * @details Comparisson uses a custom character encoding or mapping.
661
 *          See @p _mapAscii2Custom for details.
662
 *
663
 * @param[in] str1    First string to compare.
664
 * @param[in] str2    Second string to compare.
665
 * @param[in] cs      Flag indicating whether comparison shall be case sensitive.
666
 * @param[in,out] n   Maximum number of character to compare (in) and number of matching characters (out).
667
 *                    If a null pointer is specified, this parameter is ignored.
668
 *                    If the value pointed to is zero, comarison will not be limited.
669
 * @param[out] m      Optional indicator whether there was at least one case mismatch.
670
 *
671
 * @return      Integer value indicating the relationship between the strings.
672
 * @retval <0   The first character that does not match has a lower value in str1 than in str2.
673
 * @retval  0   The contents of both strings are equal.
674
 * @retval >0   The first character that does not match has a greater value in str1 than in str2.
675
 */
676
static int _strccmp(const char *str1, const char *str2, bool cs, size_t* n, charmatch_t* m)
677
{
678
  aosDbgCheck(str1 != NULL);
679
  aosDbgCheck(str2 != NULL);
680

    
681
  // initialize variables
682
  if (m) {
683
    *m = CHAR_MATCH_NOT;
684
  }
685
  size_t i = 0;
686

    
687
  // iterate through the strings
688
  while ((n == NULL) || (*n == 0) || (*n > 0 && i < *n)) {
689
    // break on NUL
690
    if (str1[i] == '\0' || str2[i] == '\0') {
691
      if (n) {
692
        *n = i;
693
      }
694
      break;
695
    }
696
    // compare character
697
    const charmatch_t match = _charcmp(str1[i], str2[i]);
698
    if ((match == CHAR_MATCH_CASE) || (!cs && match == CHAR_MATCH_NCASE)) {
699
      if (m != NULL && *m != CHAR_MATCH_NCASE) {
700
        *m = match;
701
      }
702
      ++i;
703
    } else {
704
      if (n) {
705
        *n = i;
706
      }
707
      break;
708
    }
709
  }
710

    
711
  return _mapAscii2Custom(str1[i]) - _mapAscii2Custom(str2[i]);
712
}
713

    
714
/**
715
 * @brief   Read input from a channel as long as there is data available.
716
 *
717
 * @param[in]   shell     Pointer to the shell object.
718
 * @param[in]   channel   The channel to read from.
719
 * @param[out]  exec      Optional pointer to a flag, which indicates, whether a command shall be executed.
720
 *
721
 * @return  Number of read characters.
722
 */
723
static int _readChannel(aos_shell_t* shell, AosShellChannel* channel, bool* execute)
724
{
725
  aosDbgCheck(shell != NULL);
726
  aosDbgCheck(channel != NULL);
727

    
728
  // local variables
729
  aos_shellaction_t action = AOS_SHELL_ACTION_NONE;
730
  char c;
731
  special_key_t key;
732
  int nchars = 0;
733
  bool exec = false;
734

    
735
  // read character by character from the channel
736
  while (chnReadTimeout(channel, (uint8_t*)&c, 1, TIME_IMMEDIATE)) {
737
    key = KEY_UNKNOWN;
738

    
739
    // drop any input after an execution request was detected
740
    if (exec) {
741
      continue;
742
    }
743

    
744
    // incremet character counter
745
    ++nchars;
746

    
747
    // parse escape sequence
748
    if (strlen(shell->inputdata.escseq) > 0) {
749
      shell->inputdata.escseq[strlen(shell->inputdata.escseq)] = c;
750
      key = _interpreteEscapeSequence(shell->inputdata.escseq);
751
      switch (key) {
752
        case KEY_AMBIGUOUS:
753
          // read next byte to resolve ambiguity
754
          continue;
755
        case KEY_UNKNOWN:
756
          // do nothing here, but handle the unknown sequence below
757
          break;
758
        default:
759
          // reset the sequence variable and buffer
760
          memset(shell->inputdata.escseq, '\0', sizeof(shell->inputdata.escseq)*sizeof(shell->inputdata.escseq[0]));
761
          break;
762
      }
763
    }
764

    
765
    /* interprete keys or character */
766
    {
767
      // default
768
      action = AOS_SHELL_ACTION_NONE;
769

    
770
      // printable character
771
      if (key == KEY_UNKNOWN && strlen(shell->inputdata.escseq) == 0 && c >= '\x20' && c <= '\x7E') {
772
        action = AOS_SHELL_ACTION_READCHAR;
773
      }
774

    
775
      // tab key or character
776
      else if (key == KEY_TAB || c == '\x09') {
777
        /*
778
         * pressing tab once applies auto fill
779
         * pressing tab a second time prints suggestions
780
         */
781
        if (shell->inputdata.lastaction == AOS_SHELL_ACTION_AUTOFILL || shell->inputdata.lastaction == AOS_SHELL_ACTION_SUGGEST) {
782
          action = AOS_SHELL_ACTION_SUGGEST;
783
        } else {
784
          action = AOS_SHELL_ACTION_AUTOFILL;
785
        }
786
      }
787

    
788
      // INS key
789
      else if (key == KEY_INSERT) {
790
        action = AOS_SHELL_ACTION_INSERTTOGGLE;
791
      }
792

    
793
      // DEL key or character
794
      else if (key == KEY_DELETE || c == '\x7F') {
795
        // ignore if cursor is at very right
796
        if (shell->inputdata.cursorpos < shell->inputdata.lineend) {
797
          action = AOS_SHELL_ACTION_DELETEFORWARD;
798
        }
799
      }
800

    
801
      // backspace key or character
802
      else if (key == KEY_BACKSPACE || c == '\x08') {
803
        // ignore if cursor is at very left
804
        if (shell->inputdata.cursorpos > 0) {
805
          action = AOS_SHELL_ACTION_DELETEBACKWARD;
806
        }
807
      }
808

    
809
      // 'page up', 'arrow up', or key or CTRL + 'arrow up' key combination
810
      else if (key == KEY_PAGE_UP || key == KEY_ARROW_UP || key == KEY_CTRL_ARROW_UP) {
811
        // ignore if there was some input
812
        if (shell->inputdata.noinput) {
813
          action = AOS_SHELL_ACTION_RECALLLAST;
814
        }
815
      }
816

    
817
      // 'page down' key, 'arrow down' key, 'end of test' character or 'end of transmission' character, or CTRL + 'arrow down' key combination
818
      else if (key == KEY_PAGE_DOWN || key == KEY_ARROW_DOWN || c == '\x03' || c == '\x03' || key == KEY_CTRL_ARROW_DOWN) {
819
        // ignore if line is empty
820
        if (shell->inputdata.lineend > 0) {
821
          action = AOS_SHELL_ACTION_CLEAR;
822
        }
823
      }
824

    
825
      // 'home' key
826
      else if (key == KEY_HOME) {
827
        // ignore if cursor is very left
828
        if (shell->inputdata.cursorpos > 0) {
829
          action = AOS_SHELL_ACTION_CURSOR2START;
830
        }
831
      }
832

    
833
      // 'end' key
834
      else if (key == KEY_END) {
835
        // ignore if cursos is very right
836
        if (shell->inputdata.cursorpos < shell->inputdata.lineend) {
837
          action = AOS_SHELL_ACTION_CURSOR2END;
838
        }
839
      }
840

    
841
      // 'arrow left' key
842
      else if (key == KEY_ARROW_LEFT) {
843
        // ignore if cursor is very left
844
        if (shell->inputdata.cursorpos > 0) {
845
          action = AOS_SHELL_ACTION_CURSORLEFT;
846
        }
847
      }
848

    
849
      // 'arrow right' key
850
      else if (key == KEY_ARROW_RIGHT) {
851
        // ignore if cursor is very right
852
        if (shell->inputdata.cursorpos < shell->inputdata.lineend) {
853
          action = AOS_SHELL_ACTION_CURSORRIGHT;
854
        }
855
      }
856

    
857
      // CTRL + 'arrow left' key combination
858
      else if (key == KEY_CTRL_ARROW_LEFT) {
859
        // ignore if cursor is very left
860
        if (shell->inputdata.cursorpos > 0) {
861
          action = AOS_SHELL_ACTION_CURSORWORDLEFT;
862
        }
863
      }
864

    
865
      // CTRL + 'arrow right' key combination
866
      else if (key == KEY_CTRL_ARROW_RIGHT) {
867
        // ignore if cursor is very right
868
        if (shell->inputdata.cursorpos < shell->inputdata.lineend) {
869
          action = AOS_SHELL_ACTION_CURSORWORDRIGHT;
870
        }
871
      }
872

    
873
      // carriage return ('\r') or line feed ('\n') character
874
      else if (c == '\x0D' || c == '\x0A') {
875
        action = AOS_SHELL_ACTION_EXECUTE;
876
      }
877

    
878
      // ESC key or [ESCAPE] character
879
      else if (key == KEY_ESCAPE || c == '\x1B') {
880
        action = AOS_SHELL_ACTION_ESCSTART;
881
      }
882

    
883
      // unknown escape sequence
884
      else if (key == KEY_UNKNOWN && strlen(shell->inputdata.escseq) > 0) {
885
        action = AOS_SHELL_ACTION_PRINTUNKNOWNSEQUENCE;
886
      }
887
    }
888

    
889
    /* handle function */
890
    switch (action) {
891
      case AOS_SHELL_ACTION_READCHAR:
892
      {
893
        if (_readChar(shell, c) == 0) {
894
          // line is full
895
          _moveCursor(shell, shell->inputdata.cursorpos, shell->inputdata.lineend);
896
          chprintf((BaseSequentialStream*)&shell->stream, "\n\tmaximum line width reached\n");
897
          _printPrompt(shell);
898
          _printLine(shell, 0, shell->inputdata.lineend);
899
          _moveCursor(shell, shell->inputdata.lineend, shell->inputdata.cursorpos);
900
        }
901
        break;
902
      }
903

    
904
      case AOS_SHELL_ACTION_AUTOFILL:
905
      {
906
        const char* fill = shell->input.line;
907
        size_t cmatch = shell->inputdata.cursorpos;
908
        charmatch_t matchlevel = CHAR_MATCH_NOT;
909
        size_t n;
910
        // iterate through command list
911
        for (aos_shellcommand_t* cmd = shell->commands; cmd != NULL; cmd = cmd->next) {
912
          // compare current match with command
913
          n = cmatch;
914
          charmatch_t mlvl = CHAR_MATCH_NOT;
915
          _strccmp(fill, cmd->name, shell->config & AOS_SHELL_CONFIG_MATCH_CASE, (n == 0) ? NULL : &n, &mlvl);
916
          const int cmp = (n < cmatch) ?
917
                            ((int)n - (int)cmatch) :
918
                            (cmd->name[n] != '\0') ?
919
                              (int)strlen(cmd->name) - (int)n :
920
                              0;
921
          // if an exact match was found
922
          if ((size_t)((int)cmatch + cmp) == shell->inputdata.cursorpos) {
923
            cmatch = shell->inputdata.cursorpos;
924
            fill = cmd->name;
925
            // break the loop only if there are no case mismatches with the input
926
            n = shell->inputdata.cursorpos;
927
            _strccmp(fill, shell->input.line, false, &n, &mlvl);
928
            if (mlvl == CHAR_MATCH_CASE) {
929
              break;
930
            }
931
          }
932
          // if a not exact match was found
933
          else if ((size_t)((int)cmatch + cmp) > shell->inputdata.cursorpos) {
934
            // if this is the first one
935
            if (fill == shell->input.line) {
936
              cmatch = (size_t)((int)cmatch + cmp);
937
              fill = cmd->name;
938
            }
939
            // if this is a worse one
940
            else if ((cmp < 0) || (cmp == 0 && mlvl == CHAR_MATCH_CASE)) {
941
              cmatch = (size_t)((int)cmatch + cmp);
942
            }
943
          }
944
          // non matching commands are ignored
945
          else {}
946
        }
947
        // evaluate if there are case mismatches
948
        n = cmatch;
949
        _strccmp(shell->input.line, fill, shell->config & AOS_SHELL_CONFIG_MATCH_CASE, &n, &matchlevel);
950
        // print the auto fill if any
951
        if (cmatch > shell->inputdata.cursorpos || (cmatch == shell->inputdata.cursorpos && matchlevel == CHAR_MATCH_NCASE)) {
952
          shell->inputdata.noinput = false;
953
          // limit auto fill so it will not overflow the line width
954
          if (shell->inputdata.lineend + (cmatch - shell->inputdata.cursorpos) > shell->input.size) {
955
            cmatch = shell->input.size - shell->inputdata.lineend + shell->inputdata.cursorpos;
956
          }
957
          // move trailing memory further in the line
958
          memmove(&(shell->input.line[cmatch]), &(shell->input.line[shell->inputdata.cursorpos]), shell->inputdata.lineend - shell->inputdata.cursorpos);
959
          shell->inputdata.lineend += cmatch - shell->inputdata.cursorpos;
960
          // if there was no incorrect case when matching
961
          if (matchlevel == CHAR_MATCH_CASE) {
962
            // insert fill command name to line
963
            memcpy(&(shell->input.line[shell->inputdata.cursorpos]), &(fill[shell->inputdata.cursorpos]), cmatch - shell->inputdata.cursorpos);
964
            // print the output
965
            _printLine(shell, shell->inputdata.cursorpos, shell->inputdata.lineend);
966
          } else {
967
            // overwrite line with fill command name
968
            memcpy(shell->input.line, fill, cmatch);
969
            // reprint the whole line
970
            _moveCursor(shell, shell->inputdata.cursorpos, 0);
971
            _printLine(shell, 0, shell->inputdata.lineend);
972
          }
973
          // move cursor to the end of the matching sequence
974
          shell->inputdata.cursorpos = cmatch;
975
          _moveCursor(shell, shell->inputdata.lineend, shell->inputdata.cursorpos);
976
        }
977
        break;
978
      }
979

    
980
      case AOS_SHELL_ACTION_SUGGEST:
981
      {
982
        unsigned int matches = 0;
983
        // iterate through command list
984
        for (aos_shellcommand_t* cmd = shell->commands; cmd != NULL; cmd = cmd->next) {
985
          // compare line content with command, excpet if cursorpos=0
986
          size_t i = shell->inputdata.cursorpos;
987
          if (shell->inputdata.cursorpos > 0) {
988
            _strccmp(shell->input.line, cmd->name, true, &i, NULL);
989
          }
990
          const int cmp = (i < shell->inputdata.cursorpos) ?
991
                            (int)(i - shell->inputdata.cursorpos) :
992
                            (cmd->name[i] != '\0') ?
993
                              (int)strlen(cmd->name) - (int)i :
994
                              0;
995
          // if a match was found
996
          if (cmp > 0) {
997
            // if this is the first one
998
            if (matches == 0) {
999
              _moveCursor(shell, shell->inputdata.cursorpos, shell->inputdata.lineend);
1000
              streamPut(&shell->stream, '\n');
1001
            }
1002
            // print the command
1003
            chprintf((BaseSequentialStream*)&shell->stream, "\t%s\n", cmd->name);
1004
            ++matches;
1005
          }
1006
        }
1007
        // reprint the prompt and line if any matches have been found
1008
        if (matches > 0) {
1009
          _printPrompt(shell);
1010
          _printLine(shell, 0, shell->inputdata.lineend);
1011
          _moveCursor(shell, shell->inputdata.lineend, shell->inputdata.cursorpos);
1012
          shell->inputdata.noinput = false;
1013
        }
1014
        break;
1015
      }
1016

    
1017
      case AOS_SHELL_ACTION_INSERTTOGGLE:
1018
      {
1019
        if (shell->config & AOS_SHELL_CONFIG_INPUT_OVERWRITE) {
1020
          shell->config &= ~AOS_SHELL_CONFIG_INPUT_OVERWRITE;
1021
        } else {
1022
          shell->config |= AOS_SHELL_CONFIG_INPUT_OVERWRITE;
1023
        }
1024
        break;
1025
      }
1026

    
1027
      case AOS_SHELL_ACTION_DELETEFORWARD:
1028
      {
1029
        --shell->inputdata.lineend;
1030
        memmove(&(shell->input.line[shell->inputdata.cursorpos]), &(shell->input.line[shell->inputdata.cursorpos+1]), shell->inputdata.lineend - shell->inputdata.cursorpos);
1031
        _printLine(shell, shell->inputdata.cursorpos, shell->inputdata.lineend);
1032
        streamPut(&shell->stream, ' ');
1033
        _moveCursor(shell, shell->inputdata.lineend + 1, shell->inputdata.cursorpos);
1034
        break;
1035
      }
1036

    
1037
      case AOS_SHELL_ACTION_DELETEBACKWARD:
1038
      {
1039
        --shell->inputdata.cursorpos;
1040
        memmove(&(shell->input.line[shell->inputdata.cursorpos]), &(shell->input.line[shell->inputdata.cursorpos+1]), shell->inputdata.lineend - shell->inputdata.cursorpos);
1041
        --shell->inputdata.lineend;
1042
        shell->input.line[shell->inputdata.lineend] = '\0';
1043
        _moveCursor(shell, shell->inputdata.cursorpos + 1, shell->inputdata.cursorpos);
1044
        _printLine(shell, shell->inputdata.cursorpos, shell->inputdata.lineend);
1045
        streamPut(&shell->stream, ' ');
1046
        _moveCursor(shell, shell->inputdata.lineend+1, shell->inputdata.cursorpos);
1047
        break;
1048
      }
1049

    
1050
      case AOS_SHELL_ACTION_RECALLLAST:
1051
      {
1052
        // replace any intermediate NUL bytes with spaces
1053
        shell->inputdata.lineend = 0;
1054
        size_t nul_start = 0;
1055
        size_t nul_end = 0;
1056
        // search line for a NUL byte
1057
        while (nul_start < shell->input.size) {
1058
          if (shell->input.line[nul_start] == '\0') {
1059
            nul_end = nul_start + 1;
1060
            // keep searcjing for a byte that is not NUL
1061
            while (nul_end < shell->input.size) {
1062
              if (shell->input.line[nul_end] != '\0') {
1063
                // an intermediate NUL sequence was found
1064
                memset(&(shell->input.line[nul_start]), ' ', nul_end - nul_start);
1065
                shell->inputdata.lineend = nul_end + 1;
1066
                break;
1067
              } else {
1068
                ++nul_end;
1069
              }
1070
            }
1071
            nul_start = nul_end + 1;
1072
          } else {
1073
            ++shell->inputdata.lineend;
1074
            ++nul_start;
1075
          }
1076
        }
1077
        shell->inputdata.cursorpos = shell->inputdata.lineend;
1078
        // print the line
1079
        shell->inputdata.noinput = _printLine(shell, 0, shell->inputdata.lineend) == 0;
1080
        break;
1081
      }
1082

    
1083
      case AOS_SHELL_ACTION_CLEAR:
1084
      {
1085
        // clear output
1086
        _moveCursor(shell, shell->inputdata.cursorpos, 0);
1087
        for (shell->inputdata.cursorpos = 0; shell->inputdata.cursorpos < shell->inputdata.lineend; ++shell->inputdata.cursorpos) {
1088
          streamPut(&shell->stream, ' ');
1089
        }
1090
        _moveCursor(shell, shell->inputdata.lineend, 0);
1091
        shell->inputdata.cursorpos = 0;
1092
        shell->inputdata.lineend = 0;
1093
        shell->inputdata.noinput = true;
1094
        break;
1095
      }
1096

    
1097
      case AOS_SHELL_ACTION_CURSOR2START:
1098
      {
1099
        _moveCursor(shell, shell->inputdata.cursorpos, 0);
1100
        shell->inputdata.cursorpos = 0;
1101
        break;
1102
      }
1103

    
1104
      case AOS_SHELL_ACTION_CURSOR2END:
1105
      {
1106
        _moveCursor(shell, shell->inputdata.cursorpos, shell->inputdata.lineend);
1107
        shell->inputdata.cursorpos = shell->inputdata.lineend;
1108
        break;
1109
      }
1110

    
1111
      case AOS_SHELL_ACTION_CURSORLEFT:
1112
      {
1113
        _moveCursor(shell, shell->inputdata.cursorpos, shell->inputdata.cursorpos-1);
1114
        --shell->inputdata.cursorpos;
1115
        break;
1116
      }
1117

    
1118
      case AOS_SHELL_ACTION_CURSORRIGHT:
1119
      {
1120
        _moveCursor(shell, shell->inputdata.cursorpos, shell->inputdata.cursorpos+1);
1121
        ++shell->inputdata.cursorpos;
1122
        break;
1123
      }
1124

    
1125
      case AOS_SHELL_ACTION_CURSORWORDLEFT:
1126
      {
1127
        size_t cpos = shell->inputdata.cursorpos;
1128
        while (cpos > 0 && shell->input.line[cpos-1] == ' ') {
1129
          --cpos;
1130
        }
1131
        while (cpos > 0 && shell->input.line[cpos-1] != ' ') {
1132
          --cpos;
1133
        }
1134
        _moveCursor(shell, shell->inputdata.cursorpos, cpos);
1135
        shell->inputdata.cursorpos = cpos;
1136
        break;
1137
      }
1138

    
1139
      case AOS_SHELL_ACTION_CURSORWORDRIGHT:
1140
      {
1141
        size_t cpos = shell->inputdata.cursorpos;
1142
        while (cpos < shell->inputdata.lineend && shell->input.line[cpos] != ' ') {
1143
          ++cpos;
1144
        }
1145
        while (cpos < shell->inputdata.lineend && shell->input.line[cpos] == ' ') {
1146
          ++cpos;
1147
        }
1148
        _moveCursor(shell, shell->inputdata.cursorpos, cpos);
1149
        shell->inputdata.cursorpos = cpos;
1150
        break;
1151
      }
1152

    
1153
      case AOS_SHELL_ACTION_EXECUTE:
1154
      {
1155
        streamPut(&shell->stream, '\n');
1156
        // if there was some input
1157
        if (!shell->inputdata.noinput) {
1158
          // fill the remainder of the line with NUL bytes
1159
          memset(&(shell->input.line[shell->inputdata.lineend]), '\0', shell->input.size - shell->inputdata.lineend);
1160
        }
1161
        // set the execution flag
1162
        exec = true;
1163
        break;
1164
      }
1165

    
1166
      case AOS_SHELL_ACTION_ESCSTART:
1167
      {
1168
        shell->inputdata.escseq[0] = c;
1169
        break;
1170
      }
1171

    
1172
      case AOS_SHELL_ACTION_PRINTUNKNOWNSEQUENCE:
1173
      {
1174
        size_t seqc = 1; // element 0 would be unprintible ESC character
1175
        while (shell->inputdata.escseq[seqc] != '\0') {
1176
          _readChar(shell, shell->inputdata.escseq[seqc]);
1177
          ++seqc;
1178
        }
1179
        memset(shell->inputdata.escseq, '\0', sizeof(shell->inputdata.escseq)*sizeof(shell->inputdata.escseq[0]));
1180
        break;
1181
      }
1182

    
1183
      case AOS_SHELL_ACTION_NONE:
1184
      {
1185
        // do nothing (ignore input) and read next byte
1186
        continue;
1187
      }
1188
    } /* end of switch */
1189

    
1190
    shell->inputdata.lastaction = action;
1191
  } /* end of while */
1192

    
1193
  // set the execution output flag
1194
  if (execute) {
1195
    *execute = exec;
1196
  }
1197

    
1198
  return nchars;
1199
}
1200

    
1201
/**
1202
 * @brief   Parses the content of the input buffer (line) to separate arguments.
1203
 *
1204
 * @param[in]   shell   Pointer to the shell object.
1205
 * @param[out]  argbuf  Buffer to store argument pointers to.
1206
 *
1207
 * @return            Number of arguments found.
1208
 */
1209
static size_t _parseArguments(aos_shell_t* shell, char** argbuf)
1210
{
1211
  aosDbgCheck(shell != NULL);
1212
  aosDbgCheck(argbuf != NULL);
1213

    
1214
  /*
1215
   * States for a very small FSM.
1216
   */
1217
  typedef enum {
1218
    START,
1219
    SPACE,
1220
    TEXT,
1221
    END,
1222
  } state_t;
1223

    
1224
  // local variables
1225
  state_t state = START;
1226
  size_t nargs = 0;
1227

    
1228
  // iterate through the line
1229
  for (char* c = shell->input.line; c < shell->input.line + shell->input.size; ++c) {
1230
    // terminate at first NUL byte
1231
    if (*c == '\0') {
1232
      state = END;
1233
      break;
1234
    }
1235
    // spaces become NUL bytes
1236
    else if (*c == ' ') {
1237
      *c = '\0';
1238
      state = SPACE;
1239
    }
1240
    // handle non-NUL bytes
1241
    else {
1242
      switch (state) {
1243
        case START:
1244
        case SPACE:
1245
          // ignore too many arguments
1246
          if (nargs < shell->input.nargs) {
1247
            argbuf[nargs] = c;
1248
          }
1249
          ++nargs;
1250
          break;
1251
        case TEXT:
1252
        case END:
1253
          break;
1254
      }
1255
      state = TEXT;
1256
    }
1257
  }
1258

    
1259
  // set all remaining argument pointers to NULL
1260
  for (size_t a = nargs; a < shell->input.nargs; ++a) {
1261
    argbuf[a] = NULL;
1262
  }
1263

    
1264
  return nargs;
1265
}
1266

    
1267
/******************************************************************************/
1268
/* EXPORTED FUNCTIONS                                                         */
1269
/******************************************************************************/
1270

    
1271
/**
1272
 * @brief   Initializes a shell object with the specified parameters.
1273
 *
1274
 * @param[in] shell         Pointer to the shell object.
1275
 * @param[in] stream        I/O stream to use.
1276
 * @param[in] prompt        Prompt line to print (NULL = use default prompt).
1277
 * @param[in] line          Pointer to the input buffer.
1278
 * @param[in] linesize      Size of the input buffer.
1279
 * @param[in] numargs       Maximum number of arguments (defines size of internal buffer).
1280
 */
1281
void aosShellInit(aos_shell_t* shell, event_source_t* oseventsource, const char* prompt, char* line, size_t linesize, size_t numargs)
1282
{
1283
  aosDbgCheck(shell != NULL);
1284
  aosDbgCheck(oseventsource != NULL);
1285
  aosDbgCheck(line != NULL);
1286

    
1287
  // set parameters
1288
  shell->thread = NULL;
1289
  chEvtObjectInit(&shell->eventSource);
1290
  shell->os.eventSource = oseventsource;
1291
  aosShellStreamInit(&shell->stream);
1292
  shell->prompt = prompt;
1293
  shell->commands = NULL;
1294
  shell->execstatus.command = NULL;
1295
  shell->execstatus.retval = 0;
1296
  shell->input.line = line;
1297
  shell->input.length = linesize;
1298
  shell->input.nargs= numargs;
1299
  shell->inputdata.lastaction = AOS_SHELL_ACTION_NONE;
1300
  memset(shell->inputdata.escseq, '\0', sizeof(shell->inputdata.escseq)*sizeof(shell->inputdata.escseq[0]));
1301
  shell->inputdata.cursorpos = 0;
1302
  shell->inputdata.lineend = 0;
1303
  shell->inputdata.noinput = true;
1304
  shell->config = 0x00;
1305

    
1306
  // initialize buffers
1307
  memset(shell->input.line, '\0', shell->input.length);
1308

    
1309
  return;
1310
}
1311

    
1312
/**
1313
 * @brief   Initialize an AosShellStream object.
1314
 *
1315
 * @param[in] stream  The AosShellStrem to initialize.
1316
 */
1317
void aosShellStreamInit(AosShellStream* stream)
1318
{
1319
  aosDbgCheck(stream != NULL);
1320

    
1321
  stream->vmt = &_streamvmt;
1322
  stream->channel = NULL;
1323

    
1324
  return;
1325
}
1326

    
1327
/**
1328
 * @brief   Initialize an AosShellChannel object with the specified parameters.
1329
 *
1330
 * @param[in] channel       The AosShellChannel to initialize.
1331
 * @param[in] asyncchannel  An BaseAsynchronousChannel this AosShellChannel is associated with.
1332
 */
1333
void aosShellChannelInit(AosShellChannel* channel, BaseAsynchronousChannel* asyncchannel)
1334
{
1335
  aosDbgCheck(channel != NULL);
1336
  aosDbgCheck(asyncchannel != NULL);
1337

    
1338
  channel->vmt = &_channelvmt;
1339
  channel->asyncchannel = asyncchannel;
1340
  channel->listener.wflags = 0;
1341
  channel->next = NULL;
1342
  channel->flags = 0;
1343

    
1344
  return;
1345
}
1346

    
1347
/**
1348
 * @brief   Inserts a command to the shells list of commands.
1349
 *
1350
 * @param[in] shell   Pointer to the shell object.
1351
 * @param[in] cmd     Pointer to the command to add.
1352
 *
1353
 * @return            A status value.
1354
 * @retval AOS_SUCCESS  The command was added successfully.
1355
 * @retval AOS_ERROR    Another command with identical name already exists.
1356
 */
1357
aos_status_t aosShellAddCommand(aos_shell_t *shell, aos_shellcommand_t *cmd)
1358
{
1359
  aosDbgCheck(shell != NULL);
1360
  aosDbgCheck(cmd != NULL);
1361
  aosDbgCheck(cmd->name != NULL && strlen(cmd->name) > 0 && strchr(cmd->name, ' ') == NULL && strchr(cmd->name, '\t') == NULL);
1362
  aosDbgCheck(cmd->callback != NULL);
1363
  aosDbgCheck(cmd->next == NULL);
1364

    
1365
  aos_shellcommand_t* prev = NULL;
1366
  aos_shellcommand_t** curr = &(shell->commands);
1367

    
1368
  // insert the command to the list wrt lexographical order (exception: lower case characters preceed upper their uppercase counterparts)
1369
  while (*curr != NULL) {
1370
    // iterate through the list as long as the command names are 'smaller'
1371
    const int cmp = _strccmp((*curr)->name, cmd->name, true, NULL, NULL);
1372
    if (cmp < 0) {
1373
      prev = *curr;
1374
      curr = &((*curr)->next);
1375
      continue;
1376
    }
1377
    // error if the command already exists
1378
    else if (cmp == 0) {
1379
      return AOS_ERROR;
1380
    }
1381
    // insert the command as soon as a 'larger' name was found
1382
    else /* if (cmpval > 0) */ {
1383
      cmd->next = *curr;
1384
      // special case: the first command is larger
1385
      if (prev == NULL) {
1386
        shell->commands = cmd;
1387
      } else {
1388
        prev->next = cmd;
1389
      }
1390
      return AOS_SUCCESS;
1391
    }
1392
  }
1393
  // the end of the list has been reached
1394

    
1395
  // append the command
1396
  *curr = cmd;
1397
  return AOS_SUCCESS;
1398
}
1399

    
1400
/**
1401
 * @brief   Removes a command from the shells list of commands.
1402
 *
1403
 * @param[in] shell     Pointer to the shell object.
1404
 * @param[in] cmd       Name of the command to removde.
1405
 * @param[out] removed  Optional pointer to the command that was removed.
1406
 *
1407
 * @return              A status value.
1408
 * @retval AOS_SUCCESS  The command was removed successfully.
1409
 * @retval AOS_ERROR    The command name was not found.
1410
 */
1411
aos_status_t aosShellRemoveCommand(aos_shell_t *shell, char *cmd, aos_shellcommand_t **removed)
1412
{
1413
  aosDbgCheck(shell != NULL);
1414
  aosDbgCheck(cmd != NULL && strlen(cmd) > 0);
1415

    
1416
  aos_shellcommand_t* prev = NULL;
1417
  aos_shellcommand_t** curr = &(shell->commands);
1418

    
1419
  // iterate through the list and seach for the specified command name
1420
  while (curr != NULL) {
1421
    const int cmpval = strcmp((*curr)->name, cmd);
1422
    // iterate through the list as long as the command names are 'smaller'
1423
    if (cmpval < 0) {
1424
      prev = *curr;
1425
      curr = &((*curr)->next);
1426
      continue;
1427
    }
1428
    // remove the command when found
1429
    else if (cmpval == 0) {
1430
      // special case: the first command matches
1431
      if (prev == NULL) {
1432
        shell->commands = (*curr)->next;
1433
      } else {
1434
        prev->next = (*curr)->next;
1435
      }
1436
      (*curr)->next = NULL;
1437
      // set the optional output argument
1438
      if (removed != NULL) {
1439
        *removed = *curr;
1440
      }
1441
      return AOS_SUCCESS;
1442
    }
1443
    // break the loop if the command names are 'larger'
1444
    else /* if (cmpval > 0) */ {
1445
      break;
1446
    }
1447
  }
1448

    
1449
  // if the command was not found, return an error
1450
  return AOS_ERROR;
1451
}
1452

    
1453
/**
1454
 * @brief   Count the number of commands assigned to the shell.
1455
 *
1456
 * @param[in] shell   The shell to count the commands for.
1457
 *
1458
 * @return  The number of commands associated to the shell.
1459
 */
1460
unsigned int aosShellCountCommands(aos_shell_t* shell)
1461
{
1462
  aosDbgCheck(shell != NULL);
1463

    
1464
  unsigned int count = 0;
1465
  aos_shellcommand_t* cmd = shell->commands;
1466
  while (cmd != NULL) {
1467
    ++count;
1468
    cmd = cmd->next;
1469
  }
1470

    
1471
  return count;
1472
}
1473

    
1474
/**
1475
 * @brief   Add a channel to a AosShellStream.
1476
 *
1477
 * @param[in] stream    The AosShellStream to extend.
1478
 * @param[in] channel   The channel to be added to the stream.
1479
 */
1480
void aosShellStreamAddChannel(AosShellStream* stream, AosShellChannel* channel)
1481
{
1482
  aosDbgCheck(stream != NULL);
1483
  aosDbgCheck(channel != NULL && channel->asyncchannel != NULL && channel->next == NULL && (channel->flags & AOS_SHELLCHANNEL_ATTACHED) == 0);
1484

    
1485
  // prepend the new channel
1486
  chSysLock();
1487
  channel->flags |= AOS_SHELLCHANNEL_ATTACHED;
1488
  channel->next = stream->channel;
1489
  stream->channel = channel;
1490
  chSysUnlock();
1491

    
1492
  return;
1493
}
1494

    
1495
/**
1496
 * @brief   Remove a channel from an AosShellStream.
1497
 *
1498
 * @param[in] stream    The AosShellStream to modify.
1499
 * @param[in] channel   The channel to remove.
1500
 *
1501
 * @return              A status value.
1502
 * @retval AOS_SUCCESS  The channel was removed successfully.
1503
 * @retval AOS_ERROR    The specified channel was not found to be associated with the shell.
1504
 */
1505
aos_status_t aosShellStreamRemoveChannel(AosShellStream* stream, AosShellChannel* channel)
1506
{
1507
  aosDbgCheck(stream != NULL);
1508
  aosDbgCheck(channel != NULL && channel->asyncchannel != NULL && channel->flags & AOS_SHELLCHANNEL_ATTACHED);
1509

    
1510
  // local varibales
1511
  AosShellChannel* prev = NULL;
1512
  AosShellChannel* curr = stream->channel;
1513

    
1514
  // iterate through the list and search for the specified channel
1515
  while (curr != NULL) {
1516
    // if the channel was found
1517
    if (curr == channel) {
1518
      chSysLock();
1519
      // special case: the first channel matches (prev is NULL)
1520
      if (prev == NULL) {
1521
        stream->channel = curr->next;
1522
      } else {
1523
        prev->next = channel->next;
1524
      }
1525
      curr->next = NULL;
1526
      curr->flags &= ~AOS_SHELLCHANNEL_ATTACHED;
1527
      chSysUnlock();
1528
      return AOS_SUCCESS;
1529
    }
1530
  }
1531

    
1532
  // if the channel was not found, return an error
1533
  return AOS_ERROR;
1534
}
1535

    
1536
/**
1537
 * @brief   Enable a AosShellChannel as input.
1538
 *
1539
 * @param[in] channel   The channel to enable as input.
1540
 */
1541
void aosShellChannelInputEnable(AosShellChannel* channel)
1542
{
1543
  aosDbgCheck(channel != NULL && channel->asyncchannel != NULL);
1544

    
1545
  chSysLock();
1546
  channel->listener.wflags |= CHN_INPUT_AVAILABLE;
1547
  channel->flags |= AOS_SHELLCHANNEL_INPUT_ENABLED;
1548
  chSysUnlock();
1549

    
1550
  return;
1551
}
1552

    
1553
/**
1554
 * @brief   Disable a AosShellChannel as input.
1555
 *
1556
 * @param[in] channel   The channel to disable as input.
1557
 */
1558
void aosShellChannelInputDisable( AosShellChannel* channel)
1559
{
1560
  aosDbgCheck(channel != NULL && channel->asyncchannel != NULL);
1561

    
1562
  chSysLock();
1563
  channel->listener.wflags &= ~CHN_INPUT_AVAILABLE;
1564
  channel->flags &= ~AOS_SHELLCHANNEL_INPUT_ENABLED;
1565
  chSysUnlock();
1566

    
1567
  return;
1568
}
1569

    
1570
/**
1571
 * @brief   Enable a AosShellChannel as output.
1572
 *
1573
 * @param[in] channel   The channel to enable as output.
1574
 */
1575
void aosShellChannelOutputEnable(AosShellChannel* channel)
1576
{
1577
  aosDbgCheck(channel != NULL && channel->asyncchannel != NULL);
1578

    
1579
  channel->flags |= AOS_SHELLCHANNEL_OUTPUT_ENABLED;
1580

    
1581
  return;
1582
}
1583

    
1584
/**
1585
 * @brief   Disable a AosShellChannel as output.
1586
 *
1587
 * @param[in] channel   The channel to disable as output.
1588
 */
1589
void aosShellChannelOutputDisable(AosShellChannel* channel)
1590
{
1591
  aosDbgCheck(channel != NULL && channel->asyncchannel != NULL);
1592

    
1593
  channel->flags &= ~AOS_SHELLCHANNEL_OUTPUT_ENABLED;
1594

    
1595
  return;
1596
}
1597

    
1598
/**
1599
 * @brief   Thread main function.
1600
 *
1601
 * @param[in] aosShellThread    Name of the function;
1602
 * @param[in] shell             Pointer to the shell object.
1603
 */
1604
void aosShellThread(void* shell)
1605
{
1606
  aosDbgCheck(shell != NULL);
1607

    
1608
  // local variables
1609
  eventmask_t eventmask;
1610
  eventflags_t eventflags;
1611
  AosShellChannel* channel;
1612
  bool execute;
1613
  char* args[((aos_shell_t*)shell)->input.nargs];
1614
  size_t nargs = 0;
1615
  aos_shellcommand_t* cmd;
1616

    
1617
  // initialize variables
1618
  for (size_t arg = 0; arg < ((aos_shell_t*)shell)->input.nargs; ++arg) {
1619
    args[arg] = NULL;
1620
  }
1621

    
1622
  // register OS related events
1623
  chEvtRegisterMask(((aos_shell_t*)shell)->os.eventSource, &(((aos_shell_t*)shell)->os.eventListener), AOS_SHELL_EVENTMASK_OS);
1624
  // register events to all input channels
1625
  for (channel = ((aos_shell_t*)shell)->stream.channel; channel != NULL; channel = channel->next) {
1626
    chEvtRegisterMaskWithFlags(&(channel->asyncchannel->event), &(channel->listener), AOS_SHELL_EVENTMASK_INPUT, channel->listener.wflags);
1627
  }
1628

    
1629
  // fire start event
1630
  chEvtBroadcastFlags(&(((aos_shell_t*)shell)->eventSource), AOS_SHELL_EVTFLAG_START);
1631

    
1632
  // print the prompt for the first time
1633
  _printPrompt((aos_shell_t*)shell);
1634

    
1635
  // enter thread loop
1636
  while (!chThdShouldTerminateX()) {
1637
    // wait for event and handle it accordingly
1638
    eventmask = chEvtWaitOne(ALL_EVENTS);
1639

    
1640
    // handle event
1641
    switch (eventmask) {
1642

    
1643
      // OS related events
1644
      case AOS_SHELL_EVENTMASK_OS:
1645
      {
1646
        eventflags = chEvtGetAndClearFlags(&((aos_shell_t*)shell)->os.eventListener);
1647
        // handle shutdown/restart events
1648
        if (eventflags & AOS_SYSTEM_EVENTFLAGS_SHUTDOWN_MASK) {
1649
          chThdTerminate(((aos_shell_t*)shell)->thread);
1650
        } else {
1651
          // print an error message
1652
          chprintf((BaseSequentialStream*)&((aos_shell_t*)shell)->stream, "\nERROR: unknown OS event received (0x%08X)\n", eventflags);
1653
        }
1654
        break;
1655
      }
1656

    
1657
      // input events
1658
      case AOS_SHELL_EVENTMASK_INPUT:
1659
      {
1660
        // check and handle all channels
1661
        channel = ((aos_shell_t*)shell)->stream.channel;
1662
        while (channel != NULL) {
1663
          eventflags = chEvtGetAndClearFlags(&channel->listener);
1664
          // if there is new input and a command shall be executed
1665
          if (eventflags & CHN_INPUT_AVAILABLE) {
1666
            _readChannel((aos_shell_t*)shell, channel, &execute);
1667
            // an execution request was detected
1668
            if (execute && !((aos_shell_t*)shell)->inputdata.noinput) {
1669
              // parse input line to argument list
1670
              nargs = _parseArguments((aos_shell_t*)shell, args);
1671
              // check number of arguments
1672
              if (nargs > ((aos_shell_t*)shell)->input.nargs) {
1673
                // error too many arguments
1674
                chprintf((BaseSequentialStream*)&((aos_shell_t*)shell)->stream, "\ttoo many arguments\n");
1675
              } else if (nargs > 0) {
1676
                // search command list for arg[0] and execute callback
1677
                cmd = ((aos_shell_t*)shell)->commands;
1678
                while (cmd != NULL) {
1679
                  if (strcmp(args[0], cmd->name) == 0) {
1680
                    ((aos_shell_t*)shell)->execstatus.command = cmd;
1681
                    chEvtBroadcastFlags(&(((aos_shell_t*)shell)->eventSource), AOS_SHELL_EVTFLAG_EXEC);
1682
                    ((aos_shell_t*)shell)->execstatus.retval = cmd->callback((BaseSequentialStream*)&((aos_shell_t*)shell)->stream, (int)nargs, args);
1683
                    chEvtBroadcastFlags(&(((aos_shell_t*)shell)->eventSource), AOS_SHELL_EVTFLAG_DONE);
1684
                    // notify if the command was not successful
1685
                    if (((aos_shell_t*)shell)->execstatus.retval != 0) {
1686
                      chprintf((BaseSequentialStream*)&((aos_shell_t*)shell)->stream, "command returned exit status %d\n", ((aos_shell_t*)shell)->execstatus.retval);
1687
                    }
1688
                    break;
1689
                  }
1690
                  cmd = cmd->next;
1691
                } /* end of while */
1692

    
1693
                // if no matching command was found, print an error
1694
                if (cmd == NULL) {
1695
                  chprintf((BaseSequentialStream*)&((aos_shell_t*)shell)->stream, "\tcommand '%s' not found\n", args[0]);
1696
                }
1697
              }
1698
            }
1699

    
1700
            // reset some internal variables and print a new prompt
1701
            if (execute && !chThdShouldTerminateX()) {
1702
              ((aos_shell_t*)shell)->inputdata.cursorpos = 0;
1703
              ((aos_shell_t*)shell)->inputdata.lineend = 0;
1704
              ((aos_shell_t*)shell)->inputdata.noinput = true;
1705
              _printPrompt((aos_shell_t*)shell);
1706
            }
1707
          }
1708

    
1709
          // iterate to next channel
1710
          channel = channel->next;
1711
        }
1712
        break;
1713
      }
1714

    
1715
      // other events
1716
      default:
1717
      {
1718
        // print an error message
1719
        chprintf((BaseSequentialStream*)&((aos_shell_t*)shell)->stream, "\nSHELL: ERROR: unknown event received (0x%08X)\n", eventmask);
1720
        break;
1721
      }
1722

    
1723
    } /* end of switch */
1724

    
1725
  } /* end of while */
1726

    
1727
  // fire event and exit the thread
1728
  chSysLock();
1729
  chEvtBroadcastFlagsI(&(((aos_shell_t*)shell)->eventSource), AOS_SHELL_EVTFLAG_EXIT);
1730
  chThdExitS(MSG_OK);
1731
  // no chSysUnlock() required since the thread has been terminated an all waiting threads have been woken up
1732
}
1733

    
1734
#endif /* (AMIROOS_CFG_SHELL_ENABLE == true) */
1735

    
1736
/** @} */