Statistics
| Branch: | Tag: | Revision:

amiro-os / core / src / aos_shell.c @ 3940ba8a

History | View | Annotate | Download (49.4 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) || (AMIROOS_CFG_TESTS_ENABLE == true)
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
} special_key_t;
113

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

    
123
/******************************************************************************/
124
/* LOCAL VARIABLES                                                            */
125
/******************************************************************************/
126

    
127
/******************************************************************************/
128
/* LOCAL FUNCTIONS                                                            */
129
/******************************************************************************/
130

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

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

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

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

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

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

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

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

    
227
/**
228
 * @brief   Implementation of the BaseAsynchronousChannel ctl() method.
229
 */
230
static msg_t _channelctl(void *instance, unsigned int operation, void *arg)
231
{
232
  (void) instance;
233

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

    
247
static size_t _streamwrite(void *instance, const uint8_t *bp, size_t n)
248
{
249
  aosDbgCheck(instance != NULL);
250

    
251
  // local variables
252
  AosShellChannel* channel = ((AosShellStream*)instance)->channel;
253
  size_t bytes;
254
  size_t maxbytes = 0;
255

    
256
  // iterate through the list of channels
257
  while (channel != NULL) {
258
    bytes = streamWrite(channel, bp, n);
259
    maxbytes = (bytes > maxbytes) ? bytes : maxbytes;
260
    channel = channel->next;
261
  }
262

    
263
  return maxbytes;
264
}
265

    
266
static size_t _stremread(void *instance, uint8_t *bp, size_t n)
267
{
268
  (void)instance;
269
  (void)bp;
270
  (void)n;
271

    
272
  return 0;
273
}
274

    
275
static msg_t _streamput(void *instance, uint8_t b)
276
{
277
  aosDbgCheck(instance != NULL);
278

    
279
  // local variables
280
  AosShellChannel* channel = ((AosShellStream*)instance)->channel;
281
  msg_t ret = MSG_OK;
282

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

    
290
  return ret;
291
}
292

    
293
static msg_t _streamget(void *instance)
294
{
295
  (void)instance;
296

    
297
  return 0;
298
}
299

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

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

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

    
343
  // print the actual prompt string
344
  if (shell->prompt && !(shell->config & AOS_SHELL_CONFIG_PROMPT_MINIMAL)) {
345
    chprintf((BaseSequentialStream*)&shell->stream, "%s$ ", shell->prompt);
346
  } else {
347
    chprintf((BaseSequentialStream*)&shell->stream, "%>$ ");
348
  }
349

    
350
  return;
351
}
352

    
353
/**
354
 * @brief   Interprete a escape sequence
355
 *
356
 * @param[in] seq   Character sequence to interprete.
357
 *                  Must be terminated by NUL byte.
358
 *
359
 * @return          A @p special_key value.
360
 */
361
static special_key_t _interpreteEscapeSequence(const char seq[])
362
{
363
  // local variables
364
  bool ambiguous = false;
365
  int cmp = 0;
366

    
367
  // TAB
368
  /* not supported yet; use "\x09" instead */
369

    
370
  // BACKSPACE
371
  /* not supported yet; use "\x08" instead */
372

    
373
  // ESCAPE
374
  cmp = strcmp(seq, "\x1B");
375
  if (cmp == 0) {
376
    return KEY_ESCAPE;
377
  } else {
378
    ambiguous |= (cmp < 0);
379
  }
380

    
381
  // INSERT
382
  cmp = strcmp(seq, "\x1B\x5B\x32\x7E");
383
  if (cmp == 0) {
384
    return KEY_INSERT;
385
  } else {
386
    ambiguous |= (cmp < 0);
387
  }
388

    
389
  // DELETE
390
  cmp = strcmp(seq, "\x1B\x5B\x33\x7E");
391
  if (cmp == 0) {
392
    return KEY_DELETE;
393
  } else {
394
    ambiguous |= (cmp < 0);
395
  }
396

    
397
  // HOME
398
  cmp = strcmp(seq, "\x1B\x4F\x48");
399
  if (cmp == 0) {
400
    return KEY_HOME;
401
  } else {
402
    ambiguous |= (cmp < 0);
403
  }
404

    
405
  // END
406
  cmp = strcmp(seq, "\x1B\x4F\x46");
407
  if (cmp == 0) {
408
    return KEY_END;
409
  } else {
410
    ambiguous |= (cmp < 0);
411
  }
412

    
413
  // PAGE UP
414
  cmp = strcmp(seq, "\x1B\x5B\x35\x7E");
415
  if (cmp == 0) {
416
    return KEY_PAGE_UP;
417
  } else {
418
    ambiguous |= (cmp < 0);
419
  }
420

    
421
  // PAGE DOWN
422
  cmp = strcmp(seq, "\x1B\x5B\x36\x7E");
423
  if (cmp == 0) {
424
    return KEY_PAGE_DOWN;
425
  } else {
426
    ambiguous |= (cmp < 0);
427
  }
428

    
429
  // ARROW UP
430
  cmp = strcmp(seq, "\x1B\x5B\x41");
431
  if (cmp == 0) {
432
    return KEY_ARROW_UP;
433
  } else {
434
    ambiguous |= (cmp < 0);
435
  }
436

    
437
  // ARROW DOWN
438
  cmp = strcmp(seq, "\x1B\x5B\x42");
439
  if (cmp == 0) {
440
    return KEY_ARROW_DOWN;
441
  } else {
442
    ambiguous |= (cmp < 0);
443
  }
444

    
445
  // ARROW LEFT
446
  cmp = strcmp(seq, "\x1B\x5B\x44");
447
  if (cmp == 0) {
448
    return KEY_ARROW_LEFT;
449
  } else {
450
    ambiguous |= (cmp < 0);
451
  }
452

    
453
  // ARROW RIGHT
454
  cmp = strcmp(seq, "\x1B\x5B\x43");
455
  if (cmp == 0) {
456
    return KEY_ARROW_RIGHT;
457
  } else {
458
    ambiguous |= (cmp < 0);
459
  }
460

    
461
  return ambiguous ? KEY_AMBIGUOUS : KEY_UNKNOWN;
462
}
463

    
464
/**
465
 * @brief   Move the cursor in the terminal
466
 *
467
 * @param[in] shell   Pointer to the shell object.
468
 * @param[in] from    Starting position of the cursor.
469
 * @param[in] to      Target position to move the cursor to.
470
 *
471
 * @return            The number of positions moved.
472
 */
