Statistics
| Branch: | Tag: | Revision:

amiro-os / os / core / src / aos_system.c @ cb835a3e

History | View | Annotate | Download (30.508 KB)

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

5
This program is free software: you can redistribute it and/or modify
6
it under the terms of the GNU General Public License as published by
7
the Free Software Foundation, either version 3 of the License, or
8
(at your option) any later version.
9

10
This program is distributed in the hope that it will be useful,
11
but WITHOUT ANY WARRANTY; without even the implied warranty of
12
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13
GNU General Public License for more details.
14

15
You should have received a copy of the GNU General Public License
16
along with this program.  If not, see <http://www.gnu.org/licenses/>.
17
*/
18

    
19
#include <aos_system.h>
20

    
21
#include <amiroos.h>
22
#include <amiroblt.h>
23
#include <string.h>
24
#if (AMIROOS_CFG_TESTS_ENABLE == true)
25
#include <ch_test.h>
26
#endif
27

    
28
/**
29
 * @brief   Period of the system timer.
30
 */
31
#define SYSTIMER_PERIOD               (TIME_MAXIMUM - CH_CFG_ST_TIMEDELTA)
32

    
33
/**
34
 * @brief   Width of the printable system info text.
35
 */
36
#define SYSTEM_INFO_WIDTH             70
37

    
38
/**
39
 * @brief   Width of the name column of the system info table.
40
 */
41
#define SYSTEM_INFO_NAMEWIDTH         14
42

    
43
/* forward declarations */
44
static void _printSystemInfo(BaseSequentialStream* stream);
45
#if (AMIROOS_CFG_SHELL_ENABLE == true)
46
static int _shellcmd_configcb(BaseSequentialStream* stream, int argc, char* argv[]);
47
static int _shellcmd_infocb(BaseSequentialStream* stream, int argc, char* argv[]);
48
static int _shellcmd_shutdowncb(BaseSequentialStream* stream, int argc, char* argv[]);
49
#endif /* AMIROOS_CFG_SHELL_ENABLE == true */
50
#if (AMIROOS_CFG_TESTS_ENABLE == true)
51
static int _shellcmd_kerneltestcb(BaseSequentialStream* stream, int argc, char* argv[]);
52
#endif /* AMIROOS_CFG_TESTS_ENABLE == true */
53

    
54
/**
55
 * @brief   PD signal GPIO.
56
 */
57
static apalControlGpio_t* _gpioPd;
58

    
59
/**
60
 * @brief   Sync signal GPIO.
61
 */
62
static apalControlGpio_t* _gpioSync;
63

    
64
/**
65
 * @brief   Timer to accumulate system uptime.
66
 */
67
static virtual_timer_t _systimer;
68

    
69
/**
70
 * @brief   Accumulated system uptime.
71
 */
72
static aos_timestamp_t _uptime;
73

    
74
/**
75
 * @brief   Timer register value of last accumulation.
76
 */
77
static systime_t _synctime;
78

    
79
#if (AMIROOS_CFG_SSSP_MASTER == true) || defined(__DOXYGEN__)
80
/**
81
 * @brief   Timer to drive the SYS_SYNC signal for system wide time synchronization according to SSSP.
82
 */
83
static virtual_timer_t _syssynctimer;
84

    
85
/**
86
 * @brief   Last uptime of system wide time synchronization.
87
 */
88
static aos_timestamp_t _syssynctime;
89
#endif
90

    
91
#if (AMIROOS_CFG_SHELL_ENABLE == true) || defined(__DOXYGEN__)
92
/**
93
 * @brief   System shell.
94
 */
95
static aos_shell_t _shell;
96

    
97
/**
98
 * @brief   Shell thread working area.
99
 */
100
THD_WORKING_AREA(_shell_wa, AMIROOS_CFG_SHELL_STACKSIZE);
101

    
102
/**
103
 * @brief   Shell input buffer.
104
 */
105
static char _shell_line[AMIROOS_CFG_SHELL_LINEWIDTH];
106

    
107
/**
108
 * @brief   Shell argument buffer.
109
 */
110
static char* _shell_arglist[AMIROOS_CFG_SHELL_MAXARGS];
111

    
112
/**
113
 * @brief   Shell command to retrieve system information.
114
 */
115
static aos_shellcommand_t _shellcmd_info = {
116
  /* name     */ "module:info",
117
  /* callback */ _shellcmd_infocb,
118
  /* next     */ NULL,
119
};
120

    
121
/**
122
 * @brief   Shell command to set or retrieve system configuration.
123
 */
124
static aos_shellcommand_t _shellcmd_config = {
125
  /* name     */ "module:config",
126
  /* callback */ _shellcmd_configcb,
127
  /* next     */ NULL,
128
};
129

    
130
/**
131
 * @brief   Shell command to shutdown the system.
132
 */
133
static aos_shellcommand_t _shellcmd_shutdown = {
134
  /* name     */ "system:shutdown",
135
  /* callback */ _shellcmd_shutdowncb,
136
  /* next     */ NULL,
137
};
138
#endif /* AMIROOS_CFG_SHELL_ENABLE == true */
139

    
140
#if (AMIROOS_CFG_TESTS_ENABLE == true) || defined(__DOXYGEN__)
141
/**
142
 * @brief   Shell kommand to run a test of the ChibiOS/RT kernel.
143
 */
144
static aos_shellcommand_t _shellcmd_kerneltest = {
145
  /* name     */ "kernel:test",
146
  /* callback */ _shellcmd_kerneltestcb,
147
  /* next     */ NULL,
148
};
149
#endif /* AMIROOS_CFG_TESTS_ENABLE == true */
150

    
151
/**
152
 * @brief   Global system object.
153
 */
