Statistics
| Branch: | Tag: | Revision:

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

History | View | Annotate | Download (39.7 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 <aos_system.h>
30

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

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

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

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

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

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

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

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

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

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

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

    
99
/**
100
 * @brief   Weighting factor for the low-pass filter used for calculating the @p _syssyncskew value.
101
 */
102
#define SYSTEM_SYSSYNCSKEW_LPFACTOR   (0.1f / AOS_SYSTEM_TIME_RESOLUTION)
103
#endif /* (AMIROOS_CFG_SSSP_ENABLE == true) && (AMIROOS_CFG_SSSP_MASTER != true) && (AMIROOS_CFG_PROFILE == true) */
104

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

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

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

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

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

    
139
/**
140
 * @brief   Shell command to shutdown the system.
141
 */
142
static aos_shellcommand_t _shellcmd_shutdown = {
143
#if (AMIROOS_CFG_SSSP_ENABLE == true)
144
  /* name     */ "system:shutdown",
145
#else
146
  /* name     */ "module:shutdown",
147
#endif
148
  /* callback */ _shellcmd_shutdowncb,
149
  /* next     */ NULL,
150
};
151

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

    
164
/**
165
 * @brief   Global system object.
166
 */
167
aos_system_t aos;
168

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

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

    
188
  return n+1;
189
}
190

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

    
210
  unsigned int n = 0;
211
  va_list ap;
212

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

    
222
  streamPut(stream, '\n');
223
  ++n;
224

    
225
  return n;
226
}
227

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

    
237
  // local variables
238
  struct tm dt;
239
  aosSysGetDateTime(&dt);
240

    
241
  // print static information about module and operating system
242
  _printSystemInfoSeparator(stream, '=', SYSTEM_INFO_WIDTH);
243
#ifdef BOARD_VERSION
244
  _printSystemInfoLine(stream, "Module", SYSTEM_INFO_NAMEWIDTH, "%s (v%s)", BOARD_NAME, BOARD_VERSION);
245
#else
246
  _printSystemInfoLine(stream, "Module", SYSTEM_INFO_NAMEWIDTH, "%s", BOARD_NAME);
247
#endif
248
#ifdef PLATFORM_NAME
249
  _printSystemInfoLine(stream, "Platform", SYSTEM_INFO_NAMEWIDTH, "%s", PLATFORM_NAME);
250
#endif
251
#ifdef PORT_CORE_VARIANT_NAME
252
  _printSystemInfoLine(stream, "Core Variant", SYSTEM_INFO_NAMEWIDTH, "%s", PORT_CORE_VARIANT_NAME);
253
#endif
254
  _printSystemInfoLine(stream, "Architecture", SYSTEM_INFO_NAMEWIDTH, "%s", PORT_ARCHITECTURE_NAME);
255
  _printSystemInfoSeparator(stream, '-', SYSTEM_INFO_WIDTH);
256
#if (AMIROOS_CFG_SSSP_ENABLE == true)
257
  _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);
258
#else
259
  _printSystemInfoLine(stream, "AMiRo-OS" , SYSTEM_INFO_NAMEWIDTH, "%u.%u.%u %s", AMIROOS_VERSION_MAJOR, AMIROOS_VERSION_MINOR, AMIROOS_VERSION_PATCH, AMIROOS_RELEASE_TYPE);
260
#endif
261
  _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);
262
  _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");
263
  _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");
264
  _printSystemInfoLine(stream, "build type", SYSTEM_INFO_NAMEWIDTH,"%s", (AMIROOS_CFG_DBG == true) ? "debug" : "release");
265
  _printSystemInfoLine(stream, "Compiler" , SYSTEM_INFO_NAMEWIDTH, "%s %u.%u.%u", "GCC", __GNUC__, __GNUC_MINOR__, __GNUC_PATCHLEVEL__); // TODO: support other compilers than GCC
266
  _printSystemInfoLine(stream, "Compiled" , SYSTEM_INFO_NAMEWIDTH, "%s - %s", __DATE__, __TIME__);
267

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

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

    
312
  _printSystemInfoSeparator(stream, '=', SYSTEM_INFO_WIDTH);
313

    
314
  return;
315
}
316

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

    
333
  // local variables
334
  int retval = AOS_INVALID_ARGUMENTS;
335

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

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

    
450
      retval = AOS_OK;
451
    }
452
  }
