Statistics
| Branch: | Tag: | Revision:

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

History | View | Annotate | Download (29.1 KB)

1 e545e620 Thomas Schöpping
/*
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
/* forward declarations */
41
static void _printSystemInfo(BaseSequentialStream* stream);
42
#if (AMIROOS_CFG_SHELL_ENABLE == true)
43
static int _shellcmd_configcb(BaseSequentialStream* stream, int argc, char* argv[]);
44
static int _shellcmd_infocb(BaseSequentialStream* stream, int argc, char* argv[]);
45
static int _shellcmd_shutdowncb(BaseSequentialStream* stream, int argc, char* argv[]);
46
#endif /* AMIROOS_CFG_SHELL_ENABLE == true */
47
#if (AMIROOS_CFG_TESTS_ENABLE == true)
48
static int _shellcmd_kerneltestcb(BaseSequentialStream* stream, int argc, char* argv[]);
49
#endif /* AMIROOS_CFG_TESTS_ENABLE == true */
50
51
/**
52
 * @brief   PD signal GPIO.
53
 */
54
static apalControlGpio_t* _gpioPd;
55
56
/**
57
 * @brief   Sync signal GPIO.
58
 */
59
static apalControlGpio_t* _gpioSync;
60
61
/**
62
 * @brief   Sequelntiel Stream Multiplexer for the system I/O stream.
63
 */
64
static SequentialStreamMux _ssm;
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
  /* event      */ {
159
    /* I/O      */ {
160
      /* source           */ {
161
        /* next listener  */ NULL,
162
      },
163
      /* flagsSignalPd    */ 0,
164
      /* flagsSignalSync  */ 0,
165
    },
166
    /* OS */ {
167
      /* source */ {
168
        /* next listener  */ NULL,
169
      }
170
    },
171
  },
172
  /* ssm        */ &_ssm,
173
#if (AMIROOS_CFG_SHELL_ENABLE == true)
174
  /* shell      */ &_shell,
175
#endif
176
};
177
178
/**
179
 * @brief   Print a separator line.
180
 *
181
 * @param[in] stream    Stream to print to.
182
 * @param[in] c         Character to use.
183
 * @param[in] n         Length of the separator line.
184
 *
185
 * @return  Number of characters printed.
186
 */
187
static unsigned int _printSystemInfoSeparator(BaseSequentialStream* stream, const char c, const unsigned int n)
188
{
189
  aosDbgCheck(stream != NULL);
190
191
  // print the specified character n times
192
  for (unsigned int i = 0; i < n; ++i) {
193
    streamPut(stream, c);
194
  }
195
  streamPut(stream, '\n');
196
197
  return n+1;
198
}
199
200
/**
201
 * @brief   Print a system information line.
202
 * @details Prints a system information line with the following format:
203
 *            "<name>[spaces]fmt"
204
 *          The combined width of "<name>[spaces]" can be specified in order to align <fmt> on multiple lines.
205
 *          Note that there is not trailing newline added implicitely.
206
 *
207
 * @param[in] stream      Stream to print to.
208
 * @param[in] name        Name of the entry/line.
209
 * @param[in] namewidth   Width of the name column.
210
 * @param[in] fmt         Formatted string of information content.
211
 *
212
 * @return  Number of characters printed.
213
 */
214
static unsigned int _printSystemInfoLine(BaseSequentialStream* stream, const char* name, const unsigned int namewidth, const char* fmt, ...)
215
{
216
  aosDbgCheck(stream != NULL);
217
  aosDbgCheck(stream != NULL);
218
219
  unsigned int n = 0;
220
221
  // print the name and trailing spaces
222
  n += chprintf(stream, name);
223
  while (n < namewidth) {
224
    streamPut(stream, ' ');
225
    ++n;
226
  }
227
228
  // print the content
229
  va_list ap;
230
  va_start(ap, fmt);
231
  n += chvprintf(stream, fmt, ap);
232
  va_end(ap);
233
234
  return n;
235
}
236
237
/**
238
 * @brief   Prints information about the system.
239
 *
240
 * @param[in] stream    Stream to print to.
241
 */
