Statistics
| Branch: | Tag: | Revision:

amiro-os / core / src / aos_shell.c @ 4c72a54c

History | View | Annotate | Download (54.761 KB)

1 e545e620 Thomas Schöpping
/*
2
AMiRo-OS is an operating system designed for the Autonomous Mini Robot (AMiRo) platform.
3 84f0ce9e Thomas Schöpping
Copyright (C) 2016..2019  Thomas Schöpping et al.
4 e545e620 Thomas Schöpping

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 3940ba8a Thomas Schöpping
#include <amiroos.h>
29
#include <string.h>
30 e545e620 Thomas Schöpping
31 2dd2e257 Thomas Schöpping
#if (AMIROOS_CFG_SHELL_ENABLE == true) || (AMIROOS_CFG_TESTS_ENABLE == true)
32 3940ba8a Thomas Schöpping
33 f3ac1c96 Thomas Schöpping
/******************************************************************************/
34
/* LOCAL DEFINITIONS                                                          */
35
/******************************************************************************/
36 ba516b61 Thomas Schöpping
37
/**
38
 * @brief   Event mask to be set on OS related events.
39
 */
40
#define AOS_SHELL_EVENTMASK_OS                  EVENT_MASK(0)
41
42
/**
43
 * @brief   Event mask to be set on a input event.
44
 */
45
#define AOS_SHELL_EVENTMASK_INPUT               EVENT_MASK(1)
46
47 f3ac1c96 Thomas Schöpping
/******************************************************************************/
48
/* EXPORTED VARIABLES                                                         */
49
/******************************************************************************/
50
51
/******************************************************************************/
52
/* LOCAL TYPES                                                                */
53
/******************************************************************************/
54
55
/*
56
 * forward declarations
57
 */
58
static size_t _channelwrite(void *instance, const uint8_t *bp, size_t n);
59
static size_t _channelread(void *instance, uint8_t *bp, size_t n);
60
static msg_t _channelput(void *instance, uint8_t b);
61
static msg_t _channelget(void *instance);
62
static msg_t _channelputt(void *instance, uint8_t b, sysinterval_t time);
63
static msg_t _channelgett(void *instance, sysinterval_t time);
64
static size_t _channelwritet(void *instance, const uint8_t *bp, size_t n, sysinterval_t time);
65
static size_t _channelreadt(void *instance, uint8_t *bp, size_t n, sysinterval_t time);
66
static msg_t _channelctl(void *instance, unsigned int operation, void *arg);
67
static size_t _streamwrite(void *instance, const uint8_t *bp, size_t n);
68
static size_t _stremread(void *instance, uint8_t *bp, size_t n);
69
static msg_t _streamput(void *instance, uint8_t b);
70
static msg_t _streamget(void *instance);
71
72
static const struct AosShellChannelVMT _channelvmt = {
73
  (size_t) 0,
74
  _channelwrite,
75
  _channelread,
76
  _channelput,
77
  _channelget,
78
  _channelputt,
79
  _channelgett,
80
  _channelwritet,
81
  _channelreadt,
82
  _channelctl,
83
};
84
85
static const struct AosShellStreamVMT _streamvmt = {
86
  (size_t) 0,
87
  _streamwrite,
88
  _stremread,
89
  _streamput,
90
  _streamget,
91
};
92
93
/**
94
 * @brief   Enumerator of special keyboard keys.
95
 */
96
typedef enum special_key {
97 cc33217b Thomas Schöpping
  KEY_UNKNOWN,          /**< any/unknow key */
98
  KEY_AMBIGUOUS,        /**< key is ambiguous */
99
  KEY_TAB,              /**< tabulator key */
100
  KEY_ESCAPE,           /**< escape key */
101
  KEY_BACKSPACE,        /**< backspace key */
102
  KEY_INSERT,           /**< insert key */
103
  KEY_DELETE,           /**< delete key */
104
  KEY_HOME,             /**< home key */
105
  KEY_END,              /**< end key */
106
  KEY_PAGE_UP,          /**< page up key */
107
  KEY_PAGE_DOWN,        /**< page down key */
108
  KEY_ARROW_UP,         /**< arrow up key */
109
  KEY_ARROW_DOWN,       /**< arrow down key */
110
  KEY_ARROW_LEFT,       /**< arrow left key */
111
  KEY_ARROW_RIGHT,      /**< arrow right key */
112
  KEY_CTRL_ARROW_UP,    /**< CTRL + arrow up key */
113
  KEY_CTRL_ARROW_DOWN,  /**< CTRL + arrow down key */
114
  KEY_CTRL_ARROW_LEFT,  /**< CTRL + arrow left key */
115
  KEY_CTRL_ARROW_RIGHT, /**< CTRL + arrow right key */
116 f3ac1c96 Thomas Schöpping
} special_key_t;
117
118
/**
119
 * @brief   Enumerator for case (in)sensitive character matching.
120
 */
121
typedef enum charmatch {
122
  CHAR_MATCH_NOT    = 0,  /**< Characters do not match at all. */
123
  CHAR_MATCH_NCASE  = 1,  /**< Characters would match case insensitive. */
124
  CHAR_MATCH_CASE   = 2,  /**< Characters do match with case. */
125
} charmatch_t;
126
127
/******************************************************************************/
128
/* LOCAL VARIABLES                                                            */
129
/******************************************************************************/
130
131
/******************************************************************************/
132
/* LOCAL FUNCTIONS                                                            */
133
/******************************************************************************/
134
135 ba516b61 Thomas Schöpping
/**
136
 * @brief   Implementation of the BaseAsynchronous write() method (inherited from BaseSequentialStream).
137
 */
138
static size_t _channelwrite(void *instance, const uint8_t *bp, size_t n)
139
{
140
  if (((AosShellChannel*)instance)->flags & AOS_SHELLCHANNEL_OUTPUT_ENABLED) {
141 dd8738ea Thomas Schöpping
    return streamWrite(((AosShellChannel*)instance)->asyncchannel, bp, n);
142 ba516b61 Thomas Schöpping
  } else {
143
    return 0;
144
  }
145
}
146
147
/**
148
 * @brief   Implementation of the BaseAsynchronous read() method (inherited from BaseSequentialStream).
149
 */
150
static size_t _channelread(void *instance, uint8_t *bp, size_t n)
151
{
152 dd8738ea Thomas Schöpping
  if (((AosShellChannel*)instance)->flags & AOS_SHELLCHANNEL_INPUT_ENABLED) {
153
    return streamRead(((AosShellChannel*)instance)->asyncchannel, bp, n);
154
  } else {
155
    return 0;
156
  }
157 ba516b61 Thomas Schöpping
}
158
159
/**
160
 * @brief   Implementation of the BaseAsynchronous put() method (inherited from BaseSequentialStream).
161
 */
162
static msg_t _channelput(void *instance, uint8_t b)
163
{
164
  if (((AosShellChannel*)instance)->flags & AOS_SHELLCHANNEL_OUTPUT_ENABLED) {
165 dd8738ea Thomas Schöpping
    return streamPut(((AosShellChannel*)instance)->asyncchannel, b);
166 ba516b61 Thomas Schöpping
  } else {
167
    return MSG_RESET;
168
  }
169
}
170
171
/**
172
 * @brief   Implementation of the BaseAsynchronous get() method (inherited from BaseSequentialStream).
173
 */
174
static msg_t _channelget(void *instance)
175
{
176 dd8738ea Thomas Schöpping
  if (((AosShellChannel*)instance)->flags & AOS_SHELLCHANNEL_INPUT_ENABLED) {
177
    return streamGet(((AosShellChannel*)instance)->asyncchannel);
178
  } else {
179
    return MSG_RESET;
180
  }
181 ba516b61 Thomas Schöpping
}
182
183
/**
184
 * @brief   Implementation of the BaseAsynchronous putt() method.
185
 */
186 2c99037f Marc Rothmann
static msg_t _channelputt(void *instance, uint8_t b, sysinterval_t time)
187 ba516b61 Thomas Schöpping
{
188
  if (((AosShellChannel*)instance)->flags & AOS_SHELLCHANNEL_OUTPUT_ENABLED) {
189 dd8738ea Thomas Schöpping
    return chnPutTimeout(((AosShellChannel*)instance)->asyncchannel, b, time);
190 ba516b61 Thomas Schöpping
  } else {
191
    return MSG_RESET;
192
  }
193
}
194
195
/**
196
 * @brief   Implementation of the BaseAsynchronous gett() method.
197
 */
198 2c99037f Marc Rothmann
static msg_t _channelgett(void *instance, sysinterval_t time)
199 ba516b61 Thomas Schöpping
{
200 dd8738ea Thomas Schöpping
  if (((AosShellChannel*)instance)->flags & AOS_SHELLCHANNEL_INPUT_ENABLED) {
201
    return chnGetTimeout(((AosShellChannel*)instance)->asyncchannel, time);
202
  } else {
203
    return MSG_RESET;
204
  }
205 ba516b61 Thomas Schöpping
}
206
207
/**
208
 * @brief   Implementation of the BaseAsynchronous writet() method.
209
 */
210 2c99037f Marc Rothmann
static size_t _channelwritet(void *instance, const uint8_t *bp, size_t n, sysinterval_t time)
211 ba516b61 Thomas Schöpping
{
212
  if (((AosShellChannel*)instance)->flags & AOS_SHELLCHANNEL_OUTPUT_ENABLED) {
213 dd8738ea Thomas Schöpping
    return chnWriteTimeout(((AosShellChannel*)instance)->asyncchannel, bp, n, time);
214 ba516b61 Thomas Schöpping
  } else {
215
    return 0;
216
  }
217
}
218
219
/**
220
 * @brief   Implementation of the BaseAsynchronous readt() method.
221
 */
222 2c99037f Marc Rothmann
static size_t _channelreadt(void *instance, uint8_t *bp, size_t n, sysinterval_t time)
223 ba516b61 Thomas Schöpping
{
224 dd8738ea Thomas Schöpping
  if (((AosShellChannel*)instance)->flags & AOS_SHELLCHANNEL_INPUT_ENABLED) {
225
    return chnReadTimeout(((AosShellChannel*)instance)->asyncchannel, bp, n, time);
226
  } else {
227
    return 0;
228
  }
229 ba516b61 Thomas Schöpping
}
230
231 2c99037f Marc Rothmann
/**
232
 * @brief   Implementation of the BaseAsynchronousChannel ctl() method.
233
 */
