Statistics
| Branch: | Tag: | Revision:

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

History | View | Annotate | Download (45.207 KB)

1
/*
2
AMiRo-OS is an operating system designed for the Autonomous Mini Robot (AMiRo) platform.
3
Copyright (C) 2016..2018  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
#include <aos_shell.h>
20

    
21
#if (AMIROOS_CFG_SHELL_ENABLE == true)
22
#include <aos_debug.h>
23
#include <aos_time.h>
24
#include <aos_system.h>
25
#include <chprintf.h>
26
#include <string.h>
27
#include <aos_thread.h>
28

    
29

    
30

    
31
/**
32
 * @brief   Event mask to be set on OS related events.
33
 */
34
#define AOS_SHELL_EVENTMASK_OS                  EVENT_MASK(0)
35

    
36
/**
37
 * @brief   Event mask to be set on a input event.
38
 */
39
#define AOS_SHELL_EVENTMASK_INPUT               EVENT_MASK(1)
40

    
41
/**
42
 * @brief   Implementation of the BaseAsynchronous write() method (inherited from BaseSequentialStream).
43
 */
44
static size_t _channelwrite(void *instance, const uint8_t *bp, size_t n)
45
{
46
  if (((AosShellChannel*)instance)->flags & AOS_SHELLCHANNEL_OUTPUT_ENABLED) {
47
    return streamWrite(((AosShellChannel*)instance)->iochannel->asyncchannel, bp, n);
48
  } else {
49
    return 0;
50
  }
51
}
52

    
53
/**
54
 * @brief   Implementation of the BaseAsynchronous read() method (inherited from BaseSequentialStream).
55
 */
56
static size_t _channelread(void *instance, uint8_t *bp, size_t n)
57
{
58
  return streamRead(((AosShellChannel*)instance)->iochannel->asyncchannel, bp, n);
59
}
60

    
61
/**
62
 * @brief   Implementation of the BaseAsynchronous put() method (inherited from BaseSequentialStream).
63
 */
64
static msg_t _channelput(void *instance, uint8_t b)
65
{
66
  if (((AosShellChannel*)instance)->flags & AOS_SHELLCHANNEL_OUTPUT_ENABLED) {
67
    return streamPut(((AosShellChannel*)instance)->iochannel->asyncchannel, b);
68
  } else {
69
    return MSG_RESET;
70
  }
71
}
72

    
73
/**
74
 * @brief   Implementation of the BaseAsynchronous get() method (inherited from BaseSequentialStream).
75
 */
76
static msg_t _channelget(void *instance)
77
{
78
  return streamGet(((AosShellChannel*)instance)->iochannel->asyncchannel);
79
}
80

    
81
/**
82
 * @brief   Implementation of the BaseAsynchronous putt() method.
83
 */
84
static msg_t _channelputt(void *instance, uint8_t b, systime_t time)
85
{
86
  if (((AosShellChannel*)instance)->flags & AOS_SHELLCHANNEL_OUTPUT_ENABLED) {
87
    return chnPutTimeout(((AosShellChannel*)instance)->iochannel->asyncchannel, b, time);
88
  } else {
89
    return MSG_RESET;
90
  }
91
}
92

    
93
/**
94
 * @brief   Implementation of the BaseAsynchronous gett() method.
95
 */
96
static msg_t _channelgett(void *instance, systime_t time)
97
{
98
  return chnGetTimeout(((AosShellChannel*)instance)->iochannel->asyncchannel, time);
99
}
100

    
101
/**
102
 * @brief   Implementation of the BaseAsynchronous writet() method.
103
 */
104
static size_t _channelwritet(void *instance, const uint8_t *bp, size_t n, systime_t time)
105
{
106
  if (((AosShellChannel*)instance)->flags & AOS_SHELLCHANNEL_OUTPUT_ENABLED) {
107
    return chnWriteTimeout(((AosShellChannel*)instance)->iochannel->asyncchannel, bp, n, time);
108
  } else {
109
    return 0;
110
  }
111
}
112

    
113
/**
114
 * @brief   Implementation of the BaseAsynchronous readt() method.
115
 */
116
static size_t _channelreadt(void *instance, uint8_t *bp, size_t n, systime_t time)
117
{
118
  return chnReadTimeout(((AosShellChannel*)instance)->iochannel->asyncchannel, bp, n, time);
119
}
120

    
121
static const struct AosShellChannelVMT _channelvmt = {
122
  _channelwrite,
123
  _channelread,
124
  _channelput,
125
  _channelget,
126
  _channelputt,
127
  _channelgett,
128
  _channelwritet,
129
  _channelreadt,
130
};
131

    
132
static size_t _streamwrite(void *instance, const uint8_t *bp, size_t n)
133
{
134
  aosDbgCheck(instance != NULL);
135

    
136
  // local variables
137
  AosShellChannel* channel = ((AosShellStream*)instance)->channel;
138
  size_t bytes;
139
  size_t maxbytes = 0;
140

    
141
  // iterate through the list of channels
142
  while (channel != NULL) {
143
    bytes = streamWrite(channel, bp, n);
144
    maxbytes = (bytes > maxbytes) ? bytes : maxbytes;
145
    channel = channel->next;
146
  }
147

    
148
  return maxbytes;
149
}
150

    
151
static size_t _stremread(void *instance, uint8_t *bp, size_t n)
152
{
153
  (void)instance;
154
  (void)bp;
155
  (void)n;
156

    
157
  return 0;
158
}
159

    
160
static msg_t _streamput(void *instance, uint8_t b)
161
{
162
  aosDbgCheck(instance != NULL);
163

    
164
  // local variables
165
  AosShellChannel* channel = ((AosShellStream*)instance)->channel;
166
  msg_t ret;
167

    
168
  // iterate through the list of channels
169
  while (channel != NULL) {
170
    ret = streamPut(channel, b);
171
    if (ret != MSG_OK) {
172
      return ret;
173
    }
174
    channel = channel->next;
175
  }
176

    
177
  return MSG_OK;
178
}
179

    
180
static msg_t _streamget(void *instance)
181
{
182
  (void)instance;
183

    
184
  return 0;
185
}
186

    
187
static const struct AosShellStreamVMT _streamvmt = {
188
  _streamwrite,
189
  _stremread,
190
  _streamput,
191
  _streamget,
192
};
193

    
194
/**
195
 * @brief   Enumerator of special keyboard keys.
196
 */
197
typedef enum special_key {
198
  KEY_UNKNOWN,      /**< any/unknow key */
199
  KEY_AMBIGUOUS,    /**< key is ambiguous */
200
  KEY_TAB,          /**< tabulator key */
201
  KEY_ESCAPE,       /**< escape key */
202
  KEY_BACKSPACE,    /**< backspace key */
203
  KEY_INSERT,       /**< insert key */
204
  KEY_DELETE,       /**< delete key */
205
  KEY_HOME,         /**< home key */
206
  KEY_END,          /**< end key */
207
  KEY_PAGE_UP,      /**< page up key */
208
  KEY_PAGE_DOWN,    /**< page down key */
209
  KEY_ARROW_UP,     /**< arrow up key */
210
  KEY_ARROW_DOWN,   /**< arrow down key */
211
  KEY_ARROW_LEFT,   /**< arrow left key */
212
  KEY_ARROW_RIGHT,  /**< arrow right key */
213
} special_key_t;
214

    
215
/**
216
 * @brief   Enumerator for case (in)sensitive character matching.
217
 */
