Statistics
| Branch: | Tag: | Revision:

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

History | View | Annotate | Download (49.6 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
 * @details This function interpretes escape sequences (starting with ASCII
356
 *          "Escape" character 0x1B) according to the VT100 / VT52 ANSI escape
357
 *          sequence definitions.
358
 * @note    Only the most important escape sequences are implemented yet.
359
 *
360
 * @param[in] seq   Character sequence to interprete.
361
 *                  Must be terminated by NUL byte.
362
 *
363
 * @return          A @p special_key value.
364
 */
365
static special_key_t _interpreteEscapeSequence(const char seq[])
366
{
367
  // local variables
368
  bool ambiguous = false;
369
  int cmp = 0;
370

    
371
  // TAB
372
  /* not supported yet; use "\x09" instead */
373

    
374
  // BACKSPACE
375
  /* not supported yet; use "\x08" instead */
376

    
377
  // ESCAPE
378
  cmp = strcmp(seq, "\x1B");
379
  if (cmp == 0) {
380
    return KEY_ESCAPE;
381
  } else {
382
    ambiguous |= (cmp < 0);
383
  }
384

    
385
  // INSERT
386
  cmp = strcmp(seq, "\x1B\x5B\x32\x7E");
387
  if (cmp == 0) {
388
    return KEY_INSERT;
389
  } else {
390
    ambiguous |= (cmp < 0);
391
  }
392

    
393
  // DELETE
394
  cmp = strcmp(seq, "\x1B\x5B\x33\x7E");
395
  if (cmp == 0) {
396
    return KEY_DELETE;
397
  } else {
398
    ambiguous |= (cmp < 0);
399
  }
400

    
401
  // HOME
402
  cmp = strcmp(seq, "\x1B\x5B\x48");
403
  if (cmp == 0) {
404
    return KEY_HOME;
405
  } else {
406
    ambiguous |= (cmp < 0);
407
  }
408

    
409
  // END
410
  cmp = strcmp(seq, "\x1B\x5B\x46");
411
  if (cmp == 0) {
412
    return KEY_END;
413
  } else {
414
    ambiguous |= (cmp < 0);
415
  }
416

    
417
  // PAGE UP
418
  cmp = strcmp(seq, "\x1B\x5B\x35\x7E");
419
  if (cmp == 0) {
420
    return KEY_PAGE_UP;
421
  } else {
422
    ambiguous |= (cmp < 0);
423
  }
424

    
425
  // PAGE DOWN
426
  cmp = strcmp(seq, "\x1B\x5B\x36\x7E");
427
  if (cmp == 0) {
428
    return KEY_PAGE_DOWN;
429
  } else {
430
    ambiguous |= (cmp < 0);
431
  }
432

    
433
  // ARROW UP
434
  cmp = strcmp(seq, "\x1B\x5B\x41");
435
  if (cmp == 0) {
436
    return KEY_ARROW_UP;
437
  } else {
438
    ambiguous |= (cmp < 0);
439
  }
440

    
441
  // ARROW DOWN
442
  cmp = strcmp(seq, "\x1B\x5B\x42");
443
  if (cmp == 0) {
444
    return KEY_ARROW_DOWN;
445
  } else {
446
    ambiguous |= (cmp < 0);
447
  }
448

    
449
  // ARROW LEFT
450
  cmp = strcmp(seq, "\x1B\x5B\x44");
451
  if (cmp == 0) {
452
    return KEY_ARROW_LEFT;
453
  } else {
454
    ambiguous |= (cmp < 0);
455
  }
456

    
457
  // ARROW RIGHT
458
  cmp = strcmp(seq, "\x1B\x5B\x43");
459
  if (cmp == 0) {
460
    return KEY_ARROW_RIGHT;
461
  } else {
462
    ambiguous |= (cmp < 0);
463
  }
464

    
465
  return ambiguous ? KEY_AMBIGUOUS : KEY_UNKNOWN;
466
}
467

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

    
481
  // local variables
482
  size_t pos = from;
483

    
484
  // move cursor left by printing backspaces
485
  while (pos > to) {
486
    streamPut(&shell->stream, '\b');
487
    --pos;
488
  }
489

    
490
  // move cursor right by printing line content
491
  while (pos < to) {
492
    streamPut(&shell->stream, shell->line[pos]);
493
    ++pos;
494
  }
495

    
496
  return (int)pos - (int)from;
497
}
498

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

    
512
  // local variables
513
  size_t cnt;
514

    
515
  for (cnt = 0; from + cnt < to; ++cnt) {
516
    streamPut(&shell->stream, shell->line[from + cnt]);
517
  }
518

    
519
  return cnt;
520
}
521

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

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

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

    
594
  // initialize variables
595
  if (m) {
596
    *m = CHAR_MATCH_NOT;
597
  }