154
aos_system_t aos = {
155
  /* SSSP stage       */ AOS_SSSP_STARTUP_2_1,
156
  /* I/O stream       */ {
157
    /* channel          */ NULL,
158
  },
159
  /* event            */ {
160
    /* I/O              */ {
161
      /* source           */ {
162
        /* next listener    */ NULL,
163
      },
164
      /* flagsSignalPd    */ 0,
165
      /* flagsSignalSync  */ 0,
166
    },
167
    /* OS               */ {
168
      /* source           */ {
169
        /* next listener    */ NULL,
170
      }
171
    },
172
  },
173
#if (AMIROOS_CFG_SHELL_ENABLE == true)
174
  /* shell            */ &_shell,
175
#endif
176
};
177

    
178
/**
179
 * @brief   Print a separator line.
180
 *
181
 * @param[in] stream    Stream to print to or NULL to print to all system streams.
182
 * @param[in] c         Character to use.
183
 * @param[in] n         Length of the separator line.
184
 *
185
 * @return  Number of characters printed.
186
 */
187
static unsigned int _printSystemInfoSeparator(BaseSequentialStream* stream, const char c, const unsigned int n)
188
{
189
  aosDbgCheck(stream != NULL);
190

    
191
  // print the specified character n times
192
  for (unsigned int i = 0; i < n; ++i) {
193
    streamPut(stream, c);
194
  }
195
  streamPut(stream, '\n');
196

    
197
  return n+1;
198
}
199

    
200
/**
201
 * @brief   Print a system information line.
202
 * @details Prints a system information line with the following format:
203
 *            "<name>[spaces]fmt"
204
 *          The combined width of "<name>[spaces]" can be specified in order to align <fmt> on multiple lines.
205
 *          Note that there is not trailing newline added implicitely.
206
 *
207
 * @param[in] stream      Stream to print to or NULL to print to all system streams.
208
 * @param[in] name        Name of the entry/line.
209
 * @param[in] namewidth   Width of the name column.
210
 * @param[in] fmt         Formatted string of information content.
211
 *
212
 * @return  Number of characters printed.
213
 */
214
static unsigned int _printSystemInfoLine(BaseSequentialStream* stream, const char* name, const unsigned int namewidth, const char* fmt, ...)
215
{
216
  aosDbgCheck(stream != NULL);
217
  aosDbgCheck(name != NULL);
218

    
219
  unsigned int n = 0;
220
  va_list ap;
221

    
222
  va_start(ap, fmt);
223
  n += chprintf(stream, name);
224
  while (n < namewidth) {
225
    streamPut(stream, ' ');
226
    ++n;
227
  }
228
  n += chvprintf(stream, fmt, ap);
229
  va_end(ap);
230

    
231
  return n;
232
}
233

    
234
/**
235
 * @brief   Prints information about the system.
236
 *
237
 * @param[in] stream    Stream to print to.
238
 */
