Statistics
| Branch: | Tag: | Revision:

amiro-os / core / src / aos_system.c @ 7da800ab

History | View | Annotate | Download (41.427 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
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) || (AMIROOS_CFG_TESTS_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) || (AMIROOS_CFG_TESTS_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) && (AMIROOS_CFG_SSSP_MASTER == true)) || defined(__DOXYGEN__)
112
/**
113
 * @brief   Timer to drive the SYS_SYNC signal for system wide time synchronization according to SSSP.
114
 */
115
static virtual_timer_t _syssynctimer;
116

    
117
/**
118
 * @brief   Last uptime of system wide time synchronization.
119
 */
120
static aos_timestamp_t _syssynctime;
121
#endif /* (AMIROOS_CFG_SSSP_ENABLE == true) && (AMIROOS_CFG_SSSP_MASTER == true) */
122

    
123
#if ((AMIROOS_CFG_SSSP_ENABLE == true) && (AMIROOS_CFG_SSSP_MASTER != true) && (AMIROOS_CFG_PROFILE == true)) || defined(__DOXYGEN__)
124
/**
125
 * @brief   Offset between local clock and system wide synchronization signal.
126
 */
127
static float _syssyncskew;
128

    
129
#endif /* (AMIROOS_CFG_SSSP_ENABLE == true) && (AMIROOS_CFG_SSSP_MASTER != true) && (AMIROOS_CFG_PROFILE == true) */
130

    
131
#if (AMIROOS_CFG_SHELL_ENABLE == true) || (AMIROOS_CFG_TESTS_ENABLE == true) || defined(__DOXYGEN__)
132
/**
133
 * @brief   Shell thread working area.
134
 */
135
THD_WORKING_AREA(_shell_wa, AMIROOS_CFG_SHELL_STACKSIZE);
136

    
137
/**
138
 * @brief   Shell input buffer.
139
 */
140
static char _shell_line[AMIROOS_CFG_SHELL_LINEWIDTH];
141

    
142
/**
143
 * @brief   Shell argument buffer.
144
 */
145
static char* _shell_arglist[AMIROOS_CFG_SHELL_MAXARGS];
146

    
147
/**
148
 * @brief   Shell command to retrieve system information.
149
 */
150
static aos_shellcommand_t _shellcmd_info = {
151
  /* name     */ "module:info",
152
  /* callback */ _shellcmd_infocb,
153
  /* next     */ NULL,
154
};
155

    
156
/**
157
 * @brief   Shell command to set or retrieve system configuration.
158
 */
159
static aos_shellcommand_t _shellcmd_config = {
160
  /* name     */ "module:config",
161
  /* callback */ _shellcmd_configcb,
162
  /* next     */ NULL,
163
};
164

    
165
/**
166
 * @brief   Shell command to shutdown the system.
167
 */
168
static aos_shellcommand_t _shellcmd_shutdown = {
169
#if (AMIROOS_CFG_SSSP_ENABLE == true)
170
  /* name     */ "system:shutdown",
171
#else
172
  /* name     */ "module:shutdown",
173
#endif
174
  /* callback */ _shellcmd_shutdowncb,
175
  /* next     */ NULL,
176
};
177

    
178
#if (AMIROOS_CFG_TESTS_ENABLE == true) || defined(__DOXYGEN__)
179
/**
180
 * @brief   Shell kommand to run a test of the ChibiOS/RT kernel.
181
 */
182
static aos_shellcommand_t _shellcmd_kerneltest = {
183
  /* name     */ "kernel:test",
184
  /* callback */ _shellcmd_kerneltestcb,
185
  /* next     */ NULL,
186
};
187
#endif /* AMIROOS_CFG_TESTS_ENABLE == true */
188
#endif /* (AMIROOS_CFG_SHELL_ENABLE == true) || (AMIROOS_CFG_TESTS_ENABLE == true) */
189

    
190
/******************************************************************************/
191
/* LOCAL FUNCTIONS                                                            */
192
/******************************************************************************/
193

    
194
/**
195
 * @brief   Print a separator line.
196
 *
197
 * @param[in] stream    Stream to print to or NULL to print to all system streams.
198
 * @param[in] c         Character to use.
199
 * @param[in] n         Length of the separator line.
200
 *
201
 * @return  Number of characters printed.
202
 */
203
static unsigned int _printSystemInfoSeparator(BaseSequentialStream* stream, const char c, const unsigned int n)
204
{
205
  aosDbgCheck(stream != NULL);
206

    
207
  // print the specified character n times
208
  for (unsigned int i = 0; i < n; ++i) {
209
    streamPut(stream, c);
210
  }
211
  streamPut(stream, '\n');
212

    
213
  return n+1;
214
}
215

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

    
235
  unsigned int n = 0;
