Statistics
| Branch: | Tag: | Revision:

amiro-os / core / src / aos_system.c @ 75c1f470

History | View | Annotate | Download (43.6 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) || (AMIROOS_CFG_TESTS_ENABLE == true) || defined(__DOXYGEN__)
88
static int _shellcmd_configcb(BaseSequentialStream* stream, int argc, char* argv[]);
89
static int _shellcmd_infocb(BaseSequentialStream* stream, int argc, char* argv[]);
90
static int _shellcmd_shutdowncb(BaseSequentialStream* stream, int argc, char* argv[]);
91
#if (AMIROOS_CFG_TESTS_ENABLE == true) || defined(__DOXYGEN__)
92
static int _shellcmd_kerneltestcb(BaseSequentialStream* stream, int argc, char* argv[]);
93
#endif /* (AMIROOS_CFG_TESTS_ENABLE == true) */
94
#endif /* (AMIROOS_CFG_SHELL_ENABLE == true) || (AMIROOS_CFG_TESTS_ENABLE == true) */
95

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
213
  return n+1;
214
}
215

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

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

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

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

    
250
  return n;
251
}
252

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

    
262
  // local variables
263
#if (HAL_USE_RTC == TRUE)
264
  struct tm dt;
265
  aosSysGetDateTime(&dt);
266
#endif /* (HAL_USE_RTC == TRUE) */
267

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

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

    
320
  // print dynamic information about the module
321
  _printSystemInfoSeparator(stream, '-', SYSTEM_INFO_WIDTH);
322
#if (AMIROOS_CFG_SSSP_ENABLE == true)
323
  if (aos.sssp.moduleId != 0) {
324
    _printSystemInfoLine(stream, "Module ID", SYSTEM_INFO_NAMEWIDTH, "%u", aos.sssp.moduleId);
325
  } else {
326
    _printSystemInfoLine(stream, "Module ID", SYSTEM_INFO_NAMEWIDTH, "not available");
327
  }
328
#endif /* (AMIROOS_CFG_SSSP_ENABLE == true) */
329
#if (HAL_USE_RTC == TRUE)
330
  _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",
331
                       dt.tm_mday,
332
                       dt.tm_mon + 1,
333
                       dt.tm_year + 1900);
334
  _printSystemInfoLine(stream, "Time", SYSTEM_INFO_NAMEWIDTH, "%02u:%02u:%02u", dt.tm_hour, dt.tm_min, dt.tm_sec);
335
#if (AMIROOS_CFG_SSSP_ENABLE == true) && (HAL_USE_CAN != TRUE)
336
#if (AMIROOS_CFG_SSSP_MASTER == true)
337
  _printSystemInfoLine(stream, "", SYSTEM_INFO_NAMEWIDTH, "Date & Time were not synchronized to slave modules.");
338
#else /* (AMIROOS_CFG_SSSP_MASTER == true) */
339
  _printSystemInfoLine(stream, "", SYSTEM_INFO_NAMEWIDTH, "Date & Time were not synchronized from master module.");
340
#endif /* (AMIROOS_CFG_SSSP_MASTER == true) */
341
#endif /* (AMIROOS_CFG_SSSP_ENABLE == true) && (HAL_USE_CAN != TRUE) */
342
#endif /* (HAL_USE_RTC == TRUE) */
343

    
344
  _printSystemInfoSeparator(stream, '=', SYSTEM_INFO_WIDTH);
345

    
346
  return;
347
}
348

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

    
365
  // local variables
366
  int retval = AOS_INVALID_ARGUMENTS;
367

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

    
477
      // read and print new date and time
478
      aosSysGetDateTime(&dt);
479
      chprintf(stream, "date/time set to %02u:%02u:%02u @ %02u-%02u-%04u\n",
480
               dt.tm_hour, dt.tm_min, dt.tm_sec,
481
               dt.tm_mday, dt.tm_mon+1, dt.tm_year+1900);
482

    
483
      retval = AOS_OK;
484
    }
485
#endif /* (HAL_USE_RTC == TRUE) */
486
  }
487

    
488
  // print help, if required
