Statistics
| Branch: | Tag: | Revision:

amiro-os / core / src / aos_shell.c @ 960338cc

History | View | Annotate | Download (46.846 KB)

1 e545e620 Thomas Schöpping
/*
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 53710ca3 Marc Rothmann
/**
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 e545e620 Thomas Schöpping
#include <aos_shell.h>
29
30 ba516b61 Thomas Schöpping
#if (AMIROOS_CFG_SHELL_ENABLE == true)
31 e545e620 Thomas Schöpping
#include <aos_debug.h>
32
#include <aos_time.h>
33
#include <aos_system.h>
34
#include <string.h>
35 ba516b61 Thomas Schöpping
36
/**
37
 * @brief   Event mask to be set on OS related events.
38
 */
39
#define AOS_SHELL_EVENTMASK_OS                  EVENT_MASK(0)
40
41
/**
42
 * @brief   Event mask to be set on a input event.
43
 */
44
#define AOS_SHELL_EVENTMASK_INPUT               EVENT_MASK(1)
45
46
/**
47
 * @brief   Implementation of the BaseAsynchronous write() method (inherited from BaseSequentialStream).
48
 */
49
static size_t _channelwrite(void *instance, const uint8_t *bp, size_t n)
50
{
51
  if (((AosShellChannel*)instance)->flags & AOS_SHELLCHANNEL_OUTPUT_ENABLED) {
52 dd8738ea Thomas Schöpping
    return streamWrite(((AosShellChannel*)instance)->asyncchannel, bp, n);
53 ba516b61 Thomas Schöpping
  } else {
54
    return 0;
55
  }
56
}
57
58
/**
59
 * @brief   Implementation of the BaseAsynchronous read() method (inherited from BaseSequentialStream).
60
 */
61
static size_t _channelread(void *instance, uint8_t *bp, size_t n)
62
{
63 dd8738ea Thomas Schöpping
  if (((AosShellChannel*)instance)->flags & AOS_SHELLCHANNEL_INPUT_ENABLED) {
64
    return streamRead(((AosShellChannel*)instance)->asyncchannel, bp, n);
65
  } else {
66
    return 0;
67
  }
68 ba516b61 Thomas Schöpping
}
69
70
/**
71
 * @brief   Implementation of the BaseAsynchronous put() method (inherited from BaseSequentialStream).
72
 */
73
static msg_t _channelput(void *instance, uint8_t b)
74
{
75
  if (((AosShellChannel*)instance)->flags & AOS_SHELLCHANNEL_OUTPUT_ENABLED) {
76 dd8738ea Thomas Schöpping
    return streamPut(((AosShellChannel*)instance)->asyncchannel, b);
77 ba516b61 Thomas Schöpping
  } else {
78
    return MSG_RESET;
79
  }
80
}
81
82
/**
83
 * @brief   Implementation of the BaseAsynchronous get() method (inherited from BaseSequentialStream).
84
 */
85
static msg_t _channelget(void *instance)
86
{
87 dd8738ea Thomas Schöpping
  if (((AosShellChannel*)instance)->flags & AOS_SHELLCHANNEL_INPUT_ENABLED) {
88
    return streamGet(((AosShellChannel*)instance)->asyncchannel);
89
  } else {
90
    return MSG_RESET;
91
  }
92 ba516b61 Thomas Schöpping
}
93
94
/**
95
 * @brief   Implementation of the BaseAsynchronous putt() method.
96
 */
97 2c99037f Marc Rothmann
static msg_t _channelputt(void *instance, uint8_t b, sysinterval_t time)
98 ba516b61 Thomas Schöpping
{
99
  if (((AosShellChannel*)instance)->flags & AOS_SHELLCHANNEL_OUTPUT_ENABLED) {
100 dd8738ea Thomas Schöpping
    return chnPutTimeout(((AosShellChannel*)instance)->asyncchannel, b, time);
101 ba516b61 Thomas Schöpping
  } else {
102
    return MSG_RESET;
103
  }
104
}
105
106
/**
107
 * @brief   Implementation of the BaseAsynchronous gett() method.
108
 */
109 2c99037f Marc Rothmann
static msg_t _channelgett(void *instance, sysinterval_t time)
110 ba516b61 Thomas Schöpping
{
111 dd8738ea Thomas Schöpping
  if (((AosShellChannel*)instance)->flags & AOS_SHELLCHANNEL_INPUT_ENABLED) {
112
    return chnGetTimeout(((AosShellChannel*)instance)->asyncchannel, time);
113
  } else {
114
    return MSG_RESET;
115
  }
116 ba516b61 Thomas Schöpping
}
117
118
/**
119
 * @brief   Implementation of the BaseAsynchronous writet() method.
120
 */
121 2c99037f Marc Rothmann
static size_t _channelwritet(void *instance, const uint8_t *bp, size_t n, sysinterval_t time)
122 ba516b61 Thomas Schöpping
{
123
  if (((AosShellChannel*)instance)->flags & AOS_SHELLCHANNEL_OUTPUT_ENABLED) {
124 dd8738ea Thomas Schöpping
    return chnWriteTimeout(((AosShellChannel*)instance)->asyncchannel, bp, n, time);
125 ba516b61 Thomas Schöpping
  } else {
126
    return 0;
127
  }
128
}
129
130
/**
131
 * @brief   Implementation of the BaseAsynchronous readt() method.
132
 */
133 2c99037f Marc Rothmann
static size_t _channelreadt(void *instance, uint8_t *bp, size_t n, sysinterval_t time)
134 ba516b61 Thomas Schöpping
{
135 dd8738ea Thomas Schöpping
  if (((AosShellChannel*)instance)->flags & AOS_SHELLCHANNEL_INPUT_ENABLED) {
136
    return chnReadTimeout(((AosShellChannel*)instance)->asyncchannel, bp, n, time);
137
  } else {
138
    return 0;
139
  }
140 ba516b61 Thomas Schöpping
}
141
142 2c99037f Marc Rothmann
/**
143
 * @brief   Implementation of the BaseAsynchronousChannel ctl() method.
144
 */
145
static msg_t _channelctl(void *instance, unsigned int operation, void *arg) {
146
  (void) instance;
147
148
  switch (operation) {
149
  case CHN_CTL_NOP:
150
    osalDbgCheck(arg == NULL);
151
    break;
152
  case CHN_CTL_INVALID:
153
    osalDbgAssert(false, "invalid CTL operation");
154
    break;
155
  default:
156
    break;
157
  }
158
  return MSG_OK;
159
}
160
161 ba516b61 Thomas Schöpping
static const struct AosShellChannelVMT _channelvmt = {
162 0128be0f Marc Rothmann
  (size_t) 0,
163 ba516b61 Thomas Schöpping
  _channelwrite,
164
  _channelread,
165
  _channelput,
166
  _channelget,
167
  _channelputt,
168
  _channelgett,
169
  _channelwritet,
170
  _channelreadt,
171 2c99037f Marc Rothmann
  _channelctl,
172 ba516b61 Thomas Schöpping
};
173
174
static size_t _streamwrite(void *instance, const uint8_t *bp, size_t n)
175
{
176
  aosDbgCheck(instance != NULL);
177
178
  // local variables
179
  AosShellChannel* channel = ((AosShellStream*)instance)->channel;
180
  size_t bytes;
181
  size_t maxbytes = 0;
182
183
  // iterate through the list of channels
184
  while (channel != NULL) {
185
    bytes = streamWrite(channel, bp, n);
186
    maxbytes = (bytes > maxbytes) ? bytes : maxbytes;
187
    channel = channel->next;
188
  }
189
190
  return maxbytes;
191
}
192
193
static size_t _stremread(void *instance, uint8_t *bp, size_t n)
194
{
195
  (void)instance;
196
  (void)bp;
197
  (void)n;
198
199
  return 0;
200
}
201
202
static msg_t _streamput(void *instance, uint8_t b)
203
{
204
  aosDbgCheck(instance != NULL);
205
206
  // local variables
207
  AosShellChannel* channel = ((AosShellStream*)instance)->channel;
208 dd8738ea Thomas Schöpping
  msg_t ret = MSG_OK;
209 ba516b61 Thomas Schöpping
210
  // iterate through the list of channels
211
  while (channel != NULL) {
212 dd8738ea Thomas Schöpping
    msg_t ret_ = streamPut(channel, b);
213
    ret = (ret_ < ret) ? ret_ : ret;
214 ba516b61 Thomas Schöpping
    channel = channel->next;
215
  }
216
217 dd8738ea Thomas Schöpping
  return ret;
218 ba516b61 Thomas Schöpping
}
219
220
static msg_t _streamget(void *instance)
221
{
222
  (void)instance;
223
224
  return 0;
225
}
226
227
static const struct AosShellStreamVMT _streamvmt = {
228 0128be0f Marc Rothmann
  (size_t) 0,
229 ba516b61 Thomas Schöpping
  _streamwrite,
230
  _stremread,
231
  _streamput,
232
  _streamget,
233
};
234
235 e545e620 Thomas Schöpping
/**
236
 * @brief   Enumerator of special keyboard keys.
237
 */