598
  size_t i = 0;
599

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

    
624
  return _mapAscii2Custom(str1[i]) - _mapAscii2Custom(str2[i]);
625
}
626

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

    
642
  // local variables
643
  aos_shellaction_t action = AOS_SHELL_ACTION_NONE;
644
  char c;
645
  special_key_t key;
646

    
647
  // initialize output variables
648
  *n = 0;
649

    
650
  // read character by character from the channel
651
  while (chnReadTimeout(channel, (uint8_t*)&c, 1, TIME_IMMEDIATE)) {
652
    key = KEY_UNKNOWN;
653

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

    
673
    /* interprete keys or character */
674
    {
675
      // default
676
      action = AOS_SHELL_ACTION_NONE;
677

    
678
      // printable character
679
      if (key == KEY_UNKNOWN && c >= '\x20' && c <= '\x7E') {
680
        action = AOS_SHELL_ACTION_READCHAR;
681
      }
682

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

    
696
      // INS key
697
      else if (key == KEY_INSERT) {
698
        action = AOS_SHELL_ACTION_INSERTTOGGLE;
699
      }
700

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

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

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

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

    
733
      // 'home' key
734
      else if (key == KEY_HOME) {
735
        // ignore if cursor is very left
736
        if (shell->inputdata.cursorpos > 0) {
737
          action = AOS_SHELL_ACTION_CURSOR2START;
738
        }
739
      }
740

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

    
749
      // 'arrow left' key
750
      else if (key == KEY_ARROW_LEFT) {
751
        // ignore if cursor is very left
752
        if (shell->inputdata.cursorpos > 0) {
753
          action = AOS_SHELL_ACTION_CURSORLEFT;
754
        }
755
      }
756

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

    
765
      // carriage return ('\r') or line feed ('\n') character
766
      else if (c == '\x0D' || c == '\x0A') {
767
        action = AOS_SHELL_ACTION_EXECUTE;
768
      }
769

    
770
      // ESC key or [ESCAPE] character
771
      else if (key == KEY_ESCAPE || c == '\x1B') {
772
        action = AOS_SHELL_ACTION_ESCSTART;
773
      }
774
    }
775

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

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

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

    
928
      case AOS_SHELL_ACTION_INSERTTOGGLE:
929
      {
930
        if (shell->config & AOS_SHELL_CONFIG_INPUT_OVERWRITE) {
931
          shell->config &= ~AOS_SHELL_CONFIG_INPUT_OVERWRITE;
932
        } else {
933
          shell->config |= AOS_SHELL_CONFIG_INPUT_OVERWRITE;
934
        }
935
        break;
936
      }
937

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

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

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

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

    
1008
      case AOS_SHELL_ACTION_CURSOR2START:
1009
      {
1010
        _moveCursor(shell, shell->inputdata.cursorpos, 0);
1011
        shell->inputdata.cursorpos = 0;
1012
        break;
1013
      }
1014

    
1015
      case AOS_SHELL_ACTION_CURSOR2END:
1016
      {
1017
        _moveCursor(shell, shell->inputdata.cursorpos, shell->inputdata.lineend);
1018
        shell->inputdata.cursorpos = shell->inputdata.lineend;
1019
        break;
1020
      }
1021

    
1022
      case AOS_SHELL_ACTION_CURSORLEFT:
1023
      {
1024
        _moveCursor(shell, shell->inputdata.cursorpos, shell->inputdata.cursorpos-1);
1025
        --shell->inputdata.cursorpos;
1026
        break;
1027
      }
1028

    
1029
      case AOS_SHELL_ACTION_CURSORRIGHT:
1030
      {
1031
        _moveCursor(shell, shell->inputdata.cursorpos, shell->inputdata.cursorpos+1);
1032
        ++shell->inputdata.cursorpos;
1033
        break;
1034
      }
1035

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

    
1050
      case AOS_SHELL_ACTION_ESCSTART:
1051
      {
1052
        shell->inputdata.escseq[0] = c;
1053
        ++shell->inputdata.escp;
1054
        break;
1055
      }
1056

    
1057
      case AOS_SHELL_ACTION_NONE:
1058
      default:
1059
      {
1060
        // do nothing (ignore input) and read next byte
1061
        continue;
1062
      }
1063
    } /* end of switch */
1064

    
1065
    shell->inputdata.lastaction = action;
1066
  } /* end of while */
1067

    
1068
  // no more data could be read from the channel
1069
  return AOS_WARNING;
1070
}
1071

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

    
1083
  /*
1084
   * States for a very small FSM.
1085
   */
1086
  typedef enum {
1087
    START,
1088
    SPACE,
1089
    TEXT,
1090
    END,
1091
  } state_t;
1092

    
1093
  // local variables
1094
  state_t state = START;
1095
  size_t arg = 0;