489
  if (retval == AOS_INVALID_ARGUMENTS) {
490
    chprintf(stream, "Usage: %s OPTION\n", argv[0]);
491
    chprintf(stream, "Options:\n");
492
    chprintf(stream, "  --help\n");
493
    chprintf(stream, "    Print this help text.\n");
494
    chprintf(stream, "  --shell [OPT [VAL]]\n");
495
    chprintf(stream, "    Set or retrieve shell configuration.\n");
496
    chprintf(stream, "    Possible OPTs and VALs are:\n");
497
    chprintf(stream, "      prompt text|minimal|uptime|date&time|notime\n");
498
    chprintf(stream, "        Configures the prompt.\n");
499
    chprintf(stream, "      match casesensitive|caseinsenitive\n");
500
    chprintf(stream, "        Configures string matching.\n");
501
#if (HAL_USE_RTC == TRUE)
502
    chprintf(stream, "  --date&time OPT VAL\n");
503
    chprintf(stream, "    Set the date/time value of OPT to VAL.\n");
504
    chprintf(stream, "    Possible OPTs are:\n");
505
    chprintf(stream, "      year\n");
506
    chprintf(stream, "      month\n");
507
    chprintf(stream, "      day\n");
508
    chprintf(stream, "      hour\n");
509
    chprintf(stream, "      minute\n");
510
    chprintf(stream, "      second\n");
511
#endif /* (HAL_USE_RTC == TRUE) */
512
  }
513

    
514
  return (argc > 1 && strcmp(argv[1], "--help") == 0) ? AOS_OK : retval;
515
}
516

    
517
/**
518
 * @brief   Callback function for the system:info shell command.
519
 *
520
 * @param[in] stream    The I/O stream to use.
521
 * @param[in] argc      Number of arguments.
522
 * @param[in] argv      List of pointers to the arguments.
523
 *
524
 * @return            An exit status.
525
 * @retval  AOS_OK    The command was executed successfully.
526
 */
527
static int _shellcmd_infocb(BaseSequentialStream* stream, int argc, char* argv[])
528
{
529
  aosDbgCheck(stream != NULL);
530

    
531
  (void)argc;
532
  (void)argv;
533

    
534
  // print system information
535
  _printSystemInfo(stream);
536

    
537
  // print time measurement precision
538
  chprintf(stream, "module time resolution: %uus\n", AOS_SYSTEM_TIME_RESOLUTION);
539

    
540
  // print system uptime
541
  aos_timestamp_t uptime;
542
  aosSysGetUptime(&uptime);
543
  chprintf(stream, "The system is running for\n");
544
  chprintf(stream, "%10u days\n", (uint32_t)(uptime / MICROSECONDS_PER_DAY));
545
  chprintf(stream, "%10u hours\n", (uint8_t)(uptime % MICROSECONDS_PER_DAY / MICROSECONDS_PER_HOUR));
546
  chprintf(stream, "%10u minutes\n", (uint8_t)(uptime % MICROSECONDS_PER_HOUR / MICROSECONDS_PER_MINUTE));
547
  chprintf(stream, "%10u seconds\n", (uint8_t)(uptime % MICROSECONDS_PER_MINUTE / MICROSECONDS_PER_SECOND));
548
  chprintf(stream, "%10u milliseconds\n", (uint16_t)(uptime % MICROSECONDS_PER_SECOND / MICROSECONDS_PER_MILLISECOND));
549
  chprintf(stream, "%10u microseconds\n", (uint16_t)(uptime % MICROSECONDS_PER_MILLISECOND / MICROSECONDS_PER_MICROSECOND));
550
#if (AMIROOS_CFG_SSSP_ENABLE == true) && (AMIROOS_CFG_SSSP_MASTER != true) && (AMIROOS_CFG_PROFILE == true)
551
  chprintf(stream, "SSSP synchronization offset: %.3fus per %uus\n", _syssyncskew, AMIROOS_CFG_SSSP_SYSSYNCPERIOD);
552
#endif /* (AMIROOS_CFG_SSSP_ENABLE == true) && (AMIROOS_CFG_SSSP_MASTER != true) && (AMIROOS_CFG_PROFILE == true) */
553
  _printSystemInfoSeparator(stream, '=', SYSTEM_INFO_WIDTH);
554

    
555
  // print shell info
556
  chprintf(stream, "System shell information:\n");
557
  chprintf(stream, "\tcommands available:     %u\n", aosShellCountCommands(&aos.shell));
558
  chprintf(stream, "\tline width:             %u characters\n", aos.shell.linesize);
559
  chprintf(stream, "\tmaximum arguments:      %u\n", aos.shell.arglistsize);
560
#if (AMIROOS_CFG_DBG == true)
561
  chprintf(stream, "\tthread stack size:      %u bytes\n", aosThdGetStacksize(aos.shell.thread));
562
#if (CH_DBG_FILL_THREADS == TRUE)
563
  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);