238
typedef enum special_key {
239
  KEY_UNKNOWN,      /**< any/unknow key */
240
  KEY_AMBIGUOUS,    /**< key is ambiguous */
241
  KEY_TAB,          /**< tabulator key */
242
  KEY_ESCAPE,       /**< escape key */
243
  KEY_BACKSPACE,    /**< backspace key */
244
  KEY_INSERT,       /**< insert key */
245
  KEY_DELETE,       /**< delete key */
246
  KEY_HOME,         /**< home key */
247
  KEY_END,          /**< end key */
248
  KEY_PAGE_UP,      /**< page up key */
249
  KEY_PAGE_DOWN,    /**< page down key */
250
  KEY_ARROW_UP,     /**< arrow up key */
251
  KEY_ARROW_DOWN,   /**< arrow down key */
252
  KEY_ARROW_LEFT,   /**< arrow left key */
253
  KEY_ARROW_RIGHT,  /**< arrow right key */
254
} special_key_t;
255
256
/**
257
 * @brief   Enumerator for case (in)sensitive character matching.
258
 */
259
typedef enum charmatch {
260
  CHAR_MATCH_NOT    = 0,  /**< Characters do not match at all. */
261
  CHAR_MATCH_NCASE  = 1,  /**< Characters would match case insensitive. */
262
  CHAR_MATCH_CASE   = 2,  /**< Characters do match with case. */
263
} charmatch_t;
264
265
/**
266
 * @brief   Print the shell prompt
267
 * @details Depending on the configuration flags, the system uptime is printed before the prompt string.
268
 *
269
 * @param[in] shell   Pointer to the shell object.
270
 */
271
static void _printPrompt(aos_shell_t* shell)
272
{
273 27d0378b Simon Welzel
/** commented out by simon welzel
274 e545e620 Thomas Schöpping
  aosDbgCheck(shell != NULL);
275

276 8399aeae Thomas Schöpping
  // print some time informattion before prompt if configured
277
  if (shell->config & (AOS_SHELL_CONFIG_PROMPT_UPTIME | AOS_SHELL_CONFIG_PROMPT_DATETIME)) {
278
    // printf the system uptime
279
    if ((shell->config & (AOS_SHELL_CONFIG_PROMPT_UPTIME | AOS_SHELL_CONFIG_PROMPT_DATETIME)) == AOS_SHELL_CONFIG_PROMPT_UPTIME) {
280
      // get current system uptime
281
      aos_timestamp_t uptime;
282
      aosSysGetUptime(&uptime);
283

284
      chprintf((BaseSequentialStream*)&shell->stream, "[%01u:%02u:%02u:%02u:%03u:%03u] ",
285
               (uint32_t)(uptime / MICROSECONDS_PER_DAY),
286
               (uint8_t)(uptime % MICROSECONDS_PER_DAY / MICROSECONDS_PER_HOUR),
287
               (uint8_t)(uptime % MICROSECONDS_PER_HOUR / MICROSECONDS_PER_MINUTE),
288
               (uint8_t)(uptime % MICROSECONDS_PER_MINUTE / MICROSECONDS_PER_SECOND),
289
               (uint16_t)(uptime % MICROSECONDS_PER_SECOND / MICROSECONDS_PER_MILLISECOND),
290
               (uint16_t)(uptime % MICROSECONDS_PER_MILLISECOND / MICROSECONDS_PER_MICROSECOND));
291
    }
292
    else if ((shell->config & (AOS_SHELL_CONFIG_PROMPT_UPTIME | AOS_SHELL_CONFIG_PROMPT_DATETIME)) == AOS_SHELL_CONFIG_PROMPT_DATETIME) {
293
      // get current RTC time
294
      struct tm dt;
295
      aosSysGetDateTime(&dt);
296
      chprintf((BaseSequentialStream*)&shell->stream, "[%02u-%02u-%04u|%02u:%02u:%02u] ",
297
               dt.tm_mday,
298
               dt.tm_mon + 1,
299
               dt.tm_year + 1900,
300
               dt.tm_hour,
301
               dt.tm_min,
302
               dt.tm_sec);
303
    }
304
    else {
305
      aosDbgAssert(false);
306
    }
307 e545e620 Thomas Schöpping
  }
308

309
  // print the actual prompt string
310
  if (shell->prompt && !(shell->config & AOS_SHELL_CONFIG_PROMPT_MINIMAL)) {
311 ba516b61 Thomas Schöpping
    chprintf((BaseSequentialStream*)&shell->stream, "%s$ ", shell->prompt);
312 e545e620 Thomas Schöpping
  } else {
313 ba516b61 Thomas Schöpping
    chprintf((BaseSequentialStream*)&shell->stream, "%>$ ");
314 e545e620 Thomas Schöpping
  }
315 27d0378b Simon Welzel
*/
316 e545e620 Thomas Schöpping
  return;
317
}
318
319
/**
320
 * @brief   Interprete a escape sequence
321
 *
322
 * @param[in] seq   Character sequence to interprete.
323
 *                  Must be terminated by NUL byte.
324
 *
325
 * @return          A @p special_key value.
326
 */
327
static special_key_t _interpreteEscapeSequence(const char seq[])
328
{
329
  // local variables
330
  bool ambiguous = false;
331
  int cmp = 0;
332
333
  // TAB
334
  /* not supported yet; use "\x09" instead */
335
336
  // BACKSPACE
337
  /* not supported yet; use "\x08" instead */
338
339
  // ESCAPE
340
  cmp = strcmp(seq, "\x1B");
341
  if (cmp == 0) {
342
    return KEY_ESCAPE;
343
  } else {
344
    ambiguous |= (cmp < 0);
345
  }
346
347
  // INSERT
348
  cmp = strcmp(seq, "\x1B\x5B\x32\x7E");
349
  if (cmp == 0) {
350
    return KEY_INSERT;
351
  } else {
352
    ambiguous |= (cmp < 0);
353
  }
354
355
  // DELETE
356
  cmp = strcmp(seq, "\x1B\x5B\x33\x7E");
357
  if (cmp == 0) {
358
    return KEY_DELETE;
359
  } else {
360
    ambiguous |= (cmp < 0);
361
  }
362
363
  // HOME
364
  cmp = strcmp(seq, "\x1B\x4F\x48");
365
  if (cmp == 0) {
366
    return KEY_HOME;
367
  } else {
368
    ambiguous |= (cmp < 0);
369
  }
370
371
  // END
372
  cmp = strcmp(seq, "\x1B\x4F\x46");
373
  if (cmp == 0) {
374
    return KEY_END;
375
  } else {
376
    ambiguous |= (cmp < 0);
377
  }
378
379
  // PAGE UP
380
  cmp = strcmp(seq, "\x1B\x5B\x35\x7E");
381
  if (cmp == 0) {
382
    return KEY_PAGE_UP;
383
  } else {
384
    ambiguous |= (cmp < 0);
385
  }
386
387
  // PAGE DOWN
388
  cmp = strcmp(seq, "\x1B\x5B\x36\x7E");
389
  if (cmp == 0) {
390
    return KEY_PAGE_DOWN;
391
  } else {
392
    ambiguous |= (cmp < 0);
393
  }
394
395
  // ARROW UP
396
  cmp = strcmp(seq, "\x1B\x5B\x41");
397
  if (cmp == 0) {
398
    return KEY_ARROW_UP;
399
  } else {
400
    ambiguous |= (cmp < 0);
401
  }
402
403
  // ARROW DOWN
404
  cmp = strcmp(seq, "\x1B\x5B\x42");
405
  if (cmp == 0) {
406
    return KEY_ARROW_DOWN;
407
  } else {
408
    ambiguous |= (cmp < 0);
409
  }
410
411
  // ARROW LEFT
412
  cmp = strcmp(seq, "\x1B\x5B\x44");
413
  if (cmp == 0) {
414
    return KEY_ARROW_LEFT;
415
  } else {
416
    ambiguous |= (cmp < 0);
417
  }
418
419
  // ARROW RIGHT
420
  cmp = strcmp(seq, "\x1B\x5B\x43");
421
  if (cmp == 0) {
422
    return KEY_ARROW_RIGHT;
423
  } else {
424
    ambiguous |= (cmp < 0);
425
  }
426
427
  return ambiguous ? KEY_AMBIGUOUS : KEY_UNKNOWN;
428
}
429
430
/**
431
 * @brief   Move the cursor in the terminal
432
 *
433
 * @param[in] shell   Pointer to the shell object.
434
 * @param[in] from    Starting position of the cursor.
435
 * @param[in] to      Target position to move the cursor to.
436
 *
437
 * @return            The number of positions moved.
438
 */
439
static int _moveCursor(aos_shell_t* shell, const size_t from, const size_t to)
440
{
441
  aosDbgCheck(shell != NULL);
442
443
  // local variables
444
  size_t pos = from;
445
446
  // move cursor left by printing backspaces
447
  while (pos > to) {
448 ba516b61 Thomas Schöpping
    streamPut(&shell->stream, '\b');
449 e545e620 Thomas Schöpping
    --pos;
450
  }
451
452
  // move cursor right by printing line content
453
  while (pos < to) {
454 ba516b61 Thomas Schöpping
    streamPut(&shell->stream, shell->line[pos]);
455 e545e620 Thomas Schöpping
    ++pos;
456
  }
457
458
  return (int)pos - (int)from;
459
}
460
461
/**
462
 * @brief   Print content of the shell line
463
 *
464
 * @param[in] shell   Pointer to the shell object.
465
 * @param[in] from    First position to start printing from.
466
 * @param[in] to      Position after the last character to print.
467
 *
468
 * @return            Number of characters printed.
469
 */
