Revision 27d0378b

View differences:

core/src/aos_main.cpp
1036 1036
   * There must be no delays at this point, thus no hook is allowed.
1037 1037
   */
1038 1038

  
1039
#if (AMIROOS_CFG_SSSP_ENABLE == true)
1039 1040
  /* SSSP startup stage 3 (module stack initialization) */
1040 1041
  if (shutdown == AOS_SHUTDOWN_NONE) {
1041 1042
    shutdown = _ssspModuleStackInitialization();
1042 1043
  }
1044
#endif
1043 1045

  
1044 1046
  /*
1045 1047
   * There must be no delays at this point, thus no hook is allowed.
core/src/aos_shell.c
270 270
 */
271 271
static void _printPrompt(aos_shell_t* shell)
272 272
{
273
/** commented out by simon welzel
273 274
  aosDbgCheck(shell != NULL);
274 275

  
275 276
  // print some time informattion before prompt if configured
......
311 312
  } else {
312 313
    chprintf((BaseSequentialStream*)&shell->stream, "%>$ ");
313 314
  }
314

  
315
*/
315 316
  return;
316 317
}
317 318

  
core/src/aos_system.c.autosave
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
/**
20
 * @file    aos_system.c
21
 * @brief   System code.
22
 * @details Contains system initialization and shutdown routines
23
 *          and system shell commands.
24
 *
25
 * @addtogroup aos_system
26
 * @{
27
 */
28

  
29
#include <aos_system.h>
30

  
31
#include <amiroos.h>
32
#include <amiroblt.h>
33
#include <module.h>
34
#include <string.h>
35
#include <stdlib.h>
36
#if (AMIROOS_CFG_TESTS_ENABLE == true)
37
#include <ch_test.h>
38
#include <rt_test_root.h>
39
#endif
40

  
41
/**
42
 * @brief   Period of the system timer.
43
 */
44
#define SYSTIMER_PERIOD               (TIME_MAX_SYSTIME - CH_CFG_ST_TIMEDELTA)
45

  
46
/**
47
 * @brief   Width of the printable system info text.
48
 */
49
#define SYSTEM_INFO_WIDTH             70
50

  
51
/**
52
 * @brief   Width of the name column of the system info table.
53
 */
54
#define SYSTEM_INFO_NAMEWIDTH         14
55

  
56
/* forward declarations */
57
static void _printSystemInfo(BaseSequentialStream* stream);
58
#if (AMIROOS_CFG_SHELL_ENABLE == true)
59
static int _shellcmd_configcb(BaseSequentialStream* stream, int argc, char* argv[]);
60
static int _shellcmd_infocb(BaseSequentialStream* stream, int argc, char* argv[]);
61
static int _shellcmd_shutdowncb(BaseSequentialStream* stream, int argc, char* argv[]);
62
#if (AMIROOS_CFG_TESTS_ENABLE == true)
63
static int _shellcmd_kerneltestcb(BaseSequentialStream* stream, int argc, char* argv[]);
64
#endif /* AMIROOS_CFG_TESTS_ENABLE == true */
65
#endif /* AMIROOS_CFG_SHELL_ENABLE == true */
66

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

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

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

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

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

  
94
#if ((AMIROOS_CFG_SSSP_MASTER != true) && (AMIROOS_CFG_PROFILE == true)) || defined(__DOXYGEN__)
95
/**
96
 * @brief   Offset between local clock and system wide synchronization signal.
97
 */
98
static float _syssyncskew;
99

  
100
/**
101
 * @brief   Weighting factor for the low-pass filter used for calculating the @p _syssyncskew value.
102
 */
103
#define SYSTEM_SYSSYNCSKEW_LPFACTOR   (0.1f / AOS_SYSTEM_TIME_RESOLUTION)
104
#endif
105

  
106
#if (AMIROOS_CFG_SHELL_ENABLE == true) || defined(__DOXYGEN__)
107
/**
108
 * @brief   Shell thread working area.
109
 */
110
THD_WORKING_AREA(_shell_wa, AMIROOS_CFG_SHELL_STACKSIZE);
111

  
112
/**
113
 * @brief   Shell input buffer.
114
 */
115
static char _shell_line[AMIROOS_CFG_SHELL_LINEWIDTH];
116

  
117
/**
118
 * @brief   Shell argument buffer.
119
 */
120
static char* _shell_arglist[AMIROOS_CFG_SHELL_MAXARGS];
121

  
122
/**
123
 * @brief   Shell command to retrieve system information.
124
 */
125
static aos_shellcommand_t _shellcmd_info = {
126
  /* name     */ "module:info",
127
  /* callback */ _shellcmd_infocb,
128
  /* next     */ NULL,
129
};
130

  
131
/**
132
 * @brief   Shell command to set or retrieve system configuration.
133
 */
134
static aos_shellcommand_t _shellcmd_config = {
135
  /* name     */ "module:config",
136
  /* callback */ _shellcmd_configcb,
137
  /* next     */ NULL,
138
};
139

  
140
/**
141
 * @brief   Shell command to shutdown the system.
142
 */
143
static aos_shellcommand_t _shellcmd_shutdown = {
144
  /* name     */ "system:shutdown",
145
  /* callback */ _shellcmd_shutdowncb,
146
  /* next     */ NULL,
147
};
148
#endif /* AMIROOS_CFG_SHELL_ENABLE == true */
149

  
150
#if (AMIROOS_CFG_TESTS_ENABLE == true) || defined(__DOXYGEN__)
151
/**
152
 * @brief   Shell kommand to run a test of the ChibiOS/RT kernel.
153
 */
154
static aos_shellcommand_t _shellcmd_kerneltest = {
155
  /* name     */ "kernel:test",
156
  /* callback */ _shellcmd_kerneltestcb,
157
  /* next     */ NULL,
158
};
159
#endif /* AMIROOS_CFG_TESTS_ENABLE == true */
160

  
161
/**
162
 * @brief   Global system object.
163
 */
164
aos_system_t aos;
165

  
166
/**
167
 * @brief   Print a separator line.
168
 *
169
 * @param[in] stream    Stream to print to or NULL to print to all system streams.
170
 * @param[in] c         Character to use.
171
 * @param[in] n         Length of the separator line.
172
 *
173
 * @return  Number of characters printed.
174
 */
175
static unsigned int _printSystemInfoSeparator(BaseSequentialStream* stream, const char c, const unsigned int n)
176
{
177
  aosDbgCheck(stream != NULL);
178

  
179
  // print the specified character n times
180
  for (unsigned int i = 0; i < n; ++i) {
181
    streamPut(stream, c);
182
  }
183
  streamPut(stream, '\n');
184

  
185
  return n+1;
186
}
187

  
188
/**
189
 * @brief   Print a system information line.
190
 * @details Prints a system information line with the following format:
191
 *            "<name>[spaces]fmt"
192
 *          The combined width of "<name>[spaces]" can be specified in order to align <fmt> on multiple lines.
193
 *          Note that there is not trailing newline added implicitely.
194
 *
195
 * @param[in] stream      Stream to print to or NULL to print to all system streams.
196
 * @param[in] name        Name of the entry/line.
197
 * @param[in] namewidth   Width of the name column.
198
 * @param[in] fmt         Formatted string of information content.
199
 *
200
 * @return  Number of characters printed.
201
 */
202
static unsigned int _printSystemInfoLine(BaseSequentialStream* stream, const char* name, const unsigned int namewidth, const char* fmt, ...)
203
{
204
  aosDbgCheck(stream != NULL);
205
  aosDbgCheck(name != NULL);
206

  
207
  unsigned int n = 0;
208
  va_list ap;
209

  
210
  va_start(ap, fmt);
211
  n += chprintf(stream, name);
212
  while (n < namewidth) {
213
    streamPut(stream, ' ');
214
    ++n;
215
  }
216
  n += chvprintf(stream, fmt, ap);
217
  va_end(ap);
218

  
219
  streamPut(stream, '\n');
220
  ++n;
221

  
222
  return n;
223
}
224

  
225
/**
226
 * @brief   Prints information about the system.
227
 *
228
 * @param[in] stream    Stream to print to.
229
 */
