Statistics
| Branch: | Tag: | Revision:

amiro-os / core / src / aos_system.c @ 78b92b33

History | View | Annotate | Download (42.921 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 /* (AMIROOS_CFG_TESTS_ENABLE == true) */
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) || 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) */
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) || 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_SHELL_COMMAND(_shellcmd_info, "module:info", _shellcmd_infocb);
151

    
152
/**
153
 * @brief   Shell command to set or retrieve system configuration.
154
 */
155
static AOS_SHELL_COMMAND(_shellcmd_config, "module:config", _shellcmd_configcb);
156

    
157
/**
158
 * @brief   Shell command to shutdown the system.
159
 */
160
#if (AMIROOS_CFG_SSSP_ENABLE == true) || defined(__DOXYGEN__)
161
static AOS_SHELL_COMMAND(_shellcmd_shutdown, "system:shutdown", _shellcmd_shutdowncb);
162
#else /* (AMIROOS_CFG_SSSP_ENABLE == true) */
163
static AOS_SHELL_COMMAND(_shellcmd_shutdown, "module:shutdown", _shellcmd_shutdowncb);
164
#endif /* (AMIROOS_CFG_SSSP_ENABLE == true) */
165

    
166
#if (AMIROOS_CFG_TESTS_ENABLE == true) || defined(__DOXYGEN__)
167

    
168
/**
169
 * @brief   Shell kommand to run a test of the ChibiOS/RT kernel.
170
 */
171
static AOS_SHELL_COMMAND(_shellcmd_kerneltest, "kernel:test", _shellcmd_kerneltestcb);
172

    
173
#endif /* (AMIROOS_CFG_TESTS_ENABLE == true) */
174
#endif /* (AMIROOS_CFG_SHELL_ENABLE == true) */
175

    
176
/******************************************************************************/
177
/* LOCAL FUNCTIONS                                                            */
178
/******************************************************************************/
179

    
180
/**
181
 * @brief   Print a separator line.
182
 *
183
 * @param[in] stream    Stream to print to or NULL to print to all system streams.
184
 * @param[in] c         Character to use.
185
 * @param[in] n         Length of the separator line.
186
 *
187
 * @return  Number of characters printed.
188
 */
189
static unsigned int _printSystemInfoSeparator(BaseSequentialStream* stream, const char c, const unsigned int n)
190
{
191
  aosDbgCheck(stream != NULL);
192

    
193
  // print the specified character n times
194
  for (unsigned int i = 0; i < n; ++i) {
195
    streamPut(stream, (uint8_t)c);
196
  }
197
  streamPut(stream, '\n');
198

    
199
  return n+1;
200
}
201

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

    
221
  unsigned int n = 0;
222
  va_list ap;
223

    
224
  va_start(ap, fmt);
225
  n += (unsigned int)chprintf(stream, name);
226
  while (n < namewidth) {
227
    streamPut(stream, ' ');
228
    ++n;
229
  }
230
  n += (unsigned int)chvprintf(stream, fmt, ap);
231
  va_end(ap);
232

    
233
  streamPut(stream, '\n');
234
  ++n;
235

    
236
  return n;
237
}
238

    
239
/**
240
 * @brief   Prints information about the system.
241
 *
242
 * @param[in] stream    Stream to print to.
243
 */
244
static void _printSystemInfo(BaseSequentialStream* stream)
245
{
246
  aosDbgCheck(stream != NULL);
247

    
248
  // local variables
249
#if (HAL_USE_RTC == TRUE)
250
  struct tm dt;
251
  aosSysGetDateTime(&dt);
252
#endif /* (HAL_USE_RTC == TRUE) */
253

    
254
  // print static information about module and operating system
255
  _printSystemInfoSeparator(stream, '=', SYSTEM_INFO_WIDTH);
256
  _printSystemInfoLine(stream, "Module", SYSTEM_INFO_NAMEWIDTH, "%s", BOARD_NAME);
257
#if defined(PLATFORM_NAME)
258
  _printSystemInfoLine(stream, "Platform", SYSTEM_INFO_NAMEWIDTH, "%s", PLATFORM_NAME);
259
#endif /* defined(PLATFORM_NAME) */
260
#if defined(PORT_CORE_VARIANT_NAME)
261
  _printSystemInfoLine(stream, "Core Variant", SYSTEM_INFO_NAMEWIDTH, "%s", PORT_CORE_VARIANT_NAME);
262
#endif /* defined(PORT_CORE_VARIANT_NAME) */
263
  _printSystemInfoLine(stream, "Architecture", SYSTEM_INFO_NAMEWIDTH, "%s", PORT_ARCHITECTURE_NAME);
264
  _printSystemInfoSeparator(stream, '-', SYSTEM_INFO_WIDTH);
265
#if (AMIROOS_CFG_SSSP_ENABLE == true)
266
  _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);
