Statistics
| Branch: | Tag: | Revision:

amiro-os / os / core / src / aos_system.c @ 8399aeae

History | View | Annotate | Download (34.189 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   PD signal GPIO.
58
 */
59
static apalControlGpio_t* _gpioPd;
60

    
61
/**
62
 * @brief   Sync signal GPIO.
63
 */
64
static apalControlGpio_t* _gpioSync;
65

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

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

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

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

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

    
93
#if (AMIROOS_CFG_SHELL_ENABLE == true) || defined(__DOXYGEN__)
94
/**
95
 * @brief   System shell.
96
 */
97
static aos_shell_t _shell;
98

    
99
/**
100
 * @brief   Shell thread working area.
101
 */
102
THD_WORKING_AREA(_shell_wa, AMIROOS_CFG_SHELL_STACKSIZE);
103

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

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

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

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

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

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

    
153
/**
154
 * @brief   Global system object.
155
 */
156
aos_system_t aos = {
157
  /* SSSP stage       */ AOS_SSSP_STARTUP_2_1,
158
  /* I/O stream       */ {
159
    /* channel          */ NULL,
160
  },
161
  /* event            */ {
162
    /* I/O              */ {
163
      /* source           */ {
164
        /* next listener    */ NULL,
165
      },
166
      /* flagsSignalPd    */ 0,
167
      /* flagsSignalSync  */ 0,
168
    },
169
    /* OS               */ {
170
      /* source           */ {
171
        /* next listener    */ NULL,
172
      }
173
    },
174
  },
175
#if (AMIROOS_CFG_SHELL_ENABLE == true)
176
  /* shell            */ &_shell,
177
#endif
178
};
179

    
180
/**
181
 * @brief   Print a separator line.
182
 *
183
 * @param[in] stream    Stream to print to or NULL to print to all system streams.
184
 * @param[in] c         Character to use.
185
 * @param[in] n         Length of the separator line.
186
 *
187
 * @return  Number of characters printed.
188
 */
189
static unsigned int _printSystemInfoSeparator(BaseSequentialStream* stream, const char c, const unsigned int n)
190
{
191
  aosDbgCheck(stream != NULL);
192

    
193
  // print the specified character n times
194
  for (unsigned int i = 0; i < n; ++i) {
195
    streamPut(stream, c);
196
  }
197
  streamPut(stream, '\n');
198

    
199
  return n+1;
200
}
201

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

    
221
  unsigned int n = 0;
222
  va_list ap;
223

    
224
  va_start(ap, fmt);
225
  n += chprintf(stream, name);
226
  while (n < namewidth) {
227
    streamPut(stream, ' ');
228
    ++n;
229
  }
230
  n += chvprintf(stream, fmt, ap);
231
  va_end(ap);
232

    
233
  return n;
234
}
235

    
236
/**
237
 * @brief   Prints information about the system.
238
 *
239
 * @param[in] stream    Stream to print to.
240
 */
