Statistics
| Branch: | Tag: | Revision:

amiro-os / os / core / src / aos_shell.c @ 0128be0f

History | View | Annotate | Download (45.612 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 <string.h>
26

    
27
/**
28
 * @brief   Event mask to be set on OS related events.
29
 */
30
#define AOS_SHELL_EVENTMASK_OS                  EVENT_MASK(0)
31

    
32
/**
33
 * @brief   Event mask to be set on a input event.
34
 */
35
#define AOS_SHELL_EVENTMASK_INPUT               EVENT_MASK(1)
36

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

    
49
/**
50
 * @brief   Implementation of the BaseAsynchronous read() method (inherited from BaseSequentialStream).
51
 */
52
static size_t _channelread(void *instance, uint8_t *bp, size_t n)
53
{
54
  if (((AosShellChannel*)instance)->flags & AOS_SHELLCHANNEL_INPUT_ENABLED) {
55
    return streamRead(((AosShellChannel*)instance)->asyncchannel, bp, n);
56
  } else {
57
    return 0;
58
  }
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)->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
  if (((AosShellChannel*)instance)->flags & AOS_SHELLCHANNEL_INPUT_ENABLED) {
79
    return streamGet(((AosShellChannel*)instance)->asyncchannel);
80
  } else {
81
    return MSG_RESET;
82
  }
83
}
84

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

    
97
/**
98
 * @brief   Implementation of the BaseAsynchronous gett() method.
99
 */
100
static msg_t _channelgett(void *instance, systime_t time)
101
{
102
  if (((AosShellChannel*)instance)->flags & AOS_SHELLCHANNEL_INPUT_ENABLED) {
103
    return chnGetTimeout(((AosShellChannel*)instance)->asyncchannel, time);
104
  } else {
105
    return MSG_RESET;
106
  }
107
}
108

    
109
/**
110
 * @brief   Implementation of the BaseAsynchronous writet() method.
111
 */
112
static size_t _channelwritet(void *instance, const uint8_t *bp, size_t n, systime_t time)
113
{
114
  if (((AosShellChannel*)instance)->flags & AOS_SHELLCHANNEL_OUTPUT_ENABLED) {
115
    return chnWriteTimeout(((AosShellChannel*)instance)->asyncchannel, bp, n, time);
116
  } else {
117
    return 0;
118
  }
119
}
120

    
121
/**
122
 * @brief   Implementation of the BaseAsynchronous readt() method.
123
 */
124
static size_t _channelreadt(void *instance, uint8_t *bp, size_t n, systime_t time)
125
{
126
  if (((AosShellChannel*)instance)->flags & AOS_SHELLCHANNEL_INPUT_ENABLED) {
127
    return chnReadTimeout(((AosShellChannel*)instance)->asyncchannel, bp, n, time);
128
  } else {
129
    return 0;
130
  }
131
}
132

    
133
static const struct AosShellChannelVMT _channelvmt = {
134
  (size_t) 0,
135
  _channelwrite,
136
  _channelread,
137
  _channelput,
138
  _channelget,
139
  _channelputt,
140
  _channelgett,
141
  _channelwritet,
142
  _channelreadt,
143
};
144

    
145
static size_t _streamwrite(void *instance, const uint8_t *bp, size_t n)
146
{
147
  aosDbgCheck(instance != NULL);
148

    
149
  // local variables
150
  AosShellChannel* channel = ((AosShellStream*)instance)->channel;
151
  size_t bytes;
152
  size_t maxbytes = 0;
153

    
154
  // iterate through the list of channels
155
  while (channel != NULL) {
156
    bytes = streamWrite(channel, bp, n);
157
    maxbytes = (bytes > maxbytes) ? bytes : maxbytes;
158
    channel = channel->next;
159
  }
160

    
161
  return maxbytes;
162
}
163

    
164
static size_t _stremread(void *instance, uint8_t *bp, size_t n)
165
{
166
  (void)instance;
167
  (void)bp;
168
  (void)n;
169

    
170
  return 0;
171
}
172

    
173
static msg_t _streamput(void *instance, uint8_t b)
174
{
175
  aosDbgCheck(instance != NULL);
176

    
177
  // local variables
178
  AosShellChannel* channel = ((AosShellStream*)instance)->channel;
179
  msg_t ret = MSG_OK;
180

    
181
  // iterate through the list of channels
182
  while (channel != NULL) {
183
    msg_t ret_ = streamPut(channel, b);
184
    ret = (ret_ < ret) ? ret_ : ret;
185
    channel = channel->next;
186
  }
187

    
188
  return ret;
189
}
190

    
191
static msg_t _streamget(void *instance)
192
{
193
  (void)instance;
194

    
195
  return 0;
196
}
197

    
198
static const struct AosShellStreamVMT _streamvmt = {
199
  (size_t) 0,
200
  _streamwrite,
201
  _stremread,
202
  _streamput,
203
  _streamget,
204
};
205

    
206
/**
207
 * @brief   Enumerator of special keyboard keys.
208
 */
209
typedef enum special_key {
210
  KEY_UNKNOWN,      /**< any/unknow key */
211
  KEY_AMBIGUOUS,    /**< key is ambiguous */
212
  KEY_TAB,          /**< tabulator key */
213
  KEY_ESCAPE,       /**< escape key */
214
  KEY_BACKSPACE,    /**< backspace key */
215
  KEY_INSERT,       /**< insert key */
216
  KEY_DELETE,       /**< delete key */
217
  KEY_HOME,         /**< home key */
218
  KEY_END,          /**< end key */
219
  KEY_PAGE_UP,      /**< page up key */
220
  KEY_PAGE_DOWN,    /**< page down key */
221
  KEY_ARROW_UP,     /**< arrow up key */
222
  KEY_ARROW_DOWN,   /**< arrow down key */
223
  KEY_ARROW_LEFT,   /**< arrow left key */
224
  KEY_ARROW_RIGHT,  /**< arrow right key */
225
} special_key_t;
226

    
227
/**
228
 * @brief   Enumerator for case (in)sensitive character matching.
229
 */
230
typedef enum charmatch {
231
  CHAR_MATCH_NOT    = 0,  /**< Characters do not match at all. */
232
  CHAR_MATCH_NCASE  = 1,  /**< Characters would match case insensitive. */
233
  CHAR_MATCH_CASE   = 2,  /**< Characters do match with case. */
234
} charmatch_t;
235

    
236
/**
237
 * @brief   Print the shell prompt
238
 * @details Depending on the configuration flags, the system uptime is printed before the prompt string.
239
 *
240
 * @param[in] shell   Pointer to the shell object.
241
 */
