Statistics
| Branch: | Tag: | Revision:

amiro-os / os / core / src / aos_system.c @ 933df08e

History | View | Annotate | Download (33 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
#endif
29

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

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

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

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

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

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

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

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

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

    
83
#if (AMIROOS_CFG_SHELL_ENABLE == true) || defined(__DOXYGEN__)
84
/**
85
 * @brief   Shell thread working area.
86
 */
87
THD_WORKING_AREA(_shell_wa, AMIROOS_CFG_SHELL_STACKSIZE);
88

    
89
/**
90
 * @brief   Shell input buffer.
91
 */
92
static char _shell_line[AMIROOS_CFG_SHELL_LINEWIDTH];
93

    
94
/**
95
 * @brief   Shell argument buffer.
96
 */
97
static char* _shell_arglist[AMIROOS_CFG_SHELL_MAXARGS];
98

    
99
/**
100
 * @brief   Shell command to retrieve system information.
101
 */
102
static aos_shellcommand_t _shellcmd_info = {
103
  /* name     */ "module:info",
104
  /* callback */ _shellcmd_infocb,
105
  /* next     */ NULL,
106
};
107

    
108
/**
109
 * @brief   Shell command to set or retrieve system configuration.
110
 */
111
static aos_shellcommand_t _shellcmd_config = {
112
  /* name     */ "module:config",
113
  /* callback */ _shellcmd_configcb,
114
  /* next     */ NULL,
115
};
116

    
117
/**
118
 * @brief   Shell command to shutdown the system.
119
 */
120
static aos_shellcommand_t _shellcmd_shutdown = {
121
  /* name     */ "system:shutdown",
122
  /* callback */ _shellcmd_shutdowncb,
123
  /* next     */ NULL,
124
};
125
#endif /* AMIROOS_CFG_SHELL_ENABLE == true */
126

    
127
#if (AMIROOS_CFG_TESTS_ENABLE == true) || defined(__DOXYGEN__)
128
/**
129
 * @brief   Shell kommand to run a test of the ChibiOS/RT kernel.
130
 */
131
static aos_shellcommand_t _shellcmd_kerneltest = {
132
  /* name     */ "kernel:test",
133
  /* callback */ _shellcmd_kerneltestcb,
134
  /* next     */ NULL,
135
};
136
#endif /* AMIROOS_CFG_TESTS_ENABLE == true */
137

    
138
/**
139
 * @brief   Global system object.
140
 */
141
aos_system_t aos;
142

    
143
/**
144
 * @brief   Print a separator line.
145
 *
146
 * @param[in] stream    Stream to print to or NULL to print to all system streams.
147
 * @param[in] c         Character to use.
148
 * @param[in] n         Length of the separator line.
149
 *
150
 * @return  Number of characters printed.
151
 */
152
static unsigned int _printSystemInfoSeparator(BaseSequentialStream* stream, const char c, const unsigned int n)
153
{
154
  aosDbgCheck(stream != NULL);
155

    
156
  // print the specified character n times
157
  for (unsigned int i = 0; i < n; ++i) {
158
    streamPut(stream, c);
159
  }
160
  streamPut(stream, '\n');
161

    
162
  return n+1;
163
}
164

    
165
/**
166
 * @brief   Print a system information line.
167
 * @details Prints a system information line with the following format:
168
 *            "<name>[spaces]fmt"
169
 *          The combined width of "<name>[spaces]" can be specified in order to align <fmt> on multiple lines.
170
 *          Note that there is not trailing newline added implicitely.
171
 *
172
 * @param[in] stream      Stream to print to or NULL to print to all system streams.
173
 * @param[in] name        Name of the entry/line.
174
 * @param[in] namewidth   Width of the name column.
175
 * @param[in] fmt         Formatted string of information content.
176
 *
177
 * @return  Number of characters printed.
178
 */
179
static unsigned int _printSystemInfoLine(BaseSequentialStream* stream, const char* name, const unsigned int namewidth, const char* fmt, ...)
180
{
181
  aosDbgCheck(stream != NULL);
182
  aosDbgCheck(name != NULL);
183

    
184
  unsigned int n = 0;
185
  va_list ap;
186

    
187
  va_start(ap, fmt);
188
  n += chprintf(stream, name);
189
  while (n < namewidth) {
190
    streamPut(stream, ' ');
191
    ++n;
192
  }
193
  n += chvprintf(stream, fmt, ap);
194
  va_end(ap);
195

    
196
  streamPut(stream, '\n');
197
  ++n;
198

    
199
  return n;
200
}
201

    
202
/**
203
 * @brief   Prints information about the system.
204
 *
205
 * @param[in] stream    Stream to print to.
206
 */
207
static void _printSystemInfo(BaseSequentialStream* stream)
208
{
209
  aosDbgCheck(stream != NULL);
210

    
211
  // local variables
212
  struct tm dt;
213
  aosSysGetDateTime(&dt);
214

    
215
  // print static information about module and operating system
216
  _printSystemInfoSeparator(stream, '=', SYSTEM_INFO_WIDTH);
217
  _printSystemInfoLine(stream, "Module", SYSTEM_INFO_NAMEWIDTH, "%s (v%s)", BOARD_NAME, BOARD_VERSION);
218
#ifdef PLATFORM_NAME
219
  _printSystemInfoLine(stream, "Platform", SYSTEM_INFO_NAMEWIDTH, "%s", PLATFORM_NAME);
220
#endif
221
#ifdef PORT_CORE_VARIANT_NAME
222
  _printSystemInfoLine(stream, "Core Variant", SYSTEM_INFO_NAMEWIDTH, "%s", PORT_CORE_VARIANT_NAME);
223
#endif
224
  _printSystemInfoLine(stream, "Architecture", SYSTEM_INFO_NAMEWIDTH, "%s", PORT_ARCHITECTURE_NAME);
225
  _printSystemInfoSeparator(stream, '-', SYSTEM_INFO_WIDTH);
226
  _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);
227
  _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);