242
static void _printSystemInfo(BaseSequentialStream *stream)
243
{
244
  aosDbgCheck(stream != NULL);
245
246
  _printSystemInfoSeparator(stream, '=', SYSTEM_INFO_WIDTH);
247
  _printSystemInfoLine(stream, "Module", 14, "%s (v%s)\n", BOARD_NAME, BOARD_VERSION);
248
#ifdef PLATFORM_NAME
249
  _printSystemInfoLine(stream, "Platform", 14, "%s\n", PLATFORM_NAME);
250
#endif
251
#ifdef PORT_CORE_VARIANT_NAME
252
  _printSystemInfoLine(stream, "Core Variant", 14, "%s\n", PORT_CORE_VARIANT_NAME);
253
#endif
254
  _printSystemInfoLine(stream, "Architecture", 14, "%s\n", PORT_ARCHITECTURE_NAME);
255
  _printSystemInfoSeparator(stream, '-', SYSTEM_INFO_WIDTH);
256
  _printSystemInfoLine(stream, "AMiRo-OS" ,14, "%u.%u.%u %s (%s build)\n", AMIROOS_VERSION_MAJOR, AMIROOS_VERSION_MINOR, AMIROOS_VERSION_PATCH, AMIROOS_RELEASE_TYPE, (AMIROOS_CFG_DBG == true) ? "debug" : "release");
257
  _printSystemInfoLine(stream, "AMiRo-LLD" ,14, "%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);
258
  _printSystemInfoLine(stream, "ChibiOS/RT" ,14, "%u.%u.%u %s\n", CH_KERNEL_MAJOR, CH_KERNEL_MINOR, CH_KERNEL_PATCH, (CH_KERNEL_STABLE == 1) ? "stable" : "non-stable");
259
  _printSystemInfoLine(stream, "ChibiOS/HAL",14, "%u.%u.%u %s\n", CH_HAL_MAJOR, CH_HAL_MINOR, CH_HAL_PATCH, (CH_HAL_STABLE == 1) ? "stable" : "non-stable");
260
  _printSystemInfoLine(stream, "Compiler" ,14, "%s %u.%u.%u\n", "GCC", __GNUC__, __GNUC_MINOR__, __GNUC_PATCHLEVEL__); // TODO: support other compilers than GCC
261
  _printSystemInfoLine(stream, "Compiled" ,14, "%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", 14, "%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
    _printSystemInfoLine(stream, "Compiler", 14, "%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
273
  } else {
274
    chprintf(stream, "Bootloader incompatible or not available.\n");
275
  }
276
  _printSystemInfoSeparator(stream, '=', SYSTEM_INFO_WIDTH);
277
278
  return;
279
}
280
281
#if (AMIROOS_CFG_SHELL_ENABLE == true) || defined(__DOXYGEN__)
282
/**
283
 * @brief   Callback function for the system:config shell command.
284
 *
285
 * @param[in] stream    The I/O stream to use.
286
 * @param[in] argc      Number of arguments.
287
 * @param[in] argv      List of pointers to the arguments.
288
 *
289
 * @return              An exit status.
290
 * @retval  AOS_OK                  The command was executed successfuly.
291
 * @retval  AOS_INVALID_ARGUMENTS   There was an issue with the arguemnts.
292
 */
293
static int _shellcmd_configcb(BaseSequentialStream* stream, int argc, char* argv[])
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;
319
              retval = AOS_OK;
320
            }
321
            else if (strcmp(argv[3], "uptime") == 0) {
322
              aos.shell->config |= AOS_SHELL_CONFIG_PROMPT_UPTIME;
323
              retval = AOS_OK;
324
            }
325
          }
326
        }
327
        // if the user wants to modify the string matching
328
        else if (strcmp(argv[2], "match") == 0) {
329
          // there must be a further argument
330
          if (argc > 3) {
331
            if (strcmp(argv[3], "casesensitive") == 0) {
332
              aos.shell->config |= AOS_SHELL_CONFIG_MATCH_CASE;
333
              retval = AOS_OK;
334
            }
335
            else if (strcmp(argv[3], "caseinsensitive") == 0) {
336
              aos.shell->config &= ~AOS_SHELL_CONFIG_MATCH_CASE;
337
              retval = AOS_OK;
338
            }
339
          }
340
        }
