Statistics
| Branch: | Tag: | Revision:

amiro-os / os / core / src / aos_system.c @ 9461fadc

History | View | Annotate | Download (33.3 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
  // if the system is in operation phase
608
  if (aos.sssp.stage == AOS_SSSP_OPERATION) {
609
    // read signal S
610
    apalControlGpioGet(&moduleSsspGpioSync, &s_state);
611
    // if S was toggled from on to off
612
    if (s_state == APAL_GPIO_OFF) {
613
      // get current uptime
614
      aosSysGetUptimeX(&uptime);
615
      // align the uptime with the synchronization period
616
      if (uptime % AMIROOS_CFG_SSSP_SYSSYNCPERIOD < AMIROOS_CFG_SSSP_SYSSYNCPERIOD / 2) {
617
        _uptime -= uptime % AMIROOS_CFG_SSSP_SYSSYNCPERIOD;
618
      } else {
619
        _uptime += AMIROOS_CFG_SSSP_SYSSYNCPERIOD - (uptime % AMIROOS_CFG_SSSP_SYSSYNCPERIOD);
620
      }
621
    }
622
  }
623
  // broadcast event
624
  chEvtBroadcastFlagsI(&aos.events.io, (1 << channel));
625
  chSysUnlockFromISR();
626
#endif
627

    
628
  return;
629
}
630

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

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

    
650
  return;
651
}
652

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

    
664
  apalControlGpioState_t s_state;
665
  aos_timestamp_t uptime;
666

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

    
685
  return;
686
}
687
#endif
688

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

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

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

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

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

    
743
  return;
744
}
745

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

    
754
#if (AMIROOS_CFG_SSSP_MASTER == true)
755
  {
756
    chSysLock();
757
    // start the system synchronization counter
758
    // The first iteration of the timer is set to the next 'center' of a 'slice'.
759
    aos_timestamp_t t;
760
    aosSysGetUptimeX(&t);
761
    t = AMIROOS_CFG_SSSP_SYSSYNCPERIOD - (t % AMIROOS_CFG_SSSP_SYSSYNCPERIOD);
762
    chVTSetI(&_syssynctimer, LL_US2ST((t > (AMIROOS_CFG_SSSP_SYSSYNCPERIOD / 2)) ? (t - (AMIROOS_CFG_SSSP_SYSSYNCPERIOD / 2)) : (t + (AMIROOS_CFG_SSSP_SYSSYNCPERIOD / 2))), _sysSyncTimerCallback, NULL);
763
    chSysUnlock();
764
  }
765
#endif
766

    
767
  // print system information;
768
  _printSystemInfo((BaseSequentialStream*)&aos.iostream);
769
  aosprintf("\n");
770

    
771
#if (AMIROOS_CFG_SHELL_ENABLE == true)
772
  // start system shell thread
773
  aos.shell.thread = chThdCreateStatic(_shell_wa, sizeof(_shell_wa), AMIROOS_CFG_SHELL_THREADPRIO, aosShellThread, &aos.shell);
774
#endif
775

    
776
  return;
777
}
778

    
779
/**
780
 * @brief   Implements the SSSP startup synchronization step.
781
 *
782
 * @param[in] syncEvtListener   Event listener that receives the Sync event.
783
 *
784
 * @return    If another event that the listener is interested in was received, its mask is returned.
785
 *            Otherwise an empty mask (0) is returned.
786
 */