564
#endif /* (CH_DBG_FILL_THREADS == TRUE) */
565
#endif /* (AMIROOS_CFG_DBG == true) */
566
  _printSystemInfoSeparator(stream, '=', SYSTEM_INFO_WIDTH);
567

    
568
  return AOS_OK;
569
}
570

    
571
/**
572
 * @brief   Callback function for the sytem:shutdown shell command.
573
 *
574
 * @param[in] stream    The I/O stream to use.
575
 * @param[in] argc      Number of arguments.
576
 * @param[in] argv      List of pointers to the arguments.
577
 *
578
 * @return              An exit status.
579
 * @retval  AOS_OK                  The command was executed successfully.
580
 * @retval  AOS_INVALID_ARGUMENTS   There was an issue with the arguments.
581
 */
582
static int _shellcmd_shutdowncb(BaseSequentialStream* stream, int argc, char* argv[])
583
{
584
  aosDbgCheck(stream != NULL);
585

    
586
#if (AMIROOS_CFG_SSSP_ENABLE == true)
587
  // print help text
588
  if (argc != 2 || strcmp(argv[1], "--help") == 0) {
589
    chprintf(stream, "Usage: %s OPTION\n", argv[0]);
590
    chprintf(stream, "Options:\n");
591
    chprintf(stream, "  --help\n");
592
    chprintf(stream, "    Print this help text.\n");
593
    chprintf(stream, "  --hibernate, -h\n");
594
    chprintf(stream, "    Shutdown to hibernate mode.\n");
595
    chprintf(stream, "    Least energy saving, but allows charging via pins.\n");
596
    chprintf(stream, "  --deepsleep, -d\n");
597
    chprintf(stream, "    Shutdown to deepsleep mode.\n");
598
    chprintf(stream, "    Minimum energy consumption while allowing charging via plug.\n");
599
    chprintf(stream, "  --transportation, -t\n");
600
    chprintf(stream, "    Shutdown to transportation mode.\n");
601
    chprintf(stream, "    Minimum energy consumption with all interrupts disabled (no charging).\n");
602
    chprintf(stream, "  --restart, -r\n");
603
    chprintf(stream, "    Shutdown and restart system.\n");
604

    
605
    return (argc != 2) ? AOS_INVALID_ARGUMENTS : AOS_OK;
606
  }
607
  // handle argument
608
  else {
609
    if (strcmp(argv[1], "-h") == 0 || strcmp(argv[1], "--hibernate") == 0) {
610
      chEvtBroadcastFlags(&aos.events.os, AOS_SYSTEM_EVENTFLAGS_HIBERNATE);
611
      chThdTerminate(chThdGetSelfX());
612
      return AOS_OK;
613
    }
614
    else if (strcmp(argv[1], "-d") == 0 || strcmp(argv[1], "--deepsleep") == 0) {
615
      chEvtBroadcastFlags(&aos.events.os, AOS_SYSTEM_EVENTFLAGS_DEEPSLEEP);
616
      chThdTerminate(chThdGetSelfX());
617
      return AOS_OK;
618
    }
619
    else if (strcmp(argv[1], "-t") == 0 || strcmp(argv[1], "--transportation") == 0) {
620
      chEvtBroadcastFlags(&aos.events.os, AOS_SYSTEM_EVENTFLAGS_TRANSPORTATION);
621
      chThdTerminate(chThdGetSelfX());
622
      return AOS_OK;
623
    }
624
    else if (strcmp(argv[1], "-r") == 0 || strcmp(argv[1], "--restart") == 0) {
625
      chEvtBroadcastFlags(&aos.events.os, AOS_SYSTEM_EVENTFLAGS_RESTART);
626
      chThdTerminate(chThdGetSelfX());
627
      return AOS_OK;
628
    }
629
    else {
630
      chprintf(stream, "unknown argument %s\n", argv[1]);
631
      return AOS_INVALID_ARGUMENTS;
632
    }
633
  }
634
#else /* (AMIROOS_CFG_SSSP_ENABLE == true) */
635
  (void)argv;
636
  (void)argc;
637

    
638
  chEvtBroadcastFlags(&aos.events.os, AOS_SYSTEM_EVENTFLAGS_SHUTDOWN);
639
  chThdTerminate(chThdGetSelfX());
640
  return AOS_OK;
641
#endif /* (AMIROOS_CFG_SSSP_ENABLE == true) */
642
}
643

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

    
658
  (void)argc;