470
static inline size_t _printLine(aos_shell_t* shell, const size_t from, const size_t to)
471
{
472
  aosDbgCheck(shell != NULL);
473
474
  // local variables
475
  size_t cnt;
476
477
  for (cnt = 0; from + cnt < to; ++cnt) {
478 ba516b61 Thomas Schöpping
    streamPut(&shell->stream, shell->line[from + cnt]);
479 e545e620 Thomas Schöpping
  }
480
481
  return cnt;
482
}
483
484
/**
485
 * @brief   Compare two characters.
486
 *
487
 * @param[in] lhs       First character to compare.
488
 * @param[in] rhs       Second character to compare.
489
 *
490
 * @return              How well the characters match.
491
 */
492
static inline charmatch_t _charcmp(char lhs, char rhs)
493
{
494
  // if lhs is a upper case letter and rhs is a lower case letter
495
  if (lhs >= 'A' && lhs <= 'Z' && rhs >= 'a' && rhs <= 'z') {
496
    return (lhs == (rhs - 'a' + 'A')) ? CHAR_MATCH_NCASE : CHAR_MATCH_NOT;
497
  }
498
  // if lhs is a lower case letter and rhs is a upper case letter
499
  else if (lhs >= 'a' && lhs <= 'z' && rhs >= 'A' && rhs <= 'Z') {
500
    return ((lhs - 'a' + 'A') == rhs) ? CHAR_MATCH_NCASE : CHAR_MATCH_NOT;
501
  }
502
  // default
503
  else {
504
    return (lhs == rhs) ? CHAR_MATCH_CASE : CHAR_MATCH_NOT;
505
  }
506
}
507
508
/**
509
 * @brief   Maps an character from ASCII to a modified custom encoding.
510
 * @details The custom character encoding is very similar to ASCII and has the following structure:
511
 *          0x00=NULL ... 0x40='@' (identically to ASCII)
512
 *          0x4A='a'; 0x4B='A'; 0x4C='b'; 0x4D='B' ... 0x73='z'; 0x74='Z' (custom letter order)
513
 *          0x75='[' ... 0x7A='`' (0x5B..0x60 is ASCII)
514
 *          0x7B='{' ... 0x7F=DEL (identically to ASCII)
515
 *
516
 * @param[in] c   Character to map to the custom encoding.
517
 *
518
 * @return    The customly encoded character.
519
 */
520
static inline char _mapAscii2Custom(const char c)
521
{
522
  if (c >= 'A' && c <= 'Z') {
523
    return ((c - 'A') * 2) + 'A' + 1;
524
  } else if (c > 'Z' && c < 'a') {
525
    return c + ('z' - 'a') + 1;
526
  } else if (c >= 'a' && c <= 'z') {
527
    return ((c - 'a') * 2) + 'A';
528
  } else {
529
    return c;
530
  }
531
}
532
533
/**
534
 * @brief   Compares two strings wrt letter case.
535
 * @details Comparisson uses a custom character encoding or mapping.
536
 *          See @p _mapAscii2Custom for details.
537
 *
538
 * @param[in] str1    First string to compare.
539
 * @param[in] str2    Second string to compare.
540
 * @param[in] cs      Flag indicating whether comparison shall be case sensitive.
541
 * @param[in,out] n   Maximum number of character to compare (in) and number of matching characters (out).
542
 *                    If a null pointer is specified, this parameter is ignored.
543
 *                    If the value pointed to is zero, comarison will not be limited.
544
 * @param[out] m      Optional indicator whether there was at least one case mismatch.
545
 *
546
 * @return      Integer value indicating the relationship between the strings.
547
 * @retval <0   The first character that does not match has a lower value in str1 than in str2.
548
 * @retval  0   The contents of both strings are equal.
549
 * @retval >0   The first character that does not match has a greater value in str1 than in str2.
550
 */
