Statistics
| Branch: | Tag: | Revision:

amiro-os / core / src / aos_system.c @ 510b93cc

History | View | Annotate | Download (42.704 KB)

1
/*
2
AMiRo-OS is an operating system designed for the Autonomous Mini Robot (AMiRo) platform.
3
Copyright (C) 2016..2019  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 <amiroos.h>
30
#include <stdarg.h>
31
#include <string.h>
32
#include <stdlib.h>
33

    
34
#if (AMIROOS_CFG_TESTS_ENABLE == true)
35
#include <ch_test.h>
36
#include <rt_test_root.h>
37
#endif /* (AMIROOS_CFG_TESTS_ENABLE == true) */
38

    
39
/******************************************************************************/
40
/* LOCAL DEFINITIONS                                                          */
41
/******************************************************************************/
42

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

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

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

    
58
#if ((AMIROOS_CFG_SSSP_ENABLE == true) && (AMIROOS_CFG_SSSP_MASTER != true) && (AMIROOS_CFG_PROFILE == true)) || defined(__DOXYGEN__)
59

    
60
/**
61
 * @brief   Weighting factor for the low-pass filter used for calculating the @p _syssyncskew value.
62
 */
63
#define SYSTEM_SYSSYNCSKEW_LPFACTOR   (0.1f / AOS_SYSTEM_TIME_RESOLUTION)
64

    
65
#endif /* (AMIROOS_CFG_SSSP_ENABLE == true) && (AMIROOS_CFG_SSSP_MASTER != true) && (AMIROOS_CFG_PROFILE == true) */
66

    
67
/******************************************************************************/
68
/* EXPORTED VARIABLES                                                         */
69
/******************************************************************************/
70

    
71
/**
72
 * @brief   Global system object.
73
 */
74
aos_system_t aos;
75

    
76
/******************************************************************************/
77
/* LOCAL TYPES                                                                */
78
/******************************************************************************/
79

    
80
/******************************************************************************/
81
/* LOCAL VARIABLES                                                            */
82
/******************************************************************************/
83

    
84
/*
85
 * forward declarations
86
 */
87
#if (AMIROOS_CFG_SHELL_ENABLE == true) || defined(__DOXYGEN__)
88
static int _shellcmd_configcb(BaseSequentialStream* stream, int argc, char* argv[]);
89
static int _shellcmd_infocb(BaseSequentialStream* stream, int argc, char* argv[]);
90
static int _shellcmd_shutdowncb(BaseSequentialStream* stream, int argc, char* argv[]);
91
#if (AMIROOS_CFG_TESTS_ENABLE == true) || defined(__DOXYGEN__)
92
static int _shellcmd_kerneltestcb(BaseSequentialStream* stream, int argc, char* argv[]);
93
#endif /* (AMIROOS_CFG_TESTS_ENABLE == true) */
94
#endif /* (AMIROOS_CFG_SHELL_ENABLE == true) */
95

    
96
/**
97
 * @brief   Timer to accumulate system uptime.
98
 */
99
static virtual_timer_t _systimer;
100

    
101
/**
102
 * @brief   Accumulated system uptime.
103
 */
104
static aos_timestamp_t _uptime;
105

    
106
/**
107
 * @brief   Timer register value of last accumulation.
108
 */
109
static systime_t _synctime;
110

    
111
#if (AMIROOS_CFG_SSSP_ENABLE == true) || defined(__DOXYGEN__)
112
#if (AMIROOS_CFG_SSSP_MASTER == true) || defined(__DOXYGEN__)
113

    
114
/**
115
 * @brief   Timer to drive the SYS_SYNC signal for system wide time synchronization according to SSSP.
116
 */
117
static virtual_timer_t _syssynctimer;
118

    
119
/**
120
 * @brief   Last uptime of system wide time synchronization.
121
 */
122
static aos_timestamp_t _syssynctime;
123

    
124
#endif /* (AMIROOS_CFG_SSSP_MASTER == true) */
125

    
126
#if ((AMIROOS_CFG_SSSP_MASTER != true) && (AMIROOS_CFG_PROFILE == true)) || defined(__DOXYGEN__)
127

    
128
/**
129
 * @brief   Offset between local clock and system wide synchronization signal.
130
 */
131
static float _syssyncskew;
132

    
133
#endif /* (AMIROOS_CFG_SSSP_MASTER != true) && (AMIROOS_CFG_PROFILE == true) */
134
#endif /* (AMIROOS_CFG_SSSP_ENABLE == true) */
135

    
136
#if (AMIROOS_CFG_SHELL_ENABLE == true) || defined(__DOXYGEN__)
137

    
138
/**
139
 * @brief   Shell thread working area.
140
 */
141
THD_WORKING_AREA(_shell_wa, AMIROOS_CFG_SHELL_STACKSIZE);
142

    
143
/**
144
 * @brief   Shell input buffer.
145
 */
146
static char _shell_line[AMIROOS_CFG_SHELL_LINEWIDTH];
147

    
148
/**
149
 * @brief   Shell argument buffer.
150
 */
151
static char* _shell_arglist[AMIROOS_CFG_SHELL_MAXARGS];
152

    
153
/**
154
 * @brief   Shell command to retrieve system information.
155
 */
156
static AOS_SHELL_COMMAND(_shellcmd_info, "module:info", _shellcmd_infocb);
157

    
158
/**
159
 * @brief   Shell command to set or retrieve system configuration.
160
 */
161
static AOS_SHELL_COMMAND(_shellcmd_config, "module:config", _shellcmd_configcb);
162

    
163
/**
164
 * @brief   Shell command to shutdown the system.
165
 */
166
#if (AMIROOS_CFG_SSSP_ENABLE == true) || defined(__DOXYGEN__)
167
static AOS_SHELL_COMMAND(_shellcmd_shutdown, "system:shutdown", _shellcmd_shutdowncb);
168
#else /* (AMIROOS_CFG_SSSP_ENABLE == true) */
169
static AOS_SHELL_COMMAND(_shellcmd_shutdown, "module:shutdown", _shellcmd_shutdowncb);
170
#endif /* (AMIROOS_CFG_SSSP_ENABLE == true) */
171

    
172
#if (AMIROOS_CFG_TESTS_ENABLE == true) || defined(__DOXYGEN__)
173

    
174
/**
175
 * @brief   Shell kommand to run a test of the ChibiOS/RT kernel.
176
 */
177
static AOS_SHELL_COMMAND(_shellcmd_kerneltest, "kernel:test", _shellcmd_kerneltestcb);
178

    
179
#endif /* (AMIROOS_CFG_TESTS_ENABLE == true) */
180
#endif /* (AMIROOS_CFG_SHELL_ENABLE == true) */
181

    
182
/******************************************************************************/
183
/* LOCAL FUNCTIONS                                                            */
184
/******************************************************************************/
185

    
186
/**
187
 * @brief   Print a separator line.
188
 *
189
 * @param[in] stream    Stream to print to or NULL to print to all system streams.
190
 * @param[in] c         Character to use.
191
 * @param[in] n         Length of the separator line.
192
 *
193
 * @return  Number of characters printed.
194
 */
195
static unsigned int _printSystemInfoSeparator(BaseSequentialStream* stream, const char c, const unsigned int n)
196
{
197
  aosDbgCheck(stream != NULL);
198

    
199
  // print the specified character n times
200
  for (unsigned int i = 0; i < n; ++i) {
201
    streamPut(stream, c);
202
  }
203
  streamPut(stream, '\n');
204

    
205
  return n+1;
206
}
207

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

    
227
  unsigned int n = 0;
