Statistics
| Branch: | Tag: | Revision:

amiro-os / core / src / aos_system.c @ 3cb82b1a

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

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

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

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

    
335
  return;
336
}
337

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

    
354
  // local variables
355
  int retval = AOS_INVALID_ARGUMENTS;
356

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

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

    
471
      retval = AOS_OK;
472
    }
473
  }
474

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

    
499
  return (argc > 1 && strcmp(argv[1], "--help") == 0) ? AOS_OK : retval;
500
}
501

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

    
516
  (void)argc;
517
  (void)argv;
518

    
519
  // print system information
520
  _printSystemInfo(stream);
521

    
522
  // print time measurement precision
523
  chprintf(stream, "module time resolution: %uus\n", AOS_SYSTEM_TIME_RESOLUTION);
524

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

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

    
553
  return AOS_OK;
554
}
555

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

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

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

    
623
  chEvtBroadcastFlags(&aos.events.os, AOS_SYSTEM_EVENTFLAGS_SHUTDOWN);
624
  chThdTerminate(chThdGetSelfX());
625
  return AOS_OK;
626
#endif /* AMIROOS_CFG_SSSP_ENABLE */
627
}
628

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

    
643
  (void)argc;
644
  (void)argv;
645

    
646
  msg_t retval = test_execute(stream, &rt_test_suite);
647

    
648
  return retval;
649
}
650
#endif /* AMIROOS_CFG_TESTS_ENABLE == true */
651
#endif /* (AMIROOS_CFG_SHELL_ENABLE == true) || (AMIROOS_CFG_TESTS_ENABLE == true) */
652

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

    
665
  chSysLockFromISR();
666
  chEvtBroadcastFlagsI(&aos.events.io, AOS_IOEVENT_FLAG(*((iopadid_t*)args)));
667
  chSysUnlockFromISR();
668

    
669
  return;
670
}
671
#pragma GCC diagnostic pop
672

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

    
683
  apalControlGpioState_t s_state;
684
  aos_timestamp_t uptime;
685

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

    
713
  return;
714
}
715
#endif /* (AMIROOS_CFG_SSSP_ENABLE == true) && (AMIROOS_CFG_SSSP_MASTER != true) */
716

    
717
/**
718
 * @brief   Callback function for the uptime accumulation timer.
719
 *
720
 * @param[in] par   Generic parameter.
721
 */
722
static void _uptimeCallback(void* par)
723
{
724
  (void)par;
725

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

    
736
  return;
737
}
738

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

    
750
  apalControlGpioState_t s_state;
751
  aos_timestamp_t uptime;
752

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

    
771
  return;
772
}
773
#endif /* (AMIROOS_CFG_SSSP_ENABLE == true) && (AMIROOS_CFG_SSSP_MASTER == true) */
774

    
775
/******************************************************************************/
776
/* EXPORTED FUNCTIONS                                                         */
777
/******************************************************************************/
778

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

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

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

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

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

    
870
  return;
871
}
872

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

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

    
896
  // print system information;
897
  _printSystemInfo((BaseSequentialStream*)&aos.iostream);
898
  aosprintf("\n");
899

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

    
909
  return;
910
}
911

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

    
925
  // local variables
926
  eventmask_t m;
927
  eventflags_t f;
928
  apalControlGpioState_t s;
929

    
930
  // update the system SSSP stage
931
  aos.sssp.stage = AOS_SSSP_STARTUP_2_2;
932

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

    
936
  // wait for any event to occur (do not apply any filter in order not to miss any event)
937
  m = chEvtWaitOne(ALL_EVENTS);
938
  f = chEvtGetAndClearFlags(syncEvtListener);
939
  apalControlGpioGet(&moduleSsspGpioSync, &s);
940

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

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

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

    
974
  *ut = _uptime + chTimeI2US(chTimeDiffX(_synctime, chVTGetSystemTimeX()));
975

    
976
  return;
977
}
978

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

    
988
  RTCDateTime rtc;
989
  rtcGetTime(&MODULE_HAL_RTC, &rtc);
990
  rtcConvertDateTimeToStructTm(&rtc, dt, NULL);
991

    
992
  return;
993
}
994

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

    
1004
  RTCDateTime rtc;
1005
  rtcConvertStructTmToDateTime(dt, 0, &rtc);
1006
  rtcSetTime(&MODULE_HAL_RTC, &rtc);
1007

    
1008
  return;
1009
}
1010

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

    
1022
#if (AMIROOS_CFG_SSSP_ENABLE == true)
1023
#if (AMIROOS_CFG_SSSP_MASTER == true)
1024
  // deactivate the system synchronization timer
1025
  chVTReset(&_syssynctimer);
1026
#endif
1027

    
1028
  // update the system SSSP stage
1029
  aos.sssp.stage = AOS_SSSP_SHUTDOWN_1_1;
1030

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

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

    
1068
#if (AMIROOS_CFG_SSSP_ENABLE == true)
1069
  // update the system SSSP stage
1070
  aos.sssp.stage = AOS_SSSP_SHUTDOWN_1_2;
1071
#endif
1072

    
1073
  return;
1074
}
1075

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

    
1085
  return;
1086
}
1087

    
1088
/**
1089
 * @brief   Deinitialize all system variables.
1090
 */
1091
void aosSysDeinit(void)
1092
{
1093
  return;
1094
}
1095

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

    
1107
  // disable all interrupts
1108
  irqDeinit();
1109

    
1110
#if (AMIROOS_CFG_SSSP_ENABLE == true)
1111
  // update the system SSSP stage
1112
  aos.sssp.stage = AOS_SSSP_SHUTDOWN_1_3;
1113
#endif
1114

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

    
1148
  return;
1149
}
1150

    
1151
/** @} */