341
      }
342
      // if the user wants to retrieve the shell configuration
343
      else {
344
        chprintf(stream, "current shell configuration:\n");
345
        chprintf(stream, "  prompt text:   %s\n",
346
                 (aos.shell->prompt != NULL) ? aos.shell->prompt : "n/a");
347
        chprintf(stream, "  prompt style:  %s, %s\n",
348
                 (aos.shell->config & AOS_SHELL_CONFIG_PROMPT_MINIMAL) ? "minimal" : "text",
349
                 (aos.shell->config & AOS_SHELL_CONFIG_PROMPT_UPTIME) ? "system uptime" : "no time");
350
        chprintf(stream, "  input method:  %s\n",
351
                 (aos.shell->config & AOS_SHELL_CONFIG_INPUT_OVERWRITE) ? "replace" : "insert");
352
        chprintf(stream, "  text matching: %s\n",
353
                 (aos.shell->config & AOS_SHELL_CONFIG_MATCH_CASE) ? "case sensitive" : "case insensitive");
354
        retval = AOS_OK;
355
      }
356
    }
357
  }
358
359
  // print help, if required
360
  if (retval == AOS_INVALID_ARGUMENTS) {
361
    chprintf(stream, "Usage: %s OPTION\n", argv[0]);
362
    chprintf(stream, "Options:\n");
363
    chprintf(stream, "  --help\n");
364
    chprintf(stream, "    Print this help text.\n");
365
    chprintf(stream, "  --shell [OPT [VAL]]\n");
366
    chprintf(stream, "    Set or retrieve shell configuration.\n");
367
    chprintf(stream, "    Possible OPTs and VALs are:\n");
368
    chprintf(stream, "      prompt text|minimal|uptime|notime\n");
369
    chprintf(stream, "        Configures the prompt.\n");
370
    chprintf(stream, "      match casesensitive|caseinsenitive\n");
371
    chprintf(stream, "        Configures string matching.\n");
372
  }
373
374
  return (argc > 1 && strcmp(argv[1], "--help") == 0) ? AOS_OK : retval;
375
}
376
377
/**
378
 * @brief   Callback function for the system:info shell command.
379
 *
380
 * @param[in] stream    The I/O stream to use.
381
 * @param[in] argc      Number of arguments.
382
 * @param[in] argv      List of pointers to the arguments.
383
 *
384
 * @return            An exit status.
385
 * @retval  AOS_OK    The command was executed successfully.
386
 */
387
static int _shellcmd_infocb(BaseSequentialStream* stream, int argc, char* argv[])
388
{
389
  (void)argc;
390
  (void)argv;
391
392
  // print system information
393
  _printSystemInfo(stream);
394
395
  // print time measurement precision
396
  chprintf(stream, "system time resolution: %uus\n", AOS_SYSTEM_TIME_RESOLUTION);
397
398
  // print system uptime
399
  aos_timestamp_t uptime;
400
  aosSysGetUptime(&uptime);
401
  chprintf(stream, "The system is running for\n");
402
  chprintf(stream, "%10u days\n", (uint32_t)(uptime / MICROSECONDS_PER_DAY));
403
  chprintf(stream, "%10u hours\n", (uint8_t)(uptime % MICROSECONDS_PER_DAY / MICROSECONDS_PER_HOUR));
404
  chprintf(stream, "%10u minutes\n", (uint8_t)(uptime % MICROSECONDS_PER_HOUR / MICROSECONDS_PER_MINUTE));
405
  chprintf(stream, "%10u seconds\n", (uint8_t)(uptime % MICROSECONDS_PER_MINUTE / MICROSECONDS_PER_SECOND));
406
  chprintf(stream, "%10u milliseconds\n", (uint16_t)(uptime % MICROSECONDS_PER_SECOND / MICROSECONDS_PER_MILLISECOND));
407
  chprintf(stream, "%10u microseconds\n", (uint16_t)(uptime % MICROSECONDS_PER_MILLISECOND / MICROSECONDS_PER_MICROSECOND));
408
409
  return AOS_OK;
410
}
411
412
/**
413
 * @brief   Callback function for the sytem:shutdown shell command.
414
 *
415
 * @param[in] stream    The I/O stream to use.
416
 * @param[in] argc      Number of arguments.
417
 * @param[in] argv      List of pointers to the arguments.
418
 *
419
 * @return              An exit status.
420
 * @retval  AOS_OK                  The command was executed successfully.
421
 * @retval  AOS_INVALID_ARGUMENTS   There was an issue with the arguments.
422
 */