228
  va_list ap;
229

    
230
  va_start(ap, fmt);
231
  n += chprintf(stream, name);
232
  while (n < namewidth) {
233
    streamPut(stream, ' ');
234
    ++n;
235
  }
236
  n += chvprintf(stream, fmt, ap);
237
  va_end(ap);
238

    
239
  streamPut(stream, '\n');
240
  ++n;
241

    
242
  return n;
243
}
244

    
245
/**
246
 * @brief   Prints information about the system.
247
 *
248
 * @param[in] stream    Stream to print to.
249
 */
250
static void _printSystemInfo(BaseSequentialStream* stream)
251
{
252
  aosDbgCheck(stream != NULL);
253

    
254
  // local variables
255
#if (HAL_USE_RTC == TRUE)
256
  struct tm dt;
257
  aosSysGetDateTime(&dt);
258
#endif /* (HAL_USE_RTC == TRUE) */
259

    
260
  // print static information about module and operating system
261
  _printSystemInfoSeparator(stream, '=', SYSTEM_INFO_WIDTH);
262
  _printSystemInfoLine(stream, "Module", SYSTEM_INFO_NAMEWIDTH, "%s", BOARD_NAME);
263
#if defined(PLATFORM_NAME)
264
  _printSystemInfoLine(stream, "Platform", SYSTEM_INFO_NAMEWIDTH, "%s", PLATFORM_NAME);
265
#endif /* defined(PLATFORM_NAME) */
266
#if defined(PORT_CORE_VARIANT_NAME)
267
  _printSystemInfoLine(stream, "Core Variant", SYSTEM_INFO_NAMEWIDTH, "%s", PORT_CORE_VARIANT_NAME);
268
#endif /* defined(PORT_CORE_VARIANT_NAME) */
269
  _printSystemInfoLine(stream, "Architecture", SYSTEM_INFO_NAMEWIDTH, "%s", PORT_ARCHITECTURE_NAME);
270
  _printSystemInfoSeparator(stream, '-', SYSTEM_INFO_WIDTH);
271
#if (AMIROOS_CFG_SSSP_ENABLE == true)
272
  _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_SSSP_VERSION_MAJOR, AOS_SSSP_VERSION_MINOR);
273
#else /* (AMIROOS_CFG_SSSP_ENABLE == true) */
274
  _printSystemInfoLine(stream, "AMiRo-OS" , SYSTEM_INFO_NAMEWIDTH, "%u.%u.%u %s", AMIROOS_VERSION_MAJOR, AMIROOS_VERSION_MINOR, AMIROOS_VERSION_PATCH, AMIROOS_RELEASE_TYPE);
275
#endif /* (AMIROOS_CFG_SSSP_ENABLE == true) */
276
  _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);
277
  _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");
278
  _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");
279
  _printSystemInfoLine(stream, "build type", SYSTEM_INFO_NAMEWIDTH,"%s", (AMIROOS_CFG_DBG == true) ? "debug" : "release");
280
  _printSystemInfoLine(stream, "Compiler" , SYSTEM_INFO_NAMEWIDTH, "%s %u.%u.%u", "GCC", __GNUC__, __GNUC_MINOR__, __GNUC_PATCHLEVEL__); // TODO: support other compilers than GCC
281
  _printSystemInfoLine(stream, "Compiled" , SYSTEM_INFO_NAMEWIDTH, "%s - %s", __DATE__, __TIME__);
282

    
283
  // print static information about the bootloader
284
#if (AMIROOS_CFG_BOOTLOADER != AOS_BOOTLOADER_NONE)
285
  _printSystemInfoSeparator(stream, '-', SYSTEM_INFO_WIDTH);
286
#endif /* (AMIROOS_CFG_BOOTLOADER != AOS_BOOTLOADER_NONE) */
287
#if (AMIROOS_CFG_BOOTLOADER == AOS_BOOTLOADER_AMiRoBLT)
288
  if (BL_CALLBACK_TABLE_ADDRESS->magicNumber == BL_MAGIC_NUMBER) {
289
    _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,
290
                         (BL_CALLBACK_TABLE_ADDRESS->vBootloader.identifier == BL_VERSION_ID_AMiRoBLT_Release) ? "stable" :
291
                         (BL_CALLBACK_TABLE_ADDRESS->vBootloader.identifier == BL_VERSION_ID_AMiRoBLT_ReleaseCandidate) ? "release candidate" :
292
                         (BL_CALLBACK_TABLE_ADDRESS->vBootloader.identifier == BL_VERSION_ID_AMiRoBLT_Beta) ? "beta" :
293
                         (BL_CALLBACK_TABLE_ADDRESS->vBootloader.identifier == BL_VERSION_ID_AMiRoBLT_Alpha) ? "alpha" :
294
                         (BL_CALLBACK_TABLE_ADDRESS->vBootloader.identifier == BL_VERSION_ID_AMiRoBLT_PreAlpha) ? "pre-alpha" :
295
                         "<release type unknown>",
296
                         BL_CALLBACK_TABLE_ADDRESS->vSSSP.major, BL_CALLBACK_TABLE_ADDRESS->vSSSP.minor);
297
#if (AMIROOS_CFG_SSSP_ENABLE == true)
298
    if (BL_CALLBACK_TABLE_ADDRESS->vSSSP.major != AOS_SSSP_VERSION_MAJOR) {
299
      const char* msg = "WARNING: AMiRo-BLT and AMiRo-OS implement incompatible SSSP versions!\n";
300
      stream ? chprintf(stream, msg) : aosprintf(msg);
301
    }
302
#endif /* (AMIROOS_CFG_SSSP_ENABLE == true) */
303
    _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
304
  } else {
305
    const char* msg = "WARNING: AMiRo-BLT incompatible or not available.\n";
306
    stream ? chprintf(stream, "%s", msg) : aosprintf("%s", msg);
307
  }
308
#endif /* (AMIROOS_CFG_BOOTLOADER == X) */
309

    
310
  // print dynamic information about the module
311
  _printSystemInfoSeparator(stream, '-', SYSTEM_INFO_WIDTH);
312
#if (AMIROOS_CFG_SSSP_ENABLE == true)
313
#if (AMIROOS_CFG_SSSP_MSI == true)
314
  if (aos.sssp.moduleId != 0) {
315
    _printSystemInfoLine(stream, "Module ID", SYSTEM_INFO_NAMEWIDTH, "%u", aos.sssp.moduleId);
316
  } else {
317
    _printSystemInfoLine(stream, "Module ID", SYSTEM_INFO_NAMEWIDTH, "not available");
318
  }
319
#else /* (AMIROOS_CFG_SSSP_MSI == true) */
320
  _printSystemInfoLine(stream, "Module ID", SYSTEM_INFO_NAMEWIDTH, "not available");