239
static void _printSystemInfo(BaseSequentialStream* stream)
240
{
241
  aosDbgCheck(stream != NULL);
242

    
243
  _printSystemInfoSeparator(stream, '=', SYSTEM_INFO_WIDTH);
244
  _printSystemInfoLine(stream, "Module", SYSTEM_INFO_NAMEWIDTH, "%s (v%s)\n", BOARD_NAME, BOARD_VERSION);
245
#ifdef PLATFORM_NAME
246
  _printSystemInfoLine(stream, "Platform", SYSTEM_INFO_NAMEWIDTH, "%s\n", PLATFORM_NAME);
247
#endif
248
#ifdef PORT_CORE_VARIANT_NAME
249
  _printSystemInfoLine(stream, "Core Variant", SYSTEM_INFO_NAMEWIDTH, "%s\n", PORT_CORE_VARIANT_NAME);
250
#endif
251
  _printSystemInfoLine(stream, "Architecture", SYSTEM_INFO_NAMEWIDTH, "%s\n", PORT_ARCHITECTURE_NAME);
252
  _printSystemInfoSeparator(stream, '-', SYSTEM_INFO_WIDTH);
253
  _printSystemInfoLine(stream, "AMiRo-OS" ,SYSTEM_INFO_NAMEWIDTH, "%u.%u.%u %s (SSSP %u.%u)\n", AMIROOS_VERSION_MAJOR, AMIROOS_VERSION_MINOR, AMIROOS_VERSION_PATCH, AMIROOS_RELEASE_TYPE, AOS_SYSTEM_SSSP_MAJOR, AOS_SYSTEM_SSSP_MINOR);
254
  _printSystemInfoLine(stream, "AMiRo-LLD" ,SYSTEM_INFO_NAMEWIDTH, "%u.%u.%u %s (periphAL %u.%u)\n", AMIRO_LLD_VERSION_MAJOR, AMIRO_LLD_VERSION_MINOR, AMIRO_LLD_VERSION_PATCH, AMIRO_LLD_RELEASE_TYPE, PERIPHAL_VERSION_MAJOR, PERIPHAL_VERSION_MINOR);
255
  _printSystemInfoLine(stream, "ChibiOS/RT" ,SYSTEM_INFO_NAMEWIDTH, "%u.%u.%u %s\n", CH_KERNEL_MAJOR, CH_KERNEL_MINOR, CH_KERNEL_PATCH, (CH_KERNEL_STABLE == 1) ? "stable" : "non-stable");
256
  _printSystemInfoLine(stream, "ChibiOS/HAL",SYSTEM_INFO_NAMEWIDTH, "%u.%u.%u %s\n", CH_HAL_MAJOR, CH_HAL_MINOR, CH_HAL_PATCH, (CH_HAL_STABLE == 1) ? "stable" : "non-stable");
257
  _printSystemInfoLine(stream, "build type",SYSTEM_INFO_NAMEWIDTH,"%s\n", (AMIROOS_CFG_DBG == true) ? "debug" : "release");
258
  _printSystemInfoLine(stream, "Compiler" ,SYSTEM_INFO_NAMEWIDTH, "%s %u.%u.%u\n", "GCC", __GNUC__, __GNUC_MINOR__, __GNUC_PATCHLEVEL__); // TODO: support other compilers than GCC
259
  _printSystemInfoLine(stream, "Compiled" ,SYSTEM_INFO_NAMEWIDTH, "%s - %s\n", __DATE__, __TIME__);
260
  _printSystemInfoSeparator(stream, '-', SYSTEM_INFO_WIDTH);
261
  if (BL_CALLBACK_TABLE_ADDRESS->magicNumber == BL_MAGIC_NUMBER) {
262
    _printSystemInfoLine(stream, "AMiRo-BLT", SYSTEM_INFO_NAMEWIDTH, "%u.%u.%u %s (SSSP %u.%u)\n", BL_CALLBACK_TABLE_ADDRESS->vBootloader.major, BL_CALLBACK_TABLE_ADDRESS->vBootloader.minor, BL_CALLBACK_TABLE_ADDRESS->vBootloader.patch,
263
                         (BL_CALLBACK_TABLE_ADDRESS->vBootloader.identifier == BL_VERSION_ID_AMiRoBLT_Release) ? "stable" :
264
                         (BL_CALLBACK_TABLE_ADDRESS->vBootloader.identifier == BL_VERSION_ID_AMiRoBLT_ReleaseCandidate) ? "release candidate" :
265
                         (BL_CALLBACK_TABLE_ADDRESS->vBootloader.identifier == BL_VERSION_ID_AMiRoBLT_Beta) ? "beta" :
266
                         (BL_CALLBACK_TABLE_ADDRESS->vBootloader.identifier == BL_VERSION_ID_AMiRoBLT_Alpha) ? "alpha" :
267
                         (BL_CALLBACK_TABLE_ADDRESS->vBootloader.identifier == BL_VERSION_ID_AMiRoBLT_PreAlpha) ? "pre-alpha" :
268
                         "<release type unknown>",
269
                         BL_CALLBACK_TABLE_ADDRESS->vSSSP.major, BL_CALLBACK_TABLE_ADDRESS->vSSSP.minor);
270
    if (BL_CALLBACK_TABLE_ADDRESS->vSSSP.major != AOS_SYSTEM_SSSP_MAJOR) {
271
      if (stream) {
272
        chprintf(stream, "WARNING: Bootloader and AMiRo-OS implement incompatible SSSP versions!\n");
273
      } else {
274
        aosprintf("WARNING: Bootloader and AMiRo-OS implement incompatible SSSP versions!\n");
275
      }
276
    }
277
    _printSystemInfoLine(stream, "Compiler", SYSTEM_INFO_NAMEWIDTH, "%s %u.%u.%u\n", (BL_CALLBACK_TABLE_ADDRESS->vCompiler.identifier == BL_VERSION_ID_GCC) ? "GCC" : "<compiler unknown>", BL_CALLBACK_TABLE_ADDRESS->vCompiler.major, BL_CALLBACK_TABLE_ADDRESS->vCompiler.minor, BL_CALLBACK_TABLE_ADDRESS->vCompiler.patch); // TODO: support other compilers than GCC
278
  } else {
279
    if (stream) {
280
      chprintf(stream, "Bootloader incompatible or not available.\n");
281
    } else {
282
      aosprintf("Bootloader incompatible or not available.\n");
283
    }
284
  }
285
  _printSystemInfoSeparator(stream, '=', SYSTEM_INFO_WIDTH);
286

    
287
  return;
288
}
289

    
290
#if (AMIROOS_CFG_SHELL_ENABLE == true) || defined(__DOXYGEN__)
291
/**
292
 * @brief   Callback function for the system:config shell command.
293
 *
294
 * @param[in] stream    The I/O stream to use.
295
 * @param[in] argc      Number of arguments.
296
 * @param[in] argv      List of pointers to the arguments.
297
 *
298
 * @return              An exit status.
299
 * @retval  AOS_OK                  The command was executed successfuly.
300
 * @retval  AOS_INVALID_ARGUMENTS   There was an issue with the arguemnts.
301
 */