234 f3ac1c96 Thomas Schöpping
static msg_t _channelctl(void *instance, unsigned int operation, void *arg)
235
{
236 2c99037f Marc Rothmann
  (void) instance;
237
238
  switch (operation) {
239
  case CHN_CTL_NOP:
240
    osalDbgCheck(arg == NULL);
241
    break;
242
  case CHN_CTL_INVALID:
243
    osalDbgAssert(false, "invalid CTL operation");
244
    break;
245
  default:
246
    break;
247
  }
248
  return MSG_OK;
249
}
250
251 ba516b61 Thomas Schöpping
static size_t _streamwrite(void *instance, const uint8_t *bp, size_t n)
252
{
253
  aosDbgCheck(instance != NULL);
254
255
  // local variables
256
  AosShellChannel* channel = ((AosShellStream*)instance)->channel;
257
  size_t bytes;
258
  size_t maxbytes = 0;
259
260
  // iterate through the list of channels
261
  while (channel != NULL) {
262
    bytes = streamWrite(channel, bp, n);
263
    maxbytes = (bytes > maxbytes) ? bytes : maxbytes;
264
    channel = channel->next;
265
  }
266
267
  return maxbytes;
268
}
269
270
static size_t _stremread(void *instance, uint8_t *bp, size_t n)
271
{
272
  (void)instance;
273
  (void)bp;
274
  (void)n;
275
276
  return 0;
277
}
278
279
static msg_t _streamput(void *instance, uint8_t b)
280
{
281
  aosDbgCheck(instance != NULL);
282
283
  // local variables
284
  AosShellChannel* channel = ((AosShellStream*)instance)->channel;
285 dd8738ea Thomas Schöpping
  msg_t ret = MSG_OK;
286 ba516b61 Thomas Schöpping
287
  // iterate through the list of channels
288
  while (channel != NULL) {
289 dd8738ea Thomas Schöpping
    msg_t ret_ = streamPut(channel, b);
290
    ret = (ret_ < ret) ? ret_ : ret;
291 ba516b61 Thomas Schöpping
    channel = channel->next;
292
  }
293
294 dd8738ea Thomas Schöpping
  return ret;
295 ba516b61 Thomas Schöpping
}
296
297
static msg_t _streamget(void *instance)
298
{
299
  (void)instance;
300
301
  return 0;
302
}
303
304 e545e620 Thomas Schöpping
/**
305
 * @brief   Print the shell prompt
306
 * @details Depending on the configuration flags, the system uptime is printed before the prompt string.
307
 *
308
 * @param[in] shell   Pointer to the shell object.
309
 */
310
static void _printPrompt(aos_shell_t* shell)
311
{
312
  aosDbgCheck(shell != NULL);
313
314 8399aeae Thomas Schöpping
  // print some time informattion before prompt if configured
315
  if (shell->config & (AOS_SHELL_CONFIG_PROMPT_UPTIME | AOS_SHELL_CONFIG_PROMPT_DATETIME)) {
316
    // printf the system uptime
317
    if ((shell->config & (AOS_SHELL_CONFIG_PROMPT_UPTIME | AOS_SHELL_CONFIG_PROMPT_DATETIME)) == AOS_SHELL_CONFIG_PROMPT_UPTIME) {
318
      // get current system uptime
319
      aos_timestamp_t uptime;
320
      aosSysGetUptime(&uptime);
321
322
      chprintf((BaseSequentialStream*)&shell->stream, "[%01u:%02u:%02u:%02u:%03u:%03u] ",
323
               (uint32_t)(uptime / MICROSECONDS_PER_DAY),
324
               (uint8_t)(uptime % MICROSECONDS_PER_DAY / MICROSECONDS_PER_HOUR),
325
               (uint8_t)(uptime % MICROSECONDS_PER_HOUR / MICROSECONDS_PER_MINUTE),
326
               (uint8_t)(uptime % MICROSECONDS_PER_MINUTE / MICROSECONDS_PER_SECOND),
327
               (uint16_t)(uptime % MICROSECONDS_PER_SECOND / MICROSECONDS_PER_MILLISECOND),
328
               (uint16_t)(uptime % MICROSECONDS_PER_MILLISECOND / MICROSECONDS_PER_MICROSECOND));
329
    }
330 23437e98 Thomas Schöpping
#if (HAL_USE_RTC == TRUE)
331 8399aeae Thomas Schöpping
    else if ((shell->config & (AOS_SHELL_CONFIG_PROMPT_UPTIME | AOS_SHELL_CONFIG_PROMPT_DATETIME)) == AOS_SHELL_CONFIG_PROMPT_DATETIME) {
332
      // get current RTC time
333
      struct tm dt;
334
      aosSysGetDateTime(&dt);
335
      chprintf((BaseSequentialStream*)&shell->stream, "[%02u-%02u-%04u|%02u:%02u:%02u] ",
336
               dt.tm_mday,
337
               dt.tm_mon + 1,
338
               dt.tm_year + 1900,
339
               dt.tm_hour,
340
               dt.tm_min,
341
               dt.tm_sec);
342
    }
343 7de0cc90 Thomas Schöpping
#endif /* (HAL_USE_RTC == TRUE) */
344 8399aeae Thomas Schöpping
    else {
345
      aosDbgAssert(false);
346
    }
347 e545e620 Thomas Schöpping
  }
348
349
  // print the actual prompt string
350
  if (shell->prompt && !(shell->config & AOS_SHELL_CONFIG_PROMPT_MINIMAL)) {
351 ba516b61 Thomas Schöpping
    chprintf((BaseSequentialStream*)&shell->stream, "%s$ ", shell->prompt);
352 e545e620 Thomas Schöpping
  } else {
353 ba516b61 Thomas Schöpping
    chprintf((BaseSequentialStream*)&shell->stream, "%>$ ");
354 e545e620 Thomas Schöpping
  }
355
356
  return;
357
}
358
359
/**
360
 * @brief   Interprete a escape sequence
361 d96ce104 Thomas Schöpping
 * @details This function interpretes escape sequences (starting with ASCII
362
 *          "Escape" character 0x1B) according to the VT100 / VT52 ANSI escape
363
 *          sequence definitions.
364
 * @note    Only the most important escape sequences are implemented yet.
365 e545e620 Thomas Schöpping
 *
366
 * @param[in] seq   Character sequence to interprete.
367
 *                  Must be terminated by NUL byte.
368
 *
369
 * @return          A @p special_key value.
370
 */
371
static special_key_t _interpreteEscapeSequence(const char seq[])
372
{
373
  // local variables
374 cc33217b Thomas Schöpping
  char str[AOS_SHELL_ESCSEQUENCE_LENGTH];
375
  unsigned long strl = 0;
376
  const unsigned long seql = strlen(seq);
377 e545e620 Thomas Schöpping
  bool ambiguous = false;
378
379
  // TAB
380
  /* not supported yet; use "\x09" instead */
381
382
  // BACKSPACE
383
  /* not supported yet; use "\x08" instead */
384
385
  // ESCAPE
386 cc33217b Thomas Schöpping
  strncpy(str, "\x1B", AOS_SHELL_ESCSEQUENCE_LENGTH);
387
  strl = strlen(str);
388
  if (seql == strl && strncmp(seq, str, seql) == 0) {
389 e545e620 Thomas Schöpping
    return KEY_ESCAPE;
390 cc33217b Thomas Schöpping
  } else if(seql < strl && strncmp(seq, str, seql) == 0) {
391
    ambiguous = true;
392 e545e620 Thomas Schöpping
  }
393
394
  // INSERT
395 cc33217b Thomas Schöpping
  strncpy(str, "\x1B\x5B\x32\x7E", AOS_SHELL_ESCSEQUENCE_LENGTH);
396
  strl = strlen(str);
397
  if (seql == strl && strncmp(seq, str, seql) == 0) {
398 e545e620 Thomas Schöpping
    return KEY_INSERT;
399 cc33217b Thomas Schöpping
  } else if(seql < strl && strncmp(seq, str, seql) == 0) {
400
    ambiguous = true;
401 e545e620 Thomas Schöpping
  }
402
403
  // DELETE
404 cc33217b Thomas Schöpping
  strncpy(str, "\x1B\x5B\x33\x7E", AOS_SHELL_ESCSEQUENCE_LENGTH);
405
  strl = strlen(str);
406
  if (seql == strl && strncmp(seq, str, seql) == 0) {
407 e545e620 Thomas Schöpping
    return KEY_DELETE;
408 cc33217b Thomas Schöpping
  } else if(seql < strl && strncmp(seq, str, seql) == 0) {
409
    ambiguous = true;
410 e545e620 Thomas Schöpping
  }
411
412
  // HOME
413 cc33217b Thomas Schöpping
  strncpy(str, "\x1B\x5B\x48", AOS_SHELL_ESCSEQUENCE_LENGTH);
414
  strl = strlen(str);
415
  if (seql == strl && strncmp(seq, str, seql) == 0) {
416 e545e620 Thomas Schöpping
    return KEY_HOME;
417 cc33217b Thomas Schöpping
  } else if(seql < strl && strncmp(seq, str, seql) == 0) {
418
    ambiguous = true;
419 e545e620 Thomas Schöpping
  }
420
421
  // END
422 cc33217b Thomas Schöpping
  strncpy(str, "\x1B\x5B\x46", AOS_SHELL_ESCSEQUENCE_LENGTH);
423
  strl = strlen(str);
424
  if (seql == strl && strncmp(seq, str, seql) == 0) {
425 e545e620 Thomas Schöpping
    return KEY_END;
426 cc33217b Thomas Schöpping
  } else if(seql < strl && strncmp(seq, str, seql) == 0) {
427
    ambiguous = true;
428 e545e620 Thomas Schöpping
  }
429
430
  // PAGE UP
431 cc33217b Thomas Schöpping
  strncpy(str, "\x1B\x5B\x35\x7E", AOS_SHELL_ESCSEQUENCE_LENGTH);
432
  strl = strlen(str);
433
  if (seql == strl && strncmp(seq, str, seql) == 0) {
434 e545e620 Thomas Schöpping
    return KEY_PAGE_UP;
435 cc33217b Thomas Schöpping
  } else if(seql < strl && strncmp(seq, str, seql) == 0) {
436
    ambiguous = true;
437 e545e620 Thomas Schöpping
  }
438
439
  // PAGE DOWN
440 cc33217b Thomas Schöpping
  strncpy(str, "\x1B\x5B\x36\x7E", AOS_SHELL_ESCSEQUENCE_LENGTH);
441
  strl = strlen(str);
442
  if (seql == strl && strncmp(seq, str, seql) == 0) {
443 e545e620 Thomas Schöpping
    return KEY_PAGE_DOWN;
444 cc33217b Thomas Schöpping
  } else if(seql < strl && strncmp(seq, str, seql) == 0) {
445
    ambiguous = true;
446 e545e620 Thomas Schöpping
  }
447
448
  // ARROW UP
449 cc33217b Thomas Schöpping
  strncpy(str, "\x1B\x5B\x41", AOS_SHELL_ESCSEQUENCE_LENGTH);
450
  strl = strlen(str);
451
  if (seql == strl && strncmp(seq, str, seql) == 0) {
452 e545e620 Thomas Schöpping
    return KEY_ARROW_UP;
453 cc33217b Thomas Schöpping
  } else if(seql < strl && strncmp(seq, str, seql) == 0) {
454
    ambiguous = true;
455 e545e620 Thomas Schöpping
  }
456
457
  // ARROW DOWN
458 cc33217b Thomas Schöpping
  strncpy(str, "\x1B\x5B\x42", AOS_SHELL_ESCSEQUENCE_LENGTH);
459
  strl = strlen(str);
460
  if (seql == strl && strncmp(seq, str, seql) == 0) {
461 e545e620 Thomas Schöpping
    return KEY_ARROW_DOWN;
462 cc33217b Thomas Schöpping
  } else if (seql < strl && strncmp(seq, str, seql) == 0) {
463
    ambiguous = true;
464 e545e620 Thomas Schöpping
  }
465
466
  // ARROW LEFT
467 cc33217b Thomas Schöpping
  strncpy(str, "\x1B\x5B\x44", AOS_SHELL_ESCSEQUENCE_LENGTH);
468
  strl = strlen(str);
469
  if (seql == strl && strncmp(seq, str, seql) == 0) {
470 e545e620 Thomas Schöpping
    return KEY_ARROW_LEFT;
471 cc33217b Thomas Schöpping
  } else if (seql < strl && strncmp(seq, str, seql) == 0) {
472
    ambiguous = true;
473 e545e620 Thomas Schöpping
  }
474
475
  // ARROW RIGHT
476 cc33217b Thomas Schöpping
  strncpy(str, "\x1B\x5B\x43", AOS_SHELL_ESCSEQUENCE_LENGTH);
477
  strl = strlen(str);
478
  if (seql == strl && strncmp(seq, str, seql) == 0) {
479 e545e620 Thomas Schöpping
    return KEY_ARROW_RIGHT;
480 cc33217b Thomas Schöpping
  } else if (seql < strl && strncmp(seq, str, seql) == 0) {
481
    ambiguous = true;
482
  }
483
484
  // CTRL + ARROW UP
485
  strncpy(str, "\x1B\x5B\x31\x3B\x35\x41", AOS_SHELL_ESCSEQUENCE_LENGTH);
486
  strl = strlen(str);
487
  if (seql == strl && strncmp(seq, str, seql) == 0) {
488
    return KEY_CTRL_ARROW_UP;
489
  } else if(seql < strl && strncmp(seq, str, seql) == 0) {
490
    ambiguous = true;
491
  }
492
493
  // CTRL + ARROW DOWN
494
  strncpy(str, "\x1B\x5B\x31\x3B\x35\x42", AOS_SHELL_ESCSEQUENCE_LENGTH);
495
  strl = strlen(str);
496
  if (seql == strl && strncmp(seq, str, seql) == 0) {
497
    return KEY_CTRL_ARROW_DOWN;
498
  } else if(seql < strl && strncmp(seq, str, seql) == 0) {
499
    ambiguous = true;
500
  }
501
502
  // CTRL + ARROW LEFT
503
  strncpy(str, "\x1B\x5B\x31\x3B\x35\x44", AOS_SHELL_ESCSEQUENCE_LENGTH);
504
  strl = strlen(str);
505
  if (seql == strl && strncmp(seq, str, seql) == 0) {
506
    return KEY_CTRL_ARROW_LEFT;
507
  } else if(seql < strl && strncmp(seq, str, seql) == 0) {
508
    ambiguous = true;
509
  }
510
511
  // CTRL + ARROW RIGHT
512
  strncpy(str, "\x1B\x5B\x31\x3B\x35\x43", AOS_SHELL_ESCSEQUENCE_LENGTH);
513
  strl = strlen(str);
514
  if (seql == strl && strncmp(seq, str, seql) == 0) {
515
    return KEY_CTRL_ARROW_RIGHT;
516
  } else if(seql < strl && strncmp(seq, str, seql) == 0) {
517
    ambiguous = true;
518 e545e620 Thomas Schöpping
  }
519
520
  return ambiguous ? KEY_AMBIGUOUS : KEY_UNKNOWN;
521
}
522
523
/**
524
 * @brief   Move the cursor in the terminal
525
 *
526
 * @param[in] shell   Pointer to the shell object.
527
 * @param[in] from    Starting position of the cursor.
528
 * @param[in] to      Target position to move the cursor to.
529
 *
530
 * @return            The number of positions moved.
531
 */
