Statistics
| Branch: | Tag: | Revision:

amiro-os / os / core / src / aos_system.c @ 0128be0f

History | View | Annotate | Download (34.521 KB)

1
/*
2
AMiRo-OS is an operating system designed for the Autonomous Mini Robot (AMiRo) platform.
3
Copyright (C) 2016..2018  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
#include <aos_system.h>
20

    
21
#include <amiroos.h>
22
#include <amiroblt.h>
23
#include <module.h>
24
#include <string.h>
25
#include <stdlib.h>
26
#if (AMIROOS_CFG_TESTS_ENABLE == true)
27
#include <ch_test.h>
28
#include <rt_test_root.h>
29
#endif
30

    
31
/**
32
 * @brief   Period of the system timer.
33
 */
34
#define SYSTIMER_PERIOD               (TIME_MAX_INTERVAL - CH_CFG_ST_TIMEDELTA)
35

    
36
/**
37
 * @brief   Width of the printable system info text.
38
 */
39
#define SYSTEM_INFO_WIDTH             70
40

    
41
/**
42
 * @brief   Width of the name column of the system info table.
43
 */
44
#define SYSTEM_INFO_NAMEWIDTH         14
45

    
46
/* forward declarations */
47
static void _printSystemInfo(BaseSequentialStream* stream);
48
#if (AMIROOS_CFG_SHELL_ENABLE == true)
49
static int _shellcmd_configcb(BaseSequentialStream* stream, int argc, char* argv[]);
50
static int _shellcmd_infocb(BaseSequentialStream* stream, int argc, char* argv[]);
51
static int _shellcmd_shutdowncb(BaseSequentialStream* stream, int argc, char* argv[]);
52
#endif /* AMIROOS_CFG_SHELL_ENABLE == true */
53
#if (AMIROOS_CFG_TESTS_ENABLE == true)
54
static int _shellcmd_kerneltestcb(BaseSequentialStream* stream, int argc, char* argv[]);
55
#endif /* AMIROOS_CFG_TESTS_ENABLE == true */
56

    
57
/**
58
 * @brief   Timer to accumulate system uptime.
59
 */
60
static virtual_timer_t _systimer;
61

    
62
/**
63
 * @brief   Accumulated system uptime.
64
 */
65
static aos_timestamp_t _uptime;
66

    
67
/**
68
 * @brief   Timer register value of last accumulation.
69
 */
70
static systime_t _synctime;
71

    
72
#if (AMIROOS_CFG_SSSP_MASTER == true) || defined(__DOXYGEN__)
73
/**
74
 * @brief   Timer to drive the SYS_SYNC signal for system wide time synchronization according to SSSP.
75
 */
76
static virtual_timer_t _syssynctimer;
77

    
78
/**
79
 * @brief   Last uptime of system wide time synchronization.
80
 */
81
static aos_timestamp_t _syssynctime;
82
#endif
83

    
84
#if ((AMIROOS_CFG_SSSP_MASTER != true) && (AMIROOS_CFG_PROFILE == true)) || defined(__DOXYGEN__)
85
/**
86
 * @brief   Offset between local clock and system wide synchronization signal.
87
 */
88
static float _syssyncskew;
89

    
90
/**
91
 * @brief   Weighting factor for the low-pass filter used for calculating the @p _syssyncskew value.
92
 */
93
#define SYSTEM_SYSSYNCSKEW_LPFACTOR   (0.1f / AOS_SYSTEM_TIME_RESOLUTION)
94
#endif
95

    
96
#if (AMIROOS_CFG_SHELL_ENABLE == true) || defined(__DOXYGEN__)
97
/**
98
 * @brief   Shell thread working area.
99
 */
100
THD_WORKING_AREA(_shell_wa, AMIROOS_CFG_SHELL_STACKSIZE);
101

    
102
/**
103
 * @brief   Shell input buffer.
104
 */
105
static char _shell_line[AMIROOS_CFG_SHELL_LINEWIDTH];
106

    
107
/**
108
 * @brief   Shell argument buffer.
109
 */
110
static char* _shell_arglist[AMIROOS_CFG_SHELL_MAXARGS];
111

    
112
/**
113
 * @brief   Shell command to retrieve system information.
114
 */
115
static aos_shellcommand_t _shellcmd_info = {
116
  /* name     */ "module:info",
117
  /* callback */ _shellcmd_infocb,
118
  /* next     */ NULL,
119
};
120

    
121
/**
122
 * @brief   Shell command to set or retrieve system configuration.
123
 */
124
static aos_shellcommand_t _shellcmd_config = {
125
  /* name     */ "module:config",
126
  /* callback */ _shellcmd_configcb,
127
  /* next     */ NULL,
128
};
129

    
130
/**
131
 * @brief   Shell command to shutdown the system.
132
 */
133
static aos_shellcommand_t _shellcmd_shutdown = {
134
  /* name     */ "system:shutdown",
135
  /* callback */ _shellcmd_shutdowncb,
136
  /* next     */ NULL,
137
};
138
#endif /* AMIROOS_CFG_SHELL_ENABLE == true */
139

    
140
#if (AMIROOS_CFG_TESTS_ENABLE == true) || defined(__DOXYGEN__)
141
/**
142
 * @brief   Shell kommand to run a test of the ChibiOS/RT kernel.
143
 */
