Statistics
| Branch: | Tag: | Revision:

amiro-os / core / src / aos_system.c @ 2c89d7e2

History | View | Annotate | Download (38.971 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_ENABLE == true) && (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_ENABLE == true) && (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 /* (AMIROOS_CFG_SSSP_ENABLE == true) && (AMIROOS_CFG_SSSP_MASTER != true) && (AMIROOS_CFG_PROFILE == true) */
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
#if (AMIROOS_CFG_SSSP_ENABLE == true)
254
  _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);
255
#else
256
  _printSystemInfoLine(stream, "AMiRo-OS" , SYSTEM_INFO_NAMEWIDTH, "%u.%u.%u %s", AMIROOS_VERSION_MAJOR, AMIROOS_VERSION_MINOR, AMIROOS_VERSION_PATCH, AMIROOS_RELEASE_TYPE);
257
#endif
258
  _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);
259
  _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");
260
  _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");
261
  _printSystemInfoLine(stream, "build type", SYSTEM_INFO_NAMEWIDTH,"%s", (AMIROOS_CFG_DBG == true) ? "debug" : "release");
262
  _printSystemInfoLine(stream, "Compiler" , SYSTEM_INFO_NAMEWIDTH, "%s %u.%u.%u", "GCC", __GNUC__, __GNUC_MINOR__, __GNUC_PATCHLEVEL__); // TODO: support other compilers than GCC
263
  _printSystemInfoLine(stream, "Compiled" , SYSTEM_INFO_NAMEWIDTH, "%s - %s", __DATE__, __TIME__);
264

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

    
294
  // print dynamic information about the module
295
  _printSystemInfoSeparator(stream, '-', SYSTEM_INFO_WIDTH);
296
#if (AMIROOS_CFG_SSSP_ENABLE == true)
297
  if (aos.sssp.moduleId != 0) {
298
    _printSystemInfoLine(stream, "Module ID", SYSTEM_INFO_NAMEWIDTH, "%u", aos.sssp.moduleId);
299
  } else {
300
    _printSystemInfoLine(stream, "Module ID", SYSTEM_INFO_NAMEWIDTH, "not available");
301
  }
302
#endif
303
  _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",
304
                       dt.tm_mday,
305
                       dt.tm_mon + 1,
306
                       dt.tm_year + 1900);
307
  _printSystemInfoLine(stream, "Time", SYSTEM_INFO_NAMEWIDTH, "%02u:%02u:%02u", dt.tm_hour, dt.tm_min, dt.tm_sec);
308

    
309
  _printSystemInfoSeparator(stream, '=', SYSTEM_INFO_WIDTH);
310

    
311
  return;
312
}
313

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

    
330
  // local variables
331
  int retval = AOS_INVALID_ARGUMENTS;
332

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

    
441
      // read and print new date and time
442
      aosSysGetDateTime(&dt);
443
      chprintf(stream, "date/time set to %02u:%02u:%02u @ %02u-%02u-%04u\n",
444
               dt.tm_hour, dt.tm_min, dt.tm_sec,
445
               dt.tm_mday, dt.tm_mon+1, dt.tm_year+1900);
446

    
447
      retval = AOS_OK;
448
    }
449
  }
450

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

    
475
  return (argc > 1 && strcmp(argv[1], "--help") == 0) ? AOS_OK : retval;
476
}
477

    
478
/**
479
 * @brief   Callback function for the system:info shell command.
480
 *
481
 * @param[in] stream    The I/O stream to use.
482
 * @param[in] argc      Number of arguments.
483
 * @param[in] argv      List of pointers to the arguments.
484
 *
485
 * @return            An exit status.
486
 * @retval  AOS_OK    The command was executed successfully.
487
 */
488
static int _shellcmd_infocb(BaseSequentialStream* stream, int argc, char* argv[])
489
{
490
  aosDbgCheck(stream != NULL);
491

    
492
  (void)argc;
493
  (void)argv;
494

    
495
  // print system information
496
  _printSystemInfo(stream);
497

    
498
  // print time measurement precision
499
  chprintf(stream, "module time resolution: %uus\n", AOS_SYSTEM_TIME_RESOLUTION);
500

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

    
516
#if (AMIROOS_CFG_SHELL_ENABLE == true)
517
  // print shell info
518
  chprintf(stream, "System shell information:\n");
519
  chprintf(stream, "\tnumber of commands:      %u\n", aosShellCountCommands(&aos.shell));
520
  chprintf(stream, "\tmaximum line width:      %u characters\n", aos.shell.linesize);
521
  chprintf(stream, "\tmaximum #arguments:      %u\n", aos.shell.arglistsize);
522
  chprintf(stream, "\tshell thread stack size: %u bytes\n", aosThdGetStacksize(aos.shell.thread));
523
#if (CH_DBG_FILL_THREADS == TRUE)
524
  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);