236
  va_list ap;
237

    
238
  va_start(ap, fmt);
239
  n += chprintf(stream, name);
240
  while (n < namewidth) {
241
    streamPut(stream, ' ');
242
    ++n;
243
  }
244
  n += chvprintf(stream, fmt, ap);
245
  va_end(ap);
246

    
247
  streamPut(stream, '\n');
248
  ++n;
249

    
250
  return n;
251
}
252

    
253
/**
254
 * @brief   Prints information about the system.
255
 *
256
 * @param[in] stream    Stream to print to.
257
 */
258
static void _printSystemInfo(BaseSequentialStream* stream)
259
{
260
  aosDbgCheck(stream != NULL);
261

    
262
  // local variables
263
  struct tm dt;
264
  aosSysGetDateTime(&dt);
265

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

    
293
  // print static information about the bootloader
294
  _printSystemInfoSeparator(stream, '-', SYSTEM_INFO_WIDTH);
295
  if (BL_CALLBACK_TABLE_ADDRESS->magicNumber == BL_MAGIC_NUMBER) {
296
    _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,
297
                         (BL_CALLBACK_TABLE_ADDRESS->vBootloader.identifier == BL_VERSION_ID_AMiRoBLT_Release) ? "stable" :
298
                         (BL_CALLBACK_TABLE_ADDRESS->vBootloader.identifier == BL_VERSION_ID_AMiRoBLT_ReleaseCandidate) ? "release candidate" :
299
                         (BL_CALLBACK_TABLE_ADDRESS->vBootloader.identifier == BL_VERSION_ID_AMiRoBLT_Beta) ? "beta" :
300
                         (BL_CALLBACK_TABLE_ADDRESS->vBootloader.identifier == BL_VERSION_ID_AMiRoBLT_Alpha) ? "alpha" :
301
                         (BL_CALLBACK_TABLE_ADDRESS->vBootloader.identifier == BL_VERSION_ID_AMiRoBLT_PreAlpha) ? "pre-alpha" :
302
                         "<release type unknown>",
303
                         BL_CALLBACK_TABLE_ADDRESS->vSSSP.major, BL_CALLBACK_TABLE_ADDRESS->vSSSP.minor);
304
#if (AMIROOS_CFG_SSSP_ENABLE == true)
305
    if (BL_CALLBACK_TABLE_ADDRESS->vSSSP.major != AOS_SYSTEM_SSSP_VERSION_MAJOR) {
306
      if (stream) {
307
        chprintf(stream, "WARNING: Bootloader and AMiRo-OS implement incompatible SSSP versions!\n");
308
      } else {
309
        aosprintf("WARNING: Bootloader and AMiRo-OS implement incompatible SSSP versions!\n");
310
      }
311
    }
312
#endif
313
    _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
314
  } else {
315
    if (stream) {
316
      chprintf(stream, "Bootloader incompatible or not available.\n");
317
    } else {
318
      aosprintf("Bootloader incompatible or not available.\n");
319
    }
320
  }
321

    
322
  // print dynamic information about the module
323
  _printSystemInfoSeparator(stream, '-', SYSTEM_INFO_WIDTH);
324
#if (AMIROOS_CFG_SSSP_ENABLE == true)
325
  if (aos.sssp.moduleId != 0) {
326
    _printSystemInfoLine(stream, "Module ID", SYSTEM_INFO_NAMEWIDTH, "%u", aos.sssp.moduleId);
327
  } else {
328
    _printSystemInfoLine(stream, "Module ID", SYSTEM_INFO_NAMEWIDTH, "not available");
329
  }
330
#endif
331
  _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",
332
                       dt.tm_mday,
333
                       dt.tm_mon + 1,
334
                       dt.tm_year + 1900);
335
  _printSystemInfoLine(stream, "Time", SYSTEM_INFO_NAMEWIDTH, "%02u:%02u:%02u", dt.tm_hour, dt.tm_min, dt.tm_sec);
336

    
337
  _printSystemInfoSeparator(stream, '=', SYSTEM_INFO_WIDTH);
338

    
339
  return;
340
}
341

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

    
358
  // local variables
359
  int retval = AOS_INVALID_ARGUMENTS;
360

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

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

    
475
      retval = AOS_OK;
476
    }
477
  }
478

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

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

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

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

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

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

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

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

    
557
  return AOS_OK;
558
}
559

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

    
575
#if (AMIROOS_CFG_SSSP_ENABLE == true)
576
  // print help text