473
static int _moveCursor(aos_shell_t* shell, const size_t from, const size_t to)
474
{
475
  aosDbgCheck(shell != NULL);
476

    
477
  // local variables
478
  size_t pos = from;
479

    
480
  // move cursor left by printing backspaces
481
  while (pos > to) {
482
    streamPut(&shell->stream, '\b');
483
    --pos;
484
  }
485

    
486
  // move cursor right by printing line content
487
  while (pos < to) {
488
    streamPut(&shell->stream, shell->line[pos]);
489
    ++pos;
490
  }
491

    
492
  return (int)pos - (int)from;
493
}
494

    
495
/**
496
 * @brief   Print content of the shell line
497
 *
498
 * @param[in] shell   Pointer to the shell object.
499
 * @param[in] from    First position to start printing from.
500
 * @param[in] to      Position after the last character to print.
501
 *
502
 * @return            Number of characters printed.
503
 */
504
static inline size_t _printLine(aos_shell_t* shell, const size_t from, const size_t to)
505
{
506
  aosDbgCheck(shell != NULL);
507

    
508
  // local variables
509
  size_t cnt;
510

    
511
  for (cnt = 0; from + cnt < to; ++cnt) {
512
    streamPut(&shell->stream, shell->line[from + cnt]);
513
  }
514

    
515
  return cnt;
516
}
517

    
518
/**
519
 * @brief   Compare two characters.
520
 *
521
 * @param[in] lhs       First character to compare.
522
 * @param[in] rhs       Second character to compare.
523
 *
524
 * @return              How well the characters match.
525
 */
526
static inline charmatch_t _charcmp(char lhs, char rhs)
527
{
528
  // if lhs is a upper case letter and rhs is a lower case letter
529
  if (lhs >= 'A' && lhs <= 'Z' && rhs >= 'a' && rhs <= 'z') {
530
    return (lhs == (rhs - 'a' + 'A')) ? CHAR_MATCH_NCASE : CHAR_MATCH_NOT;
531
  }
532
  // if lhs is a lower case letter and rhs is a upper case letter
533
  else if (lhs >= 'a' && lhs <= 'z' && rhs >= 'A' && rhs <= 'Z') {
534
    return ((lhs - 'a' + 'A') == rhs) ? CHAR_MATCH_NCASE : CHAR_MATCH_NOT;
535
  }
536
  // default
537
  else {
538
    return (lhs == rhs) ? CHAR_MATCH_CASE : CHAR_MATCH_NOT;
539
  }
540
}
541

    
542
/**
543
 * @brief   Maps an character from ASCII to a modified custom encoding.
544
 * @details The custom character encoding is very similar to ASCII and has the following structure:
545
 *          0x00=NULL ... 0x40='@' (identically to ASCII)
546
 *          0x4A='a'; 0x4B='A'; 0x4C='b'; 0x4D='B' ... 0x73='z'; 0x74='Z' (custom letter order)
547
 *          0x75='[' ... 0x7A='`' (0x5B..0x60 is ASCII)
548
 *          0x7B='{' ... 0x7F=DEL (identically to ASCII)
549
 *
550
 * @param[in] c   Character to map to the custom encoding.
551
 *
552
 * @return    The customly encoded character.
553
 */
554
static inline char _mapAscii2Custom(const char c)
555
{
556
  if (c >= 'A' && c <= 'Z') {
557
    return ((c - 'A') * 2) + 'A' + 1;
558
  } else if (c > 'Z' && c < 'a') {
559
    return c + ('z' - 'a') + 1;
560
  } else if (c >= 'a' && c <= 'z') {
561
    return ((c - 'a') * 2) + 'A';
562
  } else {
563
    return c;
564
  }
565
}
566

    
567
/**
568
 * @brief   Compares two strings wrt letter case.
569
 * @details Comparisson uses a custom character encoding or mapping.
570
 *          See @p _mapAscii2Custom for details.
571
 *
572
 * @param[in] str1    First string to compare.
573
 * @param[in] str2    Second string to compare.
574
 * @param[in] cs      Flag indicating whether comparison shall be case sensitive.
575
 * @param[in,out] n   Maximum number of character to compare (in) and number of matching characters (out).
576
 *                    If a null pointer is specified, this parameter is ignored.
577
 *                    If the value pointed to is zero, comarison will not be limited.
578
 * @param[out] m      Optional indicator whether there was at least one case mismatch.
579
 *
580
 * @return      Integer value indicating the relationship between the strings.
581
 * @retval <0   The first character that does not match has a lower value in str1 than in str2.
582
 * @retval  0   The contents of both strings are equal.
583
 * @retval >0   The first character that does not match has a greater value in str1 than in str2.
584
 */
585
static int _strccmp(const char *str1, const char *str2, bool cs, size_t* n, charmatch_t* m)
586
{
587
  aosDbgCheck(str1 != NULL);
588
  aosDbgCheck(str2 != NULL);
589

    
590
  // initialize variables
591
  if (m) {
592
    *m = CHAR_MATCH_NOT;
593
  }
594
  size_t i = 0;
595

    
596
  // iterate through the strings
597
  while ((n == NULL) || (*n == 0) || (*n > 0 && i < *n)) {
598
    // break on NUL
599
    if (str1[i] == '\0' || str2[i] == '\0') {
600
      if (n) {
601
        *n = i;
602
      }
603
      break;
604
    }
605
    // compare character
606
    const charmatch_t match = _charcmp(str1[i], str2[i]);
607
    if ((match == CHAR_MATCH_CASE) || (!cs && match == CHAR_MATCH_NCASE)) {
608
      if (m != NULL && *m != CHAR_MATCH_NCASE) {
609
        *m = match;
610
      }
611
      ++i;
612
    } else {
613
      if (n) {
614
        *n = i;
615
      }
616
      break;
617
    }
618
  }
619

    
620
  return _mapAscii2Custom(str1[i]) - _mapAscii2Custom(str2[i]);
621
}
622

    
623
/**
624
 * @brief   Read input from a channel as long as there is data available.
625
 *
626
 * @param[in]   shell     Pointer to the shell object.
627
 * @param[in]   channel   The channel to read from.
628
 * @param[out]  n         Pointer to a variable to store the number of read characters to.
629
 *
630
 * @return
631
 */
