Statistics
| Branch: | Tag: | Revision:

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

History | View | Annotate | Download (41.5 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
/* LOCAL DEFINITIONS                                                          */
42
/******************************************************************************/
43

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

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

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

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

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

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

    
68
/******************************************************************************/
69
/* EXPORTED VARIABLES                                                         */
70
/******************************************************************************/
71

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

    
77
/******************************************************************************/
78
/* LOCAL TYPES                                                                */
79
/******************************************************************************/
80

    
81
/******************************************************************************/
82
/* LOCAL VARIABLES                                                            */
83
/******************************************************************************/
84

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

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

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

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

    
112
#if ((AMIROOS_CFG_SSSP_ENABLE == true) && (AMIROOS_CFG_SSSP_MASTER == true)) || defined(__DOXYGEN__)
113
/**
114
 * @brief   Timer to drive the SYS_SYNC signal for system wide time synchronization according to SSSP.
115
 */
116
static virtual_timer_t _syssynctimer;
117

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

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

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

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

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

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

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

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

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

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

    
191
/******************************************************************************/
192
/* LOCAL FUNCTIONS                                                            */
193
/******************************************************************************/
194

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

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

    
214
  return n+1;
215
}
216

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

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

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

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

    
251
  return n;
252
}
253

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

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

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

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

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

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

    
340
  return;
341
}
342

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

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

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

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

    
476
      retval = AOS_OK;
477
    }
478
  }
479

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

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

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

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

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

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

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

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

    
558
  return AOS_OK;
559
}
560

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

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

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

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

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

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

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

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

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

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

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

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

    
688
  apalControlGpioState_t s_state;
689
  aos_timestamp_t uptime;
690

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

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

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

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

    
741
  return;
742
}
743

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

    
755
  apalControlGpioState_t s_state;
756
  aos_timestamp_t uptime;
757

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

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

    
780
/******************************************************************************/
781
/* EXPORTED FUNCTIONS                                                         */
782
/******************************************************************************/
783

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

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

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

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

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

    
875
  return;
876
}
877

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

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

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

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

    
914
  return;
915
}
916

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

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

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

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

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

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

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

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

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

    
981
  return;
982
}
983

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

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

    
997
  return;
998
}
999

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

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

    
1013
  return;
1014
}
1015

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

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

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

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

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

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

    
1078
  return;
1079
}
1080

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

    
1090
  return;
1091
}
1092

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

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

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

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

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

    
1153
  return;
1154
}
1155

    
1156
/** @} */