144
static aos_shellcommand_t _shellcmd_kerneltest = {
145
  /* name     */ "kernel:test",
146
  /* callback */ _shellcmd_kerneltestcb,
147
  /* next     */ NULL,
148
};
149
#endif /* AMIROOS_CFG_TESTS_ENABLE == true */
150

    
151
/**
152
 * @brief   Global system object.
153
 */
154
aos_system_t aos;
155

    
156
/**
157
 * @brief   Print a separator line.
158
 *
159
 * @param[in] stream    Stream to print to or NULL to print to all system streams.
160
 * @param[in] c         Character to use.
161
 * @param[in] n         Length of the separator line.
162
 *
163
 * @return  Number of characters printed.
164
 */
165
static unsigned int _printSystemInfoSeparator(BaseSequentialStream* stream, const char c, const unsigned int n)
166
{
167
  aosDbgCheck(stream != NULL);
168

    
169
  // print the specified character n times
170
  for (unsigned int i = 0; i < n; ++i) {
171
    streamPut(stream, c);
172
  }
173
  streamPut(stream, '\n');
174

    
175
  return n+1;
176
}
177

    
178
/**
179
 * @brief   Print a system information line.
180
 * @details Prints a system information line with the following format:
181
 *            "<name>[spaces]fmt"
182
 *          The combined width of "<name>[spaces]" can be specified in order to align <fmt> on multiple lines.
183
 *          Note that there is not trailing newline added implicitely.
184
 *
185
 * @param[in] stream      Stream to print to or NULL to print to all system streams.
186
 * @param[in] name        Name of the entry/line.
187
 * @param[in] namewidth   Width of the name column.
188
 * @param[in] fmt         Formatted string of information content.
189
 *
190
 * @return  Number of characters printed.
191
 */
192
static unsigned int _printSystemInfoLine(BaseSequentialStream* stream, const char* name, const unsigned int namewidth, const char* fmt, ...)
193
{
194
  aosDbgCheck(stream != NULL);
195
  aosDbgCheck(name != NULL);
196

    
197
  unsigned int n = 0;
198
  va_list ap;
199

    
200
  va_start(ap, fmt);
201
  n += chprintf(stream, name);
202
  while (n < namewidth) {
203
    streamPut(stream, ' ');
204
    ++n;
205
  }
206
  n += chvprintf(stream, fmt, ap);
207
  va_end(ap);
208

    
209
  streamPut(stream, '\n');
210
  ++n;
211

    
212
  return n;
213
}
214

    
215
/**
216
 * @brief   Prints information about the system.
217
 *
218
 * @param[in] stream    Stream to print to.
219
 */
220
static void _printSystemInfo(BaseSequentialStream* stream)
221
{
222
  aosDbgCheck(stream != NULL);
223

    
224
  // local variables
225
  struct tm dt;
226
  aosSysGetDateTime(&dt);
227

    
228
  // print static information about module and operating system
229
  _printSystemInfoSeparator(stream, '=', SYSTEM_INFO_WIDTH);
230
  _printSystemInfoLine(stream, "Module", SYSTEM_INFO_NAMEWIDTH, "%s (v%s)", BOARD_NAME, BOARD_VERSION);
231
#ifdef PLATFORM_NAME
232
  _printSystemInfoLine(stream, "Platform", SYSTEM_INFO_NAMEWIDTH, "%s", PLATFORM_NAME);
233
#endif
234
#ifdef PORT_CORE_VARIANT_NAME
235
  _printSystemInfoLine(stream, "Core Variant", SYSTEM_INFO_NAMEWIDTH, "%s", PORT_CORE_VARIANT_NAME);
236
#endif
237
  _printSystemInfoLine(stream, "Architecture", SYSTEM_INFO_NAMEWIDTH, "%s", PORT_ARCHITECTURE_NAME);
238
  _printSystemInfoSeparator(stream, '-', SYSTEM_INFO_WIDTH);
239
  _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);
240
  _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);
241
  _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");
242
  _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");
243
  _printSystemInfoLine(stream, "build type", SYSTEM_INFO_NAMEWIDTH,"%s", (AMIROOS_CFG_DBG == true) ? "debug" : "release");
244
  _printSystemInfoLine(stream, "Compiler" , SYSTEM_INFO_NAMEWIDTH, "%s %u.%u.%u", "GCC", __GNUC__, __GNUC_MINOR__, __GNUC_PATCHLEVEL__); // TODO: support other compilers than GCC
245
  _printSystemInfoLine(stream, "Compiled" , SYSTEM_INFO_NAMEWIDTH, "%s - %s", __DATE__, __TIME__);
246

    
247
  // print static information about the bootloader
248
  _printSystemInfoSeparator(stream, '-', SYSTEM_INFO_WIDTH);