242
static void _printPrompt(aos_shell_t* shell)
243
{
244
  aosDbgCheck(shell != NULL);
245

    
246
  // print some time informattion before prompt if configured
247
  if (shell->config & (AOS_SHELL_CONFIG_PROMPT_UPTIME | AOS_SHELL_CONFIG_PROMPT_DATETIME)) {
248
    // printf the system uptime
249
    if ((shell->config & (AOS_SHELL_CONFIG_PROMPT_UPTIME | AOS_SHELL_CONFIG_PROMPT_DATETIME)) == AOS_SHELL_CONFIG_PROMPT_UPTIME) {
250
      // get current system uptime
251
      aos_timestamp_t uptime;
252
      aosSysGetUptime(&uptime);
253

    
254
      chprintf((BaseSequentialStream*)&shell->stream, "[%01u:%02u:%02u:%02u:%03u:%03u] ",
255
               (uint32_t)(uptime / MICROSECONDS_PER_DAY),
256
               (uint8_t)(uptime % MICROSECONDS_PER_DAY / MICROSECONDS_PER_HOUR),
257
               (uint8_t)(uptime % MICROSECONDS_PER_HOUR / MICROSECONDS_PER_MINUTE),
258
               (uint8_t)(uptime % MICROSECONDS_PER_MINUTE / MICROSECONDS_PER_SECOND),
259
               (uint16_t)(uptime % MICROSECONDS_PER_SECOND / MICROSECONDS_PER_MILLISECOND),
260
               (uint16_t)(uptime % MICROSECONDS_PER_MILLISECOND / MICROSECONDS_PER_MICROSECOND));
261
    }
262
    else if ((shell->config & (AOS_SHELL_CONFIG_PROMPT_UPTIME | AOS_SHELL_CONFIG_PROMPT_DATETIME)) == AOS_SHELL_CONFIG_PROMPT_DATETIME) {
263
      // get current RTC time
264
      struct tm dt;
265
      aosSysGetDateTime(&dt);
266
      chprintf((BaseSequentialStream*)&shell->stream, "[%02u-%02u-%04u|%02u:%02u:%02u] ",
267
               dt.tm_mday,
268
               dt.tm_mon + 1,
269
               dt.tm_year + 1900,
270
               dt.tm_hour,
271
               dt.tm_min,
272
               dt.tm_sec);
273
    }
274
    else {
275
      aosDbgAssert(false);
276
    }
277
  }
278

    
279
  // print the actual prompt string
280
  if (shell->prompt && !(shell->config & AOS_SHELL_CONFIG_PROMPT_MINIMAL)) {
281
    chprintf((BaseSequentialStream*)&shell->stream, "%s$ ", shell->prompt);
282
  } else {
283
    chprintf((BaseSequentialStream*)&shell->stream, "%>$ ");
284
  }
285

    
286
  return;
287
}
288

    
289
/**
290
 * @brief   Interprete a escape sequence
291
 *
292
 * @param[in] seq   Character sequence to interprete.
293
 *                  Must be terminated by NUL byte.
294
 *
295
 * @return          A @p special_key value.
296
 */
297
static special_key_t _interpreteEscapeSequence(const char seq[])
298
{
299
  // local variables
300
  bool ambiguous = false;
301
  int cmp = 0;
302

    
303
  // TAB
304
  /* not supported yet; use "\x09" instead */
305

    
306
  // BACKSPACE
307
  /* not supported yet; use "\x08" instead */
308

    
309
  // ESCAPE
310
  cmp = strcmp(seq, "\x1B");
311
  if (cmp == 0) {
312
    return KEY_ESCAPE;
313
  } else {
314
    ambiguous |= (cmp < 0);
315
  }
316

    
317
  // INSERT
318
  cmp = strcmp(seq, "\x1B\x5B\x32\x7E");
319
  if (cmp == 0) {
320
    return KEY_INSERT;
321
  } else {
322
    ambiguous |= (cmp < 0);
323
  }
324

    
325
  // DELETE
326
  cmp = strcmp(seq, "\x1B\x5B\x33\x7E");
327
  if (cmp == 0) {
328
    return KEY_DELETE;
329
  } else {
330
    ambiguous |= (cmp < 0);
331
  }
332

    
333
  // HOME
334
  cmp = strcmp(seq, "\x1B\x4F\x48");
335
  if (cmp == 0) {
336
    return KEY_HOME;
337
  } else {
338
    ambiguous |= (cmp < 0);
339
  }
340

    
341
  // END
342
  cmp = strcmp(seq, "\x1B\x4F\x46");
343
  if (cmp == 0) {
344
    return KEY_END;
345
  } else {
346
    ambiguous |= (cmp < 0);
347
  }
348

    
349
  // PAGE UP
350
  cmp = strcmp(seq, "\x1B\x5B\x35\x7E");
351
  if (cmp == 0) {
352
    return KEY_PAGE_UP;
353
  } else {
354
    ambiguous |= (cmp < 0);
355
  }
356

    
357
  // PAGE DOWN
358
  cmp = strcmp(seq, "\x1B\x5B\x36\x7E");
359
  if (cmp == 0) {
360
    return KEY_PAGE_DOWN;
361
  } else {
362
    ambiguous |= (cmp < 0);
363
  }
364

    
365
  // ARROW UP
366
  cmp = strcmp(seq, "\x1B\x5B\x41");
367
  if (cmp == 0) {
368
    return KEY_ARROW_UP;
369
  } else {
370
    ambiguous |= (cmp < 0);
371
  }
372

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

    
381
  // ARROW LEFT
382
  cmp = strcmp(seq, "\x1B\x5B\x44");
383
  if (cmp == 0) {
384
    return KEY_ARROW_LEFT;
385
  } else {
386
    ambiguous |= (cmp < 0);
387
  }
388

    
389
  // ARROW RIGHT
390
  cmp = strcmp(seq, "\x1B\x5B\x43");
391
  if (cmp == 0) {
392
    return KEY_ARROW_RIGHT;
393
  } else {
394
    ambiguous |= (cmp < 0);
395
  }
396

    
397
  return ambiguous ? KEY_AMBIGUOUS : KEY_UNKNOWN;
398
}
399

    
400
/**
401
 * @brief   Move the cursor in the terminal
402
 *
403
 * @param[in] shell   Pointer to the shell object.
404
 * @param[in] from    Starting position of the cursor.
405
 * @param[in] to      Target position to move the cursor to.
406
 *
407
 * @return            The number of positions moved.
408
 */
409
static int _moveCursor(aos_shell_t* shell, const size_t from, const size_t to)
410
{
411
  aosDbgCheck(shell != NULL);
412

    
413
  // local variables
414
  size_t pos = from;
415

    
416
  // move cursor left by printing backspaces
417
  while (pos > to) {
418
    streamPut(&shell->stream, '\b');
419
    --pos;
420
  }
421

    
422
  // move cursor right by printing line content
423
  while (pos < to) {
424
    streamPut(&shell->stream, shell->line[pos]);
425
    ++pos;
426
  }
427

    
428
  return (int)pos - (int)from;
429
}
430

    
431
/**
432
 * @brief   Print content of the shell line
433
 *
434
 * @param[in] shell   Pointer to the shell object.
435
 * @param[in] from    First position to start printing from.
436
 * @param[in] to      Position after the last character to print.
437
 *
438
 * @return            Number of characters printed.
439
 */
440
static inline size_t _printLine(aos_shell_t* shell, const size_t from, const size_t to)
441
{
442
  aosDbgCheck(shell != NULL);
443

    
444
  // local variables
445
  size_t cnt;
446

    
447
  for (cnt = 0; from + cnt < to; ++cnt) {
448
    streamPut(&shell->stream, shell->line[from + cnt]);
449
  }
450

    
451
  return cnt;
452
}
453

    
454
/**
455
 * @brief   Compare two characters.
456
 *
457
 * @param[in] lhs       First character to compare.
458
 * @param[in] rhs       Second character to compare.
459
 *
460
 * @return              How well the characters match.
461
 */