525
#endif /* CH_DBG_FILL_THREADS == TRUE */
526
  _printSystemInfoSeparator(stream, '=', SYSTEM_INFO_WIDTH);
527
#endif /* AMIROOS_CFG_SHELL_ENABLE == true */
528

    
529
  return AOS_OK;
530
}
531

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

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

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

    
596
#if (AMIROOS_CFG_TESTS_ENABLE == true) || defined(__DOXYGEN__)
597
/**
598
 * @brief   Callback function for the kernel:test shell command.
599
 *
600
 * @param[in] stream    The I/O stream to use.
601
 * @param[in] argc      Number of arguments.
602
 * @param[in] argv      List of pointers to the arguments.
603
 *
604
 * @return      An exit status.
605
 */
606
static int _shellcmd_kerneltestcb(BaseSequentialStream* stream, int argc, char* argv[])
607
{
608
  aosDbgCheck(stream != NULL);
609

    
610
  (void)argc;
611
  (void)argv;
612

    
613
  msg_t retval = test_execute(stream, &rt_test_suite);
614

    
615
  return retval;
616
}
617
#endif /* AMIROOS_CFG_TESTS_ENABLE == true */
618
#endif /* AMIROOS_CFG_SHELL_ENABLE == true */
619

    
620
// suppress warning in case no interrupt GPIOs are defined
621
#pragma GCC diagnostic push
622
#pragma GCC diagnostic ignored "-Wunused-function"
623
/**
624
 * @brief   Generic callback function for GPIO interrupts.
625
 *
626
 * @param[in] args   Pointer to the GPIO pad identifier.
627
 */
628
static void _intCallback(void* args)
629
{
630
  aosDbgCheck((args != NULL) && (*((iopadid_t*)args) < sizeof(eventflags_t) * 8));
631

    
632
  chSysLockFromISR();
633
  chEvtBroadcastFlagsI(&aos.events.io, (eventflags_t)1 << *((iopadid_t*)args));
634
  chSysUnlockFromISR();
635

    
636
  return;
637
}
638
#pragma GCC diagnostic pop
639

    
640
#if ((AMIROOS_CFG_SSSP_ENABLE == true) && (AMIROOS_CFG_SSSP_MASTER != true)) || defined(__DOXYGEN__)
641
/**
642
 * @brief   Callback function for the Sync signal interrupt.
643
 *
644
 * @param[in] args   Pointer to the GPIO pad identifier.
645
 */
646
static void _signalSyncCallback(void *args)
647
{
648
  aosDbgCheck((args != NULL) && (*((iopadid_t*)args) < sizeof(eventflags_t) * 8));
649

    
650
  apalControlGpioState_t s_state;
651
  aos_timestamp_t uptime;
652

    
653
  chSysLockFromISR();
654
  // if the system is in operation phase
655
  if (aos.sssp.stage == AOS_SSSP_OPERATION) {
656
    // read signal S
657
    apalControlGpioGet(&moduleSsspGpioSync, &s_state);
658
    // if S was toggled from on to off
659
    if (s_state == APAL_GPIO_OFF) {
660
      // get current uptime
661
      aosSysGetUptimeX(&uptime);
662
      // align the uptime with the synchronization period
663
      if (uptime % AMIROOS_CFG_SSSP_SYSSYNCPERIOD < AMIROOS_CFG_SSSP_SYSSYNCPERIOD / 2) {
664
        _uptime -= uptime % AMIROOS_CFG_SSSP_SYSSYNCPERIOD;
665
#if (AMIROOS_CFG_PROFILE == true)
666
        _syssyncskew = ((1.0f - SYSTEM_SYSSYNCSKEW_LPFACTOR) * _syssyncskew) + (SYSTEM_SYSSYNCSKEW_LPFACTOR * (uptime % AMIROOS_CFG_SSSP_SYSSYNCPERIOD));
667
#endif
668
      } else {
669
        _uptime += AMIROOS_CFG_SSSP_SYSSYNCPERIOD - (uptime % AMIROOS_CFG_SSSP_SYSSYNCPERIOD);
670
#if (AMIROOS_CFG_PROFILE == true)
671
        _syssyncskew = ((1.0f - SYSTEM_SYSSYNCSKEW_LPFACTOR) * _syssyncskew) - (SYSTEM_SYSSYNCSKEW_LPFACTOR * (AMIROOS_CFG_SSSP_SYSSYNCPERIOD - (uptime % AMIROOS_CFG_SSSP_SYSSYNCPERIOD)));
672
#endif
673
      }
674
    }
675
  }
676
  // broadcast event
677
  chEvtBroadcastFlagsI(&aos.events.io, (eventflags_t)1 << *((iopadid_t*)args));
678
  chSysUnlockFromISR();
679

    
680
  return;
681
}
682
#endif /* (AMIROOS_CFG_SSSP_ENABLE == true) && (AMIROOS_CFG_SSSP_MASTER != true) */
683

    
684
/**
685
 * @brief   Callback function for the uptime accumulation timer.
686
 *
687
 * @param[in] par   Generic parameter.
688
 */
