Statistics
| Branch: | Tag: | Revision:

amiro-os / os / core / src / aos_system.c @ ba516b61

History | View | Annotate | Download (30.5 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 <chprintf.h>
22
#include <amiroos.h>
23
#include <amiroblt.h>
24
#include <string.h>
25
#include <stdarg.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

    
289
  return;
290
}
291

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

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

    
311
  // if there are additional arguments
312
  if (argc > 1) {
313
    // if the user wants to set or retrieve the shell configuration
314
    if (strcmp(argv[1], "--shell") == 0) {
315
      // if the user wants to modify the shell configuration
316
      if (argc > 2) {
317
        // if the user wants to modify the prompt
318
        if (strcmp(argv[2], "prompt") == 0) {
319
          // there must be a further argument
320
          if (argc > 3) {
321
            // handle the option
322
            if (strcmp(argv[3], "text") == 0) {
323
              aos.shell->config &= ~AOS_SHELL_CONFIG_PROMPT_MINIMAL;
324
              retval = AOS_OK;
325
            }
326
            else if (strcmp(argv[3], "minimal") == 0) {
327
              aos.shell->config |= AOS_SHELL_CONFIG_PROMPT_MINIMAL;
328
              retval = AOS_OK;
329
            }
330
            else if (strcmp(argv[3], "notime") == 0) {
331
              aos.shell->config &= ~AOS_SHELL_CONFIG_PROMPT_UPTIME;
332
              retval = AOS_OK;
333
            }
334
            else if (strcmp(argv[3], "uptime") == 0) {
335
              aos.shell->config |= AOS_SHELL_CONFIG_PROMPT_UPTIME;
336
              retval = AOS_OK;
337
            }
338
          }
339
        }
340
        // if the user wants to modify the string matching
341
        else if (strcmp(argv[2], "match") == 0) {
342
          // there must be a further argument
343
          if (argc > 3) {
344
            if (strcmp(argv[3], "casesensitive") == 0) {
345
              aos.shell->config |= AOS_SHELL_CONFIG_MATCH_CASE;
346
              retval = AOS_OK;
347
            }
348
            else if (strcmp(argv[3], "caseinsensitive") == 0) {
349
              aos.shell->config &= ~AOS_SHELL_CONFIG_MATCH_CASE;
350
              retval = AOS_OK;
351
            }
352
          }
353
        }
354
      }
355
      // if the user wants to retrieve the shell configuration
356
      else {
357
        chprintf(stream, "current shell configuration:\n");
358
        chprintf(stream, "  prompt text:   %s\n",
359
                 (aos.shell->prompt != NULL) ? aos.shell->prompt : "n/a");
360
        chprintf(stream, "  prompt style:  %s, %s\n",
361
                 (aos.shell->config & AOS_SHELL_CONFIG_PROMPT_MINIMAL) ? "minimal" : "text",
362
                 (aos.shell->config & AOS_SHELL_CONFIG_PROMPT_UPTIME) ? "system uptime" : "no time");
363
        chprintf(stream, "  input method:  %s\n",
364
                 (aos.shell->config & AOS_SHELL_CONFIG_INPUT_OVERWRITE) ? "replace" : "insert");
365
        chprintf(stream, "  text matching: %s\n",
366
                 (aos.shell->config & AOS_SHELL_CONFIG_MATCH_CASE) ? "case sensitive" : "case insensitive");
367
        retval = AOS_OK;
368
      }
369
    }
370
  }
371

    
372
  // print help, if required
373
  if (retval == AOS_INVALID_ARGUMENTS) {
374
    chprintf(stream, "Usage: %s OPTION\n", argv[0]);
375
    chprintf(stream, "Options:\n");
376
    chprintf(stream, "  --help\n");
377
    chprintf(stream, "    Print this help text.\n");
378
    chprintf(stream, "  --shell [OPT [VAL]]\n");
379
    chprintf(stream, "    Set or retrieve shell configuration.\n");
380
    chprintf(stream, "    Possible OPTs and VALs are:\n");
381
    chprintf(stream, "      prompt text|minimal|uptime|notime\n");
382
    chprintf(stream, "        Configures the prompt.\n");
383
    chprintf(stream, "      match casesensitive|caseinsenitive\n");
384
    chprintf(stream, "        Configures string matching.\n");
385
  }