532
static int _moveCursor(aos_shell_t* shell, const size_t from, const size_t to)
533
{
534
  aosDbgCheck(shell != NULL);
535
536
  // local variables
537
  size_t pos = from;
538
539
  // move cursor left by printing backspaces
540
  while (pos > to) {
541 ba516b61 Thomas Schöpping
    streamPut(&shell->stream, '\b');
542 e545e620 Thomas Schöpping
    --pos;
543
  }
544
545
  // move cursor right by printing line content
546
  while (pos < to) {
547 cc33217b Thomas Schöpping
    streamPut(&shell->stream, shell->input.line[pos]);
548 e545e620 Thomas Schöpping
    ++pos;
549
  }
550
551
  return (int)pos - (int)from;
552
}
553
554
/**
555
 * @brief   Print content of the shell line
556
 *
557
 * @param[in] shell   Pointer to the shell object.
558
 * @param[in] from    First position to start printing from.
559
 * @param[in] to      Position after the last character to print.
560
 *
561
 * @return            Number of characters printed.
562
 */
563
static inline size_t _printLine(aos_shell_t* shell, const size_t from, const size_t to)
564
{
565
  aosDbgCheck(shell != NULL);
566
567
  // local variables
568
  size_t cnt;
569
570
  for (cnt = 0; from + cnt < to; ++cnt) {
571 cc33217b Thomas Schöpping
    streamPut(&shell->stream, shell->input.line[from + cnt]);
572 e545e620 Thomas Schöpping
  }
573
574
  return cnt;
575
}
576
577 cc33217b Thomas Schöpping
static int _readChar(aos_shell_t* shell, const char c) {
578
  aosDbgCheck(shell != NULL);
579
580
  // check whether input line is already full
581
  if (shell->inputdata.lineend + 1 >= shell->input.width) {
582
    return 0;
583
  } else {
584
    // clear old line content on first input
585
    if (shell->inputdata.noinput) {
586
      memset(shell->input.line, '\0', shell->input.width);
587
      shell->inputdata.noinput = false;
588
    }
589
    // overwrite content
590
    if (shell->config & AOS_SHELL_CONFIG_INPUT_OVERWRITE) {
591
      shell->input.line[shell->inputdata.cursorpos] = c;
592
      ++shell->inputdata.cursorpos;
593
      shell->inputdata.lineend = (shell->inputdata.cursorpos > shell->inputdata.lineend) ? shell->inputdata.cursorpos : shell->inputdata.lineend;
594
      streamPut(&shell->stream, (uint8_t)c);
595
    }
596
    // insert character
597
    else {
598
      memmove(&(shell->input.line[shell->inputdata.cursorpos+1]), &(shell->input.line[shell->inputdata.cursorpos]), shell->inputdata.lineend - shell->inputdata.cursorpos);
599
      shell->input.line[shell->inputdata.cursorpos] = c;
600
      ++shell->inputdata.lineend;
601
      _printLine(shell, shell->inputdata.cursorpos, shell->inputdata.lineend);
602
      ++shell->inputdata.cursorpos;
603
      _moveCursor(shell, shell->inputdata.lineend, shell->inputdata.cursorpos);
604
    }
605
    return 1;
606
  }
607
}
608
609 e545e620 Thomas Schöpping
/**
610
 * @brief   Compare two characters.
611
 *
612
 * @param[in] lhs       First character to compare.
613
 * @param[in] rhs       Second character to compare.
614
 *
615
 * @return              How well the characters match.
616
 */
617
static inline charmatch_t _charcmp(char lhs, char rhs)
618
{
619
  // if lhs is a upper case letter and rhs is a lower case letter
620
  if (lhs >= 'A' && lhs <= 'Z' && rhs >= 'a' && rhs <= 'z') {
621
    return (lhs == (rhs - 'a' + 'A')) ? CHAR_MATCH_NCASE : CHAR_MATCH_NOT;
622
  }
623
  // if lhs is a lower case letter and rhs is a upper case letter
624
  else if (lhs >= 'a' && lhs <= 'z' && rhs >= 'A' && rhs <= 'Z') {
625
    return ((lhs - 'a' + 'A') == rhs) ? CHAR_MATCH_NCASE : CHAR_MATCH_NOT;
626
  }
627
  // default
628
  else {
629
    return (lhs == rhs) ? CHAR_MATCH_CASE : CHAR_MATCH_NOT;
630
  }
631
}
632
633
/**
634
 * @brief   Maps an character from ASCII to a modified custom encoding.
635
 * @details The custom character encoding is very similar to ASCII and has the following structure:
636
 *          0x00=NULL ... 0x40='@' (identically to ASCII)
637
 *          0x4A='a'; 0x4B='A'; 0x4C='b'; 0x4D='B' ... 0x73='z'; 0x74='Z' (custom letter order)
638
 *          0x75='[' ... 0x7A='`' (0x5B..0x60 is ASCII)
639
 *          0x7B='{' ... 0x7F=DEL (identically to ASCII)
640
 *
641
 * @param[in] c   Character to map to the custom encoding.
642
 *
643
 * @return    The customly encoded character.
644
 */
645
static inline char _mapAscii2Custom(const char c)
646
{
647
  if (c >= 'A' && c <= 'Z') {
648
    return ((c - 'A') * 2) + 'A' + 1;
649
  } else if (c > 'Z' && c < 'a') {
650
    return c + ('z' - 'a') + 1;
651
  } else if (c >= 'a' && c <= 'z') {
652
    return ((c - 'a') * 2) + 'A';
653
  } else {
654
    return c;
655
  }
656
}
657
658
/**
659
 * @brief   Compares two strings wrt letter case.
660
 * @details Comparisson uses a custom character encoding or mapping.
661
 *          See @p _mapAscii2Custom for details.
662
 *
663
 * @param[in] str1    First string to compare.
664
 * @param[in] str2    Second string to compare.
665
 * @param[in] cs      Flag indicating whether comparison shall be case sensitive.
666
 * @param[in,out] n   Maximum number of character to compare (in) and number of matching characters (out).
667
 *                    If a null pointer is specified, this parameter is ignored.
668
 *                    If the value pointed to is zero, comarison will not be limited.
669
 * @param[out] m      Optional indicator whether there was at least one case mismatch.
670
 *
671
 * @return      Integer value indicating the relationship between the strings.
672
 * @retval <0   The first character that does not match has a lower value in str1 than in str2.
673
 * @retval  0   The contents of both strings are equal.
674
 * @retval >0   The first character that does not match has a greater value in str1 than in str2.
675
 */