577
  if (argc != 2 || strcmp(argv[1], "--help") == 0) {
578
    chprintf(stream, "Usage: %s OPTION\n", argv[0]);
579
    chprintf(stream, "Options:\n");
580
    chprintf(stream, "  --help\n");
581
    chprintf(stream, "    Print this help text.\n");
582
    chprintf(stream, "  --hibernate, -h\n");
583
    chprintf(stream, "    Shutdown to hibernate mode.\n");
584
    chprintf(stream, "    Least energy saving, but allows charging via pins.\n");
585
    chprintf(stream, "  --deepsleep, -d\n");
586
    chprintf(stream, "    Shutdown to deepsleep mode.\n");
587
    chprintf(stream, "    Minimum energy consumption while allowing charging via plug.\n");
588
    chprintf(stream, "  --transportation, -t\n");
589
    chprintf(stream, "    Shutdown to transportation mode.\n");
590
    chprintf(stream, "    Minimum energy consumption with all interrupts disabled (no charging).\n");
591
    chprintf(stream, "  --restart, -r\n");
592
    chprintf(stream, "    Shutdown and restart system.\n");
593

    
594
    return (argc != 2) ? AOS_INVALID_ARGUMENTS : AOS_OK;
595
  }
596
  // handle argument
597
  else {
598
    if (strcmp(argv[1], "-h") == 0 || strcmp(argv[1], "--hibernate") == 0) {
599
      chEvtBroadcastFlags(&aos.events.os, AOS_SYSTEM_EVENTFLAGS_HIBERNATE);
600
      chThdTerminate(chThdGetSelfX());
601
      return AOS_OK;
602
    }
603
    else if (strcmp(argv[1], "-d") == 0 || strcmp(argv[1], "--deepsleep") == 0) {
604
      chEvtBroadcastFlags(&aos.events.os, AOS_SYSTEM_EVENTFLAGS_DEEPSLEEP);
605
      chThdTerminate(chThdGetSelfX());
606
      return AOS_OK;
607
    }
608
    else if (strcmp(argv[1], "-t") == 0 || strcmp(argv[1], "--transportation") == 0) {
609
      chEvtBroadcastFlags(&aos.events.os, AOS_SYSTEM_EVENTFLAGS_TRANSPORTATION);
610
      chThdTerminate(chThdGetSelfX());
611
      return AOS_OK;
612
    }
613
    else if (strcmp(argv[1], "-r") == 0 || strcmp(argv[1], "--restart") == 0) {
614
      chEvtBroadcastFlags(&aos.events.os, AOS_SYSTEM_EVENTFLAGS_RESTART);
615
      chThdTerminate(chThdGetSelfX());
616
      return AOS_OK;
617
    }
618
    else {
619
      chprintf(stream, "unknown argument %s\n", argv[1]);
620
      return AOS_INVALID_ARGUMENTS;
621
    }
622
  }
623
#else /* AMIROOS_CFG_SSSP_ENABLE == false */
624
  (void)argv;
625
  (void)argc;
626

    
627
  chEvtBroadcastFlags(&aos.events.os, AOS_SYSTEM_EVENTFLAGS_SHUTDOWN);
628
  chThdTerminate(chThdGetSelfX());
629
  return AOS_OK;
630
#endif /* AMIROOS_CFG_SSSP_ENABLE */
631
}
632

    
633
#if (AMIROOS_CFG_TESTS_ENABLE == true) || defined(__DOXYGEN__)
634
/**
635
 * @brief   Callback function for the kernel:test shell command.
636
 *
637
 * @param[in] stream    The I/O stream to use.
638
 * @param[in] argc      Number of arguments.
639
 * @param[in] argv      List of pointers to the arguments.
640
 *
641
 * @return      An exit status.
642
 */
643
static int _shellcmd_kerneltestcb(BaseSequentialStream* stream, int argc, char* argv[])
644
{
645
  aosDbgCheck(stream != NULL);
646

    
647
  (void)argc;
648
  (void)argv;
649

    
650
  msg_t retval = test_execute(stream, &rt_test_suite);
651

    
652
  return retval;
653
}
654
#endif /* AMIROOS_CFG_TESTS_ENABLE == true */
655
#endif /* (AMIROOS_CFG_SHELL_ENABLE == true) || (AMIROOS_CFG_TESTS_ENABLE == true) */
656

    
657
// suppress warning in case no interrupt GPIOs are defined
658
#pragma GCC diagnostic push
659
#pragma GCC diagnostic ignored "-Wunused-function"
660
/**
661
 * @brief   Generic callback function for GPIO interrupts.
662
 *
663
 * @param[in] args   Pointer to the GPIO pad identifier.
664
 */