228
  _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");
229
  _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");
230
  _printSystemInfoLine(stream, "build type", SYSTEM_INFO_NAMEWIDTH,"%s", (AMIROOS_CFG_DBG == true) ? "debug" : "release");
231
  _printSystemInfoLine(stream, "Compiler" , SYSTEM_INFO_NAMEWIDTH, "%s %u.%u.%u", "GCC", __GNUC__, __GNUC_MINOR__, __GNUC_PATCHLEVEL__); // TODO: support other compilers than GCC
232
  _printSystemInfoLine(stream, "Compiled" , SYSTEM_INFO_NAMEWIDTH, "%s - %s", __DATE__, __TIME__);
233

    
234
  // print static information about the bootloader
235
  _printSystemInfoSeparator(stream, '-', SYSTEM_INFO_WIDTH);
236
  if (BL_CALLBACK_TABLE_ADDRESS->magicNumber == BL_MAGIC_NUMBER) {
237
    _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,
238
                         (BL_CALLBACK_TABLE_ADDRESS->vBootloader.identifier == BL_VERSION_ID_AMiRoBLT_Release) ? "stable" :
239
                         (BL_CALLBACK_TABLE_ADDRESS->vBootloader.identifier == BL_VERSION_ID_AMiRoBLT_ReleaseCandidate) ? "release candidate" :
240
                         (BL_CALLBACK_TABLE_ADDRESS->vBootloader.identifier == BL_VERSION_ID_AMiRoBLT_Beta) ? "beta" :
241
                         (BL_CALLBACK_TABLE_ADDRESS->vBootloader.identifier == BL_VERSION_ID_AMiRoBLT_Alpha) ? "alpha" :
242
                         (BL_CALLBACK_TABLE_ADDRESS->vBootloader.identifier == BL_VERSION_ID_AMiRoBLT_PreAlpha) ? "pre-alpha" :
243
                         "<release type unknown>",
244
                         BL_CALLBACK_TABLE_ADDRESS->vSSSP.major, BL_CALLBACK_TABLE_ADDRESS->vSSSP.minor);
245
    if (BL_CALLBACK_TABLE_ADDRESS->vSSSP.major != AOS_SYSTEM_SSSP_VERSION_MAJOR) {
246
      if (stream) {
247
        chprintf(stream, "WARNING: Bootloader and AMiRo-OS implement incompatible SSSP versions!\n");
248
      } else {
249
        aosprintf("WARNING: Bootloader and AMiRo-OS implement incompatible SSSP versions!\n");
250
      }
251
    }
252
    _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
253
  } else {
254
    if (stream) {
255
      chprintf(stream, "Bootloader incompatible or not available.\n");
256
    } else {
257
      aosprintf("Bootloader incompatible or not available.\n");
258
    }
259
  }
260

    
261
  // print dynamic information about the module
262
  _printSystemInfoSeparator(stream, '-', SYSTEM_INFO_WIDTH);