689
static void _uptimeCallback(void* par)
690
{
691
  (void)par;
692

    
693
  chSysLockFromISR();
694
  // read current time in system ticks
695
  register const systime_t st = chVTGetSystemTimeX();
696
  // update the uptime variables
697
  _uptime += chTimeI2US(chTimeDiffX(_synctime, st));
698
  _synctime = st;
699
  // enable the timer again
700
  chVTSetI(&_systimer, SYSTIMER_PERIOD, &_uptimeCallback, NULL);
701
  chSysUnlockFromISR();
702

    
703
  return;
704
}
705

    
706
#if ((AMIROOS_CFG_SSSP_ENABLE == true) && (AMIROOS_CFG_SSSP_MASTER == true)) || defined (__DOXYGEN__)
707
/**
708
 * @brief   Periodic system synchronization callback function.
709
 * @details Toggles the SYS_SYNC signal and reconfigures the system synchronization timer.
710
 *
711
 * @param[in] par   Unuesed parameters.
712
 */
713
static void _sysSyncTimerCallback(void* par)
714
{
715
  (void)par;
716

    
717
  apalControlGpioState_t s_state;
718
  aos_timestamp_t uptime;
719

    
720
  chSysLockFromISR();
721
  // toggle and read signal S
722
  apalGpioToggle(moduleSsspGpioSync.gpio);
723
  apalControlGpioGet(&moduleSsspGpioSync, &s_state);
724
  // if S was toggled from off to on
725
  if (s_state == APAL_GPIO_ON) {
726
    // reconfigure the timer precisely, because the logically falling edge (next interrupt) snychronizes the system time
727
    _syssynctime += AMIROOS_CFG_SSSP_SYSSYNCPERIOD;
728
    aosSysGetUptimeX(&uptime);
729
    chVTSetI(&_syssynctimer, chTimeUS2I(_syssynctime - uptime), _sysSyncTimerCallback, NULL);
730
  }
731
  // if S was toggled from on to off
732
  else /* if (s_state == APAL_GPIO_OFF) */ {
733
    // reconfigure the timer (lazy)
734
    chVTSetI(&_syssynctimer, chTimeUS2I(AMIROOS_CFG_SSSP_SYSSYNCPERIOD / 2), _sysSyncTimerCallback, NULL);
735
  }
736
  chSysUnlockFromISR();
737

    
738
  return;
739
}
740
#endif /* (AMIROOS_CFG_SSSP_ENABLE == true) && (AMIROOS_CFG_SSSP_MASTER == true) */
741

    
742
/**
743
 * @brief   AMiRo-OS system initialization.
744
 * @note    Must be called from the system control thread (usually main thread).
745
 *
746
 * @param[in] shellPrompt   String to be printed as prompt of the system shell.
747
 */