249
  if (BL_CALLBACK_TABLE_ADDRESS->magicNumber == BL_MAGIC_NUMBER) {
250
    _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,
251
                         (BL_CALLBACK_TABLE_ADDRESS->vBootloader.identifier == BL_VERSION_ID_AMiRoBLT_Release) ? "stable" :
252
                         (BL_CALLBACK_TABLE_ADDRESS->vBootloader.identifier == BL_VERSION_ID_AMiRoBLT_ReleaseCandidate) ? "release candidate" :
253
                         (BL_CALLBACK_TABLE_ADDRESS->vBootloader.identifier == BL_VERSION_ID_AMiRoBLT_Beta) ? "beta" :
254
                         (BL_CALLBACK_TABLE_ADDRESS->vBootloader.identifier == BL_VERSION_ID_AMiRoBLT_Alpha) ? "alpha" :
255
                         (BL_CALLBACK_TABLE_ADDRESS->vBootloader.identifier == BL_VERSION_ID_AMiRoBLT_PreAlpha) ? "pre-alpha" :
256
                         "<release type unknown>",
257
                         BL_CALLBACK_TABLE_ADDRESS->vSSSP.major, BL_CALLBACK_TABLE_ADDRESS->vSSSP.minor);
258
    if (BL_CALLBACK_TABLE_ADDRESS->vSSSP.major != AOS_SYSTEM_SSSP_VERSION_MAJOR) {
259
      if (stream) {
260
        chprintf(stream, "WARNING: Bootloader and AMiRo-OS implement incompatible SSSP versions!\n");
261
      } else {
262
        aosprintf("WARNING: Bootloader and AMiRo-OS implement incompatible SSSP versions!\n");
263
      }
264
    }
265
    _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
266
  } else {
267
    if (stream) {
268
      chprintf(stream, "Bootloader incompatible or not available.\n");
269
    } else {
270
      aosprintf("Bootloader incompatible or not available.\n");
271
    }
272
  }
273

    
274
  // print dynamic information about the module
275
  _printSystemInfoSeparator(stream, '-', SYSTEM_INFO_WIDTH);
276
  if (aos.sssp.moduleId != 0) {
277
    _printSystemInfoLine(stream, "Module ID", SYSTEM_INFO_NAMEWIDTH, "%u", aos.sssp.moduleId);
278
  } else {
279
    _printSystemInfoLine(stream, "Module ID", SYSTEM_INFO_NAMEWIDTH, "not available");
280
  }
281
  _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",
282
                       dt.tm_mday,
283
                       dt.tm_mon + 1,
284
                       dt.tm_year + 1900);
285
  _printSystemInfoLine(stream, "Time", SYSTEM_INFO_NAMEWIDTH, "%02u:%02u:%02u", dt.tm_hour, dt.tm_min, dt.tm_sec);
286

    
287
  _printSystemInfoSeparator(stream, '=', SYSTEM_INFO_WIDTH);
288

    
289
  return;
290
}
291

    
292
#if (AMIROOS_CFG_SHELL_ENABLE == true) || defined(__DOXYGEN__)
293
/**
294
 * @brief   Callback function for the system:config shell command.
295
 *
296
 * @param[in] stream    The I/O stream to use.
297
 * @param[in] argc      Number of arguments.
298
 * @param[in] argv      List of pointers to the arguments.
299
 *
300
 * @return              An exit status.
301
 * @retval  AOS_OK                  The command was executed successfuly.
302
 * @retval  AOS_INVALID_ARGUMENTS   There was an issue with the arguemnts.
303
 */
304
static int _shellcmd_configcb(BaseSequentialStream* stream, int argc, char* argv[])
305
{
306
  aosDbgCheck(stream != NULL);
307

    
308
  // local variables
309
  int retval = AOS_INVALID_ARGUMENTS;
310

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

    
419
      // read and print new date and time
420
      aosSysGetDateTime(&dt);
421
      chprintf(stream, "date/time set to %02u:%02u:%02u @ %02u-%02u-%04u\n",
422
               dt.tm_hour, dt.tm_min, dt.tm_sec,
423
               dt.tm_mday, dt.tm_mon+1, dt.tm_year+1900);
424

    
425
      retval = AOS_OK;
426
    }
427
  }
428

    
429
  // print help, if required
430
  if (retval == AOS_INVALID_ARGUMENTS) {
431
    chprintf(stream, "Usage: %s OPTION\n", argv[0]);
432
    chprintf(stream, "Options:\n");
433
    chprintf(stream, "  --help\n");
434
    chprintf(stream, "    Print this help text.\n");
435
    chprintf(stream, "  --shell [OPT [VAL]]\n");
436
    chprintf(stream, "    Set or retrieve shell configuration.\n");
437
    chprintf(stream, "    Possible OPTs and VALs are:\n");
438
    chprintf(stream, "      prompt text|minimal|uptime|date&time|notime\n");
439
    chprintf(stream, "        Configures the prompt.\n");
440
    chprintf(stream, "      match casesensitive|caseinsenitive\n");
441
    chprintf(stream, "        Configures string matching.\n");
442
    chprintf(stream, "  --date&time OPT VAL\n");
443
    chprintf(stream, "    Set the date/time value of OPT to VAL.\n");
444
    chprintf(stream, "    Possible OPTs are:\n");
445
    chprintf(stream, "      year\n");
446
    chprintf(stream, "      month\n");
447
    chprintf(stream, "      day\n");
448
    chprintf(stream, "      hour\n");
449
    chprintf(stream, "      minute\n");
450
    chprintf(stream, "      second\n");
451
  }