551
static int _strccmp(const char *str1, const char *str2, bool cs, size_t* n, charmatch_t* m)
552
{
553
  aosDbgCheck(str1 != NULL);
554
  aosDbgCheck(str2 != NULL);
555
556
  // initialize variables
557
  if (m) {
558
    *m = CHAR_MATCH_NOT;
559
  }
560
  size_t i = 0;
561
562
  // iterate through the strings
563
  while ((n == NULL) || (*n == 0) || (*n > 0 && i < *n)) {
564
    // break on NUL
565
    if (str1[i] == '\0' || str2[i] == '\0') {
566
      if (n) {
567
        *n = i;
568
      }
569
      break;
570
    }
571
    // compare character
572
    const charmatch_t match = _charcmp(str1[i], str2[i]);
573
    if ((match == CHAR_MATCH_CASE) || (!cs && match == CHAR_MATCH_NCASE)) {
574
      if (m != NULL && *m != CHAR_MATCH_NCASE) {
575
        *m = match;
576
      }
577
      ++i;
578
    } else {
579
      if (n) {
580
        *n = i;
581
      }
582
      break;
583
    }
584
  }
585
586
  return _mapAscii2Custom(str1[i]) - _mapAscii2Custom(str2[i]);
587
}
588
589 ba516b61 Thomas Schöpping
static aos_status_t _readChannel(aos_shell_t* shell, AosShellChannel* channel, size_t* n)
590 e545e620 Thomas Schöpping
{
591
  aosDbgCheck(shell != NULL);
592 ba516b61 Thomas Schöpping
  aosDbgCheck(channel != NULL);
593
  aosDbgCheck(n != NULL);
594 e545e620 Thomas Schöpping
595
  // local variables
596 ba516b61 Thomas Schöpping
  aos_shellaction_t action = AOS_SHELL_ACTION_NONE;
597 e545e620 Thomas Schöpping
  char c;
598 dd8738ea Thomas Schöpping
  special_key_t key;
599 e545e620 Thomas Schöpping
600 ba516b61 Thomas Schöpping
  // initialize output variables
601
  *n = 0;
602
603
  // read character by character from the channel
604
  while (chnReadTimeout(channel, (uint8_t*)&c, 1, TIME_IMMEDIATE)) {
605 dd8738ea Thomas Schöpping
    key = KEY_UNKNOWN;
606 e545e620 Thomas Schöpping
607
    // parse escape sequence
608 ba516b61 Thomas Schöpping
    if (shell->inputdata.escp > 0) {
609
      shell->inputdata.escseq[shell->inputdata.escp] = c;
610
      ++shell->inputdata.escp;
611
      key = _interpreteEscapeSequence(shell->inputdata.escseq);
612 e545e620 Thomas Schöpping
      if (key == KEY_AMBIGUOUS) {
613
        // read next byte to resolve ambiguity
614
        continue;
615
      } else {
616 ba516b61 Thomas Schöpping
        /*
617
         * If the escape sequence could either be parsed sucessfully
618
         * or there is no match (KEY_UNKNOWN),
619
         * reset the sequence variable and interprete key/character
620
         */
621
        shell->inputdata.escp = 0;
622
        memset(shell->inputdata.escseq, '\0', sizeof(shell->inputdata.escseq)*sizeof(shell->inputdata.escseq[0]));
623 e545e620 Thomas Schöpping
      }
624
    }
625
626 ba516b61 Thomas Schöpping
    /* interprete keys or character */
627 e545e620 Thomas Schöpping
    {
628 ba516b61 Thomas Schöpping
      // default
629
      action = AOS_SHELL_ACTION_NONE;
630
631
      // printable character
632
      if (key == KEY_UNKNOWN && c >= '\x20' && c <= '\x7E') {
633
        action = AOS_SHELL_ACTION_READCHAR;
634
      }
635
636
      // tab key or character
637
      else if (key == KEY_TAB || c == '\x09') {
638
        /*
639
         * pressing tab once applies auto fill
640
         * pressing tab a second time prints suggestions
641
         */
642
        if (shell->inputdata.lastaction == AOS_SHELL_ACTION_AUTOFILL || shell->inputdata.lastaction == AOS_SHELL_ACTION_SUGGEST) {
643
          action = AOS_SHELL_ACTION_SUGGEST;
644 e545e620 Thomas Schöpping
        } else {
645 ba516b61 Thomas Schöpping
          action = AOS_SHELL_ACTION_AUTOFILL;
646 e545e620 Thomas Schöpping
        }
647 ba516b61 Thomas Schöpping
      }
648
649
      // INS key
650
      else if (key == KEY_INSERT) {
651
        action = AOS_SHELL_ACTION_INSERTTOGGLE;
652
      }
653
654
      // DEL key or character
655
      else if (key == KEY_DELETE || c == '\x7F') {
656
        // ignore if cursor is at very right
657
        if (shell->inputdata.cursorpos < shell->inputdata.lineend) {
658
          action = AOS_SHELL_ACTION_DELETEFORWARD;
659 e545e620 Thomas Schöpping
        }
660 ba516b61 Thomas Schöpping
      }
661
662
      // backspace key or character
663
      else if (key == KEY_BACKSPACE || c == '\x08') {
664
        // ignore if cursor is at very left
665
        if (shell->inputdata.cursorpos > 0) {
666
          action = AOS_SHELL_ACTION_DELETEBACKWARD;
667 e545e620 Thomas Schöpping
        }
668 ba516b61 Thomas Schöpping
      }
669
670
      // 'page up' of 'arrow up' key
671
      else if (key == KEY_PAGE_UP || key == KEY_ARROW_UP) {
672 e545e620 Thomas Schöpping
        // ignore if there was some input
673 ba516b61 Thomas Schöpping
        if (shell->inputdata.noinput) {
674
          action = AOS_SHELL_ACTION_RECALLLAST;
675 e545e620 Thomas Schöpping
        }
676 ba516b61 Thomas Schöpping
      }
677
678
      // 'page down' key, 'arrow done' key, 'end of test' character or 'end of transmission' character
679
      else if (key == KEY_PAGE_DOWN || key == KEY_ARROW_DOWN || c == '\x03' || c == '\x03') {
680 e545e620 Thomas Schöpping
        // ignore if line is empty
681 ba516b61 Thomas Schöpping
        if (shell->inputdata.lineend > 0) {
682
          action = AOS_SHELL_ACTION_CLEAR;
683 e545e620 Thomas Schöpping
        }
684 ba516b61 Thomas Schöpping
      }
685
686
      // 'home' key
687
      else if (key == KEY_HOME) {
688 e545e620 Thomas Schöpping
        // ignore if cursor is very left
689 ba516b61 Thomas Schöpping
        if (shell->inputdata.cursorpos > 0) {
690
          action = AOS_SHELL_ACTION_CURSOR2START;
691 e545e620 Thomas Schöpping
        }
692 ba516b61 Thomas Schöpping
      }
693
694
      // 'end' key
695
      else if (key == KEY_END) {
696
        // ignore if cursos is very right
697
        if (shell->inputdata.cursorpos < shell->inputdata.lineend) {
698
          action = AOS_SHELL_ACTION_CURSOR2END;
699 e545e620 Thomas Schöpping
        }
700 ba516b61 Thomas Schöpping
      }
701
702
      // 'arrow left' key
703
      else if (key == KEY_ARROW_LEFT) {
704 e545e620 Thomas Schöpping
        // ignore if cursor is very left
705 ba516b61 Thomas Schöpping
        if (shell->inputdata.cursorpos > 0) {
706
          action = AOS_SHELL_ACTION_CURSORLEFT;
707 e545e620 Thomas Schöpping
        }
708 ba516b61 Thomas Schöpping
      }
709
710
      // 'arrow right' key
711
      else if (key == KEY_ARROW_RIGHT) {
712
        // irgnore if cursor is very right
713
        if (shell->inputdata.cursorpos < shell->inputdata.lineend) {
714
          action = AOS_SHELL_ACTION_CURSORRIGHT;
715 e545e620 Thomas Schöpping
        }
716 ba516b61 Thomas Schöpping
      }
717
718
      // carriage return ('\r') or line feed ('\n') character
719
      else if (c == '\x0D' || c == '\x0A') {
720
        action = AOS_SHELL_ACTION_EXECUTE;
721
      }
722
723
      // ESC key or [ESCAPE] character
724
      else if (key == KEY_ESCAPE || c == '\x1B') {
725
        action = AOS_SHELL_ACTION_ESCSTART;
726 e545e620 Thomas Schöpping
      }
727
    }
728
729
    /* handle function */
730 ba516b61 Thomas Schöpping
    switch (action) {
731
      case AOS_SHELL_ACTION_READCHAR:
732
      {
733 e545e620 Thomas Schöpping
        // line is full
734 ba516b61 Thomas Schöpping
        if (shell->inputdata.lineend + 1 >= shell->linesize) {
735
          _moveCursor(shell, shell->inputdata.cursorpos, shell->inputdata.lineend);
736
          chprintf((BaseSequentialStream*)&shell->stream, "\n\tmaximum line width reached\n");
737 e545e620 Thomas Schöpping
          _printPrompt(shell);
738 ba516b61 Thomas Schöpping
          _printLine(shell, 0, shell->inputdata.lineend);
739
          _moveCursor(shell, shell->inputdata.lineend, shell->inputdata.cursorpos);
740 e545e620 Thomas Schöpping
        }
741
        // read character
742
        else {
743
          // clear old line content on first input
744 ba516b61 Thomas Schöpping
          if (shell->inputdata.noinput) {
745 e545e620 Thomas Schöpping
            memset(shell->line, '\0', shell->linesize);
746 ba516b61 Thomas Schöpping
            shell->inputdata.noinput = false;
747 e545e620 Thomas Schöpping
          }
748
          // overwrite content
749
          if (shell->config & AOS_SHELL_CONFIG_INPUT_OVERWRITE) {
750 ba516b61 Thomas Schöpping
            shell->line[shell->inputdata.cursorpos] = c;
751
            ++shell->inputdata.cursorpos;
752
            shell->inputdata.lineend = (shell->inputdata.cursorpos > shell->inputdata.lineend) ? shell->inputdata.cursorpos : shell->inputdata.lineend;
753
            streamPut(&shell->stream, (uint8_t)c);
754 e545e620 Thomas Schöpping
          }
755
          // insert character
756
          else {
757 ba516b61 Thomas Schöpping
            memmove(&(shell->line[shell->inputdata.cursorpos+1]), &(shell->line[shell->inputdata.cursorpos]), shell->inputdata.lineend - shell->inputdata.cursorpos);
758
            shell->line[shell->inputdata.cursorpos] = c;
759
            ++shell->inputdata.lineend;
760
            _printLine(shell, shell->inputdata.cursorpos, shell->inputdata.lineend);
761
            ++shell->inputdata.cursorpos;
762
            _moveCursor(shell, shell->inputdata.lineend, shell->inputdata.cursorpos);
763 e545e620 Thomas Schöpping
          }
764
        }
765
        break;
766 ba516b61 Thomas Schöpping
      }
767 e545e620 Thomas Schöpping
768 ba516b61 Thomas Schöpping
      case AOS_SHELL_ACTION_AUTOFILL:
769 e545e620 Thomas Schöpping
      {
770
        const char* fill = shell->line;
771 ba516b61 Thomas Schöpping
        size_t cmatch = shell->inputdata.cursorpos;
772 e545e620 Thomas Schöpping
        charmatch_t matchlevel = CHAR_MATCH_NOT;
773
        size_t n;
774
        // iterate through command list
775
        for (aos_shellcommand_t* cmd = shell->commands; cmd != NULL; cmd = cmd->next) {
776
          // compare current match with command
777
          n = cmatch;
778
          charmatch_t mlvl = CHAR_MATCH_NOT;
779
          _strccmp(fill, cmd->name, shell->config & AOS_SHELL_CONFIG_MATCH_CASE, (n == 0) ? NULL : &n, &mlvl);
780
          const int cmp = (n < cmatch) ?
781
                            (n - cmatch) :
782
                            (cmd->name[n] != '\0') ?
783
                              strlen(cmd->name) - n :
784
                              0;
785
          // if an exact match was found
786 ba516b61 Thomas Schöpping
          if (cmatch + cmp == shell->inputdata.cursorpos) {
787
            cmatch = shell->inputdata.cursorpos;
788 e545e620 Thomas Schöpping
            fill = cmd->name;
789
            // break the loop only if there are no case mismatches with the input
790 ba516b61 Thomas Schöpping
            n = shell->inputdata.cursorpos;
791 e545e620 Thomas Schöpping
            _strccmp(fill, shell->line, false, &n, &mlvl);
792
            if (mlvl == CHAR_MATCH_CASE) {
793
              break;
794
            }
795
          }
796
          // if a not exact match was found
797 ba516b61 Thomas Schöpping
          else if (cmatch + cmp > shell->inputdata.cursorpos) {
798 e545e620 Thomas Schöpping
            // if this is the first one
799
            if (fill == shell->line) {
800
              cmatch += cmp;
801
              fill = cmd->name;
802
            }
803
            // if this is a worse one
804
            else if ((cmp < 0) || (cmp == 0 && mlvl == CHAR_MATCH_CASE)) {
805
              cmatch += cmp;
806
            }
807
          }
808
          // non matching commands are ignored
809
          else {}
810
        }
811
        // evaluate if there are case mismatches
812
        n = cmatch;
813
        _strccmp(shell->line, fill, shell->config & AOS_SHELL_CONFIG_MATCH_CASE, &n, &matchlevel);
814
        // print the auto fill if any
815 ba516b61 Thomas Schöpping
        if (cmatch > shell->inputdata.cursorpos || (cmatch == shell->inputdata.cursorpos && matchlevel == CHAR_MATCH_NCASE)) {
816
          shell->inputdata.noinput = false;
817 e545e620 Thomas Schöpping
          // limit auto fill so it will not overflow the line width
818 ba516b61 Thomas Schöpping
          if (shell->inputdata.lineend + (cmatch - shell->inputdata.cursorpos) > shell->linesize) {
819
            cmatch = shell->linesize - shell->inputdata.lineend + shell->inputdata.cursorpos;
820 e545e620 Thomas Schöpping
          }
821
          // move trailing memory further in the line
822 ba516b61 Thomas Schöpping
          memmove(&(shell->line[cmatch]), &(shell->line[shell->inputdata.cursorpos]), shell->inputdata.lineend - shell->inputdata.cursorpos);
823
          shell->inputdata.lineend += cmatch - shell->inputdata.cursorpos;
824 e545e620 Thomas Schöpping
          // if there was no incorrect case when matching
825
          if (matchlevel == CHAR_MATCH_CASE) {
826
            // insert fill command name to line
827 ba516b61 Thomas Schöpping
            memcpy(&(shell->line[shell->inputdata.cursorpos]), &(fill[shell->inputdata.cursorpos]), cmatch - shell->inputdata.cursorpos);
828 e545e620 Thomas Schöpping
            // print the output
829 ba516b61 Thomas Schöpping
            _printLine(shell, shell->inputdata.cursorpos, shell->inputdata.lineend);
830 e545e620 Thomas Schöpping
          } else {
831
            // overwrite line with fill command name
832
            memcpy(shell->line, fill, cmatch);
833
            // reprint the whole line
834 ba516b61 Thomas Schöpping
            _moveCursor(shell, shell->inputdata.cursorpos, 0);
835
            _printLine(shell, 0, shell->inputdata.lineend);
836 e545e620 Thomas Schöpping
          }
837
          // move cursor to the end of the matching sequence
838 ba516b61 Thomas Schöpping
          shell->inputdata.cursorpos = cmatch;
839
          _moveCursor(shell, shell->inputdata.lineend, shell->inputdata.cursorpos);
840 e545e620 Thomas Schöpping
        }
841
        break;
842
      }
843
844 ba516b61 Thomas Schöpping
      case AOS_SHELL_ACTION_SUGGEST:
845 e545e620 Thomas Schöpping
      {
846
        unsigned int matches = 0;
847
        // iterate through command list
848
        for (aos_shellcommand_t* cmd = shell->commands; cmd != NULL; cmd = cmd->next) {
849
          // compare line content with command, excpet if cursorpos=0
850 ba516b61 Thomas Schöpping
          size_t i = shell->inputdata.cursorpos;
851
          if (shell->inputdata.cursorpos > 0) {
852 e545e620 Thomas Schöpping
            _strccmp(shell->line, cmd->name, true, &i, NULL);
853
          }
854 ba516b61 Thomas Schöpping
          const int cmp = (i < shell->inputdata.cursorpos) ?
855
                            (i - shell->inputdata.cursorpos) :
856 e545e620 Thomas Schöpping
                            (cmd->name[i] != '\0') ?
857
                              strlen(cmd->name) - i :
858
                              0;
859
          // if a match was found
860
          if (cmp > 0) {
861
            // if this is the first one
862
            if (matches == 0) {
863 ba516b61 Thomas Schöpping
              _moveCursor(shell, shell->inputdata.cursorpos, shell->inputdata.lineend);
864
              streamPut(&shell->stream, '\n');
865 e545e620 Thomas Schöpping
            }
866
            // print the command
867 ba516b61 Thomas Schöpping
            chprintf((BaseSequentialStream*)&shell->stream, "\t%s\n", cmd->name);
868 e545e620 Thomas Schöpping
            ++matches;
869
          }
870
        }
871
        // reprint the prompt and line if any matches have been found
872
        if (matches > 0) {
873
          _printPrompt(shell);
874 ba516b61 Thomas Schöpping
          _printLine(shell, 0, shell->inputdata.lineend);
875
          _moveCursor(shell, shell->inputdata.lineend, shell->inputdata.cursorpos);
876
          shell->inputdata.noinput = false;
877 e545e620 Thomas Schöpping
        }
878
        break;
879
      }
880
881 ba516b61 Thomas Schöpping
      case AOS_SHELL_ACTION_INSERTTOGGLE:
882
      {
883 e545e620 Thomas Schöpping
        if (shell->config & AOS_SHELL_CONFIG_INPUT_OVERWRITE) {
884
          shell->config &= ~AOS_SHELL_CONFIG_INPUT_OVERWRITE;
885
        } else {
886
          shell->config |= AOS_SHELL_CONFIG_INPUT_OVERWRITE;
887
        }
888
        break;
889 ba516b61 Thomas Schöpping
      }
890 e545e620 Thomas Schöpping
891 ba516b61 Thomas Schöpping
      case AOS_SHELL_ACTION_DELETEFORWARD:
892
      {
893
        --shell->inputdata.lineend;
894
        memmove(&(shell->line[shell->inputdata.cursorpos]), &(shell->line[shell->inputdata.cursorpos+1]), shell->inputdata.lineend - shell->inputdata.cursorpos);
895
        _printLine(shell, shell->inputdata.cursorpos, shell->inputdata.lineend);
896
        streamPut(&shell->stream, ' ');
897
        _moveCursor(shell, shell->inputdata.lineend + 1, shell->inputdata.cursorpos);
898 e545e620 Thomas Schöpping
        break;
899 ba516b61 Thomas Schöpping
      }
900 e545e620 Thomas Schöpping
901 ba516b61 Thomas Schöpping
      case AOS_SHELL_ACTION_DELETEBACKWARD:
902
      {
903
        --shell->inputdata.cursorpos;
904
        memmove(&(shell->line[shell->inputdata.cursorpos]), &(shell->line[shell->inputdata.cursorpos+1]), shell->inputdata.lineend - shell->inputdata.cursorpos);
905
        --shell->inputdata.lineend;
906
        shell->line[shell->inputdata.lineend] = '\0';
907
        _moveCursor(shell, shell->inputdata.cursorpos + 1, shell->inputdata.cursorpos);
908
        _printLine(shell, shell->inputdata.cursorpos, shell->inputdata.lineend);
909
        streamPut(&shell->stream, ' ');
910
        _moveCursor(shell, shell->inputdata.lineend+1, shell->inputdata.cursorpos);
911 e545e620 Thomas Schöpping
        break;
912 ba516b61 Thomas Schöpping
      }
913 e545e620 Thomas Schöpping
914 ba516b61 Thomas Schöpping
      case AOS_SHELL_ACTION_RECALLLAST:
915 e545e620 Thomas Schöpping
      {
916
        // replace any intermediate NUL bytes with spaces
917 ba516b61 Thomas Schöpping
        shell->inputdata.lineend = 0;
918 e545e620 Thomas Schöpping
        size_t nul_start = 0;
919
        size_t nul_end = 0;
920
        // search line for a NUL byte
921
        while (nul_start < shell->linesize) {
922
          if (shell->line[nul_start] == '\0') {
923
            nul_end = nul_start + 1;
924
            // keep searcjing for a byte that is not NUL
925
            while (nul_end < shell->linesize) {
926
              if (shell->line[nul_end] != '\0') {
927
                // an intermediate NUL sequence was found
928
                memset(&(shell->line[nul_start]), ' ', nul_end - nul_start);
929 ba516b61 Thomas Schöpping
                shell->inputdata.lineend = nul_end + 1;
930 e545e620 Thomas Schöpping
                break;
931
              } else {
932
                ++nul_end;
933
              }
934
            }
935
            nul_start = nul_end + 1;
936
          } else {
937 ba516b61 Thomas Schöpping
            ++shell->inputdata.lineend;
938 e545e620 Thomas Schöpping
            ++nul_start;
939
          }
940
        }
941 ba516b61 Thomas Schöpping
        shell->inputdata.cursorpos = shell->inputdata.lineend;
942 e545e620 Thomas Schöpping
        // print the line
943 ba516b61 Thomas Schöpping
        shell->inputdata.noinput = _printLine(shell, 0, shell->inputdata.lineend) == 0;
944 e545e620 Thomas Schöpping
        break;
945
      }
946
947 ba516b61 Thomas Schöpping
      case AOS_SHELL_ACTION_CLEAR:
948
      {
949 e545e620 Thomas Schöpping
        // clear output
950 ba516b61 Thomas Schöpping
        _moveCursor(shell, shell->inputdata.cursorpos, 0);
951
        for (shell->inputdata.cursorpos = 0; shell->inputdata.cursorpos < shell->inputdata.lineend; ++shell->inputdata.cursorpos) {
952
          streamPut(&shell->stream, ' ');
953 e545e620 Thomas Schöpping
        }
954 ba516b61 Thomas Schöpping
        _moveCursor(shell, shell->inputdata.lineend, 0);
955
        shell->inputdata.cursorpos = 0;
956
        shell->inputdata.lineend = 0;
957
        shell->inputdata.noinput = true;
958 e545e620 Thomas Schöpping
        break;
959 ba516b61 Thomas Schöpping
      }
960 e545e620 Thomas Schöpping
961 ba516b61 Thomas Schöpping
      case AOS_SHELL_ACTION_CURSOR2START:
962
      {
963
        _moveCursor(shell, shell->inputdata.cursorpos, 0);
964
        shell->inputdata.cursorpos = 0;
965 e545e620 Thomas Schöpping
        break;
966 ba516b61 Thomas Schöpping
      }
967 e545e620 Thomas Schöpping
968 ba516b61 Thomas Schöpping
      case AOS_SHELL_ACTION_CURSOR2END:
969
      {
970
        _moveCursor(shell, shell->inputdata.cursorpos, shell->inputdata.lineend);
971
        shell->inputdata.cursorpos = shell->inputdata.lineend;
972 e545e620 Thomas Schöpping
        break;
973 ba516b61 Thomas Schöpping
      }
974 e545e620 Thomas Schöpping
975 ba516b61 Thomas Schöpping
      case AOS_SHELL_ACTION_CURSORLEFT:
976
      {
977
        _moveCursor(shell, shell->inputdata.cursorpos, shell->inputdata.cursorpos-1);
978
        --shell->inputdata.cursorpos;
979 e545e620 Thomas Schöpping
        break;
980 ba516b61 Thomas Schöpping
      }
981 e545e620 Thomas Schöpping
982 ba516b61 Thomas Schöpping
      case AOS_SHELL_ACTION_CURSORRIGHT:
983
      {
984
        _moveCursor(shell, shell->inputdata.cursorpos, shell->inputdata.cursorpos+1);
985
        ++shell->inputdata.cursorpos;
986 e545e620 Thomas Schöpping
        break;
987 ba516b61 Thomas Schöpping
      }
988 e545e620 Thomas Schöpping
989 ba516b61 Thomas Schöpping
      case AOS_SHELL_ACTION_EXECUTE:
990
      {
991
        streamPut(&shell->stream, '\n');
992
        // set the number of read bytes and return
993
        if (!shell->inputdata.noinput) {
994
          *n = shell->linesize - shell->inputdata.lineend;
995 e545e620 Thomas Schöpping
          // fill the remainder of the line with NUL bytes
996 ba516b61 Thomas Schöpping
          memset(&(shell->line[shell->inputdata.lineend]), '\0', *n);
997
          // reset static variables
998
          shell->inputdata.noinput = true;
999 e545e620 Thomas Schöpping
        }
1000 ba516b61 Thomas Schöpping
        return AOS_SUCCESS;
1001 e545e620 Thomas Schöpping
        break;
1002 ba516b61 Thomas Schöpping
      }
1003 e545e620 Thomas Schöpping
1004 ba516b61 Thomas Schöpping
      case AOS_SHELL_ACTION_ESCSTART:
1005
      {
1006
        shell->inputdata.escseq[0] = c;
1007
        ++shell->inputdata.escp;
1008 e545e620 Thomas Schöpping
        break;
1009 ba516b61 Thomas Schöpping
      }
1010 e545e620 Thomas Schöpping
1011 ba516b61 Thomas Schöpping
      case AOS_SHELL_ACTION_NONE:
1012 e545e620 Thomas Schöpping
      default:
1013 ba516b61 Thomas Schöpping
      {
1014 e545e620 Thomas Schöpping
        // do nothing (ignore input) and read next byte
1015
        continue;
1016
        break;
1017 ba516b61 Thomas Schöpping
      }
1018
    } /* end of switch */
1019 e545e620 Thomas Schöpping
1020 ba516b61 Thomas Schöpping
    shell->inputdata.lastaction = action;
1021 e545e620 Thomas Schöpping
  } /* end of while */
1022
1023 ba516b61 Thomas Schöpping
  // no more data could be read from the channel
1024
  return AOS_WARNING;
1025 e545e620 Thomas Schöpping
}
1026
1027
/**
1028
 * @brief   Parses the content of the input buffer (line) to separate arguments.
1029
 *
1030
 * @param[in] shell   Pointer to the shell object.
1031
 *
1032
 * @return            Number of arguments found.
1033
 */