676
static int _strccmp(const char *str1, const char *str2, bool cs, size_t* n, charmatch_t* m)
677
{
678
  aosDbgCheck(str1 != NULL);
679
  aosDbgCheck(str2 != NULL);
680
681
  // initialize variables
682
  if (m) {
683
    *m = CHAR_MATCH_NOT;
684
  }
685
  size_t i = 0;
686
687
  // iterate through the strings
688
  while ((n == NULL) || (*n == 0) || (*n > 0 && i < *n)) {
689
    // break on NUL
690
    if (str1[i] == '\0' || str2[i] == '\0') {
691
      if (n) {
692
        *n = i;
693
      }
694
      break;
695
    }
696
    // compare character
697
    const charmatch_t match = _charcmp(str1[i], str2[i]);
698
    if ((match == CHAR_MATCH_CASE) || (!cs && match == CHAR_MATCH_NCASE)) {
699
      if (m != NULL && *m != CHAR_MATCH_NCASE) {
700
        *m = match;
701
      }
702
      ++i;
703
    } else {
704
      if (n) {
705
        *n = i;
706
      }
707
      break;
708
    }
709
  }
710
711
  return _mapAscii2Custom(str1[i]) - _mapAscii2Custom(str2[i]);
712
}
713
714 27286ba5 Thomas Schöpping
/**
715
 * @brief   Read input from a channel as long as there is data available.
716
 *
717
 * @param[in]   shell     Pointer to the shell object.
718
 * @param[in]   channel   The channel to read from.
719
 * @param[out]  n         Pointer to a variable to store the number of read characters to.
720
 *
721
 * @return
722
 */