659
  (void)argv;
660

    
661
  msg_t retval = test_execute(stream, &rt_test_suite);
662

    
663
  return retval;
664
}
665
#endif /* (AMIROOS_CFG_TESTS_ENABLE == true) */
666
#endif /* (AMIROOS_CFG_SHELL_ENABLE == true) || (AMIROOS_CFG_TESTS_ENABLE == true) */
667

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

    
680
  chSysLockFromISR();
681
  chEvtBroadcastFlagsI(&aos.events.io, AOS_IOEVENT_FLAG(*((iopadid_t*)args)));
682
  chSysUnlockFromISR();
683

    
684
  return;
685
}
686
#pragma GCC diagnostic pop
687

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

    
698
  apalControlGpioState_t s_state;
699
  aos_timestamp_t uptime;
700

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

    
728
  return;
729
}
730
#endif /* (AMIROOS_CFG_SSSP_ENABLE == true) && (AMIROOS_CFG_SSSP_MASTER != true) */
731

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

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

    
751
  return;
752
}
753

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

    
765
  apalControlGpioState_t s_state;
766
  aos_timestamp_t uptime;
767

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

    
786
  return;
787
}
788
#endif /* (AMIROOS_CFG_SSSP_ENABLE == true) && (AMIROOS_CFG_SSSP_MASTER == true) */
789

    
790
/******************************************************************************/
791
/* EXPORTED FUNCTIONS                                                         */
792
/******************************************************************************/
793

    
794
/**
795
 * @brief   AMiRo-OS system initialization.
796
 * @note    Must be called from the system control thread (usually main thread).
797
 *
798
 * @param[in] shellPrompt   String to be printed as prompt of the system shell.
799
 */