452

    
453
  return (argc > 1 && strcmp(argv[1], "--help") == 0) ? AOS_OK : retval;
454
}
455

    
456
/**
457
 * @brief   Callback function for the system:info shell command.
458
 *
459
 * @param[in] stream    The I/O stream to use.
460
 * @param[in] argc      Number of arguments.
461
 * @param[in] argv      List of pointers to the arguments.
462
 *
463
 * @return            An exit status.
464
 * @retval  AOS_OK    The command was executed successfully.
465
 */
466
static int _shellcmd_infocb(BaseSequentialStream* stream, int argc, char* argv[])
467
{
468
  aosDbgCheck(stream != NULL);
469

    
470
  (void)argc;
471
  (void)argv;
472

    
473
  // print system information
474
  _printSystemInfo(stream);
475

    
476
  // print time measurement precision
477
  chprintf(stream, "module time resolution: %uus\n", AOS_SYSTEM_TIME_RESOLUTION);
478

    
479
  // print system uptime
480
  aos_timestamp_t uptime;
481
  aosSysGetUptime(&uptime);
482
  chprintf(stream, "The system is running for\n");
483
  chprintf(stream, "%10u days\n", (uint32_t)(uptime / MICROSECONDS_PER_DAY));
484
  chprintf(stream, "%10u hours\n", (uint8_t)(uptime % MICROSECONDS_PER_DAY / MICROSECONDS_PER_HOUR));
485
  chprintf(stream, "%10u minutes\n", (uint8_t)(uptime % MICROSECONDS_PER_HOUR / MICROSECONDS_PER_MINUTE));
486
  chprintf(stream, "%10u seconds\n", (uint8_t)(uptime % MICROSECONDS_PER_MINUTE / MICROSECONDS_PER_SECOND));
487
  chprintf(stream, "%10u milliseconds\n", (uint16_t)(uptime % MICROSECONDS_PER_SECOND / MICROSECONDS_PER_MILLISECOND));
488
  chprintf(stream, "%10u microseconds\n", (uint16_t)(uptime % MICROSECONDS_PER_MILLISECOND / MICROSECONDS_PER_MICROSECOND));
489
#if (AMIROOS_CFG_SSSP_MASTER != true) && (AMIROOS_CFG_PROFILE == true)
490
  chprintf(stream, "SSSP synchronization offset: %.3fus per %uus\n", _syssyncskew, AMIROOS_CFG_SSSP_SYSSYNCPERIOD);
491
#endif
492
  _printSystemInfoSeparator(stream, '=', SYSTEM_INFO_WIDTH);
493

    
494
  return AOS_OK;
495
}
496

    
497
/**
498
 * @brief   Callback function for the sytem:shutdown shell command.
499
 *
500
 * @param[in] stream    The I/O stream to use.
501
 * @param[in] argc      Number of arguments.
502
 * @param[in] argv      List of pointers to the arguments.
503
 *
504
 * @return              An exit status.
505
 * @retval  AOS_OK                  The command was executed successfully.
506
 * @retval  AOS_INVALID_ARGUMENTS   There was an issue with the arguments.
507
 */
508
static int _shellcmd_shutdowncb(BaseSequentialStream* stream, int argc, char* argv[])
509
{
510
  aosDbgCheck(stream != NULL);
511

    
512
  // print help text
513
  if (argc != 2 || strcmp(argv[1], "--help") == 0) {
514
    chprintf(stream, "Usage: %s OPTION\n", argv[0]);
515
    chprintf(stream, "Options:\n");
516
    chprintf(stream, "  --help\n");
517
    chprintf(stream, "    Print this help text.\n");
518
    chprintf(stream, "  --hibernate, -h\n");
519
    chprintf(stream, "    Shutdown to hibernate mode.\n");
520
    chprintf(stream, "    Least energy saving, but allows charging via pins.\n");
521
    chprintf(stream, "  --deepsleep, -d\n");
522
    chprintf(stream, "    Shutdown to deepsleep mode.\n");
523
    chprintf(stream, "    Minimum energy consumption while allowing charging via plug.\n");
524
    chprintf(stream, "  --transportation, -t\n");
525
    chprintf(stream, "    Shutdown to transportation mode.\n");
526
    chprintf(stream, "    Minimum energy consumption with all interrupts disabled (no charging).\n");
527
    chprintf(stream, "  --restart, -r\n");
528
    chprintf(stream, "    Shutdown and restart system.\n");
529

    
530
    return (argc != 2) ? AOS_INVALID_ARGUMENTS : AOS_OK;
531
  }
532
  // handle argument
533
  else {
534
    if (strcmp(argv[1], "-h") == 0 || strcmp(argv[1], "--hibernate") == 0) {
535
      chEvtBroadcastFlags(&aos.events.os, AOS_SYSTEM_EVENTFLAGS_HIBERNATE);
536
      chThdTerminate(currp);
537
      return AOS_OK;
538
    }
539
    else if (strcmp(argv[1], "-d") == 0 || strcmp(argv[1], "--deepsleep") == 0) {
540
      chEvtBroadcastFlags(&aos.events.os, AOS_SYSTEM_EVENTFLAGS_DEEPSLEEP);
541
      chThdTerminate(currp);
542
      return AOS_OK;
543
    }
544
    else if (strcmp(argv[1], "-t") == 0 || strcmp(argv[1], "--transportation") == 0) {
545
      chEvtBroadcastFlags(&aos.events.os, AOS_SYSTEM_EVENTFLAGS_TRANSPORTATION);
546
      chThdTerminate(currp);
547
      return AOS_OK;
548
    }
549
    else if (strcmp(argv[1], "-r") == 0 || strcmp(argv[1], "--restart") == 0) {
550
      chEvtBroadcastFlags(&aos.events.os, AOS_SYSTEM_EVENTFLAGS_RESTART);
551
      chThdTerminate(currp);
552
      return AOS_OK;
553
    }
554
    else {
555
      chprintf(stream, "unknown argument %s\n", argv[1]);
556
      return AOS_INVALID_ARGUMENTS;
557
    }
558
  }
559
}
560
#endif /* AMIROOS_CFG_SHELL_ENABLE == true */
561

    
562
#if (AMIROOS_CFG_TESTS_ENABLE == true) || defined(__DOXYGEN__)
563
/**
564
 * @brief   Callback function for the kernel:test shell command.
565
 *
566
 * @param[in] stream    The I/O stream to use.
567
 * @param[in] argc      Number of arguments.
568
 * @param[in] argv      List of pointers to the arguments.
569
 *
570
 * @return      An exit status.
571
 */