723 ba516b61 Thomas Schöpping
static aos_status_t _readChannel(aos_shell_t* shell, AosShellChannel* channel, size_t* n)
724 e545e620 Thomas Schöpping
{
725
  aosDbgCheck(shell != NULL);
726 ba516b61 Thomas Schöpping
  aosDbgCheck(channel != NULL);
727
  aosDbgCheck(n != NULL);
728 e545e620 Thomas Schöpping
729
  // local variables
730 ba516b61 Thomas Schöpping
  aos_shellaction_t action = AOS_SHELL_ACTION_NONE;
731 e545e620 Thomas Schöpping
  char c;
732 dd8738ea Thomas Schöpping
  special_key_t key;
733 e545e620 Thomas Schöpping
734 ba516b61 Thomas Schöpping
  // initialize output variables
735
  *n = 0;
736
737
  // read character by character from the channel
738
  while (chnReadTimeout(channel, (uint8_t*)&c, 1, TIME_IMMEDIATE)) {
739 dd8738ea Thomas Schöpping
    key = KEY_UNKNOWN;
740 e545e620 Thomas Schöpping
741
    // parse escape sequence
742 cc33217b Thomas Schöpping
    if (strlen(shell->inputdata.escseq) > 0) {
743
      shell->inputdata.escseq[strlen(shell->inputdata.escseq)] = c;
744 ba516b61 Thomas Schöpping
      key = _interpreteEscapeSequence(shell->inputdata.escseq);
745 cc33217b Thomas Schöpping
      switch (key) {
746
        case KEY_AMBIGUOUS:
747
          // read next byte to resolve ambiguity
748
          continue;
749
        case KEY_UNKNOWN:
750
          // do nothing here, but handle the unknown sequence below
751
          break;
752
        default:
753
          // reset the sequence variable and buffer
754
          memset(shell->inputdata.escseq, '\0', sizeof(shell->inputdata.escseq)*sizeof(shell->inputdata.escseq[0]));
755
          break;
756 e545e620 Thomas Schöpping
      }
757
    }
758
759 ba516b61 Thomas Schöpping
    /* interprete keys or character */
760 e545e620 Thomas Schöpping
    {
761 ba516b61 Thomas Schöpping
      // default
762
      action = AOS_SHELL_ACTION_NONE;
763
764
      // printable character
765 cc33217b Thomas Schöpping
      if (key == KEY_UNKNOWN && strlen(shell->inputdata.escseq) == 0 && c >= '\x20' && c <= '\x7E') {
766 ba516b61 Thomas Schöpping
        action = AOS_SHELL_ACTION_READCHAR;
767
      }
768
769
      // tab key or character
770
      else if (key == KEY_TAB || c == '\x09') {
771
        /*
772
         * pressing tab once applies auto fill
773
         * pressing tab a second time prints suggestions
774
         */
775
        if (shell->inputdata.lastaction == AOS_SHELL_ACTION_AUTOFILL || shell->inputdata.lastaction == AOS_SHELL_ACTION_SUGGEST) {
776
          action = AOS_SHELL_ACTION_SUGGEST;
777 e545e620 Thomas Schöpping
        } else {
778 ba516b61 Thomas Schöpping
          action = AOS_SHELL_ACTION_AUTOFILL;
779 e545e620 Thomas Schöpping
        }
780 ba516b61 Thomas Schöpping
      }
781
782
      // INS key
783
      else if (key == KEY_INSERT) {
784
        action = AOS_SHELL_ACTION_INSERTTOGGLE;
785
      }
786
787
      // DEL key or character
788
      else if (key == KEY_DELETE || c == '\x7F') {
789
        // ignore if cursor is at very right
790
        if (shell->inputdata.cursorpos < shell->inputdata.lineend) {
791
          action = AOS_SHELL_ACTION_DELETEFORWARD;
792 e545e620 Thomas Schöpping
        }
793 ba516b61 Thomas Schöpping
      }
794
795
      // backspace key or character
796
      else if (key == KEY_BACKSPACE || c == '\x08') {
797
        // ignore if cursor is at very left
798
        if (shell->inputdata.cursorpos > 0) {
799
          action = AOS_SHELL_ACTION_DELETEBACKWARD;
800 e545e620 Thomas Schöpping
        }
801 ba516b61 Thomas Schöpping
      }
802
803 080149cf Thomas Schöpping
      // 'page up', 'arrow up', or key or CTRL + 'arrow up' key combination
804
      else if (key == KEY_PAGE_UP || key == KEY_ARROW_UP || key == KEY_CTRL_ARROW_UP) {
805 e545e620 Thomas Schöpping
        // ignore if there was some input
806 ba516b61 Thomas Schöpping
        if (shell->inputdata.noinput) {
807
          action = AOS_SHELL_ACTION_RECALLLAST;
808 e545e620 Thomas Schöpping
        }
809 ba516b61 Thomas Schöpping
      }
810
811 cc33217b Thomas Schöpping
      // 'page down' key, 'arrow down' key, 'end of test' character or 'end of transmission' character, or CTRL + 'arrow down' key combination
812
      else if (key == KEY_PAGE_DOWN || key == KEY_ARROW_DOWN || c == '\x03' || c == '\x03' || key == KEY_CTRL_ARROW_DOWN) {
813 e545e620 Thomas Schöpping
        // ignore if line is empty
814 ba516b61 Thomas Schöpping
        if (shell->inputdata.lineend > 0) {
815
          action = AOS_SHELL_ACTION_CLEAR;
816 e545e620 Thomas Schöpping
        }
817 ba516b61 Thomas Schöpping
      }
818
819
      // 'home' key
820
      else if (key == KEY_HOME) {
821 e545e620 Thomas Schöpping
        // ignore if cursor is very left
822 ba516b61 Thomas Schöpping
        if (shell->inputdata.cursorpos > 0) {
823
          action = AOS_SHELL_ACTION_CURSOR2START;
824 e545e620 Thomas Schöpping
        }
825 ba516b61 Thomas Schöpping
      }
826
827
      // 'end' key
828
      else if (key == KEY_END) {
829
        // ignore if cursos is very right
830
        if (shell->inputdata.cursorpos < shell->inputdata.lineend) {
831
          action = AOS_SHELL_ACTION_CURSOR2END;
832 e545e620 Thomas Schöpping
        }
833 ba516b61 Thomas Schöpping
      }
834
835
      // 'arrow left' key
836
      else if (key == KEY_ARROW_LEFT) {
837 e545e620 Thomas Schöpping
        // ignore if cursor is very left
838 ba516b61 Thomas Schöpping
        if (shell->inputdata.cursorpos > 0) {
839
          action = AOS_SHELL_ACTION_CURSORLEFT;
840 e545e620 Thomas Schöpping
        }
841 ba516b61 Thomas Schöpping
      }
842
843
      // 'arrow right' key
844
      else if (key == KEY_ARROW_RIGHT) {
845 cc33217b Thomas Schöpping
        // ignore if cursor is very right
846 ba516b61 Thomas Schöpping
        if (shell->inputdata.cursorpos < shell->inputdata.lineend) {
847
          action = AOS_SHELL_ACTION_CURSORRIGHT;
848 e545e620 Thomas Schöpping
        }
849 ba516b61 Thomas Schöpping
      }
850
851 cc33217b Thomas Schöpping
      // CTRL + 'arrow left' key combination
852
      else if (key == KEY_CTRL_ARROW_LEFT) {
853
        // ignore if cursor is very left
854
        if (shell->inputdata.cursorpos > 0) {
855
          action = AOS_SHELL_ACTION_CURSORWORDLEFT;
856
        }
857
      }
858
859
      // CTRL + 'arrow right' key combination
860
      else if (key == KEY_CTRL_ARROW_RIGHT) {
861
        // ignore if cursor is very right
862
        if (shell->inputdata.cursorpos < shell->inputdata.lineend) {
863
          action = AOS_SHELL_ACTION_CURSORWORDRIGHT;
864
        }
865
      }
866
867 ba516b61 Thomas Schöpping
      // carriage return ('\r') or line feed ('\n') character
868
      else if (c == '\x0D' || c == '\x0A') {
869
        action = AOS_SHELL_ACTION_EXECUTE;
870
      }
871
872
      // ESC key or [ESCAPE] character
873
      else if (key == KEY_ESCAPE || c == '\x1B') {
874
        action = AOS_SHELL_ACTION_ESCSTART;
875 e545e620 Thomas Schöpping
      }
876 cc33217b Thomas Schöpping
877
      // unknown escape sequence
878
      else if (key == KEY_UNKNOWN && strlen(shell->inputdata.escseq) > 0) {
879
        action = AOS_SHELL_ACTION_PRINTUNKNOWNSEQUENCE;
880
      }
881 e545e620 Thomas Schöpping
    }
882
883
    /* handle function */
884 ba516b61 Thomas Schöpping
    switch (action) {
885
      case AOS_SHELL_ACTION_READCHAR:
886
      {
887 cc33217b Thomas Schöpping
        if (_readChar(shell, c) == 0) {
888
          // line is full
889 ba516b61 Thomas Schöpping
          _moveCursor(shell, shell->inputdata.cursorpos, shell->inputdata.lineend);
890
          chprintf((BaseSequentialStream*)&shell->stream, "\n\tmaximum line width reached\n");
891 e545e620 Thomas Schöpping
          _printPrompt(shell);
892 ba516b61 Thomas Schöpping
          _printLine(shell, 0, shell->inputdata.lineend);
893
          _moveCursor(shell, shell->inputdata.lineend, shell->inputdata.cursorpos);
894 e545e620 Thomas Schöpping
        }
895
        break;
896 ba516b61 Thomas Schöpping
      }
897 e545e620 Thomas Schöpping
898 ba516b61 Thomas Schöpping
      case AOS_SHELL_ACTION_AUTOFILL:
899 e545e620 Thomas Schöpping
      {
900 cc33217b Thomas Schöpping
        const char* fill = shell->input.line;
901 ba516b61 Thomas Schöpping
        size_t cmatch = shell->inputdata.cursorpos;
902 e545e620 Thomas Schöpping
        charmatch_t matchlevel = CHAR_MATCH_NOT;
903
        size_t n;
904
        // iterate through command list
905
        for (aos_shellcommand_t* cmd = shell->commands; cmd != NULL; cmd = cmd->next) {
906
          // compare current match with command
907
          n = cmatch;
908
          charmatch_t mlvl = CHAR_MATCH_NOT;
909
          _strccmp(fill, cmd->name, shell->config & AOS_SHELL_CONFIG_MATCH_CASE, (n == 0) ? NULL : &n, &mlvl);
910
          const int cmp = (n < cmatch) ?
911
                            (n - cmatch) :
912
                            (cmd->name[n] != '\0') ?
913
                              strlen(cmd->name) - n :
914
                              0;
915
          // if an exact match was found
916 ba516b61 Thomas Schöpping
          if (cmatch + cmp == shell->inputdata.cursorpos) {
917
            cmatch = shell->inputdata.cursorpos;
918 e545e620 Thomas Schöpping
            fill = cmd->name;
919
            // break the loop only if there are no case mismatches with the input
920 ba516b61 Thomas Schöpping
            n = shell->inputdata.cursorpos;
921 cc33217b Thomas Schöpping
            _strccmp(fill, shell->input.line, false, &n, &mlvl);
922 e545e620 Thomas Schöpping
            if (mlvl == CHAR_MATCH_CASE) {
923
              break;
924
            }
925
          }
926
          // if a not exact match was found
927 ba516b61 Thomas Schöpping
          else if (cmatch + cmp > shell->inputdata.cursorpos) {
928 e545e620 Thomas Schöpping
            // if this is the first one
929 cc33217b Thomas Schöpping
            if (fill == shell->input.line) {
930 e545e620 Thomas Schöpping
              cmatch += cmp;
931
              fill = cmd->name;
932
            }
933
            // if this is a worse one
934
            else if ((cmp < 0) || (cmp == 0 && mlvl == CHAR_MATCH_CASE)) {
935
              cmatch += cmp;
936
            }
937
          }
938
          // non matching commands are ignored
939
          else {}
940
        }
941
        // evaluate if there are case mismatches
942
        n = cmatch;
943 cc33217b Thomas Schöpping
        _strccmp(shell->input.line, fill, shell->config & AOS_SHELL_CONFIG_MATCH_CASE, &n, &matchlevel);
944 e545e620 Thomas Schöpping
        // print the auto fill if any
945 ba516b61 Thomas Schöpping
        if (cmatch > shell->inputdata.cursorpos || (cmatch == shell->inputdata.cursorpos && matchlevel == CHAR_MATCH_NCASE)) {
946
          shell->inputdata.noinput = false;
947 e545e620 Thomas Schöpping
          // limit auto fill so it will not overflow the line width
948 cc33217b Thomas Schöpping
          if (shell->inputdata.lineend + (cmatch - shell->inputdata.cursorpos) > shell->input.width) {
949
            cmatch = shell->input.width - shell->inputdata.lineend + shell->inputdata.cursorpos;
950 e545e620 Thomas Schöpping
          }
951
          // move trailing memory further in the line
952 cc33217b Thomas Schöpping
          memmove(&(shell->input.line[cmatch]), &(shell->input.line[shell->inputdata.cursorpos]), shell->inputdata.lineend - shell->inputdata.cursorpos);
953 ba516b61 Thomas Schöpping
          shell->inputdata.lineend += cmatch - shell->inputdata.cursorpos;
954 e545e620 Thomas Schöpping
          // if there was no incorrect case when matching
955
          if (matchlevel == CHAR_MATCH_CASE) {
956
            // insert fill command name to line
957 cc33217b Thomas Schöpping
            memcpy(&(shell->input.line[shell->inputdata.cursorpos]), &(fill[shell->inputdata.cursorpos]), cmatch - shell->inputdata.cursorpos);
958 e545e620 Thomas Schöpping
            // print the output
959 ba516b61 Thomas Schöpping
            _printLine(shell, shell->inputdata.cursorpos, shell->inputdata.lineend);
960 e545e620 Thomas Schöpping
          } else {
961
            // overwrite line with fill command name
962 cc33217b Thomas Schöpping
            memcpy(shell->input.line, fill, cmatch);
963 e545e620 Thomas Schöpping
            // reprint the whole line
964 ba516b61 Thomas Schöpping
            _moveCursor(shell, shell->inputdata.cursorpos, 0);
965
            _printLine(shell, 0, shell->inputdata.lineend);
966 e545e620 Thomas Schöpping
          }
967
          // move cursor to the end of the matching sequence
968 ba516b61 Thomas Schöpping
          shell->inputdata.cursorpos = cmatch;
969
          _moveCursor(shell, shell->inputdata.lineend, shell->inputdata.cursorpos);
970 e545e620 Thomas Schöpping
        }
971
        break;
972
      }
973
974 ba516b61 Thomas Schöpping
      case AOS_SHELL_ACTION_SUGGEST:
975 e545e620 Thomas Schöpping
      {
976
        unsigned int matches = 0;
977
        // iterate through command list
978
        for (aos_shellcommand_t* cmd = shell->commands; cmd != NULL; cmd = cmd->next) {
979
          // compare line content with command, excpet if cursorpos=0
980 ba516b61 Thomas Schöpping
          size_t i = shell->inputdata.cursorpos;
981
          if (shell->inputdata.cursorpos > 0) {
982 cc33217b Thomas Schöpping
            _strccmp(shell->input.line, cmd->name, true, &i, NULL);
983 e545e620 Thomas Schöpping
          }
984 ba516b61 Thomas Schöpping
          const int cmp = (i < shell->inputdata.cursorpos) ?
985
                            (i - shell->inputdata.cursorpos) :
986 e545e620 Thomas Schöpping
                            (cmd->name[i] != '\0') ?
987
                              strlen(cmd->name) - i :
988
                              0;
989
          // if a match was found
990
          if (cmp > 0) {
991
            // if this is the first one
992
            if (matches == 0) {
993 ba516b61 Thomas Schöpping
              _moveCursor(shell, shell->inputdata.cursorpos, shell->inputdata.lineend);
994
              streamPut(&shell->stream, '\n');
995 e545e620 Thomas Schöpping
            }
996
            // print the command
997 ba516b61 Thomas Schöpping
            chprintf((BaseSequentialStream*)&shell->stream, "\t%s\n", cmd->name);
998 e545e620 Thomas Schöpping
            ++matches;
999
          }
1000
        }
1001
        // reprint the prompt and line if any matches have been found
1002
        if (matches > 0) {
1003
          _printPrompt(shell);
1004 ba516b61 Thomas Schöpping
          _printLine(shell, 0, shell->inputdata.lineend);
1005
          _moveCursor(shell, shell->inputdata.lineend, shell->inputdata.cursorpos);
1006
          shell->inputdata.noinput = false;
1007 e545e620 Thomas Schöpping
        }
1008
        break;
1009
      }
1010
1011 ba516b61 Thomas Schöpping
      case AOS_SHELL_ACTION_INSERTTOGGLE:
1012
      {
1013 e545e620 Thomas Schöpping
        if (shell->config & AOS_SHELL_CONFIG_INPUT_OVERWRITE) {
1014
          shell->config &= ~AOS_SHELL_CONFIG_INPUT_OVERWRITE;
1015
        } else {
1016
          shell->config |= AOS_SHELL_CONFIG_INPUT_OVERWRITE;
1017
        }
1018
        break;
1019 ba516b61 Thomas Schöpping
      }
1020 e545e620 Thomas Schöpping
1021 ba516b61 Thomas Schöpping
      case AOS_SHELL_ACTION_DELETEFORWARD:
1022
      {
1023
        --shell->inputdata.lineend;
1024 cc33217b Thomas Schöpping
        memmove(&(shell->input.line[shell->inputdata.cursorpos]), &(shell->input.line[shell->inputdata.cursorpos+1]), shell->inputdata.lineend - shell->inputdata.cursorpos);
1025 ba516b61 Thomas Schöpping
        _printLine(shell, shell->inputdata.cursorpos, shell->inputdata.lineend);
1026
        streamPut(&shell->stream, ' ');
1027
        _moveCursor(shell, shell->inputdata.lineend + 1, shell->inputdata.cursorpos);
1028 e545e620 Thomas Schöpping
        break;
1029 ba516b61 Thomas Schöpping
      }
1030 e545e620 Thomas Schöpping
1031 ba516b61 Thomas Schöpping
      case AOS_SHELL_ACTION_DELETEBACKWARD:
1032
      {
1033
        --shell->inputdata.cursorpos;
1034 cc33217b Thomas Schöpping
        memmove(&(shell->input.line[shell->inputdata.cursorpos]), &(shell->input.line[shell->inputdata.cursorpos+1]), shell->inputdata.lineend - shell->inputdata.cursorpos);
1035 ba516b61 Thomas Schöpping
        --shell->inputdata.lineend;
1036 cc33217b Thomas Schöpping
        shell->input.line[shell->inputdata.lineend] = '\0';
1037 ba516b61 Thomas Schöpping
        _moveCursor(shell, shell->inputdata.cursorpos + 1, shell->inputdata.cursorpos);
1038
        _printLine(shell, shell->inputdata.cursorpos, shell->inputdata.lineend);
1039
        streamPut(&shell->stream, ' ');
1040
        _moveCursor(shell, shell->inputdata.lineend+1, shell->inputdata.cursorpos);
1041 e545e620 Thomas Schöpping
        break;
1042 ba516b61 Thomas Schöpping
      }
1043 e545e620 Thomas Schöpping
1044 ba516b61 Thomas Schöpping
      case AOS_SHELL_ACTION_RECALLLAST:
1045 e545e620 Thomas Schöpping
      {
1046
        // replace any intermediate NUL bytes with spaces
1047 ba516b61 Thomas Schöpping
        shell->inputdata.lineend = 0;
1048 e545e620 Thomas Schöpping
        size_t nul_start = 0;
1049
        size_t nul_end = 0;
1050
        // search line for a NUL byte
1051 cc33217b Thomas Schöpping
        while (nul_start < shell->input.width) {
1052
          if (shell->input.line[nul_start] == '\0') {
1053 e545e620 Thomas Schöpping
            nul_end = nul_start + 1;
1054
            // keep searcjing for a byte that is not NUL
1055 cc33217b Thomas Schöpping
            while (nul_end < shell->input.width) {
1056
              if (shell->input.line[nul_end] != '\0') {
1057 e545e620 Thomas Schöpping
                // an intermediate NUL sequence was found
1058 cc33217b Thomas Schöpping
                memset(&(shell->input.line[nul_start]), ' ', nul_end - nul_start);
1059 ba516b61 Thomas Schöpping
                shell->inputdata.lineend = nul_end + 1;
1060 e545e620 Thomas Schöpping
                break;
1061
              } else {
1062
                ++nul_end;
1063
              }
1064
            }
1065
            nul_start = nul_end + 1;
1066
          } else {
1067 ba516b61 Thomas Schöpping
            ++shell->inputdata.lineend;
1068 e545e620 Thomas Schöpping
            ++nul_start;
1069
          }
1070
        }
1071 ba516b61 Thomas Schöpping
        shell->inputdata.cursorpos = shell->inputdata.lineend;
1072 e545e620 Thomas Schöpping
        // print the line
1073 ba516b61 Thomas Schöpping
        shell->inputdata.noinput = _printLine(shell, 0, shell->inputdata.lineend) == 0;
1074 e545e620 Thomas Schöpping
        break;
1075
      }
1076
1077 ba516b61 Thomas Schöpping
      case AOS_SHELL_ACTION_CLEAR:
1078
      {
1079 e545e620 Thomas Schöpping
        // clear output
1080 ba516b61 Thomas Schöpping
        _moveCursor(shell, shell->inputdata.cursorpos, 0);
1081
        for (shell->inputdata.cursorpos = 0; shell->inputdata.cursorpos < shell->inputdata.lineend; ++shell->inputdata.cursorpos) {
1082
          streamPut(&shell->stream, ' ');
1083 e545e620 Thomas Schöpping
        }
1084 ba516b61 Thomas Schöpping
        _moveCursor(shell, shell->inputdata.lineend, 0);
1085
        shell->inputdata.cursorpos = 0;
1086
        shell->inputdata.lineend = 0;
1087
        shell->inputdata.noinput = true;
1088 e545e620 Thomas Schöpping
        break;
1089 ba516b61 Thomas Schöpping
      }
1090 e545e620 Thomas Schöpping
1091 ba516b61 Thomas Schöpping
      case AOS_SHELL_ACTION_CURSOR2START:
1092
      {
1093
        _moveCursor(shell, shell->inputdata.cursorpos, 0);
1094
        shell->inputdata.cursorpos = 0;
1095 e545e620 Thomas Schöpping
        break;
1096 ba516b61 Thomas Schöpping
      }
1097 e545e620 Thomas Schöpping
1098 ba516b61 Thomas Schöpping
      case AOS_SHELL_ACTION_CURSOR2END:
1099
      {
1100
        _moveCursor(shell, shell->inputdata.cursorpos, shell->inputdata.lineend);
1101
        shell->inputdata.cursorpos = shell->inputdata.lineend;
1102 e545e620 Thomas Schöpping
        break;
1103 ba516b61 Thomas Schöpping
      }
1104 e545e620 Thomas Schöpping
1105 ba516b61 Thomas Schöpping
      case AOS_SHELL_ACTION_CURSORLEFT:
1106
      {
1107
        _moveCursor(shell, shell->inputdata.cursorpos, shell->inputdata.cursorpos-1);
1108
        --shell->inputdata.cursorpos;
1109 e545e620 Thomas Schöpping
        break;
1110 ba516b61 Thomas Schöpping
      }
1111 e545e620 Thomas Schöpping
1112 ba516b61 Thomas Schöpping
      case AOS_SHELL_ACTION_CURSORRIGHT:
1113
      {
1114
        _moveCursor(shell, shell->inputdata.cursorpos, shell->inputdata.cursorpos+1);
1115
        ++shell->inputdata.cursorpos;
1116 e545e620 Thomas Schöpping
        break;
1117 ba516b61 Thomas Schöpping
      }
1118 e545e620 Thomas Schöpping
1119 cc33217b Thomas Schöpping
      case AOS_SHELL_ACTION_CURSORWORDLEFT:
1120
      {
1121
        size_t cpos = shell->inputdata.cursorpos;
1122
        while (cpos > 0 && shell->input.line[cpos-1] == ' ') {
1123
          --cpos;
1124
        }
1125
        while (cpos > 0 && shell->input.line[cpos-1] != ' ') {
1126
          --cpos;
1127
        }
1128
        _moveCursor(shell, shell->inputdata.cursorpos, cpos);
1129
        shell->inputdata.cursorpos = cpos;
1130
        break;
1131
      }
1132
1133
      case AOS_SHELL_ACTION_CURSORWORDRIGHT:
1134
      {
1135
        size_t cpos = shell->inputdata.cursorpos;
1136
        while (cpos < shell->inputdata.lineend && shell->input.line[cpos] != ' ') {
1137
          ++cpos;
1138
        }
1139
        while (cpos < shell->inputdata.lineend && shell->input.line[cpos] == ' ') {
1140
          ++cpos;
1141
        }
1142
        _moveCursor(shell, shell->inputdata.cursorpos, cpos);
1143
        shell->inputdata.cursorpos = cpos;
1144
        break;
1145
      }
1146
1147 ba516b61 Thomas Schöpping
      case AOS_SHELL_ACTION_EXECUTE:
1148
      {
1149
        streamPut(&shell->stream, '\n');
1150
        // set the number of read bytes and return
1151
        if (!shell->inputdata.noinput) {
1152 cc33217b Thomas Schöpping
          *n = shell->input.width - shell->inputdata.lineend;
1153 e545e620 Thomas Schöpping
          // fill the remainder of the line with NUL bytes
1154 cc33217b Thomas Schöpping
          memset(&(shell->input.line[shell->inputdata.lineend]), '\0', *n);
1155 ba516b61 Thomas Schöpping
          // reset static variables
1156
          shell->inputdata.noinput = true;
1157 e545e620 Thomas Schöpping
        }
1158 ba516b61 Thomas Schöpping
        return AOS_SUCCESS;
1159
      }
1160 e545e620 Thomas Schöpping
1161 ba516b61 Thomas Schöpping
      case AOS_SHELL_ACTION_ESCSTART:
1162
      {
1163
        shell->inputdata.escseq[0] = c;
1164 cc33217b Thomas Schöpping
        break;
1165
      }
1166
1167
      case AOS_SHELL_ACTION_PRINTUNKNOWNSEQUENCE:
1168
      {
1169
        size_t seqc = 1; // element 0 would be unprintible ESC character
1170
        while (shell->inputdata.escseq[seqc] != '\0') {
1171
          _readChar(shell, shell->inputdata.escseq[seqc]);
1172
          ++seqc;
1173
        }
1174
        memset(shell->inputdata.escseq, '\0', sizeof(shell->inputdata.escseq)*sizeof(shell->inputdata.escseq[0]));
1175 e545e620 Thomas Schöpping
        break;
1176 ba516b61 Thomas Schöpping
      }
1177 e545e620 Thomas Schöpping
1178 ba516b61 Thomas Schöpping
      case AOS_SHELL_ACTION_NONE:
1179
      {
1180 e545e620 Thomas Schöpping
        // do nothing (ignore input) and read next byte
1181
        continue;
1182 ba516b61 Thomas Schöpping
      }
1183
    } /* end of switch */
1184 e545e620 Thomas Schöpping
1185 ba516b61 Thomas Schöpping
    shell->inputdata.lastaction = action;
1186 e545e620 Thomas Schöpping
  } /* end of while */
1187
1188 ba516b61 Thomas Schöpping
  // no more data could be read from the channel
1189
  return AOS_WARNING;
1190 e545e620 Thomas Schöpping
}
1191
1192
/**
1193
 * @brief   Parses the content of the input buffer (line) to separate arguments.
1194
 *
1195
 * @param[in] shell   Pointer to the shell object.
1196
 *
1197
 * @return            Number of arguments found.
1198
 */