453

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

    
478
  return (argc > 1 && strcmp(argv[1], "--help") == 0) ? AOS_OK : retval;
479
}
480

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

    
495
  (void)argc;
496
  (void)argv;
497

    
498
  // print system information
499
  _printSystemInfo(stream);
500

    
501
  // print time measurement precision
502
  chprintf(stream, "module time resolution: %uus\n", AOS_SYSTEM_TIME_RESOLUTION);
503

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

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

    
532
  return AOS_OK;
533
}
534

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

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

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

    
602
  chEvtBroadcastFlags(&aos.events.os, AOS_SYSTEM_EVENTFLAGS_SHUTDOWN);
603
  chThdTerminate(chThdGetSelfX());
604
  return AOS_OK;
605
#endif /* AMIROOS_CFG_SSSP_ENABLE */
606
}
607

    
608
#if (AMIROOS_CFG_TESTS_ENABLE == true) || defined(__DOXYGEN__)
609
/**
610
 * @brief   Callback function for the kernel:test shell command.
611
 *
612
 * @param[in] stream    The I/O stream to use.
613
 * @param[in] argc      Number of arguments.
614
 * @param[in] argv      List of pointers to the arguments.
615
 *
616
 * @return      An exit status.
617
 */
618
static int _shellcmd_kerneltestcb(BaseSequentialStream* stream, int argc, char* argv[])
619
{
620
  aosDbgCheck(stream != NULL);
621

    
622
  (void)argc;
623
  (void)argv;
624

    
625
  msg_t retval = test_execute(stream, &rt_test_suite);
626

    
627
  return retval;
628
}
629
#endif /* AMIROOS_CFG_TESTS_ENABLE == true */
630
#endif /* (AMIROOS_CFG_SHELL_ENABLE == true) || (AMIROOS_CFG_TESTS_ENABLE == true) */
631

    
632
// suppress warning in case no interrupt GPIOs are defined
633
#pragma GCC diagnostic push
634
#pragma GCC diagnostic ignored "-Wunused-function"
635
/**
636
 * @brief   Generic callback function for GPIO interrupts.
637
 *
638
 * @param[in] args   Pointer to the GPIO pad identifier.
639
 */
640
static void _intCallback(void* args)
641
{
642
  aosDbgCheck((args != NULL) && (*((iopadid_t*)args) < sizeof(eventflags_t) * 8));
643

    
644
  chSysLockFromISR();
645
  chEvtBroadcastFlagsI(&aos.events.io, AOS_IOEVENT_FLAG(*((iopadid_t*)args)));
646
  chSysUnlockFromISR();
647

    
648
  return;
649
}
650
#pragma GCC diagnostic pop
651

    
652
#if ((AMIROOS_CFG_SSSP_ENABLE == true) && (AMIROOS_CFG_SSSP_MASTER != true)) || defined(__DOXYGEN__)
653
/**
654
 * @brief   Callback function for the Sync signal interrupt.
655
 *
656
 * @param[in] args   Pointer to the GPIO pad identifier.
657
 */
658
static void _signalSyncCallback(void *args)
659
{
660
  aosDbgCheck((args != NULL) && (*((iopadid_t*)args) < sizeof(eventflags_t) * 8));
661

    
662
  apalControlGpioState_t s_state;
663
  aos_timestamp_t uptime;
664

    
665
  chSysLockFromISR();
666
  // if the system is in operation phase
667
  if (aos.sssp.stage == AOS_SSSP_OPERATION) {
668
    // read signal S
669
    apalControlGpioGet(&moduleSsspGpioSync, &s_state);
670
    // if S was toggled from on to off
671
    if (s_state == APAL_GPIO_OFF) {
672
      // get current uptime
673
      aosSysGetUptimeX(&uptime);
674
      // align the uptime with the synchronization period
675
      if (uptime % AMIROOS_CFG_SSSP_SYSSYNCPERIOD < AMIROOS_CFG_SSSP_SYSSYNCPERIOD / 2) {
676
        _uptime -= uptime % AMIROOS_CFG_SSSP_SYSSYNCPERIOD;
677
#if (AMIROOS_CFG_PROFILE == true)
678
        _syssyncskew = ((1.0f - SYSTEM_SYSSYNCSKEW_LPFACTOR) * _syssyncskew) + (SYSTEM_SYSSYNCSKEW_LPFACTOR * (uptime % AMIROOS_CFG_SSSP_SYSSYNCPERIOD));
679
#endif
680
      } else {
681
        _uptime += AMIROOS_CFG_SSSP_SYSSYNCPERIOD - (uptime % AMIROOS_CFG_SSSP_SYSSYNCPERIOD);
682
#if (AMIROOS_CFG_PROFILE == true)
683
        _syssyncskew = ((1.0f - SYSTEM_SYSSYNCSKEW_LPFACTOR) * _syssyncskew) - (SYSTEM_SYSSYNCSKEW_LPFACTOR * (AMIROOS_CFG_SSSP_SYSSYNCPERIOD - (uptime % AMIROOS_CFG_SSSP_SYSSYNCPERIOD)));
684
#endif
685
      }
686
    }
687
  }
688
  // broadcast event
689
  chEvtBroadcastFlagsI(&aos.events.io, AOS_IOEVENT_FLAG(*((iopadid_t*)args)));
690
  chSysUnlockFromISR();
691

    
692
  return;
693
}
694
#endif /* (AMIROOS_CFG_SSSP_ENABLE == true) && (AMIROOS_CFG_SSSP_MASTER != true) */
695

    
696
/**
697
 * @brief   Callback function for the uptime accumulation timer.
698
 *
699
 * @param[in] par   Generic parameter.
700
 */