321
#endif /* (AMIROOS_CFG_SSSP_MSI == true) */
322
#endif /* (AMIROOS_CFG_SSSP_ENABLE == true) */
323
#if (HAL_USE_RTC == TRUE)
324
  _printSystemInfoLine(stream, "Date", SYSTEM_INFO_NAMEWIDTH, "%04u-%02u-%02u (%s)",
325
                       dt.tm_year + 1900,
326
                       dt.tm_mon + 1,
327
                       dt.tm_mday,
328
                       (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");
329
  _printSystemInfoLine(stream, "Time", SYSTEM_INFO_NAMEWIDTH, "%02u:%02u:%02u", dt.tm_hour, dt.tm_min, dt.tm_sec);
330
#endif /* (HAL_USE_RTC == TRUE) */
331

    
332
  _printSystemInfoSeparator(stream, '=', SYSTEM_INFO_WIDTH);
333

    
334
  return;
335
}
336

    
337
#if (AMIROOS_CFG_SHELL_ENABLE == true) || defined(__DOXYGEN__)
338
/**
339
 * @brief   Callback function for the system:config shell command.
340
 *
341
 * @param[in] stream    The I/O stream to use.
342
 * @param[in] argc      Number of arguments.
343
 * @param[in] argv      List of pointers to the arguments.
344
 *
345
 * @return              An exit status.
346
 * @retval  AOS_OK                  The command was executed successfuly.
347
 * @retval  AOS_INVALIDARGUMENTS    There was an issue with the arguemnts.
348
 */
349
static int _shellcmd_configcb(BaseSequentialStream* stream, int argc, char* argv[])
350
{
351
  aosDbgCheck(stream != NULL);
352

    
353
  // local variables
354
  int retval = AOS_INVALIDARGUMENTS;
355

    
356
  // if there are additional arguments
357
  if (argc > 1) {
358
    // if the user wants to set or retrieve the shell configuration
359
    if (strcmp(argv[1], "--shell") == 0) {
360
      // if the user wants to modify the shell configuration
361
      if (argc > 2) {
362
        // if the user wants to modify the prompt
363
        if (strcmp(argv[2], "prompt") == 0) {
364
          // there must be a further argument
365
          if (argc > 3) {
366
            // handle the option
367
            if (strcmp(argv[3], "text") == 0) {
368
              aos.shell.config &= ~AOS_SHELL_CONFIG_PROMPT_MINIMAL;
369
              retval = AOS_OK;
370
            }
371
            else if (strcmp(argv[3], "minimal") == 0) {
372
              aos.shell.config |= AOS_SHELL_CONFIG_PROMPT_MINIMAL;
373
              retval = AOS_OK;
374
            }
375
            else if (strcmp(argv[3], "notime") == 0) {
376
              aos.shell.config &= ~(AOS_SHELL_CONFIG_PROMPT_UPTIME | AOS_SHELL_CONFIG_PROMPT_DATETIME);
377
              retval = AOS_OK;
378
            }
379
            else if (strcmp(argv[3], "uptime") == 0) {
380
              aos.shell.config &= ~AOS_SHELL_CONFIG_PROMPT_DATETIME;
381
              aos.shell.config |= AOS_SHELL_CONFIG_PROMPT_UPTIME;
382
              retval = AOS_OK;
383
            }
384
            else if (strcmp(argv[3], "date&time") == 0) {
385
              aos.shell.config &= ~AOS_SHELL_CONFIG_PROMPT_UPTIME;
386
              aos.shell.config |= AOS_SHELL_CONFIG_PROMPT_DATETIME;
387
              retval = AOS_OK;
388
            }
389
            else {
390
              chprintf(stream, "unknown option '%s'\n", argv[3]);
391
              return AOS_INVALIDARGUMENTS;
392
            }
393
          }
394
        }
395
        // if the user wants to modify the string matching
396
        else if (strcmp(argv[2], "match") == 0) {
397
          // there must be a further argument
398
          if (argc > 3) {
399
            if (strcmp(argv[3], "casesensitive") == 0) {
400
              aos.shell.config |= AOS_SHELL_CONFIG_MATCH_CASE;
401
              retval = AOS_OK;
402
            }
403
            else if (strcmp(argv[3], "caseinsensitive") == 0) {
404
              aos.shell.config &= ~AOS_SHELL_CONFIG_MATCH_CASE;
405
              retval = AOS_OK;
406
            }
407
          }
408
        }
409
      }
410
      // if the user wants to retrieve the shell configuration
411
      else {
412
        chprintf(stream, "current shell configuration:\n");
413
        chprintf(stream, "  prompt text:   %s\n",
414
                 (aos.shell.prompt != NULL) ? aos.shell.prompt : "n/a");
415
        char time[10];
416
        switch (aos.shell.config & (AOS_SHELL_CONFIG_PROMPT_UPTIME | AOS_SHELL_CONFIG_PROMPT_DATETIME)) {
417
          case AOS_SHELL_CONFIG_PROMPT_UPTIME:
418
            strcpy(time, "uptime"); break;
419
          case AOS_SHELL_CONFIG_PROMPT_DATETIME:
420
            strcpy(time, "date&time"); break;
421
          default:
422
            strcpy(time, "no time"); break;
423
        }
424
        chprintf(stream, "  prompt style:  %s, %s\n",
425
                 (aos.shell.config & AOS_SHELL_CONFIG_PROMPT_MINIMAL) ? "minimal" : "text",
426
                 time);
427
        chprintf(stream, "  input method:  %s\n",
428
                 (aos.shell.config & AOS_SHELL_CONFIG_INPUT_OVERWRITE) ? "replace" : "insert");
429
        chprintf(stream, "  text matching: %s\n",
430
                 (aos.shell.config & AOS_SHELL_CONFIG_MATCH_CASE) ? "case sensitive" : "case insensitive");
431
        retval = AOS_OK;
432
      }
433
    }
434
# if (HAL_USE_RTC == TRUE)
435
    // if the user wants to configure the date or time
436
    else if (strcmp(argv[1], "--date&time") == 0 && argc == 4) {
437
      struct tm dt;
438
      aosSysGetDateTime(&dt);
439
      int val = atoi(argv[3]);
440
      if (strcmp(argv[2], "year") == 0 && val >= 1900) {
441
        dt.tm_year = val - 1900;
442
      }
443
      else if (strcmp(argv[2], "month") == 0 && val > 0 && val <= 12) {
444
        dt.tm_mon = val - 1;
445
      }
446
      else if (strcmp(argv[2], "day") == 0 && val > 0 && val <= 31) {
447
        dt.tm_mday = val;
448
      }
449
      else if (strcmp(argv[2], "hour") == 0 && val >= 0 && val < 24) {
450
        dt.tm_hour = val;
451
      }
452
      else if (strcmp(argv[2], "minute") == 0 && val >= 0 && val < 60) {
453
        dt.tm_min = val;
454
      }
455
      else if (strcmp(argv[2], "second") == 0 && val >= 0 && val < 60) {
456
        dt.tm_sec = val;
457
      }
458
      else {
459
        chprintf(stream, "unknown option '%s' or invalid value '%s'\n", argv[2], argv[3]);
460
        return AOS_INVALIDARGUMENTS;
461
      }
462
      dt.tm_wday = aosTimeDayOfWeekFromDate((uint16_t)dt.tm_mday, (uint8_t)dt.tm_mon+1, (uint16_t)dt.tm_year+1900) % DAYS_PER_WEEK;
463
      aosSysSetDateTime(&dt);
464

    
465
      // read and print new date and time
466
      aosSysGetDateTime(&dt);
467
      chprintf(stream, "date/time set to %04u-%02u-%02u %02u:%02u:%02u\n",
468
               dt.tm_year+1900, dt.tm_mon+1, dt.tm_mday,
469
               dt.tm_hour, dt.tm_min, dt.tm_sec);
470

    
471
      retval = AOS_OK;
472
    }
473
#endif /* (HAL_USE_RTC == TRUE) */
474
  }
475

    
476
  // print help, if required
477
  if (retval == AOS_INVALIDARGUMENTS) {
478
    chprintf(stream, "Usage: %s OPTION\n", argv[0]);
479
    chprintf(stream, "Options:\n");
480
    chprintf(stream, "  --help\n");
481
    chprintf(stream, "    Print this help text.\n");
482
    chprintf(stream, "  --shell [OPT [VAL]]\n");
483
    chprintf(stream, "    Set or retrieve shell configuration.\n");
484
    chprintf(stream, "    Possible OPTs and VALs are:\n");
485
    chprintf(stream, "      prompt text|minimal|uptime|date&time|notime\n");
486
    chprintf(stream, "        Configures the prompt.\n");
487
    chprintf(stream, "      match casesensitive|caseinsenitive\n");
488
    chprintf(stream, "        Configures string matching.\n");
489
#if (HAL_USE_RTC == TRUE)
490
    chprintf(stream, "  --date&time OPT VAL\n");
491
    chprintf(stream, "    Set the date/time value of OPT to VAL.\n");
492
    chprintf(stream, "    Possible OPTs are:\n");
493
    chprintf(stream, "      year\n");
494
    chprintf(stream, "      month\n");
495
    chprintf(stream, "      day\n");
496
    chprintf(stream, "      hour\n");
497
    chprintf(stream, "      minute\n");
498
    chprintf(stream, "      second\n");
499
#endif /* (HAL_USE_RTC == TRUE) */
500
  }
501

    
502
  return (argc > 1 && strcmp(argv[1], "--help") == 0) ? AOS_OK : retval;
503
}
504

    
505
/**
506
 * @brief   Callback function for the system:info shell command.
507
 *
508
 * @param[in] stream    The I/O stream to use.
509
 * @param[in] argc      Number of arguments.
510
 * @param[in] argv      List of pointers to the arguments.
511
 *
512
 * @return            An exit status.
513
 * @retval  AOS_OK    The command was executed successfully.
514
 */
515
static int _shellcmd_infocb(BaseSequentialStream* stream, int argc, char* argv[])
516
{
517
  aosDbgCheck(stream != NULL);
518

    
519
  (void)argc;
520
  (void)argv;
521

    
522
  // print system information
523
  _printSystemInfo(stream);
524

    
525
  // print time measurement precision
526
  chprintf(stream, "module time resolution: %uus\n", AOS_SYSTEM_TIME_RESOLUTION);
527

    
528
  // print system uptime
529
  aos_timestamp_t uptime;
530
  aosSysGetUptime(&uptime);
531
  chprintf(stream, "The system is running for\n");
532
  chprintf(stream, "%10u days\n", (uint32_t)(uptime / MICROSECONDS_PER_DAY));
533
  chprintf(stream, "%10u hours\n", (uint8_t)(uptime % MICROSECONDS_PER_DAY / MICROSECONDS_PER_HOUR));
534
  chprintf(stream, "%10u minutes\n", (uint8_t)(uptime % MICROSECONDS_PER_HOUR / MICROSECONDS_PER_MINUTE));
535
  chprintf(stream, "%10u seconds\n", (uint8_t)(uptime % MICROSECONDS_PER_MINUTE / MICROSECONDS_PER_SECOND));
536
  chprintf(stream, "%10u milliseconds\n", (uint16_t)(uptime % MICROSECONDS_PER_SECOND / MICROSECONDS_PER_MILLISECOND));
537
  chprintf(stream, "%10u microseconds\n", (uint16_t)(uptime % MICROSECONDS_PER_MILLISECOND / MICROSECONDS_PER_MICROSECOND));
538
#if (AMIROOS_CFG_SSSP_ENABLE == true) && (AMIROOS_CFG_SSSP_MASTER != true) && (AMIROOS_CFG_PROFILE == true)
539
  chprintf(stream, "SSSP synchronization offset: %.3fus per %uus\n", _syssyncskew, AMIROOS_CFG_SSSP_SYSSYNCPERIOD);
540
#endif /* (AMIROOS_CFG_SSSP_ENABLE == true) && (AMIROOS_CFG_SSSP_MASTER != true) && (AMIROOS_CFG_PROFILE == true) */
541
  _printSystemInfoSeparator(stream, '=', SYSTEM_INFO_WIDTH);
542

    
543
  // print shell info
544
  chprintf(stream, "System shell information:\n");
545
  chprintf(stream, "\tcommands available:     %u\n", aosShellCountCommands(&aos.shell));
546
  chprintf(stream, "\tline width:             %u characters\n", aos.shell.input.width);
547
  chprintf(stream, "\tmaximum arguments:      %u\n", aos.shell.arglistsize);
548
#if (AMIROOS_CFG_DBG == true)
549
  chprintf(stream, "\tthread stack size:      %u bytes\n", aosThdGetStacksize(aos.shell.thread));
550
#if (CH_DBG_FILL_THREADS == TRUE)
551
  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);
552
#endif /* (CH_DBG_FILL_THREADS == TRUE) */
553
#endif /* (AMIROOS_CFG_DBG == true) */
554
  _printSystemInfoSeparator(stream, '=', SYSTEM_INFO_WIDTH);
555

    
556
  return AOS_OK;
557
}
558

    
559
/**
560
 * @brief   Callback function for the sytem:shutdown or module:shutdown shell command.
561
 *
562
 * @param[in] stream    The I/O stream to use.
563
 * @param[in] argc      Number of arguments.
564
 * @param[in] argv      List of pointers to the arguments.
565
 *
566
 * @return              An exit status.
567
 * @retval  AOS_OK                  The command was executed successfully.
568
 * @retval  AOS_INVALIDARGUMENTS   There was an issue with the arguments.
569
 */