1096

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

    
1129
  // set all remaining argument pointers to NULL
1130
  for (size_t a = arg; a < shell->arglistsize; ++a) {
1131
    shell->arglist[a] = NULL;
1132
  }
1133

    
1134
  return arg;
1135
}
1136

    
1137
/******************************************************************************/
1138
/* EXPORTED FUNCTIONS                                                         */
1139
/******************************************************************************/
1140

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

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

    
1180
  // initialize arrays
1181
  memset(shell->line, '\0', shell->linesize);
1182
  for (size_t a = 0; a < shell->arglistsize; ++a) {
1183
    shell->arglist[a] = NULL;
1184
  }
1185

    
1186
  return;
1187
}
1188

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

    
1198
  stream->vmt = &_streamvmt;
1199
  stream->channel = NULL;
1200

    
1201
  return;
1202
}
1203

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

    
1215
  channel->vmt = &_channelvmt;
1216
  channel->asyncchannel = asyncchannel;
1217
  channel->listener.wflags = 0;
1218
  channel->next = NULL;
1219
  channel->flags = 0;
1220

    
1221
  return;
1222
}
1223

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

    
1242
  aos_shellcommand_t* prev = NULL;
1243
  aos_shellcommand_t** curr = &(shell->commands);
1244

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

    
1272
  // append the command
1273
  *curr = cmd;
1274
  return AOS_SUCCESS;
1275
}
1276

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

    
1293
  aos_shellcommand_t* prev = NULL;
1294
  aos_shellcommand_t** curr = &(shell->commands);
1295

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

    
1326
  // if the command was not found, return an error
1327
  return AOS_ERROR;
1328
}
1329

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

    
1341
  unsigned int count = 0;
1342
  aos_shellcommand_t* cmd = shell->commands;
1343
  while (cmd != NULL) {
1344
    ++count;
1345
    cmd = cmd->next;
1346
  }
1347

    
1348
  return count;
1349
}
1350

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

    
1362
  // prepend the new channel
1363
  chSysLock();
1364
  channel->flags |= AOS_SHELLCHANNEL_ATTACHED;
1365
  channel->next = stream->channel;
1366
  stream->channel = channel;
1367
  chSysUnlock();
1368

    
1369
  return;
1370
}
1371

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

    
1387
  // local varibales
1388
  AosShellChannel* prev = NULL;
1389
  AosShellChannel* curr = stream->channel;
1390

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

    
1409
  // if the channel was not found, return an error
1410
  return AOS_ERROR;
1411
}
1412

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

    
1422
  chSysLock();
1423
  channel->listener.wflags |= CHN_INPUT_AVAILABLE;
1424
  channel->flags |= AOS_SHELLCHANNEL_INPUT_ENABLED;
1425
  chSysUnlock();
1426

    
1427
  return;
1428
}
1429

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

    
1439
  chSysLock();
1440
  channel->listener.wflags &= ~CHN_INPUT_AVAILABLE;
1441
  channel->flags &= ~AOS_SHELLCHANNEL_INPUT_ENABLED;
1442
  chSysUnlock();
1443

    
1444
  return;
1445
}
1446

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

    
1456
  channel->flags |= AOS_SHELLCHANNEL_OUTPUT_ENABLED;
1457

    
1458
  return;
1459
}
1460

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

    
1470
  channel->flags &= ~AOS_SHELLCHANNEL_OUTPUT_ENABLED;
1471

    
1472
  return;
1473
}
1474

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

    
1485
  // local variables
1486
  eventmask_t eventmask;
1487
  eventflags_t eventflags;
1488
  AosShellChannel* channel;
1489
  aos_status_t readeval;
1490
  size_t nchars = 0;
1491
  size_t nargs = 0;
1492
  aos_shellcommand_t* cmd;
1493

    
1494

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

    
1502
  // fire start event
1503
  chEvtBroadcastFlags(&(((aos_shell_t*)shell)->eventSource), AOS_SHELL_EVTFLAG_START);
1504

    
1505
  // print the prompt for the first time
1506
  _printPrompt((aos_shell_t*)shell);
1507

    
1508
  // enter thread loop
1509
  while (!chThdShouldTerminateX()) {
1510
    // wait for event and handle it accordingly
1511
    eventmask = chEvtWaitOne(ALL_EVENTS);
1512

    
1513
    // handle event
1514
    switch (eventmask) {
1515

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

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

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

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

    
1579
          // iterate to next channel
1580
          channel = channel->next;
1581
        }
1582
        break;
1583
      }
1584

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

    
1593
    } /* end of switch */
1594

    
1595
  } /* end of while */
1596

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

    
1604
#endif /* (AMIROOS_CFG_SHELL_ENABLE == true) || (AMIROOS_CFG_TESTS_ENABLE == true)*/
1605

    
1606
/** @} */