572
static int _shellcmd_kerneltestcb(BaseSequentialStream* stream, int argc, char* argv[])
573
{
574
  aosDbgCheck(stream != NULL);
575

    
576
  (void)argc;
577
  (void)argv;
578

    
579
  tprio_t prio = chThdGetPriorityX();
580
  chThdSetPriority(HIGHPRIO - 5); // some tests increase priorirty by 5, so this is the maximum priority permitted
581
  msg_t retval = test_execute(stream, &rt_test_suite);
582
  chThdSetPriority(prio);
583

    
584
  return retval;
585
}
586
#endif /* AMIROOS_CFG_TESTS_ENABLE == true */
587

    
588
/**
589
 * @brief   Callback function for the PD signal interrupt.
590
 *
591
 * @param[in] extp      Pointer to the interrupt driver object.
592
 * @param[in] channel   Interrupt channel identifier.
593
 */
594
static void _signalPdCallback(void *args)
595
{
596
  (void)args;
597

    
598
  chSysLockFromISR();
599
  chEvtBroadcastFlagsI(&aos.events.io, 0);
600
  chSysUnlockFromISR();
601

    
602
  return;
603
}
604

    
605
/**
606
 * @brief   Callback function for the Sync signal interrupt.
607
 *
608
 * @param[in] extp      Pointer to the interrupt driver object.
609
 * @param[in] channel   Interrupt channel identifier.
610
 */
611
static void _signalSyncCallback(void *args)
612
{
613
  (void)args;
614

    
615
#if (AMIROOS_CFG_SSSP_MASTER == true)
616
  chSysLockFromISR();
617
  chEvtBroadcastFlagsI(&aos.events.io, 0);
618
  chSysUnlockFromISR();
619
#else
620
  apalControlGpioState_t s_state;
621
  aos_timestamp_t uptime;
622

    
623
  chSysLockFromISR();
624
  // if the system is in operation phase
625
  if (aos.sssp.stage == AOS_SSSP_OPERATION) {
626
    // read signal S
627
    apalControlGpioGet(&moduleSsspGpioSync, &s_state);
628
    // if S was toggled from on to off
629
    if (s_state == APAL_GPIO_OFF) {
630
      // get current uptime
631
      aosSysGetUptimeX(&uptime);
632
      // align the uptime with the synchronization period
633
      if (uptime % AMIROOS_CFG_SSSP_SYSSYNCPERIOD < AMIROOS_CFG_SSSP_SYSSYNCPERIOD / 2) {
634
        _uptime -= uptime % AMIROOS_CFG_SSSP_SYSSYNCPERIOD;
635
#if (AMIROOS_CFG_PROFILE == true)
636
        _syssyncskew = ((1.0f - SYSTEM_SYSSYNCSKEW_LPFACTOR) * _syssyncskew) + (SYSTEM_SYSSYNCSKEW_LPFACTOR * (uptime % AMIROOS_CFG_SSSP_SYSSYNCPERIOD));
637
#endif
638
      } else {
639
        _uptime += AMIROOS_CFG_SSSP_SYSSYNCPERIOD - (uptime % AMIROOS_CFG_SSSP_SYSSYNCPERIOD);
640
#if (AMIROOS_CFG_PROFILE == true)
641
        _syssyncskew = ((1.0f - SYSTEM_SYSSYNCSKEW_LPFACTOR) * _syssyncskew) - (SYSTEM_SYSSYNCSKEW_LPFACTOR * (AMIROOS_CFG_SSSP_SYSSYNCPERIOD - (uptime % AMIROOS_CFG_SSSP_SYSSYNCPERIOD)));
642
#endif
643
      }
644
    }
645
  }
646
  // broadcast event
647
  chEvtBroadcastFlagsI(&aos.events.io, 0);
648
  chSysUnlockFromISR();
649
#endif
650

    
651
  return;
652
}
653

    
654
/**
655
 * @brief   Callback function for the uptime accumulation timer.
656
 *
657
 * @param[in] par   Generic parameter.
658
 */