302
static int _shellcmd_configcb(BaseSequentialStream* stream, int argc, char* argv[])
303
{
304
  aosDbgCheck(stream != NULL);
305

    
306
  // local variables
307
  int retval = AOS_INVALID_ARGUMENTS;
308

    
309
  // if there are additional arguments
310
  if (argc > 1) {
311
    // if the user wants to set or retrieve the shell configuration
312
    if (strcmp(argv[1], "--shell") == 0) {
313
      // if the user wants to modify the shell configuration
314
      if (argc > 2) {
315
        // if the user wants to modify the prompt
316
        if (strcmp(argv[2], "prompt") == 0) {
317
          // there must be a further argument
318
          if (argc > 3) {
319
            // handle the option
320
            if (strcmp(argv[3], "text") == 0) {
321
              aos.shell->config &= ~AOS_SHELL_CONFIG_PROMPT_MINIMAL;
322
              retval = AOS_OK;
323
            }
324
            else if (strcmp(argv[3], "minimal") == 0) {
325
              aos.shell->config |= AOS_SHELL_CONFIG_PROMPT_MINIMAL;
326
              retval = AOS_OK;
327
            }
328
            else if (strcmp(argv[3], "notime") == 0) {
329
              aos.shell->config &= ~AOS_SHELL_CONFIG_PROMPT_UPTIME;
330
              retval = AOS_OK;
331
            }
332
            else if (strcmp(argv[3], "uptime") == 0) {
333
              aos.shell->config |= AOS_SHELL_CONFIG_PROMPT_UPTIME;
334
              retval = AOS_OK;
335
            }
336
          }
337
        }
338
        // if the user wants to modify the string matching
339
        else if (strcmp(argv[2], "match") == 0) {
340
          // there must be a further argument
341
          if (argc > 3) {
342
            if (strcmp(argv[3], "casesensitive") == 0) {
343
              aos.shell->config |= AOS_SHELL_CONFIG_MATCH_CASE;
344
              retval = AOS_OK;
345
            }
346
            else if (strcmp(argv[3], "caseinsensitive") == 0) {
347
              aos.shell->config &= ~AOS_SHELL_CONFIG_MATCH_CASE;
348
              retval = AOS_OK;
349
            }
350
          }
351
        }
352
      }
353
      // if the user wants to retrieve the shell configuration
354
      else {
355
        chprintf(stream, "current shell configuration:\n");
356
        chprintf(stream, "  prompt text:   %s\n",
357
                 (aos.shell->prompt != NULL) ? aos.shell->prompt : "n/a");
358
        chprintf(stream, "  prompt style:  %s, %s\n",
359
                 (aos.shell->config & AOS_SHELL_CONFIG_PROMPT_MINIMAL) ? "minimal" : "text",
360
                 (aos.shell->config & AOS_SHELL_CONFIG_PROMPT_UPTIME) ? "system uptime" : "no time");
361
        chprintf(stream, "  input method:  %s\n",
362
                 (aos.shell->config & AOS_SHELL_CONFIG_INPUT_OVERWRITE) ? "replace" : "insert");
363
        chprintf(stream, "  text matching: %s\n",
364
                 (aos.shell->config & AOS_SHELL_CONFIG_MATCH_CASE) ? "case sensitive" : "case insensitive");
365
        retval = AOS_OK;
366
      }
367
    }
368
  }
369

    
370
  // print help, if required
371
  if (retval == AOS_INVALID_ARGUMENTS) {
372
    chprintf(stream, "Usage: %s OPTION\n", argv[0]);
373
    chprintf(stream, "Options:\n");
374
    chprintf(stream, "  --help\n");
375
    chprintf(stream, "    Print this help text.\n");
376
    chprintf(stream, "  --shell [OPT [VAL]]\n");
377
    chprintf(stream, "    Set or retrieve shell configuration.\n");
378
    chprintf(stream, "    Possible OPTs and VALs are:\n");
379
    chprintf(stream, "      prompt text|minimal|uptime|notime\n");
380
    chprintf(stream, "        Configures the prompt.\n");
381
    chprintf(stream, "      match casesensitive|caseinsenitive\n");
382
    chprintf(stream, "        Configures string matching.\n");
383
  }
384

    
385
  return (argc > 1 && strcmp(argv[1], "--help") == 0) ? AOS_OK : retval;
386
}
387

    
388
/**
389
 * @brief   Callback function for the system:info shell command.
390
 *
391
 * @param[in] stream    The I/O stream to use.
392
 * @param[in] argc      Number of arguments.
393
 * @param[in] argv      List of pointers to the arguments.
394
 *
395
 * @return            An exit status.
396
 * @retval  AOS_OK    The command was executed successfully.
397
 */
398
static int _shellcmd_infocb(BaseSequentialStream* stream, int argc, char* argv[])
399
{
400
  aosDbgCheck(stream != NULL);
401

    
402
  (void)argc;
403
  (void)argv;
404

    
405
  // print system information
406
  _printSystemInfo(stream);
407

    
408
  // print time measurement precision
409
  chprintf(stream, "system time resolution: %uus\n", AOS_SYSTEM_TIME_RESOLUTION);
410

    
411
  // print system uptime
412
  aos_timestamp_t uptime;
413
  aosSysGetUptime(&uptime);
414
  chprintf(stream, "The system is running for\n");
415
  chprintf(stream, "%10u days\n", (uint32_t)(uptime / MICROSECONDS_PER_DAY));
416
  chprintf(stream, "%10u hours\n", (uint8_t)(uptime % MICROSECONDS_PER_DAY / MICROSECONDS_PER_HOUR));
417
  chprintf(stream, "%10u minutes\n", (uint8_t)(uptime % MICROSECONDS_PER_HOUR / MICROSECONDS_PER_MINUTE));
418
  chprintf(stream, "%10u seconds\n", (uint8_t)(uptime % MICROSECONDS_PER_MINUTE / MICROSECONDS_PER_SECOND));
419
  chprintf(stream, "%10u milliseconds\n", (uint16_t)(uptime % MICROSECONDS_PER_SECOND / MICROSECONDS_PER_MILLISECOND));
420
  chprintf(stream, "%10u microseconds\n", (uint16_t)(uptime % MICROSECONDS_PER_MILLISECOND / MICROSECONDS_PER_MICROSECOND));
421

    
422
  return AOS_OK;
423
}
424

    
425
/**
426
 * @brief   Callback function for the sytem:shutdown shell command.
427
 *
428
 * @param[in] stream    The I/O stream to use.
429
 * @param[in] argc      Number of arguments.
430
 * @param[in] argv      List of pointers to the arguments.
431
 *
432
 * @return              An exit status.
433
 * @retval  AOS_OK                  The command was executed successfully.
434
 * @retval  AOS_INVALID_ARGUMENTS   There was an issue with the arguments.
435
 */