218
typedef enum charmatch {
219
  CHAR_MATCH_NOT    = 0,  /**< Characters do not match at all. */
220
  CHAR_MATCH_NCASE  = 1,  /**< Characters would match case insensitive. */
221
  CHAR_MATCH_CASE   = 2,  /**< Characters do match with case. */
222
} charmatch_t;
223

    
224
/**
225
 * @brief   Print the shell prompt
226
 * @details Depending on the configuration flags, the system uptime is printed before the prompt string.
227
 *
228
 * @param[in] shell   Pointer to the shell object.
229
 */
230
static void _printPrompt(aos_shell_t* shell)
231
{
232
  aosDbgCheck(shell != NULL);
233

    
234
  // print the system uptime before prompt is configured
235
  if (shell->config & AOS_SHELL_CONFIG_PROMPT_UPTIME) {
236
    // get current system uptime
237
    aos_timestamp_t uptime;
238
    aosSysGetUptime(&uptime);
239

    
240
    chprintf((BaseSequentialStream*)&shell->stream, "[%01u:%02u:%02u:%02u:%03u:%03u] ",
241
             (uint32_t)(uptime / MICROSECONDS_PER_DAY),
242
             (uint8_t)(uptime % MICROSECONDS_PER_DAY / MICROSECONDS_PER_HOUR),
243
             (uint8_t)(uptime % MICROSECONDS_PER_HOUR / MICROSECONDS_PER_MINUTE),
244
             (uint8_t)(uptime % MICROSECONDS_PER_MINUTE / MICROSECONDS_PER_SECOND),
245
             (uint16_t)(uptime % MICROSECONDS_PER_SECOND / MICROSECONDS_PER_MILLISECOND),
246
             (uint16_t)(uptime % MICROSECONDS_PER_MILLISECOND / MICROSECONDS_PER_MICROSECOND));
247
  }
248

    
249
  // print the actual prompt string
250
  if (shell->prompt && !(shell->config & AOS_SHELL_CONFIG_PROMPT_MINIMAL)) {
251
    chprintf((BaseSequentialStream*)&shell->stream, "%s$ ", shell->prompt);
252
  } else {
253
    chprintf((BaseSequentialStream*)&shell->stream, "%>$ ");
254
  }
255

    
256
  return;
257
}
258

    
259
/**
260
 * @brief   Interprete a escape sequence
261
 *
262
 * @param[in] seq   Character sequence to interprete.
263
 *                  Must be terminated by NUL byte.
264
 *
265
 * @return          A @p special_key value.
266
 */
267
static special_key_t _interpreteEscapeSequence(const char seq[])
268
{
269
  // local variables
270
  bool ambiguous = false;
271
  int cmp = 0;
272

    
273
  // TAB
274
  /* not supported yet; use "\x09" instead */
275

    
276
  // BACKSPACE
277
  /* not supported yet; use "\x08" instead */
278

    
279
  // ESCAPE
280
  cmp = strcmp(seq, "\x1B");
281
  if (cmp == 0) {
282
    return KEY_ESCAPE;
283
  } else {
284
    ambiguous |= (cmp < 0);
285
  }
286

    
287
  // INSERT
288
  cmp = strcmp(seq, "\x1B\x5B\x32\x7E");
289
  if (cmp == 0) {
290
    return KEY_INSERT;
291
  } else {
292
    ambiguous |= (cmp < 0);
293
  }
294

    
295
  // DELETE
296
  cmp = strcmp(seq, "\x1B\x5B\x33\x7E");
297
  if (cmp == 0) {
298
    return KEY_DELETE;
299
  } else {
300
    ambiguous |= (cmp < 0);
301
  }
302

    
303
  // HOME
304
  cmp = strcmp(seq, "\x1B\x4F\x48");
305
  if (cmp == 0) {
306
    return KEY_HOME;
307
  } else {
308
    ambiguous |= (cmp < 0);
309
  }
310

    
311
  // END
312
  cmp = strcmp(seq, "\x1B\x4F\x46");
313
  if (cmp == 0) {
314
    return KEY_END;
315
  } else {
316
    ambiguous |= (cmp < 0);
317
  }
318

    
319
  // PAGE UP
320
  cmp = strcmp(seq, "\x1B\x5B\x35\x7E");
321
  if (cmp == 0) {
322
    return KEY_PAGE_UP;
323
  } else {
324
    ambiguous |= (cmp < 0);
325
  }
326

    
327
  // PAGE DOWN
328
  cmp = strcmp(seq, "\x1B\x5B\x36\x7E");
329
  if (cmp == 0) {
330
    return KEY_PAGE_DOWN;
331
  } else {
332
    ambiguous |= (cmp < 0);
333
  }
334

    
335
  // ARROW UP
336
  cmp = strcmp(seq, "\x1B\x5B\x41");
337
  if (cmp == 0) {
338
    return KEY_ARROW_UP;
339
  } else {
340
    ambiguous |= (cmp < 0);
341
  }
342

    
343
  // ARROW DOWN
344
  cmp = strcmp(seq, "\x1B\x5B\x42");
345
  if (cmp == 0) {
346
    return KEY_ARROW_DOWN;
347
  } else {
348
    ambiguous |= (cmp < 0);
349
  }
350

    
351
  // ARROW LEFT
352
  cmp = strcmp(seq, "\x1B\x5B\x44");
353
  if (cmp == 0) {
354
    return KEY_ARROW_LEFT;
355
  } else {
356
    ambiguous |= (cmp < 0);
357
  }
358

    
359
  // ARROW RIGHT
360
  cmp = strcmp(seq, "\x1B\x5B\x43");
361
  if (cmp == 0) {
362
    return KEY_ARROW_RIGHT;
363
  } else {
364
    ambiguous |= (cmp < 0);
365
  }
366

    
367
  return ambiguous ? KEY_AMBIGUOUS : KEY_UNKNOWN;
368
}
369

    
370
/**
371
 * @brief   Move the cursor in the terminal
372
 *
373
 * @param[in] shell   Pointer to the shell object.
374
 * @param[in] from    Starting position of the cursor.
375
 * @param[in] to      Target position to move the cursor to.
376
 *
377
 * @return            The number of positions moved.
378
 */
379
static int _moveCursor(aos_shell_t* shell, const size_t from, const size_t to)
380
{
381
  aosDbgCheck(shell != NULL);
382

    
383
  // local variables
384
  size_t pos = from;
385

    
386
  // move cursor left by printing backspaces
387
  while (pos > to) {
388
    streamPut(&shell->stream, '\b');
389
    --pos;
390
  }
391

    
392
  // move cursor right by printing line content
393
  while (pos < to) {
394
    streamPut(&shell->stream, shell->line[pos]);
395
    ++pos;
396
  }
397

    
398
  return (int)pos - (int)from;
399
}
400

    
401
/**
402
 * @brief   Print content of the shell line
403
 *
404
 * @param[in] shell   Pointer to the shell object.
405
 * @param[in] from    First position to start printing from.
406
 * @param[in] to      Position after the last character to print.
407
 *
408
 * @return            Number of characters printed.
409
 */
410
static inline size_t _printLine(aos_shell_t* shell, const size_t from, const size_t to)
411
{
412
  aosDbgCheck(shell != NULL);
413

    
414
  // local variables
415
  size_t cnt;
416

    
417
  for (cnt = 0; from + cnt < to; ++cnt) {
418
    streamPut(&shell->stream, shell->line[from + cnt]);
419
  }
420

    
421
  return cnt;
422
}
423

    
424
/**
425
 * @brief   Compare two characters.
426
 *
427
 * @param[in] lhs       First character to compare.
428
 * @param[in] rhs       Second character to compare.
429
 *
430
 * @return              How well the characters match.
431
 */