570
static int _shellcmd_shutdowncb(BaseSequentialStream* stream, int argc, char* argv[])
571
{
572
  aosDbgCheck(stream != NULL);
573

    
574
#if (AMIROOS_CFG_BOOTLOADER == AOS_BOOTLOADER_NONE)
575

    
576
  (void)argv;
577

    
578
  if (argc != 1) {
579
    // error
580
    chprintf(stream, "ERROR: no arguments allowed.\n");
581
    return AOS_INVALIDARGUMENTS;
582
  } else {
583
    // broadcast shutdown event
584
    chEvtBroadcastFlags(&aos.events.os, AOS_SYSTEM_EVENTFLAGS_SHUTDOWN_MASK);
585
    // set terminate flag so no further prompt will be printed
586
    chThdTerminate(chThdGetSelfX());
587
    return AOS_OK;
588
  }
589

    
590
#elif (AMIROOS_CFG_BOOTLOADER == AOS_BOOTLOADER_AMiRoBLT)
591

    
592
  // print help text
593
  if (argc != 2 || strcmp(argv[1], "--help") == 0) {
594
    chprintf(stream, "Usage: %s OPTION\n", argv[0]);
595
    chprintf(stream, "Options:\n");
596
    chprintf(stream, "  --help\n");
597
    chprintf(stream, "    Print this help text.\n");
598
    chprintf(stream, "  --hibernate, -h\n");
599
    chprintf(stream, "    Shutdown to hibernate mode.\n");
600
    chprintf(stream, "    Least energy saving, but allows charging via pins.\n");
601
    chprintf(stream, "  --deepsleep, -d\n");
602
    chprintf(stream, "    Shutdown to deepsleep mode.\n");
603
    chprintf(stream, "    Minimum energy consumption while allowing charging via plug.\n");
604
    chprintf(stream, "  --transportation, -t\n");
605
    chprintf(stream, "    Shutdown to transportation mode.\n");
606
    chprintf(stream, "    Minimum energy consumption with all interrupts disabled (no charging).\n");
607
    chprintf(stream, "  --restart, -r\n");
608
    chprintf(stream, "    Shutdown and restart system.\n");
609

    
610
    return (argc != 2) ? AOS_INVALIDARGUMENTS : AOS_OK;
611
  }
612
  // handle argument
613
  else {
614
    if (strcmp(argv[1], "-h") == 0 || strcmp(argv[1], "--hibernate") == 0) {
615
      // broadcast shutdown event
616
      chEvtBroadcastFlags(&aos.events.os, AOS_SYSTEM_EVENTFLAGS_SHUTDOWN_HIBERNATE);
617
      // set terminate flag so no further prompt will be printed
618
      chThdTerminate(chThdGetSelfX());
619
      return AOS_OK;
620
    }
621
    else if (strcmp(argv[1], "-d") == 0 || strcmp(argv[1], "--deepsleep") == 0) {
622
      // broadcast shutdown event
623
      chEvtBroadcastFlags(&aos.events.os, AOS_SYSTEM_EVENTFLAGS_SHUTDOWN_DEEPSLEEP);
624
      // set terminate flag so no further prompt will be printed
625
      chThdTerminate(chThdGetSelfX());
626
      return AOS_OK;
627
    }
628
    else if (strcmp(argv[1], "-t") == 0 || strcmp(argv[1], "--transportation") == 0) {
629
      // broadcast shutdown event
630
      chEvtBroadcastFlags(&aos.events.os, AOS_SYSTEM_EVENTFLAGS_SHUTDOWN_TRANSPORTATION);
631
      // set terminate flag so no further prompt will be printed
632
      chThdTerminate(chThdGetSelfX());
633
      return AOS_OK;
634
    }
635
    else if (strcmp(argv[1], "-r") == 0 || strcmp(argv[1], "--restart") == 0) {
636
      // broadcast shutdown event
637
      chEvtBroadcastFlags(&aos.events.os, AOS_SYSTEM_EVENTFLAGS_SHUTDOWN_RESTART);
638
      // set terminate flag so no further prompt will be printed
639
      chThdTerminate(chThdGetSelfX());
640
      return AOS_OK;
641
    }
642
    else {
643
      chprintf(stream, "unknown argument %s\n", argv[1]);
644
      return AOS_INVALIDARGUMENTS;
645
    }
646
  }
647

    
648
#endif /* (AMIROOS_CFG_BOOTLOADER == X) */
649
}
650

    
651
#if (AMIROOS_CFG_TESTS_ENABLE == true) || defined(__DOXYGEN__)
652

    
653
/**
654
 * @brief   Callback function for the kernel:test shell command.
655
 *
656
 * @param[in] stream    The I/O stream to use.
657
 * @param[in] argc      Number of arguments.
658
 * @param[in] argv      List of pointers to the arguments.
659
 *
660
 * @return      An exit status.
661
 */