436
static int _shellcmd_shutdowncb(BaseSequentialStream* stream, int argc, char* argv[])
437
{
438
  aosDbgCheck(stream != NULL);
439

    
440
  // print help text
441
  if (argc != 2 || strcmp(argv[1], "--help") == 0) {
442
    chprintf(stream, "Usage: %s OPTION\n", argv[0]);
443
    chprintf(stream, "Options:\n");
444
    chprintf(stream, "  --help\n");
445
    chprintf(stream, "    Print this help text.\n");
446
    chprintf(stream, "  --hibernate, -h\n");
447
    chprintf(stream, "    Shutdown to hibernate mode.\n");
448
    chprintf(stream, "    Least energy saving, but allows charging via pins.\n");
449
    chprintf(stream, "  --deepsleep, -d\n");
450
    chprintf(stream, "    Shutdown to deepsleep mode.\n");
451
    chprintf(stream, "    Minimum energy consumption while allowing charging via plug.\n");
452
    chprintf(stream, "  --transportation, -t\n");
453
    chprintf(stream, "    Shutdown to transportation mode.\n");
454
    chprintf(stream, "    Minimum energy consumption with all interrupts disabled (no charging).\n");
455
    chprintf(stream, "  --restart, -r\n");
456
    chprintf(stream, "    Shutdown and restart system.\n");
457

    
458
    return (argc != 2) ? AOS_INVALID_ARGUMENTS : AOS_OK;
459
  }
460
  // handle argument
461
  else {
462
    if (strcmp(argv[1], "-h") == 0 || strcmp(argv[1], "--hibernate") == 0) {
463
      chEvtBroadcastFlags(&aos.events.os.source, AOS_SYSTEM_EVENTFLAGS_HIBERNATE);
464
      chThdTerminate(currp);
465
      return AOS_OK;
466
    }
467
    else if (strcmp(argv[1], "-d") == 0 || strcmp(argv[1], "--deepsleep") == 0) {
468
      chEvtBroadcastFlags(&aos.events.os.source, AOS_SYSTEM_EVENTFLAGS_DEEPSLEEP);
469
      chThdTerminate(currp);
470
      return AOS_OK;
471
    }
472
    else if (strcmp(argv[1], "-t") == 0 || strcmp(argv[1], "--transportation") == 0) {
473
      chEvtBroadcastFlags(&aos.events.os.source, AOS_SYSTEM_EVENTFLAGS_TRANSPORTATION);
474
      chThdTerminate(currp);
475
      return AOS_OK;
476
    }
477
    else if (strcmp(argv[1], "-r") == 0 || strcmp(argv[1], "--restart") == 0) {
478
      chEvtBroadcastFlags(&aos.events.os.source, AOS_SYSTEM_EVENTFLAGS_RESTART);
479
      chThdTerminate(currp);
480
      return AOS_OK;
481
    }
482
    else {
483
      chprintf(stream, "unknown argument %s\n", argv[1]);
484
      return AOS_INVALID_ARGUMENTS;
485
    }
486
  }
487
}
488
#endif /* AMIROOS_CFG_SHELL_ENABLE == true */
489

    
490
#if (AMIROOS_CFG_TESTS_ENABLE == true) || defined(__DOXYGEN__)
491
/**
492
 * @brief   Callback function for the kernel:test shell command.
493
 *
494
 * @param[in] stream    The I/O stream to use.
495
 * @param[in] argc      Number of arguments.
496
 * @param[in] argv      List of pointers to the arguments.
497
 *
498
 * @return      An exit status.
499
 */
500
static int _shellcmd_kerneltestcb(BaseSequentialStream* stream, int argc, char* argv[])
501
{
502
  aosDbgCheck(stream != NULL);
503

    
504
  (void)argc;
505
  (void)argv;
506

    
507
  tprio_t prio = chThdGetPriorityX();
508
  chThdSetPriority(HIGHPRIO - 5); // some tests increase priorirty by 5, so this is the maximum priority permitted
509
  msg_t retval = test_execute(stream);
510
  chThdSetPriority(prio);
511

    
512
  return retval;
513
}
514
#endif /* AMIROOS_CFG_TESTS_ENABLE == true */
515

    
516
/**
517
 * @brief   Callback function for the PD signal interrupt.
518
 *
519
 * @param[in] extp      Pointer to the interrupt driver object.
520
 * @param[in] channel   Interrupt channel identifier.
521
 */
522
static void _signalPdCallback(EXTDriver* extp, expchannel_t channel)
523
{
524
  (void)extp;
525
  (void)channel;
526

    
527
  chSysLockFromISR();
528
  chEvtBroadcastFlagsI(&aos.events.io.source, aos.events.io.flagsSignalPd);
529
  chSysUnlockFromISR();
530

    
531
  return;
532
}
533

    
534
/**
535
 * @brief   Callback function for the Sync signal interrupt.
536
 *
537
 * @param[in] extp      Pointer to the interrupt driver object.
538
 * @param[in] channel   Interrupt channel identifier.
539
 */