462
static inline charmatch_t _charcmp(char lhs, char rhs)
463
{
464
  // if lhs is a upper case letter and rhs is a lower case letter
465
  if (lhs >= 'A' && lhs <= 'Z' && rhs >= 'a' && rhs <= 'z') {
466
    return (lhs == (rhs - 'a' + 'A')) ? CHAR_MATCH_NCASE : CHAR_MATCH_NOT;
467
  }
468
  // if lhs is a lower case letter and rhs is a upper case letter
469
  else if (lhs >= 'a' && lhs <= 'z' && rhs >= 'A' && rhs <= 'Z') {
470
    return ((lhs - 'a' + 'A') == rhs) ? CHAR_MATCH_NCASE : CHAR_MATCH_NOT;
471
  }
472
  // default
473
  else {
474
    return (lhs == rhs) ? CHAR_MATCH_CASE : CHAR_MATCH_NOT;
475
  }
476
}
477

    
478
/**
479
 * @brief   Maps an character from ASCII to a modified custom encoding.
480
 * @details The custom character encoding is very similar to ASCII and has the following structure:
481
 *          0x00=NULL ... 0x40='@' (identically to ASCII)
482
 *          0x4A='a'; 0x4B='A'; 0x4C='b'; 0x4D='B' ... 0x73='z'; 0x74='Z' (custom letter order)
483
 *          0x75='[' ... 0x7A='`' (0x5B..0x60 is ASCII)
484
 *          0x7B='{' ... 0x7F=DEL (identically to ASCII)
485
 *
486
 * @param[in] c   Character to map to the custom encoding.
487
 *
488
 * @return    The customly encoded character.
489
 */
490
static inline char _mapAscii2Custom(const char c)
491
{
492
  if (c >= 'A' && c <= 'Z') {
493
    return ((c - 'A') * 2) + 'A' + 1;
494
  } else if (c > 'Z' && c < 'a') {
495
    return c + ('z' - 'a') + 1;
496
  } else if (c >= 'a' && c <= 'z') {
497
    return ((c - 'a') * 2) + 'A';
498
  } else {
499
    return c;
500
  }
501
}
502

    
503
/**
504
 * @brief   Compares two strings wrt letter case.
505
 * @details Comparisson uses a custom character encoding or mapping.
506
 *          See @p _mapAscii2Custom for details.
507
 *
508
 * @param[in] str1    First string to compare.
509
 * @param[in] str2    Second string to compare.
510
 * @param[in] cs      Flag indicating whether comparison shall be case sensitive.
511
 * @param[in,out] n   Maximum number of character to compare (in) and number of matching characters (out).
512
 *                    If a null pointer is specified, this parameter is ignored.
513
 *                    If the value pointed to is zero, comarison will not be limited.
514
 * @param[out] m      Optional indicator whether there was at least one case mismatch.
515
 *
516
 * @return      Integer value indicating the relationship between the strings.
517
 * @retval <0   The first character that does not match has a lower value in str1 than in str2.
518
 * @retval  0   The contents of both strings are equal.
519
 * @retval >0   The first character that does not match has a greater value in str1 than in str2.
520
 */