1199
static size_t _parseArguments(aos_shell_t* shell)
1200
{
1201
  aosDbgCheck(shell != NULL);
1202
1203
  /*
1204
   * States for a very small FSM.
1205
   */
1206
  typedef enum {
1207
    START,
1208
    SPACE,
1209
    TEXT,
1210
    END,
1211
  } state_t;
1212
1213
  // local variables
1214
  state_t state = START;
1215
  size_t arg = 0;
1216
1217
  // iterate through the line
1218 cc33217b Thomas Schöpping
  for (char* c = shell->input.line; c < shell->input.line + shell->input.width; ++c) {
1219 e545e620 Thomas Schöpping
    // terminate at first NUL byte
1220
    if (*c == '\0') {
1221
      state = END;
1222
      break;
1223
    }
1224
    // spaces become NUL bytes
1225
    else if (*c == ' ') {
1226
      *c = '\0';
1227
      state = SPACE;
1228
    }
1229
    // handle non-NUL bytes
1230
    else {
1231
      switch (state) {
1232
        case START:
1233
        case SPACE:
1234
          // ignore too many arguments
1235
          if (arg < shell->arglistsize) {
1236
            shell->arglist[arg] = c;
1237
          }
1238
          ++arg;
1239
          break;
1240
        case TEXT:
1241
        case END:
1242
        default:
1243
          break;
1244
      }
1245
      state = TEXT;
1246
    }
1247
  }
1248
1249
  // set all remaining argument pointers to NULL
1250
  for (size_t a = arg; a < shell->arglistsize; ++a) {
1251
    shell->arglist[a] = NULL;
1252
  }
1253
1254
  return arg;
1255
}
1256
1257 f3ac1c96 Thomas Schöpping
/******************************************************************************/
1258
/* EXPORTED FUNCTIONS                                                         */
1259
/******************************************************************************/
1260
1261 e545e620 Thomas Schöpping
/**
1262
 * @brief   Initializes a shell object with the specified parameters.
1263
 *
1264
 * @param[in] shell         Pointer to the shell object.
1265
 * @param[in] stream        I/O stream to use.
1266
 * @param[in] prompt        Prompt line to print (NULL = use default prompt).
1267
 * @param[in] line          Pointer to the input buffer.
1268
 * @param[in] linesize      Size of the input buffer.
1269
 * @param[in] arglist       Pointer to the argument buffer.
1270
 * @param[in] arglistsize   Size of te argument buffer.
1271
 */