386

    
387
  return (argc > 1 && strcmp(argv[1], "--help") == 0) ? AOS_OK : retval;
388
}
389

    
390
/**
391
 * @brief   Callback function for the system:info shell command.
392
 *
393
 * @param[in] stream    The I/O stream to use.
394
 * @param[in] argc      Number of arguments.
395
 * @param[in] argv      List of pointers to the arguments.
396
 *
397
 * @return            An exit status.
398
 * @retval  AOS_OK    The command was executed successfully.
399
 */
400
static int _shellcmd_infocb(BaseSequentialStream* stream, int argc, char* argv[])
401
{
402
  aosDbgCheck(stream != NULL);
403

    
404
  (void)argc;
405
  (void)argv;
406

    
407
  // print system information
408
  _printSystemInfo(stream);
409

    
410
  // print time measurement precision
411
  chprintf(stream, "system time resolution: %uus\n", AOS_SYSTEM_TIME_RESOLUTION);
412

    
413
  // print system uptime
414
  aos_timestamp_t uptime;
415
  aosSysGetUptime(&uptime);
416
  chprintf(stream, "The system is running for\n");
417
  chprintf(stream, "%10u days\n", (uint32_t)(uptime / MICROSECONDS_PER_DAY));
418
  chprintf(stream, "%10u hours\n", (uint8_t)(uptime % MICROSECONDS_PER_DAY / MICROSECONDS_PER_HOUR));
419
  chprintf(stream, "%10u minutes\n", (uint8_t)(uptime % MICROSECONDS_PER_HOUR / MICROSECONDS_PER_MINUTE));
420
  chprintf(stream, "%10u seconds\n", (uint8_t)(uptime % MICROSECONDS_PER_MINUTE / MICROSECONDS_PER_SECOND));
421
  chprintf(stream, "%10u milliseconds\n", (uint16_t)(uptime % MICROSECONDS_PER_SECOND / MICROSECONDS_PER_MILLISECOND));
422
  chprintf(stream, "%10u microseconds\n", (uint16_t)(uptime % MICROSECONDS_PER_MILLISECOND / MICROSECONDS_PER_MICROSECOND));
423

    
424
  return AOS_OK;
425
}
426

    
427
/**
428
 * @brief   Callback function for the sytem:shutdown shell command.
429
 *
430
 * @param[in] stream    The I/O stream to use.
431
 * @param[in] argc      Number of arguments.
432
 * @param[in] argv      List of pointers to the arguments.
433
 *
434
 * @return              An exit status.
435
 * @retval  AOS_OK                  The command was executed successfully.
436
 * @retval  AOS_INVALID_ARGUMENTS   There was an issue with the arguments.
437
 */