263
  if (aos.sssp.moduleId != 0) {
264
    _printSystemInfoLine(stream, "Module ID", SYSTEM_INFO_NAMEWIDTH, "%u", aos.sssp.moduleId);
265
  } else {
266
    _printSystemInfoLine(stream, "Module ID", SYSTEM_INFO_NAMEWIDTH, "not available");
267
  }
268
  _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",
269
                       dt.tm_mday,
270
                       dt.tm_mon + 1,
271
                       dt.tm_year + 1900);
272
  _printSystemInfoLine(stream, "Time", SYSTEM_INFO_NAMEWIDTH, "%02u:%02u:%02u", dt.tm_hour, dt.tm_min, dt.tm_sec);
273

    
274
  _printSystemInfoSeparator(stream, '=', SYSTEM_INFO_WIDTH);
275

    
276
  return;
277
}
278

    
279
#if (AMIROOS_CFG_SHELL_ENABLE == true) || defined(__DOXYGEN__)
280
/**
281
 * @brief   Callback function for the system:config shell command.
282
 *
283
 * @param[in] stream    The I/O stream to use.
284
 * @param[in] argc      Number of arguments.
285
 * @param[in] argv      List of pointers to the arguments.
286
 *
287
 * @return              An exit status.
288
 * @retval  AOS_OK                  The command was executed successfuly.
289
 * @retval  AOS_INVALID_ARGUMENTS   There was an issue with the arguemnts.
290
 */
291
static int _shellcmd_configcb(BaseSequentialStream* stream, int argc, char* argv[])
292
{
293
  aosDbgCheck(stream != NULL);
294

    
295
  // local variables
296
  int retval = AOS_INVALID_ARGUMENTS;
297

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

    
406
      // read and print new date and time
407
      aosSysGetDateTime(&dt);
408
      chprintf(stream, "date/time set to %02u:%02u:%02u @ %02u-%02u-%04u\n",
409
               dt.tm_hour, dt.tm_min, dt.tm_sec,
410
               dt.tm_mday, dt.tm_mon+1, dt.tm_year+1900);
411

    
412
      retval = AOS_OK;
413
    }
414
  }
415

    
416
  // print help, if required
417
  if (retval == AOS_INVALID_ARGUMENTS) {
418
    chprintf(stream, "Usage: %s OPTION\n", argv[0]);
419
    chprintf(stream, "Options:\n");
420
    chprintf(stream, "  --help\n");
421
    chprintf(stream, "    Print this help text.\n");
422
    chprintf(stream, "  --shell [OPT [VAL]]\n");
423
    chprintf(stream, "    Set or retrieve shell configuration.\n");
424
    chprintf(stream, "    Possible OPTs and VALs are:\n");
425
    chprintf(stream, "      prompt text|minimal|uptime|date&time|notime\n");
426
    chprintf(stream, "        Configures the prompt.\n");
427
    chprintf(stream, "      match casesensitive|caseinsenitive\n");
428
    chprintf(stream, "        Configures string matching.\n");
429
    chprintf(stream, "  --date&time OPT VAL\n");
430
    chprintf(stream, "    Set the date/time value of OPT to VAL.\n");
431
    chprintf(stream, "    Possible OPTs are:\n");
432
    chprintf(stream, "      year\n");
433
    chprintf(stream, "      month\n");
434
    chprintf(stream, "      day\n");
435
    chprintf(stream, "      hour\n");
436
    chprintf(stream, "      minute\n");
437
    chprintf(stream, "      second\n");
438
  }
439

    
440
  return (argc > 1 && strcmp(argv[1], "--help") == 0) ? AOS_OK : retval;
441
}
442

    
443
/**
444
 * @brief   Callback function for the system:info shell command.
445
 *
446
 * @param[in] stream    The I/O stream to use.
447
 * @param[in] argc      Number of arguments.
448
 * @param[in] argv      List of pointers to the arguments.
449
 *
450
 * @return            An exit status.
451
 * @retval  AOS_OK    The command was executed successfully.
452
 */