800
#if (AMIROOS_CFG_SHELL_ENABLE == true) || (AMIROOS_CFG_TESTS_ENABLE == true) || defined(__DOXYGEN__)
801
void aosSysInit(const char* shellPrompt)
802
#else /* (AMIROOS_CFG_SHELL_ENABLE == true) || (AMIROOS_CFG_TESTS_ENABLE == true) */
803
void aosSysInit(void)
804
#endif /* (AMIROOS_CFG_SHELL_ENABLE == true) || (AMIROOS_CFG_TESTS_ENABLE == true) */
805
{
806
  /* set control thread to maximum priority */
807
  chThdSetPriority(AOS_THD_CTRLPRIO);
808

    
809
  /* set local variables */
810
  chVTObjectInit(&_systimer);
811
#if (AMIROOS_CFG_SSSP_ENABLE == true)
812
  _synctime = 0;
813
  _uptime = 0;
814
#if (AMIROOS_CFG_SSSP_MASTER == true)
815
  chVTObjectInit(&_syssynctimer);
816
  _syssynctime = 0;
817
#endif /* (AMIROOS_CFG_SSSP_MASTER == true) */
818
#if (AMIROOS_CFG_SSSP_MASTER != true) && (AMIROOS_CFG_PROFILE == true)
819
  _syssyncskew = 0.0f;
820
#endif /* (AMIROOS_CFG_SSSP_MASTER != true) && (AMIROOS_CFG_PROFILE == true) */
821
#else /* (AMIROOS_CFG_SSSP_ENABLE == true) */
822
  // start the uptime counter
823
  chSysLock();
824
  _synctime = chVTGetSystemTimeX();
825
  _uptime = 0;
826
  chVTSetI(&_systimer, SYSTIMER_PERIOD, &_uptimeCallback, NULL);
827
  chSysUnlock();
828
#endif /* (AMIROOS_CFG_SSSP_ENABLE == true) */
829

    
830
  /* initialize aos configuration */
831
#if (AMIROOS_CFG_SSSP_ENABLE == true)
832
  aos.sssp.stage = AOS_SSSP_STARTUP_2_1;
833
  aos.sssp.moduleId = 0;
834
#endif /* (AMIROOS_CFG_SSSP_ENABLE == true) */
835
  aosIOStreamInit(&aos.iostream);
836
  chEvtObjectInit(&aos.events.io);
837
  chEvtObjectInit(&aos.events.os);
838

    
839
  /* interrupt setup */
840
#if (AMIROOS_CFG_SSSP_ENABLE == true)
841
  // PD signal
842
  palSetPadCallback(moduleSsspGpioPd.gpio->port, moduleSsspGpioPd.gpio->pad, _intCallback, &moduleSsspGpioPd.gpio->pad);
843
  palEnablePadEvent(moduleSsspGpioPd.gpio->port, moduleSsspGpioPd.gpio->pad, APAL2CH_EDGE(moduleSsspGpioPd.meta.edge));
844
  // SYNC signal
845
#if (AMIROOS_CFG_SSSP_MASTER == true)
846
  palSetPadCallback(moduleSsspGpioSync.gpio->port, moduleSsspGpioSync.gpio->pad, _intCallback, &moduleSsspGpioSync.gpio->pad);
847
#else /* (AMIROOS_CFG_SSSP_MASTER == true) */
848
  palSetPadCallback(moduleSsspGpioSync.gpio->port, moduleSsspGpioSync.gpio->pad, _signalSyncCallback, &moduleSsspGpioSync.gpio->pad);
849
#endif /* (AMIROOS_CFG_SSSP_MASTER == true) */
850
  palEnablePadEvent(moduleSsspGpioSync.gpio->port, moduleSsspGpioSync.gpio->pad, APAL2CH_EDGE(moduleSsspGpioSync.meta.edge));
851
#if (AMIROOS_CFG_SSSP_STACK_START != true)
852
  // DN signal
853
  palSetPadCallback(moduleSsspGpioDn.gpio->port, moduleSsspGpioDn.gpio->pad, _intCallback, &moduleSsspGpioDn.gpio->pad);
854
  palEnablePadEvent(moduleSsspGpioDn.gpio->port, moduleSsspGpioDn.gpio->pad, APAL2CH_EDGE(moduleSsspGpioDn.meta.edge));
855
#endif /* (AMIROOS_CFG_SSSP_STACK_START != true) */
856
#if (AMIROOS_CFG_SSSP_STACK_END != true)
857
  // UP signal
858
  palSetPadCallback(moduleSsspGpioUp.gpio->port, moduleSsspGpioUp.gpio->pad, _intCallback, &moduleSsspGpioUp.gpio->pad);
859
  palEnablePadEvent(moduleSsspGpioUp.gpio->port, moduleSsspGpioUp.gpio->pad, APAL2CH_EDGE(moduleSsspGpioUp.meta.edge));
860
#endif /* (AMIROOS_CFG_SSSP_STACK_END != true) */
861
#endif /* (AMIROOS_CFG_SSSP_ENABLE == true) */
862
#if defined(MODULE_INIT_INTERRUPTS)
863
  // further interrupt signals
864
  MODULE_INIT_INTERRUPTS();
865
#endif /* defined(MODULE_INIT_INTERRUPTS) */
866

    
867
#if (AMIROOS_CFG_SHELL_ENABLE == true) || (AMIROOS_CFG_TESTS_ENABLE == true)
868
  /* init shell */
869
  aosShellInit(&aos.shell,
870
               &aos.events.os,
871
               shellPrompt,
872
               _shell_line,
873
               AMIROOS_CFG_SHELL_LINEWIDTH,
874
               _shell_arglist,
875
               AMIROOS_CFG_SHELL_MAXARGS);
876
  // add system commands
877
  aosShellAddCommand(&aos.shell, &_shellcmd_config);
878
  aosShellAddCommand(&aos.shell, &_shellcmd_info);
879
  aosShellAddCommand(&aos.shell, &_shellcmd_shutdown);
880
#if (AMIROOS_CFG_TESTS_ENABLE == true)
881
  aosShellAddCommand(&aos.shell, &_shellcmd_kerneltest);
882
#endif /* (AMIROOS_CFG_TESTS_ENABLE == true) */
883
#endif /* (AMIROOS_CFG_SHELL_ENABLE == true) || (AMIROOS_CFG_TESTS_ENABLE == true) */
884

    
885
  return;
886
}
887

    
888
/**
889
 * @brief   Starts the system and all system threads.
890
 */