540
static void _signalSyncCallback(EXTDriver* extp, expchannel_t channel)
541
{
542
  (void)extp;
543
  (void)channel;
544

    
545
#if (AMIROOS_CFG_SSSP_MASTER == true)
546
  chSysLockFromISR();
547
  chEvtBroadcastFlagsI(&aos.events.io.source, aos.events.io.flagsSignalSync);
548
  chSysUnlockFromISR();
549
#else
550
  apalControlGpioState_t s_state;
551
  aos_timestamp_t uptime;
552

    
553
  chSysLockFromISR();
554
  // get current uptime
555
  aosSysGetUptimeX(&uptime);
556
  // read signal S
557
  apalControlGpioGet(_gpioSync, &s_state);
558
  // if S was toggled from on to off during SSSP operation phase
559
  if (aos.ssspStage == AOS_SSSP_OPERATION && s_state == APAL_GPIO_OFF) {
560
    // align the uptime with the synchronization period
561
    if (uptime % AMIROOS_CFG_SSSP_SYSSYNCPERIOD < AMIROOS_CFG_SSSP_SYSSYNCPERIOD / 2) {
562
      _uptime -= uptime % AMIROOS_CFG_SSSP_SYSSYNCPERIOD;
563
    } else {
564
      _uptime += AMIROOS_CFG_SSSP_SYSSYNCPERIOD - (uptime % AMIROOS_CFG_SSSP_SYSSYNCPERIOD);
565
    }
566
  }
567
  // broadcast event
568
  chEvtBroadcastFlagsI(&aos.events.io.source, aos.events.io.flagsSignalSync);
569
  chSysUnlockFromISR();
570
#endif
571

    
572
  return;
573
}
574

    
575
/**
576
 * @brief   Callback function for the uptime accumulation timer.
577
 *
578
 * @param[in] par   Generic parameter.
579
 */
580
#include <module.h>
581
static void _uptimeCallback(void* par)
582
{
583
  (void)par;
584

    
585
  chSysLockFromISR();
586
  // read current time in system ticks
587
  register const systime_t st = chVTGetSystemTimeX();
588
  // update the uptime variables
589
  _uptime += LL_ST2US(st - _synctime);
590
  _synctime = st;
591
  // enable the timer again
592
  chVTSetI(&_systimer, SYSTIMER_PERIOD, &_uptimeCallback, NULL);
593
  chSysUnlockFromISR();
594

    
595
  return;
596
}
597

    
598
#if (AMIROOS_CFG_SSSP_MASTER == true) || defined (__DOXYGEN__)
599
/**
600
 * @brief   Periodic system synchronization callback function.
601
 * @details Toggles the SYS_SYNC signal and reconfigures the system synchronization timer.
602
 *
603
 * @param[in] par   Unuesed parameters.
604
 */
605
static void _sysSyncTimerCallback(void* par)
606
{
607
  (void)par;
608

    
609
  apalControlGpioState_t s_state;
610
  aos_timestamp_t uptime;
611

    
612
  chSysLockFromISR();
613
  // read and toggle signal S
614
  apalControlGpioGet(_gpioSync, &s_state);
615
  s_state = (s_state == APAL_GPIO_ON) ? APAL_GPIO_OFF : APAL_GPIO_ON;
616
  apalControlGpioSet(_gpioSync, s_state);
617
  // if S was toggled from off to on
618
  if (s_state == APAL_GPIO_ON) {
619
    // reconfigure the timer precisely, because the logically falling edge (next interrupt) snychronizes the system time
620
    _syssynctime += AMIROOS_CFG_SSSP_SYSSYNCPERIOD;
621
    aosSysGetUptimeX(&uptime);
622
    chVTSetI(&_syssynctimer, LL_US2ST(_syssynctime - uptime), _sysSyncTimerCallback, NULL);
623
  }
624
  // if S was toggled from on to off
625
  else /* if (s_state == APAL_GPIO_OFF) */ {
626
    // reconfigure the timer (lazy)
627
    chVTSetI(&_syssynctimer, LL_US2ST(AMIROOS_CFG_SSSP_SYSSYNCPERIOD / 2), _sysSyncTimerCallback, NULL);
628
  }
629
  chSysUnlockFromISR();
630

    
631
  return;
632
}
633
#endif
634

    
635
/**
636
 * @brief   AMiRo-OS system initialization.
637
 * @note    Must be called from the system control thread (usually main thread).
638
 *
639
 * @param[in] extDrv        Pointer to the interrupt driver.
640
 * @param[in] extCfg        Configuration for the interrupt driver.
641
 * @param[in] gpioPd        GPIO of the PD signal.
642
 * @param[in] gpioSync      GPIO of the Sync signal
643
 * @param[in] evtFlagsPd    Event flags to be set when a PD interrupt occurs.
644
 * @param[in] evtFlagsSync  Event flags to be set when a Sync interrupt occurs.
645
 * @param[in] shellPrompt   String to be printed as prompt of the system shell.
646
 * @param[in] stdio         Default (usually physically) interface for I/O like shell.
647
 */
648
void aosSysInit(EXTDriver* extDrv,
649
                EXTConfig* extCfg,
650
                apalControlGpio_t* gpioPd,
651
                apalControlGpio_t* gpioSync,
652
                eventflags_t evtFlagsPd,
653
                eventflags_t evtFlagsSync,
654
                const char* shellPrompt)