432
static inline charmatch_t _charcmp(char lhs, char rhs)
433
{
434
  // if lhs is a upper case letter and rhs is a lower case letter
435
  if (lhs >= 'A' && lhs <= 'Z' && rhs >= 'a' && rhs <= 'z') {
436
    return (lhs == (rhs - 'a' + 'A')) ? CHAR_MATCH_NCASE : CHAR_MATCH_NOT;
437
  }
438
  // if lhs is a lower case letter and rhs is a upper case letter
439
  else if (lhs >= 'a' && lhs <= 'z' && rhs >= 'A' && rhs <= 'Z') {
440
    return ((lhs - 'a' + 'A') == rhs) ? CHAR_MATCH_NCASE : CHAR_MATCH_NOT;
441
  }
442
  // default
443
  else {
444
    return (lhs == rhs) ? CHAR_MATCH_CASE : CHAR_MATCH_NOT;
445
  }
446
}
447

    
448
/**
449
 * @brief   Maps an character from ASCII to a modified custom encoding.
450
 * @details The custom character encoding is very similar to ASCII and has the following structure:
451
 *          0x00=NULL ... 0x40='@' (identically to ASCII)
452
 *          0x4A='a'; 0x4B='A'; 0x4C='b'; 0x4D='B' ... 0x73='z'; 0x74='Z' (custom letter order)
453
 *          0x75='[' ... 0x7A='`' (0x5B..0x60 is ASCII)
454
 *          0x7B='{' ... 0x7F=DEL (identically to ASCII)
455
 *
456
 * @param[in] c   Character to map to the custom encoding.
457
 *
458
 * @return    The customly encoded character.
459
 */
460
static inline char _mapAscii2Custom(const char c)
461
{
462
  if (c >= 'A' && c <= 'Z') {
463
    return ((c - 'A') * 2) + 'A' + 1;
464
  } else if (c > 'Z' && c < 'a') {
465
    return c + ('z' - 'a') + 1;
466
  } else if (c >= 'a' && c <= 'z') {
467
    return ((c - 'a') * 2) + 'A';
468
  } else {
469
    return c;
470
  }
471
}
472

    
473
/**
474
 * @brief   Compares two strings wrt letter case.
475
 * @details Comparisson uses a custom character encoding or mapping.
476
 *          See @p _mapAscii2Custom for details.
477
 *
478
 * @param[in] str1    First string to compare.
479
 * @param[in] str2    Second string to compare.
480
 * @param[in] cs      Flag indicating whether comparison shall be case sensitive.
481
 * @param[in,out] n   Maximum number of character to compare (in) and number of matching characters (out).
482
 *                    If a null pointer is specified, this parameter is ignored.
483
 *                    If the value pointed to is zero, comarison will not be limited.
484
 * @param[out] m      Optional indicator whether there was at least one case mismatch.
485
 *
486
 * @return      Integer value indicating the relationship between the strings.
487
 * @retval <0   The first character that does not match has a lower value in str1 than in str2.
488
 * @retval  0   The contents of both strings are equal.
489
 * @retval >0   The first character that does not match has a greater value in str1 than in str2.
490
 */