1272 cc33217b 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)
1273 e545e620 Thomas Schöpping
{
1274
  aosDbgCheck(shell != NULL);
1275 ba516b61 Thomas Schöpping
  aosDbgCheck(oseventsource != NULL);
1276 e545e620 Thomas Schöpping
  aosDbgCheck(line != NULL);
1277
  aosDbgCheck(arglist != NULL);
1278
1279
  // set parameters
1280
  shell->thread = NULL;
1281
  chEvtObjectInit(&shell->eventSource);
1282 ba516b61 Thomas Schöpping
  shell->os.eventSource = oseventsource;
1283
  aosShellStreamInit(&shell->stream);
1284 e545e620 Thomas Schöpping
  shell->prompt = prompt;
1285
  shell->commands = NULL;
1286
  shell->execstatus.command = NULL;
1287
  shell->execstatus.retval = 0;
1288 cc33217b Thomas Schöpping
  shell->input.line = line;
1289
  shell->input.width = linesize;
1290 ba516b61 Thomas Schöpping
  shell->inputdata.lastaction = AOS_SHELL_ACTION_NONE;
1291
  memset(shell->inputdata.escseq, '\0', sizeof(shell->inputdata.escseq)*sizeof(shell->inputdata.escseq[0]));
1292
  shell->inputdata.cursorpos = 0;
1293
  shell->inputdata.lineend = 0;
1294
  shell->inputdata.noinput = true;
1295 e545e620 Thomas Schöpping
  shell->arglist = arglist;
1296
  shell->arglistsize = arglistsize;
1297
  shell->config = 0x00;
1298
1299 cc33217b Thomas Schöpping
  // initialize buffers
1300
  memset(shell->input.line, '\0', shell->input.width);
1301 e545e620 Thomas Schöpping
  for (size_t a = 0; a < shell->arglistsize; ++a) {
1302
    shell->arglist[a] = NULL;
1303
  }
1304
1305
  return;
1306
}
1307
1308
/**
1309 ba516b61 Thomas Schöpping
 * @brief   Initialize an AosShellStream object.
1310
 *
1311
 * @param[in] stream  The AosShellStrem to initialize.
1312
 */
1313
void aosShellStreamInit(AosShellStream* stream)
1314
{
1315
  aosDbgCheck(stream != NULL);
1316
1317
  stream->vmt = &_streamvmt;
1318
  stream->channel = NULL;
1319
1320
  return;
1321
}
1322
1323
/**
1324
 * @brief   Initialize an AosShellChannel object with the specified parameters.
1325
 *
1326 dd8738ea Thomas Schöpping
 * @param[in] channel       The AosShellChannel to initialize.
1327
 * @param[in] asyncchannel  An BaseAsynchronousChannel this AosShellChannel is associated with.
1328 ba516b61 Thomas Schöpping
 */
1329 dd8738ea Thomas Schöpping
void aosShellChannelInit(AosShellChannel* channel, BaseAsynchronousChannel* asyncchannel)
1330 ba516b61 Thomas Schöpping
{
1331
  aosDbgCheck(channel != NULL);
1332 dd8738ea Thomas Schöpping
  aosDbgCheck(asyncchannel != NULL);
1333 ba516b61 Thomas Schöpping
1334
  channel->vmt = &_channelvmt;
1335 dd8738ea Thomas Schöpping
  channel->asyncchannel = asyncchannel;
1336
  channel->listener.wflags = 0;
1337 ba516b61 Thomas Schöpping
  channel->next = NULL;
1338
  channel->flags = 0;
1339
1340
  return;
1341
}
1342
1343
/**
1344 e545e620 Thomas Schöpping
 * @brief   Inserts a command to the shells list of commands.
1345
 *
1346
 * @param[in] shell   Pointer to the shell object.
1347
 * @param[in] cmd     Pointer to the command to add.
1348
 *
1349
 * @return            A status value.
1350
 * @retval AOS_SUCCESS  The command was added successfully.
1351
 * @retval AOS_ERROR    Another command with identical name already exists.
1352
 */
1353
aos_status_t aosShellAddCommand(aos_shell_t *shell, aos_shellcommand_t *cmd)
1354
{
1355
  aosDbgCheck(shell != NULL);
1356
  aosDbgCheck(cmd != NULL);
1357
  aosDbgCheck(cmd->name != NULL && strlen(cmd->name) > 0 && strchr(cmd->name, ' ') == NULL && strchr(cmd->name, '\t') == NULL);
1358
  aosDbgCheck(cmd->callback != NULL);
1359
  aosDbgCheck(cmd->next == NULL);
1360
1361
  aos_shellcommand_t* prev = NULL;
1362
  aos_shellcommand_t** curr = &(shell->commands);
1363
1364
  // insert the command to the list wrt lexographical order (exception: lower case characters preceed upper their uppercase counterparts)
1365 ba516b61 Thomas Schöpping
  while (*curr != NULL) {
1366
    // iterate through the list as long as the command names are 'smaller'
1367
    const int cmp = _strccmp((*curr)->name, cmd->name, true, NULL, NULL);
1368
    if (cmp < 0) {
1369
      prev = *curr;
1370
      curr = &((*curr)->next);
1371
      continue;
1372
    }
1373
    // error if the command already exists
1374
    else if (cmp == 0) {
1375
      return AOS_ERROR;
1376
    }
1377
    // insert the command as soon as a 'larger' name was found
1378
    else /* if (cmpval > 0) */ {
1379
      cmd->next = *curr;
1380
      // special case: the first command is larger
1381
      if (prev == NULL) {
1382
        shell->commands = cmd;
1383
      } else {
1384
        prev->next = cmd;
1385 e545e620 Thomas Schöpping
      }
1386 ba516b61 Thomas Schöpping
      return AOS_SUCCESS;
1387 e545e620 Thomas Schöpping
    }
1388
  }
1389 ba516b61 Thomas Schöpping
  // the end of the list has been reached
1390
1391
  // append the command
1392
  *curr = cmd;
1393
  return AOS_SUCCESS;
1394 e545e620 Thomas Schöpping
}
1395
1396
/**
1397
 * @brief   Removes a command from the shells list of commands.
1398
 *
1399
 * @param[in] shell     Pointer to the shell object.
1400
 * @param[in] cmd       Name of the command to removde.
1401
 * @param[out] removed  Optional pointer to the command that was removed.
1402
 *
1403
 * @return              A status value.
1404
 * @retval AOS_SUCCESS  The command was removed successfully.
1405
 * @retval AOS_ERROR    The command name was not found.
1406
 */
1407
aos_status_t aosShellRemoveCommand(aos_shell_t *shell, char *cmd, aos_shellcommand_t **removed)
1408
{
1409
  aosDbgCheck(shell != NULL);
1410
  aosDbgCheck(cmd != NULL && strlen(cmd) > 0);
1411
1412
  aos_shellcommand_t* prev = NULL;
1413
  aos_shellcommand_t** curr = &(shell->commands);
1414
1415
  // iterate through the list and seach for the specified command name
1416
  while (curr != NULL) {
1417
    const int cmpval = strcmp((*curr)->name, cmd);
1418
    // iterate through the list as long as the command names are 'smaller'
1419
    if (cmpval < 0) {
1420
      prev = *curr;
1421
      curr = &((*curr)->next);
1422
      continue;
1423
    }
1424
    // remove the command when found
1425
    else if (cmpval == 0) {
1426
      // special case: the first command matches
1427
      if (prev == NULL) {
1428
        shell->commands = (*curr)->next;
1429
      } else {
1430
        prev->next = (*curr)->next;
1431
      }
1432
      (*curr)->next = NULL;
1433
      // set the optional output argument
1434
      if (removed != NULL) {
1435
        *removed = *curr;
1436
      }
1437
      return AOS_SUCCESS;
1438
    }
1439
    // break the loop if the command names are 'larger'
1440
    else /* if (cmpval > 0) */ {
1441
      break;
1442
    }
1443
  }
1444
1445
  // if the command was not found, return an error
1446
  return AOS_ERROR;
1447
}
1448
1449
/**
1450 aed3754b Thomas Schöpping
 * @brief   Count the number of commands assigned to the shell.
1451
 *
1452
 * @param[in] shell   The shell to count the commands for.
1453
 *
1454
 * @return  The number of commands associated to the shell.
1455
 */
1456
unsigned int aosShellCountCommands(aos_shell_t* shell)
1457
{
1458
  aosDbgCheck(shell != NULL);
1459
1460
  unsigned int count = 0;
1461
  aos_shellcommand_t* cmd = shell->commands;
1462
  while (cmd != NULL) {
1463
    ++count;
1464
    cmd = cmd->next;
1465
  }
1466
1467
  return count;
1468
}
1469
1470
/**
1471 ba516b61 Thomas Schöpping
 * @brief   Add a channel to a AosShellStream.
1472
 *
1473
 * @param[in] stream    The AosShellStream to extend.
1474
 * @param[in] channel   The channel to be added to the stream.
1475
 */
1476
void aosShellStreamAddChannel(AosShellStream* stream, AosShellChannel* channel)
1477
{
1478
  aosDbgCheck(stream != NULL);
1479 dd8738ea Thomas Schöpping
  aosDbgCheck(channel != NULL && channel->asyncchannel != NULL && channel->next == NULL && (channel->flags & AOS_SHELLCHANNEL_ATTACHED) == 0);
1480 ba516b61 Thomas Schöpping
1481
  // prepend the new channel
1482
  chSysLock();
1483
  channel->flags |= AOS_SHELLCHANNEL_ATTACHED;
1484
  channel->next = stream->channel;
1485
  stream->channel = channel;
1486
  chSysUnlock();
1487
1488
  return;
1489
}
1490
1491
/**
1492
 * @brief   Remove a channel from an AosShellStream.
1493
 *
1494
 * @param[in] stream    The AosShellStream to modify.
1495
 * @param[in] channel   The channel to remove.
1496 aed3754b Thomas Schöpping
 *
1497
 * @return              A status value.
1498
 * @retval AOS_SUCCESS  The channel was removed successfully.
1499
 * @retval AOS_ERROR    The specified channel was not found to be associated with the shell.
1500 ba516b61 Thomas Schöpping
 */
1501
aos_status_t aosShellStreamRemoveChannel(AosShellStream* stream, AosShellChannel* channel)
1502
{
1503
  aosDbgCheck(stream != NULL);
1504 dd8738ea Thomas Schöpping
  aosDbgCheck(channel != NULL && channel->asyncchannel != NULL && channel->flags & AOS_SHELLCHANNEL_ATTACHED);
1505 ba516b61 Thomas Schöpping
1506
  // local varibales
1507
  AosShellChannel* prev = NULL;
1508
  AosShellChannel* curr = stream->channel;
1509
1510
  // iterate through the list and search for the specified channel
1511
  while (curr != NULL) {
1512
    // if the channel was found
1513
    if (curr == channel) {
1514
      chSysLock();
1515
      // special case: the first channel matches (prev is NULL)
1516
      if (prev == NULL) {
1517
        stream->channel = curr->next;
1518
      } else {
1519
        prev->next = channel->next;
1520
      }
1521
      curr->next = NULL;
1522
      curr->flags &= ~AOS_SHELLCHANNEL_ATTACHED;
1523
      chSysUnlock();
1524
      return AOS_SUCCESS;
1525
    }
1526
  }
1527
1528
  // if the channel was not found, return an error
1529
  return AOS_ERROR;
1530
}
1531
1532
/**
1533
 * @brief   Enable a AosSheööChannel as input.
1534
 *
1535
 * @param[in] channel   The channel to enable as input.
1536
 */