230
static void _printSystemInfo(BaseSequentialStream* stream)
231
{
232
  aosDbgCheck(stream != NULL);
233

  
234
  // local variables
235
  struct tm dt;
236
  aosSysGetDateTime(&dt);
237

  
238
  // print static information about module and operating system
239
  _printSystemInfoSeparator(stream, '=', SYSTEM_INFO_WIDTH);
240
  _printSystemInfoLine(stream, "Module", SYSTEM_INFO_NAMEWIDTH, "%s (v%s)", BOARD_NAME, BOARD_VERSION);
241
#ifdef PLATFORM_NAME
242
  _printSystemInfoLine(stream, "Platform", SYSTEM_INFO_NAMEWIDTH, "%s", PLATFORM_NAME);
243
#endif
244
#ifdef PORT_CORE_VARIANT_NAME
245
  _printSystemInfoLine(stream, "Core Variant", SYSTEM_INFO_NAMEWIDTH, "%s", PORT_CORE_VARIANT_NAME);
246
#endif
247
  _printSystemInfoLine(stream, "Architecture", SYSTEM_INFO_NAMEWIDTH, "%s", PORT_ARCHITECTURE_NAME);
248
  _printSystemInfoSeparator(stream, '-', SYSTEM_INFO_WIDTH);
249
  _printSystemInfoLine(stream, "AMiRo-OS" , SYSTEM_INFO_NAMEWIDTH, "%u.%u.%u %s (SSSP %u.%u)", AMIROOS_VERSION_MAJOR, AMIROOS_VERSION_MINOR, AMIROOS_VERSION_PATCH, AMIROOS_RELEASE_TYPE, AOS_SYSTEM_SSSP_VERSION_MAJOR, AOS_SYSTEM_SSSP_VERSION_MINOR);
250
  _printSystemInfoLine(stream, "AMiRo-LLD" , SYSTEM_INFO_NAMEWIDTH, "%u.%u.%u %s (periphAL %u.%u)", AMIRO_LLD_VERSION_MAJOR, AMIRO_LLD_VERSION_MINOR, AMIRO_LLD_VERSION_PATCH, AMIRO_LLD_RELEASE_TYPE, PERIPHAL_VERSION_MAJOR, PERIPHAL_VERSION_MINOR);
251
  _printSystemInfoLine(stream, "ChibiOS/RT" , SYSTEM_INFO_NAMEWIDTH, "%u.%u.%u %s", CH_KERNEL_MAJOR, CH_KERNEL_MINOR, CH_KERNEL_PATCH, (CH_KERNEL_STABLE == 1) ? "stable" : "non-stable");
252
  _printSystemInfoLine(stream, "ChibiOS/HAL", SYSTEM_INFO_NAMEWIDTH, "%u.%u.%u %s", CH_HAL_MAJOR, CH_HAL_MINOR, CH_HAL_PATCH, (CH_HAL_STABLE == 1) ? "stable" : "non-stable");
253
  _printSystemInfoLine(stream, "build type", SYSTEM_INFO_NAMEWIDTH,"%s", (AMIROOS_CFG_DBG == true) ? "debug" : "release");
254
  _printSystemInfoLine(stream, "Compiler" , SYSTEM_INFO_NAMEWIDTH, "%s %u.%u.%u", "GCC", __GNUC__, __GNUC_MINOR__, __GNUC_PATCHLEVEL__); // TODO: support other compilers than GCC
255
  _printSystemInfoLine(stream, "Compiled" , SYSTEM_INFO_NAMEWIDTH, "%s - %s", __DATE__, __TIME__);
256

  
257
  // print static information about the bootloader
258
  _printSystemInfoSeparator(stream, '-', SYSTEM_INFO_WIDTH);
259
  if (BL_CALLBACK_TABLE_ADDRESS->magicNumber == BL_MAGIC_NUMBER) {
260
    _printSystemInfoLine(stream, "AMiRo-BLT", SYSTEM_INFO_NAMEWIDTH, "%u.%u.%u %s (SSSP %u.%u)", BL_CALLBACK_TABLE_ADDRESS->vBootloader.major, BL_CALLBACK_TABLE_ADDRESS->vBootloader.minor, BL_CALLBACK_TABLE_ADDRESS->vBootloader.patch,
261
                         (BL_CALLBACK_TABLE_ADDRESS->vBootloader.identifier == BL_VERSION_ID_AMiRoBLT_Release) ? "stable" :
262
                         (BL_CALLBACK_TABLE_ADDRESS->vBootloader.identifier == BL_VERSION_ID_AMiRoBLT_ReleaseCandidate) ? "release candidate" :
263
                         (BL_CALLBACK_TABLE_ADDRESS->vBootloader.identifier == BL_VERSION_ID_AMiRoBLT_Beta) ? "beta" :
264
                         (BL_CALLBACK_TABLE_ADDRESS->vBootloader.identifier == BL_VERSION_ID_AMiRoBLT_Alpha) ? "alpha" :
265
                         (BL_CALLBACK_TABLE_ADDRESS->vBootloader.identifier == BL_VERSION_ID_AMiRoBLT_PreAlpha) ? "pre-alpha" :
266
                         "<release type unknown>",
267
                         BL_CALLBACK_TABLE_ADDRESS->vSSSP.major, BL_CALLBACK_TABLE_ADDRESS->vSSSP.minor);
268
    if (BL_CALLBACK_TABLE_ADDRESS->vSSSP.major != AOS_SYSTEM_SSSP_VERSION_MAJOR) {
269
      if (stream) {
270
        chprintf(stream, "WARNING: Bootloader and AMiRo-OS implement incompatible SSSP versions!\n");
271
      } else {
272
        aosprintf("WARNING: Bootloader and AMiRo-OS implement incompatible SSSP versions!\n");
273
      }
274
    }
275
    _printSystemInfoLine(stream, "Compiler", SYSTEM_INFO_NAMEWIDTH, "%s %u.%u.%u", (BL_CALLBACK_TABLE_ADDRESS->vCompiler.identifier == BL_VERSION_ID_GCC) ? "GCC" : "<compiler unknown>", BL_CALLBACK_TABLE_ADDRESS->vCompiler.major, BL_CALLBACK_TABLE_ADDRESS->vCompiler.minor, BL_CALLBACK_TABLE_ADDRESS->vCompiler.patch); // TODO: support other compilers than GCC
276
  } else {
277
    if (stream) {
278
      chprintf(stream, "Bootloader incompatible or not available.\n");
279
    } else {
280
      aosprintf("Bootloader incompatible or not available.\n");
281
    }
282
  }
283

  
284
  // print dynamic information about the module
285
  _printSystemInfoSeparator(stream, '-', SYSTEM_INFO_WIDTH);
286
  if (aos.sssp.moduleId != 0) {
287
    _printSystemInfoLine(stream, "Module ID", SYSTEM_INFO_NAMEWIDTH, "%u", aos.sssp.moduleId);
288
  } else {
289
    _printSystemInfoLine(stream, "Module ID", SYSTEM_INFO_NAMEWIDTH, "not available");
290
  }
291
  _printSystemInfoLine(stream, "Date", SYSTEM_INFO_NAMEWIDTH, "%s %02u-%02u-%04u", (dt.tm_wday == 0) ? "Sunday" : (dt.tm_wday == 1) ? "Monday" : (dt.tm_wday == 2) ? "Tuesday" : (dt.tm_wday == 3) ? "Wednesday" : (dt.tm_wday == 4) ? "Thursday" : (dt.tm_wday == 5) ? "Friday" : "Saturday",
292
                       dt.tm_mday,
293
                       dt.tm_mon + 1,
294
                       dt.tm_year + 1900);
295
  _printSystemInfoLine(stream, "Time", SYSTEM_INFO_NAMEWIDTH, "%02u:%02u:%02u", dt.tm_hour, dt.tm_min, dt.tm_sec);
296

  
297
  _printSystemInfoSeparator(stream, '=', SYSTEM_INFO_WIDTH);
298

  
299
  return;
300
}
301

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

  
318
  // local variables