491
static int _strccmp(const char *str1, const char *str2, bool cs, size_t* n, charmatch_t* m)
492
{
493
  aosDbgCheck(str1 != NULL);
494
  aosDbgCheck(str2 != NULL);
495

    
496
  // initialize variables
497
  if (m) {
498
    *m = CHAR_MATCH_NOT;
499
  }
500
  size_t i = 0;
501

    
502
  // iterate through the strings
503
  while ((n == NULL) || (*n == 0) || (*n > 0 && i < *n)) {
504
    // break on NUL
505
    if (str1[i] == '\0' || str2[i] == '\0') {
506
      if (n) {
507
        *n = i;
508
      }
509
      break;
510
    }
511
    // compare character
512
    const charmatch_t match = _charcmp(str1[i], str2[i]);
513
    if ((match == CHAR_MATCH_CASE) || (!cs && match == CHAR_MATCH_NCASE)) {
514
      if (m != NULL && *m != CHAR_MATCH_NCASE) {
515
        *m = match;
516
      }
517
      ++i;
518
    } else {
519
      if (n) {
520
        *n = i;
521
      }
522
      break;
523
    }
524
  }
525

    
526
  return _mapAscii2Custom(str1[i]) - _mapAscii2Custom(str2[i]);
527
}
528

    
529
static aos_status_t _readChannel(aos_shell_t* shell, AosShellChannel* channel, size_t* n)
530
{
531
  aosDbgCheck(shell != NULL);
532
  aosDbgCheck(channel != NULL);
533
  aosDbgCheck(n != NULL);
534

    
535
  // local variables
536
  aos_shellaction_t action = AOS_SHELL_ACTION_NONE;
537
  char c;
538

    
539
  // initialize output variables
540
  *n = 0;
541

    
542
  // read character by character from the channel
543
  while (chnReadTimeout(channel, (uint8_t*)&c, 1, TIME_IMMEDIATE)) {
544
    special_key_t key = KEY_UNKNOWN;
545

    
546
    // parse escape sequence
547
    if (shell->inputdata.escp > 0) {
548
      shell->inputdata.escseq[shell->inputdata.escp] = c;
549
      ++shell->inputdata.escp;
550
      key = _interpreteEscapeSequence(shell->inputdata.escseq);
551
      if (key == KEY_AMBIGUOUS) {
552
        // read next byte to resolve ambiguity
553
        continue;
554
      } else {
555
        /*
556
         * If the escape sequence could either be parsed sucessfully
557
         * or there is no match (KEY_UNKNOWN),
558
         * reset the sequence variable and interprete key/character
559
         */
560
        shell->inputdata.escp = 0;
561
        memset(shell->inputdata.escseq, '\0', sizeof(shell->inputdata.escseq)*sizeof(shell->inputdata.escseq[0]));
562
      }
563
    }
564

    
565
    /* interprete keys or character */
566
    {
567
      // default
568
      action = AOS_SHELL_ACTION_NONE;
569

    
570
      // printable character
571
      if (key == KEY_UNKNOWN && c >= '\x20' && c <= '\x7E') {
572
        action = AOS_SHELL_ACTION_READCHAR;
573
      }
574

    
575
      // tab key or character
576
      else if (key == KEY_TAB || c == '\x09') {
577
        /*
578
         * pressing tab once applies auto fill
579
         * pressing tab a second time prints suggestions
580
         */
581
        if (shell->inputdata.lastaction == AOS_SHELL_ACTION_AUTOFILL || shell->inputdata.lastaction == AOS_SHELL_ACTION_SUGGEST) {
582
          action = AOS_SHELL_ACTION_SUGGEST;
583
        } else {
584
          action = AOS_SHELL_ACTION_AUTOFILL;
585
        }
586
      }
587

    
588
      // INS key
589
      else if (key == KEY_INSERT) {
590
        action = AOS_SHELL_ACTION_INSERTTOGGLE;
591
      }
592

    
593
      // DEL key or character
594
      else if (key == KEY_DELETE || c == '\x7F') {
595
        // ignore if cursor is at very right
596
        if (shell->inputdata.cursorpos < shell->inputdata.lineend) {
597
          action = AOS_SHELL_ACTION_DELETEFORWARD;
598
        }
599
      }
600

    
601
      // backspace key or character
602
      else if (key == KEY_BACKSPACE || c == '\x08') {
603
        // ignore if cursor is at very left
604
        if (shell->inputdata.cursorpos > 0) {
605
          action = AOS_SHELL_ACTION_DELETEBACKWARD;
606
        }
607
      }
608

    
609
      // 'page up' of 'arrow up' key
610
      else if (key == KEY_PAGE_UP || key == KEY_ARROW_UP) {
611
        // ignore if there was some input
612
        if (shell->inputdata.noinput) {
613
          action = AOS_SHELL_ACTION_RECALLLAST;
614
        }
615
      }
616

    
617
      // 'page down' key, 'arrow done' key, 'end of test' character or 'end of transmission' character
618
      else if (key == KEY_PAGE_DOWN || key == KEY_ARROW_DOWN || c == '\x03' || c == '\x03') {
619
        // ignore if line is empty
620
        if (shell->inputdata.lineend > 0) {
621
          action = AOS_SHELL_ACTION_CLEAR;
622
        }
623
      }
624

    
625
      // 'home' key
626
      else if (key == KEY_HOME) {
627
        // ignore if cursor is very left
628
        if (shell->inputdata.cursorpos > 0) {
629
          action = AOS_SHELL_ACTION_CURSOR2START;
630
        }
631
      }
632

    
633
      // 'end' key
634
      else if (key == KEY_END) {
635
        // ignore if cursos is very right
636
        if (shell->inputdata.cursorpos < shell->inputdata.lineend) {
637
          action = AOS_SHELL_ACTION_CURSOR2END;
638
        }
639
      }
640

    
641
      // 'arrow left' key
642
      else if (key == KEY_ARROW_LEFT) {
643
        // ignore if cursor is very left
644
        if (shell->inputdata.cursorpos > 0) {
645
          action = AOS_SHELL_ACTION_CURSORLEFT;
646
        }
647
      }
648

    
649
      // 'arrow right' key
650
      else if (key == KEY_ARROW_RIGHT) {
651
        // irgnore if cursor is very right
652
        if (shell->inputdata.cursorpos < shell->inputdata.lineend) {
653
          action = AOS_SHELL_ACTION_CURSORRIGHT;
654
        }
655
      }
656

    
657
      // carriage return ('\r') or line feed ('\n') character
658
      else if (c == '\x0D' || c == '\x0A') {
659
        action = AOS_SHELL_ACTION_EXECUTE;
660
      }
661

    
662
      // ESC key or [ESCAPE] character
663
      else if (key == KEY_ESCAPE || c == '\x1B') {
664
        action = AOS_SHELL_ACTION_ESCSTART;
665
      }
666
    }
667

    
668
    /* handle function */
669
    switch (action) {
670
      case AOS_SHELL_ACTION_READCHAR:
671
      {
672
        // line is full
673
        if (shell->inputdata.lineend + 1 >= shell->linesize) {
674
          _moveCursor(shell, shell->inputdata.cursorpos, shell->inputdata.lineend);
675
          chprintf((BaseSequentialStream*)&shell->stream, "\n\tmaximum line width reached\n");
676
          _printPrompt(shell);
677
          _printLine(shell, 0, shell->inputdata.lineend);
678
          _moveCursor(shell, shell->inputdata.lineend, shell->inputdata.cursorpos);
679
        }
680
        // read character
681
        else {
682
          // clear old line content on first input
683
          if (shell->inputdata.noinput) {
684
            memset(shell->line, '\0', shell->linesize);
685
            shell->inputdata.noinput = false;
686
          }
687
          // overwrite content
688
          if (shell->config & AOS_SHELL_CONFIG_INPUT_OVERWRITE) {
689
            shell->line[shell->inputdata.cursorpos] = c;
690
            ++shell->inputdata.cursorpos;
691
            shell->inputdata.lineend = (shell->inputdata.cursorpos > shell->inputdata.lineend) ? shell->inputdata.cursorpos : shell->inputdata.lineend;
692
            streamPut(&shell->stream, (uint8_t)c);
693
          }
694
          // insert character
695
          else {
696
            memmove(&(shell->line[shell->inputdata.cursorpos+1]), &(shell->line[shell->inputdata.cursorpos]), shell->inputdata.lineend - shell->inputdata.cursorpos);
697
            shell->line[shell->inputdata.cursorpos] = c;
698
            ++shell->inputdata.lineend;
699
            _printLine(shell, shell->inputdata.cursorpos, shell->inputdata.lineend);
700
            ++shell->inputdata.cursorpos;
701
            _moveCursor(shell, shell->inputdata.lineend, shell->inputdata.cursorpos);
702
          }
703
        }
704
        break;
705
      }
706

    
707
      case AOS_SHELL_ACTION_AUTOFILL:
708
      {
709
        const char* fill = shell->line;
710
        size_t cmatch = shell->inputdata.cursorpos;
711
        charmatch_t matchlevel = CHAR_MATCH_NOT;
712
        size_t n;
713
        // iterate through command list
714
        for (aos_shellcommand_t* cmd = shell->commands; cmd != NULL; cmd = cmd->next) {
715
          // compare current match with command
716
          n = cmatch;
717
          charmatch_t mlvl = CHAR_MATCH_NOT;
718
          _strccmp(fill, cmd->name, shell->config & AOS_SHELL_CONFIG_MATCH_CASE, (n == 0) ? NULL : &n, &mlvl);
719
          const int cmp = (n < cmatch) ?
720
                            (n - cmatch) :
721
                            (cmd->name[n] != '\0') ?
722
                              strlen(cmd->name) - n :
723
                              0;
724
          // if an exact match was found
725
          if (cmatch + cmp == shell->inputdata.cursorpos) {
726
            cmatch = shell->inputdata.cursorpos;
727
            fill = cmd->name;
728
            // break the loop only if there are no case mismatches with the input
729
            n = shell->inputdata.cursorpos;
730
            _strccmp(fill, shell->line, false, &n, &mlvl);
731
            if (mlvl == CHAR_MATCH_CASE) {
732
              break;
733
            }
734
          }
735
          // if a not exact match was found
736
          else if (cmatch + cmp > shell->inputdata.cursorpos) {
737
            // if this is the first one
738
            if (fill == shell->line) {
739
              cmatch += cmp;
740
              fill = cmd->name;
741
            }
742
            // if this is a worse one
743
            else if ((cmp < 0) || (cmp == 0 && mlvl == CHAR_MATCH_CASE)) {
744
              cmatch += cmp;
745
            }
746
          }
747
          // non matching commands are ignored
748
          else {}
749
        }
750
        // evaluate if there are case mismatches
751
        n = cmatch;
752
        _strccmp(shell->line, fill, shell->config & AOS_SHELL_CONFIG_MATCH_CASE, &n, &matchlevel);
753
        // print the auto fill if any
754
        if (cmatch > shell->inputdata.cursorpos || (cmatch == shell->inputdata.cursorpos && matchlevel == CHAR_MATCH_NCASE)) {
755
          shell->inputdata.noinput = false;
756
          // limit auto fill so it will not overflow the line width
757
          if (shell->inputdata.lineend + (cmatch - shell->inputdata.cursorpos) > shell->linesize) {
758
            cmatch = shell->linesize - shell->inputdata.lineend + shell->inputdata.cursorpos;
759
          }
760
          // move trailing memory further in the line
761
          memmove(&(shell->line[cmatch]), &(shell->line[shell->inputdata.cursorpos]), shell->inputdata.lineend - shell->inputdata.cursorpos);
762
          shell->inputdata.lineend += cmatch - shell->inputdata.cursorpos;
763
          // if there was no incorrect case when matching
764
          if (matchlevel == CHAR_MATCH_CASE) {
765
            // insert fill command name to line
766
            memcpy(&(shell->line[shell->inputdata.cursorpos]), &(fill[shell->inputdata.cursorpos]), cmatch - shell->inputdata.cursorpos);
767
            // print the output
768
            _printLine(shell, shell->inputdata.cursorpos, shell->inputdata.lineend);
769
          } else {
770
            // overwrite line with fill command name
771
            memcpy(shell->line, fill, cmatch);
772
            // reprint the whole line
773
            _moveCursor(shell, shell->inputdata.cursorpos, 0);
774
            _printLine(shell, 0, shell->inputdata.lineend);
775
          }
776
          // move cursor to the end of the matching sequence
777
          shell->inputdata.cursorpos = cmatch;
778
          _moveCursor(shell, shell->inputdata.lineend, shell->inputdata.cursorpos);
779
        }
780
        break;
781
      }
782

    
783
      case AOS_SHELL_ACTION_SUGGEST:
784
      {
785
        unsigned int matches = 0;
786
        // iterate through command list
787
        for (aos_shellcommand_t* cmd = shell->commands; cmd != NULL; cmd = cmd->next) {
788
          // compare line content with command, excpet if cursorpos=0
789
          size_t i = shell->inputdata.cursorpos;
790
          if (shell->inputdata.cursorpos > 0) {
791
            _strccmp(shell->line, cmd->name, true, &i, NULL);
792
          }
793
          const int cmp = (i < shell->inputdata.cursorpos) ?
794
                            (i - shell->inputdata.cursorpos) :
795
                            (cmd->name[i] != '\0') ?
796
                              strlen(cmd->name) - i :
797
                              0;
798
          // if a match was found
799
          if (cmp > 0) {
800
            // if this is the first one
801
            if (matches == 0) {
802
              _moveCursor(shell, shell->inputdata.cursorpos, shell->inputdata.lineend);
803
              streamPut(&shell->stream, '\n');
804
            }
805
            // print the command
806
            chprintf((BaseSequentialStream*)&shell->stream, "\t%s\n", cmd->name);
807
            ++matches;
808
          }
809
        }
810
        // reprint the prompt and line if any matches have been found
811
        if (matches > 0) {
812
          _printPrompt(shell);
813
          _printLine(shell, 0, shell->inputdata.lineend);
814
          _moveCursor(shell, shell->inputdata.lineend, shell->inputdata.cursorpos);
815
          shell->inputdata.noinput = false;
816
        }
817
        break;
818
      }
819

    
820
      case AOS_SHELL_ACTION_INSERTTOGGLE:
821
      {
822
        if (shell->config & AOS_SHELL_CONFIG_INPUT_OVERWRITE) {
823
          shell->config &= ~AOS_SHELL_CONFIG_INPUT_OVERWRITE;
824
        } else {
825
          shell->config |= AOS_SHELL_CONFIG_INPUT_OVERWRITE;
826
        }
827
        break;
828
      }
829

    
830
      case AOS_SHELL_ACTION_DELETEFORWARD:
831
      {
832
        --shell->inputdata.lineend;
833
        memmove(&(shell->line[shell->inputdata.cursorpos]), &(shell->line[shell->inputdata.cursorpos+1]), shell->inputdata.lineend - shell->inputdata.cursorpos);
834
        _printLine(shell, shell->inputdata.cursorpos, shell->inputdata.lineend);
835
        streamPut(&shell->stream, ' ');
836
        _moveCursor(shell, shell->inputdata.lineend + 1, shell->inputdata.cursorpos);
837
        break;
838
      }
839

    
840
      case AOS_SHELL_ACTION_DELETEBACKWARD:
841
      {
842
        --shell->inputdata.cursorpos;
843
        memmove(&(shell->line[shell->inputdata.cursorpos]), &(shell->line[shell->inputdata.cursorpos+1]), shell->inputdata.lineend - shell->inputdata.cursorpos);
844
        --shell->inputdata.lineend;
845
        shell->line[shell->inputdata.lineend] = '\0';
846
        _moveCursor(shell, shell->inputdata.cursorpos + 1, shell->inputdata.cursorpos);
847
        _printLine(shell, shell->inputdata.cursorpos, shell->inputdata.lineend);
848
        streamPut(&shell->stream, ' ');
849
        _moveCursor(shell, shell->inputdata.lineend+1, shell->inputdata.cursorpos);
850
        break;
851
      }
852

    
853
      case AOS_SHELL_ACTION_RECALLLAST:
854
      {
855
        // replace any intermediate NUL bytes with spaces
856
        shell->inputdata.lineend = 0;
857
        size_t nul_start = 0;
858
        size_t nul_end = 0;
859
        // search line for a NUL byte
860
        while (nul_start < shell->linesize) {
861
          if (shell->line[nul_start] == '\0') {
862
            nul_end = nul_start + 1;
863
            // keep searcjing for a byte that is not NUL
864
            while (nul_end < shell->linesize) {
865
              if (shell->line[nul_end] != '\0') {
866
                // an intermediate NUL sequence was found
867
                memset(&(shell->line[nul_start]), ' ', nul_end - nul_start);
868
                shell->inputdata.lineend = nul_end + 1;
869
                break;
870
              } else {
871
                ++nul_end;
872
              }
873
            }
874
            nul_start = nul_end + 1;
875
          } else {
876
            ++shell->inputdata.lineend;
877
            ++nul_start;
878
          }
879
        }
880
        shell->inputdata.cursorpos = shell->inputdata.lineend;
881
        // print the line
882
        shell->inputdata.noinput = _printLine(shell, 0, shell->inputdata.lineend) == 0;
883
        break;
884
      }
885

    
886
      case AOS_SHELL_ACTION_CLEAR:
887
      {
888
        // clear output
889
        _moveCursor(shell, shell->inputdata.cursorpos, 0);
890
        for (shell->inputdata.cursorpos = 0; shell->inputdata.cursorpos < shell->inputdata.lineend; ++shell->inputdata.cursorpos) {
891
          streamPut(&shell->stream, ' ');
892
        }
893
        _moveCursor(shell, shell->inputdata.lineend, 0);
894
        shell->inputdata.cursorpos = 0;
895
        shell->inputdata.lineend = 0;
896
        shell->inputdata.noinput = true;
897
        break;
898
      }
899

    
900
      case AOS_SHELL_ACTION_CURSOR2START:
901
      {
902
        _moveCursor(shell, shell->inputdata.cursorpos, 0);
903
        shell->inputdata.cursorpos = 0;
904
        break;
905
      }
906

    
907
      case AOS_SHELL_ACTION_CURSOR2END:
908
      {
909
        _moveCursor(shell, shell->inputdata.cursorpos, shell->inputdata.lineend);
910
        shell->inputdata.cursorpos = shell->inputdata.lineend;
911
        break;
912
      }
913

    
914
      case AOS_SHELL_ACTION_CURSORLEFT:
915
      {
916
        _moveCursor(shell, shell->inputdata.cursorpos, shell->inputdata.cursorpos-1);
917
        --shell->inputdata.cursorpos;
918
        break;
919
      }
920

    
921
      case AOS_SHELL_ACTION_CURSORRIGHT:
922
      {
923
        _moveCursor(shell, shell->inputdata.cursorpos, shell->inputdata.cursorpos+1);
924
        ++shell->inputdata.cursorpos;
925
        break;
926
      }
927

    
928
      case AOS_SHELL_ACTION_EXECUTE:
929
      {
930
        streamPut(&shell->stream, '\n');
931
        // set the number of read bytes and return
932
        if (!shell->inputdata.noinput) {
933
          *n = shell->linesize - shell->inputdata.lineend;
934
          // fill the remainder of the line with NUL bytes
935
          memset(&(shell->line[shell->inputdata.lineend]), '\0', *n);
936
          // reset static variables
937
          shell->inputdata.noinput = true;
938
        }
939
        return AOS_SUCCESS;
940
        break;
941
      }
942

    
943
      case AOS_SHELL_ACTION_ESCSTART:
944
      {
945
        shell->inputdata.escseq[0] = c;
946
        ++shell->inputdata.escp;
947
        break;
948
      }
949

    
950
      case AOS_SHELL_ACTION_NONE:
951
      default:
952
      {
953
        // do nothing (ignore input) and read next byte
954
        continue;
955
        break;
956
      }
957
    } /* end of switch */
958

    
959
    shell->inputdata.lastaction = action;
960
  } /* end of while */
961

    
962
  // no more data could be read from the channel
963
  return AOS_WARNING;
964
}
965

    
966
/**
967
 * @brief   Parses the content of the input buffer (line) to separate arguments.
968
 *
969
 * @param[in] shell   Pointer to the shell object.
970
 *
971
 * @return            Number of arguments found.
972
 */