267
#else /* (AMIROOS_CFG_SSSP_ENABLE == true) */
268
  _printSystemInfoLine(stream, "AMiRo-OS" , SYSTEM_INFO_NAMEWIDTH, "%u.%u.%u %s", AMIROOS_VERSION_MAJOR, AMIROOS_VERSION_MINOR, AMIROOS_VERSION_PATCH, AMIROOS_RELEASE_TYPE);
269
#endif /* (AMIROOS_CFG_SSSP_ENABLE == true) */
270
  _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);
271
  _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");
272
  _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");
273
  _printSystemInfoLine(stream, "build type", SYSTEM_INFO_NAMEWIDTH,"%s", (AMIROOS_CFG_DBG == true) ? "debug" : "release");
274
  _printSystemInfoLine(stream, "Compiler" , SYSTEM_INFO_NAMEWIDTH, "%s %u.%u.%u", "GCC", __GNUC__, __GNUC_MINOR__, __GNUC_PATCHLEVEL__); // TODO: support other compilers than GCC
275
  _printSystemInfoLine(stream, "Compiled" , SYSTEM_INFO_NAMEWIDTH, "%s - %s", __DATE__, __TIME__);
276

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

    
306
  // print dynamic information about the module
307
  _printSystemInfoSeparator(stream, '-', SYSTEM_INFO_WIDTH);
308
#if (AMIROOS_CFG_SSSP_ENABLE == true)
309
  if (aos.sssp.moduleId != 0) {
310
    _printSystemInfoLine(stream, "Module ID", SYSTEM_INFO_NAMEWIDTH, "%u", aos.sssp.moduleId);
311
  } else {
312
    _printSystemInfoLine(stream, "Module ID", SYSTEM_INFO_NAMEWIDTH, "not available");
313
  }
314
#endif /* (AMIROOS_CFG_SSSP_ENABLE == true) */
315
#if (HAL_USE_RTC == TRUE)
316
  _printSystemInfoLine(stream, "Date", SYSTEM_INFO_NAMEWIDTH, "%04u-%02u-%02u (%s)",
317
                       dt.tm_year + 1900,
318
                       dt.tm_mon + 1,
319
                       dt.tm_mday,
320
                       (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");
321
  _printSystemInfoLine(stream, "Time", SYSTEM_INFO_NAMEWIDTH, "%02u:%02u:%02u", dt.tm_hour, dt.tm_min, dt.tm_sec);
322
#if (AMIROOS_CFG_SSSP_ENABLE == true) && (HAL_USE_CAN != TRUE)
323
#if (AMIROOS_CFG_SSSP_MASTER == true)
324
  _printSystemInfoLine(stream, "", SYSTEM_INFO_NAMEWIDTH, "Date & Time were not synchronized to slave modules.");
325
#else /* (AMIROOS_CFG_SSSP_MASTER == true) */
326
  _printSystemInfoLine(stream, "", SYSTEM_INFO_NAMEWIDTH, "Date & Time were not synchronized from master module.");
327
#endif /* (AMIROOS_CFG_SSSP_MASTER == true) */
328
#endif /* (AMIROOS_CFG_SSSP_ENABLE == true) && (HAL_USE_CAN != TRUE) */
329
#endif /* (HAL_USE_RTC == TRUE) */
330

    
331
  _printSystemInfoSeparator(stream, '=', SYSTEM_INFO_WIDTH);
332

    
333
  return;
334
}
335

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

    
352
  // local variables
353
  int retval = AOS_INVALIDARGUMENTS;
354

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

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

    
470
      retval = AOS_OK;
471
    }