319
  int retval = AOS_INVALID_ARGUMENTS;
320

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

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

  
435
      retval = AOS_OK;
436
    }
437
  }
438

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

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

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

  
480
  (void)argc;
481
  (void)argv;
482

  
483
  // print system information
484
  _printSystemInfo(stream);
485

  
486
  // print time measurement precision
487
  chprintf(stream, "module time resolution: %uus\n", AOS_SYSTEM_TIME_RESOLUTION);
488

  
489
  // print system uptime
490
  aos_timestamp_t uptime;
491
  aosSysGetUptime(&uptime);
492
  chprintf(stream, "The system is running for\n");
493
  chprintf(stream, "%10u days\n", (uint32_t)(uptime / MICROSECONDS_PER_DAY));
494
  chprintf(stream, "%10u hours\n", (uint8_t)(uptime % MICROSECONDS_PER_DAY / MICROSECONDS_PER_HOUR));
495
  chprintf(stream, "%10u minutes\n", (uint8_t)(uptime % MICROSECONDS_PER_HOUR / MICROSECONDS_PER_MINUTE));
496
  chprintf(stream, "%10u seconds\n", (uint8_t)(uptime % MICROSECONDS_PER_MINUTE / MICROSECONDS_PER_SECOND));
497
  chprintf(stream, "%10u milliseconds\n", (uint16_t)(uptime % MICROSECONDS_PER_SECOND / MICROSECONDS_PER_MILLISECOND));
498
  chprintf(stream, "%10u microseconds\n", (uint16_t)(uptime % MICROSECONDS_PER_MILLISECOND / MICROSECONDS_PER_MICROSECOND));
499
#if (AMIROOS_CFG_SSSP_MASTER != true) && (AMIROOS_CFG_PROFILE == true)
500
  chprintf(stream, "SSSP synchronization offset: %.3fus per %uus\n", _syssyncskew, AMIROOS_CFG_SSSP_SYSSYNCPERIOD);
501
#endif /* AMIROOS_CFG_SSSP_MASTER != true && AMIROOS_CFG_PROFILE == true */
502
  _printSystemInfoSeparator(stream, '=', SYSTEM_INFO_WIDTH);
503

  
504
#if (AMIROOS_CFG_SHELL_ENABLE == true)
505
  // print shell info
506
  chprintf(stream, "System shell information:\n");
507
  chprintf(stream, "\tnumber of commands:      %u\n", aosShellCountCommands(&aos.shell));
508
  chprintf(stream, "\tmaximum line width:      %u characters\n", aos.shell.linesize);
509
  chprintf(stream, "\tmaximum #arguments:      %u\n", aos.shell.arglistsize);
510
  chprintf(stream, "\tshell thread stack size: %u bytes\n", aosThdGetStacksize(aos.shell.thread));
511
#if (CH_DBG_FILL_THREADS == TRUE)
512
  chprintf(stream, "\tstack peak utilization:  %u bytes (%.2f%%)\n", aosThdGetStackPeakUtilization(aos.shell.thread), (float)aosThdGetStackPeakUtilization(aos.shell.thread) / (float)aosThdGetStacksize(aos.shell.thread) * 100.0f);
513
#endif /* CH_DBG_FILL_THREADS == TRUE */
514
  _printSystemInfoSeparator(stream, '=', SYSTEM_INFO_WIDTH);
515
#endif /* AMIROOS_CFG_SHELL_ENABLE == true */
516

  
517
  return AOS_OK;
518
}
519

  
520
/**
521
 * @brief   Callback function for the sytem:shutdown shell command.
522
 *
523
 * @param[in] stream    The I/O stream to use.
524
 * @param[in] argc      Number of arguments.
525
 * @param[in] argv      List of pointers to the arguments.
526
 *
527
 * @return              An exit status.
528
 * @retval  AOS_OK                  The command was executed successfully.
529
 * @retval  AOS_INVALID_ARGUMENTS   There was an issue with the arguments.
530
 */
531
static int _shellcmd_shutdowncb(BaseSequentialStream* stream, int argc, char* argv[])
532
{
533
  aosDbgCheck(stream != NULL);
534

  
535
  // print help text
536
  if (argc != 2 || strcmp(argv[1], "--help") == 0) {
537
    chprintf(stream, "Usage: %s OPTION\n", argv[0]);
538
    chprintf(stream, "Options:\n");
539
    chprintf(stream, "  --help\n");
540
    chprintf(stream, "    Print this help text.\n");
541
    chprintf(stream, "  --hibernate, -h\n");
542
    chprintf(stream, "    Shutdown to hibernate mode.\n");
543
    chprintf(stream, "    Least energy saving, but allows charging via pins.\n");
544
    chprintf(stream, "  --deepsleep, -d\n");
545
    chprintf(stream, "    Shutdown to deepsleep mode.\n");
546
    chprintf(stream, "    Minimum energy consumption while allowing charging via plug.\n");
547
    chprintf(stream, "  --transportation, -t\n");
548
    chprintf(stream, "    Shutdown to transportation mode.\n");
549
    chprintf(stream, "    Minimum energy consumption with all interrupts disabled (no charging).\n");
550
    chprintf(stream, "  --restart, -r\n");
551
    chprintf(stream, "    Shutdown and restart system.\n");
552

  
553
    return (argc != 2) ? AOS_INVALID_ARGUMENTS : AOS_OK;
554
  }
555
  // handle argument
556
  else {
557
    if (strcmp(argv[1], "-h") == 0 || strcmp(argv[1], "--hibernate") == 0) {
558
      chEvtBroadcastFlags(&aos.events.os, AOS_SYSTEM_EVENTFLAGS_HIBERNATE);
559
      chThdTerminate(chThdGetSelfX());
560
      return AOS_OK;
561
    }
562
    else if (strcmp(argv[1], "-d") == 0 || strcmp(argv[1], "--deepsleep") == 0) {
563
      chEvtBroadcastFlags(&aos.events.os, AOS_SYSTEM_EVENTFLAGS_DEEPSLEEP);
564
      chThdTerminate(chThdGetSelfX());
565
      return AOS_OK;
566
    }
567
    else if (strcmp(argv[1], "-t") == 0 || strcmp(argv[1], "--transportation") == 0) {
568
      chEvtBroadcastFlags(&aos.events.os, AOS_SYSTEM_EVENTFLAGS_TRANSPORTATION);
569
      chThdTerminate(chThdGetSelfX());
570
      return AOS_OK;
571
    }
572
    else if (strcmp(argv[1], "-r") == 0 || strcmp(argv[1], "--restart") == 0) {
573
      chEvtBroadcastFlags(&aos.events.os, AOS_SYSTEM_EVENTFLAGS_RESTART);
574
      chThdTerminate(chThdGetSelfX());
575
      return AOS_OK;
576
    }
577
    else {
578
      chprintf(stream, "unknown argument %s\n", argv[1]);
579
      return AOS_INVALID_ARGUMENTS;
580
    }
581
  }
582
}
583

  
584
#if (AMIROOS_CFG_TESTS_ENABLE == true) || defined(__DOXYGEN__)
585
/**
586
 * @brief   Callback function for the kernel:test shell command.
587
 *
588
 * @param[in] stream    The I/O stream to use.
589
 * @param[in] argc      Number of arguments.
590
 * @param[in] argv      List of pointers to the arguments.
591
 *
592
 * @return      An exit status.
593
 */