662
static int _shellcmd_kerneltestcb(BaseSequentialStream* stream, int argc, char* argv[])
663
{
664
  aosDbgCheck(stream != NULL);
665

    
666
  (void)argc;
667
  (void)argv;
668

    
669
  msg_t retval = test_execute(stream, &rt_test_suite);
670

    
671
  return retval;
672
}
673

    
674
#endif /* (AMIROOS_CFG_TESTS_ENABLE == true) */
675
#endif /* (AMIROOS_CFG_SHELL_ENABLE == true) */
676

    
677
// suppress warning in case no interrupt GPIOs are defined
678
#pragma GCC diagnostic push
679
#pragma GCC diagnostic ignored "-Wunused-function"
680
/**
681
 * @brief   Generic callback function for GPIO interrupts.
682
 *
683
 * @param[in] args   Pointer to the GPIO line identifier.
684
 */
685
static void _gpioCallback(void* args)
686
{
687
  aosDbgCheck((args != NULL) && (*((ioline_t*)args) != PAL_NOLINE) && (PAL_PAD(*((ioline_t*)args)) < sizeof(eventflags_t) * 8));
688

    
689
  chSysLockFromISR();
690
  chEvtBroadcastFlagsI(&aos.events.gpio, AOS_GPIOEVENT_FLAG(PAL_PAD(*((ioline_t*)args))));
691
  chSysUnlockFromISR();
692

    
693
  return;
694
}
695
#pragma GCC diagnostic pop
696

    
697
#if ((AMIROOS_CFG_SSSP_ENABLE == true) && (AMIROOS_CFG_SSSP_MASTER != true)) || defined(__DOXYGEN__)
698

    
699
/**
700
 * @brief   Callback function for the Sync signal interrupt.
701
 *
702
 * @param[in] args   Pointer to the GPIO line identifier.
703
 */
704
static void _signalSyncCallback(void *args)
705
{
706
  aosDbgCheck((args != NULL) && (*((ioline_t*)args) != PAL_NOLINE) && (PAL_PAD(*((ioline_t*)args)) < sizeof(eventflags_t) * 8));
707

    
708
  apalControlGpioState_t state;
709
  aos_timestamp_t uptime;
710

    
711
  chSysLockFromISR();
712

    
713
  // if the system is in operation phase
714
  if (aos.sssp.stage == AOS_SSSP_STAGE_OPERATION) {
715
    // read signal S
716
    apalControlGpioGet(&moduleSsspGpioS, &state);
717
    // if S was toggled from on to off
718
    if (state == APAL_GPIO_OFF) {
719
      // get current uptime
720
      aosSysGetUptimeX(&uptime);
721
      // align the uptime with the synchronization period
722
      if (uptime % AMIROOS_CFG_SSSP_SYSSYNCPERIOD < AMIROOS_CFG_SSSP_SYSSYNCPERIOD / 2) {
723
        _uptime -= uptime % AMIROOS_CFG_SSSP_SYSSYNCPERIOD;
724
#if (AMIROOS_CFG_PROFILE == true)
725
        _syssyncskew = ((1.0f - SYSTEM_SYSSYNCSKEW_LPFACTOR) * _syssyncskew) + (SYSTEM_SYSSYNCSKEW_LPFACTOR * (uptime % AMIROOS_CFG_SSSP_SYSSYNCPERIOD));
726
#endif /* (AMIROOS_CFG_PROFILE == true) */
727
      } else {
728
        _uptime += AMIROOS_CFG_SSSP_SYSSYNCPERIOD - (uptime % AMIROOS_CFG_SSSP_SYSSYNCPERIOD);
729
#if (AMIROOS_CFG_PROFILE == true)
730
        _syssyncskew = ((1.0f - SYSTEM_SYSSYNCSKEW_LPFACTOR) * _syssyncskew) - (SYSTEM_SYSSYNCSKEW_LPFACTOR * (AMIROOS_CFG_SSSP_SYSSYNCPERIOD - (uptime % AMIROOS_CFG_SSSP_SYSSYNCPERIOD)));
731
#endif /* (AMIROOS_CFG_PROFILE == true) */
732
      }
733
    }
734
  }
735

    
736
  // broadcast event
737
  chEvtBroadcastFlagsI(&aos.events.gpio, AOS_GPIOEVENT_FLAG(PAL_PAD(*((ioline_t*)args))));
738
  chSysUnlockFromISR();
739

    
740
  return;
741
}
742

    
743
#endif /* (AMIROOS_CFG_SSSP_ENABLE == true) && (AMIROOS_CFG_SSSP_MASTER != true) */
744

    
745
/**
746
 * @brief   Callback function for the uptime accumulation timer.
747
 *
748
 * @param[in] par   Generic parameter.
749
 */