787
eventmask_t aosSysSsspStartupOsInitSyncCheck(event_listener_t* syncEvtListener)
788
{
789
  aosDbgCheck(syncEvtListener != NULL);
790

    
791
  // local variables
792
  eventmask_t m;
793
  eventflags_t f;
794
  apalControlGpioState_t s;
795

    
796
  // update the system SSSP stage
797
  aos.sssp.stage = AOS_SSSP_STARTUP_2_2;
798

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

    
802
  // wait for any event to occur (do not apply any filter in order not to miss any event)
803
  m = chEvtWaitOne(ALL_EVENTS);
804
  f = chEvtGetAndClearFlags(syncEvtListener);
805
  apalControlGpioGet(&moduleSsspGpioSync, &s);
806

    
807
  // if the event was a system event,
808
  //   and it was fired because of the SysSync control signal,
809
  //   and the SysSync control signal has been deactivated
810
  if (m & syncEvtListener->events &&
811
      f == MODULE_SSSP_EVENTFLAGS_SYNC &&
812
      s == APAL_GPIO_OFF) {
813
    chSysLock();
814
    // start the uptime counter
815
    _synctime = chVTGetSystemTimeX();
816
    _uptime = 0;
817
    chVTSetI(&_systimer, SYSTIMER_PERIOD, &_uptimeCallback, NULL);
818
    chSysUnlock();
819

    
820
    return 0;
821
  }
822
  // an unexpected event occurred
823
  else {
824
    // reassign the flags to the event and return the event mask
825
    syncEvtListener->flags |= f;
826
    return m;
827
  }
828
}
829

    
830
/**
831
 * @brief   Retrieves the system uptime.
832
 *
833
 * @param[out] ut   The system uptime.
834
 */
835
inline void aosSysGetUptimeX(aos_timestamp_t* ut)
836
{
837
  aosDbgCheck(ut != NULL);
838

    
839
  *ut = _uptime + LL_ST2US(chVTGetSystemTimeX() - _synctime);
840

    
841
  return;
842
}
843

    
844
/**
845
 * @brief   retrieves the date and time from the MCU clock.
846
 *
847
 * @param[out] td   The date and time.
848
 */
849
void aosSysGetDateTime(struct tm* dt)
850
{
851
  aosDbgCheck(dt != NULL);
852

    
853
  RTCDateTime rtc;
854
  rtcGetTime(&MODULE_HAL_RTC, &rtc);
855
  rtcConvertDateTimeToStructTm(&rtc, dt, NULL);
856

    
857
  return;
858
}
859

    
860
/**
861
 * @brief   set the date and time of the MCU clock.
862
 *
863
 * @param[in] dt    The date and time to set.
864
 */
865
void aosSysSetDateTime(struct tm* dt)
866
{
867
  aosDbgCheck(dt != NULL);
868

    
869
  RTCDateTime rtc;
870
  rtcConvertStructTmToDateTime(dt, 0, &rtc);
871
  rtcSetTime(&MODULE_HAL_RTC, &rtc);
872

    
873
  return;
874
}
875

    
876
/**
877
 * @brief   Initializes/Acknowledges a system shutdown/restart request.
878
 * @note    This functions should be called from the thread with highest priority.
879
 *
880
 * @param[in] shutdown    Type of shutdown.
881
 */