472
#endif /* (HAL_USE_RTC == TRUE) */
473
  }
474

    
475
  // print help, if required
476
  if (retval == AOS_INVALIDARGUMENTS) {
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
#if (HAL_USE_RTC == TRUE)
489
    chprintf(stream, "  --date&time OPT VAL\n");
490
    chprintf(stream, "    Set the date/time value of OPT to VAL.\n");
491
    chprintf(stream, "    Possible OPTs are:\n");
492
    chprintf(stream, "      year\n");
493
    chprintf(stream, "      month\n");
494
    chprintf(stream, "      day\n");
495
    chprintf(stream, "      hour\n");
496
    chprintf(stream, "      minute\n");
497
    chprintf(stream, "      second\n");
498
#endif /* (HAL_USE_RTC == TRUE) */
499
  }
500

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

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

    
518
  (void)argc;
519
  (void)argv;
520

    
521
  // print system information
522
  _printSystemInfo(stream);
523

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

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

    
542
  // print shell info
543
  chprintf(stream, "System shell information:\n");
544
  chprintf(stream, "\tcommands available:     %u\n", aosShellCountCommands(&aos.shell));
545
  chprintf(stream, "\tline width:             %u characters\n", aos.shell.input.width);
546
  chprintf(stream, "\tmaximum arguments:      %u\n", aos.shell.arglistsize);
547
#if (AMIROOS_CFG_DBG == true)
548
  chprintf(stream, "\tthread stack size:      %u bytes\n", aosThdGetStacksize(aos.shell.thread));
549
#if (CH_DBG_FILL_THREADS == TRUE)
550
  chprintf(stream, "\tstack peak utilization: %u bytes (%.2f%%)\n", aosThdGetStackPeakUtilization(aos.shell.thread), (double)((float)(aosThdGetStackPeakUtilization(aos.shell.thread)) / (float)(aosThdGetStacksize(aos.shell.thread)) * 100.0f));
551
#endif /* (CH_DBG_FILL_THREADS == TRUE) */
552
#endif /* (AMIROOS_CFG_DBG == true) */
553
  _printSystemInfoSeparator(stream, '=', SYSTEM_INFO_WIDTH);
554

    
555
  return AOS_OK;
556
}
557

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

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

    
592
    return (argc != 2) ? AOS_INVALIDARGUMENTS : AOS_OK;
593
  }
594
  // handle argument
595
  else {
596
    if (strcmp(argv[1], "-h") == 0 || strcmp(argv[1], "--hibernate") == 0) {
597
      // broadcast shutdown event
598
      chEvtBroadcastFlags(&aos.events.os, AOS_SYSTEM_EVENTFLAGS_SHUTDOWN_HIBERNATE);
599
      // set terminate flag so no further prompt will be printed
600
      chThdTerminate(chThdGetSelfX());
601
      return AOS_OK;
602
    }
603
    else if (strcmp(argv[1], "-d") == 0 || strcmp(argv[1], "--deepsleep") == 0) {
604
      // broadcast shutdown event
605
      chEvtBroadcastFlags(&aos.events.os, AOS_SYSTEM_EVENTFLAGS_SHUTDOWN_DEEPSLEEP);
606
      // set terminate flag so no further prompt will be printed
607
      chThdTerminate(chThdGetSelfX());
608
      return AOS_OK;
609
    }
610
    else if (strcmp(argv[1], "-t") == 0 || strcmp(argv[1], "--transportation") == 0) {
611
      // broadcast shutdown event
612
      chEvtBroadcastFlags(&aos.events.os, AOS_SYSTEM_EVENTFLAGS_SHUTDOWN_TRANSPORTATION);
613
      // set terminate flag so no further prompt will be printed
614
      chThdTerminate(chThdGetSelfX());
615
      return AOS_OK;
616
    }
617
    else if (strcmp(argv[1], "-r") == 0 || strcmp(argv[1], "--restart") == 0) {
618
      // broadcast shutdown event
619
      chEvtBroadcastFlags(&aos.events.os, AOS_SYSTEM_EVENTFLAGS_SHUTDOWN_RESTART);
620
      // set terminate flag so no further prompt will be printed
621
      chThdTerminate(chThdGetSelfX());
622
      return AOS_OK;
623
    }
624
    else {
625
      chprintf(stream, "unknown argument %s\n", argv[1]);
626
      return AOS_INVALIDARGUMENTS;
627
    }
628
  }