665
static void _intCallback(void* args)
666
{
667
  aosDbgCheck((args != NULL) && (*((iopadid_t*)args) < sizeof(eventflags_t) * 8));
668

    
669
  chSysLockFromISR();
670
  chEvtBroadcastFlagsI(&aos.events.io, AOS_IOEVENT_FLAG(*((iopadid_t*)args)));
671
  chSysUnlockFromISR();
672

    
673
  return;
674
}
675
#pragma GCC diagnostic pop
676

    
677
#if ((AMIROOS_CFG_SSSP_ENABLE == true) && (AMIROOS_CFG_SSSP_MASTER != true)) || defined(__DOXYGEN__)
678
/**
679
 * @brief   Callback function for the Sync signal interrupt.
680
 *
681
 * @param[in] args   Pointer to the GPIO pad identifier.
682
 */
683
static void _signalSyncCallback(void *args)
684
{
685
  aosDbgCheck((args != NULL) && (*((iopadid_t*)args) < sizeof(eventflags_t) * 8));
686

    
687
  apalControlGpioState_t s_state;
688
  aos_timestamp_t uptime;
689

    
690
  chSysLockFromISR();
691
  // if the system is in operation phase
692
  if (aos.sssp.stage == AOS_SSSP_OPERATION) {
693
    // read signal S
694
    apalControlGpioGet(&moduleSsspGpioSync, &s_state);
695
    // if S was toggled from on to off
696
    if (s_state == APAL_GPIO_OFF) {
697
      // get current uptime
698
      aosSysGetUptimeX(&uptime);
699
      // align the uptime with the synchronization period
700
      if (uptime % AMIROOS_CFG_SSSP_SYSSYNCPERIOD < AMIROOS_CFG_SSSP_SYSSYNCPERIOD / 2) {
701
        _uptime -= uptime % AMIROOS_CFG_SSSP_SYSSYNCPERIOD;
702
#if (AMIROOS_CFG_PROFILE == true)
703
        _syssyncskew = ((1.0f - SYSTEM_SYSSYNCSKEW_LPFACTOR) * _syssyncskew) + (SYSTEM_SYSSYNCSKEW_LPFACTOR * (uptime % AMIROOS_CFG_SSSP_SYSSYNCPERIOD));
704
#endif
705
      } else {
706
        _uptime += AMIROOS_CFG_SSSP_SYSSYNCPERIOD - (uptime % AMIROOS_CFG_SSSP_SYSSYNCPERIOD);
707
#if (AMIROOS_CFG_PROFILE == true)
708
        _syssyncskew = ((1.0f - SYSTEM_SYSSYNCSKEW_LPFACTOR) * _syssyncskew) - (SYSTEM_SYSSYNCSKEW_LPFACTOR * (AMIROOS_CFG_SSSP_SYSSYNCPERIOD - (uptime % AMIROOS_CFG_SSSP_SYSSYNCPERIOD)));
709
#endif
710
      }
711
    }
712
  }
713
  // broadcast event
714
  chEvtBroadcastFlagsI(&aos.events.io, AOS_IOEVENT_FLAG(*((iopadid_t*)args)));
715
  chSysUnlockFromISR();
716

    
717
  return;
718
}
719
#endif /* (AMIROOS_CFG_SSSP_ENABLE == true) && (AMIROOS_CFG_SSSP_MASTER != true) */
720

    
721
/**
722
 * @brief   Callback function for the uptime accumulation timer.
723
 *
724
 * @param[in] par   Generic parameter.
725
 */
726
static void _uptimeCallback(void* par)
727
{
728
  (void)par;
729

    
730
  chSysLockFromISR();
731
  // read current time in system ticks
732
  register const systime_t st = chVTGetSystemTimeX();
733
  // update the uptime variables
734
  _uptime += chTimeI2US(chTimeDiffX(_synctime, st));
735
  _synctime = st;
736
  // enable the timer again
737
  chVTSetI(&_systimer, SYSTIMER_PERIOD, &_uptimeCallback, NULL);
738
  chSysUnlockFromISR();
739

    
740
  return;
741
}
742

    
743
#if ((AMIROOS_CFG_SSSP_ENABLE == true) && (AMIROOS_CFG_SSSP_MASTER == true)) || defined (__DOXYGEN__)
744
/**
745
 * @brief   Periodic system synchronization callback function.
746
 * @details Toggles the SYS_SYNC signal and reconfigures the system synchronization timer.
747
 *
748
 * @param[in] par   Unuesed parameters.
749
 */