882
void aosSysShutdownInit(aos_shutdown_t shutdown)
883
{
884
  // check arguments
885
  aosDbgCheck(shutdown != AOS_SHUTDOWN_NONE);
886

    
887
#if (AMIROOS_CFG_SSSP_MASTER == true)
888
  // deactivate the system synchronization timer
889
  chVTReset(&_syssynctimer);
890
#endif
891

    
892
  // update the system SSSP stage
893
  aos.sssp.stage = AOS_SSSP_SHUTDOWN_1_1;
894

    
895
  // activate the SYS_PD control signal only, if this module initiated the shutdown
896
  chSysLock();
897
  if (shutdown != AOS_SHUTDOWN_PASSIVE) {
898
    apalControlGpioSet(&moduleSsspGpioPd, APAL_GPIO_ON);
899
  }
900
  // activate the SYS_SYNC signal
901
  apalControlGpioSet(&moduleSsspGpioSync, APAL_GPIO_ON);
902
  chSysUnlock();
903

    
904
  switch (shutdown) {
905
    case AOS_SHUTDOWN_PASSIVE:
906
      chEvtBroadcastFlags(&aos.events.os, AOS_SYSTEM_EVENTFLAGS_SHUTDOWN);
907
      aosprintf("shutdown request received...\n");
908
      break;
909
    case AOS_SHUTDOWN_HIBERNATE:
910
      chEvtBroadcastFlags(&aos.events.os, AOS_SYSTEM_EVENTFLAGS_HIBERNATE);
911
      aosprintf("shutdown to hibernate mode...\n");
912
      break;
913
    case AOS_SHUTDOWN_DEEPSLEEP:
914
      chEvtBroadcastFlags(&aos.events.os, AOS_SYSTEM_EVENTFLAGS_DEEPSLEEP);
915
      aosprintf("shutdown to deepsleep mode...\n");
916
      break;
917
    case AOS_SHUTDOWN_TRANSPORTATION:
918
      chEvtBroadcastFlags(&aos.events.os, AOS_SYSTEM_EVENTFLAGS_TRANSPORTATION);
919
      aosprintf("shutdown to transportation mode...\n");
920
      break;
921
    case AOS_SHUTDOWN_RESTART:
922
      chEvtBroadcastFlags(&aos.events.os, AOS_SYSTEM_EVENTFLAGS_RESTART);
923
      aosprintf("restarting system...\n");
924
      break;
925
   // must never occur
926
   case AOS_SHUTDOWN_NONE:
927
   default:
928
      break;
929
  }
930

    
931
  // update the system SSSP stage
932
  aos.sssp.stage = AOS_SSSP_SHUTDOWN_1_2;
933

    
934
  return;
935
}
936

    
937
/**
938
 * @brief   Stops the system and all related threads (not the thread this function is called from).
939
 */
940
void aosSysStop(void)
941
{
942
#if (AMIROOS_CFG_SHELL_ENABLE == true)
943
  chThdWait(aos.shell.thread);
944
#endif
945

    
946
  return;
947
}
948

    
949
/**
950
 * @brief   Deinitialize all system variables.
951
 */
952
void aosSysDeinit(void)
953
{
954
  return;
955
}
956

    
957
/**
958
 * @brief   Finally shuts down the system and calls the bootloader callback function.
959
 * @note    This function should be called from the thtead with highest priority.
960
 *
961
 * @param[in] extDrv      Pointer to the interrupt driver.
962
 * @param[in] shutdown    Type of shutdown.
963
 */
964
void aosSysShutdownFinal(EXTDriver* extDrv, aos_shutdown_t shutdown)
965
{
966
  // check arguments
967
  aosDbgCheck(extDrv != NULL);
968
  aosDbgCheck(shutdown != AOS_SHUTDOWN_NONE);
969

    
970
  // stop external interrupt system
971
  extStop(extDrv);
972

    
973
  // update the system SSSP stage
974
  aos.sssp.stage = AOS_SSSP_SHUTDOWN_1_3;
975

    
976
  // call bootloader callback depending on arguments
977
  switch (shutdown) {
978
    case AOS_SHUTDOWN_PASSIVE:
979
      BL_CALLBACK_TABLE_ADDRESS->cbHandleShutdownRequest();
980
      break;
981
    case AOS_SHUTDOWN_HIBERNATE:
982
      BL_CALLBACK_TABLE_ADDRESS->cbShutdownHibernate();
983
      break;
984
    case AOS_SHUTDOWN_DEEPSLEEP:
985
      BL_CALLBACK_TABLE_ADDRESS->cbShutdownDeepsleep();
986
      break;
987
    case AOS_SHUTDOWN_TRANSPORTATION:
988
      BL_CALLBACK_TABLE_ADDRESS->cbShutdownTransportation();
989
      break;
990
    case AOS_SHUTDOWN_RESTART:
991
      BL_CALLBACK_TABLE_ADDRESS->cbShutdownRestart();
992
      break;
993
    // must never occur
994
    case AOS_SHUTDOWN_NONE:
995
    default:
996
      break;
997
  }
998

    
999
  return;
1000
}