594
static int _shellcmd_kerneltestcb(BaseSequentialStream* stream, int argc, char* argv[])
595
{
596
  aosDbgCheck(stream != NULL);
597

  
598
  (void)argc;
599
  (void)argv;
600

  
601
  msg_t retval = test_execute(stream, &rt_test_suite);
602

  
603
  return retval;
604
}
605
#endif /* AMIROOS_CFG_TESTS_ENABLE == true */
606
#endif /* AMIROOS_CFG_SHELL_ENABLE == true */
607

  
608
/**
609
 * @brief   Generic callback function for GPIO interrupts.
610
 *
611
 * @param[in] args   Pointer to the GPIO pad identifier.
612
 */
613
static void _intCallback(void* args)
614
{
615
  aosDbgCheck((args != NULL) && (*((iopadid_t*)args) < sizeof(eventflags_t) * 8));
616

  
617
  chSysLockFromISR();
618
  chEvtBroadcastFlagsI(&aos.events.io, (eventflags_t)1 << *((iopadid_t*)args));
619
  chSysUnlockFromISR();
620

  
621
  return;
622
}
623

  
624
#if (AMIROOS_CFG_SSSP_MASTER != true) || defined(__DOXYGEN__)
625
/**
626
 * @brief   Callback function for the Sync signal interrupt.
627
 *
628
 * @param[in] args   Pointer to the GPIO pad identifier.
629
 */
630
static void _signalSyncCallback(void *args)
631
{
632
  aosDbgCheck((args != NULL) && (*((iopadid_t*)args) < sizeof(eventflags_t) * 8));
633

  
634
  apalControlGpioState_t s_state;
635
  aos_timestamp_t uptime;
636

  
637
  chSysLockFromISR();
638
  // if the system is in operation phase
639
  if (aos.sssp.stage == AOS_SSSP_OPERATION) {
640
    // read signal S
641
    apalControlGpioGet(&moduleSsspGpioSync, &s_state);
642
    // if S was toggled from on to off
643
    if (s_state == APAL_GPIO_OFF) {
644
      // get current uptime
645
      aosSysGetUptimeX(&uptime);
646
      // align the uptime with the synchronization period
647
      if (uptime % AMIROOS_CFG_SSSP_SYSSYNCPERIOD < AMIROOS_CFG_SSSP_SYSSYNCPERIOD / 2) {
648
        _uptime -= uptime % AMIROOS_CFG_SSSP_SYSSYNCPERIOD;
649
#if (AMIROOS_CFG_PROFILE == true)
650
        _syssyncskew = ((1.0f - SYSTEM_SYSSYNCSKEW_LPFACTOR) * _syssyncskew) + (SYSTEM_SYSSYNCSKEW_LPFACTOR * (uptime % AMIROOS_CFG_SSSP_SYSSYNCPERIOD));
651
#endif
652
      } else {
653
        _uptime += AMIROOS_CFG_SSSP_SYSSYNCPERIOD - (uptime % AMIROOS_CFG_SSSP_SYSSYNCPERIOD);
654
#if (AMIROOS_CFG_PROFILE == true)
655
        _syssyncskew = ((1.0f - SYSTEM_SYSSYNCSKEW_LPFACTOR) * _syssyncskew) - (SYSTEM_SYSSYNCSKEW_LPFACTOR * (AMIROOS_CFG_SSSP_SYSSYNCPERIOD - (uptime % AMIROOS_CFG_SSSP_SYSSYNCPERIOD)));
656
#endif
657
      }
658
    }
659
  }
660
  // broadcast event
661
  chEvtBroadcastFlagsI(&aos.events.io, (eventflags_t)1 << *((iopadid_t*)args));
662
  chSysUnlockFromISR();
663

  
664
  return;
665
}
666
#endif
667

  
668
/**
669
 * @brief   Callback function for the uptime accumulation timer.
670
 *
671
 * @param[in] par   Generic parameter.
672
 */
673
static void _uptimeCallback(void* par)
674
{
675
  (void)par;
676

  
677
  chSysLockFromISR();
678
  // read current time in system ticks
679
  register const systime_t st = chVTGetSystemTimeX();
680
  // update the uptime variables
681
  _uptime += chTimeI2US(chTimeDiffX(_synctime, st));
682
  _synctime = st;
683
  // enable the timer again
684
  chVTSetI(&_systimer, SYSTIMER_PERIOD, &_uptimeCallback, NULL);
685
  chSysUnlockFromISR();
686

  
687
  return;
688
}
689

  
690
#if (AMIROOS_CFG_SSSP_MASTER == true) || defined (__DOXYGEN__)
691
/**
692
 * @brief   Periodic system synchronization callback function.
693
 * @details Toggles the SYS_SYNC signal and reconfigures the system synchronization timer.
694
 *
695
 * @param[in] par   Unuesed parameters.
696
 */
697
static void _sysSyncTimerCallback(void* par)
698
{
699
  (void)par;
700

  
701
  apalControlGpioState_t s_state;
702
  aos_timestamp_t uptime;
703

  
704
  chSysLockFromISR();
705
  // toggle and read signal S
706
  apalGpioToggle(moduleSsspGpioSync.gpio);
707
  apalControlGpioGet(&moduleSsspGpioSync, &s_state);
708
  // if S was toggled from off to on
709
  if (s_state == APAL_GPIO_ON) {
710
    // reconfigure the timer precisely, because the logically falling edge (next interrupt) snychronizes the system time
711
    _syssynctime += AMIROOS_CFG_SSSP_SYSSYNCPERIOD;
712
    aosSysGetUptimeX(&uptime);
713
    chVTSetI(&_syssynctimer, chTimeUS2I(_syssynctime - uptime), _sysSyncTimerCallback, NULL);
714
  }
715
  // if S was toggled from on to off
716
  else /* if (s_state == APAL_GPIO_OFF) */ {
717
    // reconfigure the timer (lazy)
718
    chVTSetI(&_syssynctimer, chTimeUS2I(AMIROOS_CFG_SSSP_SYSSYNCPERIOD / 2), _sysSyncTimerCallback, NULL);
719
  }
720
  chSysUnlockFromISR();
721

  
722
  return;
723
}
724
#endif
725

  
726
/**
727
 * @brief   AMiRo-OS system initialization.
728
 * @note    Must be called from the system control thread (usually main thread).
729
 *
730
 * @param[in] shellPrompt   String to be printed as prompt of the system shell.
731
 */