659
static void _uptimeCallback(void* par)
660
{
661
  (void)par;
662

    
663
  chSysLockFromISR();
664
  // read current time in system ticks
665
  register const systime_t st = chVTGetSystemTimeX();
666
  // update the uptime variables
667
  _uptime += TIME_I2US(st - _synctime);
668
  _synctime = st;
669
  // enable the timer again
670
  chVTSetI(&_systimer, SYSTIMER_PERIOD, &_uptimeCallback, NULL);
671
  chSysUnlockFromISR();
672

    
673
  return;
674
}
675

    
676
#if (AMIROOS_CFG_SSSP_MASTER == true) || defined (__DOXYGEN__)
677
/**
678
 * @brief   Periodic system synchronization callback function.
679
 * @details Toggles the SYS_SYNC signal and reconfigures the system synchronization timer.
680
 *
681
 * @param[in] par   Unuesed parameters.
682
 */
683
static void _sysSyncTimerCallback(void* par)
684
{
685
  (void)par;
686

    
687
  apalControlGpioState_t s_state;
688
  aos_timestamp_t uptime;
689

    
690
  chSysLockFromISR();
691
  // toggle and read signal S
692
  apalGpioToggle(moduleSsspGpioSync.gpio);
693
  apalControlGpioGet(&moduleSsspGpioSync, &s_state);
694
  // if S was toggled from off to on
695
  if (s_state == APAL_GPIO_ON) {
696
    // reconfigure the timer precisely, because the logically falling edge (next interrupt) snychronizes the system time
697
    _syssynctime += AMIROOS_CFG_SSSP_SYSSYNCPERIOD;
698
    aosSysGetUptimeX(&uptime);
699
    chVTSetI(&_syssynctimer, TIME_US2I(_syssynctime - uptime), _sysSyncTimerCallback, NULL);
700
  }
701
  // if S was toggled from on to off
702
  else /* if (s_state == APAL_GPIO_OFF) */ {
703
    // reconfigure the timer (lazy)
704
    chVTSetI(&_syssynctimer, TIME_US2I(AMIROOS_CFG_SSSP_SYSSYNCPERIOD / 2), _sysSyncTimerCallback, NULL);
705
  }
706
  chSysUnlockFromISR();
707

    
708
  return;
709
}
710
#endif
711

    
712
/**
713
 * @brief   AMiRo-OS system initialization.
714
 * @note    Must be called from the system control thread (usually main thread).
715
 *
716
 * @param[in] shellPrompt   String to be printed as prompt of the system shell.
717
 */
718
#if (AMIROOS_CFG_SHELL_ENABLE == true) || defined(__DOXYGEN__)
719
void aosSysInit(const char* shellPrompt)
720
#else
721
void aosSysInit(void)
722
#endif
723
{
724
  // set control thread to maximum priority
725
  chThdSetPriority(AOS_THD_CTRLPRIO);
726

    
727
  // set local variables
728
  chVTObjectInit(&_systimer);
729
  _synctime = 0;
730
  _uptime = 0;
731
#if (AMIROOS_CFG_SSSP_MASTER == true)
732
  chVTObjectInit(&_syssynctimer);
733
  _syssynctime = 0;
734
#endif
735
#if (AMIROOS_CFG_SSSP_MASTER != true) && (AMIROOS_CFG_PROFILE == true)
736
  _syssyncskew = 0.0f;
737
#endif
738

    
739
  // set aos configuration
740
  aos.sssp.stage = AOS_SSSP_STARTUP_2_1;
741
  aos.sssp.moduleId = 0;
742
  aosIOStreamInit(&aos.iostream);
743
  chEvtObjectInit(&aos.events.io);
744
  chEvtObjectInit(&aos.events.os);
745

    
746
  // setup external interrupt system
747
  aosIntDriverInit(&moduleIntDriver, moduleIntConfig);
748
  chSysLock();
749
  palSetPadCallbackI(moduleGpioSysPd.port, moduleGpioSysPd.pad, _signalPdCallback, NULL);
750
  palSetPadCallbackI(moduleGpioSysSync.port, moduleGpioSysSync.pad, _signalSyncCallback, NULL);
751
  chSysUnlock();
752
  aosIntDriverStart(&moduleIntDriver);
753

    
754
#if (AMIROOS_CFG_SHELL_ENABLE == true)
755
  // init shell
756
  aosShellInit(&aos.shell,
757
               &aos.events.os,
758
               shellPrompt,
759
               _shell_line,
760
               AMIROOS_CFG_SHELL_LINEWIDTH,
761
               _shell_arglist,
762
               AMIROOS_CFG_SHELL_MAXARGS);
763
  // add system commands
764
  aosShellAddCommand(&aos.shell, &_shellcmd_config);
765
  aosShellAddCommand(&aos.shell, &_shellcmd_info);
766
  aosShellAddCommand(&aos.shell, &_shellcmd_shutdown);
767
#if (AMIROOS_CFG_TESTS_ENABLE == true)
768
  aosShellAddCommand(&aos.shell, &_shellcmd_kerneltest);
769
#endif
770
#endif
771

    
772
  return;
773
}
774

    
775
/**
776
 * @brief   Starts the system and all system threads.
777
 */