750
static void _uptimeCallback(void* par)
751
{
752
  (void)par;
753

    
754
  chSysLockFromISR();
755
  // read current time in system ticks
756
  register const systime_t st = chVTGetSystemTimeX();
757
  // update the uptime variables
758
  _uptime += chTimeI2US(chTimeDiffX(_synctime, st));
759
  _synctime = st;
760
  // enable the timer again
761
  chVTSetI(&_systimer, SYSTIMER_PERIOD, &_uptimeCallback, NULL);
762
  chSysUnlockFromISR();
763

    
764
  return;
765
}
766

    
767
#if ((AMIROOS_CFG_SSSP_ENABLE == true) && (AMIROOS_CFG_SSSP_MASTER == true)) || defined (__DOXYGEN__)
768

    
769
/**
770
 * @brief   Periodic system synchronization callback function.
771
 * @details Toggles the SYS_SYNC signal and reconfigures the system synchronization timer.
772
 *
773
 * @param[in] par   Unused parameters.
774
 */
775
static void _sysSyncTimerCallback(void* par)
776
{
777
  (void)par;
778

    
779
  apalControlGpioState_t state;
780
  aos_timestamp_t uptime;
781

    
782
  chSysLockFromISR();
783
  // toggle and read signal S
784
  apalGpioToggle(moduleSsspGpioS.gpio);
785
  apalControlGpioGet(&moduleSsspGpioS, &state);
786
  // if S was toggled from off to on
787
  if (state == APAL_GPIO_ON) {
788
    // reconfigure the timer precisely, because the logically falling edge (next interrupt) snychronizes the system time
789
    _syssynctime += AMIROOS_CFG_SSSP_SYSSYNCPERIOD;
790
    aosSysGetUptimeX(&uptime);
791
    chVTSetI(&_syssynctimer, chTimeUS2I(_syssynctime - uptime), _sysSyncTimerCallback, NULL);
792
  }
793
  // if S was toggled from on to off
794
  else /* if (state == APAL_GPIO_OFF) */ {
795
    // reconfigure the timer (lazy)
796
    chVTSetI(&_syssynctimer, chTimeUS2I(AMIROOS_CFG_SSSP_SYSSYNCPERIOD / 2), _sysSyncTimerCallback, NULL);
797
  }
798
  chSysUnlockFromISR();
799

    
800
  return;
801
}
802

    
803
#endif /* (AMIROOS_CFG_SSSP_ENABLE == true) && (AMIROOS_CFG_SSSP_MASTER == true) */
804

    
805
/**
806
 * @brief   Retreive the number of active threads.
807
 *
808
 * @return  Number of active threads.
809
 */
810
size_t _numActiveThreads(void)
811
{
812
  size_t threads = 0;
813
  thread_t* tp = chRegFirstThread();
814
  while (tp) {
815
    threads += (tp->state == CH_STATE_FINAL) ? 1 : 0;
816
    tp = chRegNextThread(tp);
817
  }
818

    
819
  return threads;
820
}
821

    
822
/******************************************************************************/
823
/* EXPORTED FUNCTIONS                                                         */
824
/******************************************************************************/
825

    
826
/**
827
 * @brief   AMiRo-OS system initialization.
828
 * @note    Must be called from the system control thread (usually main thread).
829
 *
830
 * @param[in] shellPrompt   String to be printed as prompt of the system shell.
831
 */
832
#if (AMIROOS_CFG_SHELL_ENABLE == true) || defined(__DOXYGEN__)
833
void aosSysInit(const char* shellPrompt)
834
#else /* (AMIROOS_CFG_SHELL_ENABLE == true) */
835
void aosSysInit(void)
836
#endif /* (AMIROOS_CFG_SHELL_ENABLE == true) */
837
{
838
  /* set control thread to maximum priority */
839
  chThdSetPriority(AOS_THD_CTRLPRIO);
840

    
841
#if (AMIROOS_CFG_SSSP_ENABLE == true)
842
  aosSsspInit();
843
#endif /* (AMIROOS_CFG_SSSP_ENABLE == true) */
844

    
845
  /* set local variables */
846
  chVTObjectInit(&_systimer);
847
#if (AMIROOS_CFG_SSSP_ENABLE == true)
848
  _synctime = 0;
849
  _uptime = 0;
850
#if (AMIROOS_CFG_SSSP_MASTER == true)
851
  chVTObjectInit(&_syssynctimer);
852
  _syssynctime = 0;
853
#endif /* (AMIROOS_CFG_SSSP_MASTER == true) */
854
#if (AMIROOS_CFG_SSSP_MASTER != true) && (AMIROOS_CFG_PROFILE == true)
855
  _syssyncskew = 0.0f;
856
#endif /* (AMIROOS_CFG_SSSP_MASTER != true) && (AMIROOS_CFG_PROFILE == true) */
857
#else /* (AMIROOS_CFG_SSSP_ENABLE == true) */
858
  // start the uptime counter
859
  chSysLock();
860
  _synctime = chVTGetSystemTimeX();
861
  _uptime = 0;
862
  chVTSetI(&_systimer, SYSTIMER_PERIOD, &_uptimeCallback, NULL);
863
  chSysUnlock();
864
#endif /* (AMIROOS_CFG_SSSP_ENABLE == true) */
865

    
866
  /* initialize aos configuration */
867
  aosIOStreamInit(&aos.iostream);
868
  chEvtObjectInit(&aos.events.gpio);
869
  chEvtObjectInit(&aos.events.os);
870

    
871
#if (AMIROOS_CFG_SSSP_ENABLE == true)
872

    
873
  /* SSSP signal interrupt setup */
874
  // PD signal
875
  palSetLineCallback(moduleSsspGpioPD.gpio->line, _gpioCallback, &moduleSsspGpioPD.gpio->line);
876
  palEnableLineEvent(moduleSsspGpioPD.gpio->line, APAL2CH_EDGE(moduleSsspGpioPD.meta.edge));
877
  // S signal
878
#if (AMIROOS_CFG_SSSP_MASTER == true)
879
  palSetLineCallback(moduleSsspGpioS.gpio->line, _gpioCallback, &moduleSsspGpioS.gpio->line);
880
#else /* (AMIROOS_CFG_SSSP_MASTER == true) */
881
  palSetLineCallback(moduleSsspGpioS.gpio->line, _signalSyncCallback, &moduleSsspGpioS.gpio->line);
882
#endif /* (AMIROOS_CFG_SSSP_MASTER == true) */
883
  palEnableLineEvent(moduleSsspGpioS.gpio->line, APAL2CH_EDGE(moduleSsspGpioS.meta.edge));
884
#if (AMIROOS_CFG_SSSP_STACK_START != true)
885
  // DN signal
886
  palSetLineCallback(moduleSsspGpioDN.gpio->line, _gpioCallback, &moduleSsspGpioDN.gpio->line);
887
  palEnableLineEvent(moduleSsspGpioDN.gpio->line, APAL2CH_EDGE(moduleSsspGpioDN.meta.edge));
888
#endif /* (AMIROOS_CFG_SSSP_STACK_START != true) */
889
#if (AMIROOS_CFG_SSSP_STACK_END != true)
890
  // UP signal
891
  palSetLineCallback(moduleSsspGpioUP.gpio->line, _gpioCallback, &moduleSsspGpioUP.gpio->line);
892
  palEnableLineEvent(moduleSsspGpioUP.gpio->line, APAL2CH_EDGE(moduleSsspGpioUP.meta.edge));
893
#endif /* (AMIROOS_CFG_SSSP_STACK_END != true) */
894

    
895
#endif /* (AMIROOS_CFG_SSSP_ENABLE == true) */
896

    
897
#if (AMIROOS_CFG_SHELL_ENABLE == true)
898

    
899
  /* init shell */
900
  aosShellInit(&aos.shell,
901
               &aos.events.os,
902
               shellPrompt,
903
               _shell_line,
904
               AMIROOS_CFG_SHELL_LINEWIDTH,
905
               _shell_arglist,
906
               AMIROOS_CFG_SHELL_MAXARGS);
907
  // add system commands
908
  aosShellAddCommand(&aos.shell, &_shellcmd_config);
909
  aosShellAddCommand(&aos.shell, &_shellcmd_info);
910
  aosShellAddCommand(&aos.shell, &_shellcmd_shutdown);
911
#if (AMIROOS_CFG_TESTS_ENABLE == true)
912
  aosShellAddCommand(&aos.shell, &_shellcmd_kerneltest);
913
#endif /* (AMIROOS_CFG_TESTS_ENABLE == true) */
914

    
915
#endif /* (AMIROOS_CFG_SHELL_ENABLE == true) */
916

    
917
  return;
918
}
919

    
920
/**
921
 * @brief   Starts the system and all system threads.
922
 */