453
static int _shellcmd_infocb(BaseSequentialStream* stream, int argc, char* argv[])
454
{
455
  aosDbgCheck(stream != NULL);
456

    
457
  (void)argc;
458
  (void)argv;
459

    
460
  // print system information
461
  _printSystemInfo(stream);
462

    
463
  // print time measurement precision
464
  chprintf(stream, "system time resolution: %uus\n", AOS_SYSTEM_TIME_RESOLUTION);
465

    
466
  // print system uptime
467
  aos_timestamp_t uptime;
468
  aosSysGetUptime(&uptime);
469
  chprintf(stream, "The system is running for\n");
470
  chprintf(stream, "%10u days\n", (uint32_t)(uptime / MICROSECONDS_PER_DAY));
471
  chprintf(stream, "%10u hours\n", (uint8_t)(uptime % MICROSECONDS_PER_DAY / MICROSECONDS_PER_HOUR));
472
  chprintf(stream, "%10u minutes\n", (uint8_t)(uptime % MICROSECONDS_PER_HOUR / MICROSECONDS_PER_MINUTE));
473
  chprintf(stream, "%10u seconds\n", (uint8_t)(uptime % MICROSECONDS_PER_MINUTE / MICROSECONDS_PER_SECOND));
474
  chprintf(stream, "%10u milliseconds\n", (uint16_t)(uptime % MICROSECONDS_PER_SECOND / MICROSECONDS_PER_MILLISECOND));
475
  chprintf(stream, "%10u microseconds\n", (uint16_t)(uptime % MICROSECONDS_PER_MILLISECOND / MICROSECONDS_PER_MICROSECOND));
476

    
477
  return AOS_OK;
478
}
479

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

    
495
  // print help text
496
  if (argc != 2 || strcmp(argv[1], "--help") == 0) {
497
    chprintf(stream, "Usage: %s OPTION\n", argv[0]);
498
    chprintf(stream, "Options:\n");
499
    chprintf(stream, "  --help\n");
500
    chprintf(stream, "    Print this help text.\n");
501
    chprintf(stream, "  --hibernate, -h\n");
502
    chprintf(stream, "    Shutdown to hibernate mode.\n");
503
    chprintf(stream, "    Least energy saving, but allows charging via pins.\n");
504
    chprintf(stream, "  --deepsleep, -d\n");
505
    chprintf(stream, "    Shutdown to deepsleep mode.\n");
506
    chprintf(stream, "    Minimum energy consumption while allowing charging via plug.\n");
507
    chprintf(stream, "  --transportation, -t\n");
508
    chprintf(stream, "    Shutdown to transportation mode.\n");
509
    chprintf(stream, "    Minimum energy consumption with all interrupts disabled (no charging).\n");
510
    chprintf(stream, "  --restart, -r\n");
511
    chprintf(stream, "    Shutdown and restart system.\n");
512

    
513
    return (argc != 2) ? AOS_INVALID_ARGUMENTS : AOS_OK;
514
  }
515
  // handle argument
516
  else {
517
    if (strcmp(argv[1], "-h") == 0 || strcmp(argv[1], "--hibernate") == 0) {
518
      chEvtBroadcastFlags(&aos.events.os, AOS_SYSTEM_EVENTFLAGS_HIBERNATE);
519
      chThdTerminate(currp);
520
      return AOS_OK;
521
    }
522
    else if (strcmp(argv[1], "-d") == 0 || strcmp(argv[1], "--deepsleep") == 0) {
523
      chEvtBroadcastFlags(&aos.events.os, AOS_SYSTEM_EVENTFLAGS_DEEPSLEEP);
524
      chThdTerminate(currp);
525
      return AOS_OK;
526
    }
527
    else if (strcmp(argv[1], "-t") == 0 || strcmp(argv[1], "--transportation") == 0) {
528
      chEvtBroadcastFlags(&aos.events.os, AOS_SYSTEM_EVENTFLAGS_TRANSPORTATION);
529
      chThdTerminate(currp);
530
      return AOS_OK;
531
    }
532
    else if (strcmp(argv[1], "-r") == 0 || strcmp(argv[1], "--restart") == 0) {
533
      chEvtBroadcastFlags(&aos.events.os, AOS_SYSTEM_EVENTFLAGS_RESTART);
534
      chThdTerminate(currp);
535
      return AOS_OK;
536
    }
537
    else {
538
      chprintf(stream, "unknown argument %s\n", argv[1]);
539
      return AOS_INVALID_ARGUMENTS;
540
    }
541
  }
542
}
543
#endif /* AMIROOS_CFG_SHELL_ENABLE == true */
544

    
545
#if (AMIROOS_CFG_TESTS_ENABLE == true) || defined(__DOXYGEN__)
546
/**
547
 * @brief   Callback function for the kernel:test shell command.
548
 *
549
 * @param[in] stream    The I/O stream to use.
550
 * @param[in] argc      Number of arguments.
551
 * @param[in] argv      List of pointers to the arguments.
552
 *
553
 * @return      An exit status.
554
 */