1537
void aosShellChannelInputEnable(AosShellChannel* channel)
1538
{
1539 dd8738ea Thomas Schöpping
  aosDbgCheck(channel != NULL && channel->asyncchannel != NULL);
1540 ba516b61 Thomas Schöpping
1541
  chSysLock();
1542
  channel->listener.wflags |= CHN_INPUT_AVAILABLE;
1543
  channel->flags |= AOS_SHELLCHANNEL_INPUT_ENABLED;
1544
  chSysUnlock();
1545
1546
  return;
1547
}
1548
1549
/**
1550
 * @brief   Disable a AosSheööChannel as input.
1551
 *
1552
 * @param[in] channel   The channel to disable as input.
1553
 */
1554
void aosShellChannelInputDisable( AosShellChannel* channel)
1555
{
1556 dd8738ea Thomas Schöpping
  aosDbgCheck(channel != NULL && channel->asyncchannel != NULL);
1557 ba516b61 Thomas Schöpping
1558
  chSysLock();
1559
  channel->listener.wflags &= ~CHN_INPUT_AVAILABLE;
1560
  channel->flags &= ~AOS_SHELLCHANNEL_INPUT_ENABLED;
1561
  chSysUnlock();
1562
1563
  return;
1564
}
1565
1566
/**
1567
 * @brief   Enable a AosSheööChannel as output.
1568
 *
1569
 * @param[in] channel   The channel to enable as output.
1570
 */
1571
void aosShellChannelOutputEnable(AosShellChannel* channel)
1572
{
1573 dd8738ea Thomas Schöpping
  aosDbgCheck(channel != NULL && channel->asyncchannel != NULL);
1574 ba516b61 Thomas Schöpping
1575
  channel->flags |= AOS_SHELLCHANNEL_OUTPUT_ENABLED;
1576
1577
  return;
1578
}
1579
1580
/**
1581
 * @brief   Disable a AosSheööChannel as output.
1582
 *
1583
 * @param[in] channel   The channel to disable as output.
1584
 */
1585
void aosShellChannelOutputDisable(AosShellChannel* channel)
1586
{
1587 dd8738ea Thomas Schöpping
  aosDbgCheck(channel != NULL && channel->asyncchannel != NULL);
1588 ba516b61 Thomas Schöpping
1589
  channel->flags &= ~AOS_SHELLCHANNEL_OUTPUT_ENABLED;
1590
1591
  return;
1592
}
1593
1594
/**
1595 e545e620 Thomas Schöpping
 * @brief   Thread main function.
1596
 *
1597
 * @param[in] aosShellThread    Name of the function;
1598
 * @param[in] shell             Pointer to the shell object.
1599
 */
1600 af4fd4a2 Thomas Schöpping
void aosShellThread(void* shell)
1601 e545e620 Thomas Schöpping
{
1602
  aosDbgCheck(shell != NULL);
1603
1604
  // local variables
1605 ba516b61 Thomas Schöpping
  eventmask_t eventmask;
1606
  eventflags_t eventflags;
1607
  AosShellChannel* channel;
1608
  aos_status_t readeval;
1609
  size_t nchars = 0;
1610 e545e620 Thomas Schöpping
  size_t nargs = 0;
1611 ba516b61 Thomas Schöpping
  aos_shellcommand_t* cmd;
1612
1613
1614
  // register OS related events
1615
  chEvtRegisterMask(((aos_shell_t*)shell)->os.eventSource, &(((aos_shell_t*)shell)->os.eventListener), AOS_SHELL_EVENTMASK_OS);
1616
  // register events to all input channels
1617
  for (channel = ((aos_shell_t*)shell)->stream.channel; channel != NULL; channel = channel->next) {
1618 dd8738ea Thomas Schöpping
    chEvtRegisterMaskWithFlags(&(channel->asyncchannel->event), &(channel->listener), AOS_SHELL_EVENTMASK_INPUT, channel->listener.wflags);
1619 ba516b61 Thomas Schöpping
  }
1620 e545e620 Thomas Schöpping
1621
  // fire start event
1622
  chEvtBroadcastFlags(&(((aos_shell_t*)shell)->eventSource), AOS_SHELL_EVTFLAG_START);
1623
1624 ba516b61 Thomas Schöpping
  // print the prompt for the first time
1625
  _printPrompt((aos_shell_t*)shell);
1626
1627 e545e620 Thomas Schöpping
  // enter thread loop
1628
  while (!chThdShouldTerminateX()) {
1629 ba516b61 Thomas Schöpping
    // wait for event and handle it accordingly
1630
    eventmask = chEvtWaitOne(ALL_EVENTS);
1631
1632
    // handle event
1633
    switch (eventmask) {
1634
1635
      // OS related events
1636
      case AOS_SHELL_EVENTMASK_OS:
1637
      {
1638
        eventflags = chEvtGetAndClearFlags(&((aos_shell_t*)shell)->os.eventListener);
1639
        // handle shutdown/restart events
1640
        if (eventflags & AOS_SYSTEM_EVENTFLAGS_SHUTDOWN) {
1641
          chThdTerminate(((aos_shell_t*)shell)->thread);
1642
        } else {
1643
          // print an error message
1644
          chprintf((BaseSequentialStream*)&((aos_shell_t*)shell)->stream, "\nERROR: unknown OS event received (0x%08X)\n", eventflags);
1645
        }
1646 e545e620 Thomas Schöpping
        break;
1647
      }
1648
1649 ba516b61 Thomas Schöpping
      // input events
1650
      case AOS_SHELL_EVENTMASK_INPUT:
1651
      {
1652
        // check and handle all channels
1653
        channel = ((aos_shell_t*)shell)->stream.channel;
1654
        while (channel != NULL) {
1655
          eventflags = chEvtGetAndClearFlags(&channel->listener);
1656
          // if there is new input
1657
          if (eventflags & CHN_INPUT_AVAILABLE) {
1658 dd8738ea Thomas Schöpping
            // read input from channel
1659
            readeval = _readChannel((aos_shell_t*)shell, channel, &nchars);
1660
            // parse input line to argument list only if the input shall be executed
1661
            nargs = (readeval == AOS_SUCCESS && nchars > 0) ? _parseArguments((aos_shell_t*)shell) : 0;
1662
            // check number of arguments
1663
            if (nargs > ((aos_shell_t*)shell)->arglistsize) {
1664
              // error too many arguments
1665
              chprintf((BaseSequentialStream*)&((aos_shell_t*)shell)->stream, "\ttoo many arguments\n");
1666
            } else if (nargs > 0) {
1667
              // search command list for arg[0] and execute callback
1668
              cmd = ((aos_shell_t*)shell)->commands;
1669
              while (cmd != NULL) {
1670
                if (strcmp(((aos_shell_t*)shell)->arglist[0], cmd->name) == 0) {
1671
                  ((aos_shell_t*)shell)->execstatus.command = cmd;
1672
                  chEvtBroadcastFlags(&(((aos_shell_t*)shell)->eventSource), AOS_SHELL_EVTFLAG_EXEC);
1673
                  ((aos_shell_t*)shell)->execstatus.retval = cmd->callback((BaseSequentialStream*)&((aos_shell_t*)shell)->stream, nargs, ((aos_shell_t*)shell)->arglist);
1674
                  chEvtBroadcastFlags(&(((aos_shell_t*)shell)->eventSource), AOS_SHELL_EVTFLAG_DONE);
1675
                  // notify if the command was not successful
1676
                  if (((aos_shell_t*)shell)->execstatus.retval != 0) {
1677
                    chprintf((BaseSequentialStream*)&((aos_shell_t*)shell)->stream, "command returned exit status %d\n", ((aos_shell_t*)shell)->execstatus.retval);
1678 ba516b61 Thomas Schöpping
                  }
1679 dd8738ea Thomas Schöpping
                  break;
1680 ba516b61 Thomas Schöpping
                }
1681 dd8738ea Thomas Schöpping
                cmd = cmd->next;
1682
              } /* end of while */
1683 e545e620 Thomas Schöpping
1684 dd8738ea Thomas Schöpping
              // if no matching command was found, print an error
1685
              if (cmd == NULL) {
1686 cc33217b Thomas Schöpping
                chprintf((BaseSequentialStream*)&((aos_shell_t*)shell)->stream, "\tcommand '%s' not found\n", ((aos_shell_t*)shell)->arglist[0]);
1687 ba516b61 Thomas Schöpping
              }
1688
            }
1689 dd8738ea Thomas Schöpping
1690
            // reset some internal variables and eprint a new prompt
1691
            if (readeval == AOS_SUCCESS && !chThdShouldTerminateX()) {
1692
              ((aos_shell_t*)shell)->inputdata.cursorpos = 0;
1693
              ((aos_shell_t*)shell)->inputdata.lineend = 0;
1694
              _printPrompt((aos_shell_t*)shell);
1695 ba516b61 Thomas Schöpping
            }
1696 e545e620 Thomas Schöpping
          }
1697 ba516b61 Thomas Schöpping
1698
          // iterate to next channel
1699
          channel = channel->next;
1700 e545e620 Thomas Schöpping
        }
1701 ba516b61 Thomas Schöpping
        break;
1702 e545e620 Thomas Schöpping
      }
1703 ba516b61 Thomas Schöpping
1704
      // other events
1705
      default:
1706
      {
1707
        // print an error message
1708 1e5f7648 Thomas Schöpping
        chprintf((BaseSequentialStream*)&((aos_shell_t*)shell)->stream, "\nSHELL: ERROR: unknown event received (0x%08X)\n", eventmask);
1709 ba516b61 Thomas Schöpping
        break;
1710 e545e620 Thomas Schöpping
      }
1711
1712 ba516b61 Thomas Schöpping
    } /* end of switch */
1713
1714
  } /* end of while */
1715 e545e620 Thomas Schöpping
1716
  // fire event and exit the thread
1717
  chSysLock();
1718
  chEvtBroadcastFlagsI(&(((aos_shell_t*)shell)->eventSource), AOS_SHELL_EVTFLAG_EXIT);
1719
  chThdExitS(MSG_OK);
1720
  // no chSysUnlock() required since the thread has been terminated an all waiting threads have been woken up
1721
}
1722 ba516b61 Thomas Schöpping
1723 2dd2e257 Thomas Schöpping
#endif /* (AMIROOS_CFG_SHELL_ENABLE == true) || (AMIROOS_CFG_TESTS_ENABLE == true)*/
1724 53710ca3 Marc Rothmann
1725
/** @} */