Statistics
| Branch: | Tag: | Revision:

amiro-os / core / src / aos_system.c @ 1816cbc6

History | View | Annotate | Download (36.8 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
/**
20
 * @file    aos_system.c
21
 * @brief   System code.
22
 * @details Contains system initialization and shutdown routines
23
 *          and system shell commands.
24
 *
25
 * @addtogroup aos_system
26
 * @{
27
 */
28

    
29
#include <aos_system.h>
30

    
31
#include <amiroos.h>
32
#include <amiroblt.h>
33
#include <module.h>
34
#include <string.h>
35
#include <stdlib.h>
36
#if (AMIROOS_CFG_TESTS_ENABLE == true)
37
#include <ch_test.h>
38
#include <rt_test_root.h>
39
#endif
40

    
41
/**
42
 * @brief   Period of the system timer.
43
 */
44
#define SYSTIMER_PERIOD               (TIME_MAX_SYSTIME - CH_CFG_ST_TIMEDELTA)
45

    
46
/**
47
 * @brief   Width of the printable system info text.
48
 */
49
#define SYSTEM_INFO_WIDTH             70
50

    
51
/**
52
 * @brief   Width of the name column of the system info table.
53
 */
54
#define SYSTEM_INFO_NAMEWIDTH         14
55

    
56
/* forward declarations */
57
static void _printSystemInfo(BaseSequentialStream* stream);
58
#if (AMIROOS_CFG_SHELL_ENABLE == true)
59
static int _shellcmd_configcb(BaseSequentialStream* stream, int argc, char* argv[]);
60
static int _shellcmd_infocb(BaseSequentialStream* stream, int argc, char* argv[]);
61
static int _shellcmd_shutdowncb(BaseSequentialStream* stream, int argc, char* argv[]);
62
#if (AMIROOS_CFG_TESTS_ENABLE == true)
63
static int _shellcmd_kerneltestcb(BaseSequentialStream* stream, int argc, char* argv[]);
64
#endif /* AMIROOS_CFG_TESTS_ENABLE == true */
65
#endif /* AMIROOS_CFG_SHELL_ENABLE == true */
66

    
67
/**
68
 * @brief   Timer to accumulate system uptime.
69
 */
70
static virtual_timer_t _systimer;
71

    
72
/**
73
 * @brief   Accumulated system uptime.
74
 */
75
static aos_timestamp_t _uptime;
76

    
77
/**
78
 * @brief   Timer register value of last accumulation.
79
 */
80
static systime_t _synctime;
81

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

    
88
/**
89
 * @brief   Last uptime of system wide time synchronization.
90
 */
91
static aos_timestamp_t _syssynctime;
92
#endif
93

    
94
#if ((AMIROOS_CFG_SSSP_MASTER != true) && (AMIROOS_CFG_PROFILE == true)) || defined(__DOXYGEN__)
95
/**
96
 * @brief   Offset between local clock and system wide synchronization signal.
97
 */
98
static float _syssyncskew;
99

    
100
/**
101
 * @brief   Weighting factor for the low-pass filter used for calculating the @p _syssyncskew value.
102
 */
103
#define SYSTEM_SYSSYNCSKEW_LPFACTOR   (0.1f / AOS_SYSTEM_TIME_RESOLUTION)
104
#endif
105

    
106
#if (AMIROOS_CFG_SHELL_ENABLE == true) || defined(__DOXYGEN__)
107
/**
108
 * @brief   Shell thread working area.
109
 */
110
THD_WORKING_AREA(_shell_wa, AMIROOS_CFG_SHELL_STACKSIZE);
111

    
112
/**
113
 * @brief   Shell input buffer.
114
 */
115
static char _shell_line[AMIROOS_CFG_SHELL_LINEWIDTH];
116

    
117
/**
118
 * @brief   Shell argument buffer.
119
 */
120
static char* _shell_arglist[AMIROOS_CFG_SHELL_MAXARGS];
121

    
122
/**
123
 * @brief   Shell command to retrieve system information.
124
 */
125
static aos_shellcommand_t _shellcmd_info = {
126
  /* name     */ "module:info",
127
  /* callback */ _shellcmd_infocb,
128
  /* next     */ NULL,
129
};
130

    
131
/**
132
 * @brief   Shell command to set or retrieve system configuration.
133
 */
134
static aos_shellcommand_t _shellcmd_config = {
135
  /* name     */ "module:config",
136
  /* callback */ _shellcmd_configcb,
137
  /* next     */ NULL,
138
};
139

    
140
/**
141
 * @brief   Shell command to shutdown the system.
142
 */
143
static aos_shellcommand_t _shellcmd_shutdown = {
144
  /* name     */ "system:shutdown",
145
  /* callback */ _shellcmd_shutdowncb,
146
  /* next     */ NULL,
147
};
148
#endif /* AMIROOS_CFG_SHELL_ENABLE == true */
149

    
150
#if (AMIROOS_CFG_TESTS_ENABLE == true) || defined(__DOXYGEN__)
151
/**
152
 * @brief   Shell kommand to run a test of the ChibiOS/RT kernel.
153
 */
154
static aos_shellcommand_t _shellcmd_kerneltest = {
155
  /* name     */ "kernel:test",
156
  /* callback */ _shellcmd_kerneltestcb,
157
  /* next     */ NULL,
158
};
159
#endif /* AMIROOS_CFG_TESTS_ENABLE == true */
160

    
161
/**
162
 * @brief   Global system object.
163
 */
164
aos_system_t aos;
165

    
166
/**
167
 * @brief   Print a separator line.
168
 *
169
 * @param[in] stream    Stream to print to or NULL to print to all system streams.
170
 * @param[in] c         Character to use.
171
 * @param[in] n         Length of the separator line.
172
 *
173
 * @return  Number of characters printed.
174
 */
175
static unsigned int _printSystemInfoSeparator(BaseSequentialStream* stream, const char c, const unsigned int n)
176
{
177
  aosDbgCheck(stream != NULL);
178

    
179
  // print the specified character n times
180
  for (unsigned int i = 0; i < n; ++i) {
181
    streamPut(stream, c);
182
  }
183
  streamPut(stream, '\n');
184

    
185
  return n+1;
186
}
187

    
188
/**
189
 * @brief   Print a system information line.
190
 * @details Prints a system information line with the following format:
191
 *            "<name>[spaces]fmt"
192
 *          The combined width of "<name>[spaces]" can be specified in order to align <fmt> on multiple lines.
193
 *          Note that there is not trailing newline added implicitely.
194
 *
195
 * @param[in] stream      Stream to print to or NULL to print to all system streams.
196
 * @param[in] name        Name of the entry/line.
197
 * @param[in] namewidth   Width of the name column.
198
 * @param[in] fmt         Formatted string of information content.
199
 *
200
 * @return  Number of characters printed.
201
 */
202
static unsigned int _printSystemInfoLine(BaseSequentialStream* stream, const char* name, const unsigned int namewidth, const char* fmt, ...)
203
{
204
  aosDbgCheck(stream != NULL);
205
  aosDbgCheck(name != NULL);
206

    
207
  unsigned int n = 0;
208
  va_list ap;
209

    
210
  va_start(ap, fmt);
211
  n += chprintf(stream, name);
212
  while (n < namewidth) {
213
    streamPut(stream, ' ');
214
    ++n;
215
  }
216
  n += chvprintf(stream, fmt, ap);
217
  va_end(ap);
218

    
219
  streamPut(stream, '\n');
220
  ++n;
221

    
222
  return n;
223
}
224

    
225
/**
226
 * @brief   Prints information about the system.
227
 *
228
 * @param[in] stream    Stream to print to.
229
 */
230
static void _printSystemInfo(BaseSequentialStream* stream)
231
{
232
  aosDbgCheck(stream != NULL);
233

    
234
  // local variables
235
  struct tm dt;
236
  aosSysGetDateTime(&dt);
237

    
238
  // print static information about module and operating system
239
  _printSystemInfoSeparator(stream, '=', SYSTEM_INFO_WIDTH);
240
#ifdef BOARD_VERSION
241
  _printSystemInfoLine(stream, "Module", SYSTEM_INFO_NAMEWIDTH, "%s (v%s)", BOARD_NAME, BOARD_VERSION);
242
#else
243
  _printSystemInfoLine(stream, "Module", SYSTEM_INFO_NAMEWIDTH, "%s", BOARD_NAME);
244
#endif
245
#ifdef PLATFORM_NAME
246
  _printSystemInfoLine(stream, "Platform", SYSTEM_INFO_NAMEWIDTH, "%s", PLATFORM_NAME);
247
#endif
248
#ifdef PORT_CORE_VARIANT_NAME
249
  _printSystemInfoLine(stream, "Core Variant", SYSTEM_INFO_NAMEWIDTH, "%s", PORT_CORE_VARIANT_NAME);
250
#endif
251
  _printSystemInfoLine(stream, "Architecture", SYSTEM_INFO_NAMEWIDTH, "%s", PORT_ARCHITECTURE_NAME);
252
  _printSystemInfoSeparator(stream, '-', SYSTEM_INFO_WIDTH);
253
  _printSystemInfoLine(stream, "AMiRo-OS" , SYSTEM_INFO_NAMEWIDTH, "%u.%u.%u %s (SSSP %u.%u)", AMIROOS_VERSION_MAJOR, AMIROOS_VERSION_MINOR, AMIROOS_VERSION_PATCH, AMIROOS_RELEASE_TYPE, AOS_SYSTEM_SSSP_VERSION_MAJOR, AOS_SYSTEM_SSSP_VERSION_MINOR);
254
  _printSystemInfoLine(stream, "AMiRo-LLD" , SYSTEM_INFO_NAMEWIDTH, "%u.%u.%u %s (periphAL %u.%u)", 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", 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", 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", (AMIROOS_CFG_DBG == true) ? "debug" : "release");
258
  _printSystemInfoLine(stream, "Compiler" , SYSTEM_INFO_NAMEWIDTH, "%s %u.%u.%u", "GCC", __GNUC__, __GNUC_MINOR__, __GNUC_PATCHLEVEL__); // TODO: support other compilers than GCC
259
  _printSystemInfoLine(stream, "Compiled" , SYSTEM_INFO_NAMEWIDTH, "%s - %s", __DATE__, __TIME__);
260

    
261
  // print static information about the bootloader
262
  _printSystemInfoSeparator(stream, '-', SYSTEM_INFO_WIDTH);
263
  if (BL_CALLBACK_TABLE_ADDRESS->magicNumber == BL_MAGIC_NUMBER) {
264
    _printSystemInfoLine(stream, "AMiRo-BLT", SYSTEM_INFO_NAMEWIDTH, "%u.%u.%u %s (SSSP %u.%u)", BL_CALLBACK_TABLE_ADDRESS->vBootloader.major, BL_CALLBACK_TABLE_ADDRESS->vBootloader.minor, BL_CALLBACK_TABLE_ADDRESS->vBootloader.patch,
265
                         (BL_CALLBACK_TABLE_ADDRESS->vBootloader.identifier == BL_VERSION_ID_AMiRoBLT_Release) ? "stable" :
266
                         (BL_CALLBACK_TABLE_ADDRESS->vBootloader.identifier == BL_VERSION_ID_AMiRoBLT_ReleaseCandidate) ? "release candidate" :
267
                         (BL_CALLBACK_TABLE_ADDRESS->vBootloader.identifier == BL_VERSION_ID_AMiRoBLT_Beta) ? "beta" :
268
                         (BL_CALLBACK_TABLE_ADDRESS->vBootloader.identifier == BL_VERSION_ID_AMiRoBLT_Alpha) ? "alpha" :
269
                         (BL_CALLBACK_TABLE_ADDRESS->vBootloader.identifier == BL_VERSION_ID_AMiRoBLT_PreAlpha) ? "pre-alpha" :
270
                         "<release type unknown>",
271
                         BL_CALLBACK_TABLE_ADDRESS->vSSSP.major, BL_CALLBACK_TABLE_ADDRESS->vSSSP.minor);
272
    if (BL_CALLBACK_TABLE_ADDRESS->vSSSP.major != AOS_SYSTEM_SSSP_VERSION_MAJOR) {
273
      if (stream) {
274
        chprintf(stream, "WARNING: Bootloader and AMiRo-OS implement incompatible SSSP versions!\n");
275
      } else {
276
        aosprintf("WARNING: Bootloader and AMiRo-OS implement incompatible SSSP versions!\n");
277
      }
278
    }
279
    _printSystemInfoLine(stream, "Compiler", SYSTEM_INFO_NAMEWIDTH, "%s %u.%u.%u", (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
280
  } else {
281
    if (stream) {
282
      chprintf(stream, "Bootloader incompatible or not available.\n");
283
    } else {
284
      aosprintf("Bootloader incompatible or not available.\n");
285
    }
286
  }
287

    
288
  // print dynamic information about the module
289
  _printSystemInfoSeparator(stream, '-', SYSTEM_INFO_WIDTH);
290
  if (aos.sssp.moduleId != 0) {
291
    _printSystemInfoLine(stream, "Module ID", SYSTEM_INFO_NAMEWIDTH, "%u", aos.sssp.moduleId);
292
  } else {
293
    _printSystemInfoLine(stream, "Module ID", SYSTEM_INFO_NAMEWIDTH, "not available");
294
  }
295
  _printSystemInfoLine(stream, "Date", SYSTEM_INFO_NAMEWIDTH, "%s %02u-%02u-%04u", (dt.tm_wday == 0) ? "Sunday" : (dt.tm_wday == 1) ? "Monday" : (dt.tm_wday == 2) ? "Tuesday" : (dt.tm_wday == 3) ? "Wednesday" : (dt.tm_wday == 4) ? "Thursday" : (dt.tm_wday == 5) ? "Friday" : "Saturday",
296
                       dt.tm_mday,
297
                       dt.tm_mon + 1,
298
                       dt.tm_year + 1900);
299
  _printSystemInfoLine(stream, "Time", SYSTEM_INFO_NAMEWIDTH, "%02u:%02u:%02u", dt.tm_hour, dt.tm_min, dt.tm_sec);
300

    
301
  _printSystemInfoSeparator(stream, '=', SYSTEM_INFO_WIDTH);
302

    
303
  return;
304
}
305

    
306
#if (AMIROOS_CFG_SHELL_ENABLE == true) || defined(__DOXYGEN__)
307
/**
308
 * @brief   Callback function for the system:config shell command.
309
 *
310
 * @param[in] stream    The I/O stream to use.
311
 * @param[in] argc      Number of arguments.
312
 * @param[in] argv      List of pointers to the arguments.
313
 *
314
 * @return              An exit status.
315
 * @retval  AOS_OK                  The command was executed successfuly.
316
 * @retval  AOS_INVALID_ARGUMENTS   There was an issue with the arguemnts.
317
 */
318
static int _shellcmd_configcb(BaseSequentialStream* stream, int argc, char* argv[])
319
{
320
  aosDbgCheck(stream != NULL);
321

    
322
  // local variables
323
  int retval = AOS_INVALID_ARGUMENTS;
324

    
325
  // if there are additional arguments
326
  if (argc > 1) {
327
    // if the user wants to set or retrieve the shell configuration
328
    if (strcmp(argv[1], "--shell") == 0) {
329
      // if the user wants to modify the shell configuration
330
      if (argc > 2) {
331
        // if the user wants to modify the prompt
332
        if (strcmp(argv[2], "prompt") == 0) {
333
          // there must be a further argument
334
          if (argc > 3) {
335
            // handle the option
336
            if (strcmp(argv[3], "text") == 0) {
337
              aos.shell.config &= ~AOS_SHELL_CONFIG_PROMPT_MINIMAL;
338
              retval = AOS_OK;
339
            }
340
            else if (strcmp(argv[3], "minimal") == 0) {
341
              aos.shell.config |= AOS_SHELL_CONFIG_PROMPT_MINIMAL;
342
              retval = AOS_OK;
343
            }
344
            else if (strcmp(argv[3], "notime") == 0) {
345
              aos.shell.config &= ~(AOS_SHELL_CONFIG_PROMPT_UPTIME | AOS_SHELL_CONFIG_PROMPT_DATETIME);
346
              retval = AOS_OK;
347
            }
348
            else if (strcmp(argv[3], "uptime") == 0) {
349
              aos.shell.config &= ~AOS_SHELL_CONFIG_PROMPT_DATETIME;
350
              aos.shell.config |= AOS_SHELL_CONFIG_PROMPT_UPTIME;
351
              retval = AOS_OK;
352
            }
353
            else if (strcmp(argv[3], "date&time") == 0) {
354
              aos.shell.config &= ~AOS_SHELL_CONFIG_PROMPT_UPTIME;
355
              aos.shell.config |= AOS_SHELL_CONFIG_PROMPT_DATETIME;
356
              retval = AOS_OK;
357
            }
358
            else {
359
              chprintf(stream, "unknown option '%s'\n", argv[3]);
360
              return AOS_INVALID_ARGUMENTS;
361
            }
362
          }
363
        }
364
        // if the user wants to modify the string matching
365
        else if (strcmp(argv[2], "match") == 0) {
366
          // there must be a further argument
367
          if (argc > 3) {
368
            if (strcmp(argv[3], "casesensitive") == 0) {
369
              aos.shell.config |= AOS_SHELL_CONFIG_MATCH_CASE;
370
              retval = AOS_OK;
371
            }
372
            else if (strcmp(argv[3], "caseinsensitive") == 0) {
373
              aos.shell.config &= ~AOS_SHELL_CONFIG_MATCH_CASE;
374
              retval = AOS_OK;
375
            }
376
          }
377
        }
378
      }
379
      // if the user wants to retrieve the shell configuration
380
      else {
381
        chprintf(stream, "current shell configuration:\n");
382
        chprintf(stream, "  prompt text:   %s\n",
383
                 (aos.shell.prompt != NULL) ? aos.shell.prompt : "n/a");
384
        char time[10];
385
        switch (aos.shell.config & (AOS_SHELL_CONFIG_PROMPT_UPTIME | AOS_SHELL_CONFIG_PROMPT_DATETIME)) {
386
          case AOS_SHELL_CONFIG_PROMPT_UPTIME:
387
            strcpy(time, "uptime"); break;
388
          case AOS_SHELL_CONFIG_PROMPT_DATETIME:
389
            strcpy(time, "date&time"); break;
390
          default:
391
            strcpy(time, "no time"); break;
392
        }
393
        chprintf(stream, "  prompt style:  %s, %s\n",
394
                 (aos.shell.config & AOS_SHELL_CONFIG_PROMPT_MINIMAL) ? "minimal" : "text",
395
                 time);
396
        chprintf(stream, "  input method:  %s\n",
397
                 (aos.shell.config & AOS_SHELL_CONFIG_INPUT_OVERWRITE) ? "replace" : "insert");
398
        chprintf(stream, "  text matching: %s\n",
399
                 (aos.shell.config & AOS_SHELL_CONFIG_MATCH_CASE) ? "case sensitive" : "case insensitive");
400
        retval = AOS_OK;
401
      }
402
    }
403
    // if the user wants to configure the date or time
404
    else if (strcmp(argv[1], "--date&time") == 0 && argc == 4) {
405
      struct tm dt;
406
      aosSysGetDateTime(&dt);
407
      unsigned int val = atoi(argv[3]);
408
      if (strcmp(argv[2], "year") == 0) {
409
        dt.tm_year = val - 1900;
410
      }
411
      else if (strcmp(argv[2], "month") == 0 && val <= 12) {
412
        dt.tm_mon = val - 1;
413
      }
414
      else if (strcmp(argv[2], "day") == 0 && val <= 31) {
415
        dt.tm_mday = val;
416
      }
417
      else if (strcmp(argv[2], "hour") == 0 && val < 24) {
418
        dt.tm_hour = val;
419
      }
420
      else if (strcmp(argv[2], "minute") == 0 && val < 60) {
421
        dt.tm_min = val;
422
      }
423
      else if (strcmp(argv[2], "second") == 0 && val < 60) {
424
        dt.tm_sec = val;
425
      }
426
      else {
427
        chprintf(stream, "unknown option '%s' or value '%s'\n", argv[2], argv[3]);
428
        return AOS_INVALID_ARGUMENTS;
429
      }
430
      dt.tm_wday = aosTimeDayOfWeekFromDate(dt.tm_mday, dt.tm_mon+1, dt.tm_year+1900) % 7;
431
      aosSysSetDateTime(&dt);
432

    
433
      // read and print new date and time
434
      aosSysGetDateTime(&dt);
435
      chprintf(stream, "date/time set to %02u:%02u:%02u @ %02u-%02u-%04u\n",
436
               dt.tm_hour, dt.tm_min, dt.tm_sec,
437
               dt.tm_mday, dt.tm_mon+1, dt.tm_year+1900);
438

    
439
      retval = AOS_OK;
440
    }
441
  }
442

    
443
  // print help, if required
444
  if (retval == AOS_INVALID_ARGUMENTS) {
445
    chprintf(stream, "Usage: %s OPTION\n", argv[0]);
446
    chprintf(stream, "Options:\n");
447
    chprintf(stream, "  --help\n");
448
    chprintf(stream, "    Print this help text.\n");
449
    chprintf(stream, "  --shell [OPT [VAL]]\n");
450
    chprintf(stream, "    Set or retrieve shell configuration.\n");
451
    chprintf(stream, "    Possible OPTs and VALs are:\n");
452
    chprintf(stream, "      prompt text|minimal|uptime|date&time|notime\n");
453
    chprintf(stream, "        Configures the prompt.\n");
454
    chprintf(stream, "      match casesensitive|caseinsenitive\n");
455
    chprintf(stream, "        Configures string matching.\n");
456
    chprintf(stream, "  --date&time OPT VAL\n");
457
    chprintf(stream, "    Set the date/time value of OPT to VAL.\n");
458
    chprintf(stream, "    Possible OPTs are:\n");
459
    chprintf(stream, "      year\n");
460
    chprintf(stream, "      month\n");
461
    chprintf(stream, "      day\n");
462
    chprintf(stream, "      hour\n");
463
    chprintf(stream, "      minute\n");
464
    chprintf(stream, "      second\n");
465
  }
466

    
467
  return (argc > 1 && strcmp(argv[1], "--help") == 0) ? AOS_OK : retval;
468
}
469

    
470
/**
471
 * @brief   Callback function for the system:info shell command.
472
 *
473
 * @param[in] stream    The I/O stream to use.
474
 * @param[in] argc      Number of arguments.
475
 * @param[in] argv      List of pointers to the arguments.
476
 *
477
 * @return            An exit status.
478
 * @retval  AOS_OK    The command was executed successfully.
479
 */
480
static int _shellcmd_infocb(BaseSequentialStream* stream, int argc, char* argv[])
481
{
482
  aosDbgCheck(stream != NULL);
483

    
484
  (void)argc;
485
  (void)argv;
486

    
487
  // print system information
488
  _printSystemInfo(stream);
489

    
490
  // print time measurement precision
491
  chprintf(stream, "module time resolution: %uus\n", AOS_SYSTEM_TIME_RESOLUTION);
492

    
493
  // print system uptime
494
  aos_timestamp_t uptime;
495
  aosSysGetUptime(&uptime);
496
  chprintf(stream, "The system is running for\n");
497
  chprintf(stream, "%10u days\n", (uint32_t)(uptime / MICROSECONDS_PER_DAY));
498
  chprintf(stream, "%10u hours\n", (uint8_t)(uptime % MICROSECONDS_PER_DAY / MICROSECONDS_PER_HOUR));
499
  chprintf(stream, "%10u minutes\n", (uint8_t)(uptime % MICROSECONDS_PER_HOUR / MICROSECONDS_PER_MINUTE));
500
  chprintf(stream, "%10u seconds\n", (uint8_t)(uptime % MICROSECONDS_PER_MINUTE / MICROSECONDS_PER_SECOND));
501
  chprintf(stream, "%10u milliseconds\n", (uint16_t)(uptime % MICROSECONDS_PER_SECOND / MICROSECONDS_PER_MILLISECOND));
502
  chprintf(stream, "%10u microseconds\n", (uint16_t)(uptime % MICROSECONDS_PER_MILLISECOND / MICROSECONDS_PER_MICROSECOND));
503
#if (AMIROOS_CFG_SSSP_MASTER != true) && (AMIROOS_CFG_PROFILE == true)
504
  chprintf(stream, "SSSP synchronization offset: %.3fus per %uus\n", _syssyncskew, AMIROOS_CFG_SSSP_SYSSYNCPERIOD);
505
#endif /* AMIROOS_CFG_SSSP_MASTER != true && AMIROOS_CFG_PROFILE == true */
506
  _printSystemInfoSeparator(stream, '=', SYSTEM_INFO_WIDTH);
507

    
508
#if (AMIROOS_CFG_SHELL_ENABLE == true)
509
  // print shell info
510
  chprintf(stream, "System shell information:\n");
511
  chprintf(stream, "\tnumber of commands:      %u\n", aosShellCountCommands(&aos.shell));
512
  chprintf(stream, "\tmaximum line width:      %u characters\n", aos.shell.linesize);
513
  chprintf(stream, "\tmaximum #arguments:      %u\n", aos.shell.arglistsize);
514
  chprintf(stream, "\tshell thread stack size: %u bytes\n", aosThdGetStacksize(aos.shell.thread));
515
#if (CH_DBG_FILL_THREADS == TRUE)
516
  chprintf(stream, "\tstack peak utilization:  %u bytes (%.2f%%)\n", aosThdGetStackPeakUtilization(aos.shell.thread), (float)aosThdGetStackPeakUtilization(aos.shell.thread) / (float)aosThdGetStacksize(aos.shell.thread) * 100.0f);
517
#endif /* CH_DBG_FILL_THREADS == TRUE */
518
  _printSystemInfoSeparator(stream, '=', SYSTEM_INFO_WIDTH);
519
#endif /* AMIROOS_CFG_SHELL_ENABLE == true */
520

    
521
  return AOS_OK;
522
}
523

    
524
/**
525
 * @brief   Callback function for the sytem:shutdown shell command.
526
 *
527
 * @param[in] stream    The I/O stream to use.
528
 * @param[in] argc      Number of arguments.
529
 * @param[in] argv      List of pointers to the arguments.
530
 *
531
 * @return              An exit status.
532
 * @retval  AOS_OK                  The command was executed successfully.
533
 * @retval  AOS_INVALID_ARGUMENTS   There was an issue with the arguments.
534
 */
535
static int _shellcmd_shutdowncb(BaseSequentialStream* stream, int argc, char* argv[])
536
{
537
  aosDbgCheck(stream != NULL);
538

    
539
  // print help text
540
  if (argc != 2 || strcmp(argv[1], "--help") == 0) {
541
    chprintf(stream, "Usage: %s OPTION\n", argv[0]);
542
    chprintf(stream, "Options:\n");
543
    chprintf(stream, "  --help\n");
544
    chprintf(stream, "    Print this help text.\n");
545
    chprintf(stream, "  --hibernate, -h\n");
546
    chprintf(stream, "    Shutdown to hibernate mode.\n");
547
    chprintf(stream, "    Least energy saving, but allows charging via pins.\n");
548
    chprintf(stream, "  --deepsleep, -d\n");
549
    chprintf(stream, "    Shutdown to deepsleep mode.\n");
550
    chprintf(stream, "    Minimum energy consumption while allowing charging via plug.\n");
551
    chprintf(stream, "  --transportation, -t\n");
552
    chprintf(stream, "    Shutdown to transportation mode.\n");
553
    chprintf(stream, "    Minimum energy consumption with all interrupts disabled (no charging).\n");
554
    chprintf(stream, "  --restart, -r\n");
555
    chprintf(stream, "    Shutdown and restart system.\n");
556

    
557
    return (argc != 2) ? AOS_INVALID_ARGUMENTS : AOS_OK;
558
  }
559
  // handle argument
560
  else {
561
    if (strcmp(argv[1], "-h") == 0 || strcmp(argv[1], "--hibernate") == 0) {
562
      chEvtBroadcastFlags(&aos.events.os, AOS_SYSTEM_EVENTFLAGS_HIBERNATE);
563
      chThdTerminate(chThdGetSelfX());
564
      return AOS_OK;
565
    }
566
    else if (strcmp(argv[1], "-d") == 0 || strcmp(argv[1], "--deepsleep") == 0) {
567
      chEvtBroadcastFlags(&aos.events.os, AOS_SYSTEM_EVENTFLAGS_DEEPSLEEP);
568
      chThdTerminate(chThdGetSelfX());
569
      return AOS_OK;
570
    }
571
    else if (strcmp(argv[1], "-t") == 0 || strcmp(argv[1], "--transportation") == 0) {
572
      chEvtBroadcastFlags(&aos.events.os, AOS_SYSTEM_EVENTFLAGS_TRANSPORTATION);
573
      chThdTerminate(chThdGetSelfX());
574
      return AOS_OK;
575
    }
576
    else if (strcmp(argv[1], "-r") == 0 || strcmp(argv[1], "--restart") == 0) {
577
      chEvtBroadcastFlags(&aos.events.os, AOS_SYSTEM_EVENTFLAGS_RESTART);
578
      chThdTerminate(chThdGetSelfX());
579
      return AOS_OK;
580
    }
581
    else {
582
      chprintf(stream, "unknown argument %s\n", argv[1]);
583
      return AOS_INVALID_ARGUMENTS;
584
    }
585
  }
586
}
587

    
588
#if (AMIROOS_CFG_TESTS_ENABLE == true) || defined(__DOXYGEN__)
589
/**
590
 * @brief   Callback function for the kernel:test shell command.
591
 *
592
 * @param[in] stream    The I/O stream to use.
593
 * @param[in] argc      Number of arguments.
594
 * @param[in] argv      List of pointers to the arguments.
595
 *
596
 * @return      An exit status.
597
 */
598
static int _shellcmd_kerneltestcb(BaseSequentialStream* stream, int argc, char* argv[])
599
{
600
  aosDbgCheck(stream != NULL);
601

    
602
  (void)argc;
603
  (void)argv;
604

    
605
  msg_t retval = test_execute(stream, &rt_test_suite);
606

    
607
  return retval;
608
}
609
#endif /* AMIROOS_CFG_TESTS_ENABLE == true */
610
#endif /* AMIROOS_CFG_SHELL_ENABLE == true */
611

    
612
/**
613
 * @brief   Generic callback function for GPIO interrupts.
614
 *
615
 * @param[in] args   Pointer to the GPIO pad identifier.
616
 */
617
static void _intCallback(void* args)
618
{
619
  aosDbgCheck((args != NULL) && (*((iopadid_t*)args) < sizeof(eventflags_t) * 8));
620

    
621
  chSysLockFromISR();
622
  chEvtBroadcastFlagsI(&aos.events.io, (eventflags_t)1 << *((iopadid_t*)args));
623
  chSysUnlockFromISR();
624

    
625
  return;
626
}
627

    
628
#if (AMIROOS_CFG_SSSP_MASTER != true) || defined(__DOXYGEN__)
629
/**
630
 * @brief   Callback function for the Sync signal interrupt.
631
 *
632
 * @param[in] args   Pointer to the GPIO pad identifier.
633
 */
634
static void _signalSyncCallback(void *args)
635
{
636
  aosDbgCheck((args != NULL) && (*((iopadid_t*)args) < sizeof(eventflags_t) * 8));
637

    
638
  apalControlGpioState_t s_state;
639
  aos_timestamp_t uptime;
640

    
641
  chSysLockFromISR();
642
  // if the system is in operation phase
643
  if (aos.sssp.stage == AOS_SSSP_OPERATION) {
644
    // read signal S
645
    apalControlGpioGet(&moduleSsspGpioSync, &s_state);
646
    // if S was toggled from on to off
647
    if (s_state == APAL_GPIO_OFF) {
648
      // get current uptime
649
      aosSysGetUptimeX(&uptime);
650
      // align the uptime with the synchronization period
651
      if (uptime % AMIROOS_CFG_SSSP_SYSSYNCPERIOD < AMIROOS_CFG_SSSP_SYSSYNCPERIOD / 2) {
652
        _uptime -= uptime % AMIROOS_CFG_SSSP_SYSSYNCPERIOD;
653
#if (AMIROOS_CFG_PROFILE == true)
654
        _syssyncskew = ((1.0f - SYSTEM_SYSSYNCSKEW_LPFACTOR) * _syssyncskew) + (SYSTEM_SYSSYNCSKEW_LPFACTOR * (uptime % AMIROOS_CFG_SSSP_SYSSYNCPERIOD));
655
#endif
656
      } else {
657
        _uptime += AMIROOS_CFG_SSSP_SYSSYNCPERIOD - (uptime % AMIROOS_CFG_SSSP_SYSSYNCPERIOD);
658
#if (AMIROOS_CFG_PROFILE == true)
659
        _syssyncskew = ((1.0f - SYSTEM_SYSSYNCSKEW_LPFACTOR) * _syssyncskew) - (SYSTEM_SYSSYNCSKEW_LPFACTOR * (AMIROOS_CFG_SSSP_SYSSYNCPERIOD - (uptime % AMIROOS_CFG_SSSP_SYSSYNCPERIOD)));
660
#endif
661
      }
662
    }
663
  }
664
  // broadcast event
665
  chEvtBroadcastFlagsI(&aos.events.io, (eventflags_t)1 << *((iopadid_t*)args));
666
  chSysUnlockFromISR();
667

    
668
  return;
669
}
670
#endif
671

    
672
/**
673
 * @brief   Callback function for the uptime accumulation timer.
674
 *
675
 * @param[in] par   Generic parameter.
676
 */
677
static void _uptimeCallback(void* par)
678
{
679
  (void)par;
680

    
681
  chSysLockFromISR();
682
  // read current time in system ticks
683
  register const systime_t st = chVTGetSystemTimeX();
684
  // update the uptime variables
685
  _uptime += chTimeI2US(chTimeDiffX(_synctime, st));
686
  _synctime = st;
687
  // enable the timer again
688
  chVTSetI(&_systimer, SYSTIMER_PERIOD, &_uptimeCallback, NULL);
689
  chSysUnlockFromISR();
690

    
691
  return;
692
}
693

    
694
#if (AMIROOS_CFG_SSSP_MASTER == true) || defined (__DOXYGEN__)
695
/**
696
 * @brief   Periodic system synchronization callback function.
697
 * @details Toggles the SYS_SYNC signal and reconfigures the system synchronization timer.
698
 *
699
 * @param[in] par   Unuesed parameters.
700
 */
701
static void _sysSyncTimerCallback(void* par)
702
{
703
  (void)par;
704

    
705
  apalControlGpioState_t s_state;
706
  aos_timestamp_t uptime;
707

    
708
  chSysLockFromISR();
709
  // toggle and read signal S
710
  apalGpioToggle(moduleSsspGpioSync.gpio);
711
  apalControlGpioGet(&moduleSsspGpioSync, &s_state);
712
  // if S was toggled from off to on
713
  if (s_state == APAL_GPIO_ON) {
714
    // reconfigure the timer precisely, because the logically falling edge (next interrupt) snychronizes the system time
715
    _syssynctime += AMIROOS_CFG_SSSP_SYSSYNCPERIOD;
716
    aosSysGetUptimeX(&uptime);
717
    chVTSetI(&_syssynctimer, chTimeUS2I(_syssynctime - uptime), _sysSyncTimerCallback, NULL);
718
  }
719
  // if S was toggled from on to off
720
  else /* if (s_state == APAL_GPIO_OFF) */ {
721
    // reconfigure the timer (lazy)
722
    chVTSetI(&_syssynctimer, chTimeUS2I(AMIROOS_CFG_SSSP_SYSSYNCPERIOD / 2), _sysSyncTimerCallback, NULL);
723
  }
724
  chSysUnlockFromISR();
725

    
726
  return;
727
}
728
#endif
729

    
730
/**
731
 * @brief   AMiRo-OS system initialization.
732
 * @note    Must be called from the system control thread (usually main thread).
733
 *
734
 * @param[in] shellPrompt   String to be printed as prompt of the system shell.
735
 */
736
#if (AMIROOS_CFG_SHELL_ENABLE == true) || defined(__DOXYGEN__)
737
void aosSysInit(const char* shellPrompt)
738
#else
739
void aosSysInit(void)
740
#endif
741
{
742
  /* set control thread to maximum priority */
743
  chThdSetPriority(AOS_THD_CTRLPRIO);
744

    
745
  /* set local variables */
746
  chVTObjectInit(&_systimer);
747
  _synctime = 0;
748
  _uptime = 0;
749
#if (AMIROOS_CFG_SSSP_MASTER == true)
750
  chVTObjectInit(&_syssynctimer);
751
  _syssynctime = 0;
752
#endif
753
#if (AMIROOS_CFG_SSSP_MASTER != true) && (AMIROOS_CFG_PROFILE == true)
754
  _syssyncskew = 0.0f;
755
#endif
756

    
757
  /* initialize aos configuration */
758
  aos.sssp.stage = AOS_SSSP_STARTUP_2_1;
759
  aos.sssp.moduleId = 0;
760
  aosIOStreamInit(&aos.iostream);
761
  chEvtObjectInit(&aos.events.io);
762
  chEvtObjectInit(&aos.events.os);
763

    
764
  /* interrupt setup */
765
  // PD signal
766
  palSetPadCallback(moduleSsspGpioPd.gpio->port, moduleSsspGpioPd.gpio->pad, _intCallback, &moduleSsspGpioPd.gpio->pad);
767
  palEnablePadEvent(moduleSsspGpioPd.gpio->port, moduleSsspGpioPd.gpio->pad, APAL2CH_EDGE(moduleSsspGpioPd.meta.edge));
768
  // SYNC signal
769
#if (AMIROOS_CFG_SSSP_MASTER == true)
770
  palSetPadCallback(moduleSsspGpioSync.gpio->port, moduleSsspGpioSync.gpio->pad, _intCallback, &moduleSsspGpioSync.gpio->pad);
771
#else
772
  palSetPadCallback(moduleSsspGpioSync.gpio->port, moduleSsspGpioSync.gpio->pad, _signalSyncCallback, &moduleSsspGpioSync.gpio->pad);
773
#endif
774
  palEnablePadEvent(moduleSsspGpioSync.gpio->port, moduleSsspGpioSync.gpio->pad, APAL2CH_EDGE(moduleSsspGpioSync.meta.edge));
775
#if (AMIROOS_CFG_SSSP_STACK_START != true)
776
  // DN signal
777
  palSetPadCallback(moduleSsspGpioDn.gpio->port, moduleSsspGpioDn.gpio->pad, _intCallback, &moduleSsspGpioDn.gpio->pad);
778
  palEnablePadEvent(moduleSsspGpioDn.gpio->port, moduleSsspGpioDn.gpio->pad, APAL2CH_EDGE(moduleSsspGpioDn.meta.edge));
779
#endif
780
#if (AMIROOS_CFG_SSSP_STACK_END != true)
781
  // UP signal
782
  palSetPadCallback(moduleSsspGpioUp.gpio->port, moduleSsspGpioUp.gpio->pad, _intCallback, &moduleSsspGpioUp.gpio->pad);
783
  palEnablePadEvent(moduleSsspGpioUp.gpio->port, moduleSsspGpioUp.gpio->pad, APAL2CH_EDGE(moduleSsspGpioUp.meta.edge));
784
#endif
785
#ifdef MODULE_INIT_INTERRUPTS
786
  // further interrupt signals
787
  MODULE_INIT_INTERRUPTS();
788
#endif
789

    
790
#if (AMIROOS_CFG_SHELL_ENABLE == true)
791
  /* init shell */
792
  aosShellInit(&aos.shell,
793
               &aos.events.os,
794
               shellPrompt,
795
               _shell_line,
796
               AMIROOS_CFG_SHELL_LINEWIDTH,
797
               _shell_arglist,
798
               AMIROOS_CFG_SHELL_MAXARGS);
799
  // add system commands
800
  aosShellAddCommand(&aos.shell, &_shellcmd_config);
801
  aosShellAddCommand(&aos.shell, &_shellcmd_info);
802
  aosShellAddCommand(&aos.shell, &_shellcmd_shutdown);
803
#if (AMIROOS_CFG_TESTS_ENABLE == true)
804
  aosShellAddCommand(&aos.shell, &_shellcmd_kerneltest);
805
#endif
806
#endif
807

    
808
  return;
809
}
810

    
811
/**
812
 * @brief   Starts the system and all system threads.
813
 */
814
inline void aosSysStart(void)
815
{
816
  // update the system SSSP stage
817
  aos.sssp.stage = AOS_SSSP_OPERATION;
818

    
819
#if (AMIROOS_CFG_SSSP_MASTER == true)
820
  {
821
    chSysLock();
822
    // start the system synchronization counter
823
    // The first iteration of the timer is set to the next 'center' of a 'slice'.
824
    aos_timestamp_t t;
825
    aosSysGetUptimeX(&t);
826
    t = AMIROOS_CFG_SSSP_SYSSYNCPERIOD - (t % AMIROOS_CFG_SSSP_SYSSYNCPERIOD);
827
    chVTSetI(&_syssynctimer, chTimeUS2I((t > (AMIROOS_CFG_SSSP_SYSSYNCPERIOD / 2)) ? (t - (AMIROOS_CFG_SSSP_SYSSYNCPERIOD / 2)) : (t + (AMIROOS_CFG_SSSP_SYSSYNCPERIOD / 2))), _sysSyncTimerCallback, NULL);
828
    chSysUnlock();
829
  }
830
#endif
831

    
832
  // print system information;
833
  _printSystemInfo((BaseSequentialStream*)&aos.iostream);
834
  aosprintf("\n");
835

    
836
#if (AMIROOS_CFG_SHELL_ENABLE == true)
837
  // start system shell thread
838
#if (CH_CFG_USE_THREADHIERARCHY == TRUE)
839
  aos.shell.thread = chThdCreateStatic(_shell_wa, sizeof(_shell_wa), AMIROOS_CFG_SHELL_THREADPRIO, aosShellThread, &aos.shell, &ch.mainthread);
840
#else
841
  aos.shell.thread = chThdCreateStatic(_shell_wa, sizeof(_shell_wa), AMIROOS_CFG_SHELL_THREADPRIO, aosShellThread, &aos.shell);
842
#endif
843
#endif
844

    
845
  return;
846
}
847

    
848
/**
849
 * @brief   Implements the SSSP startup synchronization step.
850
 *
851
 * @param[in] syncEvtListener   Event listener that receives the Sync event.
852
 *
853
 * @return    If another event that the listener is interested in was received, its mask is returned.
854
 *            Otherwise an empty mask (0) is returned.
855
 */
856
eventmask_t aosSysSsspStartupOsInitSyncCheck(event_listener_t* syncEvtListener)
857
{
858
  aosDbgCheck(syncEvtListener != NULL);
859

    
860
  // local variables
861
  eventmask_t m;
862
  eventflags_t f;
863
  apalControlGpioState_t s;
864

    
865
  // update the system SSSP stage
866
  aos.sssp.stage = AOS_SSSP_STARTUP_2_2;
867

    
868
  // deactivate the sync signal to indicate that the module is ready (SSSPv1 stage 2.1 of startup phase)
869
  apalControlGpioSet(&moduleSsspGpioSync, APAL_GPIO_OFF);
870

    
871
  // wait for any event to occur (do not apply any filter in order not to miss any event)
872
  m = chEvtWaitOne(ALL_EVENTS);
873
  f = chEvtGetAndClearFlags(syncEvtListener);
874
  apalControlGpioGet(&moduleSsspGpioSync, &s);
875

    
876
  // if the event was a system event,
877
  //   and it was fired because of the SysSync control signal,
878
  //   and the SysSync control signal has been deactivated
879
  if (m & syncEvtListener->events &&
880
      f == MODULE_SSSP_EVENTFLAGS_SYNC &&
881
      s == APAL_GPIO_OFF) {
882
    chSysLock();
883
    // start the uptime counter
884
    _synctime = chVTGetSystemTimeX();
885
    _uptime = 0;
886
    chVTSetI(&_systimer, SYSTIMER_PERIOD, &_uptimeCallback, NULL);
887
    chSysUnlock();
888

    
889
    return 0;
890
  }
891
  // an unexpected event occurred
892
  else {
893
    // reassign the flags to the event and return the event mask
894
    syncEvtListener->flags |= f;
895
    return m;
896
  }
897
}
898

    
899
/**
900
 * @brief   Retrieves the system uptime.
901
 *
902
 * @param[out] ut   The system uptime.
903
 */
904
inline void aosSysGetUptimeX(aos_timestamp_t* ut)
905
{
906
  aosDbgCheck(ut != NULL);
907

    
908
  *ut = _uptime + chTimeI2US(chTimeDiffX(_synctime, chVTGetSystemTimeX()));
909

    
910
  return;
911
}
912

    
913
/**
914
 * @brief   retrieves the date and time from the MCU clock.
915
 *
916
 * @param[out] td   The date and time.
917
 */
918
void aosSysGetDateTime(struct tm* dt)
919
{
920
  aosDbgCheck(dt != NULL);
921

    
922
  RTCDateTime rtc;
923
  rtcGetTime(&MODULE_HAL_RTC, &rtc);
924
  rtcConvertDateTimeToStructTm(&rtc, dt, NULL);
925

    
926
  return;
927
}
928

    
929
/**
930
 * @brief   set the date and time of the MCU clock.
931
 *
932
 * @param[in] dt    The date and time to set.
933
 */
934
void aosSysSetDateTime(struct tm* dt)
935
{
936
  aosDbgCheck(dt != NULL);
937

    
938
  RTCDateTime rtc;
939
  rtcConvertStructTmToDateTime(dt, 0, &rtc);
940
  rtcSetTime(&MODULE_HAL_RTC, &rtc);
941

    
942
  return;
943
}
944

    
945
/**
946
 * @brief   Initializes/Acknowledges a system shutdown/restart request.
947
 * @note    This functions should be called from the thread with highest priority.
948
 *
949
 * @param[in] shutdown    Type of shutdown.
950
 */
951
void aosSysShutdownInit(aos_shutdown_t shutdown)
952
{
953
  // check arguments
954
  aosDbgCheck(shutdown != AOS_SHUTDOWN_NONE);
955

    
956
#if (AMIROOS_CFG_SSSP_MASTER == true)
957
  // deactivate the system synchronization timer
958
  chVTReset(&_syssynctimer);
959
#endif
960

    
961
  // update the system SSSP stage
962
  aos.sssp.stage = AOS_SSSP_SHUTDOWN_1_1;
963

    
964
  // activate the SYS_PD control signal only, if this module initiated the shutdown
965
  chSysLock();
966
  if (shutdown != AOS_SHUTDOWN_PASSIVE) {
967
    apalControlGpioSet(&moduleSsspGpioPd, APAL_GPIO_ON);
968
  }
969
  // activate the SYS_SYNC signal
970
  apalControlGpioSet(&moduleSsspGpioSync, APAL_GPIO_ON);
971
  chSysUnlock();
972

    
973
  switch (shutdown) {
974
    case AOS_SHUTDOWN_PASSIVE:
975
      chEvtBroadcastFlags(&aos.events.os, AOS_SYSTEM_EVENTFLAGS_SHUTDOWN);
976
      aosprintf("shutdown request received...\n");
977
      break;
978
    case AOS_SHUTDOWN_HIBERNATE:
979
      chEvtBroadcastFlags(&aos.events.os, AOS_SYSTEM_EVENTFLAGS_HIBERNATE);
980
      aosprintf("shutdown to hibernate mode...\n");
981
      break;
982
    case AOS_SHUTDOWN_DEEPSLEEP:
983
      chEvtBroadcastFlags(&aos.events.os, AOS_SYSTEM_EVENTFLAGS_DEEPSLEEP);
984
      aosprintf("shutdown to deepsleep mode...\n");
985
      break;
986
    case AOS_SHUTDOWN_TRANSPORTATION:
987
      chEvtBroadcastFlags(&aos.events.os, AOS_SYSTEM_EVENTFLAGS_TRANSPORTATION);
988
      aosprintf("shutdown to transportation mode...\n");
989
      break;
990
    case AOS_SHUTDOWN_RESTART:
991
      chEvtBroadcastFlags(&aos.events.os, AOS_SYSTEM_EVENTFLAGS_RESTART);
992
      aosprintf("restarting system...\n");
993
      break;
994
   // must never occur
995
   case AOS_SHUTDOWN_NONE:
996
   default:
997
      break;
998
  }
999

    
1000
  // update the system SSSP stage
1001
  aos.sssp.stage = AOS_SSSP_SHUTDOWN_1_2;
1002

    
1003
  return;
1004
}
1005

    
1006
/**
1007
 * @brief   Stops the system and all related threads (not the thread this function is called from).
1008
 */
1009
void aosSysStop(void)
1010
{
1011
#if (AMIROOS_CFG_SHELL_ENABLE == true)
1012
  chThdWait(aos.shell.thread);
1013
#endif
1014

    
1015
  return;
1016
}
1017

    
1018
/**
1019
 * @brief   Deinitialize all system variables.
1020
 */
1021
void aosSysDeinit(void)
1022
{
1023
  return;
1024
}
1025

    
1026
/**
1027
 * @brief   Finally shuts down the system and calls the bootloader callback function.
1028
 * @note    This function should be called from the thtead with highest priority.
1029
 *
1030
 * @param[in] shutdown    Type of shutdown.
1031
 */
1032
void aosSysShutdownFinal(aos_shutdown_t shutdown)
1033
{
1034
  // check arguments
1035
  aosDbgCheck(shutdown != AOS_SHUTDOWN_NONE);
1036

    
1037
  // disable all interrupts
1038
  irqDeinit();
1039

    
1040
  // update the system SSSP stage
1041
  aos.sssp.stage = AOS_SSSP_SHUTDOWN_1_3;
1042

    
1043
  // call bootloader callback depending on arguments
1044
  switch (shutdown) {
1045
    case AOS_SHUTDOWN_PASSIVE:
1046
      BL_CALLBACK_TABLE_ADDRESS->cbHandleShutdownRequest();
1047
      break;
1048
    case AOS_SHUTDOWN_HIBERNATE:
1049
      BL_CALLBACK_TABLE_ADDRESS->cbShutdownHibernate();
1050
      break;
1051
    case AOS_SHUTDOWN_DEEPSLEEP:
1052
      BL_CALLBACK_TABLE_ADDRESS->cbShutdownDeepsleep();
1053
      break;
1054
    case AOS_SHUTDOWN_TRANSPORTATION:
1055
      BL_CALLBACK_TABLE_ADDRESS->cbShutdownTransportation();
1056
      break;
1057
    case AOS_SHUTDOWN_RESTART:
1058
      BL_CALLBACK_TABLE_ADDRESS->cbShutdownRestart();
1059
      break;
1060
    // must never occur
1061
    case AOS_SHUTDOWN_NONE:
1062
    default:
1063
      break;
1064
  }
1065

    
1066
  return;
1067
}
1068

    
1069
/** @} */