732
#if (AMIROOS_CFG_SHELL_ENABLE == true) || defined(__DOXYGEN__)
733
void aosSysInit(const char* shellPrompt)
734
#else
735
void aosSysInit(void)
736
#endif
737
{
738
  /* set control thread to maximum priority */
739
  chThdSetPriority(AOS_THD_CTRLPRIO);
740

  
741
  /* set local variables */
742
  chVTObjectInit(&_systimer);
743
  _synctime = 0;
744
  _uptime = 0;
745
#if (AMIROOS_CFG_SSSP_MASTER == true)
746
  chVTObjectInit(&_syssynctimer);
747
  _syssynctime = 0;
748
#endif
749
#if (AMIROOS_CFG_SSSP_MASTER != true) && (AMIROOS_CFG_PROFILE == true)
750
  _syssyncskew = 0.0f;
751
#endif
752

  
753
  /* initialize aos configuration */
754
  aos.sssp.stage = AOS_SSSP_STARTUP_2_1;
755
  aos.sssp.moduleId = 0;
756
  aosIOStreamInit(&aos.iostream);
757
  chEvtObjectInit(&aos.events.io);
758
  chEvtObjectInit(&aos.events.os);
759

  
760
  /* interrupt setup */
761
  // PD signal
762
  palSetPadCallback(moduleSsspGpioPd.gpio->port, moduleSsspGpioPd.gpio->pad, _intCallback, &moduleSsspGpioPd.gpio->pad);
763
  palEnablePadEvent(moduleSsspGpioPd.gpio->port, moduleSsspGpioPd.gpio->pad, APAL2CH_EDGE(moduleSsspGpioPd.meta.edge));
764
  // SYNC signal
765
#if (AMIROOS_CFG_SSSP_MASTER == true)
766
  palSetPadCallback(moduleSsspGpioSync.gpio->port, moduleSsspGpioSync.gpio->pad, _intCallback, &moduleSsspGpioSync.gpio->pad);
767
#else
768
  palSetPadCallback(moduleSsspGpioSync.gpio->port, moduleSsspGpioSync.gpio->pad, _signalSyncCallback, &moduleSsspGpioSync.gpio->pad);
769
#endif
770
  palEnablePadEvent(moduleSsspGpioSync.gpio->port, moduleSsspGpioSync.gpio->pad, APAL2CH_EDGE(moduleSsspGpioSync.meta.edge));
771
#if (AMIROOS_CFG_SSSP_STACK_START != true)
772
  // DN signal
773
  palSetPadCallback(moduleSsspGpioDn.gpio->port, moduleSsspGpioDn.gpio->pad, _intCallback, &moduleSsspGpioDn.gpio->pad);
774
  palEnablePadEvent(moduleSsspGpioDn.gpio->port, moduleSsspGpioDn.gpio->pad, APAL2CH_EDGE(moduleSsspGpioDn.meta.edge));
775
#endif
776
#if (AMIROOS_CFG_SSSP_STACK_END != true)
777
  // UP signal
778
  palSetPadCallback(moduleSsspGpioUp.gpio->port, moduleSsspGpioUp.gpio->pad, _intCallback, &moduleSsspGpioUp.gpio->pad);
779
  palEnablePadEvent(moduleSsspGpioUp.gpio->port, moduleSsspGpioUp.gpio->pad, APAL2CH_EDGE(moduleSsspGpioUp.meta.edge));
780
#endif
781
#ifdef MODULE_INIT_INTERRUPTS
782
  // further interrupt signals
783
  MODULE_INIT_INTERRUPTS();
784
#endif
785

  
786
#if (AMIROOS_CFG_SHELL_ENABLE == true)
787
  /* init shell */
788
  aosShellInit(&aos.shell,
789
               &aos.events.os,
790
               shellPrompt,
791
               _shell_line,
792
               AMIROOS_CFG_SHELL_LINEWIDTH,
793
               _shell_arglist,
794
               AMIROOS_CFG_SHELL_MAXARGS);
795
  // add system commands
796
  aosShellAddCommand(&aos.shell, &_shellcmd_config);
797
  aosShellAddCommand(&aos.shell, &_shellcmd_info);
798
  aosShellAddCommand(&aos.shell, &_shellcmd_shutdown);
799
#if (AMIROOS_CFG_TESTS_ENABLE == true)
800
  aosShellAddCommand(&aos.shell, &_shellcmd_kerneltest);
801
#endif
802
#endif
803

  
804
  return;
805
}
806

  
807
/**
808
 * @brief   Starts the system and all system threads.
809
 */
810
inline void aosSysStart(void)
811
{
812
  // update the system SSSP stage
813
  aos.sssp.stage = AOS_SSSP_OPERATION;
814

  
815
#if (AMIROOS_CFG_SSSP_MASTER == true)
816
  {
817
    chSysLock();
818
    // start the system synchronization counter
819
    // The first iteration of the timer is set to the next 'center' of a 'slice'.
820
    aos_timestamp_t t;
821
    aosSysGetUptimeX(&t);
822
    t = AMIROOS_CFG_SSSP_SYSSYNCPERIOD - (t % AMIROOS_CFG_SSSP_SYSSYNCPERIOD);
823
    chVTSetI(&_syssynctimer, chTimeUS2I((t > (AMIROOS_CFG_SSSP_SYSSYNCPERIOD / 2)) ? (t - (AMIROOS_CFG_SSSP_SYSSYNCPERIOD / 2)) : (t + (AMIROOS_CFG_SSSP_SYSSYNCPERIOD / 2))), _sysSyncTimerCallback, NULL);
824
    chSysUnlock();
825
  }
826
#endif
827

  
828
  // print system information;
829
  _printSystemInfo((BaseSequentialStream*)&aos.iostream);
830
  aosprintf("\n");
831

  
832
#if (AMIROOS_CFG_SHELL_ENABLE == true)
833
  // start system shell thread
834
#if (CH_CFG_USE_THREADHIERARCHY == TRUE)
835
  aos.shell.thread = chThdCreateStatic(_shell_wa, sizeof(_shell_wa), AMIROOS_CFG_SHELL_THREADPRIO, aosShellThread, &aos.shell, &ch.mainthread);
836
#else
837
  aos.shell.thread = chThdCreateStatic(_shell_wa, sizeof(_shell_wa), AMIROOS_CFG_SHELL_THREADPRIO, aosShellThread, &aos.shell);
838
#endif
839
#endif
840

  
841
  return;
842
}
843

  
844
/**
845
 * @brief   Implements the SSSP startup synchronization step.
846
 *
847
 * @param[in] syncEvtListener   Event listener that receives the Sync event.
848
 *
849
 * @return    If another event that the listener is interested in was received, its mask is returned.
850
 *            Otherwise an empty mask (0) is returned.
851
 */
852
eventmask_t aosSysSsspStartupOsInitSyncCheck(event_listener_t* syncEvtListener)
853
{
854
  aosDbgCheck(syncEvtListener != NULL);
855

  
856
  // local variables
857
  eventmask_t m;
858
  eventflags_t f;
859
  apalControlGpioState_t s;
860

  
861
  // update the system SSSP stage
862
  aos.sssp.stage = AOS_SSSP_STARTUP_2_2;
863

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

  
867
  // wait for any event to occur (do not apply any filter in order not to miss any event)
868
  m = chEvtWaitOne(ALL_EVENTS);
869
  f = chEvtGetAndClearFlags(syncEvtListener);
870
  apalControlGpioGet(&moduleSsspGpioSync, &s);
871

  
872
  // if the event was a system event,
873
  //   and it was fired because of the SysSync control signal,
874
  //   and the SysSync control signal has been deactivated
875
  if (m & syncEvtListener->events &&
876
      f == MODULE_SSSP_EVENTFLAGS_SYNC &&
877
      s == APAL_GPIO_OFF) {
878
    chSysLock();
879
    // start the uptime counter
880
    _synctime = chVTGetSystemTimeX();
881
    _uptime = 0;
882
    chVTSetI(&_systimer, SYSTIMER_PERIOD, &_uptimeCallback, NULL);
883
    chSysUnlock();
884

  
885
    return 0;
886
  }
887
  // an unexpected event occurred
888
  else {
889
    // reassign the flags to the event and return the event mask
890
    syncEvtListener->flags |= f;
891
    return m;
892
  }
893
}
894

  
895
/**
896
 * @brief   Retrieves the system uptime.
897
 *
898
 * @param[out] ut   The system uptime.
899
 */
900
inline void aosSysGetUptimeX(aos_timestamp_t* ut)
901
{
902
  aosDbgCheck(ut != NULL);
903

  
904
  *ut = _uptime + chTimeI2US(chTimeDiffX(_synctime, chVTGetSystemTimeX()));
905

  
906
  return;
907
}
908

  
909
/**
910
 * @brief   retrieves the date and time from the MCU clock.
911
 *
912
 * @param[out] td   The date and time.
913
 */
914
void aosSysGetDateTime(struct tm* dt)
915
{
916
  aosDbgCheck(dt != NULL);
917

  
918
  RTCDateTime rtc;
919
  rtcGetTime(&MODULE_HAL_RTC, &rtc);
920
  rtcConvertDateTimeToStructTm(&rtc, dt, NULL);
921

  
922
  return;
923
}
924

  
925
/**
926
 * @brief   set the date and time of the MCU clock.
927
 *
928
 * @param[in] dt    The date and time to set.
929
 */