1034
static size_t _parseArguments(aos_shell_t* shell)
1035
{
1036
  aosDbgCheck(shell != NULL);
1037
1038
  /*
1039
   * States for a very small FSM.
1040
   */
1041
  typedef enum {
1042
    START,
1043
    SPACE,
1044
    TEXT,
1045
    END,
1046
  } state_t;
1047
1048
  // local variables
1049
  state_t state = START;
1050
  size_t arg = 0;
1051
1052
  // iterate through the line
1053
  for (char* c = shell->line; c < shell->line + shell->linesize; ++c) {
1054
    // terminate at first NUL byte
1055
    if (*c == '\0') {
1056
      state = END;
1057
      break;
1058
    }
1059
    // spaces become NUL bytes
1060
    else if (*c == ' ') {
1061
      *c = '\0';
1062
      state = SPACE;
1063
    }
1064
    // handle non-NUL bytes
1065
    else {
1066
      switch (state) {
1067
        case START:
1068
        case SPACE:
1069
          // ignore too many arguments
1070
          if (arg < shell->arglistsize) {
1071
            shell->arglist[arg] = c;
1072
          }
1073
          ++arg;
1074
          break;
1075
        case TEXT:
1076
        case END:
1077
        default:
1078
          break;
1079
      }
1080
      state = TEXT;
1081
    }
1082
  }
1083
1084
  // set all remaining argument pointers to NULL
1085
  for (size_t a = arg; a < shell->arglistsize; ++a) {
1086
    shell->arglist[a] = NULL;
1087
  }
1088
1089
  return arg;
1090
}
1091
1092
/**
1093
 * @brief   Initializes a shell object with the specified parameters.
1094
 *
1095
 * @param[in] shell         Pointer to the shell object.
1096
 * @param[in] stream        I/O stream to use.
1097
 * @param[in] prompt        Prompt line to print (NULL = use default prompt).
1098
 * @param[in] line          Pointer to the input buffer.
1099
 * @param[in] linesize      Size of the input buffer.
1100
 * @param[in] arglist       Pointer to the argument buffer.
1101
 * @param[in] arglistsize   Size of te argument buffer.
1102
 */