891
inline void aosSysStart(void)
892
{
893
#if (AMIROOS_CFG_SSSP_ENABLE == true)
894
  // update the system SSSP stage
895
  aos.sssp.stage = AOS_SSSP_OPERATION;
896

    
897
#if (AMIROOS_CFG_SSSP_MASTER == true)
898
  {
899
    chSysLock();
900
    // start the system synchronization counter
901
    // The first iteration of the timer is set to the next 'center' of a 'slice'.
902
    aos_timestamp_t t;
903
    aosSysGetUptimeX(&t);
904
    t = AMIROOS_CFG_SSSP_SYSSYNCPERIOD - (t % AMIROOS_CFG_SSSP_SYSSYNCPERIOD);
905
    chVTSetI(&_syssynctimer, chTimeUS2I((t > (AMIROOS_CFG_SSSP_SYSSYNCPERIOD / 2)) ? (t - (AMIROOS_CFG_SSSP_SYSSYNCPERIOD / 2)) : (t + (AMIROOS_CFG_SSSP_SYSSYNCPERIOD / 2))), _sysSyncTimerCallback, NULL);
906
    chSysUnlock();
907
  }
908
#endif /* (AMIROOS_CFG_SSSP_MASTER == true) */
909
#endif /* (AMIROOS_CFG_SSSP_ENABLE == true) */
910

    
911
  // print system information;
912
  _printSystemInfo((BaseSequentialStream*)&aos.iostream);
913
  aosprintf("\n");
914

    
915
#if (AMIROOS_CFG_SHELL_ENABLE == true) || (AMIROOS_CFG_TESTS_ENABLE == true)
916
  // start system shell thread
917
#if (CH_CFG_USE_THREADHIERARCHY == TRUE)
918
  aos.shell.thread = chThdCreateStatic(_shell_wa, sizeof(_shell_wa), AMIROOS_CFG_SHELL_THREADPRIO, aosShellThread, &aos.shell, &ch.mainthread);
919
#else /* (CH_CFG_USE_THREADHIERARCHY == TRUE) */
920
  aos.shell.thread = chThdCreateStatic(_shell_wa, sizeof(_shell_wa), AMIROOS_CFG_SHELL_THREADPRIO, aosShellThread, &aos.shell);
921
#endif /* (CH_CFG_USE_THREADHIERARCHY == TRUE) */
922
#endif /* (AMIROOS_CFG_SHELL_ENABLE == true) || (AMIROOS_CFG_TESTS_ENABLE == true) */
923

    
924
  return;
925
}
926

    
927
#if (AMIROOS_CFG_SSSP_ENABLE == true) || defined(__DOXYGEN__)
928
/**
929
 * @brief   Implements the SSSP startup synchronization step.
930
 *
931
 * @param[in] syncEvtListener   Event listener that receives the Sync event.
932
 *
933
 * @return    If another event that the listener is interested in was received, its mask is returned.
934
 *            Otherwise an empty mask (0) is returned.
935
 */
936
eventmask_t aosSysSsspStartupOsInitSyncCheck(event_listener_t* syncEvtListener)
937
{
938
  aosDbgCheck(syncEvtListener != NULL);
939

    
940
  // local variables
941
  eventmask_t m;
942
  eventflags_t f;
943
  apalControlGpioState_t s;
944

    
945
  // update the system SSSP stage
946
  aos.sssp.stage = AOS_SSSP_STARTUP_2_2;
947

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

    
951
  // wait for any event to occur (do not apply any filter in order not to miss any event)
952
  m = chEvtWaitOne(ALL_EVENTS);
953
  f = chEvtGetAndClearFlags(syncEvtListener);
954
  apalControlGpioGet(&moduleSsspGpioSync, &s);
955

    
956
  // if the event was a system event,
957
  //   and it was fired because of the SysSync control signal,
958
  //   and the SysSync control signal has been deactivated
959
  if (m & syncEvtListener->events &&
960
      f == MODULE_SSSP_EVENTFLAGS_SYNC &&
961
      s == APAL_GPIO_OFF) {
962
    chSysLock();
963
    // start the uptime counter
964
    _synctime = chVTGetSystemTimeX();
965
    _uptime = 0;
966
    chVTSetI(&_systimer, SYSTIMER_PERIOD, &_uptimeCallback, NULL);
967
    chSysUnlock();
968

    
969
    return 0;
970
  }
971
  // an unexpected event occurred
972
  else {
973
    // reassign the flags to the event and return the event mask
974
    syncEvtListener->flags |= f;
975
    return m;
976
  }
977
}
978
#endif /* (AMIROOS_CFG_SSSP_ENABLE == true) */
979

    
980
/**
981
 * @brief   Retrieves the system uptime.
982
 *
983
 * @param[out] ut   The system uptime.
984
 */