655
{
656
  // check arguments
657
  aosDbgCheck(extDrv != NULL);
658
  aosDbgCheck(extCfg != NULL);
659
  aosDbgCheck(gpioPd != NULL);
660
  aosDbgCheck(gpioSync != NULL);
661

    
662
  // set control thread to maximum priority
663
  chThdSetPriority(THD_CTRLPRIO);
664

    
665
  // set local variables
666
  _gpioPd = gpioPd;
667
  _gpioSync = gpioSync;
668
  chVTObjectInit(&_systimer);
669
  _synctime = 0;
670
  _uptime = 0;
671
#if (AMIROOS_CFG_SSSP_MASTER == true)
672
  chVTObjectInit(&_syssynctimer);
673
  _syssynctime = 0;
674
#endif
675

    
676
  // set aos configuration
677
  aos.ssspStage = AOS_SSSP_STARTUP_2_1;
678
  aosIOStreamInit(&aos.iostream);
679
  chEvtObjectInit(&aos.events.io.source);
680
  chEvtObjectInit(&aos.events.os.source);
681
  aos.events.io.flagsSignalPd = evtFlagsPd;
682
  aos.events.io.flagsSignalSync = evtFlagsSync;
683

    
684
  // setup external interrupt system
685
  extCfg->channels[gpioPd->gpio->pad].cb = _signalPdCallback;
686
  extCfg->channels[gpioSync->gpio->pad].cb = _signalSyncCallback;
687
  extStart(extDrv, extCfg);
688

    
689
#if (AMIROOS_CFG_SHELL_ENABLE == true)
690
  // init shell
691
  aosShellInit(aos.shell,
692
               &aos.events.os.source,
693
               shellPrompt,
694
               _shell_line,
695
               AMIROOS_CFG_SHELL_LINEWIDTH,
696
               _shell_arglist,
697
               AMIROOS_CFG_SHELL_MAXARGS);
698
  // add system commands
699
  aosShellAddCommand(aos.shell, &_shellcmd_config);
700
  aosShellAddCommand(aos.shell, &_shellcmd_info);
701
  aosShellAddCommand(aos.shell, &_shellcmd_shutdown);
702
#if (AMIROOS_CFG_TESTS_ENABLE == true)
703
  aosShellAddCommand(aos.shell, &_shellcmd_kerneltest);
704
#endif
705
#else
706
  (void)shellPrompt;
707
#endif
708

    
709
  return;
710
}
711

    
712
/**
713
 * @brief   Starts the system and all system threads.
714
 */
715
inline void aosSysStart(void)
716
{
717
  // update the system SSSP stage
718
  aos.ssspStage = AOS_SSSP_OPERATION;
719

    
720
  // print system information;
721
  _printSystemInfo((BaseSequentialStream*)&aos.iostream);
722
  aosprintf("\n");
723

    
724
#if (AMIROOS_CFG_SHELL_ENABLE == true)
725
  // start system shell thread
726
  aos.shell->thread = chThdCreateStatic(_shell_wa, sizeof(_shell_wa), AMIROOS_CFG_SHELL_THREADPRIO, aosShellThread, aos.shell);
727
#endif
728

    
729
  return;
730
}
731

    
732
/**
733
 * @brief   Implements the SSSP startup synchronization step.
734
 *
735
 * @param[in] syncEvtListener   Event listener that receives the Sync event.
736
 *
737
 * @return    If another event that the listener is interested in was received, its mask is returned.
738
 *            Otherwise an empty mask (0) is returned.
739
 */
740
eventmask_t aosSysSsspStartupOsInitSyncCheck(event_listener_t* syncEvtListener)
741
{
742
  aosDbgCheck(syncEvtListener != NULL);
743

    
744
  // local variables
745
  eventmask_t m;
746
  eventflags_t f;
747
  apalControlGpioState_t s;
748

    
749
  // update the system SSSP stage
750
  aos.ssspStage = AOS_SSSP_STARTUP_2_2;
751

    
752
  // deactivate the sync signal to indicate that the module is ready (SSSPv1 stage 2.1 of startup phase)
753
  apalControlGpioSet(_gpioSync, APAL_GPIO_OFF);
754

    
755
  // wait for any event to occur (do not apply any filter in order not to miss any event)
756
  m = chEvtWaitOne(ALL_EVENTS);
757
  f = chEvtGetAndClearFlags(syncEvtListener);
758
  apalControlGpioGet(_gpioSync, &s);
759

    
760
  // if the event was a system event,
761
  //   and it was fired because of the SysSync control signal,
762
  //   and the SysSync control signal has been deactivated
763
  if (m & syncEvtListener->events &&
764
      f == aos.events.io.flagsSignalSync &&
765
      s == APAL_GPIO_OFF) {
766
    chSysLock();
767
#if (AMIROOS_CFG_SSSP_MASTER == true)
768
    // start the systen synchronization counter
769
    chVTSetI(&_syssynctimer, LL_US2ST(AMIROOS_CFG_SSSP_SYSSYNCPERIOD / 2), &_sysSyncTimerCallback, NULL);
770
#endif
771
    // start the uptime counter
772
    _synctime = chVTGetSystemTimeX();
773
    _uptime = 0;
774
    chVTSetI(&_systimer, SYSTIMER_PERIOD, &_uptimeCallback, NULL);
775
    chSysUnlock();
776

    
777
    return 0;
778
  }
779
  // an unexpected event occurred
780
  else {
781
    // reassign the flags to the event and return the event mask
782
    syncEvtListener->flags |= f;
783
    return m;
784
  }
785
}
786

    
787
/**
788
 * @brief   Retrieves the system uptime.
789
 *
790
 * @param[out] ut   The system uptime.
791
 */