521
static int _strccmp(const char *str1, const char *str2, bool cs, size_t* n, charmatch_t* m)
522
{
523
  aosDbgCheck(str1 != NULL);
524
  aosDbgCheck(str2 != NULL);
525

    
526
  // initialize variables
527
  if (m) {
528
    *m = CHAR_MATCH_NOT;
529
  }
530
  size_t i = 0;
531

    
532
  // iterate through the strings
533
  while ((n == NULL) || (*n == 0) || (*n > 0 && i < *n)) {
534
    // break on NUL
535
    if (str1[i] == '\0' || str2[i] == '\0') {
536
      if (n) {
537
        *n = i;
538
      }
539
      break;
540
    }
541
    // compare character
542
    const charmatch_t match = _charcmp(str1[i], str2[i]);
543
    if ((match == CHAR_MATCH_CASE) || (!cs && match == CHAR_MATCH_NCASE)) {
544
      if (m != NULL && *m != CHAR_MATCH_NCASE) {
545
        *m = match;
546
      }
547
      ++i;
548
    } else {
549
      if (n) {
550
        *n = i;
551
      }
552
      break;
553
    }
554
  }
555

    
556
  return _mapAscii2Custom(str1[i]) - _mapAscii2Custom(str2[i]);
557
}
558

    
559
static aos_status_t _readChannel(aos_shell_t* shell, AosShellChannel* channel, size_t* n)
560
{
561
  aosDbgCheck(shell != NULL);
562
  aosDbgCheck(channel != NULL);
563
  aosDbgCheck(n != NULL);
564

    
565
  // local variables
566
  aos_shellaction_t action = AOS_SHELL_ACTION_NONE;
567
  char c;
568
  special_key_t key;
569

    
570
  // initialize output variables
571
  *n = 0;
572

    
573
  // read character by character from the channel
574
  while (chnReadTimeout(channel, (uint8_t*)&c, 1, TIME_IMMEDIATE)) {
575
    key = KEY_UNKNOWN;
576

    
577
    // parse escape sequence
578
    if (shell->inputdata.escp > 0) {
579
      shell->inputdata.escseq[shell->inputdata.escp] = c;
580
      ++shell->inputdata.escp;
581
      key = _interpreteEscapeSequence(shell->inputdata.escseq);
582
      if (key == KEY_AMBIGUOUS) {
583
        // read next byte to resolve ambiguity
584
        continue;
585
      } else {
586
        /*
587
         * If the escape sequence could either be parsed sucessfully
588
         * or there is no match (KEY_UNKNOWN),
589
         * reset the sequence variable and interprete key/character
590
         */
591
        shell->inputdata.escp = 0;
592
        memset(shell->inputdata.escseq, '\0', sizeof(shell->inputdata.escseq)*sizeof(shell->inputdata.escseq[0]));
593
      }
594
    }
595

    
596
    /* interprete keys or character */
597
    {
598
      // default
599
      action = AOS_SHELL_ACTION_NONE;
600

    
601
      // printable character
602
      if (key == KEY_UNKNOWN && c >= '\x20' && c <= '\x7E') {
603
        action = AOS_SHELL_ACTION_READCHAR;
604
      }
605

    
606
      // tab key or character
607
      else if (key == KEY_TAB || c == '\x09') {
608
        /*
609
         * pressing tab once applies auto fill
610
         * pressing tab a second time prints suggestions
611
         */
612
        if (shell->inputdata.lastaction == AOS_SHELL_ACTION_AUTOFILL || shell->inputdata.lastaction == AOS_SHELL_ACTION_SUGGEST) {
613
          action = AOS_SHELL_ACTION_SUGGEST;
614
        } else {
615
          action = AOS_SHELL_ACTION_AUTOFILL;
616
        }
617
      }
618

    
619
      // INS key
620
      else if (key == KEY_INSERT) {
621
        action = AOS_SHELL_ACTION_INSERTTOGGLE;
622
      }
623

    
624
      // DEL key or character
625
      else if (key == KEY_DELETE || c == '\x7F') {
626
        // ignore if cursor is at very right
627
        if (shell->inputdata.cursorpos < shell->inputdata.lineend) {
628
          action = AOS_SHELL_ACTION_DELETEFORWARD;
629
        }
630
      }
631

    
632
      // backspace key or character
633
      else if (key == KEY_BACKSPACE || c == '\x08') {
634
        // ignore if cursor is at very left
635
        if (shell->inputdata.cursorpos > 0) {
636
          action = AOS_SHELL_ACTION_DELETEBACKWARD;
637
        }
638
      }
639

    
640
      // 'page up' of 'arrow up' key
641
      else if (key == KEY_PAGE_UP || key == KEY_ARROW_UP) {
642
        // ignore if there was some input
643
        if (shell->inputdata.noinput) {
644
          action = AOS_SHELL_ACTION_RECALLLAST;
645
        }
646
      }
647

    
648
      // 'page down' key, 'arrow done' key, 'end of test' character or 'end of transmission' character
649
      else if (key == KEY_PAGE_DOWN || key == KEY_ARROW_DOWN || c == '\x03' || c == '\x03') {
650
        // ignore if line is empty
651
        if (shell->inputdata.lineend > 0) {
652
          action = AOS_SHELL_ACTION_CLEAR;
653
        }
654
      }
655

    
656
      // 'home' key
657
      else if (key == KEY_HOME) {
658
        // ignore if cursor is very left
659
        if (shell->inputdata.cursorpos > 0) {
660
          action = AOS_SHELL_ACTION_CURSOR2START;
661
        }
662
      }
663

    
664
      // 'end' key
665
      else if (key == KEY_END) {
666
        // ignore if cursos is very right
667
        if (shell->inputdata.cursorpos < shell->inputdata.lineend) {
668
          action = AOS_SHELL_ACTION_CURSOR2END;
669
        }
670
      }
671

    
672
      // 'arrow left' key
673
      else if (key == KEY_ARROW_LEFT) {
674
        // ignore if cursor is very left
675
        if (shell->inputdata.cursorpos > 0) {
676
          action = AOS_SHELL_ACTION_CURSORLEFT;
677
        }
678
      }
679

    
680
      // 'arrow right' key
681
      else if (key == KEY_ARROW_RIGHT) {
682
        // irgnore if cursor is very right
683
        if (shell->inputdata.cursorpos < shell->inputdata.lineend) {
684
          action = AOS_SHELL_ACTION_CURSORRIGHT;
685
        }
686
      }
687

    
688
      // carriage return ('\r') or line feed ('\n') character
689
      else if (c == '\x0D' || c == '\x0A') {
690
        action = AOS_SHELL_ACTION_EXECUTE;
691
      }
692

    
693
      // ESC key or [ESCAPE] character
694
      else if (key == KEY_ESCAPE || c == '\x1B') {
695
        action = AOS_SHELL_ACTION_ESCSTART;
696
      }
697
    }
698

    
699
    /* handle function */
700
    switch (action) {
701
      case AOS_SHELL_ACTION_READCHAR:
702
      {
703
        // line is full
704
        if (shell->inputdata.lineend + 1 >= shell->linesize) {
705
          _moveCursor(shell, shell->inputdata.cursorpos, shell->inputdata.lineend);
706
          chprintf((BaseSequentialStream*)&shell->stream, "\n\tmaximum line width reached\n");
707
          _printPrompt(shell);
708
          _printLine(shell, 0, shell->inputdata.lineend);
709
          _moveCursor(shell, shell->inputdata.lineend, shell->inputdata.cursorpos);
710
        }
711
        // read character
712
        else {
713
          // clear old line content on first input
714
          if (shell->inputdata.noinput) {
715
            memset(shell->line, '\0', shell->linesize);
716
            shell->inputdata.noinput = false;
717
          }
718
          // overwrite content
719
          if (shell->config & AOS_SHELL_CONFIG_INPUT_OVERWRITE) {
720
            shell->line[shell->inputdata.cursorpos] = c;
721
            ++shell->inputdata.cursorpos;
722
            shell->inputdata.lineend = (shell->inputdata.cursorpos > shell->inputdata.lineend) ? shell->inputdata.cursorpos : shell->inputdata.lineend;
723
            streamPut(&shell->stream, (uint8_t)c);
724
          }
725
          // insert character
726
          else {
727
            memmove(&(shell->line[shell->inputdata.cursorpos+1]), &(shell->line[shell->inputdata.cursorpos]), shell->inputdata.lineend - shell->inputdata.cursorpos);
728
            shell->line[shell->inputdata.cursorpos] = c;
729
            ++shell->inputdata.lineend;
730
            _printLine(shell, shell->inputdata.cursorpos, shell->inputdata.lineend);
731
            ++shell->inputdata.cursorpos;
732
            _moveCursor(shell, shell->inputdata.lineend, shell->inputdata.cursorpos);
733
          }
734
        }
735
        break;
736
      }
737

    
738
      case AOS_SHELL_ACTION_AUTOFILL:
739
      {
740
        const char* fill = shell->line;
741
        size_t cmatch = shell->inputdata.cursorpos;
742
        charmatch_t matchlevel = CHAR_MATCH_NOT;
743
        size_t n;
744
        // iterate through command list
745
        for (aos_shellcommand_t* cmd = shell->commands; cmd != NULL; cmd = cmd->next) {
746
          // compare current match with command
747
          n = cmatch;
748
          charmatch_t mlvl = CHAR_MATCH_NOT;
749
          _strccmp(fill, cmd->name, shell->config & AOS_SHELL_CONFIG_MATCH_CASE, (n == 0) ? NULL : &n, &mlvl);
750
          const int cmp = (n < cmatch) ?
751
                            (n - cmatch) :
752
                            (cmd->name[n] != '\0') ?
753
                              strlen(cmd->name) - n :
754
                              0;
755
          // if an exact match was found
756
          if (cmatch + cmp == shell->inputdata.cursorpos) {
757
            cmatch = shell->inputdata.cursorpos;
758
            fill = cmd->name;
759
            // break the loop only if there are no case mismatches with the input
760
            n = shell->inputdata.cursorpos;
761
            _strccmp(fill, shell->line, false, &n, &mlvl);
762
            if (mlvl == CHAR_MATCH_CASE) {
763
              break;
764
            }
765
          }
766
          // if a not exact match was found
767
          else if (cmatch + cmp > shell->inputdata.cursorpos) {
768
            // if this is the first one
769
            if (fill == shell->line) {
770
              cmatch += cmp;
771
              fill = cmd->name;
772
            }
773
            // if this is a worse one
774
            else if ((cmp < 0) || (cmp == 0 && mlvl == CHAR_MATCH_CASE)) {
775
              cmatch += cmp;
776
            }
777
          }
778
          // non matching commands are ignored
779
          else {}
780
        }
781
        // evaluate if there are case mismatches
782
        n = cmatch;
783
        _strccmp(shell->line, fill, shell->config & AOS_SHELL_CONFIG_MATCH_CASE, &n, &matchlevel);
784
        // print the auto fill if any
785
        if (cmatch > shell->inputdata.cursorpos || (cmatch == shell->inputdata.cursorpos && matchlevel == CHAR_MATCH_NCASE)) {
786
          shell->inputdata.noinput = false;
787
          // limit auto fill so it will not overflow the line width
788
          if (shell->inputdata.lineend + (cmatch - shell->inputdata.cursorpos) > shell->linesize) {
789
            cmatch = shell->linesize - shell->inputdata.lineend + shell->inputdata.cursorpos;
790
          }
791
          // move trailing memory further in the line
792
          memmove(&(shell->line[cmatch]), &(shell->line[shell->inputdata.cursorpos]), shell->inputdata.lineend - shell->inputdata.cursorpos);
793
          shell->inputdata.lineend += cmatch - shell->inputdata.cursorpos;
794
          // if there was no incorrect case when matching
795
          if (matchlevel == CHAR_MATCH_CASE) {
796
            // insert fill command name to line
797
            memcpy(&(shell->line[shell->inputdata.cursorpos]), &(fill[shell->inputdata.cursorpos]), cmatch - shell->inputdata.cursorpos);
798
            // print the output
799
            _printLine(shell, shell->inputdata.cursorpos, shell->inputdata.lineend);
800
          } else {
801
            // overwrite line with fill command name
802
            memcpy(shell->line, fill, cmatch);
803
            // reprint the whole line
804
            _moveCursor(shell, shell->inputdata.cursorpos, 0);
805
            _printLine(shell, 0, shell->inputdata.lineend);
806
          }
807
          // move cursor to the end of the matching sequence
808
          shell->inputdata.cursorpos = cmatch;
809
          _moveCursor(shell, shell->inputdata.lineend, shell->inputdata.cursorpos);
810
        }
811
        break;
812
      }
813

    
814
      case AOS_SHELL_ACTION_SUGGEST:
815
      {
816
        unsigned int matches = 0;
817
        // iterate through command list
818
        for (aos_shellcommand_t* cmd = shell->commands; cmd != NULL; cmd = cmd->next) {
819
          // compare line content with command, excpet if cursorpos=0
820
          size_t i = shell->inputdata.cursorpos;
821
          if (shell->inputdata.cursorpos > 0) {
822
            _strccmp(shell->line, cmd->name, true, &i, NULL);
823
          }
824
          const int cmp = (i < shell->inputdata.cursorpos) ?
825
                            (i - shell->inputdata.cursorpos) :
826
                            (cmd->name[i] != '\0') ?
827
                              strlen(cmd->name) - i :
828
                              0;
829
          // if a match was found
830
          if (cmp > 0) {
831
            // if this is the first one
832
            if (matches == 0) {
833
              _moveCursor(shell, shell->inputdata.cursorpos, shell->inputdata.lineend);
834
              streamPut(&shell->stream, '\n');
835
            }
836
            // print the command
837
            chprintf((BaseSequentialStream*)&shell->stream, "\t%s\n", cmd->name);
838
            ++matches;
839
          }
840
        }
841
        // reprint the prompt and line if any matches have been found
842
        if (matches > 0) {
843
          _printPrompt(shell);
844
          _printLine(shell, 0, shell->inputdata.lineend);
845
          _moveCursor(shell, shell->inputdata.lineend, shell->inputdata.cursorpos);
846
          shell->inputdata.noinput = false;
847
        }
848
        break;
849
      }
850

    
851
      case AOS_SHELL_ACTION_INSERTTOGGLE:
852
      {
853
        if (shell->config & AOS_SHELL_CONFIG_INPUT_OVERWRITE) {
854
          shell->config &= ~AOS_SHELL_CONFIG_INPUT_OVERWRITE;
855
        } else {
856
          shell->config |= AOS_SHELL_CONFIG_INPUT_OVERWRITE;
857
        }
858
        break;
859
      }
860

    
861
      case AOS_SHELL_ACTION_DELETEFORWARD:
862
      {
863
        --shell->inputdata.lineend;
864
        memmove(&(shell->line[shell->inputdata.cursorpos]), &(shell->line[shell->inputdata.cursorpos+1]), shell->inputdata.lineend - shell->inputdata.cursorpos);
865
        _printLine(shell, shell->inputdata.cursorpos, shell->inputdata.lineend);
866
        streamPut(&shell->stream, ' ');
867
        _moveCursor(shell, shell->inputdata.lineend + 1, shell->inputdata.cursorpos);
868
        break;
869
      }
870

    
871
      case AOS_SHELL_ACTION_DELETEBACKWARD:
872
      {
873
        --shell->inputdata.cursorpos;
874
        memmove(&(shell->line[shell->inputdata.cursorpos]), &(shell->line[shell->inputdata.cursorpos+1]), shell->inputdata.lineend - shell->inputdata.cursorpos);
875
        --shell->inputdata.lineend;
876
        shell->line[shell->inputdata.lineend] = '\0';
877
        _moveCursor(shell, shell->inputdata.cursorpos + 1, shell->inputdata.cursorpos);
878
        _printLine(shell, shell->inputdata.cursorpos, shell->inputdata.lineend);
879
        streamPut(&shell->stream, ' ');
880
        _moveCursor(shell, shell->inputdata.lineend+1, shell->inputdata.cursorpos);
881
        break;
882
      }
883

    
884
      case AOS_SHELL_ACTION_RECALLLAST:
885
      {
886
        // replace any intermediate NUL bytes with spaces
887
        shell->inputdata.lineend = 0;
888
        size_t nul_start = 0;
889
        size_t nul_end = 0;
890
        // search line for a NUL byte
891
        while (nul_start < shell->linesize) {
892
          if (shell->line[nul_start] == '\0') {
893
            nul_end = nul_start + 1;
894
            // keep searcjing for a byte that is not NUL
895
            while (nul_end < shell->linesize) {
896
              if (shell->line[nul_end] != '\0') {
897
                // an intermediate NUL sequence was found
898
                memset(&(shell->line[nul_start]), ' ', nul_end - nul_start);
899
                shell->inputdata.lineend = nul_end + 1;
900
                break;
901
              } else {
902
                ++nul_end;
903
              }
904
            }
905
            nul_start = nul_end + 1;
906
          } else {
907
            ++shell->inputdata.lineend;
908
            ++nul_start;
909
          }
910
        }
911
        shell->inputdata.cursorpos = shell->inputdata.lineend;
912
        // print the line
913
        shell->inputdata.noinput = _printLine(shell, 0, shell->inputdata.lineend) == 0;
914
        break;
915
      }
916

    
917
      case AOS_SHELL_ACTION_CLEAR:
918
      {
919
        // clear output
920
        _moveCursor(shell, shell->inputdata.cursorpos, 0);
921
        for (shell->inputdata.cursorpos = 0; shell->inputdata.cursorpos < shell->inputdata.lineend; ++shell->inputdata.cursorpos) {
922
          streamPut(&shell->stream, ' ');
923
        }
924
        _moveCursor(shell, shell->inputdata.lineend, 0);
925
        shell->inputdata.cursorpos = 0;
926
        shell->inputdata.lineend = 0;
927
        shell->inputdata.noinput = true;
928
        break;
929
      }
930

    
931
      case AOS_SHELL_ACTION_CURSOR2START:
932
      {
933
        _moveCursor(shell, shell->inputdata.cursorpos, 0);
934
        shell->inputdata.cursorpos = 0;
935
        break;
936
      }
937

    
938
      case AOS_SHELL_ACTION_CURSOR2END:
939
      {
940
        _moveCursor(shell, shell->inputdata.cursorpos, shell->inputdata.lineend);
941
        shell->inputdata.cursorpos = shell->inputdata.lineend;
942
        break;
943
      }
944

    
945
      case AOS_SHELL_ACTION_CURSORLEFT:
946
      {
947
        _moveCursor(shell, shell->inputdata.cursorpos, shell->inputdata.cursorpos-1);
948
        --shell->inputdata.cursorpos;
949
        break;
950
      }
951

    
952
      case AOS_SHELL_ACTION_CURSORRIGHT:
953
      {
954
        _moveCursor(shell, shell->inputdata.cursorpos, shell->inputdata.cursorpos+1);
955
        ++shell->inputdata.cursorpos;
956
        break;
957
      }
958

    
959
      case AOS_SHELL_ACTION_EXECUTE:
960
      {
961
        streamPut(&shell->stream, '\n');
962
        // set the number of read bytes and return
963
        if (!shell->inputdata.noinput) {
964
          *n = shell->linesize - shell->inputdata.lineend;
965
          // fill the remainder of the line with NUL bytes
966
          memset(&(shell->line[shell->inputdata.lineend]), '\0', *n);
967
          // reset static variables
968
          shell->inputdata.noinput = true;
969
        }
970
        return AOS_SUCCESS;
971
        break;
972
      }
973

    
974
      case AOS_SHELL_ACTION_ESCSTART:
975
      {
976
        shell->inputdata.escseq[0] = c;
977
        ++shell->inputdata.escp;
978
        break;
979
      }
980

    
981
      case AOS_SHELL_ACTION_NONE:
982
      default:
983
      {
984
        // do nothing (ignore input) and read next byte
985
        continue;
986
        break;
987
      }
988
    } /* end of switch */
989

    
990
    shell->inputdata.lastaction = action;
991
  } /* end of while */
992

    
993
  // no more data could be read from the channel
994
  return AOS_WARNING;
995
}
996

    
997
/**
998
 * @brief   Parses the content of the input buffer (line) to separate arguments.
999
 *
1000
 * @param[in] shell   Pointer to the shell object.
1001
 *
1002
 * @return            Number of arguments found.
1003
 */