923
void aosSysStart(void)
924
{
925
#if (AMIROOS_CFG_SSSP_ENABLE == true) && (AMIROOS_CFG_SSSP_MASTER == true)
926
  {
927
    chSysLock();
928
    // start the system synchronization counter
929
    // The first iteration of the timer is set to the next 'center' of a 'slice'.
930
    aos_timestamp_t t;
931
    aosSysGetUptimeX(&t);
932
    t = AMIROOS_CFG_SSSP_SYSSYNCPERIOD - (t % AMIROOS_CFG_SSSP_SYSSYNCPERIOD);
933
    chVTSetI(&_syssynctimer, chTimeUS2I((t > (AMIROOS_CFG_SSSP_SYSSYNCPERIOD / 2)) ? (t - (AMIROOS_CFG_SSSP_SYSSYNCPERIOD / 2)) : (t + (AMIROOS_CFG_SSSP_SYSSYNCPERIOD / 2))), _sysSyncTimerCallback, NULL);
934
    chSysUnlock();
935
  }
936
#endif /* (AMIROOS_CFG_SSSP_MASTER == true) && (AMIROOS_CFG_SSSP_ENABLE == true) */
937

    
938
  // print system information;
939
  _printSystemInfo((BaseSequentialStream*)&aos.iostream);
940
  aosprintf("\n");
941

    
942
#if (AMIROOS_CFG_SHELL_ENABLE == true)
943
  // start system shell thread
944
#if (CH_CFG_USE_THREADHIERARCHY == TRUE)
945
  aos.shell.thread = chThdCreateStatic(_shell_wa, sizeof(_shell_wa), AMIROOS_CFG_SHELL_THREADPRIO, aosShellThread, &aos.shell, &ch.mainthread);
946
#else /* (CH_CFG_USE_THREADHIERARCHY == TRUE) */
947
  aos.shell.thread = chThdCreateStatic(_shell_wa, sizeof(_shell_wa), AMIROOS_CFG_SHELL_THREADPRIO, aosShellThread, &aos.shell);
948
#endif /* (CH_CFG_USE_THREADHIERARCHY == TRUE) */
949
#endif /* (AMIROOS_CFG_SHELL_ENABLE == true) */
950

    
951
  return;
952
}
953

    
954
#if (AMIROOS_CFG_SSSP_ENABLE == true) || defined(__DOXYGEN__)
955

    
956
/**
957
 * @brief   Start the system uptime measurement.
958
 */
959
void aosSysStartUptime(void)
960
{
961
  chSysLock();
962

    
963
  // start the uptime counter
964
  _synctime = chVTGetSystemTimeX();
965
  _uptime = 0;
966
  chVTSetI(&_systimer, SYSTIMER_PERIOD, &_uptimeCallback, NULL);
967

    
968
  chSysUnlock();
969

    
970
  return;
971
}
972

    
973
#endif /* (AMIROOS_CFG_SSSP_ENABLE == true) */
974

    
975
/**
976
 * @brief   Retrieves the system uptime.
977
 *
978
 * @param[out] ut   The system uptime.
979
 */
980
void aosSysGetUptimeX(aos_timestamp_t* ut)
981
{
982
  aosDbgCheck(ut != NULL);
983

    
984
  *ut = _uptime + chTimeI2US(chTimeDiffX(_synctime, chVTGetSystemTimeX()));
985

    
986
  return;
987
}
988

    
989
#if (HAL_USE_RTC == TRUE) || defined(__DOXYGEN__)
990

    
991
/**
992
 * @brief   retrieves the date and time from the MCU clock.
993
 *
994
 * @param[out] td   The date and time.
995
 */
996
void aosSysGetDateTime(struct tm* dt)
997
{
998
  aosDbgCheck(dt != NULL);
999

    
1000
  RTCDateTime rtc;
1001
  rtcGetTime(&MODULE_HAL_RTC, &rtc);
1002
  rtcConvertDateTimeToStructTm(&rtc, dt, NULL);
1003

    
1004
  return;
1005
}
1006

    
1007
/**
1008
 * @brief   set the date and time of the MCU clock.
1009
 *
1010
 * @param[in] dt    The date and time to set.
1011
 */
1012
void aosSysSetDateTime(struct tm* dt)
1013
{
1014
  aosDbgCheck(dt != NULL);
1015

    
1016
  RTCDateTime rtc;
1017
  rtcConvertStructTmToDateTime(dt, 0, &rtc);
1018
  rtcSetTime(&MODULE_HAL_RTC, &rtc);
1019

    
1020
  return;
1021
}
1022

    
1023
#endif /* (HAL_USE_RTC == TRUE) */
1024

    
1025
/**
1026
 * @brief   Initializes/Acknowledges a system shutdown/restart request.
1027
 * @note    This functions should be called from the thread with highest priority.
1028
 *
1029
 * @param[in] shutdown    Type of shutdown.
1030
 */