973
static size_t _parseArguments(aos_shell_t* shell)
974
{
975
  aosDbgCheck(shell != NULL);
976

    
977
  /*
978
   * States for a very small FSM.
979
   */
980
  typedef enum {
981
    START,
982
    SPACE,
983
    TEXT,
984
    END,
985
  } state_t;
986

    
987
  // local variables
988
  state_t state = START;
989
  size_t arg = 0;
990

    
991
  // iterate through the line
992
  for (char* c = shell->line; c < shell->line + shell->linesize; ++c) {
993
    // terminate at first NUL byte
994
    if (*c == '\0') {
995
      state = END;
996
      break;
997
    }
998
    // spaces become NUL bytes
999
    else if (*c == ' ') {
1000
      *c = '\0';
1001
      state = SPACE;
1002
    }
1003
    // handle non-NUL bytes
1004
    else {
1005
      switch (state) {
1006
        case START:
1007
        case SPACE:
1008
          // ignore too many arguments
1009
          if (arg < shell->arglistsize) {
1010
            shell->arglist[arg] = c;
1011
          }
1012
          ++arg;
1013
          break;
1014
        case TEXT:
1015
        case END:
1016
        default:
1017
          break;
1018
      }
1019
      state = TEXT;
1020
    }
1021
  }
1022

    
1023
  // set all remaining argument pointers to NULL
1024
  for (size_t a = arg; a < shell->arglistsize; ++a) {
1025
    shell->arglist[a] = NULL;
1026
  }
1027

    
1028
  return arg;
1029
}
1030

    
1031
/**
1032
 * @brief   Initializes a shell object with the specified parameters.
1033
 *
1034
 * @param[in] shell         Pointer to the shell object.
1035
 * @param[in] stream        I/O stream to use.
1036
 * @param[in] prompt        Prompt line to print (NULL = use default prompt).
1037
 * @param[in] line          Pointer to the input buffer.
1038
 * @param[in] linesize      Size of the input buffer.
1039
 * @param[in] arglist       Pointer to the argument buffer.
1040
 * @param[in] arglistsize   Size of te argument buffer.
1041
 */