241
static void _printSystemInfo(BaseSequentialStream* stream)
242
{
243
  aosDbgCheck(stream != NULL);
244

    
245
  _printSystemInfoSeparator(stream, '=', SYSTEM_INFO_WIDTH);
246
  _printSystemInfoLine(stream, "Module", SYSTEM_INFO_NAMEWIDTH, "%s (v%s)\n", BOARD_NAME, BOARD_VERSION);
247
#ifdef PLATFORM_NAME
248
  _printSystemInfoLine(stream, "Platform", SYSTEM_INFO_NAMEWIDTH, "%s\n", PLATFORM_NAME);
249
#endif
250
#ifdef PORT_CORE_VARIANT_NAME
251
  _printSystemInfoLine(stream, "Core Variant", SYSTEM_INFO_NAMEWIDTH, "%s\n", PORT_CORE_VARIANT_NAME);
252
#endif
253
  _printSystemInfoLine(stream, "Architecture", SYSTEM_INFO_NAMEWIDTH, "%s\n", PORT_ARCHITECTURE_NAME);
254
  _printSystemInfoSeparator(stream, '-', SYSTEM_INFO_WIDTH);
255
  _printSystemInfoLine(stream, "AMiRo-OS" , SYSTEM_INFO_NAMEWIDTH, "%u.%u.%u %s (SSSP %u.%u)\n", AMIROOS_VERSION_MAJOR, AMIROOS_VERSION_MINOR, AMIROOS_VERSION_PATCH, AMIROOS_RELEASE_TYPE, AOS_SYSTEM_SSSP_MAJOR, AOS_SYSTEM_SSSP_MINOR);
256
  _printSystemInfoLine(stream, "AMiRo-LLD" , SYSTEM_INFO_NAMEWIDTH, "%u.%u.%u %s (periphAL %u.%u)\n", AMIRO_LLD_VERSION_MAJOR, AMIRO_LLD_VERSION_MINOR, AMIRO_LLD_VERSION_PATCH, AMIRO_LLD_RELEASE_TYPE, PERIPHAL_VERSION_MAJOR, PERIPHAL_VERSION_MINOR);
257
  _printSystemInfoLine(stream, "ChibiOS/RT" , SYSTEM_INFO_NAMEWIDTH, "%u.%u.%u %s\n", CH_KERNEL_MAJOR, CH_KERNEL_MINOR, CH_KERNEL_PATCH, (CH_KERNEL_STABLE == 1) ? "stable" : "non-stable");
258
  _printSystemInfoLine(stream, "ChibiOS/HAL", SYSTEM_INFO_NAMEWIDTH, "%u.%u.%u %s\n", CH_HAL_MAJOR, CH_HAL_MINOR, CH_HAL_PATCH, (CH_HAL_STABLE == 1) ? "stable" : "non-stable");
259
  _printSystemInfoLine(stream, "build type", SYSTEM_INFO_NAMEWIDTH,"%s\n", (AMIROOS_CFG_DBG == true) ? "debug" : "release");
260
  _printSystemInfoLine(stream, "Compiler" , SYSTEM_INFO_NAMEWIDTH, "%s %u.%u.%u\n", "GCC", __GNUC__, __GNUC_MINOR__, __GNUC_PATCHLEVEL__); // TODO: support other compilers than GCC
261
  _printSystemInfoLine(stream, "Compiled" , SYSTEM_INFO_NAMEWIDTH, "%s - %s\n", __DATE__, __TIME__);
262
  _printSystemInfoSeparator(stream, '-', SYSTEM_INFO_WIDTH);
263
  if (BL_CALLBACK_TABLE_ADDRESS->magicNumber == BL_MAGIC_NUMBER) {
264
    _printSystemInfoLine(stream, "AMiRo-BLT", SYSTEM_INFO_NAMEWIDTH, "%u.%u.%u %s (SSSP %u.%u)\n", BL_CALLBACK_TABLE_ADDRESS->vBootloader.major, BL_CALLBACK_TABLE_ADDRESS->vBootloader.minor, BL_CALLBACK_TABLE_ADDRESS->vBootloader.patch,
265
                         (BL_CALLBACK_TABLE_ADDRESS->vBootloader.identifier == BL_VERSION_ID_AMiRoBLT_Release) ? "stable" :
266
                         (BL_CALLBACK_TABLE_ADDRESS->vBootloader.identifier == BL_VERSION_ID_AMiRoBLT_ReleaseCandidate) ? "release candidate" :
267
                         (BL_CALLBACK_TABLE_ADDRESS->vBootloader.identifier == BL_VERSION_ID_AMiRoBLT_Beta) ? "beta" :
268
                         (BL_CALLBACK_TABLE_ADDRESS->vBootloader.identifier == BL_VERSION_ID_AMiRoBLT_Alpha) ? "alpha" :
269
                         (BL_CALLBACK_TABLE_ADDRESS->vBootloader.identifier == BL_VERSION_ID_AMiRoBLT_PreAlpha) ? "pre-alpha" :
270
                         "<release type unknown>",
271
                         BL_CALLBACK_TABLE_ADDRESS->vSSSP.major, BL_CALLBACK_TABLE_ADDRESS->vSSSP.minor);
272
    if (BL_CALLBACK_TABLE_ADDRESS->vSSSP.major != AOS_SYSTEM_SSSP_MAJOR) {
273
      if (stream) {
274
        chprintf(stream, "WARNING: Bootloader and AMiRo-OS implement incompatible SSSP versions!\n");
275
      } else {
276
        aosprintf("WARNING: Bootloader and AMiRo-OS implement incompatible SSSP versions!\n");
277
      }
278
    }
279
    _printSystemInfoLine(stream, "Compiler", SYSTEM_INFO_NAMEWIDTH, "%s %u.%u.%u\n", (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
280
  } else {
281
    if (stream) {
282
      chprintf(stream, "Bootloader incompatible or not available.\n");
283
    } else {
284
      aosprintf("Bootloader incompatible or not available.\n");
285
    }
286
  }
287
  _printSystemInfoSeparator(stream, '-', SYSTEM_INFO_WIDTH);
288
  struct tm dt;
289
  aosSysGetDateTime(&dt);
290
  _printSystemInfoLine(stream, "Date", SYSTEM_INFO_NAMEWIDTH, "%s %02u-%02u-%04u\n", (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",
291
                       dt.tm_mday,
292
                       dt.tm_mon + 1,
293
                       dt.tm_year + 1900);
294
  _printSystemInfoLine(stream, "Time", SYSTEM_INFO_NAMEWIDTH, "%02u:%02u:%02u\n", dt.tm_hour, dt.tm_min, dt.tm_sec);
295
  _printSystemInfoSeparator(stream, '=', SYSTEM_INFO_WIDTH);
296

    
297
  return;
298
}
299

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

    
316
  // local variables
317
  int retval = AOS_INVALID_ARGUMENTS;
318

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

    
427
      // read and print new date and time
428
      aosSysGetDateTime(&dt);
429
      chprintf(stream, "date/time set to %02u:%02u:%02u @ %02u-%02u-%04u\n",
430
               dt.tm_hour, dt.tm_min, dt.tm_sec,
431
               dt.tm_mday, dt.tm_mon+1, dt.tm_year+1900);
432

    
433
      retval = AOS_OK;
434
    }
435
  }
436

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

    
461
  return (argc > 1 && strcmp(argv[1], "--help") == 0) ? AOS_OK : retval;
462
}
463

    
464
/**
465
 * @brief   Callback function for the system:info shell command.
466
 *
467
 * @param[in] stream    The I/O stream to use.
468
 * @param[in] argc      Number of arguments.
469
 * @param[in] argv      List of pointers to the arguments.
470
 *
471
 * @return            An exit status.
472
 * @retval  AOS_OK    The command was executed successfully.
473
 */