750
static void _sysSyncTimerCallback(void* par)
751
{
752
  (void)par;
753

    
754
  apalControlGpioState_t s_state;
755
  aos_timestamp_t uptime;
756

    
757
  chSysLockFromISR();
758
  // toggle and read signal S
759
  apalGpioToggle(moduleSsspGpioSync.gpio);
760
  apalControlGpioGet(&moduleSsspGpioSync, &s_state);
761
  // if S was toggled from off to on
762
  if (s_state == APAL_GPIO_ON) {
763
    // reconfigure the timer precisely, because the logically falling edge (next interrupt) snychronizes the system time
764
    _syssynctime += AMIROOS_CFG_SSSP_SYSSYNCPERIOD;
765
    aosSysGetUptimeX(&uptime);
766
    chVTSetI(&_syssynctimer, chTimeUS2I(_syssynctime - uptime), _sysSyncTimerCallback, NULL);
767
  }
768
  // if S was toggled from on to off
769
  else /* if (s_state == APAL_GPIO_OFF) */ {
770
    // reconfigure the timer (lazy)
771
    chVTSetI(&_syssynctimer, chTimeUS2I(AMIROOS_CFG_SSSP_SYSSYNCPERIOD / 2), _sysSyncTimerCallback, NULL);
772
  }
773
  chSysUnlockFromISR();
774

    
775
  return;
776
}
777
#endif /* (AMIROOS_CFG_SSSP_ENABLE == true) && (AMIROOS_CFG_SSSP_MASTER == true) */
778

    
779
/******************************************************************************/
780
/* EXPORTED FUNCTIONS                                                         */
781
/******************************************************************************/
782

    
783
/**
784
 * @brief   AMiRo-OS system initialization.
785
 * @note    Must be called from the system control thread (usually main thread).
786
 *
787
 * @param[in] shellPrompt   String to be printed as prompt of the system shell.
788
 */
789
#if (AMIROOS_CFG_SHELL_ENABLE == true) || (AMIROOS_CFG_TESTS_ENABLE == true) || defined(__DOXYGEN__)
790
void aosSysInit(const char* shellPrompt)
791
#else
792
void aosSysInit(void)
793
#endif
794
{
795
  /* set control thread to maximum priority */
796
  chThdSetPriority(AOS_THD_CTRLPRIO);
797

    
798
  /* set local variables */
799
  chVTObjectInit(&_systimer);
800
#if (AMIROOS_CFG_SSSP_ENABLE == true)
801
  _synctime = 0;
802
  _uptime = 0;
803
#if (AMIROOS_CFG_SSSP_MASTER == true)
804
  chVTObjectInit(&_syssynctimer);
805
  _syssynctime = 0;
806
#endif
807
#if (AMIROOS_CFG_SSSP_MASTER != true) && (AMIROOS_CFG_PROFILE == true)
808
  _syssyncskew = 0.0f;
809
#endif
810
#else /* AMIROOS_CFG_SSSP_ENABLE == false */
811
  // start the uptime counter
812
  chSysLock();
813
  _synctime = chVTGetSystemTimeX();
814
  _uptime = 0;
815
  chVTSetI(&_systimer, SYSTIMER_PERIOD, &_uptimeCallback, NULL);
816
  chSysUnlock();
817
#endif /* AMIROOS_CFG_SSSP_ENABLE */
818

    
819
  /* initialize aos configuration */
820
#if (AMIROOS_CFG_SSSP_ENABLE == true)
821
  aos.sssp.stage = AOS_SSSP_STARTUP_2_1;
822
  aos.sssp.moduleId = 0;
823
#endif
824
  aosIOStreamInit(&aos.iostream);
825
  chEvtObjectInit(&aos.events.io);
826
  chEvtObjectInit(&aos.events.os);
827

    
828
  /* interrupt setup */
829
#if (AMIROOS_CFG_SSSP_ENABLE == true)
830
  // PD signal
831
  palSetPadCallback(moduleSsspGpioPd.gpio->port, moduleSsspGpioPd.gpio->pad, _intCallback, &moduleSsspGpioPd.gpio->pad);
832
  palEnablePadEvent(moduleSsspGpioPd.gpio->port, moduleSsspGpioPd.gpio->pad, APAL2CH_EDGE(moduleSsspGpioPd.meta.edge));
833
  // SYNC signal
834
#if (AMIROOS_CFG_SSSP_MASTER == true)
835
  palSetPadCallback(moduleSsspGpioSync.gpio->port, moduleSsspGpioSync.gpio->pad, _intCallback, &moduleSsspGpioSync.gpio->pad);
836
#else
837
  palSetPadCallback(moduleSsspGpioSync.gpio->port, moduleSsspGpioSync.gpio->pad, _signalSyncCallback, &moduleSsspGpioSync.gpio->pad);
838
#endif
839
  palEnablePadEvent(moduleSsspGpioSync.gpio->port, moduleSsspGpioSync.gpio->pad, APAL2CH_EDGE(moduleSsspGpioSync.meta.edge));
840
#if (AMIROOS_CFG_SSSP_STACK_START != true)
841
  // DN signal
842
  palSetPadCallback(moduleSsspGpioDn.gpio->port, moduleSsspGpioDn.gpio->pad, _intCallback, &moduleSsspGpioDn.gpio->pad);
843
  palEnablePadEvent(moduleSsspGpioDn.gpio->port, moduleSsspGpioDn.gpio->pad, APAL2CH_EDGE(moduleSsspGpioDn.meta.edge));
844
#endif
845
#if (AMIROOS_CFG_SSSP_STACK_END != true)
846
  // UP signal
847
  palSetPadCallback(moduleSsspGpioUp.gpio->port, moduleSsspGpioUp.gpio->pad, _intCallback, &moduleSsspGpioUp.gpio->pad);
848
  palEnablePadEvent(moduleSsspGpioUp.gpio->port, moduleSsspGpioUp.gpio->pad, APAL2CH_EDGE(moduleSsspGpioUp.meta.edge));
849
#endif
850
#endif /* AMIROOS_CFG_SSSP_ENABLE == true */
851
#ifdef MODULE_INIT_INTERRUPTS
852
  // further interrupt signals
853
  MODULE_INIT_INTERRUPTS();
854
#endif
855

    
856
#if (AMIROOS_CFG_SHELL_ENABLE == true) || (AMIROOS_CFG_TESTS_ENABLE == true)
857
  /* init shell */
858
  aosShellInit(&aos.shell,
859
               &aos.events.os,
860
               shellPrompt,
861
               _shell_line,
862
               AMIROOS_CFG_SHELL_LINEWIDTH,
863
               _shell_arglist,
864
               AMIROOS_CFG_SHELL_MAXARGS);
865
  // add system commands
866
  aosShellAddCommand(&aos.shell, &_shellcmd_config);
867
  aosShellAddCommand(&aos.shell, &_shellcmd_info);
868
  aosShellAddCommand(&aos.shell, &_shellcmd_shutdown);
869
#if (AMIROOS_CFG_TESTS_ENABLE == true)
870
  aosShellAddCommand(&aos.shell, &_shellcmd_kerneltest);
871
#endif
872
#endif /* (AMIROOS_CFG_SHELL_ENABLE == true) || (AMIROOS_CFG_TESTS_ENABLE == true) */
873

    
874
  return;
875
}
876

    
877
/**
878
 * @brief   Starts the system and all system threads.
879
 */