1042
void aosShellInit(aos_shell_t* shell, event_source_t* oseventsource,  const char* prompt, char* line, size_t linesize, char** arglist, size_t arglistsize)
1043
{
1044
  aosDbgCheck(shell != NULL);
1045
  aosDbgCheck(oseventsource != NULL);
1046
  aosDbgCheck(line != NULL);
1047
  aosDbgCheck(arglist != NULL);
1048

    
1049
  // set parameters
1050
  shell->thread = NULL;
1051
  chEvtObjectInit(&shell->eventSource);
1052
  shell->os.eventSource = oseventsource;
1053
  aosShellStreamInit(&shell->stream);
1054
  shell->prompt = prompt;
1055
  shell->commands = NULL;
1056
  shell->execstatus.command = NULL;
1057
  shell->execstatus.retval = 0;
1058
  shell->line = line;
1059
  shell->linesize = linesize;
1060
  shell->inputdata.lastaction = AOS_SHELL_ACTION_NONE;
1061
  shell->inputdata.escp = 0;
1062
  memset(shell->inputdata.escseq, '\0', sizeof(shell->inputdata.escseq)*sizeof(shell->inputdata.escseq[0]));
1063
  shell->inputdata.cursorpos = 0;
1064
  shell->inputdata.lineend = 0;
1065
  shell->inputdata.noinput = true;
1066
  shell->arglist = arglist;
1067
  shell->arglistsize = arglistsize;
1068
  shell->config = 0x00;
1069

    
1070
  // initialize arrays
1071
  memset(shell->line, '\0', shell->linesize);
1072
  for (size_t a = 0; a < shell->arglistsize; ++a) {
1073
    shell->arglist[a] = NULL;
1074
  }
1075

    
1076
  return;
1077
}
1078

    
1079
/**
1080
 * @brief   Initialize an AosShellStream object.
1081
 *
1082
 * @param[in] stream  The AosShellStrem to initialize.
1083
 */
1084
void aosShellStreamInit(AosShellStream* stream)
1085
{
1086
  aosDbgCheck(stream != NULL);
1087

    
1088
  stream->vmt = &_streamvmt;
1089
  stream->channel = NULL;
1090

    
1091
  return;
1092
}
1093

    
1094
/**
1095
 * @brief   Initialize an AosShellChannel object with the specified parameters.
1096
 *
1097
 * @param[in] channel     The AosShellChannel to initialize.
1098
 * @param[in] iochannel   An AosIOChannel this AosShellChannel is associated with.
1099
 */
1100
void aosShellChannelInit(AosShellChannel* channel, AosIOChannel* iochannel)
1101
{
1102
  aosDbgCheck(channel != NULL);
1103
  aosDbgCheck(iochannel != NULL && iochannel->asyncchannel != NULL);
1104

    
1105
  channel->vmt = &_channelvmt;
1106
  channel->iochannel = iochannel;
1107
  channel->next = NULL;
1108
  channel->flags = 0;
1109

    
1110
  return;
1111
}
1112

    
1113
/**
1114
 * @brief   Inserts a command to the shells list of commands.
1115
 *
1116
 * @param[in] shell   Pointer to the shell object.
1117
 * @param[in] cmd     Pointer to the command to add.
1118
 *
1119
 * @return            A status value.
1120
 * @retval AOS_SUCCESS  The command was added successfully.
1121
 * @retval AOS_ERROR    Another command with identical name already exists.
1122
 */