629
#else /* (AMIROOS_CFG_SSSP_ENABLE == true) */
630
  (void)argv;
631
  (void)argc;
632

    
633
  chEvtBroadcastFlags(&aos.events.os, AOS_SYSTEM_EVENTFLAGS_SHUTDOWN_MASK);
634
  chThdTerminate(chThdGetSelfX());
635
  return AOS_OK;
636
#endif /* (AMIROOS_CFG_SSSP_ENABLE == true) */
637
}
638

    
639
#if (AMIROOS_CFG_TESTS_ENABLE == true) || defined(__DOXYGEN__)
640

    
641
/**
642
 * @brief   Callback function for the kernel:test shell command.
643
 *
644
 * @param[in] stream    The I/O stream to use.
645
 * @param[in] argc      Number of arguments.
646
 * @param[in] argv      List of pointers to the arguments.
647
 *
648
 * @return      An exit status.
649
 */
650
static int _shellcmd_kerneltestcb(BaseSequentialStream* stream, int argc, char* argv[])
651
{
652
  aosDbgCheck(stream != NULL);
653

    
654
  (void)argc;
655
  (void)argv;
656

    
657
  msg_t retval = test_execute(stream, &rt_test_suite);
658

    
659
  return retval;
660
}
661

    
662
#endif /* (AMIROOS_CFG_TESTS_ENABLE == true) */
663
#endif /* (AMIROOS_CFG_SHELL_ENABLE == true) */
664

    
665
// suppress warning in case no interrupt GPIOs are defined
666
#pragma GCC diagnostic push
667
#pragma GCC diagnostic ignored "-Wunused-function"
668
/**
669
 * @brief   Generic callback function for GPIO interrupts.
670
 *
671
 * @param[in] args   Pointer to the GPIO line identifier.
672
 */
673
static void _gpioCallback(void* args)
674
{
675
  aosDbgCheck((args != NULL) && (*((ioline_t*)args) != PAL_NOLINE) && (PAL_PAD(*((ioline_t*)args)) < sizeof(eventflags_t) * 8));
676

    
677
  chSysLockFromISR();
678
  chEvtBroadcastFlagsI(&aos.events.gpio, AOS_GPIOEVENT_FLAG(PAL_PAD(*((ioline_t*)args))));
679
  chSysUnlockFromISR();
680

    
681
  return;
682
}
683
#pragma GCC diagnostic pop
684

    
685
#if ((AMIROOS_CFG_SSSP_ENABLE == true) && (AMIROOS_CFG_SSSP_MASTER != true)) || defined(__DOXYGEN__)
686
/**
687
 * @brief   Callback function for the Sync signal interrupt.
688
 *
689
 * @param[in] args   Pointer to the GPIO line identifier.
690
 */