1103 ba516b61 Thomas Schöpping
void aosShellInit(aos_shell_t* shell, event_source_t* oseventsource,  const char* prompt, char* line, size_t linesize, char** arglist, size_t arglistsize)
1104 e545e620 Thomas Schöpping
{
1105
  aosDbgCheck(shell != NULL);
1106 ba516b61 Thomas Schöpping
  aosDbgCheck(oseventsource != NULL);
1107 e545e620 Thomas Schöpping
  aosDbgCheck(line != NULL);
1108
  aosDbgCheck(arglist != NULL);
1109
1110
  // set parameters
1111
  shell->thread = NULL;
1112
  chEvtObjectInit(&shell->eventSource);
1113 ba516b61 Thomas Schöpping
  shell->os.eventSource = oseventsource;
1114
  aosShellStreamInit(&shell->stream);
1115 e545e620 Thomas Schöpping
  shell->prompt = prompt;
1116
  shell->commands = NULL;
1117
  shell->execstatus.command = NULL;
1118
  shell->execstatus.retval = 0;
1119
  shell->line = line;
1120
  shell->linesize = linesize;
1121 ba516b61 Thomas Schöpping
  shell->inputdata.lastaction = AOS_SHELL_ACTION_NONE;
1122
  shell->inputdata.escp = 0;
1123
  memset(shell->inputdata.escseq, '\0', sizeof(shell->inputdata.escseq)*sizeof(shell->inputdata.escseq[0]));
1124
  shell->inputdata.cursorpos = 0;
1125
  shell->inputdata.lineend = 0;
1126
  shell->inputdata.noinput = true;
1127 e545e620 Thomas Schöpping
  shell->arglist = arglist;
1128
  shell->arglistsize = arglistsize;
1129
  shell->config = 0x00;
1130
1131
  // initialize arrays
1132
  memset(shell->line, '\0', shell->linesize);
1133
  for (size_t a = 0; a < shell->arglistsize; ++a) {
1134
    shell->arglist[a] = NULL;
1135
  }
1136
1137
  return;
1138
}
1139
1140
/**
1141 ba516b61 Thomas Schöpping
 * @brief   Initialize an AosShellStream object.
1142
 *
1143
 * @param[in] stream  The AosShellStrem to initialize.
1144
 */
1145
void aosShellStreamInit(AosShellStream* stream)
1146
{
1147
  aosDbgCheck(stream != NULL);
1148
1149
  stream->vmt = &_streamvmt;
1150
  stream->channel = NULL;
1151
1152
  return;
1153
}
1154
1155
/**
1156
 * @brief   Initialize an AosShellChannel object with the specified parameters.
1157
 *
1158 dd8738ea Thomas Schöpping
 * @param[in] channel       The AosShellChannel to initialize.
1159
 * @param[in] asyncchannel  An BaseAsynchronousChannel this AosShellChannel is associated with.
1160 ba516b61 Thomas Schöpping
 */
1161 dd8738ea Thomas Schöpping
void aosShellChannelInit(AosShellChannel* channel, BaseAsynchronousChannel* asyncchannel)
1162 ba516b61 Thomas Schöpping
{
1163
  aosDbgCheck(channel != NULL);
1164 dd8738ea Thomas Schöpping
  aosDbgCheck(asyncchannel != NULL);
1165 ba516b61 Thomas Schöpping
1166
  channel->vmt = &_channelvmt;
1167 dd8738ea Thomas Schöpping
  channel->asyncchannel = asyncchannel;
1168
  channel->listener.wflags = 0;
1169 ba516b61 Thomas Schöpping
  channel->next = NULL;
1170
  channel->flags = 0;
1171
1172
  return;
1173
}
1174
1175
/**
1176 e545e620 Thomas Schöpping
 * @brief   Inserts a command to the shells list of commands.
1177
 *
1178
 * @param[in] shell   Pointer to the shell object.
1179
 * @param[in] cmd     Pointer to the command to add.
1180
 *
1181
 * @return            A status value.
1182
 * @retval AOS_SUCCESS  The command was added successfully.
1183
 * @retval AOS_ERROR    Another command with identical name already exists.
1184
 */