1123
aos_status_t aosShellAddCommand(aos_shell_t *shell, aos_shellcommand_t *cmd)
1124
{
1125
  aosDbgCheck(shell != NULL);
1126
  aosDbgCheck(cmd != NULL);
1127
  aosDbgCheck(cmd->name != NULL && strlen(cmd->name) > 0 && strchr(cmd->name, ' ') == NULL && strchr(cmd->name, '\t') == NULL);
1128
  aosDbgCheck(cmd->callback != NULL);
1129
  aosDbgCheck(cmd->next == NULL);
1130

    
1131
  aos_shellcommand_t* prev = NULL;
1132
  aos_shellcommand_t** curr = &(shell->commands);
1133

    
1134
  // insert the command to the list wrt lexographical order (exception: lower case characters preceed upper their uppercase counterparts)
1135
  while (*curr != NULL) {
1136
    // iterate through the list as long as the command names are 'smaller'
1137
    const int cmp = _strccmp((*curr)->name, cmd->name, true, NULL, NULL);
1138
    if (cmp < 0) {
1139
      prev = *curr;
1140
      curr = &((*curr)->next);
1141
      continue;
1142
    }
1143
    // error if the command already exists
1144
    else if (cmp == 0) {
1145
      return AOS_ERROR;
1146
    }
1147
    // insert the command as soon as a 'larger' name was found
1148
    else /* if (cmpval > 0) */ {
1149
      cmd->next = *curr;
1150
      // special case: the first command is larger
1151
      if (prev == NULL) {
1152
        shell->commands = cmd;
1153
      } else {
1154
        prev->next = cmd;
1155
      }
1156
      return AOS_SUCCESS;
1157
    }
1158
  }
1159
  // the end of the list has been reached
1160

    
1161
  // append the command
1162
  *curr = cmd;
1163
  return AOS_SUCCESS;
1164
}
1165

    
1166
/**
1167
 * @brief   Removes a command from the shells list of commands.
1168
 *
1169
 * @param[in] shell     Pointer to the shell object.
1170
 * @param[in] cmd       Name of the command to removde.
1171
 * @param[out] removed  Optional pointer to the command that was removed.
1172
 *
1173
 * @return              A status value.
1174
 * @retval AOS_SUCCESS  The command was removed successfully.
1175
 * @retval AOS_ERROR    The command name was not found.
1176
 */
1177
aos_status_t aosShellRemoveCommand(aos_shell_t *shell, char *cmd, aos_shellcommand_t **removed)
1178
{
1179
  aosDbgCheck(shell != NULL);
1180
  aosDbgCheck(cmd != NULL && strlen(cmd) > 0);
1181

    
1182
  aos_shellcommand_t* prev = NULL;
1183
  aos_shellcommand_t** curr = &(shell->commands);
1184

    
1185
  // iterate through the list and seach for the specified command name
1186
  while (curr != NULL) {
1187
    const int cmpval = strcmp((*curr)->name, cmd);
1188
    // iterate through the list as long as the command names are 'smaller'
1189
    if (cmpval < 0) {
1190
      prev = *curr;
1191
      curr = &((*curr)->next);
1192
      continue;
1193
    }
1194
    // remove the command when found
1195
    else if (cmpval == 0) {
1196
      // special case: the first command matches
1197
      if (prev == NULL) {
1198
        shell->commands = (*curr)->next;
1199
      } else {
1200
        prev->next = (*curr)->next;
1201
      }
1202
      (*curr)->next = NULL;
1203
      // set the optional output argument
1204
      if (removed != NULL) {
1205
        *removed = *curr;
1206
      }
1207
      return AOS_SUCCESS;
1208
    }
1209
    // break the loop if the command names are 'larger'
1210
    else /* if (cmpval > 0) */ {
1211
      break;
1212
    }
1213
  }
1214

    
1215
  // if the command was not found, return an error
1216
  return AOS_ERROR;
1217
}
1218

    
1219
/**
1220
 * @brief   Add a channel to a AosShellStream.
1221
 *
1222
 * @param[in] stream    The AosShellStream to extend.
1223
 * @param[in] channel   The channel to be added to the stream.
1224
 */
1225
void aosShellStreamAddChannel(AosShellStream* stream, AosShellChannel* channel)
1226
{
1227
  aosDbgCheck(stream != NULL);
1228
  aosDbgCheck(channel != NULL && channel->iochannel != NULL && channel->iochannel->asyncchannel != NULL && channel->next == NULL && (channel->flags & AOS_SHELLCHANNEL_ATTACHED) == 0);
1229

    
1230
  // prepend the new channel
1231
  chSysLock();
1232
  channel->flags |= AOS_SHELLCHANNEL_ATTACHED;
1233
  channel->next = stream->channel;
1234
  stream->channel = channel;
1235
  chSysUnlock();
1236

    
1237
  return;
1238
}
1239

    
1240
/**
1241
 * @brief   Remove a channel from an AosShellStream.
1242
 *
1243
 * @param[in] stream    The AosShellStream to modify.
1244
 * @param[in] channel   The channel to remove.
1245
 * @return
1246
 */
1247
aos_status_t aosShellStreamRemoveChannel(AosShellStream* stream, AosShellChannel* channel)
1248
{
1249
  aosDbgCheck(stream != NULL);
1250
  aosDbgCheck(channel != NULL && channel->iochannel != NULL && channel->iochannel->asyncchannel != NULL && channel->flags & AOS_SHELLCHANNEL_ATTACHED);
1251

    
1252
  // local varibales
1253
  AosShellChannel* prev = NULL;
1254
  AosShellChannel* curr = stream->channel;
1255

    
1256
  // iterate through the list and search for the specified channel
1257
  while (curr != NULL) {
1258
    // if the channel was found
1259
    if (curr == channel) {
1260
      chSysLock();
1261
      // special case: the first channel matches (prev is NULL)
1262
      if (prev == NULL) {
1263
        stream->channel = curr->next;
1264
      } else {
1265
        prev->next = channel->next;
1266
      }
1267
      curr->next = NULL;
1268
      curr->flags &= ~AOS_SHELLCHANNEL_ATTACHED;
1269
      chSysUnlock();
1270
      return AOS_SUCCESS;
1271
    }
1272
  }
1273

    
1274
  // if the channel was not found, return an error
1275
  return AOS_ERROR;
1276
}
1277

    
1278
/**
1279
 * @brief   Enable a AosSheööChannel as input.
1280
 *
1281
 * @param[in] channel   The channel to enable as input.
1282
 */
1283
void aosShellChannelInputEnable(AosShellChannel* channel)
1284
{
1285
  aosDbgCheck(channel != NULL && channel->iochannel != NULL && channel->iochannel->asyncchannel != NULL);
1286

    
1287
  chSysLock();
1288
  channel->listener.wflags |= CHN_INPUT_AVAILABLE;
1289
  channel->flags |= AOS_SHELLCHANNEL_INPUT_ENABLED;
1290
  chSysUnlock();
1291

    
1292
  return;
1293
}
1294

    
1295
/**
1296
 * @brief   Disable a AosSheööChannel as input.
1297
 *
1298
 * @param[in] channel   The channel to disable as input.
1299
 */
1300
void aosShellChannelInputDisable( AosShellChannel* channel)
1301
{
1302
  aosDbgCheck(channel != NULL && channel->iochannel != NULL && channel->iochannel->asyncchannel != NULL);
1303

    
1304
  chSysLock();
1305
  channel->listener.wflags &= ~CHN_INPUT_AVAILABLE;
1306
  channel->flags &= ~AOS_SHELLCHANNEL_INPUT_ENABLED;
1307
  chSysUnlock();
1308

    
1309
  return;
1310
}
1311

    
1312
/**
1313
 * @brief   Enable a AosSheööChannel as output.
1314
 *
1315
 * @param[in] channel   The channel to enable as output.
1316
 */
1317
void aosShellChannelOutputEnable(AosShellChannel* channel)
1318
{
1319
  aosDbgCheck(channel != NULL && channel->iochannel != NULL && channel->iochannel->asyncchannel != NULL);
1320

    
1321
  channel->flags |= AOS_SHELLCHANNEL_OUTPUT_ENABLED;
1322

    
1323
  return;
1324
}
1325

    
1326
/**
1327
 * @brief   Disable a AosSheööChannel as output.
1328
 *
1329
 * @param[in] channel   The channel to disable as output.
1330
 */