1004
static size_t _parseArguments(aos_shell_t* shell)
1005
{
1006
  aosDbgCheck(shell != NULL);
1007

    
1008
  /*
1009
   * States for a very small FSM.
1010
   */
1011
  typedef enum {
1012
    START,
1013
    SPACE,
1014
    TEXT,
1015
    END,
1016
  } state_t;
1017

    
1018
  // local variables
1019
  state_t state = START;
1020
  size_t arg = 0;
1021

    
1022
  // iterate through the line
1023
  for (char* c = shell->line; c < shell->line + shell->linesize; ++c) {
1024
    // terminate at first NUL byte
1025
    if (*c == '\0') {
1026
      state = END;
1027
      break;
1028
    }
1029
    // spaces become NUL bytes
1030
    else if (*c == ' ') {
1031
      *c = '\0';
1032
      state = SPACE;
1033
    }
1034
    // handle non-NUL bytes
1035
    else {
1036
      switch (state) {
1037
        case START:
1038
        case SPACE:
1039
          // ignore too many arguments
1040
          if (arg < shell->arglistsize) {
1041
            shell->arglist[arg] = c;
1042
          }
1043
          ++arg;
1044
          break;
1045
        case TEXT:
1046
        case END:
1047
        default:
1048
          break;
1049
      }
1050
      state = TEXT;
1051
    }
1052
  }
1053

    
1054
  // set all remaining argument pointers to NULL
1055
  for (size_t a = arg; a < shell->arglistsize; ++a) {
1056
    shell->arglist[a] = NULL;
1057
  }
1058

    
1059
  return arg;
1060
}
1061

    
1062
/**
1063
 * @brief   Initializes a shell object with the specified parameters.
1064
 *
1065
 * @param[in] shell         Pointer to the shell object.
1066
 * @param[in] stream        I/O stream to use.
1067
 * @param[in] prompt        Prompt line to print (NULL = use default prompt).
1068
 * @param[in] line          Pointer to the input buffer.
1069
 * @param[in] linesize      Size of the input buffer.
1070
 * @param[in] arglist       Pointer to the argument buffer.
1071
 * @param[in] arglistsize   Size of te argument buffer.
1072
 */