1185
aos_status_t aosShellAddCommand(aos_shell_t *shell, aos_shellcommand_t *cmd)
1186
{
1187
  aosDbgCheck(shell != NULL);
1188
  aosDbgCheck(cmd != NULL);
1189
  aosDbgCheck(cmd->name != NULL && strlen(cmd->name) > 0 && strchr(cmd->name, ' ') == NULL && strchr(cmd->name, '\t') == NULL);
1190
  aosDbgCheck(cmd->callback != NULL);
1191
  aosDbgCheck(cmd->next == NULL);
1192
1193
  aos_shellcommand_t* prev = NULL;
1194
  aos_shellcommand_t** curr = &(shell->commands);
1195
1196
  // insert the command to the list wrt lexographical order (exception: lower case characters preceed upper their uppercase counterparts)
1197 ba516b61 Thomas Schöpping
  while (*curr != NULL) {
1198
    // iterate through the list as long as the command names are 'smaller'
1199
    const int cmp = _strccmp((*curr)->name, cmd->name, true, NULL, NULL);
1200
    if (cmp < 0) {
1201
      prev = *curr;
1202
      curr = &((*curr)->next);
1203
      continue;
1204
    }
1205
    // error if the command already exists
1206
    else if (cmp == 0) {
1207
      return AOS_ERROR;
1208
    }
1209
    // insert the command as soon as a 'larger' name was found
1210
    else /* if (cmpval > 0) */ {
1211
      cmd->next = *curr;
1212
      // special case: the first command is larger
1213
      if (prev == NULL) {
1214
        shell->commands = cmd;
1215
      } else {
1216
        prev->next = cmd;
1217 e545e620 Thomas Schöpping
      }
1218 ba516b61 Thomas Schöpping
      return AOS_SUCCESS;
1219 e545e620 Thomas Schöpping
    }
1220
  }
1221 ba516b61 Thomas Schöpping
  // the end of the list has been reached
1222
1223
  // append the command
1224
  *curr = cmd;
1225
  return AOS_SUCCESS;
1226 e545e620 Thomas Schöpping
}
1227
1228
/**
1229
 * @brief   Removes a command from the shells list of commands.
1230
 *
1231
 * @param[in] shell     Pointer to the shell object.
1232
 * @param[in] cmd       Name of the command to removde.
1233
 * @param[out] removed  Optional pointer to the command that was removed.
1234
 *
1235
 * @return              A status value.
1236
 * @retval AOS_SUCCESS  The command was removed successfully.
1237
 * @retval AOS_ERROR    The command name was not found.
1238
 */
1239
aos_status_t aosShellRemoveCommand(aos_shell_t *shell, char *cmd, aos_shellcommand_t **removed)
1240
{
1241
  aosDbgCheck(shell != NULL);
1242
  aosDbgCheck(cmd != NULL && strlen(cmd) > 0);
1243
1244
  aos_shellcommand_t* prev = NULL;
1245
  aos_shellcommand_t** curr = &(shell->commands);
1246
1247
  // iterate through the list and seach for the specified command name
1248
  while (curr != NULL) {
1249
    const int cmpval = strcmp((*curr)->name, cmd);
1250
    // iterate through the list as long as the command names are 'smaller'
1251
    if (cmpval < 0) {
1252
      prev = *curr;
1253
      curr = &((*curr)->next);
1254
      continue;
1255
    }
1256
    // remove the command when found
1257
    else if (cmpval == 0) {
1258
      // special case: the first command matches
1259
      if (prev == NULL) {
1260
        shell->commands = (*curr)->next;
1261
      } else {
1262
        prev->next = (*curr)->next;
1263
      }
1264
      (*curr)->next = NULL;
1265
      // set the optional output argument
1266
      if (removed != NULL) {
1267
        *removed = *curr;
1268
      }
1269
      return AOS_SUCCESS;
1270
    }
1271
    // break the loop if the command names are 'larger'
1272
    else /* if (cmpval > 0) */ {
1273
      break;
1274
    }
1275
  }
1276
1277
  // if the command was not found, return an error
1278
  return AOS_ERROR;
1279
}
1280
1281
/**
1282 aed3754b Thomas Schöpping
 * @brief   Count the number of commands assigned to the shell.
1283
 *
1284
 * @param[in] shell   The shell to count the commands for.
1285
 *
1286
 * @return  The number of commands associated to the shell.
1287
 */
1288
unsigned int aosShellCountCommands(aos_shell_t* shell)
1289
{
1290
  aosDbgCheck(shell != NULL);
1291
1292
  unsigned int count = 0;
1293
  aos_shellcommand_t* cmd = shell->commands;
1294
  while (cmd != NULL) {
1295
    ++count;
1296
    cmd = cmd->next;
1297
  }
1298
1299
  return count;
1300
}
1301
1302
/**
1303 ba516b61 Thomas Schöpping
 * @brief   Add a channel to a AosShellStream.
1304
 *
1305
 * @param[in] stream    The AosShellStream to extend.
1306
 * @param[in] channel   The channel to be added to the stream.
1307
 */
1308
void aosShellStreamAddChannel(AosShellStream* stream, AosShellChannel* channel)
1309
{
1310
  aosDbgCheck(stream != NULL);
1311 dd8738ea Thomas Schöpping
  aosDbgCheck(channel != NULL && channel->asyncchannel != NULL && channel->next == NULL && (channel->flags & AOS_SHELLCHANNEL_ATTACHED) == 0);
1312 ba516b61 Thomas Schöpping
1313
  // prepend the new channel
1314
  chSysLock();
1315
  channel->flags |= AOS_SHELLCHANNEL_ATTACHED;
1316
  channel->next = stream->channel;
1317
  stream->channel = channel;
1318
  chSysUnlock();
1319
1320
  return;
1321
}
1322
1323
/**
1324
 * @brief   Remove a channel from an AosShellStream.
1325
 *
1326
 * @param[in] stream    The AosShellStream to modify.
1327
 * @param[in] channel   The channel to remove.
1328 aed3754b Thomas Schöpping
 *
1329
 * @return              A status value.
1330
 * @retval AOS_SUCCESS  The channel was removed successfully.
1331
 * @retval AOS_ERROR    The specified channel was not found to be associated with the shell.
1332 ba516b61 Thomas Schöpping
 */
1333
aos_status_t aosShellStreamRemoveChannel(AosShellStream* stream, AosShellChannel* channel)
1334
{
1335
  aosDbgCheck(stream != NULL);
1336 dd8738ea Thomas Schöpping
  aosDbgCheck(channel != NULL && channel->asyncchannel != NULL && channel->flags & AOS_SHELLCHANNEL_ATTACHED);
1337 ba516b61 Thomas Schöpping
1338
  // local varibales
1339
  AosShellChannel* prev = NULL;
1340
  AosShellChannel* curr = stream->channel;
1341
1342
  // iterate through the list and search for the specified channel
1343
  while (curr != NULL) {
1344
    // if the channel was found
1345
    if (curr == channel) {
1346
      chSysLock();
1347
      // special case: the first channel matches (prev is NULL)
1348
      if (prev == NULL) {
1349
        stream->channel = curr->next;
1350
      } else {
1351
        prev->next = channel->next;
1352
      }
1353
      curr->next = NULL;
1354
      curr->flags &= ~AOS_SHELLCHANNEL_ATTACHED;
1355
      chSysUnlock();
1356
      return AOS_SUCCESS;
1357
    }
1358
  }
1359
1360
  // if the channel was not found, return an error
1361
  return AOS_ERROR;
1362
}
1363
1364
/**
1365
 * @brief   Enable a AosSheööChannel as input.
1366
 *
1367
 * @param[in] channel   The channel to enable as input.
1368
 */
1369
void aosShellChannelInputEnable(AosShellChannel* channel)
1370
{
1371 dd8738ea Thomas Schöpping
  aosDbgCheck(channel != NULL && channel->asyncchannel != NULL);
1372 ba516b61 Thomas Schöpping
1373
  chSysLock();
1374
  channel->listener.wflags |= CHN_INPUT_AVAILABLE;
1375
  channel->flags |= AOS_SHELLCHANNEL_INPUT_ENABLED;
1376
  chSysUnlock();
1377
1378
  return;
1379
}
1380
1381
/**
1382
 * @brief   Disable a AosSheööChannel as input.
1383
 *
1384
 * @param[in] channel   The channel to disable as input.
1385
 */
1386
void aosShellChannelInputDisable( AosShellChannel* channel)
1387
{
1388 dd8738ea Thomas Schöpping
  aosDbgCheck(channel != NULL && channel->asyncchannel != NULL);
1389 ba516b61 Thomas Schöpping
1390
  chSysLock();
1391
  channel->listener.wflags &= ~CHN_INPUT_AVAILABLE;
1392
  channel->flags &= ~AOS_SHELLCHANNEL_INPUT_ENABLED;
1393
  chSysUnlock();
1394
1395
  return;
1396
}
1397
1398
/**
1399
 * @brief   Enable a AosSheööChannel as output.
1400
 *
1401
 * @param[in] channel   The channel to enable as output.
1402
 */