474
static int _shellcmd_infocb(BaseSequentialStream* stream, int argc, char* argv[])
475
{
476
  aosDbgCheck(stream != NULL);
477

    
478
  (void)argc;
479
  (void)argv;
480

    
481
  // print system information
482
  _printSystemInfo(stream);
483

    
484
  // print time measurement precision
485
  chprintf(stream, "system time resolution: %uus\n", AOS_SYSTEM_TIME_RESOLUTION);
486

    
487
  // print system uptime
488
  aos_timestamp_t uptime;
489
  aosSysGetUptime(&uptime);
490
  chprintf(stream, "The system is running for\n");
491
  chprintf(stream, "%10u days\n", (uint32_t)(uptime / MICROSECONDS_PER_DAY));
492
  chprintf(stream, "%10u hours\n", (uint8_t)(uptime % MICROSECONDS_PER_DAY / MICROSECONDS_PER_HOUR));
493
  chprintf(stream, "%10u minutes\n", (uint8_t)(uptime % MICROSECONDS_PER_HOUR / MICROSECONDS_PER_MINUTE));
494
  chprintf(stream, "%10u seconds\n", (uint8_t)(uptime % MICROSECONDS_PER_MINUTE / MICROSECONDS_PER_SECOND));
495
  chprintf(stream, "%10u milliseconds\n", (uint16_t)(uptime % MICROSECONDS_PER_SECOND / MICROSECONDS_PER_MILLISECOND));
496
  chprintf(stream, "%10u microseconds\n", (uint16_t)(uptime % MICROSECONDS_PER_MILLISECOND / MICROSECONDS_PER_MICROSECOND));
497

    
498
  return AOS_OK;
499
}
500

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

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

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

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

    
580
  (void)argc;
581
  (void)argv;
582

    
583
  tprio_t prio = chThdGetPriorityX();
584
  chThdSetPriority(HIGHPRIO - 5); // some tests increase priorirty by 5, so this is the maximum priority permitted
585
  msg_t retval = test_execute(stream);
586
  chThdSetPriority(prio);
587

    
588
  return retval;
589
}
590
#endif /* AMIROOS_CFG_TESTS_ENABLE == true */
591

    
592
/**
593
 * @brief   Callback function for the PD signal interrupt.
594
 *
595
 * @param[in] extp      Pointer to the interrupt driver object.
596
 * @param[in] channel   Interrupt channel identifier.
597
 */
598
static void _signalPdCallback(EXTDriver* extp, expchannel_t channel)
599
{
600
  (void)extp;
601
  (void)channel;
602

    
603
  chSysLockFromISR();
604
  chEvtBroadcastFlagsI(&aos.events.io.source, aos.events.io.flagsSignalPd);
605
  chSysUnlockFromISR();
606

    
607
  return;
608
}
609

    
610
/**
611
 * @brief   Callback function for the Sync signal interrupt.
612
 *
613
 * @param[in] extp      Pointer to the interrupt driver object.
614
 * @param[in] channel   Interrupt channel identifier.
615
 */