555
static int _shellcmd_kerneltestcb(BaseSequentialStream* stream, int argc, char* argv[])
556
{
557
  aosDbgCheck(stream != NULL);
558

    
559
  (void)argc;
560
  (void)argv;
561

    
562
  tprio_t prio = chThdGetPriorityX();
563
  chThdSetPriority(HIGHPRIO - 5); // some tests increase priorirty by 5, so this is the maximum priority permitted
564
  msg_t retval = test_execute(stream);
565
  chThdSetPriority(prio);
566

    
567
  return retval;
568
}
569
#endif /* AMIROOS_CFG_TESTS_ENABLE == true */
570

    
571
/**
572
 * @brief   Callback function for the PD signal interrupt.
573
 *
574
 * @param[in] extp      Pointer to the interrupt driver object.
575
 * @param[in] channel   Interrupt channel identifier.
576
 */
577
static void _signalPdCallback(EXTDriver* extp, expchannel_t channel)
578
{
579
  (void)extp;
580

    
581
  chSysLockFromISR();
582
  chEvtBroadcastFlagsI(&aos.events.io, (1 << channel));
583
  chSysUnlockFromISR();
584

    
585
  return;
586
}
587

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

    
598
#if (AMIROOS_CFG_SSSP_MASTER == true)
599
  chSysLockFromISR();
600
  chEvtBroadcastFlagsI(&aos.events.io, (1 << channel));
601
  chSysUnlockFromISR();
602
#else
603
  apalControlGpioState_t s_state;
604
  aos_timestamp_t uptime;
605

    
606
  chSysLockFromISR();
607
  // get current uptime
608
  aosSysGetUptimeX(&uptime);
609
  // read signal S
610
  apalControlGpioGet(&moduleSsspGpioSync, &s_state);
611
  // if S was toggled from on to off during SSSP operation phase
612
  if (aos.sssp.stage == AOS_SSSP_OPERATION && s_state == APAL_GPIO_OFF) {
613
    // align the uptime with the synchronization period
614
    if (uptime % AMIROOS_CFG_SSSP_SYSSYNCPERIOD < AMIROOS_CFG_SSSP_SYSSYNCPERIOD / 2) {
615
      _uptime -= uptime % AMIROOS_CFG_SSSP_SYSSYNCPERIOD;
616
    } else {
617
      _uptime += AMIROOS_CFG_SSSP_SYSSYNCPERIOD - (uptime % AMIROOS_CFG_SSSP_SYSSYNCPERIOD);
618
    }
619
  }
620
  // broadcast event
621
  chEvtBroadcastFlagsI(&aos.events.io, (1 << channel));
622
  chSysUnlockFromISR();
623
#endif
624

    
625
  return;
626
}
627

    
628
/**
629
 * @brief   Callback function for the uptime accumulation timer.
630
 *
631
 * @param[in] par   Generic parameter.
632
 */
633
static void _uptimeCallback(void* par)
634
{
635
  (void)par;
636

    
637
  chSysLockFromISR();
638
  // read current time in system ticks
639
  register const systime_t st = chVTGetSystemTimeX();
640
  // update the uptime variables
641
  _uptime += LL_ST2US(st - _synctime);
642
  _synctime = st;
643
  // enable the timer again
644
  chVTSetI(&_systimer, SYSTIMER_PERIOD, &_uptimeCallback, NULL);
645
  chSysUnlockFromISR();
646

    
647
  return;
648
}
649

    
650
#if (AMIROOS_CFG_SSSP_MASTER == true) || defined (__DOXYGEN__)
651
/**
652
 * @brief   Periodic system synchronization callback function.
653
 * @details Toggles the SYS_SYNC signal and reconfigures the system synchronization timer.
654
 *
655
 * @param[in] par   Unuesed parameters.
656
 */