748
#if (AMIROOS_CFG_SHELL_ENABLE == true) || defined(__DOXYGEN__)
749
void aosSysInit(const char* shellPrompt)
750
#else
751
void aosSysInit(void)
752
#endif
753
{
754
  /* set control thread to maximum priority */
755
  chThdSetPriority(AOS_THD_CTRLPRIO);
756

    
757
  /* set local variables */
758
  chVTObjectInit(&_systimer);
759
#if (AMIROOS_CFG_SSSP_ENABLE == true)
760
  _synctime = 0;
761
  _uptime = 0;
762
#if (AMIROOS_CFG_SSSP_MASTER == true)
763
  chVTObjectInit(&_syssynctimer);
764
  _syssynctime = 0;
765
#endif
766
#if (AMIROOS_CFG_SSSP_MASTER != true) && (AMIROOS_CFG_PROFILE == true)
767
  _syssyncskew = 0.0f;
768
#endif
769
#else /* AMIROOS_CFG_SSSP_ENABLE == false */
770
  // start the uptime counter
771
  chSysLock();
772
  _synctime = chVTGetSystemTimeX();
773
  _uptime = 0;
774
  chVTSetI(&_systimer, SYSTIMER_PERIOD, &_uptimeCallback, NULL);
775
  chSysUnlock();
776
#endif /* AMIROOS_CFG_SSSP_ENABLE */
777

    
778
  /* initialize aos configuration */
779
#if (AMIROOS_CFG_SSSP_ENABLE == true)
780
  aos.sssp.stage = AOS_SSSP_STARTUP_2_1;
781
  aos.sssp.moduleId = 0;
782
#endif
783
  aosIOStreamInit(&aos.iostream);
784
  chEvtObjectInit(&aos.events.io);
785
  chEvtObjectInit(&aos.events.os);
786

    
787
  /* interrupt setup */
788
#if (AMIROOS_CFG_SSSP_ENABLE == true)
789
  // PD signal
790
  palSetPadCallback(moduleSsspGpioPd.gpio->port, moduleSsspGpioPd.gpio->pad, _intCallback, &moduleSsspGpioPd.gpio->pad);
791
  palEnablePadEvent(moduleSsspGpioPd.gpio->port, moduleSsspGpioPd.gpio->pad, APAL2CH_EDGE(moduleSsspGpioPd.meta.edge));
792
  // SYNC signal
793
#if (AMIROOS_CFG_SSSP_MASTER == true)
794
  palSetPadCallback(moduleSsspGpioSync.gpio->port, moduleSsspGpioSync.gpio->pad, _intCallback, &moduleSsspGpioSync.gpio->pad);
795
#else
796
  palSetPadCallback(moduleSsspGpioSync.gpio->port, moduleSsspGpioSync.gpio->pad, _signalSyncCallback, &moduleSsspGpioSync.gpio->pad);
797
#endif
798
  palEnablePadEvent(moduleSsspGpioSync.gpio->port, moduleSsspGpioSync.gpio->pad, APAL2CH_EDGE(moduleSsspGpioSync.meta.edge));
799
#if (AMIROOS_CFG_SSSP_STACK_START != true)
800
  // DN signal
801
  palSetPadCallback(moduleSsspGpioDn.gpio->port, moduleSsspGpioDn.gpio->pad, _intCallback, &moduleSsspGpioDn.gpio->pad);
802
  palEnablePadEvent(moduleSsspGpioDn.gpio->port, moduleSsspGpioDn.gpio->pad, APAL2CH_EDGE(moduleSsspGpioDn.meta.edge));
803
#endif
804
#if (AMIROOS_CFG_SSSP_STACK_END != true)
805
  // UP signal
806
  palSetPadCallback(moduleSsspGpioUp.gpio->port, moduleSsspGpioUp.gpio->pad, _intCallback, &moduleSsspGpioUp.gpio->pad);
807
  palEnablePadEvent(moduleSsspGpioUp.gpio->port, moduleSsspGpioUp.gpio->pad, APAL2CH_EDGE(moduleSsspGpioUp.meta.edge));
808
#endif
809
#endif /* AMIROOS_CFG_SSSP_ENABLE == true */
810
#ifdef MODULE_INIT_INTERRUPTS
811
  // further interrupt signals
812
  MODULE_INIT_INTERRUPTS();
813
#endif
814

    
815
#if (AMIROOS_CFG_SHELL_ENABLE == true)
816
  /* init shell */
817
  aosShellInit(&aos.shell,
818
               &aos.events.os,
819
               shellPrompt,
820
               _shell_line,
821
               AMIROOS_CFG_SHELL_LINEWIDTH,
822
               _shell_arglist,
823
               AMIROOS_CFG_SHELL_MAXARGS);
824
  // add system commands
825
  aosShellAddCommand(&aos.shell, &_shellcmd_config);
826
  aosShellAddCommand(&aos.shell, &_shellcmd_info);
827
  aosShellAddCommand(&aos.shell, &_shellcmd_shutdown);
828
#if (AMIROOS_CFG_TESTS_ENABLE == true)
829
  aosShellAddCommand(&aos.shell, &_shellcmd_kerneltest);
830
#endif
831
#endif /* AMIROOS_CFG_SHELL_ENABLE == true */
832

    
833
  return;
834
}
835

    
836
/**
837
 * @brief   Starts the system and all system threads.
838
 */