423
static int _shellcmd_shutdowncb(BaseSequentialStream* stream, int argc, char* argv[])
424
{
425
  // print help text
426
  if (argc != 2 || strcmp(argv[1], "--help") == 0) {
427
    chprintf(stream, "Usage: %s OPTION\n", argv[0]);
428
    chprintf(stream, "Options:\n");
429
    chprintf(stream, "  --help\n");
430
    chprintf(stream, "    Print this help text.\n");
431
    chprintf(stream, "  --hibernate, -h\n");
432
    chprintf(stream, "    Shutdown to hibernate mode.\n");
433
    chprintf(stream, "    Least energy saving, but allows charging via pins.\n");
434
    chprintf(stream, "  --deepsleep, -d\n");
435
    chprintf(stream, "    Shutdown to deepsleep mode.\n");
436
    chprintf(stream, "    Minimum energy consumption while allowing charging via plug.\n");
437
    chprintf(stream, "  --transportation, -t\n");
438
    chprintf(stream, "    Shutdown to transportation mode.\n");
439
    chprintf(stream, "    Minimum energy consumption with all interrupts disabled (no charging).\n");
440
    chprintf(stream, "  --restart, -r\n");
441
    chprintf(stream, "    Shutdown and restart system.\n");
442
443
    return (argc != 2) ? AOS_INVALID_ARGUMENTS : AOS_OK;
444
  }
445
  // handle argument
446
  else {
447
    if (strcmp(argv[1], "-h") == 0 || strcmp(argv[1], "--hibernate") == 0) {
448
      chEvtBroadcastFlags(&aos.events.os.source, AOS_SYSTEM_EVENTFLAGS_HIBERNATE);
449
      chThdExit(MSG_OK);
450
      return AOS_OK;
451
    }
452
    else if (strcmp(argv[1], "-d") == 0 || strcmp(argv[1], "--deepsleep") == 0) {
453
      chEvtBroadcastFlags(&aos.events.os.source, AOS_SYSTEM_EVENTFLAGS_DEEPSLEEP);
454
      chThdExit(MSG_OK);
455
      return AOS_OK;
456
    }
457
    else if (strcmp(argv[1], "-t") == 0 || strcmp(argv[1], "--transportation") == 0) {
458
      chEvtBroadcastFlags(&aos.events.os.source, AOS_SYSTEM_EVENTFLAGS_TRANSPORTATION);
459
      chThdExit(MSG_OK);
460
      return AOS_OK;
461
    }
462
    else if (strcmp(argv[1], "-r") == 0 || strcmp(argv[1], "--restart") == 0) {
463
      chEvtBroadcastFlags(&aos.events.os.source, AOS_SYSTEM_EVENTFLAGS_RESTART);
464
      chThdExit(MSG_OK);
465
      return AOS_OK;
466
    }
467
    else {
468
      chprintf(stream, "unknown argument %s\n", argv[1]);
469
      return AOS_INVALID_ARGUMENTS;
470
    }
471
  }
472
}
473
#endif /* AMIROOS_CFG_SHELL_ENABLE == true */
474
475
#if (AMIROOS_CFG_TESTS_ENABLE == true) || defined(__DOXYGEN__)
476
/**
477
 * @brief   Callback function for the kernel:test shell command.
478
 *
479
 * @param[in] stream    The I/O stream to use.
480
 * @param[in] argc      Number of arguments.
481
 * @param[in] argv      List of pointers to the arguments.
482
 *
483
 * @return      An exit status.
484
 */