438
static int _shellcmd_shutdowncb(BaseSequentialStream* stream, int argc, char* argv[])
439
{
440
  aosDbgCheck(stream != NULL);
441

    
442
  // print help text
443
  if (argc != 2 || strcmp(argv[1], "--help") == 0) {
444
    chprintf(stream, "Usage: %s OPTION\n", argv[0]);
445
    chprintf(stream, "Options:\n");
446
    chprintf(stream, "  --help\n");
447
    chprintf(stream, "    Print this help text.\n");
448
    chprintf(stream, "  --hibernate, -h\n");
449
    chprintf(stream, "    Shutdown to hibernate mode.\n");
450
    chprintf(stream, "    Least energy saving, but allows charging via pins.\n");
451
    chprintf(stream, "  --deepsleep, -d\n");
452
    chprintf(stream, "    Shutdown to deepsleep mode.\n");
453
    chprintf(stream, "    Minimum energy consumption while allowing charging via plug.\n");
454
    chprintf(stream, "  --transportation, -t\n");
455
    chprintf(stream, "    Shutdown to transportation mode.\n");
456
    chprintf(stream, "    Minimum energy consumption with all interrupts disabled (no charging).\n");
457
    chprintf(stream, "  --restart, -r\n");
458
    chprintf(stream, "    Shutdown and restart system.\n");
459

    
460
    return (argc != 2) ? AOS_INVALID_ARGUMENTS : AOS_OK;
461
  }
462
  // handle argument
463
  else {
464
    if (strcmp(argv[1], "-h") == 0 || strcmp(argv[1], "--hibernate") == 0) {
465
      chEvtBroadcastFlags(&aos.events.os.source, AOS_SYSTEM_EVENTFLAGS_HIBERNATE);
466
      chThdTerminate(currp);
467
      return AOS_OK;
468
    }
469
    else if (strcmp(argv[1], "-d") == 0 || strcmp(argv[1], "--deepsleep") == 0) {
470
      chEvtBroadcastFlags(&aos.events.os.source, AOS_SYSTEM_EVENTFLAGS_DEEPSLEEP);
471
      chThdTerminate(currp);
472
      return AOS_OK;
473
    }
474
    else if (strcmp(argv[1], "-t") == 0 || strcmp(argv[1], "--transportation") == 0) {
475
      chEvtBroadcastFlags(&aos.events.os.source, AOS_SYSTEM_EVENTFLAGS_TRANSPORTATION);
476
      chThdTerminate(currp);
477
      return AOS_OK;
478
    }
479
    else if (strcmp(argv[1], "-r") == 0 || strcmp(argv[1], "--restart") == 0) {
480
      chEvtBroadcastFlags(&aos.events.os.source, AOS_SYSTEM_EVENTFLAGS_RESTART);
481
      chThdTerminate(currp);
482
      return AOS_OK;
483
    }
484
    else {
485
      chprintf(stream, "unknown argument %s\n", argv[1]);
486
      return AOS_INVALID_ARGUMENTS;
487
    }
488
  }
489
}
490
#endif /* AMIROOS_CFG_SHELL_ENABLE == true */
491

    
492
#if (AMIROOS_CFG_TESTS_ENABLE == true) || defined(__DOXYGEN__)
493
/**
494
 * @brief   Callback function for the kernel:test shell command.
495
 *
496
 * @param[in] stream    The I/O stream to use.
497
 * @param[in] argc      Number of arguments.
498
 * @param[in] argv      List of pointers to the arguments.
499
 *
500
 * @return      An exit status.
501
 */
502
static int _shellcmd_kerneltestcb(BaseSequentialStream* stream, int argc, char* argv[])
503
{
504
  aosDbgCheck(stream != NULL);
505

    
506
  (void)argc;
507
  (void)argv;
508

    
509
  tprio_t prio = chThdGetPriorityX();
510
  chThdSetPriority(HIGHPRIO - 5); // some tests increase priorirty by 5, so this is the maximum priority permitted
511
  msg_t retval = test_execute(stream);
512
  chThdSetPriority(prio);
513

    
514
  return retval;
515
}
516
#endif /* AMIROOS_CFG_TESTS_ENABLE == true */
517

    
518
/**
519
 * @brief   Callback function for the PD signal interrupt.
520
 *
521
 * @param[in] extp      Pointer to the interrupt driver object.
522
 * @param[in] channel   Interrupt channel identifier.
523
 */
524
static void _signalPdCallback(EXTDriver* extp, expchannel_t channel)
525
{
526
  (void)extp;
527
  (void)channel;
528

    
529
  chSysLockFromISR();
530
  chEvtBroadcastFlagsI(&aos.events.io.source, aos.events.io.flagsSignalPd);
531
  chSysUnlockFromISR();
532

    
533
  return;
534
}
535

    
536
/**
537
 * @brief   Callback function for the Sync signal interrupt.
538
 *
539
 * @param[in] extp      Pointer to the interrupt driver object.
540
 * @param[in] channel   Interrupt channel identifier.
541
 */