1073
void aosShellInit(aos_shell_t* shell, event_source_t* oseventsource,  const char* prompt, char* line, size_t linesize, char** arglist, size_t arglistsize)
1074
{
1075
  aosDbgCheck(shell != NULL);
1076
  aosDbgCheck(oseventsource != NULL);
1077
  aosDbgCheck(line != NULL);
1078
  aosDbgCheck(arglist != NULL);
1079

    
1080
  // set parameters
1081
  shell->thread = NULL;
1082
  chEvtObjectInit(&shell->eventSource);
1083
  shell->os.eventSource = oseventsource;
1084
  aosShellStreamInit(&shell->stream);
1085
  shell->prompt = prompt;
1086
  shell->commands = NULL;
1087
  shell->execstatus.command = NULL;
1088
  shell->execstatus.retval = 0;
1089
  shell->line = line;
1090
  shell->linesize = linesize;
1091
  shell->inputdata.lastaction = AOS_SHELL_ACTION_NONE;
1092
  shell->inputdata.escp = 0;
1093
  memset(shell->inputdata.escseq, '\0', sizeof(shell->inputdata.escseq)*sizeof(shell->inputdata.escseq[0]));
1094
  shell->inputdata.cursorpos = 0;
1095
  shell->inputdata.lineend = 0;
1096
  shell->inputdata.noinput = true;
1097
  shell->arglist = arglist;
1098
  shell->arglistsize = arglistsize;
1099
  shell->config = 0x00;
1100

    
1101
  // initialize arrays
1102
  memset(shell->line, '\0', shell->linesize);
1103
  for (size_t a = 0; a < shell->arglistsize; ++a) {
1104
    shell->arglist[a] = NULL;
1105
  }
1106

    
1107
  return;
1108
}
1109

    
1110
/**
1111
 * @brief   Initialize an AosShellStream object.
1112
 *
1113
 * @param[in] stream  The AosShellStrem to initialize.
1114
 */
1115
void aosShellStreamInit(AosShellStream* stream)
1116
{
1117
  aosDbgCheck(stream != NULL);
1118

    
1119
  stream->vmt = &_streamvmt;
1120
  stream->channel = NULL;
1121

    
1122
  return;
1123
}
1124

    
1125
/**
1126
 * @brief   Initialize an AosShellChannel object with the specified parameters.
1127
 *
1128
 * @param[in] channel       The AosShellChannel to initialize.
1129
 * @param[in] asyncchannel  An BaseAsynchronousChannel this AosShellChannel is associated with.
1130
 */
1131
void aosShellChannelInit(AosShellChannel* channel, BaseAsynchronousChannel* asyncchannel)
1132
{
1133
  aosDbgCheck(channel != NULL);
1134
  aosDbgCheck(asyncchannel != NULL);
1135

    
1136
  channel->vmt = &_channelvmt;
1137
  channel->asyncchannel = asyncchannel;
1138
  channel->listener.wflags = 0;
1139
  channel->next = NULL;
1140
  channel->flags = 0;
1141

    
1142
  return;
1143
}
1144

    
1145
/**
1146
 * @brief   Inserts a command to the shells list of commands.
1147
 *
1148
 * @param[in] shell   Pointer to the shell object.
1149
 * @param[in] cmd     Pointer to the command to add.
1150
 *
1151
 * @return            A status value.
1152
 * @retval AOS_SUCCESS  The command was added successfully.
1153
 * @retval AOS_ERROR    Another command with identical name already exists.
1154
 */