632
static aos_status_t _readChannel(aos_shell_t* shell, AosShellChannel* channel, size_t* n)
633
{
634
  aosDbgCheck(shell != NULL);
635
  aosDbgCheck(channel != NULL);
636
  aosDbgCheck(n != NULL);
637

    
638
  // local variables
639
  aos_shellaction_t action = AOS_SHELL_ACTION_NONE;
640
  char c;
641
  special_key_t key;
642

    
643
  // initialize output variables
644
  *n = 0;
645

    
646
  // read character by character from the channel
647
  while (chnReadTimeout(channel, (uint8_t*)&c, 1, TIME_IMMEDIATE)) {
648
    key = KEY_UNKNOWN;
649

    
650
    // parse escape sequence
651
    if (shell->inputdata.escp > 0) {
652
      shell->inputdata.escseq[shell->inputdata.escp] = c;
653
      ++shell->inputdata.escp;
654
      key = _interpreteEscapeSequence(shell->inputdata.escseq);
655
      if (key == KEY_AMBIGUOUS) {
656
        // read next byte to resolve ambiguity
657
        continue;
658
      } else {
659
        /*
660
         * If the escape sequence could either be parsed sucessfully
661
         * or there is no match (KEY_UNKNOWN),
662
         * reset the sequence variable and interprete key/character
663
         */
664
        shell->inputdata.escp = 0;
665
        memset(shell->inputdata.escseq, '\0', sizeof(shell->inputdata.escseq)*sizeof(shell->inputdata.escseq[0]));
666
      }
667
    }
668

    
669
    /* interprete keys or character */
670
    {
671
      // default
672
      action = AOS_SHELL_ACTION_NONE;
673

    
674
      // printable character
675
      if (key == KEY_UNKNOWN && c >= '\x20' && c <= '\x7E') {
676
        action = AOS_SHELL_ACTION_READCHAR;
677
      }
678

    
679
      // tab key or character
680
      else if (key == KEY_TAB || c == '\x09') {
681
        /*
682
         * pressing tab once applies auto fill
683
         * pressing tab a second time prints suggestions
684
         */
685
        if (shell->inputdata.lastaction == AOS_SHELL_ACTION_AUTOFILL || shell->inputdata.lastaction == AOS_SHELL_ACTION_SUGGEST) {
686
          action = AOS_SHELL_ACTION_SUGGEST;
687
        } else {
688
          action = AOS_SHELL_ACTION_AUTOFILL;
689
        }
690
      }
691

    
692
      // INS key
693
      else if (key == KEY_INSERT) {
694
        action = AOS_SHELL_ACTION_INSERTTOGGLE;
695
      }
696

    
697
      // DEL key or character
698
      else if (key == KEY_DELETE || c == '\x7F') {
699
        // ignore if cursor is at very right
700
        if (shell->inputdata.cursorpos < shell->inputdata.lineend) {
701
          action = AOS_SHELL_ACTION_DELETEFORWARD;
702
        }
703
      }
704

    
705
      // backspace key or character
706
      else if (key == KEY_BACKSPACE || c == '\x08') {
707
        // ignore if cursor is at very left
708
        if (shell->inputdata.cursorpos > 0) {
709
          action = AOS_SHELL_ACTION_DELETEBACKWARD;
710
        }
711
      }
712

    
713
      // 'page up' of 'arrow up' key
714
      else if (key == KEY_PAGE_UP || key == KEY_ARROW_UP) {
715
        // ignore if there was some input
716
        if (shell->inputdata.noinput) {
717
          action = AOS_SHELL_ACTION_RECALLLAST;
718
        }
719
      }
720

    
721
      // 'page down' key, 'arrow done' key, 'end of test' character or 'end of transmission' character
722
      else if (key == KEY_PAGE_DOWN || key == KEY_ARROW_DOWN || c == '\x03' || c == '\x03') {
723
        // ignore if line is empty
724
        if (shell->inputdata.lineend > 0) {
725
          action = AOS_SHELL_ACTION_CLEAR;
726
        }
727
      }
728

    
729
      // 'home' key
730
      else if (key == KEY_HOME) {
731
        // ignore if cursor is very left
732
        if (shell->inputdata.cursorpos > 0) {
733
          action = AOS_SHELL_ACTION_CURSOR2START;
734
        }
735
      }
736

    
737
      // 'end' key
738
      else if (key == KEY_END) {
739
        // ignore if cursos is very right
740
        if (shell->inputdata.cursorpos < shell->inputdata.lineend) {
741
          action = AOS_SHELL_ACTION_CURSOR2END;
742
        }
743
      }
744

    
745
      // 'arrow left' key
746
      else if (key == KEY_ARROW_LEFT) {
747
        // ignore if cursor is very left
748
        if (shell->inputdata.cursorpos > 0) {
749
          action = AOS_SHELL_ACTION_CURSORLEFT;
750
        }
751
      }
752

    
753
      // 'arrow right' key
754
      else if (key == KEY_ARROW_RIGHT) {
755
        // irgnore if cursor is very right
756
        if (shell->inputdata.cursorpos < shell->inputdata.lineend) {
757
          action = AOS_SHELL_ACTION_CURSORRIGHT;
758
        }
759
      }
760

    
761
      // carriage return ('\r') or line feed ('\n') character
762
      else if (c == '\x0D' || c == '\x0A') {
763
        action = AOS_SHELL_ACTION_EXECUTE;
764
      }
765

    
766
      // ESC key or [ESCAPE] character
767
      else if (key == KEY_ESCAPE || c == '\x1B') {
768
        action = AOS_SHELL_ACTION_ESCSTART;
769
      }
770
    }
771

    
772
    /* handle function */
773
    switch (action) {
774
      case AOS_SHELL_ACTION_READCHAR:
775
      {
776
        // line is full
777
        if (shell->inputdata.lineend + 1 >= shell->linesize) {
778
          _moveCursor(shell, shell->inputdata.cursorpos, shell->inputdata.lineend);
779
          chprintf((BaseSequentialStream*)&shell->stream, "\n\tmaximum line width reached\n");
780
          _printPrompt(shell);
781
          _printLine(shell, 0, shell->inputdata.lineend);
782
          _moveCursor(shell, shell->inputdata.lineend, shell->inputdata.cursorpos);
783
        }
784
        // read character
785
        else {
786
          // clear old line content on first input
787
          if (shell->inputdata.noinput) {
788
            memset(shell->line, '\0', shell->linesize);
789
            shell->inputdata.noinput = false;
790
          }
791
          // overwrite content
792
          if (shell->config & AOS_SHELL_CONFIG_INPUT_OVERWRITE) {
793
            shell->line[shell->inputdata.cursorpos] = c;
794
            ++shell->inputdata.cursorpos;
795
            shell->inputdata.lineend = (shell->inputdata.cursorpos > shell->inputdata.lineend) ? shell->inputdata.cursorpos : shell->inputdata.lineend;
796
            streamPut(&shell->stream, (uint8_t)c);
797
          }
798
          // insert character
799
          else {
800
            memmove(&(shell->line[shell->inputdata.cursorpos+1]), &(shell->line[shell->inputdata.cursorpos]), shell->inputdata.lineend - shell->inputdata.cursorpos);
801
            shell->line[shell->inputdata.cursorpos] = c;
802
            ++shell->inputdata.lineend;
803
            _printLine(shell, shell->inputdata.cursorpos, shell->inputdata.lineend);
804
            ++shell->inputdata.cursorpos;
805
            _moveCursor(shell, shell->inputdata.lineend, shell->inputdata.cursorpos);
806
          }
807
        }
808
        break;
809
      }
810

    
811
      case AOS_SHELL_ACTION_AUTOFILL:
812
      {
813
        const char* fill = shell->line;
814
        size_t cmatch = shell->inputdata.cursorpos;
815
        charmatch_t matchlevel = CHAR_MATCH_NOT;
816
        size_t n;
817
        // iterate through command list
818
        for (aos_shellcommand_t* cmd = shell->commands; cmd != NULL; cmd = cmd->next) {
819
          // compare current match with command
820
          n = cmatch;
821
          charmatch_t mlvl = CHAR_MATCH_NOT;
822
          _strccmp(fill, cmd->name, shell->config & AOS_SHELL_CONFIG_MATCH_CASE, (n == 0) ? NULL : &n, &mlvl);
823
          const int cmp = (n < cmatch) ?
824
                            (n - cmatch) :
825
                            (cmd->name[n] != '\0') ?
826
                              strlen(cmd->name) - n :
827
                              0;
828
          // if an exact match was found
829
          if (cmatch + cmp == shell->inputdata.cursorpos) {
830
            cmatch = shell->inputdata.cursorpos;
831
            fill = cmd->name;
832
            // break the loop only if there are no case mismatches with the input
833
            n = shell->inputdata.cursorpos;
834
            _strccmp(fill, shell->line, false, &n, &mlvl);
835
            if (mlvl == CHAR_MATCH_CASE) {
836
              break;
837
            }
838
          }
839
          // if a not exact match was found
840
          else if (cmatch + cmp > shell->inputdata.cursorpos) {
841
            // if this is the first one
842
            if (fill == shell->line) {
843
              cmatch += cmp;
844
              fill = cmd->name;
845
            }
846
            // if this is a worse one
847
            else if ((cmp < 0) || (cmp == 0 && mlvl == CHAR_MATCH_CASE)) {
848
              cmatch += cmp;
849
            }
850
          }
851
          // non matching commands are ignored
852
          else {}
853
        }
854
        // evaluate if there are case mismatches
855
        n = cmatch;
856
        _strccmp(shell->line, fill, shell->config & AOS_SHELL_CONFIG_MATCH_CASE, &n, &matchlevel);
857
        // print the auto fill if any
858
        if (cmatch > shell->inputdata.cursorpos || (cmatch == shell->inputdata.cursorpos && matchlevel == CHAR_MATCH_NCASE)) {
859
          shell->inputdata.noinput = false;
860
          // limit auto fill so it will not overflow the line width
861
          if (shell->inputdata.lineend + (cmatch - shell->inputdata.cursorpos) > shell->linesize) {
862
            cmatch = shell->linesize - shell->inputdata.lineend + shell->inputdata.cursorpos;
863
          }
864
          // move trailing memory further in the line
865
          memmove(&(shell->line[cmatch]), &(shell->line[shell->inputdata.cursorpos]), shell->inputdata.lineend - shell->inputdata.cursorpos);
866
          shell->inputdata.lineend += cmatch - shell->inputdata.cursorpos;
867
          // if there was no incorrect case when matching
868
          if (matchlevel == CHAR_MATCH_CASE) {
869
            // insert fill command name to line
870
            memcpy(&(shell->line[shell->inputdata.cursorpos]), &(fill[shell->inputdata.cursorpos]), cmatch - shell->inputdata.cursorpos);
871
            // print the output
872
            _printLine(shell, shell->inputdata.cursorpos, shell->inputdata.lineend);
873
          } else {
874
            // overwrite line with fill command name
875
            memcpy(shell->line, fill, cmatch);
876
            // reprint the whole line
877
            _moveCursor(shell, shell->inputdata.cursorpos, 0);
878
            _printLine(shell, 0, shell->inputdata.lineend);
879
          }
880
          // move cursor to the end of the matching sequence
881
          shell->inputdata.cursorpos = cmatch;
882
          _moveCursor(shell, shell->inputdata.lineend, shell->inputdata.cursorpos);
883
        }
884
        break;
885
      }
886

    
887
      case AOS_SHELL_ACTION_SUGGEST:
888
      {
889
        unsigned int matches = 0;
890
        // iterate through command list
891
        for (aos_shellcommand_t* cmd = shell->commands; cmd != NULL; cmd = cmd->next) {
892
          // compare line content with command, excpet if cursorpos=0
893
          size_t i = shell->inputdata.cursorpos;
894
          if (shell->inputdata.cursorpos > 0) {
895
            _strccmp(shell->line, cmd->name, true, &i, NULL);
896
          }
897
          const int cmp = (i < shell->inputdata.cursorpos) ?
898
                            (i - shell->inputdata.cursorpos) :
899
                            (cmd->name[i] != '\0') ?
900
                              strlen(cmd->name) - i :
901
                              0;
902
          // if a match was found
903
          if (cmp > 0) {
904
            // if this is the first one
905
            if (matches == 0) {
906
              _moveCursor(shell, shell->inputdata.cursorpos, shell->inputdata.lineend);
907
              streamPut(&shell->stream, '\n');
908
            }
909
            // print the command
910
            chprintf((BaseSequentialStream*)&shell->stream, "\t%s\n", cmd->name);
911
            ++matches;
912
          }
913
        }
914
        // reprint the prompt and line if any matches have been found
915
        if (matches > 0) {
916
          _printPrompt(shell);
917
          _printLine(shell, 0, shell->inputdata.lineend);
918
          _moveCursor(shell, shell->inputdata.lineend, shell->inputdata.cursorpos);
919
          shell->inputdata.noinput = false;
920
        }
921
        break;
922
      }
923

    
924
      case AOS_SHELL_ACTION_INSERTTOGGLE:
925
      {
926
        if (shell->config & AOS_SHELL_CONFIG_INPUT_OVERWRITE) {
927
          shell->config &= ~AOS_SHELL_CONFIG_INPUT_OVERWRITE;
928
        } else {
929
          shell->config |= AOS_SHELL_CONFIG_INPUT_OVERWRITE;
930
        }
931
        break;
932
      }
933

    
934
      case AOS_SHELL_ACTION_DELETEFORWARD:
935
      {
936
        --shell->inputdata.lineend;
937
        memmove(&(shell->line[shell->inputdata.cursorpos]), &(shell->line[shell->inputdata.cursorpos+1]), shell->inputdata.lineend - shell->inputdata.cursorpos);
938
        _printLine(shell, shell->inputdata.cursorpos, shell->inputdata.lineend);
939
        streamPut(&shell->stream, ' ');
940
        _moveCursor(shell, shell->inputdata.lineend + 1, shell->inputdata.cursorpos);
941
        break;
942
      }
943

    
944
      case AOS_SHELL_ACTION_DELETEBACKWARD:
945
      {
946
        --shell->inputdata.cursorpos;
947
        memmove(&(shell->line[shell->inputdata.cursorpos]), &(shell->line[shell->inputdata.cursorpos+1]), shell->inputdata.lineend - shell->inputdata.cursorpos);
948
        --shell->inputdata.lineend;
949
        shell->line[shell->inputdata.lineend] = '\0';
950
        _moveCursor(shell, shell->inputdata.cursorpos + 1, shell->inputdata.cursorpos);
951
        _printLine(shell, shell->inputdata.cursorpos, shell->inputdata.lineend);
952
        streamPut(&shell->stream, ' ');
953
        _moveCursor(shell, shell->inputdata.lineend+1, shell->inputdata.cursorpos);
954
        break;
955
      }
956

    
957
      case AOS_SHELL_ACTION_RECALLLAST:
958
      {
959
        // replace any intermediate NUL bytes with spaces
960
        shell->inputdata.lineend = 0;
961
        size_t nul_start = 0;
962
        size_t nul_end = 0;
963
        // search line for a NUL byte
964
        while (nul_start < shell->linesize) {
965
          if (shell->line[nul_start] == '\0') {
966
            nul_end = nul_start + 1;
967
            // keep searcjing for a byte that is not NUL
968
            while (nul_end < shell->linesize) {
969
              if (shell->line[nul_end] != '\0') {
970
                // an intermediate NUL sequence was found
971
                memset(&(shell->line[nul_start]), ' ', nul_end - nul_start);
972
                shell->inputdata.lineend = nul_end + 1;
973
                break;
974
              } else {
975
                ++nul_end;
976
              }
977
            }
978
            nul_start = nul_end + 1;
979
          } else {
980
            ++shell->inputdata.lineend;
981
            ++nul_start;
982
          }
983
        }
984
        shell->inputdata.cursorpos = shell->inputdata.lineend;
985
        // print the line
986
        shell->inputdata.noinput = _printLine(shell, 0, shell->inputdata.lineend) == 0;
987
        break;
988
      }
989

    
990
      case AOS_SHELL_ACTION_CLEAR:
991
      {
992
        // clear output
993
        _moveCursor(shell, shell->inputdata.cursorpos, 0);
994
        for (shell->inputdata.cursorpos = 0; shell->inputdata.cursorpos < shell->inputdata.lineend; ++shell->inputdata.cursorpos) {
995
          streamPut(&shell->stream, ' ');
996
        }
997
        _moveCursor(shell, shell->inputdata.lineend, 0);
998
        shell->inputdata.cursorpos = 0;
999
        shell->inputdata.lineend = 0;
1000
        shell->inputdata.noinput = true;
1001
        break;
1002
      }
1003

    
1004
      case AOS_SHELL_ACTION_CURSOR2START:
1005
      {
1006
        _moveCursor(shell, shell->inputdata.cursorpos, 0);
1007
        shell->inputdata.cursorpos = 0;
1008
        break;
1009
      }
1010

    
1011
      case AOS_SHELL_ACTION_CURSOR2END:
1012
      {
1013
        _moveCursor(shell, shell->inputdata.cursorpos, shell->inputdata.lineend);
1014
        shell->inputdata.cursorpos = shell->inputdata.lineend;
1015
        break;
1016
      }
1017

    
1018
      case AOS_SHELL_ACTION_CURSORLEFT:
1019
      {
1020
        _moveCursor(shell, shell->inputdata.cursorpos, shell->inputdata.cursorpos-1);
1021
        --shell->inputdata.cursorpos;
1022
        break;
1023
      }
1024

    
1025
      case AOS_SHELL_ACTION_CURSORRIGHT:
1026
      {
1027
        _moveCursor(shell, shell->inputdata.cursorpos, shell->inputdata.cursorpos+1);
1028
        ++shell->inputdata.cursorpos;
1029
        break;
1030
      }
1031

    
1032
      case AOS_SHELL_ACTION_EXECUTE:
1033
      {
1034
        streamPut(&shell->stream, '\n');
1035
        // set the number of read bytes and return
1036
        if (!shell->inputdata.noinput) {
1037
          *n = shell->linesize - shell->inputdata.lineend;
1038
          // fill the remainder of the line with NUL bytes
1039
          memset(&(shell->line[shell->inputdata.lineend]), '\0', *n);
1040
          // reset static variables
1041
          shell->inputdata.noinput = true;
1042
        }
1043
        return AOS_SUCCESS;
1044
      }
1045

    
1046
      case AOS_SHELL_ACTION_ESCSTART:
1047
      {
1048
        shell->inputdata.escseq[0] = c;
1049
        ++shell->inputdata.escp;
1050
        break;
1051
      }
1052

    
1053
      case AOS_SHELL_ACTION_NONE:
1054
      default:
1055
      {
1056
        // do nothing (ignore input) and read next byte
1057
        continue;
1058
      }
1059
    } /* end of switch */
1060

    
1061
    shell->inputdata.lastaction = action;
1062
  } /* end of while */
1063

    
1064
  // no more data could be read from the channel
1065
  return AOS_WARNING;
1066
}
1067

    
1068
/**
1069
 * @brief   Parses the content of the input buffer (line) to separate arguments.
1070
 *
1071
 * @param[in] shell   Pointer to the shell object.
1072
 *
1073
 * @return            Number of arguments found.
1074
 */