542
static void _signalSyncCallback(EXTDriver* extp, expchannel_t channel)
543
{
544
  (void)extp;
545
  (void)channel;
546

    
547
#if (AMIROOS_CFG_SSSP_MASTER == true)
548
  chSysLockFromISR();
549
  chEvtBroadcastFlagsI(&aos.events.io.source, aos.events.io.flagsSignalSync);
550
  chSysUnlockFromISR();
551
#else
552
  apalControlGpioState_t s_state;
553
  aos_timestamp_t uptime;
554

    
555
  chSysLockFromISR();
556
  // get current uptime
557
  aosSysGetUptimeX(&uptime);
558
  // read signal S
559
  apalControlGpioGet(_gpioSync, &s_state);
560
  // if S was toggled from on to off during SSSP operation phase
561
  if (aos.ssspStage == AOS_SSSP_OPERATION && s_state == APAL_GPIO_OFF) {
562
    // align the uptime with the synchronization period
563
    if (uptime % AMIROOS_CFG_SSSP_SYSSYNCPERIOD < AMIROOS_CFG_SSSP_SYSSYNCPERIOD / 2) {
564
      _uptime -= uptime % AMIROOS_CFG_SSSP_SYSSYNCPERIOD;
565
    } else {
566
      _uptime += AMIROOS_CFG_SSSP_SYSSYNCPERIOD - (uptime % AMIROOS_CFG_SSSP_SYSSYNCPERIOD);
567
    }
568
  }
569
  // broadcast event
570
  chEvtBroadcastFlagsI(&aos.events.io.source, aos.events.io.flagsSignalSync);
571
  chSysUnlockFromISR();
572
#endif
573

    
574
  return;
575
}
576

    
577
/**
578
 * @brief   Callback function for the uptime accumulation timer.
579
 *
580
 * @param[in] par   Generic parameter.
581
 */
582
#include <module.h>
583
static void _uptimeCallback(void* par)
584
{
585
  (void)par;
586

    
587
  chSysLockFromISR();
588
  // read current time in system ticks
589
  register const systime_t st = chVTGetSystemTimeX();
590
  // update the uptime variables
591
  _uptime += LL_ST2US(st - _synctime);
592
  _synctime = st;
593
  // enable the timer again
594
  chVTSetI(&_systimer, SYSTIMER_PERIOD, &_uptimeCallback, NULL);
595
  chSysUnlockFromISR();
596

    
597
  return;
598
}
599

    
600
#if (AMIROOS_CFG_SSSP_MASTER == true) || defined (__DOXYGEN__)
601
/**
602
 * @brief   Periodic system synchronization callback function.
603
 * @details Toggles the SYS_SYNC signal and reconfigures the system synchronization timer.
604
 *
605
 * @param[in] par   Unuesed parameters.
606
 */
607
static void _sysSyncTimerCallback(void* par)
608
{
609
  (void)par;
610

    
611
  apalControlGpioState_t s_state;
612
  aos_timestamp_t uptime;
613

    
614
  chSysLockFromISR();
615
  // read and toggle signal S
616
  apalControlGpioGet(_gpioSync, &s_state);
617
  s_state = (s_state == APAL_GPIO_ON) ? APAL_GPIO_OFF : APAL_GPIO_ON;
618
  apalControlGpioSet(_gpioSync, s_state);
619
  // if S was toggled from off to on
620
  if (s_state == APAL_GPIO_ON) {
621
    // reconfigure the timer precisely, because the logically falling edge (next interrupt) snychronizes the system time
622
    _syssynctime += AMIROOS_CFG_SSSP_SYSSYNCPERIOD;
623
    aosSysGetUptimeX(&uptime);
624
    chVTSetI(&_syssynctimer, LL_US2ST(_syssynctime - uptime), _sysSyncTimerCallback, NULL);
625
  }
626
  // if S was toggled from on to off
627
  else /* if (s_state == APAL_GPIO_OFF) */ {
628
    // reconfigure the timer (lazy)
629
    chVTSetI(&_syssynctimer, LL_US2ST(AMIROOS_CFG_SSSP_SYSSYNCPERIOD / 2), _sysSyncTimerCallback, NULL);
630
  }
631
  chSysUnlockFromISR();
632

    
633
  return;
634
}
635
#endif
636

    
637
/**
638
 * @brief   AMiRo-OS system initialization.
639
 * @note    Must be called from the system control thread (usually main thread).
640
 *
641
 * @param[in] extDrv        Pointer to the interrupt driver.
642
 * @param[in] extCfg        Configuration for the interrupt driver.
643
 * @param[in] gpioPd        GPIO of the PD signal.
644
 * @param[in] gpioSync      GPIO of the Sync signal
645
 * @param[in] evtFlagsPd    Event flags to be set when a PD interrupt occurs.
646
 * @param[in] evtFlagsSync  Event flags to be set when a Sync interrupt occurs.
647
 * @param[in] shellPrompt   String to be printed as prompt of the system shell.
648
 * @param[in] stdio         Default (usually physically) interface for I/O like shell.
649
 */