616
static void _signalSyncCallback(EXTDriver* extp, expchannel_t channel)
617
{
618
  (void)extp;
619
  (void)channel;
620

    
621
#if (AMIROOS_CFG_SSSP_MASTER == true)
622
  chSysLockFromISR();
623
  chEvtBroadcastFlagsI(&aos.events.io.source, aos.events.io.flagsSignalSync);
624
  chSysUnlockFromISR();
625
#else
626
  apalControlGpioState_t s_state;
627
  aos_timestamp_t uptime;
628

    
629
  chSysLockFromISR();
630
  // get current uptime
631
  aosSysGetUptimeX(&uptime);
632
  // read signal S
633
  apalControlGpioGet(_gpioSync, &s_state);
634
  // if S was toggled from on to off during SSSP operation phase
635
  if (aos.ssspStage == AOS_SSSP_OPERATION && s_state == APAL_GPIO_OFF) {
636
    // align the uptime with the synchronization period
637
    if (uptime % AMIROOS_CFG_SSSP_SYSSYNCPERIOD < AMIROOS_CFG_SSSP_SYSSYNCPERIOD / 2) {
638
      _uptime -= uptime % AMIROOS_CFG_SSSP_SYSSYNCPERIOD;
639
    } else {
640
      _uptime += AMIROOS_CFG_SSSP_SYSSYNCPERIOD - (uptime % AMIROOS_CFG_SSSP_SYSSYNCPERIOD);
641
    }
642
  }
643
  // broadcast event
644
  chEvtBroadcastFlagsI(&aos.events.io.source, aos.events.io.flagsSignalSync);
645
  chSysUnlockFromISR();
646
#endif
647

    
648
  return;
649
}
650

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

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

    
670
  return;
671
}
672

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

    
684
  apalControlGpioState_t s_state;
685
  aos_timestamp_t uptime;
686

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

    
706
  return;
707
}
708
#endif
709

    
710
/**
711
 * @brief   AMiRo-OS system initialization.
712
 * @note    Must be called from the system control thread (usually main thread).
713
 *
714
 * @param[in] extDrv        Pointer to the interrupt driver.
715
 * @param[in] extCfg        Configuration for the interrupt driver.
716
 * @param[in] gpioPd        GPIO of the PD signal.
717
 * @param[in] gpioSync      GPIO of the Sync signal
718
 * @param[in] evtFlagsPd    Event flags to be set when a PD interrupt occurs.
719
 * @param[in] evtFlagsSync  Event flags to be set when a Sync interrupt occurs.
720
 * @param[in] shellPrompt   String to be printed as prompt of the system shell.
721
 * @param[in] stdio         Default (usually physically) interface for I/O like shell.
722
 */
723
void aosSysInit(EXTDriver* extDrv,
724
                EXTConfig* extCfg,
725
                apalControlGpio_t* gpioPd,
726
                apalControlGpio_t* gpioSync,
727
                eventflags_t evtFlagsPd,
728
                eventflags_t evtFlagsSync,
729
                const char* shellPrompt)
730
{
731
  // check arguments
732
  aosDbgCheck(extDrv != NULL);
733
  aosDbgCheck(extCfg != NULL);
734
  aosDbgCheck(gpioPd != NULL);
735
  aosDbgCheck(gpioSync != NULL);
736

    
737
  // set control thread to maximum priority
738
  chThdSetPriority(AOS_THD_CTRLPRIO);
739

    
740
  // set local variables
741
  _gpioPd = gpioPd;
742
  _gpioSync = gpioSync;
743
  chVTObjectInit(&_systimer);
744
  _synctime = 0;
745
  _uptime = 0;
746
#if (AMIROOS_CFG_SSSP_MASTER == true)
747
  chVTObjectInit(&_syssynctimer);
748
  _syssynctime = 0;
749
#endif
750

    
751
  // set aos configuration
752
  aos.ssspStage = AOS_SSSP_STARTUP_2_1;
753
  aosIOStreamInit(&aos.iostream);
754
  chEvtObjectInit(&aos.events.io.source);
755
  chEvtObjectInit(&aos.events.os.source);
756
  aos.events.io.flagsSignalPd = evtFlagsPd;
757
  aos.events.io.flagsSignalSync = evtFlagsSync;
758

    
759
  // setup external interrupt system
760
  extCfg->channels[gpioPd->gpio->pad].cb = _signalPdCallback;
761
  extCfg->channels[gpioSync->gpio->pad].cb = _signalSyncCallback;
762
  extStart(extDrv, extCfg);
763

    
764
#if (AMIROOS_CFG_SHELL_ENABLE == true)
765
  // init shell
766
  aosShellInit(aos.shell,
767
               &aos.events.os.source,
768
               shellPrompt,
769
               _shell_line,
770
               AMIROOS_CFG_SHELL_LINEWIDTH,
771
               _shell_arglist,
772
               AMIROOS_CFG_SHELL_MAXARGS);
773
  // add system commands
774
  aosShellAddCommand(aos.shell, &_shellcmd_config);
775
  aosShellAddCommand(aos.shell, &_shellcmd_info);
776
  aosShellAddCommand(aos.shell, &_shellcmd_shutdown);
777
#if (AMIROOS_CFG_TESTS_ENABLE == true)
778
  aosShellAddCommand(aos.shell, &_shellcmd_kerneltest);
779
#endif
780
#else
781
  (void)shellPrompt;
782
#endif
783

    
784
  return;
785
}
786

    
787
/**
788
 * @brief   Starts the system and all system threads.
789
 */