1075
static size_t _parseArguments(aos_shell_t* shell)
1076
{
1077
  aosDbgCheck(shell != NULL);
1078

    
1079
  /*
1080
   * States for a very small FSM.
1081
   */
1082
  typedef enum {
1083
    START,
1084
    SPACE,
1085
    TEXT,
1086
    END,
1087
  } state_t;
1088

    
1089
  // local variables
1090
  state_t state = START;
1091
  size_t arg = 0;
1092

    
1093
  // iterate through the line
1094
  for (char* c = shell->line; c < shell->line + shell->linesize; ++c) {
1095
    // terminate at first NUL byte
1096
    if (*c == '\0') {
1097
      state = END;
1098
      break;
1099
    }
1100
    // spaces become NUL bytes
1101
    else if (*c == ' ') {
1102
      *c = '\0';
1103
      state = SPACE;
1104
    }
1105
    // handle non-NUL bytes
1106
    else {
1107
      switch (state) {
1108
        case START:
1109
        case SPACE:
1110
          // ignore too many arguments
1111
          if (arg < shell->arglistsize) {
1112
            shell->arglist[arg] = c;
1113
          }
1114
          ++arg;
1115
          break;
1116
        case TEXT:
1117
        case END:
1118
        default:
1119
          break;
1120
      }
1121
      state = TEXT;
1122
    }
1123
  }
1124

    
1125
  // set all remaining argument pointers to NULL
1126
  for (size_t a = arg; a < shell->arglistsize; ++a) {
1127
    shell->arglist[a] = NULL;
1128
  }
1129

    
1130
  return arg;
1131
}
1132

    
1133
/******************************************************************************/
1134
/* EXPORTED FUNCTIONS                                                         */
1135
/******************************************************************************/
1136

    
1137
/**
1138
 * @brief   Initializes a shell object with the specified parameters.
1139
 *
1140
 * @param[in] shell         Pointer to the shell object.
1141
 * @param[in] stream        I/O stream to use.
1142
 * @param[in] prompt        Prompt line to print (NULL = use default prompt).
1143
 * @param[in] line          Pointer to the input buffer.
1144
 * @param[in] linesize      Size of the input buffer.
1145
 * @param[in] arglist       Pointer to the argument buffer.
1146
 * @param[in] arglistsize   Size of te argument buffer.
1147
 */