485
static int _shellcmd_kerneltestcb(BaseSequentialStream* stream, int argc, char* argv[])
486
{
487
  (void)argc;
488
  (void)argv;
489
490
  tprio_t prio = chThdGetPriorityX();
491
  chThdSetPriority(HIGHPRIO - 5); // some tests increase priorirty by 5, so this is the maximum priority permitted
492
  msg_t retval = test_execute(stream);
493
  chThdSetPriority(prio);
494
495
  return retval;
496
}
497
#endif /* AMIROOS_CFG_TESTS_ENABLE == true */
498
499
/**
500
 * @brief   Callback function for the PD signal interrupt.
501
 *
502
 * @param[in] extp      Pointer to the interrupt driver object.
503
 * @param[in] channel   Interrupt channel identifier.
504
 */
505
static void _signalPdCallback(EXTDriver* extp, expchannel_t channel)
506
{
507
  (void)extp;
508
  (void)channel;
509
510
  chSysLockFromISR();
511
  chEvtBroadcastFlagsI(&aos.events.io.source, aos.events.io.flagsSignalPd);
512
  chSysUnlockFromISR();
513
514
  return;
515
}
516
517
/**
518
 * @brief   Callback function for the Sync signal interrupt.
519
 *
520
 * @param[in] extp      Pointer to the interrupt driver object.
521
 * @param[in] channel   Interrupt channel identifier.
522
 */
523
static void _signalSyncCallback(EXTDriver* extp, expchannel_t channel)
524
{
525
  (void)extp;
526
  (void)channel;
527
528
#if (AMIROOS_CFG_SSSP_MASTER == true)
529
  chSysLockFromISR();
530
  chEvtBroadcastFlagsI(&aos.events.io.source, aos.events.io.flagsSignalSync);
531
  chSysUnlockFromISR();
532
#else
533
  apalControlGpioState_t s_state;
534
  aos_timestamp_t uptime;
535
536
  chSysLockFromISR();
537
  // get current uptime
538
  aosSysGetUptimeX(&uptime);
539
  // read signal S
540
  apalControlGpioGet(_gpioSync, &s_state);
541
  // if S was toggled from on to off during SSSP operation phase
542
  if (aos.ssspStage == AOS_SSSP_OPERATION && s_state == APAL_GPIO_OFF) {
543
    // align the uptime with the synchronization period
544
    if (uptime % AMIROOS_CFG_SSSP_SYSSYNCPERIOD < AMIROOS_CFG_SSSP_SYSSYNCPERIOD / 2) {
545
      _uptime -= uptime % AMIROOS_CFG_SSSP_SYSSYNCPERIOD;
546
    } else {
547
      _uptime += AMIROOS_CFG_SSSP_SYSSYNCPERIOD - (uptime % AMIROOS_CFG_SSSP_SYSSYNCPERIOD);
548
    }
549
  }
550
  // broadcast event
551
  chEvtBroadcastFlagsI(&aos.events.io.source, aos.events.io.flagsSignalSync);
552
  chSysUnlockFromISR();
553
#endif
554
555
  return;
556
}
557
558
/**
559
 * @brief   Callback function for the uptime accumulation timer.
560
 *
561
 * @param[in] par   Generic parameter.
562
 */
563
#include <module.h>
564
static void _uptimeCallback(void* par)
565
{
566
  (void)par;
567
568
  chSysLockFromISR();
569
  // read current time in system ticks
570
  register const systime_t st = chVTGetSystemTimeX();
571
  // update the uptime variables
572
  _uptime += LL_ST2US(st - _synctime);
573
  _synctime = st;
574
  // enable the timer again
575
  chVTSetI(&_systimer, SYSTIMER_PERIOD, &_uptimeCallback, NULL);
576
  chSysUnlockFromISR();
577
578
  return;
579
}
580
581
#if (AMIROOS_CFG_SSSP_MASTER == true) || defined (__DOXYGEN__)
582
/**
583
 * @brief   Periodic system synchronization callback function.
584
 * @details Toggles the SYS_SYNC signal and reconfigures the system synchronization timer.
585
 *
586
 * @param[in] par   Unuesed parameters.
587
 */