790
inline void aosSysStart(void)
791
{
792
  // update the system SSSP stage
793
  aos.ssspStage = AOS_SSSP_OPERATION;
794

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

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

    
804
  return;
805
}
806

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

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

    
824
  // update the system SSSP stage
825
  aos.ssspStage = AOS_SSSP_STARTUP_2_2;
826

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

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

    
835
  // if the event was a system event,
836
  //   and it was fired because of the SysSync control signal,
837
  //   and the SysSync control signal has been deactivated
838
  if (m & syncEvtListener->events &&
839
      f == aos.events.io.flagsSignalSync &&
840
      s == APAL_GPIO_OFF) {
841
    chSysLock();
842
#if (AMIROOS_CFG_SSSP_MASTER == true)
843
    // start the systen synchronization counter
844
    chVTSetI(&_syssynctimer, LL_US2ST(AMIROOS_CFG_SSSP_SYSSYNCPERIOD / 2), &_sysSyncTimerCallback, NULL);
845
#endif
846
    // start the uptime counter
847
    _synctime = chVTGetSystemTimeX();
848
    _uptime = 0;
849
    chVTSetI(&_systimer, SYSTIMER_PERIOD, &_uptimeCallback, NULL);
850
    chSysUnlock();
851

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

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

    
871
  *ut = _uptime + LL_ST2US(chVTGetSystemTimeX() - _synctime);
872

    
873
  return;
874
}
875

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

    
885
  RTCDateTime rtc;
886
  rtcGetTime(&MODULE_HAL_RTC, &rtc);
887
  rtcConvertDateTimeToStructTm(&rtc, dt, NULL);
888

    
889
  return;
890
}
891

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

    
901
  RTCDateTime rtc;
902
  rtcConvertStructTmToDateTime(dt, 0, &rtc);
903
  rtcSetTime(&MODULE_HAL_RTC, &rtc);
904

    
905
  return;
906
}
907

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

    
919
#if (AMIROOS_CFG_SSSP_MASTER == true)
920
  // deactivate the system synchronization timer
921
  chVTReset(&_syssynctimer);
922
#endif
923

    
924
  // update the system SSSP stage
925
  aos.ssspStage = AOS_SSSP_SHUTDOWN_1_1;
926

    
927
  // activate the SYS_PD control signal only, if this module initiated the shutdown
928
  chSysLock();
929
  if (shutdown != AOS_SHUTDOWN_PASSIVE) {
930
    apalControlGpioSet(_gpioPd, APAL_GPIO_ON);
931
  }
932
  // activate the SYS_SYNC signal
933
  apalControlGpioSet(_gpioSync, APAL_GPIO_ON);
934
  chSysUnlock();
935

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

    
963
  // update the system SSSP stage
964
  aos.ssspStage = AOS_SSSP_SHUTDOWN_1_2;
965

    
966
  return;
967
}
968

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

    
978
  return;
979
}
980

    
981
/**
982
 * @brief   Deinitialize all system variables.
983
 */
984
void aosSysDeinit(void)
985
{
986
  return;
987
}
988

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

    
1002
  // stop external interrupt system
1003
  extStop(extDrv);
1004

    
1005
  // update the system SSSP stage
1006
  aos.ssspStage = AOS_SSSP_SHUTDOWN_1_3;
1007

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

    
1031
  return;
1032
}