1148
void aosShellInit(aos_shell_t* shell, event_source_t* oseventsource,  const char* prompt, char* line, size_t linesize, char** arglist, size_t arglistsize)
1149
{
1150
  aosDbgCheck(shell != NULL);
1151
  aosDbgCheck(oseventsource != NULL);
1152
  aosDbgCheck(line != NULL);
1153
  aosDbgCheck(arglist != NULL);
1154

    
1155
  // set parameters
1156
  shell->thread = NULL;
1157
  chEvtObjectInit(&shell->eventSource);
1158
  shell->os.eventSource = oseventsource;
1159
  aosShellStreamInit(&shell->stream);
1160
  shell->prompt = prompt;
1161
  shell->commands = NULL;
1162
  shell->execstatus.command = NULL;
1163
  shell->execstatus.retval = 0;
1164
  shell->line = line;
1165
  shell->linesize = linesize;
1166
  shell->inputdata.lastaction = AOS_SHELL_ACTION_NONE;
1167
  shell->inputdata.escp = 0;
1168
  memset(shell->inputdata.escseq, '\0', sizeof(shell->inputdata.escseq)*sizeof(shell->inputdata.escseq[0]));
1169
  shell->inputdata.cursorpos = 0;
1170
  shell->inputdata.lineend = 0;
1171
  shell->inputdata.noinput = true;
1172
  shell->arglist = arglist;
1173
  shell->arglistsize = arglistsize;
1174
  shell->config = 0x00;
1175

    
1176
  // initialize arrays
1177
  memset(shell->line, '\0', shell->linesize);
1178
  for (size_t a = 0; a < shell->arglistsize; ++a) {
1179
    shell->arglist[a] = NULL;
1180
  }
1181

    
1182
  return;
1183
}
1184

    
1185
/**
1186
 * @brief   Initialize an AosShellStream object.
1187
 *
1188
 * @param[in] stream  The AosShellStrem to initialize.
1189
 */