880
inline void aosSysStart(void)
881
{
882
#if (AMIROOS_CFG_SSSP_ENABLE == true)
883
  // update the system SSSP stage
884
  aos.sssp.stage = AOS_SSSP_OPERATION;
885

    
886
#if (AMIROOS_CFG_SSSP_MASTER == true)
887
  {
888
    chSysLock();
889
    // start the system synchronization counter
890
    // The first iteration of the timer is set to the next 'center' of a 'slice'.
891
    aos_timestamp_t t;
892
    aosSysGetUptimeX(&t);
893
    t = AMIROOS_CFG_SSSP_SYSSYNCPERIOD - (t % AMIROOS_CFG_SSSP_SYSSYNCPERIOD);
894
    chVTSetI(&_syssynctimer, chTimeUS2I((t > (AMIROOS_CFG_SSSP_SYSSYNCPERIOD / 2)) ? (t - (AMIROOS_CFG_SSSP_SYSSYNCPERIOD / 2)) : (t + (AMIROOS_CFG_SSSP_SYSSYNCPERIOD / 2))), _sysSyncTimerCallback, NULL);
895
    chSysUnlock();
896
  }
897
#endif
898
#endif /* AMIROOS_CFG_SSSP_ENABLE == true */
899

    
900
  // print system information;
901
  _printSystemInfo((BaseSequentialStream*)&aos.iostream);
902
  aosprintf("\n");
903

    
904
#if (AMIROOS_CFG_SHELL_ENABLE == true) || (AMIROOS_CFG_TESTS_ENABLE == true)
905
  // start system shell thread
906
#if (CH_CFG_USE_THREADHIERARCHY == TRUE)
907
  aos.shell.thread = chThdCreateStatic(_shell_wa, sizeof(_shell_wa), AMIROOS_CFG_SHELL_THREADPRIO, aosShellThread, &aos.shell, &ch.mainthread);
908
#else
909
  aos.shell.thread = chThdCreateStatic(_shell_wa, sizeof(_shell_wa), AMIROOS_CFG_SHELL_THREADPRIO, aosShellThread, &aos.shell);
910
#endif
911
#endif
912

    
913
  return;
914
}
915

    
916
#if (AMIROOS_CFG_SSSP_ENABLE == true) || defined(__DOXYGEN__)
917
/**
918
 * @brief   Implements the SSSP startup synchronization step.
919
 *
920
 * @param[in] syncEvtListener   Event listener that receives the Sync event.
921
 *
922
 * @return    If another event that the listener is interested in was received, its mask is returned.
923
 *            Otherwise an empty mask (0) is returned.
924
 */