1155
aos_status_t aosShellAddCommand(aos_shell_t *shell, aos_shellcommand_t *cmd)
1156
{
1157
  aosDbgCheck(shell != NULL);
1158
  aosDbgCheck(cmd != NULL);
1159
  aosDbgCheck(cmd->name != NULL && strlen(cmd->name) > 0 && strchr(cmd->name, ' ') == NULL && strchr(cmd->name, '\t') == NULL);
1160
  aosDbgCheck(cmd->callback != NULL);
1161
  aosDbgCheck(cmd->next == NULL);
1162

    
1163
  aos_shellcommand_t* prev = NULL;
1164
  aos_shellcommand_t** curr = &(shell->commands);
1165

    
1166
  // insert the command to the list wrt lexographical order (exception: lower case characters preceed upper their uppercase counterparts)
1167
  while (*curr != NULL) {
1168
    // iterate through the list as long as the command names are 'smaller'
1169
    const int cmp = _strccmp((*curr)->name, cmd->name, true, NULL, NULL);
1170
    if (cmp < 0) {
1171
      prev = *curr;
1172
      curr = &((*curr)->next);
1173
      continue;
1174
    }
1175
    // error if the command already exists
1176
    else if (cmp == 0) {
1177
      return AOS_ERROR;
1178
    }
1179
    // insert the command as soon as a 'larger' name was found
1180
    else /* if (cmpval > 0) */ {
1181
      cmd->next = *curr;
1182
      // special case: the first command is larger
1183
      if (prev == NULL) {
1184
        shell->commands = cmd;
1185
      } else {
1186
        prev->next = cmd;
1187
      }
1188
      return AOS_SUCCESS;
1189
    }
1190
  }
1191
  // the end of the list has been reached
1192

    
1193
  // append the command
1194
  *curr = cmd;
1195
  return AOS_SUCCESS;
1196
}
1197

    
1198
/**
1199
 * @brief   Removes a command from the shells list of commands.
1200
 *
1201
 * @param[in] shell     Pointer to the shell object.
1202
 * @param[in] cmd       Name of the command to removde.
1203
 * @param[out] removed  Optional pointer to the command that was removed.
1204
 *
1205
 * @return              A status value.
1206
 * @retval AOS_SUCCESS  The command was removed successfully.
1207
 * @retval AOS_ERROR    The command name was not found.
1208
 */
1209
aos_status_t aosShellRemoveCommand(aos_shell_t *shell, char *cmd, aos_shellcommand_t **removed)
1210
{
1211
  aosDbgCheck(shell != NULL);
1212
  aosDbgCheck(cmd != NULL && strlen(cmd) > 0);
1213

    
1214
  aos_shellcommand_t* prev = NULL;
1215
  aos_shellcommand_t** curr = &(shell->commands);
1216

    
1217
  // iterate through the list and seach for the specified command name
1218
  while (curr != NULL) {
1219
    const int cmpval = strcmp((*curr)->name, cmd);
1220
    // iterate through the list as long as the command names are 'smaller'
1221
    if (cmpval < 0) {
1222
      prev = *curr;
1223
      curr = &((*curr)->next);
1224
      continue;
1225
    }
1226
    // remove the command when found
1227
    else if (cmpval == 0) {
1228
      // special case: the first command matches
1229
      if (prev == NULL) {
1230
        shell->commands = (*curr)->next;
1231
      } else {
1232
        prev->next = (*curr)->next;
1233
      }
1234
      (*curr)->next = NULL;
1235
      // set the optional output argument
1236
      if (removed != NULL) {
1237
        *removed = *curr;
1238
      }
1239
      return AOS_SUCCESS;
1240
    }
1241
    // break the loop if the command names are 'larger'
1242
    else /* if (cmpval > 0) */ {
1243
      break;
1244
    }
1245
  }
1246

    
1247
  // if the command was not found, return an error
1248
  return AOS_ERROR;
1249
}
1250

    
1251
/**
1252
 * @brief   Add a channel to a AosShellStream.
1253
 *
1254
 * @param[in] stream    The AosShellStream to extend.
1255
 * @param[in] channel   The channel to be added to the stream.
1256
 */
1257
void aosShellStreamAddChannel(AosShellStream* stream, AosShellChannel* channel)
1258
{
1259
  aosDbgCheck(stream != NULL);
1260
  aosDbgCheck(channel != NULL && channel->asyncchannel != NULL && channel->next == NULL && (channel->flags & AOS_SHELLCHANNEL_ATTACHED) == 0);
1261

    
1262
  // prepend the new channel
1263
  chSysLock();
1264
  channel->flags |= AOS_SHELLCHANNEL_ATTACHED;
1265
  channel->next = stream->channel;
1266
  stream->channel = channel;
1267
  chSysUnlock();
1268

    
1269
  return;
1270
}
1271

    
1272
/**
1273
 * @brief   Remove a channel from an AosShellStream.
1274
 *
1275
 * @param[in] stream    The AosShellStream to modify.
1276
 * @param[in] channel   The channel to remove.
1277
 * @return
1278
 */
1279
aos_status_t aosShellStreamRemoveChannel(AosShellStream* stream, AosShellChannel* channel)
1280
{
1281
  aosDbgCheck(stream != NULL);
1282
  aosDbgCheck(channel != NULL && channel->asyncchannel != NULL && channel->flags & AOS_SHELLCHANNEL_ATTACHED);
1283

    
1284
  // local varibales
1285
  AosShellChannel* prev = NULL;
1286
  AosShellChannel* curr = stream->channel;
1287

    
1288
  // iterate through the list and search for the specified channel
1289
  while (curr != NULL) {
1290
    // if the channel was found
1291
    if (curr == channel) {
1292
      chSysLock();
1293
      // special case: the first channel matches (prev is NULL)
1294
      if (prev == NULL) {
1295
        stream->channel = curr->next;
1296
      } else {
1297
        prev->next = channel->next;
1298
      }
1299
      curr->next = NULL;
1300
      curr->flags &= ~AOS_SHELLCHANNEL_ATTACHED;
1301
      chSysUnlock();
1302
      return AOS_SUCCESS;
1303
    }
1304
  }
1305

    
1306
  // if the channel was not found, return an error
1307
  return AOS_ERROR;
1308
}
1309

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

    
1319
  chSysLock();
1320
  channel->listener.wflags |= CHN_INPUT_AVAILABLE;
1321
  channel->flags |= AOS_SHELLCHANNEL_INPUT_ENABLED;
1322
  chSysUnlock();
1323

    
1324
  return;
1325
}
1326

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

    
1336
  chSysLock();
1337
  channel->listener.wflags &= ~CHN_INPUT_AVAILABLE;
1338
  channel->flags &= ~AOS_SHELLCHANNEL_INPUT_ENABLED;
1339
  chSysUnlock();
1340

    
1341
  return;
1342
}
1343

    
1344
/**
1345
 * @brief   Enable a AosSheööChannel as output.
1346
 *
1347
 * @param[in] channel   The channel to enable as output.
1348
 */