1190
void aosShellStreamInit(AosShellStream* stream)
1191
{
1192
  aosDbgCheck(stream != NULL);
1193

    
1194
  stream->vmt = &_streamvmt;
1195
  stream->channel = NULL;
1196

    
1197
  return;
1198
}
1199

    
1200
/**
1201
 * @brief   Initialize an AosShellChannel object with the specified parameters.
1202
 *
1203
 * @param[in] channel       The AosShellChannel to initialize.
1204
 * @param[in] asyncchannel  An BaseAsynchronousChannel this AosShellChannel is associated with.
1205
 */
1206
void aosShellChannelInit(AosShellChannel* channel, BaseAsynchronousChannel* asyncchannel)
1207
{
1208
  aosDbgCheck(channel != NULL);
1209
  aosDbgCheck(asyncchannel != NULL);
1210

    
1211
  channel->vmt = &_channelvmt;
1212
  channel->asyncchannel = asyncchannel;
1213
  channel->listener.wflags = 0;
1214
  channel->next = NULL;
1215
  channel->flags = 0;
1216

    
1217
  return;
1218
}
1219

    
1220
/**
1221
 * @brief   Inserts a command to the shells list of commands.
1222
 *
1223
 * @param[in] shell   Pointer to the shell object.
1224
 * @param[in] cmd     Pointer to the command to add.
1225
 *
1226
 * @return            A status value.
1227
 * @retval AOS_SUCCESS  The command was added successfully.
1228
 * @retval AOS_ERROR    Another command with identical name already exists.
1229
 */
1230
aos_status_t aosShellAddCommand(aos_shell_t *shell, aos_shellcommand_t *cmd)
1231
{
1232
  aosDbgCheck(shell != NULL);
1233
  aosDbgCheck(cmd != NULL);
1234
  aosDbgCheck(cmd->name != NULL && strlen(cmd->name) > 0 && strchr(cmd->name, ' ') == NULL && strchr(cmd->name, '\t') == NULL);
1235
  aosDbgCheck(cmd->callback != NULL);
1236
  aosDbgCheck(cmd->next == NULL);
1237

    
1238
  aos_shellcommand_t* prev = NULL;
1239
  aos_shellcommand_t** curr = &(shell->commands);
1240

    
1241
  // insert the command to the list wrt lexographical order (exception: lower case characters preceed upper their uppercase counterparts)
1242
  while (*curr != NULL) {
1243
    // iterate through the list as long as the command names are 'smaller'
1244
    const int cmp = _strccmp((*curr)->name, cmd->name, true, NULL, NULL);
1245
    if (cmp < 0) {
1246
      prev = *curr;
1247
      curr = &((*curr)->next);
1248
      continue;
1249
    }
1250
    // error if the command already exists
1251
    else if (cmp == 0) {
1252
      return AOS_ERROR;
1253
    }
1254
    // insert the command as soon as a 'larger' name was found
1255
    else /* if (cmpval > 0) */ {
1256
      cmd->next = *curr;
1257
      // special case: the first command is larger
1258
      if (prev == NULL) {
1259
        shell->commands = cmd;
1260
      } else {
1261
        prev->next = cmd;
1262
      }
1263
      return AOS_SUCCESS;
1264
    }
1265
  }
1266
  // the end of the list has been reached
1267

    
1268
  // append the command
1269
  *curr = cmd;
1270
  return AOS_SUCCESS;
1271
}
1272

    
1273
/**
1274
 * @brief   Removes a command from the shells list of commands.
1275
 *
1276
 * @param[in] shell     Pointer to the shell object.
1277
 * @param[in] cmd       Name of the command to removde.
1278
 * @param[out] removed  Optional pointer to the command that was removed.
1279
 *
1280
 * @return              A status value.
1281
 * @retval AOS_SUCCESS  The command was removed successfully.
1282
 * @retval AOS_ERROR    The command name was not found.
1283
 */