650
void aosSysInit(EXTDriver* extDrv,
651
                EXTConfig* extCfg,
652
                apalControlGpio_t* gpioPd,
653
                apalControlGpio_t* gpioSync,
654
                eventflags_t evtFlagsPd,
655
                eventflags_t evtFlagsSync,
656
                const char* shellPrompt)
657
{
658
  // check arguments
659
  aosDbgCheck(extDrv != NULL);
660
  aosDbgCheck(extCfg != NULL);
661
  aosDbgCheck(gpioPd != NULL);
662
  aosDbgCheck(gpioSync != NULL);
663

    
664
  // set control thread to maximum priority
665
  chThdSetPriority(THD_CTRLPRIO);
666

    
667
  // set local variables
668
  _gpioPd = gpioPd;
669
  _gpioSync = gpioSync;
670
  chVTObjectInit(&_systimer);
671
  _synctime = 0;
672
  _uptime = 0;
673
#if (AMIROOS_CFG_SSSP_MASTER == true)
674
  chVTObjectInit(&_syssynctimer);
675
  _syssynctime = 0;
676
#endif
677

    
678
  // set aos configuration
679
  aos.ssspStage = AOS_SSSP_STARTUP_2_1;
680
  aosIOStreamInit(&aos.iostream);
681
  chEvtObjectInit(&aos.events.io.source);
682
  chEvtObjectInit(&aos.events.os.source);
683
  aos.events.io.flagsSignalPd = evtFlagsPd;
684
  aos.events.io.flagsSignalSync = evtFlagsSync;
685

    
686
  // setup external interrupt system
687
  extCfg->channels[gpioPd->gpio->pad].cb = _signalPdCallback;
688
  extCfg->channels[gpioSync->gpio->pad].cb = _signalSyncCallback;
689
  extStart(extDrv, extCfg);
690

    
691
#if (AMIROOS_CFG_SHELL_ENABLE == true)
692
  // init shell
693
  aosShellInit(aos.shell,
694
               &aos.events.os.source,
695
               shellPrompt,
696
               _shell_line,
697
               AMIROOS_CFG_SHELL_LINEWIDTH,
698
               _shell_arglist,
699
               AMIROOS_CFG_SHELL_MAXARGS);
700
  // add system commands
701
  aosShellAddCommand(aos.shell, &_shellcmd_config);
702
  aosShellAddCommand(aos.shell, &_shellcmd_info);
703
  aosShellAddCommand(aos.shell, &_shellcmd_shutdown);
704
#if (AMIROOS_CFG_TESTS_ENABLE == true)
705
  aosShellAddCommand(aos.shell, &_shellcmd_kerneltest);
706
#endif
707
#else
708
  (void)shellPrompt;
709
#endif
710

    
711
  return;
712
}
713

    
714
/**
715
 * @brief   Starts the system and all system threads.
716
 */