925
eventmask_t aosSysSsspStartupOsInitSyncCheck(event_listener_t* syncEvtListener)
926
{
927
  aosDbgCheck(syncEvtListener != NULL);
928

    
929
  // local variables
930
  eventmask_t m;
931
  eventflags_t f;
932
  apalControlGpioState_t s;
933

    
934
  // update the system SSSP stage
935
  aos.sssp.stage = AOS_SSSP_STARTUP_2_2;
936

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

    
940
  // wait for any event to occur (do not apply any filter in order not to miss any event)
941
  m = chEvtWaitOne(ALL_EVENTS);
942
  f = chEvtGetAndClearFlags(syncEvtListener);
943
  apalControlGpioGet(&moduleSsspGpioSync, &s);
944

    
945
  // if the event was a system event,
946
  //   and it was fired because of the SysSync control signal,
947
  //   and the SysSync control signal has been deactivated
948
  if (m & syncEvtListener->events &&
949
      f == MODULE_SSSP_EVENTFLAGS_SYNC &&
950
      s == APAL_GPIO_OFF) {
951
    chSysLock();
952
    // start the uptime counter
953
    _synctime = chVTGetSystemTimeX();
954
    _uptime = 0;
955
    chVTSetI(&_systimer, SYSTIMER_PERIOD, &_uptimeCallback, NULL);
956
    chSysUnlock();
957

    
958
    return 0;
959
  }
960
  // an unexpected event occurred
961
  else {
962
    // reassign the flags to the event and return the event mask
963
    syncEvtListener->flags |= f;
964
    return m;
965
  }
966
}
967
#endif /* AMIROOS_CFG_SSSP_ENABLE == true */
968

    
969
/**
970
 * @brief   Retrieves the system uptime.
971
 *
972
 * @param[out] ut   The system uptime.
973
 */
974
inline void aosSysGetUptimeX(aos_timestamp_t* ut)
975
{
976
  aosDbgCheck(ut != NULL);
977

    
978
  *ut = _uptime + chTimeI2US(chTimeDiffX(_synctime, chVTGetSystemTimeX()));
979

    
980
  return;
981
}
982

    
983
/**
984
 * @brief   retrieves the date and time from the MCU clock.
985
 *
986
 * @param[out] td   The date and time.
987
 */
988
void aosSysGetDateTime(struct tm* dt)
989
{
990
  aosDbgCheck(dt != NULL);
991

    
992
  RTCDateTime rtc;
993
  rtcGetTime(&MODULE_HAL_RTC, &rtc);
994
  rtcConvertDateTimeToStructTm(&rtc, dt, NULL);
995

    
996
  return;
997
}
998

    
999
/**
1000
 * @brief   set the date and time of the MCU clock.
1001
 *
1002
 * @param[in] dt    The date and time to set.
1003
 */
1004
void aosSysSetDateTime(struct tm* dt)
1005
{
1006
  aosDbgCheck(dt != NULL);
1007

    
1008
  RTCDateTime rtc;
1009
  rtcConvertStructTmToDateTime(dt, 0, &rtc);
1010
  rtcSetTime(&MODULE_HAL_RTC, &rtc);
1011

    
1012
  return;
1013
}
1014

    
1015
/**
1016
 * @brief   Initializes/Acknowledges a system shutdown/restart request.
1017
 * @note    This functions should be called from the thread with highest priority.
1018
 *
1019
 * @param[in] shutdown    Type of shutdown.
1020
 */