1403
void aosShellChannelOutputEnable(AosShellChannel* channel)
1404
{
1405 dd8738ea Thomas Schöpping
  aosDbgCheck(channel != NULL && channel->asyncchannel != NULL);
1406 ba516b61 Thomas Schöpping
1407
  channel->flags |= AOS_SHELLCHANNEL_OUTPUT_ENABLED;
1408
1409
  return;
1410
}
1411
1412
/**
1413
 * @brief   Disable a AosSheööChannel as output.
1414
 *
1415
 * @param[in] channel   The channel to disable as output.
1416
 */
1417
void aosShellChannelOutputDisable(AosShellChannel* channel)
1418
{
1419 dd8738ea Thomas Schöpping
  aosDbgCheck(channel != NULL && channel->asyncchannel != NULL);
1420 ba516b61 Thomas Schöpping
1421
  channel->flags &= ~AOS_SHELLCHANNEL_OUTPUT_ENABLED;
1422
1423
  return;
1424
}
1425
1426
/**
1427 e545e620 Thomas Schöpping
 * @brief   Thread main function.
1428
 *
1429
 * @param[in] aosShellThread    Name of the function;
1430
 * @param[in] shell             Pointer to the shell object.
1431
 */
1432 af4fd4a2 Thomas Schöpping
void aosShellThread(void* shell)
1433 e545e620 Thomas Schöpping
{
1434
  aosDbgCheck(shell != NULL);
1435
1436
  // local variables
1437 ba516b61 Thomas Schöpping
  eventmask_t eventmask;
1438
  eventflags_t eventflags;
1439
  AosShellChannel* channel;
1440
  aos_status_t readeval;
1441
  size_t nchars = 0;
1442 e545e620 Thomas Schöpping
  size_t nargs = 0;
1443 ba516b61 Thomas Schöpping
  aos_shellcommand_t* cmd;
1444
1445
1446
  // register OS related events
1447
  chEvtRegisterMask(((aos_shell_t*)shell)->os.eventSource, &(((aos_shell_t*)shell)->os.eventListener), AOS_SHELL_EVENTMASK_OS);
1448
  // register events to all input channels
1449
  for (channel = ((aos_shell_t*)shell)->stream.channel; channel != NULL; channel = channel->next) {
1450 dd8738ea Thomas Schöpping
    chEvtRegisterMaskWithFlags(&(channel->asyncchannel->event), &(channel->listener), AOS_SHELL_EVENTMASK_INPUT, channel->listener.wflags);
1451 ba516b61 Thomas Schöpping
  }
1452 e545e620 Thomas Schöpping
1453
  // fire start event
1454
  chEvtBroadcastFlags(&(((aos_shell_t*)shell)->eventSource), AOS_SHELL_EVTFLAG_START);
1455
1456 ba516b61 Thomas Schöpping
  // print the prompt for the first time
1457
  _printPrompt((aos_shell_t*)shell);
1458
1459 e545e620 Thomas Schöpping
  // enter thread loop
1460
  while (!chThdShouldTerminateX()) {
1461 ba516b61 Thomas Schöpping
    // wait for event and handle it accordingly
1462
    eventmask = chEvtWaitOne(ALL_EVENTS);
1463
1464
    // handle event
1465
    switch (eventmask) {
1466
1467
      // OS related events
1468
      case AOS_SHELL_EVENTMASK_OS:
1469
      {
1470
        eventflags = chEvtGetAndClearFlags(&((aos_shell_t*)shell)->os.eventListener);
1471
        // handle shutdown/restart events
1472
        if (eventflags & AOS_SYSTEM_EVENTFLAGS_SHUTDOWN) {
1473
          chThdTerminate(((aos_shell_t*)shell)->thread);
1474
        } else {
1475
          // print an error message
1476
          chprintf((BaseSequentialStream*)&((aos_shell_t*)shell)->stream, "\nERROR: unknown OS event received (0x%08X)\n", eventflags);
1477
        }
1478 e545e620 Thomas Schöpping
        break;
1479
      }
1480
1481 ba516b61 Thomas Schöpping
      // input events
1482
      case AOS_SHELL_EVENTMASK_INPUT:
1483
      {
1484
        // check and handle all channels
1485
        channel = ((aos_shell_t*)shell)->stream.channel;
1486
        while (channel != NULL) {
1487
          eventflags = chEvtGetAndClearFlags(&channel->listener);
1488
          // if there is new input
1489
          if (eventflags & CHN_INPUT_AVAILABLE) {
1490 dd8738ea Thomas Schöpping
            // read input from channel
1491
            readeval = _readChannel((aos_shell_t*)shell, channel, &nchars);
1492
            // parse input line to argument list only if the input shall be executed
1493
            nargs = (readeval == AOS_SUCCESS && nchars > 0) ? _parseArguments((aos_shell_t*)shell) : 0;
1494
            // check number of arguments
1495
            if (nargs > ((aos_shell_t*)shell)->arglistsize) {
1496
              // error too many arguments
1497
              chprintf((BaseSequentialStream*)&((aos_shell_t*)shell)->stream, "\ttoo many arguments\n");
1498
            } else if (nargs > 0) {
1499
              // search command list for arg[0] and execute callback
1500
              cmd = ((aos_shell_t*)shell)->commands;
1501
              while (cmd != NULL) {
1502
                if (strcmp(((aos_shell_t*)shell)->arglist[0], cmd->name) == 0) {
1503
                  ((aos_shell_t*)shell)->execstatus.command = cmd;
1504
                  chEvtBroadcastFlags(&(((aos_shell_t*)shell)->eventSource), AOS_SHELL_EVTFLAG_EXEC);
1505
                  ((aos_shell_t*)shell)->execstatus.retval = cmd->callback((BaseSequentialStream*)&((aos_shell_t*)shell)->stream, nargs, ((aos_shell_t*)shell)->arglist);
1506
                  chEvtBroadcastFlags(&(((aos_shell_t*)shell)->eventSource), AOS_SHELL_EVTFLAG_DONE);
1507
                  // notify if the command was not successful
1508
                  if (((aos_shell_t*)shell)->execstatus.retval != 0) {
1509
                    chprintf((BaseSequentialStream*)&((aos_shell_t*)shell)->stream, "command returned exit status %d\n", ((aos_shell_t*)shell)->execstatus.retval);
1510 ba516b61 Thomas Schöpping
                  }
1511 dd8738ea Thomas Schöpping
                  break;
1512 ba516b61 Thomas Schöpping
                }
1513 dd8738ea Thomas Schöpping
                cmd = cmd->next;
1514
              } /* end of while */
1515 e545e620 Thomas Schöpping
1516 dd8738ea Thomas Schöpping
              // if no matching command was found, print an error
1517
              if (cmd == NULL) {
1518
                chprintf((BaseSequentialStream*)&((aos_shell_t*)shell)->stream, "%s: command not found\n", ((aos_shell_t*)shell)->arglist[0]);
1519 ba516b61 Thomas Schöpping
              }
1520
            }
1521 dd8738ea Thomas Schöpping
1522
            // reset some internal variables and eprint a new prompt
1523
            if (readeval == AOS_SUCCESS && !chThdShouldTerminateX()) {
1524
              ((aos_shell_t*)shell)->inputdata.cursorpos = 0;
1525
              ((aos_shell_t*)shell)->inputdata.lineend = 0;
1526
              _printPrompt((aos_shell_t*)shell);
1527 ba516b61 Thomas Schöpping
            }
1528 e545e620 Thomas Schöpping
          }
1529 ba516b61 Thomas Schöpping
1530
          // iterate to next channel
1531
          channel = channel->next;
1532 e545e620 Thomas Schöpping
        }
1533 ba516b61 Thomas Schöpping
        break;
1534 e545e620 Thomas Schöpping
      }
1535 ba516b61 Thomas Schöpping
1536
      // other events
1537
      default:
1538
      {
1539
        // print an error message
1540 1e5f7648 Thomas Schöpping
        chprintf((BaseSequentialStream*)&((aos_shell_t*)shell)->stream, "\nSHELL: ERROR: unknown event received (0x%08X)\n", eventmask);
1541 ba516b61 Thomas Schöpping
        break;
1542 e545e620 Thomas Schöpping
      }
1543
1544 ba516b61 Thomas Schöpping
    } /* end of switch */
1545
1546
  } /* end of while */
1547 e545e620 Thomas Schöpping
1548
  // fire event and exit the thread
1549
  chSysLock();
1550
  chEvtBroadcastFlagsI(&(((aos_shell_t*)shell)->eventSource), AOS_SHELL_EVTFLAG_EXIT);
1551
  chThdExitS(MSG_OK);
1552
  // no chSysUnlock() required since the thread has been terminated an all waiting threads have been woken up
1553
}
1554 ba516b61 Thomas Schöpping
1555
#endif /* AMIROOS_CFG_SHELL_ENABLE == true */
1556 53710ca3 Marc Rothmann
1557
/** @} */