717
inline void aosSysStart(void)
718
{
719
  // update the system SSSP stage
720
  aos.ssspStage = AOS_SSSP_OPERATION;
721

    
722
  // print system information;
723
  _printSystemInfo((BaseSequentialStream*)&aos.iostream);
724
  aosprintf("\n");
725

    
726
#if (AMIROOS_CFG_SHELL_ENABLE == true)
727
  // start system shell thread
728
  aos.shell->thread = chThdCreateStatic(_shell_wa, sizeof(_shell_wa), THD_LOWPRIO_MIN, aosShellThread, aos.shell);
729
#endif
730

    
731
  return;
732
}
733

    
734
/**
735
 * @brief   Implements the SSSP startup synchronization step.
736
 *
737
 * @param[in] syncEvtListener   Event listener that receives the Sync event.
738
 *
739
 * @return    If another event that the listener is interested in was received, its mask is returned.
740
 *            Otherwise an empty mask (0) is returned.
741
 */
742
eventmask_t aosSysSsspStartupOsInitSyncCheck(event_listener_t* syncEvtListener)
743
{
744
  aosDbgCheck(syncEvtListener != NULL);
745

    
746
  // local variables
747
  eventmask_t m;
748
  eventflags_t f;
749
  apalControlGpioState_t s;
750

    
751
  // update the system SSSP stage
752
  aos.ssspStage = AOS_SSSP_STARTUP_2_2;
753

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

    
757
  // wait for any event to occur (do not apply any filter in order not to miss any event)
758
  m = chEvtWaitOne(ALL_EVENTS);
759
  f = chEvtGetAndClearFlags(syncEvtListener);
760
  apalControlGpioGet(_gpioSync, &s);
761

    
762
  // if the event was a system event,
763
  //   and it was fired because of the SysSync control signal,
764
  //   and the SysSync control signal has been deactivated
765
  if (m & syncEvtListener->events &&
766
      f == aos.events.io.flagsSignalSync &&
767
      s == APAL_GPIO_OFF) {
768
    chSysLock();
769
#if (AMIROOS_CFG_SSSP_MASTER == true)
770
    // start the systen synchronization counter
771
    chVTSetI(&_syssynctimer, LL_US2ST(AMIROOS_CFG_SSSP_SYSSYNCPERIOD / 2), &_sysSyncTimerCallback, NULL);
772
#endif
773
    // start the uptime counter
774
    _synctime = chVTGetSystemTimeX();
775
    _uptime = 0;
776
    chVTSetI(&_systimer, SYSTIMER_PERIOD, &_uptimeCallback, NULL);
777
    chSysUnlock();
778

    
779
    return 0;
780
  }
781
  // an unexpected event occurred
782
  else {
783
    // reassign the flags to the event and return the event mask
784
    syncEvtListener->flags |= f;
785
    return m;
786
  }
787
}
788

    
789
/**
790
 * @brief   Retrieves the system uptime.
791
 *
792
 * @param[out] ut   The system uptime.
793
 */
794
inline void aosSysGetUptimeX(aos_timestamp_t* ut)
795
{
796
  aosDbgCheck(ut != NULL);
797

    
798
  *ut = _uptime + LL_ST2US(chVTGetSystemTimeX() - _synctime);
799

    
800
  return;
801
}
802

    
803
/**
804
 * @brief   Initializes/Acknowledges a system shutdown/restart request.
805
 * @note    This functions should be called from the thread with highest priority.
806
 *
807
 * @param[in] shutdown    Type of shutdown.
808
 */