1021
void aosSysShutdownInit(aos_shutdown_t shutdown)
1022
{
1023
  // check arguments
1024
  aosDbgCheck(shutdown != AOS_SHUTDOWN_NONE);
1025

    
1026
#if (AMIROOS_CFG_SSSP_ENABLE == true)
1027
#if (AMIROOS_CFG_SSSP_MASTER == true)
1028
  // deactivate the system synchronization timer
1029
  chVTReset(&_syssynctimer);
1030
#endif
1031

    
1032
  // update the system SSSP stage
1033
  aos.sssp.stage = AOS_SSSP_SHUTDOWN_1_1;
1034

    
1035
  chSysLock();
1036
  // activate the SYS_PD control signal only, if this module initiated the shutdown
1037
  if (shutdown != AOS_SHUTDOWN_PASSIVE) {
1038
    apalControlGpioSet(&moduleSsspGpioPd, APAL_GPIO_ON);
1039
  }
1040
  // activate the SYS_SYNC signal
1041
  apalControlGpioSet(&moduleSsspGpioSync, APAL_GPIO_ON);
1042
  chSysUnlock();
1043
#endif /* AMIROOS_CFG_SSSP_ENABLE == true */
1044

    
1045
  switch (shutdown) {
1046
    case AOS_SHUTDOWN_PASSIVE:
1047
      chEvtBroadcastFlags(&aos.events.os, AOS_SYSTEM_EVENTFLAGS_SHUTDOWN);
1048
      aosprintf("shutdown request received...\n");
1049
      break;
1050
    case AOS_SHUTDOWN_HIBERNATE:
1051
      chEvtBroadcastFlags(&aos.events.os, AOS_SYSTEM_EVENTFLAGS_HIBERNATE);
1052
      aosprintf("shutdown to hibernate mode...\n");
1053
      break;
1054
    case AOS_SHUTDOWN_DEEPSLEEP:
1055
      chEvtBroadcastFlags(&aos.events.os, AOS_SYSTEM_EVENTFLAGS_DEEPSLEEP);
1056
      aosprintf("shutdown to deepsleep mode...\n");
1057
      break;
1058
    case AOS_SHUTDOWN_TRANSPORTATION:
1059
      chEvtBroadcastFlags(&aos.events.os, AOS_SYSTEM_EVENTFLAGS_TRANSPORTATION);
1060
      aosprintf("shutdown to transportation mode...\n");
1061
      break;
1062
    case AOS_SHUTDOWN_RESTART:
1063
      chEvtBroadcastFlags(&aos.events.os, AOS_SYSTEM_EVENTFLAGS_RESTART);
1064
      aosprintf("restarting system...\n");
1065
      break;
1066
    // must never occur
1067
    case AOS_SHUTDOWN_NONE:
1068
    default:
1069
      break;
1070
  }
1071

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

    
1077
  return;
1078
}
1079

    
1080
/**
1081
 * @brief   Stops the system and all related threads (not the thread this function is called from).
1082
 */
1083
void aosSysStop(void)
1084
{
1085
#if (AMIROOS_CFG_SHELL_ENABLE == true) || (AMIROOS_CFG_TESTS_ENABLE == true)
1086
  chThdWait(aos.shell.thread);
1087
#endif
1088

    
1089
  return;
1090
}
1091

    
1092
/**
1093
 * @brief   Deinitialize all system variables.
1094
 */
1095
void aosSysDeinit(void)
1096
{
1097
  return;
1098
}
1099

    
1100
/**
1101
 * @brief   Finally shuts down the system and calls the bootloader callback function.
1102
 * @note    This function should be called from the thtead with highest priority.
1103
 *
1104
 * @param[in] shutdown    Type of shutdown.
1105
 */
1106
void aosSysShutdownFinal(aos_shutdown_t shutdown)
1107
{
1108
  // check arguments
1109
  aosDbgCheck(shutdown != AOS_SHUTDOWN_NONE);
1110

    
1111
  // disable all interrupts
1112
  irqDeinit();
1113

    
1114
#if (AMIROOS_CFG_SSSP_ENABLE == true)
1115
  // update the system SSSP stage
1116
  aos.sssp.stage = AOS_SSSP_SHUTDOWN_1_3;
1117
#endif
1118

    
1119
  // validate bootloader
1120
  if ((BL_CALLBACK_TABLE_ADDRESS->magicNumber == BL_MAGIC_NUMBER) &&
1121
      (BL_CALLBACK_TABLE_ADDRESS->vBootloader.major == BL_VERSION_MAJOR) &&
1122
      (BL_CALLBACK_TABLE_ADDRESS->vBootloader.minor >= BL_VERSION_MINOR)) {
1123
    // call bootloader callback depending on arguments
1124
    switch (shutdown) {
1125
      case AOS_SHUTDOWN_PASSIVE:
1126
        BL_CALLBACK_TABLE_ADDRESS->cbHandleShutdownRequest();
1127
        break;
1128
      case AOS_SHUTDOWN_HIBERNATE:
1129
        BL_CALLBACK_TABLE_ADDRESS->cbShutdownHibernate();
1130
        break;
1131
      case AOS_SHUTDOWN_DEEPSLEEP:
1132
        BL_CALLBACK_TABLE_ADDRESS->cbShutdownDeepsleep();
1133
        break;
1134
      case AOS_SHUTDOWN_TRANSPORTATION:
1135
        BL_CALLBACK_TABLE_ADDRESS->cbShutdownTransportation();
1136
        break;
1137
      case AOS_SHUTDOWN_RESTART:
1138
        BL_CALLBACK_TABLE_ADDRESS->cbShutdownRestart();
1139
        break;
1140
      // must never occur
1141
      case AOS_SHUTDOWN_NONE:
1142
      default:
1143
        break;
1144
    }
1145
  } else {
1146
    // fallback if bootloader was found to be invalid
1147
    aosprintf("Bootloader incompatible or not available!\n");
1148
    aosThdMSleep(10);
1149
    chSysDisable();
1150
  }
1151

    
1152
  return;
1153
}
1154

    
1155
/** @} */