839
inline void aosSysStart(void)
840
{
841
#if (AMIROOS_CFG_SSSP_ENABLE == true)
842
  // update the system SSSP stage
843
  aos.sssp.stage = AOS_SSSP_OPERATION;
844

    
845
#if (AMIROOS_CFG_SSSP_MASTER == true)
846
  {
847
    chSysLock();
848
    // start the system synchronization counter
849
    // The first iteration of the timer is set to the next 'center' of a 'slice'.
850
    aos_timestamp_t t;
851
    aosSysGetUptimeX(&t);
852
    t = AMIROOS_CFG_SSSP_SYSSYNCPERIOD - (t % AMIROOS_CFG_SSSP_SYSSYNCPERIOD);
853
    chVTSetI(&_syssynctimer, chTimeUS2I((t > (AMIROOS_CFG_SSSP_SYSSYNCPERIOD / 2)) ? (t - (AMIROOS_CFG_SSSP_SYSSYNCPERIOD / 2)) : (t + (AMIROOS_CFG_SSSP_SYSSYNCPERIOD / 2))), _sysSyncTimerCallback, NULL);
854
    chSysUnlock();
855
  }
856
#endif
857
#endif /* AMIROOS_CFG_SSSP_ENABLE == true */
858

    
859
  // print system information;
860
  _printSystemInfo((BaseSequentialStream*)&aos.iostream);
861
  aosprintf("\n");
862

    
863
#if (AMIROOS_CFG_SHELL_ENABLE == true)
864
  // start system shell thread
865
#if (CH_CFG_USE_THREADHIERARCHY == TRUE)
866
  aos.shell.thread = chThdCreateStatic(_shell_wa, sizeof(_shell_wa), AMIROOS_CFG_SHELL_THREADPRIO, aosShellThread, &aos.shell, &ch.mainthread);
867
#else
868
  aos.shell.thread = chThdCreateStatic(_shell_wa, sizeof(_shell_wa), AMIROOS_CFG_SHELL_THREADPRIO, aosShellThread, &aos.shell);
869
#endif
870
#endif
871

    
872
  return;
873
}
874

    
875
#if (AMIROOS_CFG_SSSP_ENABLE == true) || defined(__DOXYGEN__)
876
/**
877
 * @brief   Implements the SSSP startup synchronization step.
878
 *
879
 * @param[in] syncEvtListener   Event listener that receives the Sync event.
880
 *
881
 * @return    If another event that the listener is interested in was received, its mask is returned.
882
 *            Otherwise an empty mask (0) is returned.
883
 */
884
eventmask_t aosSysSsspStartupOsInitSyncCheck(event_listener_t* syncEvtListener)
885
{
886
  aosDbgCheck(syncEvtListener != NULL);
887

    
888
  // local variables
889
  eventmask_t m;
890
  eventflags_t f;
891
  apalControlGpioState_t s;
892

    
893
  // update the system SSSP stage
894
  aos.sssp.stage = AOS_SSSP_STARTUP_2_2;
895

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

    
899
  // wait for any event to occur (do not apply any filter in order not to miss any event)
900
  m = chEvtWaitOne(ALL_EVENTS);
901
  f = chEvtGetAndClearFlags(syncEvtListener);
902
  apalControlGpioGet(&moduleSsspGpioSync, &s);
903

    
904
  // if the event was a system event,
905
  //   and it was fired because of the SysSync control signal,
906
  //   and the SysSync control signal has been deactivated
907
  if (m & syncEvtListener->events &&
908
      f == MODULE_SSSP_EVENTFLAGS_SYNC &&
909
      s == APAL_GPIO_OFF) {
910
    chSysLock();
911
    // start the uptime counter
912
    _synctime = chVTGetSystemTimeX();
913
    _uptime = 0;
914
    chVTSetI(&_systimer, SYSTIMER_PERIOD, &_uptimeCallback, NULL);
915
    chSysUnlock();
916

    
917
    return 0;
918
  }
919
  // an unexpected event occurred
920
  else {
921
    // reassign the flags to the event and return the event mask
922
    syncEvtListener->flags |= f;
923
    return m;
924
  }
925
}
926
#endif /* AMIROOS_CFG_SSSP_ENABLE == true */
927

    
928
/**
929
 * @brief   Retrieves the system uptime.
930
 *
931
 * @param[out] ut   The system uptime.
932
 */