1031
void aosSysShutdownInit(aos_shutdown_t shutdown)
1032
{
1033
  // check arguments
1034
  aosDbgCheck(shutdown != AOS_SHUTDOWN_NONE);
1035

    
1036
#if (AMIROOS_CFG_SSSP_ENABLE == true)
1037

    
1038
#if (AMIROOS_CFG_SSSP_MASTER == true)
1039
  // deactivate the system synchronization timer
1040
  chVTReset(&_syssynctimer);
1041
  // activate SSSP S signal in case the synchronization timer had it deactivated.
1042
  apalControlGpioSet(&moduleSsspGpioS, APAL_GPIO_ON);
1043
#endif /* (AMIROOS_CFG_SSSP_MASTER == true) */
1044

    
1045
  // activate the PD signal only if this module initiated the shutdown
1046
  if (shutdown != AOS_SHUTDOWN_PASSIVE) {
1047
    apalControlGpioSet(&moduleSsspGpioPD, APAL_GPIO_ON);
1048
    aosSsspShutdownInit();
1049
  }
1050

    
1051
  switch (shutdown) {
1052
    case AOS_SHUTDOWN_PASSIVE:
1053
      chEvtBroadcastFlags(&aos.events.os, AOS_SYSTEM_EVENTFLAGS_SHUTDOWN_PASSIVE);
1054
      aosprintf("shutdown request received...\n");
1055
      break;
1056
#if (AMIROOS_CFG_BOOTLOADER == AOS_BOOTLOADER_NONE)
1057
    case AOS_SHUTDOWN_ACTIVE:
1058
      aosprintf("shutdown initiated...\n");
1059
      break;
1060
#elif (AMIROOS_CFG_BOOTLOADER == AOS_BOOTLOADER_AMiRoBLT)
1061
    case AOS_SHUTDOWN_HIBERNATE:
1062
      aosprintf("shutdown to hibernate mode...\n");
1063
      break;
1064
    case AOS_SHUTDOWN_DEEPSLEEP:
1065
      aosprintf("shutdown to deepsleep mode...\n");
1066
      break;
1067
    case AOS_SHUTDOWN_TRANSPORTATION:
1068
      aosprintf("shutdown to transportation mode...\n");
1069
      break;
1070
    case AOS_SHUTDOWN_RESTART:
1071
      aosprintf("restarting system...\n");
1072
      break;
1073
#endif /* (AMIROOS_CFG_BOOTLOADER == X) */
1074
    case AOS_SHUTDOWN_NONE:
1075
      // must never occur
1076
      aosDbgAssert(false);
1077
      break;
1078
  }
1079

    
1080
#else /* (AMIROOS_CFG_SSSP_ENABLE == true) */
1081

    
1082
  aosprintf("shutdown initiated...\n");
1083

    
1084
#endif /* (AMIROOS_CFG_SSSP_ENABLE == true) */
1085

    
1086
  return;
1087
}
1088

    
1089
/**
1090
 * @brief   Stops the system and all related threads (not the thread this function is called from).
1091
 */
1092
void aosSysStop(void)
1093
{
1094
  // wait until the calling thread is the only remaining active thread
1095
#if (CH_CFG_NO_IDLE_THREAD == TRUE)
1096
  while (_numActiveThreads() > 1) {
1097
#else /* (CH_CFG_NO_IDLE_THREAD == TRUE) */
1098
  while (_numActiveThreads() > 2) {
1099
#endif /* (CH_CFG_NO_IDLE_THREAD == TRUE) */
1100
    aosDbgPrintf("waiting for all threads to terminate...\n");
1101
    chThdYield();
1102
  }
1103

    
1104
  return;
1105
}
1106

    
1107
/**
1108
 * @brief   Deinitialize all system variables.
1109
 */
1110
void aosSysDeinit(void)
1111
{
1112
  return;
1113
}
1114

    
1115
#if ((AMIROOS_CFG_SSSP_ENABLE == true) && (AMIROOS_CFG_SSSP_SHUTDOWN != true)) ||                 \
1116
    ((AMIROOS_CFG_SSSP_ENABLE != true) && (AMIROOS_CFG_BOOTLOADER == AOS_BOOTLOADER_AMiRoBLT)) || \
1117
    defined(__DOXYGEN__)
1118

    
1119
/**
1120
 * @brief   Finally shuts down the system and calls the bootloader callback function.
1121
 * @note    This function should be called from the thtead with highest priority.
1122
 *
1123
 * @param[in] shutdown    Type of shutdown.
1124
 */
1125
void aosSysShutdownToBootloader(aos_shutdown_t shutdown)
1126
{
1127
  // check arguments
1128
  aosDbgCheck(shutdown != AOS_SHUTDOWN_NONE);
1129

    
1130
  // disable all interrupts
1131
  irqDeinit();
1132

    
1133
#if (AMIROOS_CFG_BOOTLOADER == AOS_BOOTLOADER_AMiRoBLT)
1134
  // validate AMiRo-BLT
1135
  if ((BL_CALLBACK_TABLE_ADDRESS->magicNumber == BL_MAGIC_NUMBER) &&
1136
      (BL_CALLBACK_TABLE_ADDRESS->vBootloader.major == BL_VERSION_MAJOR) &&
1137
      (BL_CALLBACK_TABLE_ADDRESS->vBootloader.minor >= BL_VERSION_MINOR)) {
1138
    // call bootloader callback depending on arguments
1139
    switch (shutdown) {
1140
#if (AMIROOS_CFG_SSSP_ENABLE == true)
1141
      case AOS_SHUTDOWN_PASSIVE:
1142
        BL_CALLBACK_TABLE_ADDRESS->cbHandleShutdownRequest();
1143
        break;
1144
#endif /* (AMIROOS_CFG_SSSP_ENABLE == true) */
1145
      case AOS_SHUTDOWN_HIBERNATE:
1146
        BL_CALLBACK_TABLE_ADDRESS->cbShutdownHibernate();
1147
        break;
1148
      case AOS_SHUTDOWN_DEEPSLEEP:
1149
        BL_CALLBACK_TABLE_ADDRESS->cbShutdownDeepsleep();
1150
        break;
1151
      case AOS_SHUTDOWN_TRANSPORTATION:
1152
        BL_CALLBACK_TABLE_ADDRESS->cbShutdownTransportation();
1153
        break;
1154
      case AOS_SHUTDOWN_RESTART:
1155
        BL_CALLBACK_TABLE_ADDRESS->cbShutdownRestart();
1156
        break;
1157
      // must never occur
1158
      case AOS_SHUTDOWN_NONE:
1159
      default:
1160
        break;
1161
    }
1162
  } else {
1163
    // fallback if AMiRo-BLT was found to be invalid
1164
    aosprintf("ERROR: AMiRo-BLT incompatible or not available!\n");
1165
    aosThdMSleep(10);
1166
    chSysDisable();
1167
  }
1168
#endif /* (AMIROOS_CFG_BOOTLOADER == AOS_BOOTLOADER_AMiRoBLT) */
1169

    
1170
  return;
1171
}
1172

    
1173
#endif /* ((AMIROOS_CFG_SSSP_ENABLE == true) && (AMIROOS_CFG_SSSP_SHUTDOWN != true)) || ((AMIROOS_CFG_SSSP_ENABLE != true) && (AMIROOS_CFG_BOOTLOADER == AOS_BOOTLOADER_AMiRoBLT)) */
1174

    
1175
/**
1176
 * @brief   Generic callback function for GPIO interrupts.
1177
 *
1178
 * @return  Pointer to the callback function.
1179
 */
1180
palcallback_t aosSysGetStdGpioCallback(void)
1181
{
1182
  return _gpioCallback;
1183
}
1184

    
1185
/** @} */