657
static void _sysSyncTimerCallback(void* par)
658
{
659
  (void)par;
660

    
661
  apalControlGpioState_t s_state;
662
  aos_timestamp_t uptime;
663

    
664
  chSysLockFromISR();
665
  // read and toggle signal S
666
  apalControlGpioGet(&moduleSsspGpioSync, &s_state);
667
  s_state = (s_state == APAL_GPIO_ON) ? APAL_GPIO_OFF : APAL_GPIO_ON;
668
  apalControlGpioSet(&moduleSsspGpioSync, s_state);
669
  // if S was toggled from off to on
670
  if (s_state == APAL_GPIO_ON) {
671
    // reconfigure the timer precisely, because the logically falling edge (next interrupt) snychronizes the system time
672
    _syssynctime += AMIROOS_CFG_SSSP_SYSSYNCPERIOD;
673
    aosSysGetUptimeX(&uptime);
674
    chVTSetI(&_syssynctimer, LL_US2ST(_syssynctime - uptime), _sysSyncTimerCallback, NULL);
675
  }
676
  // if S was toggled from on to off
677
  else /* if (s_state == APAL_GPIO_OFF) */ {
678
    // reconfigure the timer (lazy)
679
    chVTSetI(&_syssynctimer, LL_US2ST(AMIROOS_CFG_SSSP_SYSSYNCPERIOD / 2), _sysSyncTimerCallback, NULL);
680
  }
681
  chSysUnlockFromISR();
682

    
683
  return;
684
}
685
#endif
686

    
687
/**
688
 * @brief   AMiRo-OS system initialization.
689
 * @note    Must be called from the system control thread (usually main thread).
690
 *
691
 * @param[in] shellPrompt   String to be printed as prompt of the system shell.
692
 */
693
#if (AMIROOS_CFG_SHELL_ENABLE == true) || defined(__DOXYGEN__)
694
void aosSysInit(const char* shellPrompt)
695
#else
696
void aosSysInit(void)
697
#endif
698
{
699
  // set control thread to maximum priority
700
  chThdSetPriority(AOS_THD_CTRLPRIO);
701

    
702
  // set local variables
703
  chVTObjectInit(&_systimer);
704
  _synctime = 0;
705
  _uptime = 0;
706
#if (AMIROOS_CFG_SSSP_MASTER == true)
707
  chVTObjectInit(&_syssynctimer);
708
  _syssynctime = 0;
709
#endif
710

    
711
  // set aos configuration
712
  aos.sssp.stage = AOS_SSSP_STARTUP_2_1;
713
  aos.sssp.moduleId = 0;
714
  aosIOStreamInit(&aos.iostream);
715
  chEvtObjectInit(&aos.events.io);
716
  chEvtObjectInit(&aos.events.os);
717

    
718
  // setup external interrupt system
719
  moduleHalExtConfig.channels[moduleSsspGpioPd.gpio->pad].cb = _signalPdCallback;
720
  moduleHalExtConfig.channels[moduleSsspGpioSync.gpio->pad].cb = _signalSyncCallback;
721
  extStart(&MODULE_HAL_EXT, &moduleHalExtConfig);
722

    
723
#if (AMIROOS_CFG_SHELL_ENABLE == true)
724
  // init shell
725
  aosShellInit(&aos.shell,
726
               &aos.events.os,
727
               shellPrompt,
728
               _shell_line,
729
               AMIROOS_CFG_SHELL_LINEWIDTH,
730
               _shell_arglist,
731
               AMIROOS_CFG_SHELL_MAXARGS);
732
  // add system commands
733
  aosShellAddCommand(&aos.shell, &_shellcmd_config);
734
  aosShellAddCommand(&aos.shell, &_shellcmd_info);
735
  aosShellAddCommand(&aos.shell, &_shellcmd_shutdown);
736
#if (AMIROOS_CFG_TESTS_ENABLE == true)
737
  aosShellAddCommand(&aos.shell, &_shellcmd_kerneltest);
738
#endif
739
#endif
740

    
741
  return;
742
}
743

    
744
/**
745
 * @brief   Starts the system and all system threads.
746
 */
747
inline void aosSysStart(void)
748
{
749
  // update the system SSSP stage
750
  aos.sssp.stage = AOS_SSSP_OPERATION;
751

    
752
  // print system information;
753
  _printSystemInfo((BaseSequentialStream*)&aos.iostream);
754
  aosprintf("\n");
755

    
756
#if (AMIROOS_CFG_SHELL_ENABLE == true)
757
  // start system shell thread
758
  aos.shell.thread = chThdCreateStatic(_shell_wa, sizeof(_shell_wa), AMIROOS_CFG_SHELL_THREADPRIO, aosShellThread, &aos.shell);
759
#endif
760

    
761
  return;
762
}
763

    
764
/**
765
 * @brief   Implements the SSSP startup synchronization step.
766
 *
767
 * @param[in] syncEvtListener   Event listener that receives the Sync event.
768
 *
769
 * @return    If another event that the listener is interested in was received, its mask is returned.
770
 *            Otherwise an empty mask (0) is returned.
771
 */