701
static void _uptimeCallback(void* par)
702
{
703
  (void)par;
704

    
705
  chSysLockFromISR();
706
  // read current time in system ticks
707
  register const systime_t st = chVTGetSystemTimeX();
708
  // update the uptime variables
709
  _uptime += chTimeI2US(chTimeDiffX(_synctime, st));
710
  _synctime = st;
711
  // enable the timer again
712
  chVTSetI(&_systimer, SYSTIMER_PERIOD, &_uptimeCallback, NULL);
713
  chSysUnlockFromISR();
714

    
715
  return;
716
}
717

    
718
#if ((AMIROOS_CFG_SSSP_ENABLE == true) && (AMIROOS_CFG_SSSP_MASTER == true)) || defined (__DOXYGEN__)
719
/**
720
 * @brief   Periodic system synchronization callback function.
721
 * @details Toggles the SYS_SYNC signal and reconfigures the system synchronization timer.
722
 *
723
 * @param[in] par   Unuesed parameters.
724
 */
725
static void _sysSyncTimerCallback(void* par)
726
{
727
  (void)par;
728

    
729
  apalControlGpioState_t s_state;
730
  aos_timestamp_t uptime;
731

    
732
  chSysLockFromISR();
733
  // toggle and read signal S
734
  apalGpioToggle(moduleSsspGpioSync.gpio);
735
  apalControlGpioGet(&moduleSsspGpioSync, &s_state);
736
  // if S was toggled from off to on
737
  if (s_state == APAL_GPIO_ON) {
738
    // reconfigure the timer precisely, because the logically falling edge (next interrupt) snychronizes the system time
739
    _syssynctime += AMIROOS_CFG_SSSP_SYSSYNCPERIOD;
740
    aosSysGetUptimeX(&uptime);
741
    chVTSetI(&_syssynctimer, chTimeUS2I(_syssynctime - uptime), _sysSyncTimerCallback, NULL);
742
  }
743
  // if S was toggled from on to off
744
  else /* if (s_state == APAL_GPIO_OFF) */ {
745
    // reconfigure the timer (lazy)
746
    chVTSetI(&_syssynctimer, chTimeUS2I(AMIROOS_CFG_SSSP_SYSSYNCPERIOD / 2), _sysSyncTimerCallback, NULL);
747
  }
748
  chSysUnlockFromISR();
749

    
750
  return;
751
}
752
#endif /* (AMIROOS_CFG_SSSP_ENABLE == true) && (AMIROOS_CFG_SSSP_MASTER == true) */
753

    
754
/**
755
 * @brief   AMiRo-OS system initialization.
756
 * @note    Must be called from the system control thread (usually main thread).
757
 *
758
 * @param[in] shellPrompt   String to be printed as prompt of the system shell.
759
 */