1284
aos_status_t aosShellRemoveCommand(aos_shell_t *shell, char *cmd, aos_shellcommand_t **removed)
1285
{
1286
  aosDbgCheck(shell != NULL);
1287
  aosDbgCheck(cmd != NULL && strlen(cmd) > 0);
1288

    
1289
  aos_shellcommand_t* prev = NULL;
1290
  aos_shellcommand_t** curr = &(shell->commands);
1291

    
1292
  // iterate through the list and seach for the specified command name
1293
  while (curr != NULL) {
1294
    const int cmpval = strcmp((*curr)->name, cmd);
1295
    // iterate through the list as long as the command names are 'smaller'
1296
    if (cmpval < 0) {
1297
      prev = *curr;
1298
      curr = &((*curr)->next);
1299
      continue;
1300
    }
1301
    // remove the command when found
1302
    else if (cmpval == 0) {
1303
      // special case: the first command matches
1304
      if (prev == NULL) {
1305
        shell->commands = (*curr)->next;
1306
      } else {
1307
        prev->next = (*curr)->next;
1308
      }
1309
      (*curr)->next = NULL;
1310
      // set the optional output argument
1311
      if (removed != NULL) {
1312
        *removed = *curr;
1313
      }
1314
      return AOS_SUCCESS;
1315
    }
1316
    // break the loop if the command names are 'larger'
1317
    else /* if (cmpval > 0) */ {
1318
      break;
1319
    }
1320
  }
1321

    
1322
  // if the command was not found, return an error
1323
  return AOS_ERROR;
1324
}
1325

    
1326
/**
1327
 * @brief   Count the number of commands assigned to the shell.
1328
 *
1329
 * @param[in] shell   The shell to count the commands for.
1330
 *
1331
 * @return  The number of commands associated to the shell.
1332
 */
1333
unsigned int aosShellCountCommands(aos_shell_t* shell)
1334
{
1335
  aosDbgCheck(shell != NULL);
1336

    
1337
  unsigned int count = 0;
1338
  aos_shellcommand_t* cmd = shell->commands;
1339
  while (cmd != NULL) {
1340
    ++count;
1341
    cmd = cmd->next;
1342
  }
1343

    
1344
  return count;
1345
}
1346

    
1347
/**
1348
 * @brief   Add a channel to a AosShellStream.
1349
 *
1350
 * @param[in] stream    The AosShellStream to extend.
1351
 * @param[in] channel   The channel to be added to the stream.
1352
 */
1353
void aosShellStreamAddChannel(AosShellStream* stream, AosShellChannel* channel)
1354
{
1355
  aosDbgCheck(stream != NULL);
1356
  aosDbgCheck(channel != NULL && channel->asyncchannel != NULL && channel->next == NULL && (channel->flags & AOS_SHELLCHANNEL_ATTACHED) == 0);
1357

    
1358
  // prepend the new channel
1359
  chSysLock();
1360
  channel->flags |= AOS_SHELLCHANNEL_ATTACHED;
1361
  channel->next = stream->channel;
1362
  stream->channel = channel;
1363
  chSysUnlock();
1364

    
1365
  return;
1366
}
1367

    
1368
/**
1369
 * @brief   Remove a channel from an AosShellStream.
1370
 *
1371
 * @param[in] stream    The AosShellStream to modify.
1372
 * @param[in] channel   The channel to remove.
1373
 *
1374
 * @return              A status value.
1375
 * @retval AOS_SUCCESS  The channel was removed successfully.
1376
 * @retval AOS_ERROR    The specified channel was not found to be associated with the shell.
1377
 */
1378
aos_status_t aosShellStreamRemoveChannel(AosShellStream* stream, AosShellChannel* channel)
1379
{
1380
  aosDbgCheck(stream != NULL);
1381
  aosDbgCheck(channel != NULL && channel->asyncchannel != NULL && channel->flags & AOS_SHELLCHANNEL_ATTACHED);
1382

    
1383
  // local varibales
1384
  AosShellChannel* prev = NULL;
1385
  AosShellChannel* curr = stream->channel;
1386

    
1387
  // iterate through the list and search for the specified channel
1388
  while (curr != NULL) {
1389
    // if the channel was found
1390
    if (curr == channel) {
1391
      chSysLock();
1392
      // special case: the first channel matches (prev is NULL)
1393
      if (prev == NULL) {
1394
        stream->channel = curr->next;
1395
      } else {
1396
        prev->next = channel->next;
1397
      }
1398
      curr->next = NULL;
1399
      curr->flags &= ~AOS_SHELLCHANNEL_ATTACHED;
1400
      chSysUnlock();
1401
      return AOS_SUCCESS;
1402
    }
1403
  }
1404

    
1405
  // if the channel was not found, return an error
1406
  return AOS_ERROR;
1407
}
1408

    
1409
/**
1410
 * @brief   Enable a AosSheööChannel as input.
1411
 *
1412
 * @param[in] channel   The channel to enable as input.
1413
 */
1414
void aosShellChannelInputEnable(AosShellChannel* channel)
1415
{
1416
  aosDbgCheck(channel != NULL && channel->asyncchannel != NULL);
1417

    
1418
  chSysLock();
1419
  channel->listener.wflags |= CHN_INPUT_AVAILABLE;
1420
  channel->flags |= AOS_SHELLCHANNEL_INPUT_ENABLED;
1421
  chSysUnlock();
1422

    
1423
  return;
1424
}
1425

    
1426
/**
1427
 * @brief   Disable a AosSheööChannel as input.
1428
 *
1429
 * @param[in] channel   The channel to disable as input.
1430
 */
1431
void aosShellChannelInputDisable( AosShellChannel* channel)
1432
{
1433
  aosDbgCheck(channel != NULL && channel->asyncchannel != NULL);
1434

    
1435
  chSysLock();
1436
  channel->listener.wflags &= ~CHN_INPUT_AVAILABLE;
1437
  channel->flags &= ~AOS_SHELLCHANNEL_INPUT_ENABLED;
1438
  chSysUnlock();
1439

    
1440
  return;
1441
}
1442

    
1443
/**
1444
 * @brief   Enable a AosSheööChannel as output.
1445
 *
1446
 * @param[in] channel   The channel to enable as output.
1447
 */
1448
void aosShellChannelOutputEnable(AosShellChannel* channel)
1449
{
1450
  aosDbgCheck(channel != NULL && channel->asyncchannel != NULL);
1451

    
1452
  channel->flags |= AOS_SHELLCHANNEL_OUTPUT_ENABLED;
1453

    
1454
  return;
1455
}
1456

    
1457
/**
1458
 * @brief   Disable a AosSheööChannel as output.
1459
 *
1460
 * @param[in] channel   The channel to disable as output.
1461
 */
1462
void aosShellChannelOutputDisable(AosShellChannel* channel)
1463
{
1464
  aosDbgCheck(channel != NULL && channel->asyncchannel != NULL);
1465

    
1466
  channel->flags &= ~AOS_SHELLCHANNEL_OUTPUT_ENABLED;
1467

    
1468
  return;
1469
}
1470

    
1471
/**
1472
 * @brief   Thread main function.
1473
 *
1474
 * @param[in] aosShellThread    Name of the function;
1475
 * @param[in] shell             Pointer to the shell object.
1476
 */