985
inline void aosSysGetUptimeX(aos_timestamp_t* ut)
986
{
987
  aosDbgCheck(ut != NULL);
988

    
989
  *ut = _uptime + chTimeI2US(chTimeDiffX(_synctime, chVTGetSystemTimeX()));
990

    
991
  return;
992
}
993

    
994
#if (HAL_USE_RTC == TRUE) || defined(__DOXYGEN__)
995

    
996
/**
997
 * @brief   retrieves the date and time from the MCU clock.
998
 *
999
 * @param[out] td   The date and time.
1000
 */
1001
void aosSysGetDateTime(struct tm* dt)
1002
{
1003
  aosDbgCheck(dt != NULL);
1004

    
1005
  RTCDateTime rtc;
1006
  rtcGetTime(&MODULE_HAL_RTC, &rtc);
1007
  rtcConvertDateTimeToStructTm(&rtc, dt, NULL);
1008

    
1009
  return;
1010
}
1011

    
1012
/**
1013
 * @brief   set the date and time of the MCU clock.
1014
 *
1015
 * @param[in] dt    The date and time to set.
1016
 */
1017
void aosSysSetDateTime(struct tm* dt)
1018
{
1019
  aosDbgCheck(dt != NULL);
1020

    
1021
  RTCDateTime rtc;
1022
  rtcConvertStructTmToDateTime(dt, 0, &rtc);
1023
  rtcSetTime(&MODULE_HAL_RTC, &rtc);
1024

    
1025
  return;
1026
}
1027

    
1028
#endif /* (HAL_USE_RTC == TRUE) */
1029

    
1030
/**
1031
 * @brief   Initializes/Acknowledges a system shutdown/restart request.
1032
 * @note    This functions should be called from the thread with highest priority.
1033
 *
1034
 * @param[in] shutdown    Type of shutdown.
1035
 */
1036
void aosSysShutdownInit(aos_shutdown_t shutdown)
1037
{
1038
  // check arguments
1039
  aosDbgCheck(shutdown != AOS_SHUTDOWN_NONE);
1040

    
1041
#if (AMIROOS_CFG_SSSP_ENABLE == true)
1042
#if (AMIROOS_CFG_SSSP_MASTER == true)
1043
  // deactivate the system synchronization timer
1044
  chVTReset(&_syssynctimer);
1045
#endif /* (AMIROOS_CFG_SSSP_MASTER == true) */
1046

    
1047
  // update the system SSSP stage
1048
  aos.sssp.stage = AOS_SSSP_SHUTDOWN_1_1;
1049

    
1050
  chSysLock();
1051
  // activate the SYS_PD control signal only, if this module initiated the shutdown
1052
  if (shutdown != AOS_SHUTDOWN_PASSIVE) {
1053
    apalControlGpioSet(&moduleSsspGpioPd, APAL_GPIO_ON);
1054
  }
1055
  // activate the SYS_SYNC signal
1056
  apalControlGpioSet(&moduleSsspGpioSync, APAL_GPIO_ON);
1057
  chSysUnlock();
1058
#endif /* (AMIROOS_CFG_SSSP_ENABLE == true) */
1059

    
1060
  switch (shutdown) {
1061
    case AOS_SHUTDOWN_PASSIVE:
1062
      chEvtBroadcastFlags(&aos.events.os, AOS_SYSTEM_EVENTFLAGS_SHUTDOWN);
1063
      aosprintf("shutdown request received...\n");
1064
      break;
1065
    case AOS_SHUTDOWN_HIBERNATE:
1066
      chEvtBroadcastFlags(&aos.events.os, AOS_SYSTEM_EVENTFLAGS_HIBERNATE);
1067
      aosprintf("shutdown to hibernate mode...\n");
1068
      break;
1069
    case AOS_SHUTDOWN_DEEPSLEEP:
1070
      chEvtBroadcastFlags(&aos.events.os, AOS_SYSTEM_EVENTFLAGS_DEEPSLEEP);
1071
      aosprintf("shutdown to deepsleep mode...\n");
1072
      break;
1073
    case AOS_SHUTDOWN_TRANSPORTATION:
1074
      chEvtBroadcastFlags(&aos.events.os, AOS_SYSTEM_EVENTFLAGS_TRANSPORTATION);
1075
      aosprintf("shutdown to transportation mode...\n");
1076
      break;
1077
    case AOS_SHUTDOWN_RESTART:
1078
      chEvtBroadcastFlags(&aos.events.os, AOS_SYSTEM_EVENTFLAGS_RESTART);
1079
      aosprintf("restarting system...\n");
1080
      break;
1081
    // must never occur
1082
    case AOS_SHUTDOWN_NONE:
1083
    default:
1084
      break;
1085
  }
1086

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

    
1092
  return;
1093
}
1094

    
1095
/**
1096
 * @brief   Stops the system and all related threads (not the thread this function is called from).
1097
 */