760
#if (AMIROOS_CFG_SHELL_ENABLE == true) || (AMIROOS_CFG_TESTS_ENABLE == true) || defined(__DOXYGEN__)
761
void aosSysInit(const char* shellPrompt)
762
#else
763
void aosSysInit(void)
764
#endif
765
{
766
  /* set control thread to maximum priority */
767
  chThdSetPriority(AOS_THD_CTRLPRIO);
768

    
769
  /* set local variables */
770
  chVTObjectInit(&_systimer);
771
#if (AMIROOS_CFG_SSSP_ENABLE == true)
772
  _synctime = 0;
773
  _uptime = 0;
774
#if (AMIROOS_CFG_SSSP_MASTER == true)
775
  chVTObjectInit(&_syssynctimer);
776
  _syssynctime = 0;
777
#endif
778
#if (AMIROOS_CFG_SSSP_MASTER != true) && (AMIROOS_CFG_PROFILE == true)
779
  _syssyncskew = 0.0f;
780
#endif
781
#else /* AMIROOS_CFG_SSSP_ENABLE == false */
782
  // start the uptime counter
783
  chSysLock();
784
  _synctime = chVTGetSystemTimeX();
785
  _uptime = 0;
786
  chVTSetI(&_systimer, SYSTIMER_PERIOD, &_uptimeCallback, NULL);
787
  chSysUnlock();
788
#endif /* AMIROOS_CFG_SSSP_ENABLE */
789

    
790
  /* initialize aos configuration */
791
#if (AMIROOS_CFG_SSSP_ENABLE == true)
792
  aos.sssp.stage = AOS_SSSP_STARTUP_2_1;
793
  aos.sssp.moduleId = 0;
794
#endif
795
  aosIOStreamInit(&aos.iostream);
796
  chEvtObjectInit(&aos.events.io);
797
  chEvtObjectInit(&aos.events.os);
798

    
799
  /* interrupt setup */
800
#if (AMIROOS_CFG_SSSP_ENABLE == true)
801
  // PD signal
802
  palSetPadCallback(moduleSsspGpioPd.gpio->port, moduleSsspGpioPd.gpio->pad, _intCallback, &moduleSsspGpioPd.gpio->pad);
803
  palEnablePadEvent(moduleSsspGpioPd.gpio->port, moduleSsspGpioPd.gpio->pad, APAL2CH_EDGE(moduleSsspGpioPd.meta.edge));
804
  // SYNC signal
805
#if (AMIROOS_CFG_SSSP_MASTER == true)
806
  palSetPadCallback(moduleSsspGpioSync.gpio->port, moduleSsspGpioSync.gpio->pad, _intCallback, &moduleSsspGpioSync.gpio->pad);
807
#else
808
  palSetPadCallback(moduleSsspGpioSync.gpio->port, moduleSsspGpioSync.gpio->pad, _signalSyncCallback, &moduleSsspGpioSync.gpio->pad);
809
#endif
810
  palEnablePadEvent(moduleSsspGpioSync.gpio->port, moduleSsspGpioSync.gpio->pad, APAL2CH_EDGE(moduleSsspGpioSync.meta.edge));
811
#if (AMIROOS_CFG_SSSP_STACK_START != true)
812
  // DN signal
813
  palSetPadCallback(moduleSsspGpioDn.gpio->port, moduleSsspGpioDn.gpio->pad, _intCallback, &moduleSsspGpioDn.gpio->pad);
814
  palEnablePadEvent(moduleSsspGpioDn.gpio->port, moduleSsspGpioDn.gpio->pad, APAL2CH_EDGE(moduleSsspGpioDn.meta.edge));
815
#endif
816
#if (AMIROOS_CFG_SSSP_STACK_END != true)
817
  // UP signal
818
  palSetPadCallback(moduleSsspGpioUp.gpio->port, moduleSsspGpioUp.gpio->pad, _intCallback, &moduleSsspGpioUp.gpio->pad);
819
  palEnablePadEvent(moduleSsspGpioUp.gpio->port, moduleSsspGpioUp.gpio->pad, APAL2CH_EDGE(moduleSsspGpioUp.meta.edge));
820
#endif
821
#endif /* AMIROOS_CFG_SSSP_ENABLE == true */
822
#ifdef MODULE_INIT_INTERRUPTS
823
  // further interrupt signals
824
  MODULE_INIT_INTERRUPTS();
825
#endif
826

    
827
#if (AMIROOS_CFG_SHELL_ENABLE == true) || (AMIROOS_CFG_TESTS_ENABLE == true)
828
  /* init shell */
829
  aosShellInit(&aos.shell,
830
               &aos.events.os,
831
               shellPrompt,
832
               _shell_line,
833
               AMIROOS_CFG_SHELL_LINEWIDTH,
834
               _shell_arglist,
835
               AMIROOS_CFG_SHELL_MAXARGS);
836
  // add system commands
837
  aosShellAddCommand(&aos.shell, &_shellcmd_config);
838
  aosShellAddCommand(&aos.shell, &_shellcmd_info);
839
  aosShellAddCommand(&aos.shell, &_shellcmd_shutdown);
840
#if (AMIROOS_CFG_TESTS_ENABLE == true)
841
  aosShellAddCommand(&aos.shell, &_shellcmd_kerneltest);
842
#endif
843
#endif /* (AMIROOS_CFG_SHELL_ENABLE == true) || (AMIROOS_CFG_TESTS_ENABLE == true) */
844

    
845
  return;
846
}
847

    
848
/**
849
 * @brief   Starts the system and all system threads.
850
 */