930
void aosSysSetDateTime(struct tm* dt)
931
{
932
  aosDbgCheck(dt != NULL);
933

  
934
  RTCDateTime rtc;
935
  rtcConvertStructTmToDateTime(dt, 0, &rtc);
936
  rtcSetTime(&, &rtc);
937

  
938
  return;
939
}
940

  
941
/**
942
 * @brief   Initializes/Acknowledges a system shutdown/restart request.
943
 * @note    This functions should be called from the thread with highest priority.
944
 *
945
 * @param[in] shutdown    Type of shutdown.
946
 */
947
void aosSysShutdownInit(aos_shutdown_t shutdown)
948
{
949
  // check arguments
950
  aosDbgCheck(shutdown != AOS_SHUTDOWN_NONE);
951

  
952
#if (AMIROOS_CFG_SSSP_MASTER == true)
953
  // deactivate the system synchronization timer
954
  chVTReset(&_syssynctimer);
955
#endif
956

  
957
  // update the system SSSP stage
958
  aos.sssp.stage = AOS_SSSP_SHUTDOWN_1_1;
959

  
960
  // activate the SYS_PD control signal only, if this module initiated the shutdown
961
  chSysLock();
962
  if (shutdown != AOS_SHUTDOWN_PASSIVE) {
963
    apalControlGpioSet(&moduleSsspGpioPd, APAL_GPIO_ON);
964
  }
965
  // activate the SYS_SYNC signal
966
  apalControlGpioSet(&moduleSsspGpioSync, APAL_GPIO_ON);
967
  chSysUnlock();
968

  
969
  switch (shutdown) {
970
    case AOS_SHUTDOWN_PASSIVE:
971
      chEvtBroadcastFlags(&aos.events.os, AOS_SYSTEM_EVENTFLAGS_SHUTDOWN);
972
      aosprintf("shutdown request received...\n");
973
      break;
974
    case AOS_SHUTDOWN_HIBERNATE:
975
      chEvtBroadcastFlags(&aos.events.os, AOS_SYSTEM_EVENTFLAGS_HIBERNATE);
976
      aosprintf("shutdown to hibernate mode...\n");
977
      break;
978
    case AOS_SHUTDOWN_DEEPSLEEP:
979
      chEvtBroadcastFlags(&aos.events.os, AOS_SYSTEM_EVENTFLAGS_DEEPSLEEP);
980
      aosprintf("shutdown to deepsleep mode...\n");
981
      break;
982
    case AOS_SHUTDOWN_TRANSPORTATION:
983
      chEvtBroadcastFlags(&aos.events.os, AOS_SYSTEM_EVENTFLAGS_TRANSPORTATION);
984
      aosprintf("shutdown to transportation mode...\n");
985
      break;
986
    case AOS_SHUTDOWN_RESTART:
987
      chEvtBroadcastFlags(&aos.events.os, AOS_SYSTEM_EVENTFLAGS_RESTART);
988
      aosprintf("restarting system...\n");
989
      break;
990
   // must never occur
991
   case AOS_SHUTDOWN_NONE:
992
   default:
993
      break;
994
  }
995

  
996
  // update the system SSSP stage
997
  aos.sssp.stage = AOS_SSSP_SHUTDOWN_1_2;
998

  
999
  return;
1000
}
1001

  
1002
/**
1003
 * @brief   Stops the system and all related threads (not the thread this function is called from).
1004
 */
1005
void aosSysStop(void)
1006
{
1007
#if (AMIROOS_CFG_SHELL_ENABLE == true)
1008
  chThdWait(aos.shell.thread);
1009
#endif
1010

  
1011
  return;
1012
}
1013

  
1014
/**
1015
 * @brief   Deinitialize all system variables.
1016
 */
1017
void aosSysDeinit(void)
1018
{
1019
  return;
1020
}
1021

  
1022
/**
1023
 * @brief   Finally shuts down the system and calls the bootloader callback function.
1024
 * @note    This function should be called from the thtead with highest priority.
1025
 *
1026
 * @param[in] shutdown    Type of shutdown.
1027
 */
1028
void aosSysShutdownFinal(aos_shutdown_t shutdown)
1029
{
1030
  // check arguments
1031
  aosDbgCheck(shutdown != AOS_SHUTDOWN_NONE);
1032

  
1033
  // disable all interrupts
1034
  irqDeinit();
1035

  
1036
  // update the system SSSP stage
1037
  aos.sssp.stage = AOS_SSSP_SHUTDOWN_1_3;
1038

  
1039
  // call bootloader callback depending on arguments
1040
  switch (shutdown) {
1041
    case AOS_SHUTDOWN_PASSIVE:
1042
      BL_CALLBACK_TABLE_ADDRESS->cbHandleShutdownRequest();
1043
      break;
1044
    case AOS_SHUTDOWN_HIBERNATE:
1045
      BL_CALLBACK_TABLE_ADDRESS->cbShutdownHibernate();
1046
      break;
1047
    case AOS_SHUTDOWN_DEEPSLEEP:
1048
      BL_CALLBACK_TABLE_ADDRESS->cbShutdownDeepsleep();
1049
      break;
1050
    case AOS_SHUTDOWN_TRANSPORTATION:
1051
      BL_CALLBACK_TABLE_ADDRESS->cbShutdownTransportation();
1052
      break;
1053
    case AOS_SHUTDOWN_RESTART:
1054
      BL_CALLBACK_TABLE_ADDRESS->cbShutdownRestart();
1055
      break;
1056
    // must never occur
1057
    case AOS_SHUTDOWN_NONE:
1058
    default:
1059
      break;
1060
  }
1061

  
1062
  return;
1063
}
1064

  
1065
/** @} */
modules/RT-STM32L476RG-NUCLEO64/.cproject
1
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
2
<?fileVersion 4.0.0?><cproject storage_type_id="org.eclipse.cdt.core.XmlProjectDescriptionStorage">
3
	<storageModule moduleId="org.eclipse.cdt.core.settings">
4
		<cconfiguration id="0.603687198">
5
			<storageModule buildSystemId="org.eclipse.cdt.managedbuilder.core.configurationDataProvider" id="0.603687198" moduleId="org.eclipse.cdt.core.settings" name="Default">
6
				<externalSettings/>
7
				<extensions>
8
					<extension id="org.eclipse.cdt.core.VCErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
9
					<extension id="org.eclipse.cdt.core.GmakeErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
10
					<extension id="org.eclipse.cdt.core.CWDLocator" point="org.eclipse.cdt.core.ErrorParser"/>
11
					<extension id="org.eclipse.cdt.core.GCCErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
12
					<extension id="org.eclipse.cdt.core.GASErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
13
					<extension id="org.eclipse.cdt.core.GLDErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
14
				</extensions>
15
			</storageModule>
16
			<storageModule moduleId="cdtBuildSystem" version="4.0.0">
17
				<configuration artifactName="${ProjName}" buildProperties="" description="" id="0.603687198" name="Default" parent="org.eclipse.cdt.build.core.prefbase.cfg">
18
					<folderInfo id="0.603687198." name="/" resourcePath="">
19
						<toolChain id="org.eclipse.cdt.build.core.prefbase.toolchain.586709963" name="No ToolChain" resourceTypeBasedDiscovery="false" superClass="org.eclipse.cdt.build.core.prefbase.toolchain">
20
							<targetPlatform id="org.eclipse.cdt.build.core.prefbase.toolchain.586709963.1446538340" name=""/>
21
							<builder autoBuildTarget="all" cleanBuildTarget="clean" enableAutoBuild="false" enableCleanBuild="true" enabledIncrementalBuild="true" id="org.eclipse.cdt.build.core.settings.default.builder.1490952991" incrementalBuildTarget="all" keepEnvironmentInBuildfile="false" managedBuildOn="false" name="Gnu Make Builder" parallelBuildOn="true" parallelizationNumber="optimal" superClass="org.eclipse.cdt.build.core.settings.default.builder"/>
22
							<tool id="org.eclipse.cdt.build.core.settings.holder.libs.1134067298" name="holder for library settings" superClass="org.eclipse.cdt.build.core.settings.holder.libs"/>
