Statistics
| Branch: | Tag: | Revision:

amiro-os / core / src / aos_system.c @ 5c9e9b9d

History | View | Annotate | Download (39.4 KB)

1
/*
2
AMiRo-OS is an operating system designed for the Autonomous Mini Robot (AMiRo) platform.
3
Copyright (C) 2016..2019  Thomas Schöpping et al.
4

5
This program is free software: you can redistribute it and/or modify
6
it under the terms of the GNU General Public License as published by
7
the Free Software Foundation, either version 3 of the License, or
8
(at your option) any later version.
9

10
This program is distributed in the hope that it will be useful,
11
but WITHOUT ANY WARRANTY; without even the implied warranty of
12
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13
GNU General Public License for more details.
14

15
You should have received a copy of the GNU General Public License
16
along with this program.  If not, see <http://www.gnu.org/licenses/>.
17
*/
18

    
19
/**
20
 * @file    aos_system.c
21
 * @brief   System code.
22
 * @details Contains system initialization and shutdown routines
23
 *          and system shell commands.
24
 *
25
 * @addtogroup aos_system
26
 * @{
27
 */
28

    
29
#include <aos_system.h>
30

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
189
  return n+1;
190
}
191

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

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

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

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

    
226
  return n;
227
}
228

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

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

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

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

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

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

    
315
  return;
316
}
317

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

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

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

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

    
451
      retval = AOS_OK;
452
    }
453
  }
454

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

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

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

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

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

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

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

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

    
535
  return AOS_OK;
536
}
537

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

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

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

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

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

    
625
  (void)argc;
626
  (void)argv;
627

    
628
  msg_t retval = test_execute(stream, &rt_test_suite);
629

    
630
  return retval;
631
}
632
#endif /* AMIROOS_CFG_TESTS_ENABLE == true */
633
#endif /* AMIROOS_CFG_SHELL_ENABLE == true */
634

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

    
647
  chSysLockFromISR();
648
  chEvtBroadcastFlagsI(&aos.events.io, (eventflags_t)1 << *((iopadid_t*)args));
649
  chSysUnlockFromISR();
650

    
651
  return;
652
}
653
#pragma GCC diagnostic pop
654

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

    
665
  apalControlGpioState_t s_state;
666
  aos_timestamp_t uptime;
667

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

    
695
  return;
696
}
697
#endif /* (AMIROOS_CFG_SSSP_ENABLE == true) && (AMIROOS_CFG_SSSP_MASTER != true) */
698

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

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

    
718
  return;
719
}
720

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

    
732
  apalControlGpioState_t s_state;
733
  aos_timestamp_t uptime;
734

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

    
753
  return;
754
}
755
#endif /* (AMIROOS_CFG_SSSP_ENABLE == true) && (AMIROOS_CFG_SSSP_MASTER == true) */
756

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

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

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

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

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

    
848
  return;
849
}
850

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

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

    
874
  // print system information;
875
  _printSystemInfo((BaseSequentialStream*)&aos.iostream);
876
  aosprintf("\n");
877

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

    
887
  return;
888
}
889

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

    
903
  // local variables
904
  eventmask_t m;
905
  eventflags_t f;
906
  apalControlGpioState_t s;
907

    
908
  // update the system SSSP stage
909
  aos.sssp.stage = AOS_SSSP_STARTUP_2_2;
910

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

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

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

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

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

    
952
  *ut = _uptime + chTimeI2US(chTimeDiffX(_synctime, chVTGetSystemTimeX()));
953

    
954
  return;
955
}
956

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

    
966
  RTCDateTime rtc;
967
  rtcGetTime(&MODULE_HAL_RTC, &rtc);
968
  rtcConvertDateTimeToStructTm(&rtc, dt, NULL);
969

    
970
  return;
971
}
972

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

    
982
  RTCDateTime rtc;
983
  rtcConvertStructTmToDateTime(dt, 0, &rtc);
984
  rtcSetTime(&MODULE_HAL_RTC, &rtc);
985

    
986
  return;
987
}
988

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

    
1000
#if (AMIROOS_CFG_SSSP_ENABLE == true)
1001
#if (AMIROOS_CFG_SSSP_MASTER == true)
1002
  // deactivate the system synchronization timer
1003
  chVTReset(&_syssynctimer);
1004
#endif
1005

    
1006
  // update the system SSSP stage
1007
  aos.sssp.stage = AOS_SSSP_SHUTDOWN_1_1;
1008

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

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

    
1046
#if (AMIROOS_CFG_SSSP_ENABLE == true)
1047
  // update the system SSSP stage
1048
  aos.sssp.stage = AOS_SSSP_SHUTDOWN_1_2;
1049
#endif
1050

    
1051
  return;
1052
}
1053

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

    
1063
  return;
1064
}
1065

    
1066
/**
1067
 * @brief   Deinitialize all system variables.
1068
 */
1069
void aosSysDeinit(void)
1070
{
1071
  return;
1072
}
1073

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

    
1085
  // disable all interrupts
1086
  irqDeinit();
1087

    
1088
#if (AMIROOS_CFG_SSSP_ENABLE == true)
1089
  // update the system SSSP stage
1090
  aos.sssp.stage = AOS_SSSP_SHUTDOWN_1_3;
1091
#endif
1092

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

    
1125
  return;
1126
}
1127

    
1128
/** @} */