851
inline void aosSysStart(void)
852
{
853
#if (AMIROOS_CFG_SSSP_ENABLE == true)
854
  // update the system SSSP stage
855
  aos.sssp.stage = AOS_SSSP_OPERATION;
856

    
857
#if (AMIROOS_CFG_SSSP_MASTER == true)
858
  {
859
    chSysLock();
860
    // start the system synchronization counter
861
    // The first iteration of the timer is set to the next 'center' of a 'slice'.
862
    aos_timestamp_t t;
863
    aosSysGetUptimeX(&t);
864
    t = AMIROOS_CFG_SSSP_SYSSYNCPERIOD - (t % AMIROOS_CFG_SSSP_SYSSYNCPERIOD);
865
    chVTSetI(&_syssynctimer, chTimeUS2I((t > (AMIROOS_CFG_SSSP_SYSSYNCPERIOD / 2)) ? (t - (AMIROOS_CFG_SSSP_SYSSYNCPERIOD / 2)) : (t + (AMIROOS_CFG_SSSP_SYSSYNCPERIOD / 2))), _sysSyncTimerCallback, NULL);
866
    chSysUnlock();
867
  }
868
#endif
869
#endif /* AMIROOS_CFG_SSSP_ENABLE == true */
870

    
871
  // print system information;
872
  _printSystemInfo((BaseSequentialStream*)&aos.iostream);
873
  aosprintf("\n");
874

    
875
#if (AMIROOS_CFG_SHELL_ENABLE == true) || (AMIROOS_CFG_TESTS_ENABLE == true)
876
  // start system shell thread
877
#if (CH_CFG_USE_THREADHIERARCHY == TRUE)
878
  aos.shell.thread = chThdCreateStatic(_shell_wa, sizeof(_shell_wa), AMIROOS_CFG_SHELL_THREADPRIO, aosShellThread, &aos.shell, &ch.mainthread);
879
#else
880
  aos.shell.thread = chThdCreateStatic(_shell_wa, sizeof(_shell_wa), AMIROOS_CFG_SHELL_THREADPRIO, aosShellThread, &aos.shell);
881
#endif
882
#endif
883

    
884
  return;
885
}
886

    
887
#if (AMIROOS_CFG_SSSP_ENABLE == true) || defined(__DOXYGEN__)
888
/**
889
 * @brief   Implements the SSSP startup synchronization step.
890
 *
891
 * @param[in] syncEvtListener   Event listener that receives the Sync event.
892
 *
893
 * @return    If another event that the listener is interested in was received, its mask is returned.
894
 *            Otherwise an empty mask (0) is returned.
895
 */
896
eventmask_t aosSysSsspStartupOsInitSyncCheck(event_listener_t* syncEvtListener)
897
{
898
  aosDbgCheck(syncEvtListener != NULL);
899

    
900
  // local variables
901
  eventmask_t m;
902
  eventflags_t f;
903
  apalControlGpioState_t s;
904

    
905
  // update the system SSSP stage
906
  aos.sssp.stage = AOS_SSSP_STARTUP_2_2;
907

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

    
911
  // wait for any event to occur (do not apply any filter in order not to miss any event)
912
  m = chEvtWaitOne(ALL_EVENTS);
913
  f = chEvtGetAndClearFlags(syncEvtListener);
914
  apalControlGpioGet(&moduleSsspGpioSync, &s);
915

    
916
  // if the event was a system event,
917
  //   and it was fired because of the SysSync control signal,
918
  //   and the SysSync control signal has been deactivated
919
  if (m & syncEvtListener->events &&
920
      f == MODULE_SSSP_EVENTFLAGS_SYNC &&
921
      s == APAL_GPIO_OFF) {
922
    chSysLock();
923
    // start the uptime counter
924
    _synctime = chVTGetSystemTimeX();
925
    _uptime = 0;
926
    chVTSetI(&_systimer, SYSTIMER_PERIOD, &_uptimeCallback, NULL);
927
    chSysUnlock();
928

    
929
    return 0;
930
  }
931
  // an unexpected event occurred
932
  else {
933
    // reassign the flags to the event and return the event mask
934
    syncEvtListener->flags |= f;
935
    return m;
936
  }
937
}
938
#endif /* AMIROOS_CFG_SSSP_ENABLE == true */
939

    
940
/**
941
 * @brief   Retrieves the system uptime.
942
 *
943
 * @param[out] ut   The system uptime.
944
 */