778
inline void aosSysStart(void)
779
{
780
  // update the system SSSP stage
781
  aos.sssp.stage = AOS_SSSP_OPERATION;
782

    
783
#if (AMIROOS_CFG_SSSP_MASTER == true)
784
  {
785
    chSysLock();
786
    // start the system synchronization counter
787
    // The first iteration of the timer is set to the next 'center' of a 'slice'.
788
    aos_timestamp_t t;
789
    aosSysGetUptimeX(&t);
790
    t = AMIROOS_CFG_SSSP_SYSSYNCPERIOD - (t % AMIROOS_CFG_SSSP_SYSSYNCPERIOD);
791
    chVTSetI(&_syssynctimer, TIME_US2I((t > (AMIROOS_CFG_SSSP_SYSSYNCPERIOD / 2)) ? (t - (AMIROOS_CFG_SSSP_SYSSYNCPERIOD / 2)) : (t + (AMIROOS_CFG_SSSP_SYSSYNCPERIOD / 2))), _sysSyncTimerCallback, NULL);
792
    chSysUnlock();
793
  }
794
#endif
795

    
796
  // print system information;
797
  _printSystemInfo((BaseSequentialStream*)&aos.iostream);
798
  aosprintf("\n");
799

    
800
#if (AMIROOS_CFG_SHELL_ENABLE == true)
801
  // start system shell thread
802
  aos.shell.thread = chThdCreateStatic(_shell_wa, sizeof(_shell_wa), AMIROOS_CFG_SHELL_THREADPRIO, aosShellThread, &aos.shell);
803
#endif
804

    
805
  return;
806
}
807

    
808
/**
809
 * @brief   Implements the SSSP startup synchronization step.
810
 *
811
 * @param[in] syncEvtListener   Event listener that receives the Sync event.
812
 *
813
 * @return    If another event that the listener is interested in was received, its mask is returned.
814
 *            Otherwise an empty mask (0) is returned.
815
 */
816
eventmask_t aosSysSsspStartupOsInitSyncCheck(event_listener_t* syncEvtListener)
817
{
818
  aosDbgCheck(syncEvtListener != NULL);
819

    
820
  // local variables
821
  eventmask_t m;
822
  eventflags_t f;
823
  apalControlGpioState_t s;
824

    
825
  // update the system SSSP stage
826
  aos.sssp.stage = AOS_SSSP_STARTUP_2_2;
827

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

    
831
  // wait for any event to occur (do not apply any filter in order not to miss any event)
832
  m = chEvtWaitOne(ALL_EVENTS);
833
  f = chEvtGetAndClearFlags(syncEvtListener);
834
  apalControlGpioGet(&moduleSsspGpioSync, &s);
835

    
836
  // if the event was a system event,
837
  //   and it was fired because of the SysSync control signal,
838
  //   and the SysSync control signal has been deactivated
839
  if (m & syncEvtListener->events &&
840
      f == MODULE_SSSP_EVENTFLAGS_SYNC &&
841
      s == APAL_GPIO_OFF) {
842
    chSysLock();
843
    // start the uptime counter
844
    _synctime = chVTGetSystemTimeX();
845
    _uptime = 0;
846
    chVTSetI(&_systimer, SYSTIMER_PERIOD, &_uptimeCallback, NULL);
847
    chSysUnlock();
848

    
849
    return 0;
850
  }
851
  // an unexpected event occurred
852
  else {
853
    // reassign the flags to the event and return the event mask
854
    syncEvtListener->flags |= f;
855
    return m;
856
  }
857
}
858

    
859
/**
860
 * @brief   Retrieves the system uptime.
861
 *
862
 * @param[out] ut   The system uptime.
863
 */
864
inline void aosSysGetUptimeX(aos_timestamp_t* ut)
865
{
866
  aosDbgCheck(ut != NULL);
867

    
868
  *ut = _uptime + TIME_I2US(chVTGetSystemTimeX() - _synctime);
869

    
870
  return;
871
}
872

    
873
/**
874
 * @brief   retrieves the date and time from the MCU clock.
875
 *
876
 * @param[out] td   The date and time.
877
 */
878
void aosSysGetDateTime(struct tm* dt)
879
{
880
  aosDbgCheck(dt != NULL);
881

    
882
  RTCDateTime rtc;
883
  rtcGetTime(&MODULE_HAL_RTC, &rtc);
884
  rtcConvertDateTimeToStructTm(&rtc, dt, NULL);
885

    
886
  return;
887
}
888

    
889
/**
890
 * @brief   set the date and time of the MCU clock.
891
 *
892
 * @param[in] dt    The date and time to set.
893
 */
894
void aosSysSetDateTime(struct tm* dt)
895
{
896
  aosDbgCheck(dt != NULL);
897

    
898
  RTCDateTime rtc;
899
  rtcConvertStructTmToDateTime(dt, 0, &rtc);
900
  rtcSetTime(&MODULE_HAL_RTC, &rtc);
901

    
902
  return;
903
}
904

    
905
/**
906
 * @brief   Initializes/Acknowledges a system shutdown/restart request.
907
 * @note    This functions should be called from the thread with highest priority.
908
 *
909
 * @param[in] shutdown    Type of shutdown.
910
 */