772
eventmask_t aosSysSsspStartupOsInitSyncCheck(event_listener_t* syncEvtListener)
773
{
774
  aosDbgCheck(syncEvtListener != NULL);
775

    
776
  // local variables
777
  eventmask_t m;
778
  eventflags_t f;
779
  apalControlGpioState_t s;
780

    
781
  // update the system SSSP stage
782
  aos.sssp.stage = AOS_SSSP_STARTUP_2_2;
783

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

    
787
  // wait for any event to occur (do not apply any filter in order not to miss any event)
788
  m = chEvtWaitOne(ALL_EVENTS);
789
  f = chEvtGetAndClearFlags(syncEvtListener);
790
  apalControlGpioGet(&moduleSsspGpioSync, &s);
791

    
792
  // if the event was a system event,
793
  //   and it was fired because of the SysSync control signal,
794
  //   and the SysSync control signal has been deactivated
795
  if (m & syncEvtListener->events &&
796
      f == MODULE_SSSP_EVENTFLAGS_SYNC &&
797
      s == APAL_GPIO_OFF) {
798
    chSysLock();
799
#if (AMIROOS_CFG_SSSP_MASTER == true)
800
    // start the systen synchronization counter
801
    chVTSetI(&_syssynctimer, LL_US2ST(AMIROOS_CFG_SSSP_SYSSYNCPERIOD / 2), &_sysSyncTimerCallback, NULL);
802
#endif
803
    // start the uptime counter
804
    _synctime = chVTGetSystemTimeX();
805
    _uptime = 0;
806
    chVTSetI(&_systimer, SYSTIMER_PERIOD, &_uptimeCallback, NULL);
807
    chSysUnlock();
808

    
809
    return 0;
810
  }
811
  // an unexpected event occurred
812
  else {
813
    // reassign the flags to the event and return the event mask
814
    syncEvtListener->flags |= f;
815
    return m;
816
  }
817
}
818

    
819
/**
820
 * @brief   Retrieves the system uptime.
821
 *
822
 * @param[out] ut   The system uptime.
823
 */
824
inline void aosSysGetUptimeX(aos_timestamp_t* ut)
825
{
826
  aosDbgCheck(ut != NULL);
827

    
828
  *ut = _uptime + LL_ST2US(chVTGetSystemTimeX() - _synctime);
829

    
830
  return;
831
}
832

    
833
/**
834
 * @brief   retrieves the date and time from the MCU clock.
835
 *
836
 * @param[out] td   The date and time.
837
 */
838
void aosSysGetDateTime(struct tm* dt)
839
{
840
  aosDbgCheck(dt != NULL);
841

    
842
  RTCDateTime rtc;
843
  rtcGetTime(&MODULE_HAL_RTC, &rtc);
844
  rtcConvertDateTimeToStructTm(&rtc, dt, NULL);
845

    
846
  return;
847
}
848

    
849
/**
850
 * @brief   set the date and time of the MCU clock.
851
 *
852
 * @param[in] dt    The date and time to set.
853
 */
854
void aosSysSetDateTime(struct tm* dt)
855
{
856
  aosDbgCheck(dt != NULL);
857

    
858
  RTCDateTime rtc;
859
  rtcConvertStructTmToDateTime(dt, 0, &rtc);
860
  rtcSetTime(&MODULE_HAL_RTC, &rtc);
861

    
862
  return;
863
}
864

    
865
/**
866
 * @brief   Initializes/Acknowledges a system shutdown/restart request.
867
 * @note    This functions should be called from the thread with highest priority.
868
 *
869
 * @param[in] shutdown    Type of shutdown.
870
 */