1098
void aosSysStop(void)
1099
{
1100
#if (AMIROOS_CFG_SHELL_ENABLE == true) || (AMIROOS_CFG_TESTS_ENABLE == true)
1101
  chThdWait(aos.shell.thread);
1102
#endif /* (AMIROOS_CFG_SHELL_ENABLE == true) || (AMIROOS_CFG_TESTS_ENABLE == true) */
1103

    
1104
  return;
1105
}
1106

    
1107
/**
1108
 * @brief   Deinitialize all system variables.
1109
 */
1110
void aosSysDeinit(void)
1111
{
1112
  return;
1113
}
1114

    
1115
/**
1116
 * @brief   Finally shuts down the system and calls the bootloader callback function.
1117
 * @note    This function should be called from the thtead with highest priority.
1118
 *
1119
 * @param[in] shutdown    Type of shutdown.
1120
 */
1121
void aosSysShutdownFinal(aos_shutdown_t shutdown)
1122
{
1123
  // check arguments
1124
  aosDbgCheck(shutdown != AOS_SHUTDOWN_NONE);
1125

    
1126
  // disable all interrupts
1127
  irqDeinit();
1128

    
1129
#if (AMIROOS_CFG_SSSP_ENABLE == true)
1130
  // update the system SSSP stage
1131
  aos.sssp.stage = AOS_SSSP_SHUTDOWN_1_3;
1132
#endif /* (AMIROOS_CFG_SSSP_ENABLE == true) */
1133

    
1134
  // validate bootloader
1135
  if ((BL_CALLBACK_TABLE_ADDRESS->magicNumber == BL_MAGIC_NUMBER) &&
1136
      (BL_CALLBACK_TABLE_ADDRESS->vBootloader.major == BL_VERSION_MAJOR) &&
1137
      (BL_CALLBACK_TABLE_ADDRESS->vBootloader.minor >= BL_VERSION_MINOR)) {
1138
    // call bootloader callback depending on arguments
1139
    switch (shutdown) {
1140
      case AOS_SHUTDOWN_PASSIVE:
1141
        BL_CALLBACK_TABLE_ADDRESS->cbHandleShutdownRequest();
1142
        break;
1143
      case AOS_SHUTDOWN_HIBERNATE:
1144
        BL_CALLBACK_TABLE_ADDRESS->cbShutdownHibernate();
1145
        break;
1146
      case AOS_SHUTDOWN_DEEPSLEEP:
1147
        BL_CALLBACK_TABLE_ADDRESS->cbShutdownDeepsleep();
1148
        break;
1149
      case AOS_SHUTDOWN_TRANSPORTATION:
1150
        BL_CALLBACK_TABLE_ADDRESS->cbShutdownTransportation();
1151
        break;
1152
      case AOS_SHUTDOWN_RESTART:
1153
        BL_CALLBACK_TABLE_ADDRESS->cbShutdownRestart();
1154
        break;
1155
      // must never occur
1156
      case AOS_SHUTDOWN_NONE:
1157
      default:
1158
        break;
1159
    }
1160
  } else {
1161
    // fallback if bootloader was found to be invalid
1162
    aosprintf("Bootloader incompatible or not available!\n");
1163
    aosThdMSleep(10);
1164
    chSysDisable();
1165
  }
1166

    
1167
  return;
1168
}
1169

    
1170
/** @} */