933
inline void aosSysGetUptimeX(aos_timestamp_t* ut)
934
{
935
  aosDbgCheck(ut != NULL);
936

    
937
  *ut = _uptime + chTimeI2US(chTimeDiffX(_synctime, chVTGetSystemTimeX()));
938

    
939
  return;
940
}
941

    
942
/**
943
 * @brief   retrieves the date and time from the MCU clock.
944
 *
945
 * @param[out] td   The date and time.
946
 */
947
void aosSysGetDateTime(struct tm* dt)
948
{
949
  aosDbgCheck(dt != NULL);
950

    
951
  RTCDateTime rtc;
952
  rtcGetTime(&MODULE_HAL_RTC, &rtc);
953
  rtcConvertDateTimeToStructTm(&rtc, dt, NULL);
954

    
955
  return;
956
}
957

    
958
/**
959
 * @brief   set the date and time of the MCU clock.
960
 *
961
 * @param[in] dt    The date and time to set.
962
 */
963
void aosSysSetDateTime(struct tm* dt)
964
{
965
  aosDbgCheck(dt != NULL);
966

    
967
  RTCDateTime rtc;
968
  rtcConvertStructTmToDateTime(dt, 0, &rtc);
969
  rtcSetTime(&MODULE_HAL_RTC, &rtc);
970

    
971
  return;
972
}
973

    
974
/**
975
 * @brief   Initializes/Acknowledges a system shutdown/restart request.
976
 * @note    This functions should be called from the thread with highest priority.
977
 *
978
 * @param[in] shutdown    Type of shutdown.
979
 */
980
void aosSysShutdownInit(aos_shutdown_t shutdown)
981
{
982
  // check arguments
983
  aosDbgCheck(shutdown != AOS_SHUTDOWN_NONE);
984

    
985
#if (AMIROOS_CFG_SSSP_ENABLE == true)
986
#if (AMIROOS_CFG_SSSP_MASTER == true)
987
  // deactivate the system synchronization timer
988
  chVTReset(&_syssynctimer);
989
#endif
990

    
991
  // update the system SSSP stage
992
  aos.sssp.stage = AOS_SSSP_SHUTDOWN_1_1;
993

    
994
  // activate the SYS_PD control signal only, if this module initiated the shutdown
995
  chSysLock();
996
  if (shutdown != AOS_SHUTDOWN_PASSIVE) {
997
    apalControlGpioSet(&moduleSsspGpioPd, APAL_GPIO_ON);
998
  }
999
  // activate the SYS_SYNC signal
1000
  apalControlGpioSet(&moduleSsspGpioSync, APAL_GPIO_ON);
1001
  chSysUnlock();
1002
#endif /* AMIROOS_CFG_SSSP_ENABLE == true */
1003

    
1004
  switch (shutdown) {
1005
    case AOS_SHUTDOWN_PASSIVE:
1006
      chEvtBroadcastFlags(&aos.events.os, AOS_SYSTEM_EVENTFLAGS_SHUTDOWN);
1007
      aosprintf("shutdown request received...\n");
1008
      break;
1009
    case AOS_SHUTDOWN_HIBERNATE:
1010
      chEvtBroadcastFlags(&aos.events.os, AOS_SYSTEM_EVENTFLAGS_HIBERNATE);
1011
      aosprintf("shutdown to hibernate mode...\n");
1012
      break;
1013
    case AOS_SHUTDOWN_DEEPSLEEP:
1014
      chEvtBroadcastFlags(&aos.events.os, AOS_SYSTEM_EVENTFLAGS_DEEPSLEEP);
1015
      aosprintf("shutdown to deepsleep mode...\n");
1016
      break;
1017
    case AOS_SHUTDOWN_TRANSPORTATION:
1018
      chEvtBroadcastFlags(&aos.events.os, AOS_SYSTEM_EVENTFLAGS_TRANSPORTATION);
1019
      aosprintf("shutdown to transportation mode...\n");
1020
      break;
1021
    case AOS_SHUTDOWN_RESTART:
1022
      chEvtBroadcastFlags(&aos.events.os, AOS_SYSTEM_EVENTFLAGS_RESTART);
1023
      aosprintf("restarting system...\n");
1024
      break;
1025
   // must never occur
1026
   case AOS_SHUTDOWN_NONE:
1027
   default:
1028
      break;
1029
  }
1030

    
1031
#if (AMIROOS_CFG_SSSP_ENABLE == true)
1032
  // update the system SSSP stage
1033
  aos.sssp.stage = AOS_SSSP_SHUTDOWN_1_2;
1034
#endif
1035

    
1036
  return;
1037
}
1038

    
1039
/**
1040
 * @brief   Stops the system and all related threads (not the thread this function is called from).
1041
 */