809
void aosSysShutdownInit(aos_shutdown_t shutdown)
810
{
811
  // check arguments
812
  aosDbgCheck(shutdown != AOS_SHUTDOWN_NONE);
813

    
814
#if (AMIROOS_CFG_SSSP_MASTER == true)
815
  // deactivate the system synchronization timer
816
  chVTReset(&_syssynctimer);
817
#endif
818

    
819
  // update the system SSSP stage
820
  aos.ssspStage = AOS_SSSP_SHUTDOWN_1_1;
821

    
822
  // activate the SYS_PD control signal only, if this module initiated the shutdown
823
  chSysLock();
824
  if (shutdown != AOS_SHUTDOWN_PASSIVE) {
825
    apalControlGpioSet(_gpioPd, APAL_GPIO_ON);
826
  }
827
  // activate the SYS_SYNC signal
828
  apalControlGpioSet(_gpioSync, APAL_GPIO_ON);
829
  chSysUnlock();
830

    
831
  switch (shutdown) {
832
    case AOS_SHUTDOWN_PASSIVE:
833
      chEvtBroadcastFlags(&aos.events.os.source, AOS_SYSTEM_EVENTFLAGS_SHUTDOWN);
834
      aosprintf("shutdown request received...\n");
835
      break;
836
    case AOS_SHUTDOWN_HIBERNATE:
837
      chEvtBroadcastFlags(&aos.events.os.source, AOS_SYSTEM_EVENTFLAGS_HIBERNATE);
838
      aosprintf("shutdown to hibernate mode...\n");
839
      break;
840
    case AOS_SHUTDOWN_DEEPSLEEP:
841
      chEvtBroadcastFlags(&aos.events.os.source, AOS_SYSTEM_EVENTFLAGS_DEEPSLEEP);
842
      aosprintf("shutdown to deepsleep mode...\n");
843
      break;
844
    case AOS_SHUTDOWN_TRANSPORTATION:
845
      chEvtBroadcastFlags(&aos.events.os.source, AOS_SYSTEM_EVENTFLAGS_TRANSPORTATION);
846
      aosprintf("shutdown to transportation mode...\n");
847
      break;
848
    case AOS_SHUTDOWN_RESTART:
849
      chEvtBroadcastFlags(&aos.events.os.source, AOS_SYSTEM_EVENTFLAGS_RESTART);
850
      aosprintf("restarting system...\n");
851
      break;
852
   // must never occur
853
   case AOS_SHUTDOWN_NONE:
854
   default:
855
      break;
856
  }
857

    
858
  // update the system SSSP stage
859
  aos.ssspStage = AOS_SSSP_SHUTDOWN_1_2;
860

    
861
  return;
862
}
863

    
864
/**
865
 * @brief   Stops the system and all related threads (not the thread this function is called from).
866
 */
867
void aosSysStop(void)
868
{
869
#if (AMIROOS_CFG_SHELL_ENABLE == true)
870
  chThdWait(aos.shell->thread);
871
#endif
872

    
873
  return;
874
}
875

    
876
/**
877
 * @brief   Deinitialize all system variables.
878
 */
879
void aosSysDeinit(void)
880
{
881
  return;
882
}
883

    
884
/**
885
 * @brief   Finally shuts down the system and calls the bootloader callback function.
886
 * @note    This function should be called from the thtead with highest priority.
887
 *
888
 * @param[in] extDrv      Pointer to the interrupt driver.
889
 * @param[in] shutdown    Type of shutdown.
890
 */
891
void aosSysShutdownFinal(EXTDriver* extDrv, aos_shutdown_t shutdown)
892
{
893
  // check arguments
894
  aosDbgCheck(extDrv != NULL);
895
  aosDbgCheck(shutdown != AOS_SHUTDOWN_NONE);
896

    
897
  // stop external interrupt system
898
  extStop(extDrv);
899

    
900
  // update the system SSSP stage
901
  aos.ssspStage = AOS_SSSP_SHUTDOWN_1_3;
902

    
903
  // call bootloader callback depending on arguments
904
  switch (shutdown) {
905
    case AOS_SHUTDOWN_PASSIVE:
906
      BL_CALLBACK_TABLE_ADDRESS->cbHandleShutdownRequest();
907
      break;
908
    case AOS_SHUTDOWN_HIBERNATE:
909
      BL_CALLBACK_TABLE_ADDRESS->cbShutdownHibernate();
910
      break;
911
    case AOS_SHUTDOWN_DEEPSLEEP:
912
      BL_CALLBACK_TABLE_ADDRESS->cbShutdownDeepsleep();
913
      break;
914
    case AOS_SHUTDOWN_TRANSPORTATION:
915
      BL_CALLBACK_TABLE_ADDRESS->cbShutdownTransportation();
916
      break;
917
    case AOS_SHUTDOWN_RESTART:
918
      BL_CALLBACK_TABLE_ADDRESS->cbShutdownRestart();
919
      break;
920
    // must never occur
921
    case AOS_SHUTDOWN_NONE:
922
    default:
923
      break;
924
  }
925

    
926
  return;
927
}