588
static void _sysSyncTimerCallback(void* par)
589
{
590
  (void)par;
591
592
  apalControlGpioState_t s_state;
593
  aos_timestamp_t uptime;
594
595
  chSysLockFromISR();
596
  // read and toggle signal S
597
  apalControlGpioGet(_gpioSync, &s_state);
598
  s_state = (s_state == APAL_GPIO_ON) ? APAL_GPIO_OFF : APAL_GPIO_ON;
599
  apalControlGpioSet(_gpioSync, s_state);
600
  // if S was toggled from off to on
601
  if (s_state == APAL_GPIO_ON) {
602
    // reconfigure the timer precisely, because the logically falling edge (next interrupt) snychronizes the system time
603
    _syssynctime += AMIROOS_CFG_SSSP_SYSSYNCPERIOD;
604
    aosSysGetUptimeX(&uptime);
605
    chVTSetI(&_syssynctimer, LL_US2ST(_syssynctime - uptime), _sysSyncTimerCallback, NULL);
606
  }
607
  // if S was toggled from on to off
608
  else /* if (s_state == APAL_GPIO_OFF) */ {
609
    // reconfigure the timer (lazy)
610
    chVTSetI(&_syssynctimer, LL_US2ST(AMIROOS_CFG_SSSP_SYSSYNCPERIOD / 2), _sysSyncTimerCallback, NULL);
611
  }
612
  chSysUnlockFromISR();
613
614
  return;
615
}
616
#endif
617
618
/**
619
 * @brief   AMiRo-OS system initialization.
620
 * @note    Must be called from the system control thread (usually main thread).
621
 *
622
 * @param[in] extDrv        Pointer to the interrupt driver.
623
 * @param[in] extCfg        Configuration for the interrupt driver.
624
 * @param[in] gpioPd        GPIO of the PD signal.
625
 * @param[in] gpioSync      GPIO of the Sync signal
626
 * @param[in] evtFlagsPd    Event flags to be set when a PD interrupt occurs.
627
 * @param[in] evtFlagsSync  Event flags to be set when a Sync interrupt occurs.
628
 * @param[in] shellPrompt   String to be printed as prompt of the system shell.
629
 */
630
void aosSysInit(EXTDriver* extDrv,
631
                EXTConfig* extCfg,
632
                apalControlGpio_t* gpioPd,
633
                apalControlGpio_t* gpioSync,
634
                eventflags_t evtFlagsPd,
635
                eventflags_t evtFlagsSync,
636
                const char* shellPrompt)
637
{
638
  // check arguments
639
  aosDbgCheck(extDrv != NULL);
640
  aosDbgCheck(extCfg != NULL);
641
  aosDbgCheck(gpioPd != NULL);
642
  aosDbgCheck(gpioSync != NULL);
643
644
  // set control thread to maximum priority
645
  chThdSetPriority(THD_CTRLPRIO);
646
647
  // set local variables
648
  _gpioPd = gpioPd;
649
  _gpioSync = gpioSync;
650
  chVTObjectInit(&_systimer);
651
  _synctime = 0;
652
  _uptime = 0;
653
#if (AMIROOS_CFG_SSSP_MASTER == true)
654
  chVTObjectInit(&_syssynctimer);
655
  _syssynctime = 0;
656
#endif
657
658
  // set aos configuration
659
  aos.ssspStage = AOS_SSSP_STARTUP_2_1;
660
  chEvtObjectInit(&aos.events.io.source);
661
  chEvtObjectInit(&aos.events.os.source);
662
  aos.events.io.flagsSignalPd = evtFlagsPd;
663
  aos.events.io.flagsSignalSync = evtFlagsSync;
664
  ssmObjectInit(aos.ssm);
665
666
  // setup external interrupt system
667
  extCfg->channels[gpioPd->gpio->pad].cb = _signalPdCallback;
668
  extCfg->channels[gpioSync->gpio->pad].cb = _signalSyncCallback;
669
  extStart(extDrv, extCfg);
670
671
#if (AMIROOS_CFG_SHELL_ENABLE == true)
672
  // init shell
673
  aosShellInit(aos.shell,
674
               (BaseSequentialStream*)aos.ssm,
675
               shellPrompt,
676
               _shell_line,
677
               AMIROOS_CFG_SHELL_LINEWIDTH,
678
               _shell_arglist,
679
               AMIROOS_CFG_SHELL_MAXARGS);
680
  // add system commands
681
  aosShellAddCommand(aos.shell, &_shellcmd_config);
682
  aosShellAddCommand(aos.shell, &_shellcmd_info);
683
  aosShellAddCommand(aos.shell, &_shellcmd_shutdown);
684
#if (AMIROOS_CFG_TESTS_ENABLE == true)
685
  aosShellAddCommand(aos.shell, &_shellcmd_kerneltest);
686
#endif
687
#else
688
  (void)shellPrompt;
689
#endif
690
691
  return;
692
}
693
694
/**
695
 * @brief   Starts the system and all system threads.
696
 */