691
static void _signalSyncCallback(void *args)
692
{
693
  aosDbgCheck((args != NULL) && (*((ioline_t*)args) != PAL_NOLINE) && (PAL_PAD(*((ioline_t*)args)) < sizeof(eventflags_t) * 8));
694

    
695
  apalControlGpioState_t s_state;
696
  aos_timestamp_t uptime;
697

    
698
  chSysLockFromISR();
699
  // if the system is in operation phase
700
  if (aos.sssp.stage == AOS_SSSP_OPERATION) {
701
    // read signal S
702
    apalControlGpioGet(&moduleSsspGpioS, &s_state);
703
    // if S was toggled from on to off
704
    if (s_state == APAL_GPIO_OFF) {
705
      // get current uptime
706
      aosSysGetUptimeX(&uptime);
707
      // align the uptime with the synchronization period
708
      if (uptime % AMIROOS_CFG_SSSP_SYSSYNCPERIOD < AMIROOS_CFG_SSSP_SYSSYNCPERIOD / 2) {
709
        _uptime -= uptime % AMIROOS_CFG_SSSP_SYSSYNCPERIOD;
710
#if (AMIROOS_CFG_PROFILE == true)
711
        _syssyncskew = ((1.0f - SYSTEM_SYSSYNCSKEW_LPFACTOR) * _syssyncskew) + (SYSTEM_SYSSYNCSKEW_LPFACTOR * (uptime % AMIROOS_CFG_SSSP_SYSSYNCPERIOD));
712
#endif /* (AMIROOS_CFG_PROFILE == true) */
713
      } else {
714
        _uptime += AMIROOS_CFG_SSSP_SYSSYNCPERIOD - (uptime % AMIROOS_CFG_SSSP_SYSSYNCPERIOD);
715
#if (AMIROOS_CFG_PROFILE == true)
716
        _syssyncskew = ((1.0f - SYSTEM_SYSSYNCSKEW_LPFACTOR) * _syssyncskew) - (SYSTEM_SYSSYNCSKEW_LPFACTOR * (AMIROOS_CFG_SSSP_SYSSYNCPERIOD - (uptime % AMIROOS_CFG_SSSP_SYSSYNCPERIOD)));
717
#endif /* (AMIROOS_CFG_PROFILE == true) */
718
      }
719
    }
720
  }
721
  // broadcast event
722
  chEvtBroadcastFlagsI(&aos.events.gpio, AOS_GPIOEVENT_FLAG(PAL_PAD(*((ioline_t*)args))));
723
  chSysUnlockFromISR();
724

    
725
  return;
726
}
727
#endif /* (AMIROOS_CFG_SSSP_ENABLE == true) && (AMIROOS_CFG_SSSP_MASTER != true) */
728

    
729
/**
730
 * @brief   Callback function for the uptime accumulation timer.
731
 *
732
 * @param[in] par   Generic parameter.
733
 */
734
static void _uptimeCallback(void* par)
735
{
736
  (void)par;
737

    
738
  chSysLockFromISR();
739
  // read current time in system ticks
740
  register const systime_t st = chVTGetSystemTimeX();
741
  // update the uptime variables
742
  _uptime += chTimeI2US(chTimeDiffX(_synctime, st));
743
  _synctime = st;
744
  // enable the timer again
745
  chVTSetI(&_systimer, SYSTIMER_PERIOD, &_uptimeCallback, NULL);
746
  chSysUnlockFromISR();
747

    
748
  return;
749
}
750

    
751
#if ((AMIROOS_CFG_SSSP_ENABLE == true) && (AMIROOS_CFG_SSSP_MASTER == true)) || defined (__DOXYGEN__)
752
/**
753
 * @brief   Periodic system synchronization callback function.
754
 * @details Toggles the SYS_SYNC signal and reconfigures the system synchronization timer.
755
 *
756
 * @param[in] par   Unuesed parameters.
757
 */
758
static void _sysSyncTimerCallback(void* par)
759
{
760
  (void)par;
761

    
762
  apalControlGpioState_t s_state;
763
  aos_timestamp_t uptime;
764

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

    
783
  return;
784
}
785
#endif /* (AMIROOS_CFG_SSSP_ENABLE == true) && (AMIROOS_CFG_SSSP_MASTER == true) */
786

    
787
/******************************************************************************/
788
/* EXPORTED FUNCTIONS                                                         */
789
/******************************************************************************/
790

    
791
/**
792
 * @brief   AMiRo-OS system initialization.
793
 * @note    Must be called from the system control thread (usually main thread).
794
 *
795
 * @param[in] shellPrompt   String to be printed as prompt of the system shell.
796
 */