1477
void aosShellThread(void* shell)
1478
{
1479
  aosDbgCheck(shell != NULL);
1480

    
1481
  // local variables
1482
  eventmask_t eventmask;
1483
  eventflags_t eventflags;
1484
  AosShellChannel* channel;
1485
  aos_status_t readeval;
1486
  size_t nchars = 0;
1487
  size_t nargs = 0;
1488
  aos_shellcommand_t* cmd;
1489

    
1490

    
1491
  // register OS related events
1492
  chEvtRegisterMask(((aos_shell_t*)shell)->os.eventSource, &(((aos_shell_t*)shell)->os.eventListener), AOS_SHELL_EVENTMASK_OS);
1493
  // register events to all input channels
1494
  for (channel = ((aos_shell_t*)shell)->stream.channel; channel != NULL; channel = channel->next) {
1495
    chEvtRegisterMaskWithFlags(&(channel->asyncchannel->event), &(channel->listener), AOS_SHELL_EVENTMASK_INPUT, channel->listener.wflags);
1496
  }
1497

    
1498
  // fire start event
1499
  chEvtBroadcastFlags(&(((aos_shell_t*)shell)->eventSource), AOS_SHELL_EVTFLAG_START);
1500

    
1501
  // print the prompt for the first time
1502
  _printPrompt((aos_shell_t*)shell);
1503

    
1504
  // enter thread loop
1505
  while (!chThdShouldTerminateX()) {
1506
    // wait for event and handle it accordingly
1507
    eventmask = chEvtWaitOne(ALL_EVENTS);
1508

    
1509
    // handle event
1510
    switch (eventmask) {
1511

    
1512
      // OS related events
1513
      case AOS_SHELL_EVENTMASK_OS:
1514
      {
1515
        eventflags = chEvtGetAndClearFlags(&((aos_shell_t*)shell)->os.eventListener);
1516
        // handle shutdown/restart events
1517
        if (eventflags & AOS_SYSTEM_EVENTFLAGS_SHUTDOWN) {
1518
          chThdTerminate(((aos_shell_t*)shell)->thread);
1519
        } else {
1520
          // print an error message
1521
          chprintf((BaseSequentialStream*)&((aos_shell_t*)shell)->stream, "\nERROR: unknown OS event received (0x%08X)\n", eventflags);
1522
        }
1523
        break;
1524
      }
1525

    
1526
      // input events
1527
      case AOS_SHELL_EVENTMASK_INPUT:
1528
      {
1529
        // check and handle all channels
1530
        channel = ((aos_shell_t*)shell)->stream.channel;
1531
        while (channel != NULL) {
1532
          eventflags = chEvtGetAndClearFlags(&channel->listener);
1533
          // if there is new input
1534
          if (eventflags & CHN_INPUT_AVAILABLE) {
1535
            // read input from channel
1536
            readeval = _readChannel((aos_shell_t*)shell, channel, &nchars);
1537
            // parse input line to argument list only if the input shall be executed
1538
            nargs = (readeval == AOS_SUCCESS && nchars > 0) ? _parseArguments((aos_shell_t*)shell) : 0;
1539
            // check number of arguments
1540
            if (nargs > ((aos_shell_t*)shell)->arglistsize) {
1541
              // error too many arguments
1542
              chprintf((BaseSequentialStream*)&((aos_shell_t*)shell)->stream, "\ttoo many arguments\n");
1543
            } else if (nargs > 0) {
1544
              // search command list for arg[0] and execute callback
1545
              cmd = ((aos_shell_t*)shell)->commands;
1546
              while (cmd != NULL) {
1547
                if (strcmp(((aos_shell_t*)shell)->arglist[0], cmd->name) == 0) {
1548
                  ((aos_shell_t*)shell)->execstatus.command = cmd;
1549
                  chEvtBroadcastFlags(&(((aos_shell_t*)shell)->eventSource), AOS_SHELL_EVTFLAG_EXEC);
1550
                  ((aos_shell_t*)shell)->execstatus.retval = cmd->callback((BaseSequentialStream*)&((aos_shell_t*)shell)->stream, nargs, ((aos_shell_t*)shell)->arglist);
1551
                  chEvtBroadcastFlags(&(((aos_shell_t*)shell)->eventSource), AOS_SHELL_EVTFLAG_DONE);
1552
                  // notify if the command was not successful
1553
                  if (((aos_shell_t*)shell)->execstatus.retval != 0) {
1554
                    chprintf((BaseSequentialStream*)&((aos_shell_t*)shell)->stream, "command returned exit status %d\n", ((aos_shell_t*)shell)->execstatus.retval);
1555
                  }
1556
                  break;
1557
                }
1558
                cmd = cmd->next;
1559
              } /* end of while */
1560

    
1561
              // if no matching command was found, print an error
1562
              if (cmd == NULL) {
1563
                chprintf((BaseSequentialStream*)&((aos_shell_t*)shell)->stream, "%s: command not found\n", ((aos_shell_t*)shell)->arglist[0]);
1564
              }
1565
            }
1566

    
1567
            // reset some internal variables and eprint a new prompt
1568
            if (readeval == AOS_SUCCESS && !chThdShouldTerminateX()) {
1569
              ((aos_shell_t*)shell)->inputdata.cursorpos = 0;
1570
              ((aos_shell_t*)shell)->inputdata.lineend = 0;
1571
              _printPrompt((aos_shell_t*)shell);
1572
            }
1573
          }
1574

    
1575
          // iterate to next channel
1576
          channel = channel->next;
1577
        }
1578
        break;
1579
      }
1580

    
1581
      // other events
1582
      default:
1583
      {
1584
        // print an error message
1585
        chprintf((BaseSequentialStream*)&((aos_shell_t*)shell)->stream, "\nSHELL: ERROR: unknown event received (0x%08X)\n", eventmask);
1586
        break;
1587
      }
1588

    
1589
    } /* end of switch */
1590

    
1591
  } /* end of while */
1592

    
1593
  // fire event and exit the thread
1594
  chSysLock();
1595
  chEvtBroadcastFlagsI(&(((aos_shell_t*)shell)->eventSource), AOS_SHELL_EVTFLAG_EXIT);
1596
  chThdExitS(MSG_OK);
1597
  // no chSysUnlock() required since the thread has been terminated an all waiting threads have been woken up
1598
}
1599

    
1600
#endif /* (AMIROOS_CFG_SHELL_ENABLE == true) || (AMIROOS_CFG_TESTS_ENABLE == true)*/
1601

    
1602
/** @} */