697
inline void aosSysStart(void)
698
{
699
  // update the system SSSP stage
700
  aos.ssspStage = AOS_SSSP_OPERATION;
701
702
  // prin system information
703
  _printSystemInfo(AOS_SYSTEM_STDIO);
704
  aosprintf("\n");
705
706
#if (AMIROOS_CFG_SHELL_ENABLE == true)
707
  // start system shell thread
708
  aos.shell->thread = chThdCreateStatic(_shell_wa, sizeof(_shell_wa), THD_LOWPRIO_MIN, aosShellThread, aos.shell);
709
#endif
710
711
  return;
712
}
713
714
/**
715
 * @brief   Implements the SSSP startup synchronization step.
716
 *
717
 * @param[in] syncEvtListener   Event listener that receives the Sync event.
718
 *
719
 * @return    If another event that the listener is interested in was received, its mask is returned.
720
 *            Otherwise an empty mask (0) is returned.
721
 */
722
eventmask_t aosSysSsspStartupOsInitSyncCheck(event_listener_t* syncEvtListener)
723
{
724
  aosDbgCheck(syncEvtListener != NULL);
725
726
  // local variables
727
  eventmask_t m;
728
  eventflags_t f;
729
  apalControlGpioState_t s;
730
731
  // update the system SSSP stage
732
  aos.ssspStage = AOS_SSSP_STARTUP_2_2;
733
734
  // deactivate the sync signal to indicate that the module is ready (SSSPv1 stage 2.1 of startup phase)
735
  apalControlGpioSet(_gpioSync, APAL_GPIO_OFF);
736
737
  // wait for any event to occur (do not apply any filter in order not to miss any event)
738
  m = chEvtWaitOne(ALL_EVENTS);
739
  f = chEvtGetAndClearFlags(syncEvtListener);
740
  apalControlGpioGet(_gpioSync, &s);
741
742
  // if the event was a system event,
743
  //   and it was fired because of the SysSync control signal,
744
  //   and the SysSync control signal has been deactivated
745
  if (m & syncEvtListener->events &&
746
      f == aos.events.io.flagsSignalSync &&
747
      s == APAL_GPIO_OFF) {
748
    chSysLock();
749
#if (AMIROOS_CFG_SSSP_MASTER == true)
750
    // start the systen synchronization counter
751
    chVTSetI(&_syssynctimer, LL_US2ST(AMIROOS_CFG_SSSP_SYSSYNCPERIOD / 2), &_sysSyncTimerCallback, NULL);
752
#endif
753
    // start the uptime counter
754
    _synctime = chVTGetSystemTimeX();
755
    _uptime = 0;
756
    chVTSetI(&_systimer, SYSTIMER_PERIOD, &_uptimeCallback, NULL);
757
    chSysUnlock();
758
759
    return 0;
760
  }
761
  // an unexpected event occurred
762
  else {
763
    // reassign the flags to the event and return the event mask
764
    syncEvtListener->flags |= f;
765
    return m;
766
  }
767
}
768
769
/**
770
 * @brief   Retrieves the system uptime.
771
 *
772
 * @param[out] ut   The system uptime.
773
 */
774
inline void aosSysGetUptimeX(aos_timestamp_t* ut)
775
{
776
  aosDbgCheck(ut != NULL);
777
778
  *ut = _uptime + LL_ST2US(chVTGetSystemTimeX() - _synctime);
779
780
  return;
781
}
782
783
/**
784
 * @brief   Initializes/Acknowledges a system shutdown/restart request.
785
 * @note    This functions should be called from the thread with highest priority.
786
 *
787
 * @param[in] shutdown    Type of shutdown.
788
 */