23
							<tool id="org.eclipse.cdt.build.core.settings.holder.1927705259" name="Assembly" superClass="org.eclipse.cdt.build.core.settings.holder">
24
								<inputType id="org.eclipse.cdt.build.core.settings.holder.inType.1013764026" languageId="org.eclipse.cdt.core.assembly" languageName="Assembly" sourceContentType="org.eclipse.cdt.core.asmSource" superClass="org.eclipse.cdt.build.core.settings.holder.inType"/>
25
							</tool>
26
							<tool id="org.eclipse.cdt.build.core.settings.holder.1367371861" name="GNU C++" superClass="org.eclipse.cdt.build.core.settings.holder">
27
								<inputType id="org.eclipse.cdt.build.core.settings.holder.inType.1824820452" languageId="org.eclipse.cdt.core.g++" languageName="GNU C++" sourceContentType="org.eclipse.cdt.core.cxxSource,org.eclipse.cdt.core.cxxHeader" superClass="org.eclipse.cdt.build.core.settings.holder.inType"/>
28
							</tool>
29
							<tool id="org.eclipse.cdt.build.core.settings.holder.1584496456" name="GNU C" superClass="org.eclipse.cdt.build.core.settings.holder">
30
								<inputType id="org.eclipse.cdt.build.core.settings.holder.inType.1781547795" languageId="org.eclipse.cdt.core.gcc" languageName="GNU C" sourceContentType="org.eclipse.cdt.core.cSource,org.eclipse.cdt.core.cHeader" superClass="org.eclipse.cdt.build.core.settings.holder.inType"/>
31
							</tool>
32
						</toolChain>
33
					</folderInfo>
34
				</configuration>
35
			</storageModule>
36
			<storageModule moduleId="org.eclipse.cdt.core.externalSettings"/>
37
		</cconfiguration>
38
	</storageModule>
39
	<storageModule moduleId="cdtBuildSystem" version="4.0.0">
40
		<project id="RT-STM32L476RG-NUCLEO.null.1004513353" name="RT-STM32L476RG-NUCLEO"/>
41
	</storageModule>
42
	<storageModule moduleId="scannerConfiguration">
43
		<autodiscovery enabled="true" problemReportingEnabled="true" selectedProfileId=""/>
44
		<scannerConfigBuildInfo instanceId="0.603687198">
45
			<autodiscovery enabled="true" problemReportingEnabled="true" selectedProfileId="org.eclipse.cdt.make.core.GCCStandardMakePerProjectProfile"/>
46
		</scannerConfigBuildInfo>
47
	</storageModule>
48
	<storageModule moduleId="org.eclipse.cdt.core.LanguageSettingsProviders"/>
49
	<storageModule moduleId="refreshScope" versionNumber="2">
50
		<configuration configurationName="Default">
51
			<resource resourceType="PROJECT" workspacePath="/RT-STM32L476RG-NUCLEO"/>
52
		</configuration>
53
	</storageModule>
54
</cproject>
modules/RT-STM32L476RG-NUCLEO64/.project
1
<?xml version="1.0" encoding="UTF-8"?>
2
<projectDescription>
3
	<name>RT-STM32L476RG-NUCLEO64</name>
4
	<comment></comment>
5
	<projects>
6
	</projects>
7
	<buildSpec>
8
		<buildCommand>
9
			<name>org.eclipse.cdt.managedbuilder.core.genmakebuilder</name>
10
			<triggers>clean,full,incremental,</triggers>
11
			<arguments>
12
			</arguments>
13
		</buildCommand>
14
		<buildCommand>
15
			<name>org.eclipse.cdt.managedbuilder.core.ScannerConfigBuilder</name>
16
			<triggers>full,incremental,</triggers>
17
			<arguments>
18
			</arguments>
19
		</buildCommand>
20
	</buildSpec>
21
	<natures>
22
		<nature>org.eclipse.cdt.core.cnature</nature>
23
		<nature>org.eclipse.cdt.managedbuilder.core.managedBuildNature</nature>
24
		<nature>org.eclipse.cdt.managedbuilder.core.ScannerConfigNature</nature>
25
	</natures>
26
	<linkedResources>
27
		<link>
28
			<name>board</name>
29
			<type>2</type>
30
			<locationURI>CHIBIOS/os/hal/boards/ST_NUCLEO64_L476RG</locationURI>
31
		</link>
32
		<link>
33
			<name>os</name>
34
			<type>2</type>
35
			<locationURI>CHIBIOS/os</locationURI>
36
		</link>
37
		<link>
38
			<name>test</name>
39
			<type>2</type>
40
			<locationURI>CHIBIOS/test</locationURI>
41
		</link>
42
	</linkedResources>
43
</projectDescription>
modules/RT-STM32L476RG-NUCLEO64/Makefile
1
################################################################################
2
# AMiRo-OS is an operating system designed for the Autonomous Mini Robot       #
3
# (AMiRo) platform.                                                            #
4
# Copyright (C) 2016..2018  Thomas Schöpping et al.                            #
5
#                                                                              #
6
# This program is free software: you can redistribute it and/or modify         #
7
# it under the terms of the GNU General Public License as published by         #
8
# the Free Software Foundation, either version 3 of the License, or            #
9
# (at your option) any later version.                                          #
10
#                                                                              #
11
# This program is distributed in the hope that it will be useful,              #
12
# but WITHOUT ANY WARRANTY; without even the implied warranty of               #
13
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the                #
14
# GNU General Public License for more details.                                 #
15
#                                                                              #
16
# You should have received a copy of the GNU General Public License            #
17
# along with this program.  If not, see <http://www.gnu.org/licenses/>.        #
18
#                                                                              #
19
# This research/work was supported by the Cluster of Excellence Cognitive      #
20
# Interaction Technology 'CITEC' (EXC 277) at Bielefeld University, which is   #
21
# funded by the German Research Foundation (DFG).                              #
22
################################################################################
23

  
24

  
25

  
26
################################################################################
27
# Build global options                                                         #
28
# NOTE: Can be overridden externally.                                          #
29
#                                                                              #
30

  
31
# Compiler options here.
32
ifeq ($(USE_OPT),)
33
  USE_OPT = -O2 -fomit-frame-pointer -falign-functions=16 -fstack-usage
34
endif
35

  
36
# C specific options here (added to USE_OPT).
37
ifeq ($(USE_COPT),)
38
  USE_COPT = -std=c11
39
endif
40

  
41
# C++ specific options here (added to USE_OPT).
42
ifeq ($(USE_CPPOPT),)
43
  USE_CPPOPT = -fno-rtti -std=c++17
44
endif
45

  
46
# Enable this if you want the linker to remove unused code and data
47
ifeq ($(USE_LINK_GC),)
48
  USE_LINK_GC = yes
49
endif
50

  
51
# Linker extra options here.
52
ifeq ($(USE_LDOPT),)
53
  USE_LDOPT =
54
endif
55

  
56
# Enable this if you want link time optimizations (LTO)
57
ifeq ($(USE_LTO),)
58
  USE_LTO = yes
59
endif
60

  
61
# If enabled, this option allows to compile the application in THUMB mode.
62
ifeq ($(USE_THUMB),)
63
  USE_THUMB = yes
64
endif
65

  
66
# Enable this if you want to see the full log while compiling.
67
ifeq ($(USE_VERBOSE_COMPILE),)
68
  USE_VERBOSE_COMPILE = no
69
endif
70

  
71
# If enabled, this option makes the build process faster by not compiling
72
# modules not used in the current configuration.
73
ifeq ($(USE_SMART_BUILD),)
74
  USE_SMART_BUILD = no
75
endif
76

  
77
#                                                                              #
78
# Build global options                                                         #
79
################################################################################
80

  
81
################################################################################
82
# Architecture or project specific options                                     #
83
#                                                                              #
84

  
85
# Stack size to be allocated to the Cortex-M process stack. This stack is
86
# the stack used by the main() thread.
87
ifeq ($(USE_PROCESS_STACKSIZE),)
88
  USE_PROCESS_STACKSIZE = 0x400