945
inline void aosSysGetUptimeX(aos_timestamp_t* ut)
946
{
947
  aosDbgCheck(ut != NULL);
948

    
949
  *ut = _uptime + chTimeI2US(chTimeDiffX(_synctime, chVTGetSystemTimeX()));
950

    
951
  return;
952
}
953

    
954
/**
955
 * @brief   retrieves the date and time from the MCU clock.
956
 *
957
 * @param[out] td   The date and time.
958
 */
959
void aosSysGetDateTime(struct tm* dt)
960
{
961
  aosDbgCheck(dt != NULL);
962

    
963
  RTCDateTime rtc;
964
  rtcGetTime(&MODULE_HAL_RTC, &rtc);
965
  rtcConvertDateTimeToStructTm(&rtc, dt, NULL);
966

    
967
  return;
968
}
969

    
970
/**
971
 * @brief   set the date and time of the MCU clock.
972
 *
973
 * @param[in] dt    The date and time to set.
974
 */
975
void aosSysSetDateTime(struct tm* dt)
976
{
977
  aosDbgCheck(dt != NULL);
978

    
979
  RTCDateTime rtc;
980
  rtcConvertStructTmToDateTime(dt, 0, &rtc);
981
  rtcSetTime(&MODULE_HAL_RTC, &rtc);
982

    
983
  return;
984
}
985

    
986
/**
987
 * @brief   Initializes/Acknowledges a system shutdown/restart request.
988
 * @note    This functions should be called from the thread with highest priority.
989
 *
990
 * @param[in] shutdown    Type of shutdown.
991
 */
992
void aosSysShutdownInit(aos_shutdown_t shutdown)
993
{
994
  // check arguments
995
  aosDbgCheck(shutdown != AOS_SHUTDOWN_NONE);
996

    
997
#if (AMIROOS_CFG_SSSP_ENABLE == true)
998
#if (AMIROOS_CFG_SSSP_MASTER == true)
999
  // deactivate the system synchronization timer
1000
  chVTReset(&_syssynctimer);
1001
#endif
1002

    
1003
  // update the system SSSP stage
1004
  aos.sssp.stage = AOS_SSSP_SHUTDOWN_1_1;
1005

    
1006
  chSysLock();
1007
  // activate the SYS_PD control signal only, if this module initiated the shutdown
1008
  if (shutdown != AOS_SHUTDOWN_PASSIVE) {
1009
    apalControlGpioSet(&moduleSsspGpioPd, APAL_GPIO_ON);
1010
  }
1011
  // activate the SYS_SYNC signal
1012
  apalControlGpioSet(&moduleSsspGpioSync, APAL_GPIO_ON);
1013
  chSysUnlock();
1014
#endif /* AMIROOS_CFG_SSSP_ENABLE == true */
1015

    
1016
  switch (shutdown) {
1017
    case AOS_SHUTDOWN_PASSIVE:
1018
      chEvtBroadcastFlags(&aos.events.os, AOS_SYSTEM_EVENTFLAGS_SHUTDOWN);
1019
      aosprintf("shutdown request received...\n");
1020
      break;
1021
    case AOS_SHUTDOWN_HIBERNATE:
1022
      chEvtBroadcastFlags(&aos.events.os, AOS_SYSTEM_EVENTFLAGS_HIBERNATE);
1023
      aosprintf("shutdown to hibernate mode...\n");
1024
      break;
1025
    case AOS_SHUTDOWN_DEEPSLEEP:
1026
      chEvtBroadcastFlags(&aos.events.os, AOS_SYSTEM_EVENTFLAGS_DEEPSLEEP);
1027
      aosprintf("shutdown to deepsleep mode...\n");
1028
      break;
1029
    case AOS_SHUTDOWN_TRANSPORTATION:
1030
      chEvtBroadcastFlags(&aos.events.os, AOS_SYSTEM_EVENTFLAGS_TRANSPORTATION);
1031
      aosprintf("shutdown to transportation mode...\n");
1032
      break;
1033
    case AOS_SHUTDOWN_RESTART:
1034
      chEvtBroadcastFlags(&aos.events.os, AOS_SYSTEM_EVENTFLAGS_RESTART);
1035
      aosprintf("restarting system...\n");
1036
      break;
1037
    // must never occur
1038
    case AOS_SHUTDOWN_NONE:
1039
    default:
1040
      break;
1041
  }
1042

    
1043
#if (AMIROOS_CFG_SSSP_ENABLE == true)
1044
  // update the system SSSP stage
1045
  aos.sssp.stage = AOS_SSSP_SHUTDOWN_1_2;
1046
#endif
1047

    
1048
  return;
1049
}
1050

    
1051
/**
1052
 * @brief   Stops the system and all related threads (not the thread this function is called from).
1053
 */