789
void aosSysShutdownInit(aos_shutdown_t shutdown)
790
{
791
  // check arguments
792
  aosDbgCheck(shutdown != AOS_SHUTDOWN_NONE);
793
794
#if (AMIROOS_CFG_SSSP_MASTER == true)
795
  // deactivate the system synchronization timer
796
  chVTReset(&_syssynctimer);
797
#endif
798
799
  // update the system SSSP stage
800
  aos.ssspStage = AOS_SSSP_SHUTDOWN_1_1;
801
802
  // activate the SYS_PD control signal only, if this module initiated the shutdown
803
  chSysLock();
804
  if (shutdown != AOS_SHUTDOWN_PASSIVE) {
805
    apalControlGpioSet(_gpioPd, APAL_GPIO_ON);
806
  }
807
  // activate the SYS_SYNC signal
808
  apalControlGpioSet(_gpioSync, APAL_GPIO_ON);
809
  chSysUnlock();
810
811
  switch (shutdown) {
812
    case AOS_SHUTDOWN_PASSIVE:
813
      aosprintf("shutdown request received...\n");
814
      break;
815
    case AOS_SHUTDOWN_HIBERNATE:
816
      aosprintf("shutdown to hibernate mode...\n");
817
      break;
818
    case AOS_SHUTDOWN_DEEPSLEEP:
819
      aosprintf("shutdown to deepsleep mode...\n");
820
      break;
821
    case AOS_SHUTDOWN_TRANSPORTATION:
822
      aosprintf("shutdown to transportation mode...\n");
823
      break;
824
    case AOS_SHUTDOWN_RESTART:
825
      aosprintf("restarting system...\n");
826
      break;
827
   // must never occur
828
   case AOS_SHUTDOWN_NONE:
829
   default:
830
      break;
831
  }
832
833
  // update the system SSSP stage
834
  aos.ssspStage = AOS_SSSP_SHUTDOWN_1_2;
835
836
  return;
837
}
838
839
/**
840
 * @brief   Stops the system and all related threads (not the thread this function is called from).
841
 */
842
void aosSysStop(void)
843
{
844
#if (AMIROOS_CFG_SHELL_ENABLE == true)
845
  chThdTerminate(aos.shell->thread);
846
#endif
847
848
  return;
849
}
850
851
/**
852
 * @brief   Deinitialize all system variables.
853
 */
854
void aosSysDeinit(void)
855
{
856
  aos.ssm->input = NULL;
857
858
  return;
859
}
860
861
/**
862
 * @brief   Finally shuts down the system and calls the bootloader callback function.
863
 * @note    This function should be called from the thtead with highest priority.
864
 *
865
 * @param[in] extDrv      Pointer to the interrupt driver.
866
 * @param[in] shutdown    Type of shutdown.
867
 */
868
void aosSysShutdownFinal(EXTDriver* extDrv, aos_shutdown_t shutdown)
869
{
870
  // check arguments
871
  aosDbgCheck(extDrv != NULL);
872
  aosDbgCheck(shutdown != AOS_SHUTDOWN_NONE);
873
874
  // stop external interrupt system
875
  extStop(extDrv);
876
877
  // update the system SSSP stage
878
  aos.ssspStage = AOS_SSSP_SHUTDOWN_1_3;
879
880
  // call bootloader callback depending on arguments
881
  switch (shutdown) {
882
    case AOS_SHUTDOWN_PASSIVE:
883
      BL_CALLBACK_TABLE_ADDRESS->cbHandleShutdownRequest();
884
      break;
885
    case AOS_SHUTDOWN_HIBERNATE:
886
      BL_CALLBACK_TABLE_ADDRESS->cbShutdownHibernate();
887
      break;
888
    case AOS_SHUTDOWN_DEEPSLEEP:
889
      BL_CALLBACK_TABLE_ADDRESS->cbShutdownDeepsleep();
890
      break;
891
    case AOS_SHUTDOWN_TRANSPORTATION:
892
      BL_CALLBACK_TABLE_ADDRESS->cbShutdownTransportation();
893
      break;
894
    case AOS_SHUTDOWN_RESTART:
895
      BL_CALLBACK_TABLE_ADDRESS->cbShutdownRestart();
896
      break;
897
    // must never occur
898
    case AOS_SHUTDOWN_NONE:
899
    default:
900
      break;
901
  }
902
903
  return;
904
}