911
void aosSysShutdownInit(aos_shutdown_t shutdown)
912
{
913
  // check arguments
914
  aosDbgCheck(shutdown != AOS_SHUTDOWN_NONE);
915

    
916
#if (AMIROOS_CFG_SSSP_MASTER == true)
917
  // deactivate the system synchronization timer
918
  chVTReset(&_syssynctimer);
919
#endif
920

    
921
  // update the system SSSP stage
922
  aos.sssp.stage = AOS_SSSP_SHUTDOWN_1_1;
923

    
924
  // activate the SYS_PD control signal only, if this module initiated the shutdown
925
  chSysLock();
926
  if (shutdown != AOS_SHUTDOWN_PASSIVE) {
927
    apalControlGpioSet(&moduleSsspGpioPd, APAL_GPIO_ON);
928
  }
929
  // activate the SYS_SYNC signal
930
  apalControlGpioSet(&moduleSsspGpioSync, APAL_GPIO_ON);
931
  chSysUnlock();
932

    
933
  switch (shutdown) {
934
    case AOS_SHUTDOWN_PASSIVE:
935
      chEvtBroadcastFlags(&aos.events.os, AOS_SYSTEM_EVENTFLAGS_SHUTDOWN);
936
      aosprintf("shutdown request received...\n");
937
      break;
938
    case AOS_SHUTDOWN_HIBERNATE:
939
      chEvtBroadcastFlags(&aos.events.os, AOS_SYSTEM_EVENTFLAGS_HIBERNATE);
940
      aosprintf("shutdown to hibernate mode...\n");
941
      break;
942
    case AOS_SHUTDOWN_DEEPSLEEP:
943
      chEvtBroadcastFlags(&aos.events.os, AOS_SYSTEM_EVENTFLAGS_DEEPSLEEP);
944
      aosprintf("shutdown to deepsleep mode...\n");
945
      break;
946
    case AOS_SHUTDOWN_TRANSPORTATION:
947
      chEvtBroadcastFlags(&aos.events.os, AOS_SYSTEM_EVENTFLAGS_TRANSPORTATION);
948
      aosprintf("shutdown to transportation mode...\n");
949
      break;
950
    case AOS_SHUTDOWN_RESTART:
951
      chEvtBroadcastFlags(&aos.events.os, AOS_SYSTEM_EVENTFLAGS_RESTART);
952
      aosprintf("restarting system...\n");
953
      break;
954
   // must never occur
955
   case AOS_SHUTDOWN_NONE:
956
   default:
957
      break;
958
  }
959

    
960
  // update the system SSSP stage
961
  aos.sssp.stage = AOS_SSSP_SHUTDOWN_1_2;
962

    
963
  return;
964
}
965

    
966
/**
967
 * @brief   Stops the system and all related threads (not the thread this function is called from).
968
 */
969
void aosSysStop(void)
970
{
971
#if (AMIROOS_CFG_SHELL_ENABLE == true)
972
  chThdWait(aos.shell.thread);
973
#endif
974

    
975
  return;
976
}
977

    
978
/**
979
 * @brief   Deinitialize all system variables.
980
 */
981
void aosSysDeinit(void)
982
{
983
  return;
984
}
985

    
986
/**
987
 * @brief   Finally shuts down the system and calls the bootloader callback function.
988
 * @note    This function should be called from the thtead with highest priority.
989
 *
990
 * @param[in] extDrv      Pointer to the interrupt driver.
991
 * @param[in] shutdown    Type of shutdown.
992
 */
993
void aosSysShutdownFinal(aos_interrupt_driver_t* intDrv, aos_shutdown_t shutdown)
994
{
995
  // check arguments
996
  aosDbgCheck(intDrv != NULL);
997
  aosDbgCheck(shutdown != AOS_SHUTDOWN_NONE);
998

    
999
  // stop external interrupt system
1000
  aosIntDriverStop(intDrv);
1001

    
1002
  // update the system SSSP stage
1003
  aos.sssp.stage = AOS_SSSP_SHUTDOWN_1_3;
1004

    
1005
  // call bootloader callback depending on arguments
1006
  switch (shutdown) {
1007
    case AOS_SHUTDOWN_PASSIVE:
1008
      BL_CALLBACK_TABLE_ADDRESS->cbHandleShutdownRequest();
1009
      break;
1010
    case AOS_SHUTDOWN_HIBERNATE:
1011
      BL_CALLBACK_TABLE_ADDRESS->cbShutdownHibernate();
1012
      break;
1013
    case AOS_SHUTDOWN_DEEPSLEEP:
1014
      BL_CALLBACK_TABLE_ADDRESS->cbShutdownDeepsleep();
1015
      break;
1016
    case AOS_SHUTDOWN_TRANSPORTATION:
1017
      BL_CALLBACK_TABLE_ADDRESS->cbShutdownTransportation();
1018
      break;
1019
    case AOS_SHUTDOWN_RESTART:
1020
      BL_CALLBACK_TABLE_ADDRESS->cbShutdownRestart();
1021
      break;
1022
    // must never occur
1023
    case AOS_SHUTDOWN_NONE:
1024
    default:
1025
      break;
1026
  }
1027

    
1028
  return;
1029
}