1349
void aosShellChannelOutputEnable(AosShellChannel* channel)
1350
{
1351
  aosDbgCheck(channel != NULL && channel->asyncchannel != NULL);
1352

    
1353
  channel->flags |= AOS_SHELLCHANNEL_OUTPUT_ENABLED;
1354

    
1355
  return;
1356
}
1357

    
1358
/**
1359
 * @brief   Disable a AosSheööChannel as output.
1360
 *
1361
 * @param[in] channel   The channel to disable as output.
1362
 */
1363
void aosShellChannelOutputDisable(AosShellChannel* channel)
1364
{
1365
  aosDbgCheck(channel != NULL && channel->asyncchannel != NULL);
1366

    
1367
  channel->flags &= ~AOS_SHELLCHANNEL_OUTPUT_ENABLED;
1368

    
1369
  return;
1370
}
1371

    
1372
/**
1373
 * @brief   Thread main function.
1374
 *
1375
 * @param[in] aosShellThread    Name of the function;
1376
 * @param[in] shell             Pointer to the shell object.
1377
 */
1378
THD_FUNCTION(aosShellThread, shell)
1379
{
1380
  aosDbgCheck(shell != NULL);
1381

    
1382
  // local variables
1383
  eventmask_t eventmask;
1384
  eventflags_t eventflags;
1385
  AosShellChannel* channel;
1386
  aos_status_t readeval;
1387
  size_t nchars = 0;
1388
  size_t nargs = 0;
1389
  aos_shellcommand_t* cmd;
1390

    
1391

    
1392
  // register OS related events
1393
  chEvtRegisterMask(((aos_shell_t*)shell)->os.eventSource, &(((aos_shell_t*)shell)->os.eventListener), AOS_SHELL_EVENTMASK_OS);
1394
  // register events to all input channels
1395
  for (channel = ((aos_shell_t*)shell)->stream.channel; channel != NULL; channel = channel->next) {
1396
    chEvtRegisterMaskWithFlags(&(channel->asyncchannel->event), &(channel->listener), AOS_SHELL_EVENTMASK_INPUT, channel->listener.wflags);
1397
  }
1398

    
1399
  // fire start event
1400
  chEvtBroadcastFlags(&(((aos_shell_t*)shell)->eventSource), AOS_SHELL_EVTFLAG_START);
1401

    
1402
  // print the prompt for the first time
1403
  _printPrompt((aos_shell_t*)shell);
1404

    
1405
  // enter thread loop
1406
  while (!chThdShouldTerminateX()) {
1407
    // wait for event and handle it accordingly
1408
    eventmask = chEvtWaitOne(ALL_EVENTS);
1409

    
1410
    // handle event
1411
    switch (eventmask) {
1412

    
1413
      // OS related events
1414
      case AOS_SHELL_EVENTMASK_OS:
1415
      {
1416
        eventflags = chEvtGetAndClearFlags(&((aos_shell_t*)shell)->os.eventListener);
1417
        // handle shutdown/restart events
1418
        if (eventflags & AOS_SYSTEM_EVENTFLAGS_SHUTDOWN) {
1419
          chThdTerminate(((aos_shell_t*)shell)->thread);
1420
        } else {
1421
          // print an error message
1422
          chprintf((BaseSequentialStream*)&((aos_shell_t*)shell)->stream, "\nERROR: unknown OS event received (0x%08X)\n", eventflags);
1423
        }
1424
        break;
1425
      }
1426

    
1427
      // input events
1428
      case AOS_SHELL_EVENTMASK_INPUT:
1429
      {
1430
        // check and handle all channels
1431
        channel = ((aos_shell_t*)shell)->stream.channel;
1432
        while (channel != NULL) {
1433
          eventflags = chEvtGetAndClearFlags(&channel->listener);
1434
          // if there is new input
1435
          if (eventflags & CHN_INPUT_AVAILABLE) {
1436
            // read input from channel
1437
            readeval = _readChannel((aos_shell_t*)shell, channel, &nchars);
1438
            // parse input line to argument list only if the input shall be executed
1439
            nargs = (readeval == AOS_SUCCESS && nchars > 0) ? _parseArguments((aos_shell_t*)shell) : 0;
1440
            // check number of arguments
1441
            if (nargs > ((aos_shell_t*)shell)->arglistsize) {
1442
              // error too many arguments
1443
              chprintf((BaseSequentialStream*)&((aos_shell_t*)shell)->stream, "\ttoo many arguments\n");
1444
            } else if (nargs > 0) {
1445
              // search command list for arg[0] and execute callback
1446
              cmd = ((aos_shell_t*)shell)->commands;
1447
              while (cmd != NULL) {
1448
                if (strcmp(((aos_shell_t*)shell)->arglist[0], cmd->name) == 0) {
1449
                  ((aos_shell_t*)shell)->execstatus.command = cmd;
1450
                  chEvtBroadcastFlags(&(((aos_shell_t*)shell)->eventSource), AOS_SHELL_EVTFLAG_EXEC);
1451
                  ((aos_shell_t*)shell)->execstatus.retval = cmd->callback((BaseSequentialStream*)&((aos_shell_t*)shell)->stream, nargs, ((aos_shell_t*)shell)->arglist);
1452
                  chEvtBroadcastFlags(&(((aos_shell_t*)shell)->eventSource), AOS_SHELL_EVTFLAG_DONE);
1453
                  // notify if the command was not successful
1454
                  if (((aos_shell_t*)shell)->execstatus.retval != 0) {
1455
                    chprintf((BaseSequentialStream*)&((aos_shell_t*)shell)->stream, "command returned exit status %d\n", ((aos_shell_t*)shell)->execstatus.retval);
1456
                  }
1457
                  break;
1458
                }
1459
                cmd = cmd->next;
1460
              } /* end of while */
1461

    
1462
              // if no matching command was found, print an error
1463
              if (cmd == NULL) {
1464
                chprintf((BaseSequentialStream*)&((aos_shell_t*)shell)->stream, "%s: command not found\n", ((aos_shell_t*)shell)->arglist[0]);
1465
              }
1466
            }
1467

    
1468
            // reset some internal variables and eprint a new prompt
1469
            if (readeval == AOS_SUCCESS && !chThdShouldTerminateX()) {
1470
              ((aos_shell_t*)shell)->inputdata.cursorpos = 0;
1471
              ((aos_shell_t*)shell)->inputdata.lineend = 0;
1472
              _printPrompt((aos_shell_t*)shell);
1473
            }
1474
          }
1475

    
1476
          // iterate to next channel
1477
          channel = channel->next;
1478
        }
1479
        break;
1480
      }
1481

    
1482
      // other events
1483
      default:
1484
      {
1485
        // print an error message
1486
        chprintf((BaseSequentialStream*)&((aos_shell_t*)shell)->stream, "\nERROR: unknown event received (0x%08X)\n", eventmask);
1487
        break;
1488
      }
1489

    
1490
    } /* end of switch */
1491

    
1492
  } /* end of while */
1493

    
1494
  // fire event and exit the thread
1495
  chSysLock();
1496
  chEvtBroadcastFlagsI(&(((aos_shell_t*)shell)->eventSource), AOS_SHELL_EVTFLAG_EXIT);
1497
  chThdExitS(MSG_OK);
1498
  // no chSysUnlock() required since the thread has been terminated an all waiting threads have been woken up
1499
}
1500

    
1501
#endif /* AMIROOS_CFG_SHELL_ENABLE == true */