1054
void aosSysStop(void)
1055
{
1056
#if (AMIROOS_CFG_SHELL_ENABLE == true) || (AMIROOS_CFG_TESTS_ENABLE == true)
1057
  chThdWait(aos.shell.thread);
1058
#endif
1059

    
1060
  return;
1061
}
1062

    
1063
/**
1064
 * @brief   Deinitialize all system variables.
1065
 */
1066
void aosSysDeinit(void)
1067
{
1068
  return;
1069
}
1070

    
1071
/**
1072
 * @brief   Finally shuts down the system and calls the bootloader callback function.
1073
 * @note    This function should be called from the thtead with highest priority.
1074
 *
1075
 * @param[in] shutdown    Type of shutdown.
1076
 */
1077
void aosSysShutdownFinal(aos_shutdown_t shutdown)
1078
{
1079
  // check arguments
1080
  aosDbgCheck(shutdown != AOS_SHUTDOWN_NONE);
1081

    
1082
  // disable all interrupts
1083
  irqDeinit();
1084

    
1085
#if (AMIROOS_CFG_SSSP_ENABLE == true)
1086
  // update the system SSSP stage
1087
  aos.sssp.stage = AOS_SSSP_SHUTDOWN_1_3;
1088
#endif
1089

    
1090
  // validate bootloader
1091
  if ((BL_CALLBACK_TABLE_ADDRESS->magicNumber == BL_MAGIC_NUMBER) &&
1092
      (BL_CALLBACK_TABLE_ADDRESS->vBootloader.major == BL_VERSION_MAJOR) &&
1093
      (BL_CALLBACK_TABLE_ADDRESS->vBootloader.minor >= BL_VERSION_MINOR)) {
1094
    // call bootloader callback depending on arguments
1095
    switch (shutdown) {
1096
      case AOS_SHUTDOWN_PASSIVE:
1097
        BL_CALLBACK_TABLE_ADDRESS->cbHandleShutdownRequest();
1098
        break;
1099
      case AOS_SHUTDOWN_HIBERNATE:
1100
        BL_CALLBACK_TABLE_ADDRESS->cbShutdownHibernate();
1101
        break;
1102
      case AOS_SHUTDOWN_DEEPSLEEP:
1103
        BL_CALLBACK_TABLE_ADDRESS->cbShutdownDeepsleep();
1104
        break;
1105
      case AOS_SHUTDOWN_TRANSPORTATION:
1106
        BL_CALLBACK_TABLE_ADDRESS->cbShutdownTransportation();
1107
        break;
1108
      case AOS_SHUTDOWN_RESTART:
1109
        BL_CALLBACK_TABLE_ADDRESS->cbShutdownRestart();
1110
        break;
1111
      // must never occur
1112
      case AOS_SHUTDOWN_NONE:
1113
      default:
1114
        break;
1115
    }
1116
  } else {
1117
    // fallback if bootloader was found to be invalid
1118
    aosprintf("Bootloader incompatible or not available!\n");
1119
    chThdSleep(TIME_INFINITE);
1120
  }
1121

    
1122
  return;
1123
}
1124

    
1125
/** @} */