792
inline void aosSysGetUptimeX(aos_timestamp_t* ut)
793
{
794
  aosDbgCheck(ut != NULL);
795

    
796
  *ut = _uptime + LL_ST2US(chVTGetSystemTimeX() - _synctime);
797

    
798
  return;
799
}
800

    
801
/**
802
 * @brief   Initializes/Acknowledges a system shutdown/restart request.
803
 * @note    This functions should be called from the thread with highest priority.
804
 *
805
 * @param[in] shutdown    Type of shutdown.
806
 */
807
void aosSysShutdownInit(aos_shutdown_t shutdown)
808
{
809
  // check arguments
810
  aosDbgCheck(shutdown != AOS_SHUTDOWN_NONE);
811

    
812
#if (AMIROOS_CFG_SSSP_MASTER == true)
813
  // deactivate the system synchronization timer
814
  chVTReset(&_syssynctimer);
815
#endif
816

    
817
  // update the system SSSP stage
818
  aos.ssspStage = AOS_SSSP_SHUTDOWN_1_1;
819

    
820
  // activate the SYS_PD control signal only, if this module initiated the shutdown
821
  chSysLock();
822
  if (shutdown != AOS_SHUTDOWN_PASSIVE) {
823
    apalControlGpioSet(_gpioPd, APAL_GPIO_ON);
824
  }
825
  // activate the SYS_SYNC signal
826
  apalControlGpioSet(_gpioSync, APAL_GPIO_ON);
827
  chSysUnlock();
828

    
829
  switch (shutdown) {
830
    case AOS_SHUTDOWN_PASSIVE:
831
      chEvtBroadcastFlags(&aos.events.os.source, AOS_SYSTEM_EVENTFLAGS_SHUTDOWN);
832
      aosprintf("shutdown request received...\n");
833
      break;
834
    case AOS_SHUTDOWN_HIBERNATE:
835
      chEvtBroadcastFlags(&aos.events.os.source, AOS_SYSTEM_EVENTFLAGS_HIBERNATE);
836
      aosprintf("shutdown to hibernate mode...\n");
837
      break;
838
    case AOS_SHUTDOWN_DEEPSLEEP:
839
      chEvtBroadcastFlags(&aos.events.os.source, AOS_SYSTEM_EVENTFLAGS_DEEPSLEEP);
840
      aosprintf("shutdown to deepsleep mode...\n");
841
      break;
842
    case AOS_SHUTDOWN_TRANSPORTATION:
843
      chEvtBroadcastFlags(&aos.events.os.source, AOS_SYSTEM_EVENTFLAGS_TRANSPORTATION);
844
      aosprintf("shutdown to transportation mode...\n");
845
      break;
846
    case AOS_SHUTDOWN_RESTART:
847
      chEvtBroadcastFlags(&aos.events.os.source, AOS_SYSTEM_EVENTFLAGS_RESTART);
848
      aosprintf("restarting system...\n");
849
      break;
850
   // must never occur
851
   case AOS_SHUTDOWN_NONE:
852
   default:
853
      break;
854
  }
855

    
856
  // update the system SSSP stage
857
  aos.ssspStage = AOS_SSSP_SHUTDOWN_1_2;
858

    
859
  return;
860
}
861

    
862
/**
863
 * @brief   Stops the system and all related threads (not the thread this function is called from).
864
 */
865
void aosSysStop(void)
866
{
867
#if (AMIROOS_CFG_SHELL_ENABLE == true)
868
  chThdWait(aos.shell->thread);
869
#endif
870

    
871
  return;
872
}
873

    
874
/**
875
 * @brief   Deinitialize all system variables.
876
 */
877
void aosSysDeinit(void)
878
{
879
  return;
880
}
881

    
882
/**
883
 * @brief   Finally shuts down the system and calls the bootloader callback function.
884
 * @note    This function should be called from the thtead with highest priority.
885
 *
886
 * @param[in] extDrv      Pointer to the interrupt driver.
887
 * @param[in] shutdown    Type of shutdown.
888
 */
889
void aosSysShutdownFinal(EXTDriver* extDrv, aos_shutdown_t shutdown)
890
{
891
  // check arguments
892
  aosDbgCheck(extDrv != NULL);
893
  aosDbgCheck(shutdown != AOS_SHUTDOWN_NONE);
894

    
895
  // stop external interrupt system
896
  extStop(extDrv);
897

    
898
  // update the system SSSP stage
899
  aos.ssspStage = AOS_SSSP_SHUTDOWN_1_3;
900

    
901
  // call bootloader callback depending on arguments
902
  switch (shutdown) {
903
    case AOS_SHUTDOWN_PASSIVE:
904
      BL_CALLBACK_TABLE_ADDRESS->cbHandleShutdownRequest();
905
      break;
906
    case AOS_SHUTDOWN_HIBERNATE:
907
      BL_CALLBACK_TABLE_ADDRESS->cbShutdownHibernate();
908
      break;
909
    case AOS_SHUTDOWN_DEEPSLEEP:
910
      BL_CALLBACK_TABLE_ADDRESS->cbShutdownDeepsleep();
911
      break;
912
    case AOS_SHUTDOWN_TRANSPORTATION:
913
      BL_CALLBACK_TABLE_ADDRESS->cbShutdownTransportation();
914
      break;
915
    case AOS_SHUTDOWN_RESTART:
916
      BL_CALLBACK_TABLE_ADDRESS->cbShutdownRestart();
917
      break;
918
    // must never occur
919
    case AOS_SHUTDOWN_NONE:
920
    default:
921
      break;
922
  }
923

    
924
  return;
925
}