1331
void aosShellChannelOutputDisable(AosShellChannel* channel)
1332
{
1333
  aosDbgCheck(channel != NULL && channel->iochannel != NULL && channel->iochannel->asyncchannel != NULL);
1334

    
1335
  channel->flags &= ~AOS_SHELLCHANNEL_OUTPUT_ENABLED;
1336

    
1337
  return;
1338
}
1339

    
1340
/**
1341
 * @brief   Thread main function.
1342
 *
1343
 * @param[in] aosShellThread    Name of the function;
1344
 * @param[in] shell             Pointer to the shell object.
1345
 */
1346
THD_FUNCTION(aosShellThread, shell)
1347
{
1348
  aosDbgCheck(shell != NULL);
1349

    
1350
  // local variables
1351
  eventmask_t eventmask;
1352
  eventflags_t eventflags;
1353
  AosShellChannel* channel;
1354
  aos_status_t readeval;
1355
  size_t nchars = 0;
1356
  size_t nargs = 0;
1357
  aos_shellcommand_t* cmd;
1358

    
1359

    
1360
  // register OS related events
1361
  chEvtRegisterMask(((aos_shell_t*)shell)->os.eventSource, &(((aos_shell_t*)shell)->os.eventListener), AOS_SHELL_EVENTMASK_OS);
1362
  // register events to all input channels
1363
  for (channel = ((aos_shell_t*)shell)->stream.channel; channel != NULL; channel = channel->next) {
1364
    chEvtRegisterMaskWithFlags(&(channel->iochannel->asyncchannel->event), &(channel->listener), AOS_SHELL_EVENTMASK_INPUT, channel->listener.wflags);
1365
  }
1366

    
1367
  // fire start event
1368
  chEvtBroadcastFlags(&(((aos_shell_t*)shell)->eventSource), AOS_SHELL_EVTFLAG_START);
1369

    
1370
  // print the prompt for the first time
1371
  _printPrompt((aos_shell_t*)shell);
1372

    
1373
  // enter thread loop
1374
  while (!chThdShouldTerminateX()) {
1375
    // wait for event and handle it accordingly
1376
    eventmask = chEvtWaitOne(ALL_EVENTS);
1377

    
1378
    // handle event
1379
    switch (eventmask) {
1380

    
1381
      // OS related events
1382
      case AOS_SHELL_EVENTMASK_OS:
1383
      {
1384
        eventflags = chEvtGetAndClearFlags(&((aos_shell_t*)shell)->os.eventListener);
1385
        // handle shutdown/restart events
1386
        if (eventflags & AOS_SYSTEM_EVENTFLAGS_SHUTDOWN) {
1387
          chThdTerminate(((aos_shell_t*)shell)->thread);
1388
        } else {
1389
          // print an error message
1390
          chprintf((BaseSequentialStream*)&((aos_shell_t*)shell)->stream, "\nERROR: unknown OS event received (0x%08X)\n", eventflags);
1391
        }
1392
        break;
1393
      }
1394

    
1395
      // input events
1396
      case AOS_SHELL_EVENTMASK_INPUT:
1397
      {
1398
        // check and handle all channels
1399
        channel = ((aos_shell_t*)shell)->stream.channel;
1400
        while (channel != NULL) {
1401
          eventflags = chEvtGetAndClearFlags(&channel->listener);
1402
          // if there is new input
1403
          if (eventflags & CHN_INPUT_AVAILABLE) {
1404
            // if the channel is configured as input
1405
            if (channel->flags & AOS_SHELLCHANNEL_INPUT_ENABLED) {
1406
              // read input from channel
1407
              readeval = _readChannel((aos_shell_t*)shell, channel, &nchars);
1408
              // parse input line to argument list only if the input shall be executed
1409
              nargs = (readeval == AOS_SUCCESS && nchars > 0) ? _parseArguments((aos_shell_t*)shell) : 0;
1410
              // check number of arguments
1411
              if (nargs > ((aos_shell_t*)shell)->arglistsize) {
1412
                // error too many arguments
1413
                chprintf((BaseSequentialStream*)&((aos_shell_t*)shell)->stream, "\ttoo many arguments\n");
1414
              } else if (nargs > 0) {
1415
                // search command list for arg[0] and execute callback
1416
                cmd = ((aos_shell_t*)shell)->commands;
1417
                while (cmd != NULL) {
1418
                  if (strcmp(((aos_shell_t*)shell)->arglist[0], cmd->name) == 0) {
1419
                    ((aos_shell_t*)shell)->execstatus.command = cmd;
1420
                    chEvtBroadcastFlags(&(((aos_shell_t*)shell)->eventSource), AOS_SHELL_EVTFLAG_EXEC);
1421
                    ((aos_shell_t*)shell)->execstatus.retval = cmd->callback((BaseSequentialStream*)&((aos_shell_t*)shell)->stream, nargs, ((aos_shell_t*)shell)->arglist);
1422
                    chEvtBroadcastFlags(&(((aos_shell_t*)shell)->eventSource), AOS_SHELL_EVTFLAG_DONE);
1423
                    // notify if the command was not successful
1424
                    if (((aos_shell_t*)shell)->execstatus.retval != 0) {
1425
                      chprintf((BaseSequentialStream*)&((aos_shell_t*)shell)->stream, "command returned exit status %d\n", ((aos_shell_t*)shell)->execstatus.retval);
1426
                    }
1427
                    break;
1428
                  }
1429
                  cmd = cmd->next;
1430
                } /* end of while */
1431

    
1432
                // if no matching command was found, print an error
1433
                if (cmd == NULL) {
1434
                  chprintf((BaseSequentialStream*)&((aos_shell_t*)shell)->stream, "%s: command not found\n", ((aos_shell_t*)shell)->arglist[0]);
1435
                }
1436
              }
1437

    
1438
              // rreset some internal variables and eprint a new prompt
1439
              if (readeval == AOS_SUCCESS && !chThdShouldTerminateX()) {
1440
                ((aos_shell_t*)shell)->inputdata.cursorpos = 0;
1441
                ((aos_shell_t*)shell)->inputdata.lineend = 0;
1442
                _printPrompt((aos_shell_t*)shell);
1443
              }
1444
            }
1445
            // if the channel is not configured as input
1446
            else {
1447
              // read but drop all data
1448
              uint8_t c;
1449
              while (chnReadTimeout(channel, &c, 1, TIME_IMMEDIATE)) {
1450
                continue;
1451
              }
1452
            }
1453
          }
1454

    
1455
          // iterate to next channel
1456
          channel = channel->next;
1457
        }
1458
        break;
1459
      }
1460

    
1461
      // other events
1462
      default:
1463
      {
1464
        // print an error message
1465
        chprintf((BaseSequentialStream*)&((aos_shell_t*)shell)->stream, "\nERROR: unknown event received (0x%08X)\n", eventmask);
1466
        break;
1467
      }
1468

    
1469
    } /* end of switch */
1470

    
1471
  } /* end of while */
1472

    
1473
  // fire event and exit the thread
1474
  chSysLock();
1475
  chEvtBroadcastFlagsI(&(((aos_shell_t*)shell)->eventSource), AOS_SHELL_EVTFLAG_EXIT);
1476
  chThdExitS(MSG_OK);
1477
  // no chSysUnlock() required since the thread has been terminated an all waiting threads have been woken up
1478
}
1479

    
1480
#endif /* AMIROOS_CFG_SHELL_ENABLE == true */