871
void aosSysShutdownInit(aos_shutdown_t shutdown)
872
{
873
  // check arguments
874
  aosDbgCheck(shutdown != AOS_SHUTDOWN_NONE);
875

    
876
#if (AMIROOS_CFG_SSSP_MASTER == true)
877
  // deactivate the system synchronization timer
878
  chVTReset(&_syssynctimer);
879
#endif
880

    
881
  // update the system SSSP stage
882
  aos.sssp.stage = AOS_SSSP_SHUTDOWN_1_1;
883

    
884
  // activate the SYS_PD control signal only, if this module initiated the shutdown
885
  chSysLock();
886
  if (shutdown != AOS_SHUTDOWN_PASSIVE) {
887
    apalControlGpioSet(&moduleSsspGpioPd, APAL_GPIO_ON);
888
  }
889
  // activate the SYS_SYNC signal
890
  apalControlGpioSet(&moduleSsspGpioSync, APAL_GPIO_ON);
891
  chSysUnlock();
892

    
893
  switch (shutdown) {
894
    case AOS_SHUTDOWN_PASSIVE:
895
      chEvtBroadcastFlags(&aos.events.os, AOS_SYSTEM_EVENTFLAGS_SHUTDOWN);
896
      aosprintf("shutdown request received...\n");
897
      break;
898
    case AOS_SHUTDOWN_HIBERNATE:
899
      chEvtBroadcastFlags(&aos.events.os, AOS_SYSTEM_EVENTFLAGS_HIBERNATE);
900
      aosprintf("shutdown to hibernate mode...\n");
901
      break;
902
    case AOS_SHUTDOWN_DEEPSLEEP:
903
      chEvtBroadcastFlags(&aos.events.os, AOS_SYSTEM_EVENTFLAGS_DEEPSLEEP);
904
      aosprintf("shutdown to deepsleep mode...\n");
905
      break;
906
    case AOS_SHUTDOWN_TRANSPORTATION:
907
      chEvtBroadcastFlags(&aos.events.os, AOS_SYSTEM_EVENTFLAGS_TRANSPORTATION);
908
      aosprintf("shutdown to transportation mode...\n");
909
      break;
910
    case AOS_SHUTDOWN_RESTART:
911
      chEvtBroadcastFlags(&aos.events.os, AOS_SYSTEM_EVENTFLAGS_RESTART);
912
      aosprintf("restarting system...\n");
913
      break;
914
   // must never occur
915
   case AOS_SHUTDOWN_NONE:
916
   default:
917
      break;
918
  }
919

    
920
  // update the system SSSP stage
921
  aos.sssp.stage = AOS_SSSP_SHUTDOWN_1_2;
922

    
923
  return;
924
}
925

    
926
/**
927
 * @brief   Stops the system and all related threads (not the thread this function is called from).
928
 */
929
void aosSysStop(void)
930
{
931
#if (AMIROOS_CFG_SHELL_ENABLE == true)
932
  chThdWait(aos.shell.thread);
933
#endif
934

    
935
  return;
936
}
937

    
938
/**
939
 * @brief   Deinitialize all system variables.
940
 */
941
void aosSysDeinit(void)
942
{
943
  return;
944
}
945

    
946
/**
947
 * @brief   Finally shuts down the system and calls the bootloader callback function.
948
 * @note    This function should be called from the thtead with highest priority.
949
 *
950
 * @param[in] extDrv      Pointer to the interrupt driver.
951
 * @param[in] shutdown    Type of shutdown.
952
 */
953
void aosSysShutdownFinal(EXTDriver* extDrv, aos_shutdown_t shutdown)
954
{
955
  // check arguments
956
  aosDbgCheck(extDrv != NULL);
957
  aosDbgCheck(shutdown != AOS_SHUTDOWN_NONE);
958

    
959
  // stop external interrupt system
960
  extStop(extDrv);
961

    
962
  // update the system SSSP stage
963
  aos.sssp.stage = AOS_SSSP_SHUTDOWN_1_3;
964

    
965
  // call bootloader callback depending on arguments
966
  switch (shutdown) {
967
    case AOS_SHUTDOWN_PASSIVE:
968
      BL_CALLBACK_TABLE_ADDRESS->cbHandleShutdownRequest();
969
      break;
970
    case AOS_SHUTDOWN_HIBERNATE:
971
      BL_CALLBACK_TABLE_ADDRESS->cbShutdownHibernate();
972
      break;
973
    case AOS_SHUTDOWN_DEEPSLEEP:
974
      BL_CALLBACK_TABLE_ADDRESS->cbShutdownDeepsleep();
975
      break;
976
    case AOS_SHUTDOWN_TRANSPORTATION:
977
      BL_CALLBACK_TABLE_ADDRESS->cbShutdownTransportation();
978
      break;
979
    case AOS_SHUTDOWN_RESTART:
980
      BL_CALLBACK_TABLE_ADDRESS->cbShutdownRestart();
981
      break;
982
    // must never occur
983
    case AOS_SHUTDOWN_NONE:
984
    default:
985
      break;
986
  }
987

    
988
  return;
989
}