797
void aosSysInit(const char* shellPrompt)
798
{
799
  /* set control thread to maximum priority */
800
  chThdSetPriority(AOS_THD_CTRLPRIO);
801

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

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

    
832
  /* interrupt setup */
833
#if (AMIROOS_CFG_SSSP_ENABLE == true)
834
  // PD signal
835
  palSetLineCallback(moduleSsspGpioPD.gpio->line, _gpioCallback, &moduleSsspGpioPD.gpio->line);
836
  palEnableLineEvent(moduleSsspGpioPD.gpio->line, APAL2CH_EDGE(moduleSsspGpioPD.meta.edge));
837
  // SYNC signal
838
#if (AMIROOS_CFG_SSSP_MASTER == true)
839
  palSetLineCallback(moduleSsspGpioS.gpio->line, _gpioCallback, &moduleSsspGpioS.gpio->line);
840
#else /* (AMIROOS_CFG_SSSP_MASTER == true) */
841
  palSetLineCallback(moduleSsspGpioS.gpio->line, _signalSyncCallback, &moduleSsspGpioS.gpio->line);
842
#endif /* (AMIROOS_CFG_SSSP_MASTER == true) */
843
  palEnableLineEvent(moduleSsspGpioS.gpio->line, APAL2CH_EDGE(moduleSsspGpioS.meta.edge));
844
#if (AMIROOS_CFG_SSSP_STACK_START != true)
845
  // DN signal
846
  palSetLineCallback(moduleSsspGpioDN.gpio->line, _gpioCallback, &moduleSsspGpioDN.gpio->line);
847
  palEnableLineEvent(moduleSsspGpioDN.gpio->line, APAL2CH_EDGE(moduleSsspGpioDN.meta.edge));
848
#endif /* (AMIROOS_CFG_SSSP_STACK_START != true) */
849
#if (AMIROOS_CFG_SSSP_STACK_END != true)
850
  // UP signal
851
  palSetLineCallback(moduleSsspGpioUP.gpio->line, _gpioCallback, &moduleSsspGpioUP.gpio->line);
852
  palEnableLineEvent(moduleSsspGpioUP.gpio->line, APAL2CH_EDGE(moduleSsspGpioUP.meta.edge));
853
#endif /* (AMIROOS_CFG_SSSP_STACK_END != true) */
854
#endif /* (AMIROOS_CFG_SSSP_ENABLE == true) */
855

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

    
874
  return;
875
}
876

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

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

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

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

    
913
  return;
914
}
915

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

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

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

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

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

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

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

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

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

    
980
  return;
981
}
982

    
983
#if (HAL_USE_RTC == TRUE) || defined(__DOXYGEN__)
984

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

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

    
998
  return;
999
}
1000

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

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

    
1014
  return;
1015
}
1016

    
1017
#endif /* (HAL_USE_RTC == TRUE) */
1018

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

    
1030
#if (AMIROOS_CFG_SSSP_ENABLE == true)
1031
#if (AMIROOS_CFG_SSSP_MASTER == true)
1032
  // deactivate the system synchronization timer
1033
  chVTReset(&_syssynctimer);
1034
#endif /* (AMIROOS_CFG_SSSP_MASTER == true) */
1035

    
1036
  // update the system SSSP stage
1037
  aos.sssp.stage = AOS_SSSP_SHUTDOWN_1_1;
1038

    
1039
  chSysLock();
1040
  // activate the SYS_PD control signal only, if this module initiated the shutdown
1041
  if (shutdown != AOS_SHUTDOWN_PASSIVE) {
1042
    apalControlGpioSet(&moduleSsspGpioPD, APAL_GPIO_ON);
1043
  }
1044
  // activate the SYS_SYNC signal
1045
  apalControlGpioSet(&moduleSsspGpioS, APAL_GPIO_ON);
1046
  chSysUnlock();
1047
#endif /* (AMIROOS_CFG_SSSP_ENABLE == true) */
1048

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

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

    
1077
  return;
1078
}
1079

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

    
1089
  return;
1090
}
1091

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

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

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

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

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

    
1152
  return;
1153
}
1154

    
1155
/**
1156
 * @brief   Generic callback function for GPIO interrupts.
1157
 *
1158
 * @return  Pointer to the callback function.
1159
 */
1160
palcallback_t aosSysGetStdGpioCallback(void)
1161
{
1162
  return _gpioCallback;
1163
}
1164

    
1165
/** @} */