1042
void aosSysStop(void)
1043
{
1044
#if (AMIROOS_CFG_SHELL_ENABLE == true)
1045
  chThdWait(aos.shell.thread);
1046
#endif
1047

    
1048
  return;
1049
}
1050

    
1051
/**
1052
 * @brief   Deinitialize all system variables.
1053
 */
1054
void aosSysDeinit(void)
1055
{
1056
  return;
1057
}
1058

    
1059
/**
1060
 * @brief   Finally shuts down the system and calls the bootloader callback function.
1061
 * @note    This function should be called from the thtead with highest priority.
1062
 *
1063
 * @param[in] shutdown    Type of shutdown.
1064
 */
1065
void aosSysShutdownFinal(aos_shutdown_t shutdown)
1066
{
1067
  // check arguments
1068
  aosDbgCheck(shutdown != AOS_SHUTDOWN_NONE);
1069

    
1070
  // disable all interrupts
1071
  irqDeinit();
1072

    
1073
#if (AMIROOS_CFG_SSSP_ENABLE == true)
1074
  // update the system SSSP stage
1075
  aos.sssp.stage = AOS_SSSP_SHUTDOWN_1_3;
1076
#endif
1077

    
1078
  // validate bootloader
1079
  if ((BL_CALLBACK_TABLE_ADDRESS->magicNumber == BL_MAGIC_NUMBER) &&
1080
      (BL_CALLBACK_TABLE_ADDRESS->vBootloader.major == BL_VERSION_MAJOR) &&
1081
      (BL_CALLBACK_TABLE_ADDRESS->vBootloader.minor >= BL_VERSION_MINOR)) {
1082
    // call bootloader callback depending on arguments
1083
    switch (shutdown) {
1084
      case AOS_SHUTDOWN_PASSIVE:
1085
        BL_CALLBACK_TABLE_ADDRESS->cbHandleShutdownRequest();
1086
        break;
1087
      case AOS_SHUTDOWN_HIBERNATE:
1088
        BL_CALLBACK_TABLE_ADDRESS->cbShutdownHibernate();
1089
        break;
1090
      case AOS_SHUTDOWN_DEEPSLEEP:
1091
        BL_CALLBACK_TABLE_ADDRESS->cbShutdownDeepsleep();
1092
        break;
1093
      case AOS_SHUTDOWN_TRANSPORTATION:
1094
        BL_CALLBACK_TABLE_ADDRESS->cbShutdownTransportation();
1095
        break;
1096
      case AOS_SHUTDOWN_RESTART:
1097
        BL_CALLBACK_TABLE_ADDRESS->cbShutdownRestart();
1098
        break;
1099
      // must never occur
1100
      case AOS_SHUTDOWN_NONE:
1101
      default:
1102
        break;
1103
    }
1104
  } else {
1105
    // fallback if bootloader was found to be invalid
1106
    aosprintf("Bootloader incompatible or not available!\n");
1107
    chThdSleep(TIME_INFINITE);
1108
  }
1109

    
1110
  return;
1111
}
1112

    
1113
/** @} */