89
endif
90

  
91
# Stack size to the allocated to the Cortex-M main/exceptions stack. This
92
# stack is used for processing interrupts and exceptions.
93
ifeq ($(USE_EXCEPTIONS_STACKSIZE),)
94
  USE_EXCEPTIONS_STACKSIZE = 0x400
95
endif
96

  
97
# Enables the use of FPU on Cortex-M4.
98
# Possible selections are:
99
#   no     - no FPU is used (probably equals 'soft')
100
#   soft   - does not use the FPU, thus all floating point operations are emulated
101
#   softfp - uses the FPU, but uses the integer registers only
102
#   hard   - uses the FPU and passes data via the FPU registers
103
ifeq ($(USE_FPU),)
104
  USE_FPU = softfp
105
endif
106

  
107
#                                                                              #
108
# Architecture or project specific options                                     #
109
################################################################################
110

  
111
################################################################################
112
# Project, sources and paths                                                   #
113
#                                                                              #
114

  
115
# Define project name here
116
PROJECT := $(patsubst $(abspath $(dir $(abspath $(lastword $(MAKEFILE_LIST))))..)/%,%,$(abspath $(dir $(abspath $(lastword $(MAKEFILE_LIST))))))
117

  
118
# Imported source files and paths
119
include ../../kernel/kernel.mk
120
CHIBIOS := $(AMIROOS_KERNEL)
121
AMIROOS = ../..
122
# Startup files
123
include $(CHIBIOS)/os/common/startup/ARMCMx/compilers/GCC/mk/startup_stm32l4xx.mk
124
# HAL-OSAL files
125
include $(CHIBIOS)/os/hal/hal.mk
126
include $(CHIBIOS)/os/hal/ports/STM32/STM32L4xx/platform.mk
127
include ./board.mk
128
include $(CHIBIOS)/os/hal/osal/rt/osal.mk
129
# RTOS files
130
include $(CHIBIOS)/os/rt/rt.mk
131
include $(CHIBIOS)/os/common/ports/ARMCMx/compilers/GCC/mk/port_v7m.mk
132
# Other files (optional).
133
include $(CHIBIOS)/test/lib/test.mk
134
include $(CHIBIOS)/test/rt/rt_test.mk
135
# AMiRo-BLT files
136
include ../../bootloader/bootloader.mk
137
# AMiRo-LLD files
138
include ../../periphery-lld/periphery-lld.mk
139
# AMiRo-OS files
140
include ../modules.mk
141
include $(AMIROOS)/core/core.mk
142
include $(AMIROOS)/unittests/unittests.mk
143

  
144
# Define linker script file here
145
LDSCRIPT= $(BOARDLD)/STM32L476xG.ld
146

  
147
# C sources that can be compiled in ARM or THUMB mode depending on the global
148
# setting.
149
CSRC = $(STARTUPSRC) \
150
       $(KERNSRC) \
151
       $(PORTSRC) \
152
       $(OSALSRC) \
153
       $(HALSRC) \
154
       $(PLATFORMSRC) \
155
       $(BOARDSRC) \
156
       $(MODULESCSRC) \
157
       $(TESTSRC) \
158
       $(PERIPHERYLLDCSRC) \
159
       $(AMIROOSCORECSRC) \
160
       $(UNITTESTSCSRC) \
161
       $(CHIBIOS)/os/various/evtimer.c \
162
       $(CHIBIOS)/os/various/syscalls.c \
163
       $(CHIBIOS)/os/hal/lib/streams/chprintf.c \
164
       module.c \
165
       $(APPSCSRC)
166

  
167
# C++ sources that can be compiled in ARM or THUMB mode depending on the global
168
# setting.
169
CPPSRC = $(AMIROOSCORECPPSRC) \
170
         $(APPSCPPSRC)
171

  
172
# C sources to be compiled in ARM mode regardless of the global setting.
173
# NOTE: Mixing ARM and THUMB mode enables the -mthumb-interwork compiler
174
#       option that results in lower performance and larger code size.
175
ACSRC = $(APPSACSRC)
176

  
177
# C++ sources to be compiled in ARM mode regardless of the global setting.
178
# NOTE: Mixing ARM and THUMB mode enables the -mthumb-interwork compiler
179
#       option that results in lower performance and larger code size.
180
ACPPSRC = $(APPSACPPSRC)
181

  
182
# C sources to be compiled in THUMB mode regardless of the global setting.
183
# NOTE: Mixing ARM and THUMB mode enables the -mthumb-interwork compiler
184
#       option that results in lower performance and larger code size.
185
TCSRC = $(APPSTCSRC)
186

  
187
# C sources to be compiled in THUMB mode regardless of the global setting.
188
# NOTE: Mixing ARM and THUMB mode enables the -mthumb-interwork compiler
189
#       option that results in lower performance and larger code size.
190
TCPPSRC = $(APPSTCPPSRC)
191

  
192
# List ASM source files here
193
ASMSRC = $(APPSASMSRC)
194
ASMXSRC = $(STARTUPASM) \
195
          $(PORTASM) \
196
          $(OSALASM) \
197
          $(APPSASMXSRC)
198

  
199
INCDIR = $(CHIBIOS)/os/license \
200
         $(STARTUPINC) \
201
         $(KERNINC) \
202
         $(PORTINC) \
203
         $(OSALINC) \
204
         $(HALINC) \
205
         $(PLATFORMINC) \
206
         $(BOARDINC) \
207
         $(MODULESINC) \
208
         $(TESTINC) \
209
         $(BOOTLOADERINC) \
210
         $(CHIBIOS)/os/hal/lib/streams \
211
         $(PERIPHERYLLDINC) \
212
         $(AMIROOS) \
213
         $(AMIROOSCOREINC) \
214
         $(UNITTESTSINC) \
215
         $(APPSINC)
216

  
217
#                                                                              #
218
# Project, sources and paths                                                   #
219
################################################################################
220

  
221
################################################################################
222
# Compiler settings                                                            #
223
# NOTE: Some can be overridden externally.                                     #
224
#                                                                              #
225

  
226
MCU  = cortex-m4
227

  
228
#TRGT = arm-elf-
229
TRGT = arm-none-eabi-
230
CC   = $(TRGT)gcc
231
CPPC = $(TRGT)g++
232
# Enable loading with g++ only if you need C++ runtime support.
233
# NOTE: You can use C++ even without C++ support if you are careful. C++
234
#       runtime support makes code size explode.
235
LD   = $(TRGT)gcc
236
#LD   = $(TRGT)g++
237
CP   = $(TRGT)objcopy
238
AS   = $(TRGT)gcc -x assembler-with-cpp
239
AR   = $(TRGT)ar
240
OD   = $(TRGT)objdump
241
SZ   = $(TRGT)size
242
HEX  = $(CP) -O ihex
243
BIN  = $(CP) -O binary
244
SREC = $(CP) -O srec --srec-len=248
245

  
246
# ARM-specific options here
247
ifeq ($(AOPT),)
248
  AOPT =
249
endif
250

  
251
# THUMB-specific options here
252
ifeq ($(TOPT),)
253
  TOPT = -mthumb -DTHUMB
254
endif
255

  
256
# Define C warning options here
257
ifeq ($(CWARN),)
258
  CWARN = -Wall -Wextra -Wundef -Wstrict-prototypes
259
endif
260

  
261
# Define C++ warning options here
262
ifeq ($(CPPWARN),)
263
  CPPWARN = -Wall -Wextra -Wundef
264
endif
265

  
266
#                                                                              #
267
# Compiler settings                                                            #
268
################################################################################
269

  
270
################################################################################
271
# Start of user section                                                        #
... This diff was truncated because it exceeds the maximum size that can be displayed.

Also available in: Unified diff