Statistics
| Branch: | Tag: | Revision:

amiro-os / devices / PowerManagement / main.cpp @ 552936c8

History | View | Annotate | Download (39.579 KB)

1 58fe0e0b Thomas Schöpping
#ifndef IN_CCM
2
/*
3
 * @brief Makro to store data in the core coupled memory (ccm).
4
 *        Example:
5
 *        int compute_buffer[128] IN_CCM;
6
 *
7
 * @note The ccm is not connected to any bus system.
8
 */
9
#define IN_CCM  __attribute__((section(".ccm"))) __attribute__((aligned(4)))
10
#endif
11
12
#ifndef IN_ETH
13
/*
14
 * @brief Makro to store data in the ethernet memory (eth).
15
 *        Example:
16
 *        int dma_buffer[128] IN_ETH;
17
 *
18
 * @note The eth is a dedicated memory block with its own DMA controller.
19
 */
20
#define IN_ETH  __attribute__((section(".eth"))) __attribute__((aligned(4)))
21
#endif
22
23
#define BL_CALLBACK_TABLE_ADDR  (0x08000000 + 0x01C0)
24
#define BL_MAGIC_NUMBER         ((uint32_t)0xFF669900u)
25
26
#define SHUTDOWN_NONE             0
27
#define SHUTDOWN_TRANSPORTATION   1
28
#define SHUTDOWN_DEEPSLEEP        2
29
#define SHUTDOWN_HIBERNATE        3
30
#define SHUTDOWN_RESTART          4
31
#define SHUTDOWN_HANDLE_REQUEST   5
32
33
#include <ch.hpp>
34
#include <shell.h>
35
#include <chprintf.h>
36
#include <wakeup.h>
37
#include <cstdlib>
38
#include <cstring>
39
#include <amiro/util/util.h>
40
#include <global.hpp>
41
#include <exti.hpp>
42
43
using namespace amiro;
44
using namespace constants::PowerManagement;
45
46
Global global;
47
48
void shutdownTimeoutISR(void *arg) {
49
50
  (void) arg;
51
52
}
53
54
void systemStop() {
55
56
//  VirtualTimer shutdownTimeout;
57
  uint8_t i;
58
59
  // tell all boards that it's time to shut down
60
  global.robot.broadcastShutdown();
61
62
  global.userThread.requestTerminate();
63
  global.userThread.wait();
64
65
  // kill bluetooth
66
  boardBluetoothSetState(0);
67
68
  global.adc1_vsys.requestTerminate();
69
  global.adc1_vsys.wait();
70
71
  for (i = 0; i < global.vcnl4020.size(); ++i) {
72
    global.vcnl4020[i].requestTerminate();
73
    global.vcnl4020[i].wait();
74
  }
75
76
  for (i = 0; i < global.bq27500.size(); ++i) {
77
    global.bq27500[i].requestTerminate();
78
    global.bq27500[i].wait();
79
  }
80
81
  for (i = 0; i < global.ina219.size(); ++i) {
82
    global.ina219[i].requestTerminate();
83
    global.ina219[i].wait();
84
  }
85
86
//  boardWriteIoPower(0);
87
  global.mpr121.configure(&global.mpr121_stdby_config);
88
  /* cannot shut down touch, b/c we need it to
89
   * clear any interrupt, so WKUP is not blocked
90
   */
91
92
  // stop I²C
93
  for (i = 0; i < global.V_I2C1.size(); ++i)
94
    global.V_I2C1[i].stop();
95
  for (i = 0; i < global.V_I2C2.size(); ++i)
96
    global.V_I2C2[i].stop();
97
98
  global.mpr121.requestTerminate();
99
  global.mpr121.wait();
100
101
  global.HW_I2C2.stop();
102
  global.HW_I2C1.stop();
103
104
  // stop all threads
105
  global.robot.terminate();
106
107
//  // 60 sec timeout
108
//  palWritePad(GPIOC, GPIOC_SYS_INT_N, PAL_HIGH);
109
//  chVTSet(&shutdownTimeout, MS2ST(60000), shutdownTimeoutISR, NULL);
110
//  // wait for all boards to release SYS_INT_N
111
//  while (palReadPad(GPIOC, GPIOC_SYS_INT_N)!=PAL_HIGH && chVTIsArmedI(&shutdownTimeout)) {
112
//    BaseThread::sleep(MS2ST(1)); /* must sleep for VT, else it will never fire */
113
//  }
114
//  chVTReset(&shutdownTimeout);
115
116
//  chprintf((BaseSequentialStream*) &SD1, "Stop\n");
117
//  boardWriteSystemPower(0);
118
//  boardWriteLed(1);
119
//  boardStop(0x00, 0x00);
120
121
//  /*
122
//   * HSI-PLL domain now.
123
//   */
124
//  //chprintf((BaseSequentialStream*) &SD1, "After Stop\n");
125
//  boardWriteLed(1);
126
127
//  while (true)
128
//    BaseThread::sleep(MS2ST(250));
129
130
  return;
131
}
132
133
void systemShutdown() {
134
135
  VirtualTimer shutdownTimeout;
136
  uint8_t i;
137
138
  // tell all boards that it's time to shut down
139
  global.robot.broadcastShutdown();
140
141
  // wait a little to make sure all boards got the message and had time to pull their SYS_PD_N pins down
142
  BaseThread::sleep(MS2ST(500));
143
144
  // stop the user thread
145
  global.userThread.requestTerminate();
146
  global.userThread.wait();
147
148
  // kill bluetooth
149
  boardBluetoothSetState(0);
150
151
  // stop all threads
152
  global.robot.terminate();
153
154
  global.adc1_vsys.requestTerminate();
155
  global.adc1_vsys.wait();
156
157
  for (i = 0; i < global.vcnl4020.size(); ++i) {
158
    global.vcnl4020[i].requestTerminate();
159
    global.vcnl4020[i].wait();
160
  }
161
162
  for (i = 0; i < global.bq27500.size(); ++i) {
163
    global.bq27500[i].requestTerminate();
164
    global.bq27500[i].wait();
165
  }
166
167
  for (i = 0; i < global.ina219.size(); ++i) {
168
    global.ina219[i].requestTerminate();
169
    global.ina219[i].wait();
170
  }
171
172
  // 60 sec timeout
173
  chVTSet(&shutdownTimeout, MS2ST(60000), shutdownTimeoutISR, NULL);
174
175
  // wait for all boards to release SYS_PD_N
176
  while (!palReadPad(GPIOC, GPIOC_SYS_PD_N) && chVTIsArmedI(&shutdownTimeout))
177
    BaseThread::sleep(MS2ST(1)); /* must sleep for VT, else it will never fire */
178
179
  chVTReset(&shutdownTimeout);
180
  boardWriteIoPower(0);
181
  global.mpr121.configure(&global.mpr121_stdby_config);
182
  /* cannot shut down touch, b/c we need it to
183
   * clear any interrupt, so WKUP is not blocked
184
   */
185
186
  // stop I²C
187
  for (i = 0; i < global.V_I2C1.size(); ++i)
188
    global.V_I2C1[i].stop();
189
  for (i = 0; i < global.V_I2C2.size(); ++i)
190
    global.V_I2C2[i].stop();
191
192
  boardWriteSystemPower(0);
193
  boardStandby();
194
195
}
196
197
198
void boardPeripheryCheck(BaseSequentialStream *chp) {
199
200
#ifndef AMIRO_NSELFTEST
201
  chprintf(chp, "\nCHECK: START\n");
202
  msg_t result = 0;
203
204
    // Check the proximitysensors
205
  for (uint8_t i = 0; i < global.vcnl4020.size(); i++) {
206
    result = global.vcnl4020[i].getCheck();
207
    if (result == global.vcnl4020[i].CHECK_OK)
208
      chprintf(chp, "VCNL4020: %d OK\n", i);
209
    else
210
      chprintf(chp, "VCNL4020: %d FAIL\n", i);
211
  }
212
  chprintf(chp, "----------------------------------------\n");
213
214
  // check the PowerPath controller
215
  chprintf(chp, "\n");
216
  if (global.ltc4412.isPluggedIn())
217
    chprintf(chp, "LTC4412: plugged in\n");
218
  else
219
    chprintf(chp, "LTC4412: not plugged in\n");
220
  chprintf(chp, "----------------------------------------\n");
221
222
  // Check the eeprom
223
  result = global.memory.getCheck();
224
  if ( result != global.memory.OK)
225
    chprintf(chp, "Memory Structure: FAIL\n");
226
  else
227
    chprintf(chp, "Memory Structure: OK\n");
228
  chprintf(chp, "----------------------------------------\n");
229
230
  // Check the power monitors
231
  INA219::BusVoltage bus_voltage;
232
  chprintf(chp, "\n");
233
  chprintf(chp, "INA219:\n");
234
  chprintf(chp, "\tVDD (3.3V):\n");
235
  uint8_t result_ina219_vdd = global.ina219[INA_VDD].selftest();
236
  chprintf(chp, "->\t");
237
  if (result_ina219_vdd == BaseSensor<>::NOT_IMPLEMENTED)
238
    chprintf(chp, "not implemented");
239
  else if (result_ina219_vdd != INA219::Driver::ST_OK)
240
    chprintf(chp, "FAIL (error code 0x%02X)", result_ina219_vdd);
241
  else
242
    chprintf(chp, "OK");
243
244
  chprintf(chp, "\n\n");
245
  chprintf(chp, "\tVIO1.8:\n");
246
  uint8_t result_ina219_vio18 = global.ina219[INA_VIO18].selftest();
247
  chprintf(chp, "->\t");
248
  if (result_ina219_vio18 == BaseSensor<>::NOT_IMPLEMENTED)
249
    chprintf(chp, "not implemented");
250
  else if (result_ina219_vio18 != INA219::Driver::ST_OK)
251
    chprintf(chp, "FAIL (error code 0x%02X)", result_ina219_vio18);
252
  else
253
    chprintf(chp, "OK");
254
255
  chprintf(chp, "\n\n");
256
  chprintf(chp, "\tVIO3.3:\n");
257
  uint8_t result_ina219_vio33 = global.ina219[INA_VIO33].selftest();
258
  chprintf(chp, "->\t");
259
  if (result_ina219_vio33 == BaseSensor<>::NOT_IMPLEMENTED)
260
    chprintf(chp, "not implemented");
261
  else if (result_ina219_vio33 != INA219::Driver::ST_OK)
262
    chprintf(chp, "FAIL (error code 0x%02X)", result_ina219_vio33);
263
  else
264
    chprintf(chp, "OK");
265
266
  chprintf(chp, "\n\n");
267
  chprintf(chp, "\tVIO4.2:\n");
268
  uint8_t result_ina219_vio42 = global.ina219[INA_VIO42].selftest();
269
  chprintf(chp, "->\t");
270
  if (result_ina219_vio42 == BaseSensor<>::NOT_IMPLEMENTED)
271
    chprintf(chp, "not implemented");
272
  else if (result_ina219_vio42 != INA219::Driver::ST_OK)
273
    chprintf(chp, "FAIL (error code 0x%02X)", result_ina219_vio42);
274
  else
275
    chprintf(chp, "OK");
276
277
  bus_voltage = global.ina219[INA_VIO42].readBusVoltage();
278
  chprintf(chp, "\n\n");
279
  chprintf(chp, "\tVIO5.0:\n");
280
  uint8_t result_ina219_vio50 = global.ina219[INA_VIO50].selftest();
281
  chprintf(chp, "->\t");
282
  if (result_ina219_vio50 == BaseSensor<>::NOT_IMPLEMENTED)
283
    chprintf(chp, "not implemented");
284
  else if (result_ina219_vio50 != INA219::Driver::ST_OK)
285
    chprintf(chp, "FAIL (error code 0x%02X)", result_ina219_vio50);
286
  else
287
    chprintf(chp, "OK");
288
289
  chprintf(chp, "\n\n");
290
  result = result_ina219_vdd | result_ina219_vio18 | result_ina219_vio33 | result_ina219_vio42 | result_ina219_vio50;
291
  if (result == BaseSensor<>::NOT_IMPLEMENTED)
292
    chprintf(chp, "->\tINA219: not implemented\n");
293
  else
294
    chprintf(chp, "->\tINA219: %s\n", (result != INA219::Driver::ST_OK)? "FAIL" : "OK");
295
  chprintf(chp, "----------------------------------------\n");
296
297
  // check the fuel gauges
298
  chprintf(chp, "\n");
299
  chprintf(chp, "BQ27500:\n");
300
  chprintf(chp, "\tP7:\n");
301
  msg_t result_bq27500_p7 = global.bq27500[BAT_P7].selftest();
302
  chprintf(chp, "->\tP7: ");
303
  if (result == BaseSensor<>::NOT_IMPLEMENTED)
304
    chprintf(chp, "not implemented");
305
  else if (result_bq27500_p7 == BQ27500::Driver::ST_ABORT_NO_BAT)
306
    chprintf(chp, "ABORT (no battery detected)");
307
  else if (result_bq27500_p7 != BQ27500::Driver::ST_OK)
308
    chprintf(chp, "FAIL (error code 0x%02X)", result);
309
  else
310
    chprintf(chp, "OK");
311
312
  chprintf(chp, "\n\n");
313
  chprintf(chp, "\tP8:\n");
314
  msg_t result_bq27500_p8 = global.bq27500[BAT_P8].selftest();
315
  chprintf(chp, "->\tP8: ");
316
  if (result == BaseSensor<>::NOT_IMPLEMENTED)
317
    chprintf(chp, "not implemented");
318
  else if (result_bq27500_p8 == BQ27500::Driver::ST_ABORT_NO_BAT)
319
      chprintf(chp, "ABORT (no battery detected)");
320
  else if (result_bq27500_p8 != BQ27500::Driver::ST_OK)
321
    chprintf(chp, "FAIL (error code 0x%02X)", result);
322
  else
323
    chprintf(chp, "OK");
324
325
  chprintf(chp, "\n");
326
  result = result_bq27500_p7 | result_bq27500_p8;
327
  if (result == BaseSensor<>::NOT_IMPLEMENTED)
328
    chprintf(chp, "\n->\tBQ27500: not implemented\n");
329
  else
330
    chprintf(chp, "\n->\tBQ27500: %s\n", (result != BQ27500::Driver::ST_OK)? "FAIL" : "OK");
331
  chprintf(chp, "----------------------------------------\n");
332
333
  // check the chargers
334
  chprintf(chp, "\n");
335
  chprintf(chp, "BQ24103A:\n");
336
  if (!global.ltc4412.isPluggedIn())
337
    chprintf(chp, "This test is skipped. Rerun when plugged in.\n");
338
  else {
339
    bool status1, status2, status3;
340
    chprintf(chp, "\tP7:\n");
341
    bool status_p7 = global.bq27500[BAT_P7].isBatteryGood();
342
    chprintf(chp, "Battery good: %s\n", (status_p7? "yes" : "no"));
343
    if (!status_p7) {
344
      chprintf(chp, "-> Rerun test with (another) battery!\n");
345
      status_p7 = true;
346
    } else {
347
      status1 = global.bq24103a[BAT_P7]->isCharging();
348
      chprintf(chp, "status:%scharging\n", (status1? " " : " not "));
349
      chprintf(chp, "%sabling charger...\n", (status1? "dis" : "en"));
350
      global.bq24103a[BAT_P7]->enable(!status1);
351
      BaseThread::sleep(MS2ST(1500));
352
      status2 = global.bq24103a[BAT_P7]->isCharging();
353
      chprintf(chp, "status:%scharging\n", (status2? " " : " not "));
354
      chprintf(chp, "%sabling charger...\n", (!status1? "dis" : "en"));
355
      global.bq24103a[BAT_P7]->enable(status1);
356
      BaseThread::sleep(MS2ST(1500));
357
      status3 = global.bq24103a[BAT_P7]->isCharging();
358
      chprintf(chp, "status:%scharging\n", (status3? " " : " not "));
359
      status_p7 = status2 != status1 && status3 == status1;
360
      chprintf(chp, "->\t");
361
      if (status_p7) {
362
        chprintf(chp, "OK");
363
      } else {
364
        chprintf(chp, "FAIL");
365
      }
366
      chprintf(chp, "\n");
367
    }
368
    chprintf(chp, "\n");
369
    chprintf(chp, "\tP8:\n");
370
    bool status_p8 = global.bq27500[BAT_P8].isBatteryGood();
371
    chprintf(chp, "Battery good: %s\n", (status_p8? "yes" : "no"));
372
    if (!status_p8) {
373
      chprintf(chp, "-> Rerun test with (another) battery!\n");
374
      status_p8 = true;
375
    } else {
376
      status1 = global.bq24103a[BAT_P8]->isCharging();
377
      chprintf(chp, "status:%scharging\n", (status1? " " : " not "));
378
      chprintf(chp, "%sabling charger...\n", (status1? "dis" : "en"));
379
      global.bq24103a[BAT_P8]->enable(!status1);
380
      BaseThread::sleep(MS2ST(1500));
381
      status2 = global.bq24103a[BAT_P8]->isCharging();
382
      chprintf(chp, "status:%scharging\n", (status2? " " : " not "));
383
      chprintf(chp, "%sabling charger...\n", (!status1? "dis" : "en"));
384
      global.bq24103a[BAT_P8]->enable(status1);
385
      BaseThread::sleep(MS2ST(1500));
386
      status3 = global.bq24103a[BAT_P8]->isCharging();
387
      chprintf(chp, "status:%scharging\n", (status3? " " : "not "));
388
      status_p8 = status2 != status1 && status3 == status1;
389
      chprintf(chp, "->\t");
390
      if (status_p8)
391
        chprintf(chp, "OK");
392
      else
393
        chprintf(chp, "FAIL");
394
      chprintf(chp, "\n");
395
    }
396
    chprintf(chp, "\n");
397
    chprintf(chp, "->\tBQ24103A: ");
398
    if (status_p7 && status_p8)
399
      chprintf(chp, "OK");
400
    else
401
      chprintf(chp, "FAIL");
402
    chprintf(chp, "\n");
403
  }
404
  chprintf(chp, "----------------------------------------\n");
405
406
  // check Bluetooth (TODO: move this check to driver)
407
  chprintf(chp, "\n");
408
  chprintf(chp, "WT12-A-AI:\n");
409
410
  chprintf(chp, "testing for MUX mode:\t");
411
412
  if (global.wt12.bluetoothIsMuxMode()) {
413
    chprintf(chp, "PASSED\n");
414
  } else {
415
    chprintf(chp, "FAILED -> setting MUX mode now\n");
416
    /* initialise the WT-12 bluetooth chip on AMIRO (Please, run this processes once) */
417
    global.wt12.bluetoothSendCommand("SET BT AUTH *");
418
    global.wt12.bluetoothSendCommand("SET BT PAIR *");
419
    global.wt12.bluetoothSendCommand("SET BT SSP 3 0");
420
    global.wt12.bluetoothEnableMux();
421
    global.wt12.bluetoothReset();
422
  }
423
424
  global.wt12.bluetoothSendCommand("TEMP");
425
  global.wt12.bluetoothSendCommand("SET");
426
427
  chprintf(chp, "----------------------------------------\n");
428
429
  // check the buzzer
430
  chprintf(chp, "\n");
431
  chprintf(chp, "PKLCS1212E4001:\n");
432
  chprintf(chp, "you should hear the buzzer for one second...\n");
433
  pwmEnableChannel(&PWMD3, 1, 50);
434
  BaseThread::sleep(MS2ST(1000));
435
  pwmDisableChannel(&PWMD3, 1);
436
  chprintf(chp, "----------------------------------------\n");
437
438
  chprintf(chp, "CHECK: FINISH\n");
439
#endif
440
441
  return;
442
}
443
444
void shellRequestShutdown(BaseSequentialStream* chp, int __unused argc, char __unused *argv[]) {
445
446
  chprintf(chp, "shellRequestShutdown\n");
447
448
  /* if no argument was given, print some help text */
449
  if (argc == 0 || strcmp(argv[0],"help") == 0) {
450
    chprintf(chp, "\tUSAGE:\n");
451
    chprintf(chp, "> shutdown <type>\n");
452
    chprintf(chp, "\n");
453
    chprintf(chp, "\ttype\n");
454
    chprintf(chp, "The type of shutdown to perform.\n");
455
    chprintf(chp, "Choose one of the following types:\n");
456
    chprintf(chp, "  transportation - Ultra low-power mode with all wakeups disabled.\n");
457
    chprintf(chp, "                   The robot can not be charged.\n");
458
    chprintf(chp, "  deepsleep      - Ultra low-power mode with several wakeups enabled.\n");
459
    chprintf(chp, "                   The robot can only be charged via the power plug.\n");
460
    chprintf(chp, "  hibernate      - Medium low-power mode, but with full charging capabilities.\n");
461
    chprintf(chp, "  restart        - Performs a system restart.\n");
462
    chprintf(chp, "Alternatively, you can use the shortcuts 't', 'd', 'h', and 'r' respectively.");
463
    chprintf(chp, "\n");
464
    return;
465
  }
466
467
  if (strcmp(argv[0],"transportation") == 0 || strcmp(argv[0],"t") == 0) {
468
    shutdown_now = SHUTDOWN_TRANSPORTATION;
469
    chprintf(chp, "shutdown to transportation mode initialized\n");
470
  } else if (strcmp(argv[0],"deepsleep") == 0 || strcmp(argv[0],"d") == 0) {
471
    shutdown_now = SHUTDOWN_DEEPSLEEP;
472
    chprintf(chp, "shutdown to deepsleep mode initialized\n");
473
  } else if (strcmp(argv[0],"hibernate") == 0 || strcmp(argv[0],"h") == 0) {
474
    shutdown_now = SHUTDOWN_HIBERNATE;
475
    chprintf(chp, "shutdown to hibernate mode initialized\n");
476
  } else if (strcmp(argv[0],"restart") == 0 || strcmp(argv[0],"r") == 0) {
477
    chprintf(chp, "restart initialized\n");
478
    shutdown_now = SHUTDOWN_RESTART;
479
  } else {
480
    chprintf(chp, "ERROR: unknown argument!\n");
481
    shutdown_now = SHUTDOWN_NONE;
482
  }
483
484
  return;
485
}
486
487
void shellRequestResetMemory(BaseSequentialStream *chp, int __unused argc, char __unused *argv[]) {
488
  chprintf(chp, "shellRequestInitMemory\n");
489
490
  msg_t res = global.memory.resetMemory();
491
492
  if ( res != global.memory.OK)
493
    chprintf(chp, "Memory Init: FAIL\n");
494
  else
495
    chprintf(chp, "Memory Init: OK\n");
496
}
497
498
void shellRequestGetBoardId(BaseSequentialStream *chp, int __unused argc, char __unused *argv[]) {
499
  chprintf(chp, "shellRequestGetBoardId\n");
500
501
  uint8_t id = 0xFFu;
502
  msg_t res = global.memory.getBoardId(&id);
503
  if (res != global.memory.OK)
504
    chprintf(chp, "Get Board ID: FAIL\n");
505
  else
506
    chprintf(chp, "Get Board ID: %u\n", id);
507
}
508
509
void shellRequestSetBoardId(BaseSequentialStream *chp, int argc, char *argv[]) {
510
  chprintf(chp, "shellRequestSetBoardId\n");
511
512
  if (argc == 0) {
513
    chprintf(chp, "Usage: %s\n","set_board_id <idx>");
514
  } else {
515
    msg_t res = global.memory.setBoardId(atoi(argv[0]));
516
    if (res != global.memory.OK)
517
      chprintf(chp, "Set Board ID: FAIL\n");
518
    else
519
      chprintf(chp, "Set Board ID: OK\n");
520
  }
521
522
}
523
524
void shellRequestGetMemoryData(BaseSequentialStream *chp, int argc, char *argv[]) {
525
  enum Type {HEX, U8, U16, U32, S8, S16, S32};
526
527
  chprintf(chp, "shellRequestReadData\n");
528
529
  if (argc < 2 || strcmp(argv[0],"help") == 0)
530
  {
531
    chprintf(chp, "Usage: %s\n","get_memory_data <type> <start> [<count>]");
532
    chprintf(chp, "\n");
533
    chprintf(chp, "\ttype\n");
534
    chprintf(chp, "The data type as which to interpret the data.\n");
535
    chprintf(chp, "Choose one of the following types:\n");
536
    chprintf(chp, "  hex - one byte as hexadecimal value\n");
537
    chprintf(chp, "  u8  - unsigned integer (8 bit)\n");
538
    chprintf(chp, "  u16 - unsigned integer (16 bit)\n");
539
    chprintf(chp, "  u32 - unsigned integer (32 bit)\n");
540
    chprintf(chp, "  s8  - signed integer (8 bit)\n");
541
    chprintf(chp, "  s16 - signed integer (16 bit)\n");
542
    chprintf(chp, "  s32 - signed integer (32 bit)\n");
543
    chprintf(chp, "\tstart\n");
544
    chprintf(chp, "The first byte to read from the memory.\n");
545
    chprintf(chp, "\tcount [default = 1]\n");
546
    chprintf(chp, "The number of elements to read.\n");
547
    chprintf(chp, "\n");
548
    chprintf(chp, "\tNOTE\n");
549
    chprintf(chp, "Type conversions of this function might fail.\n");
550
    chprintf(chp, "If so, use type=hex and convert by hand.\n");
551
    chprintf(chp, "\n");
552
    return;
553
  }
554
555
  uint8_t type_size = 0;
556
  Type type = HEX;
557
  if (strcmp(argv[0],"hex") == 0) {
558
    type_size = sizeof(unsigned char);
559
    type = HEX;
560
  } else if(strcmp(argv[0],"u8") == 0) {
561
    type_size = sizeof(uint8_t);
562
    type = U8;
563
  } else if(strcmp(argv[0],"u16") == 0) {
564
    type_size = sizeof(uint16_t);
565
    type = U16;
566
  } else if(strcmp(argv[0],"u32") == 0) {
567
    type_size = sizeof(uint32_t);
568
    type = U32;
569
  } else if(strcmp(argv[0],"s8") == 0) {
570
    type_size = sizeof(int8_t);
571
    type = S8;
572
  } else if(strcmp(argv[0],"s16") == 0) {
573
    type_size = sizeof(int16_t);
574
    type = S16;
575
  } else if(strcmp(argv[0],"s32") == 0) {
576
    type_size = sizeof(int32_t);
577
    type = S32;
578
  } else {
579
    chprintf(chp, "First argument invalid. Use 'get_memory_data help' for help.\n");
580
    return;
581
  }
582
583
  unsigned int start_byte = atoi(argv[1]);
584
585
  unsigned int num_elements = 1;
586
  if (argc >= 3) {
587
    num_elements = atoi(argv[2]);
588
  }
589
590
  const size_t eeprom_size = EEPROM::getsize(&global.at24c01);
591
  uint8_t buffer[eeprom_size];
592
  if (start_byte + (type_size * num_elements) > eeprom_size) {
593
    num_elements = (eeprom_size - start_byte) / type_size;
594
    chprintf(chp, "Warning: request exceeds eeprom size -> limiting to %u values.\n", num_elements);
595
  }
596
597
  chFileStreamSeek((BaseFileStream*)&global.at24c01, start_byte);
598
  uint32_t bytes_read = chSequentialStreamRead((BaseFileStream*)&global.at24c01, buffer, type_size*num_elements);
599
600
  if (bytes_read != type_size*num_elements) {
601
    chprintf(chp, "Warning: %u of %u requested bytes were read.\n", bytes_read, type_size*num_elements);
602
  }
603
604
  for (unsigned int i = 0; i < num_elements; ++i)
605
  {
606
    switch (type)
607
    {
608
      case HEX:
609
        chprintf(chp, "%02X ", buffer[i]);
610
        break;
611
      case U8:
612
        chprintf(chp, "%03u ", ((uint8_t*)buffer)[i]);
613
        break;
614
      case U16:
615
        chprintf(chp, "%05u ", ((uint16_t*)buffer)[i]);
616
        break;
617
      case U32:
618
        chprintf(chp, "%010u ", ((uint32_t*)buffer)[i]);
619
        break;
620
      case S8:
621
        chprintf(chp, "%+03d ", ((int8_t*)buffer)[i]);
622
        break;
623
      case S16:
624
        chprintf(chp, "%+05d ", ((int16_t*)buffer)[i]);
625
        break;
626
      case S32:
627
        chprintf(chp, "%+010d ", ((int32_t*)buffer)[i]);
628
        break;
629
      default:
630
        break;
631
    }
632
  }
633
  chprintf(chp, "\n");
634
635
  return;
636
}
637
638
void shellRequestSetVcnlOffset(BaseSequentialStream *chp, int argc, char *argv[]) {
639
  chprintf(chp, "shellRequestSetVcnlOffset\n");
640
  if (argc != 2) {
641
    chprintf(chp, "Usage: %s\n","set_vcnl <idx> <offset>");
642
    return;
643
  }
644
645
  uint8_t vcnlIdx = static_cast<uint8_t>(atoi(argv[0]));
646
  uint16_t vcnlOffset = static_cast<uint16_t>(atoi(argv[1]));
647
648
  if (vcnlIdx >= global.vcnl4020.size()) {
649
    chprintf((BaseSequentialStream *)&SD1, "Wrong VCNL index: Choose [0 .. %d]\n", global.vcnl4020.size()-1);
650
    return;
651
  }
652
653
  msg_t res = global.memory.setVcnl4020Offset(vcnlOffset, vcnlIdx);
654
  if (res != global.memory.OK) {
655
    chprintf(chp, "Set Offset: FAIL\n");
656
  } else {
657
    chprintf(chp, "Set Offset: OK\n");
658
    global.vcnl4020[vcnlIdx].setProximityOffset(vcnlOffset);
659
  }
660
}
661
662
void shellRequestResetVcnlOffset(BaseSequentialStream *chp, int argc, char *argv[]) {
663
  msg_t res = global.memory.OK;
664
  for (uint8_t idx = 0; idx < 8; ++idx) {
665
    msg_t r = global.memory.setVcnl4020Offset(0, idx);
666
    if (r == global.memory.OK) {
667
      global.vcnl4020[idx].setProximityOffset(0);
668
    } else {
669
      chprintf(chp, "Reset Offset %u: FAIL\n", idx);
670
      res = r;
671
    }
672
  }
673
674
  if (res == global.memory.OK) {
675
    chprintf(chp, "Reset Offset: DONE\n");
676
  }
677
678
  return;
679
}
680
681
void shellRequestGetVcnlOffset(BaseSequentialStream *chp, int argc, char *argv[]) {
682
  chprintf(chp, "shellRequestGetVcnlOffset\n");
683
  if (argc != 1) {
684
    chprintf(chp, "Usage: %s\n","get_vcnl_offset <idx>");
685
    return;
686
  }
687
688
  uint8_t vcnlIdx = static_cast<uint8_t>(atoi(argv[0]));
689
690
  if (vcnlIdx >= global.vcnl4020.size()) {
691
    chprintf((BaseSequentialStream *)&SD1, "Wrong VCNL index: Choose [0 .. %d]\n", global.vcnl4020.size()-1);
692
    return;
693
  }
694
695
  uint16_t vcnlOffset;
696
  msg_t res = global.memory.getVcnl4020Offset(&vcnlOffset, vcnlIdx);
697
  if (res != global.memory.OK) {
698
    chprintf(chp, "Get Offset: FAIL\n");
699
  } else {
700
    chprintf(chp, "Get Offset: OK \t Offset=%d\n", vcnlOffset);
701
  }
702
}
703
704
void shellRequestCheck(BaseSequentialStream *chp, int __unused argc, char __unused *argv[]) {
705
  chprintf(chp, "shellRequestCheck\n");
706
  boardPeripheryCheck(chp);
707
708
}
709
710
void shellRequestGetVcnl(BaseSequentialStream *chp, int argc, char *argv[]) {
711
  chprintf(chp, "shellRequestGetVcnl\n");
712
  // Print the sensor information
713
  if (argc != 1) {
714
    chprintf(chp, "Usage: %s\n","get_vcnl <rep>");
715
    return;
716
  }
717
  for (int32_t rep = 0x00; rep < atoi(argv[0]); ++rep) {
718
    for (uint8_t idx = 0x00; idx < global.vcnl4020.size(); idx++) {
719
     chprintf(chp, "%d: Ambi %d\tProx raw %d\tProx scaled %d\n", idx, global.vcnl4020[idx].getAmbientLight(), global.vcnl4020[idx].getProximity(), global.vcnl4020[idx].getProximityScaledWoOffset());
720
    }
721
    chprintf(chp, "\n\n");
722
    BaseThread::sleep(MS2ST(250));
723
  }
724
}
725
726
void shellRequestCalib(BaseSequentialStream *chp, int __unused argc, char __unused *argv[]) {
727
  chprintf(chp, "shellRequestCalib\n");
728
  global.robot.calibrate();
729
730
}
731
732
void shellRequestGetRobotId(BaseSequentialStream *chp, int __unused argc, char __unused *argv[]) {
733
  chprintf(chp, "shellRequestGetRobotId\n");
734
  chprintf(chp, "Robot ID: %u\n", global.robot.getRobotID());
735
  if (global.robot.getRobotID() == 0) {
736
    chprintf(chp, "Warning: The ID seems to be uninitialized. Is CAN communication working correctly?\n");
737
  }
738
}
739
740
void shellRequestGetSystemLoad(BaseSequentialStream *chp, int argc, char *argv[]) {
741
  chprintf(chp, "shellRequestGetSystemLoad\n");
742
  uint8_t seconds = 1;
743
  if (argc >= 1) {
744
    seconds = atoi(argv[0]);
745
  }
746
  chprintf(chp, "measuring CPU load for %u %s...\n", seconds, (seconds>1)? "seconds" : "second");
747
748
  const systime_t before = chThdGetTicks(chSysGetIdleThread());
749
  BaseThread::sleep(S2ST(seconds));
750
  const systime_t after = chThdGetTicks(chSysGetIdleThread());
751
  const float usage = 1.0f - (float(after - before) / float(seconds * CH_FREQUENCY));
752
753
  chprintf(chp, "CPU load: %3.2f%%\n", usage * 100);
754
  const uint32_t memory_total = 0x1C000;
755
  const uint32_t memory_load = memory_total - chCoreStatus();
756
  chprintf(chp, "RAM load: %3.2f%% (%u / %u Byte)\n", float(memory_load)/float(memory_total) * 100, memory_load, memory_total);
757
}
758
759
void shellRequestSetCharging(BaseSequentialStream *chp, int argc, char *argv[]) {
760
  chprintf(chp, "shellRequestSetCharging\n");
761
  if (argc < 1) {
762
    chprintf(chp, "Usage: %s\n","set_charging <enable>");
763
    chprintf(chp, "\n");
764
    chprintf(chp, "\tenable\n");
765
    chprintf(chp, "Whether to enable (1) or to disable (0) the power path controller of the DiWheelDrive board.\n");
766
    chprintf(chp, "\n");
767
    return;
768
  }
769
770
  const bool enable = atoi(argv[0]);
771
  chprintf(chp, "%s power path controller\n", enable ? "enabling" : "disabling");
772
  global.robot.getPowerStatus().charging_flags.content.diwheeldrive_enable_power_path = enable;
773
774
  return;
775
}
776
777
void shellRequestPrintVCNL(BaseSequentialStream *chp, int argc, char *argv[]) {
778
  chprintf(chp, "shellRequestPrintVCNL\n");
779
  if (argc < 1) {
780
    chprintf(chp, "Warning: no arguments specified.\n");
781
    chprintf(chp, "Using default values (prints one measurement).\n");
782
    chprintf(chp, "Type 'print_vcnl help' for help.\n");
783
    chprintf(chp, "----------------------------------------\n");
784
  }
785
786
  if (strcmp(argv[0],"help") == 0) {
787
    chprintf(chp, "Usage: %s\n","print_vcnl [<seconds>] [<frequency>]");
788
    chprintf(chp, "\n");
789
    chprintf(chp, "\tseconds\n");
790
    chprintf(chp, "Number of seconds to print the VCNL values. (default: 1)\n");
791
    chprintf(chp, "\n");
792
    chprintf(chp, "\tfrequency\n");
793
    chprintf(chp, "Number prints per second. (default: 1)\n");
794
    return;
795
  }
796
797
  const uint32_t seconds = (argc >= 1) ? atoi(argv[0]) : 1;
798
  const uint32_t freq = (argc >= 2) ? atoi(argv[1]) : 1;
799
800
  uint16_t ambient = 0;
801
  uint16_t proximity = 0;
802
803
  for (uint32_t loop = 0; loop < seconds*freq; ++loop) {
804
    // Print proximity and ambilight values
805
    for (uint8_t i = 0x00; i < global.vcnl4020.size(); ++i) {
806
      ambient = global.vcnl4020[i].getAmbientLight();
807
      proximity = global.vcnl4020[i].getProximity();
808
      chprintf(chp, "#%d: ambient=0x%04X\tproximity=0x%04X\n", i, ambient, proximity);
809
    }
810
    chprintf(chp, "----------------------------------------\n");
811
812
    BaseThread::sleep(US2ST(1000000 / freq));
813
  }
814
815
  return;
816
}
817
818
void shellSwitchBoardCmd(BaseSequentialStream *chp, int argc, char *argv[]) {
819
  if (argc != 1) {
820
    chprintf(chp, "Call with decimal numbers: shell_board <idx>\n");
821
    return;
822
  }
823
  uint8_t boardIdx = static_cast<uint8_t>(atoi(argv[0]));
824
825
  chprintf(chp, "shellSwitchBoardCmd\n");
826
  global.sercanmux1.sendSwitchCmd(boardIdx);
827
}
828
829
void shellRequestGetBootloaderInfo(BaseSequentialStream* chp, int argc, char *argv[]) {
830
  // check the magic number
831
  if (*((uint32_t*)(BL_CALLBACK_TABLE_ADDR)) == BL_MAGIC_NUMBER) {
832
    chprintf(chp, "Bootloader version:  %u.%u.%u\n",
833
             *((uint32_t*)(BL_CALLBACK_TABLE_ADDR + (1*4))),
834
             *((uint32_t*)(BL_CALLBACK_TABLE_ADDR + (2*4))),
835
             *((uint32_t*)(BL_CALLBACK_TABLE_ADDR + (3*4))));
836
    chprintf(chp, "Callback functions:\n");
837
    if (*((uint32_t*)(BL_CALLBACK_TABLE_ADDR + (1*4))) == 0 && *((uint32_t*)(BL_CALLBACK_TABLE_ADDR + (2*4))) == 2) {
838
      chprintf(chp, "\thibernate:      %s\n", *((uint32_t*)(BL_CALLBACK_TABLE_ADDR + (4*4))) ? "available" : "unsupported");
839
      chprintf(chp, "\tdeepsleep:      %s\n", *((uint32_t*)(BL_CALLBACK_TABLE_ADDR + (5*4))) ? "available" : "unsupported");
840
      chprintf(chp, "\ttransportation: %s\n", *((uint32_t*)(BL_CALLBACK_TABLE_ADDR + (6*4))) ? "available" : "unsupported");
841
      chprintf(chp, "\trestart:        %s\n", *((uint32_t*)(BL_CALLBACK_TABLE_ADDR + (10*4))) ? "available" : "unsupported");
842
    } else if (*((uint32_t*)(BL_CALLBACK_TABLE_ADDR + (1*4))) == 0 && *((uint32_t*)(BL_CALLBACK_TABLE_ADDR + (2*4))) == 3) {
843
      chprintf(chp, "\thibernate:      %s\n", *((uint32_t*)(BL_CALLBACK_TABLE_ADDR + (4*4))) ? "available" : "unsupported");
844
      chprintf(chp, "\tdeepsleep:      %s\n", *((uint32_t*)(BL_CALLBACK_TABLE_ADDR + (5*4))) ? "available" : "unsupported");
845
      chprintf(chp, "\ttransportation: %s\n", *((uint32_t*)(BL_CALLBACK_TABLE_ADDR + (6*4))) ? "available" : "unsupported");
846
      chprintf(chp, "\trestart:        %s\n", *((uint32_t*)(BL_CALLBACK_TABLE_ADDR + (7*4))) ? "available" : "unsupported");
847
      chprintf(chp, "\thandle request: %s\n", *((uint32_t*)(BL_CALLBACK_TABLE_ADDR + (8*4))) ? "available" : "unsupported");
848
    }
849
  } else {
850
    chprintf((BaseSequentialStream*) &SD1, "Bootloader deprecated\n");
851
  }
852
853
  return;
854
}
855
856
static const ShellCommand commands[] = {
857
  {"shutdown", shellRequestShutdown},
858
  {"check", shellRequestCheck},
859
  {"reset_memory", shellRequestResetMemory},
860
  {"get_board_id", shellRequestGetBoardId},
861
  {"set_board_id", shellRequestSetBoardId},
862
  {"get_memory_data", shellRequestGetMemoryData},
863
  {"get_vcnl", shellRequestGetVcnl},
864
  {"calib_vcnl_offset", shellRequestCalib},
865
  {"set_vcnl_offset", shellRequestSetVcnlOffset},
866
  {"reset_vcnl_offset", shellRequestResetVcnlOffset},
867
  {"get_vcnl_offset", shellRequestGetVcnlOffset},
868
  {"get_robot_id", shellRequestGetRobotId},
869
  {"get_system_load", shellRequestGetSystemLoad},
870
  {"set_charging", shellRequestSetCharging},
871
  {"print_vcnl", shellRequestPrintVCNL},
872
  {"shell_board", shellSwitchBoardCmd},
873
  {"get_bootloader_info", shellRequestGetBootloaderInfo},
874
  {NULL, NULL}
875
};
876
877
static const ShellConfig shell_cfg1 = {
878
  (BaseSequentialStream *) &global.sercanmux1,
879
  commands
880
};
881
882
void charger_logic() {
883
  /*
884
   * if supply connected, activate charger, else
885
   * deactivate charger
886
   */
887
  if (global.ltc4412.isPluggedIn()) {
888
    boardChargerSetState(0x03u, 1), chprintf((BaseSequentialStream*) &SD1, "Charging.\n");
889
  } else {
890
    boardChargerSetState(0x03u, 0), chprintf((BaseSequentialStream*) &SD1, "Not charging.\n");
891
  }
892
}
893
894
void init_powermonitor(INA219::Driver &ina219, const float shunt_resistance_O, const float max_expected_current_A, const uint16_t current_lsb_uA)
895
{
896
  INA219::CalibData calib_data;
897
  INA219::InitData init_data;
898
899
  calib_data.input.configuration.content.brng = INA219::Configuration::BRNG_16V;
900
  calib_data.input.configuration.content.pg = INA219::Configuration::PGA_40mV;
901
  calib_data.input.configuration.content.badc = INA219::Configuration::ADC_68100us;
902
  calib_data.input.configuration.content.sadc = INA219::Configuration::ADC_68100us;
903
  calib_data.input.configuration.content.mode = INA219::Configuration::MODE_ShuntBus_Continuous;
904
  calib_data.input.shunt_resistance_O = shunt_resistance_O;
905
  calib_data.input.max_expected_current_A = max_expected_current_A;
906
  calib_data.input.current_lsb_uA = current_lsb_uA;
907
  if (ina219.calibration(&calib_data) != BaseSensor<>::SUCCESS)
908
    chprintf((BaseSequentialStream*)&SD1, "WARNING: calibration of INA219 failed.\n");
909
910
  init_data.configuration.value = calib_data.input.configuration.value;
911
  init_data.calibration = calib_data.output.calibration_value;
912
  init_data.current_lsb_uA = calib_data.output.current_lsb_uA;
913
  if (ina219.init(&init_data) != BaseSensor<>::SUCCESS)
914
    chprintf((BaseSequentialStream*)&SD1, "WARNING: initialization of INA219 failed.\n");
915
916
  if (calib_data.input.current_lsb_uA != init_data.current_lsb_uA)
917
  {
918
    chprintf((BaseSequentialStream*)&SD1, "NOTE: LSB for current measurement was limited when initializing INA219 (%u -> %u)", calib_data.input.current_lsb_uA, init_data.current_lsb_uA);
919
  }
920
921
  return;
922
}
923
924
/*
925
 * Application entry point.
926
 */
927
int main(void) {
928
929
  Thread *shelltp = NULL;
930
931
  /*
932
   * System initializations.
933
   * - HAL initialization, this also initializes the configured device drivers
934
   *   and performs the board-specific initializations.
935
   * - Kernel initialization, the main() function becomes a thread and the
936
   *   RTOS is active.
937
   */
938
  halInit();
939
  System::init();
940
941
  /*
942
   * TODO: detect the reason why the system was started by reading the 1st backup register of the RTC.
943
   *       To do that, it is probably required to extend the RTC LLD by the required methods.
944
   *       For further details, how to interprete the data in the backu register, please have a look at the bootloader project.
945
   */
946
947
  /*
948
   * Activates the serial driver 1 using the driver default configuration.
949
   */
950
  sdStart(&SD1, &global.sd1_config);
951
952
  chprintf((BaseSequentialStream*) &SD1, "\n");
953
  chprintf((BaseSequentialStream*) &SD1, BOARD_NAME " " BOARD_VERSION "\n");
954
  if (*((uint32_t*)(BL_CALLBACK_TABLE_ADDR)) == BL_MAGIC_NUMBER) {
955
    chprintf((BaseSequentialStream*) &SD1, "Bootloader %u.%u.%u\n",
956
             *((uint32_t*)(BL_CALLBACK_TABLE_ADDR + (1*4))),
957
             *((uint32_t*)(BL_CALLBACK_TABLE_ADDR + (2*4))),
958
             *((uint32_t*)(BL_CALLBACK_TABLE_ADDR + (3*4))));
959
  } else {
960
    chprintf((BaseSequentialStream*) &SD1, "Bootloader deprecated\n");
961
  }
962
  chprintf((BaseSequentialStream*) &SD1, "ChibiOS " CH_KERNEL_VERSION "\n");
963
  // make sure that the info text is completetly printed
964
  BaseThread::sleep(10);
965
966
//  boardWriteSystemPower(1);
967
//  boardWriteIoPower(1);
968
//  boardWriteWarmRestart(0);
969
970
  global.robot.start(HIGHPRIO - 1);
971
972
  pwmStart(&PWMD3, &global.pwm3_config);
973
  pwmDisableChannel(&PWMD3, 1);
974
975
  adcStart(&ADCD1, NULL);
976
977
  extStart(&EXTD1, &extcfg);
978
979 b4885314 Thomas Schöpping
  boardClearI2CBus(GPIOB_GAUGE_SCL1, GPIOB_GAUGE_SDA1);
980
  boardClearI2CBus(GPIOB_GAUGE_SCL2, GPIOB_GAUGE_SDA2);
981 58fe0e0b Thomas Schöpping
982
  global.HW_I2C1.start(&global.i2c1_config);
983
  global.HW_I2C2.start(&global.i2c2_config);
984
985 b4885314 Thomas Schöpping
  uint16_t i2c_test = 0;
986
  while (global.ina219[INA_VIO18].readRegister(INA219::Driver::REG_BUS_VOLTAGE, i2c_test) != RDY_OK) {
987
    chprintf((BaseSequentialStream*)&global.sercanmux1, "I2C #1 stalled! trying to clear the bus... (this will take 20 seconds)\n");
988
    boardWriteLed(1);
989
    boardResetBQ27500I2C(GPIOB_GAUGE_SCL2, GPIOB_GAUGE_SDA2);
990
    boardWriteLed(0);
991
  }
992
  while (global.ina219[INA_VDD].readRegister(INA219::Driver::REG_BUS_VOLTAGE, i2c_test) != RDY_OK) {
993
    chprintf((BaseSequentialStream*)&global.sercanmux1, "I2C #2 stalled! trying to clear the bus... (this will take 20 seconds)\n");
994
    boardWriteLed(1);
995
    boardResetBQ27500I2C(GPIOB_GAUGE_SCL1, GPIOB_GAUGE_SDA1);
996
    boardWriteLed(0);
997
  }
998
999 58fe0e0b Thomas Schöpping
  global.memory.init();
1000
  uint8_t i = 0;
1001
  if (global.memory.getBoardId(&i) == fileSystemIo::FileSystemIoBase::OK) {
1002
    chprintf((BaseSequentialStream*) &SD1, "Board ID: %u\n", i);
1003
  } else {
1004
    chprintf((BaseSequentialStream*) &SD1, "Error reading board ID\n");
1005
  }
1006
  chprintf((BaseSequentialStream*) &SD1, "\n");
1007
1008
  shelltp = shellCreate(&shell_cfg1, THD_WA_SIZE(1024), NORMALPRIO);
1009
1010
  // initialize the power monitors
1011
  init_powermonitor(global.ina219[INA_VDD], 0.1f, 0.075f, 10);
1012
  init_powermonitor(global.ina219[INA_VIO18], 0.01f, 1.5f, 100);
1013
  init_powermonitor(global.ina219[INA_VIO33], 0.01f, 1.5f, 100);
1014
  init_powermonitor(global.ina219[INA_VIO42], 0.01f, 1.5f, 100);
1015
  init_powermonitor(global.ina219[INA_VIO50], 0.01f, 1.5f, 100);
1016
1017
  // start the ADC watchdog
1018
  global.adc1_vsys.start(NORMALPRIO);
1019
1020
  // start the ina threads
1021
  for (i = 0; i < global.ina219.size(); ++i)
1022
    global.ina219[i].start(NORMALPRIO);
1023
1024
//  // calibrate the fuel gauges (TODO)
1025
//  BQ27500::CalibData bq27500_calib_data;
1026
//  bq27500_p7.calibration(&bq27500_calib_data);
1027
1028
  // start the fuel gauge threads
1029
  for (i = 0; i < global.bq27500.size(); ++i)
1030
    global.bq27500[i].start(NORMALPRIO);
1031
1032
  // start the proximity sensor threads
1033
  for (i = 0; i < global.vcnl4020.size(); ++i) {
1034
    uint16_t buffer;
1035
    global.memory.getVcnl4020Offset(&buffer,i);
1036
    global.vcnl4020[i].setProximityOffset(buffer);
1037
    global.vcnl4020[i].start(NORMALPRIO);
1038
  }
1039
1040
  /* Start uart port connecting bluetooth chip */
1041
  global.wt12.bluetoothStart();
1042
1043
  global.mpr121.configure(&global.mpr121_run_config);
1044
  global.mpr121.start(NORMALPRIO);
1045
1046
  global.userThread.start(NORMALPRIO);
1047
1048
  /* let the SYS_SYNC_N pin go, to signal that the initialization of the module is done */
1049
  palWritePad(GPIOC, GPIOC_SYS_INT_N, PAL_HIGH);
1050
1051
  /* wait until all modules are done */
1052
  while (palReadPad(GPIOC, GPIOC_SYS_INT_N) == PAL_LOW) {
1053
    continue;
1054
  }
1055
1056
  while (true) {
1057
1058
    if (!shelltp)
1059
      shelltp = shellCreate(&shell_cfg1, THD_WA_SIZE(1024), NORMALPRIO);
1060
    else if (chThdTerminated(shelltp)) {
1061
      chThdRelease(shelltp); /* Recovers memory of the previous shell. */
1062
      shelltp = NULL; /* Triggers spawning of a new shell.      */
1063
    }
1064
1065
    // Let the LED just blink as an alive signal
1066
    boardWriteLed(1);
1067
    BaseThread::sleep(MS2ST(250));
1068
    boardWriteLed(0);
1069
    BaseThread::sleep(MS2ST(250));
1070
1071
    /*
1072
     * Charger logic before shutdown logic,
1073
     * so we don't need to call it twice.
1074
     */
1075
    if (pathdc_change) {
1076
      pathdc_change = 0x00u;
1077
//      charger_logic();
1078
    }
1079
1080
    /*
1081
     * Shutdown logic before user logic,
1082
     * so user does not get hopes up and
1083
     * prepares wheels to drive into the
1084
     * next wall or something like that.
1085
     */
1086
    if (shutdown_now != SHUTDOWN_NONE) {
1087
      if (*((uint32_t*)(BL_CALLBACK_TABLE_ADDR)) != BL_MAGIC_NUMBER) {
1088
        chprintf((BaseSequentialStream*) &SD1, "ERROR: unable to shut down (bootloader deprecated).\n");
1089
        shutdown_now = SHUTDOWN_NONE;
1090
      } else {
1091
        uint32_t blCallbackPtrAddr = BL_CALLBACK_TABLE_ADDR;
1092
        if (*((uint32_t*)(BL_CALLBACK_TABLE_ADDR + (1*4))) == 0 && *((uint32_t*)(BL_CALLBACK_TABLE_ADDR + (2*4))) == 2) {
1093
          switch (shutdown_now) {
1094
            case SHUTDOWN_TRANSPORTATION:
1095
              blCallbackPtrAddr += 6 * 4;
1096
              break;
1097
            case SHUTDOWN_DEEPSLEEP:
1098
              blCallbackPtrAddr += 5 * 4;
1099
              break;
1100
            case SHUTDOWN_HIBERNATE:
1101
              blCallbackPtrAddr += 4 * 4;
1102
              break;
1103
            case SHUTDOWN_HANDLE_REQUEST:
1104
            case SHUTDOWN_RESTART:
1105
              blCallbackPtrAddr += 10 * 4;
1106
              break;
1107
            default:
1108
              blCallbackPtrAddr = 0;
1109
              break;
1110
          }
1111
        } else if (*((uint32_t*)(BL_CALLBACK_TABLE_ADDR + (1*4))) == 0 && *((uint32_t*)(BL_CALLBACK_TABLE_ADDR + (2*4))) == 3) {
1112
          switch (shutdown_now) {
1113
            case SHUTDOWN_TRANSPORTATION:
1114
              blCallbackPtrAddr += 6 * 4;
1115
              break;
1116
            case SHUTDOWN_DEEPSLEEP:
1117
              blCallbackPtrAddr += 5 * 4;
1118
              break;
1119
            case SHUTDOWN_HIBERNATE:
1120
              blCallbackPtrAddr += 4 * 4;
1121
              break;
1122
            case SHUTDOWN_RESTART:
1123
              blCallbackPtrAddr += 7 * 4;
1124
              break;
1125
            case SHUTDOWN_HANDLE_REQUEST:
1126
              blCallbackPtrAddr += 8 * 4;
1127
              break;
1128
            default:
1129
              blCallbackPtrAddr = 0;
1130
              break;
1131
          }
1132
        }
1133
1134
        void (*blCallback)(void) = NULL;
1135
        if (blCallbackPtrAddr) {
1136
          blCallback = (void (*)(void))(*((uint32_t*)blCallbackPtrAddr));
1137
1138
          if (!blCallback) {
1139
            chprintf((BaseSequentialStream*) &SD1, "ERROR: Requested shutdown not supported.\n");
1140
            shutdown_now = SHUTDOWN_NONE;
1141
          } else {
1142
            chprintf((BaseSequentialStream*) &SD1, "initiating shutdown sequence...\n");
1143
            palWritePad(GPIOC, GPIOC_SYS_INT_N, PAL_LOW);
1144
            palWritePad(GPIOC, GPIOC_SYS_PD_N, PAL_LOW);
1145
1146
            chprintf((BaseSequentialStream*) &SD1, "stopping all threads and periphery...");
1147
            systemStop();
1148
            chprintf((BaseSequentialStream*) &SD1, "\tdone\n");
1149
            BaseThread::sleep(MS2ST(10)); // sleep to print everything
1150
1151
            blCallback();
1152
          }
1153
1154
        } else {
1155
          chprintf((BaseSequentialStream*) &SD1, "ERROR: invalid shutdown requested (%u).\n", shutdown_now);
1156
          shutdown_now = SHUTDOWN_NONE;
1157
        }
1158
      }
1159
1160
//      shutdown_now = 0x00u;
1161
//      if (palReadPad(GPIOC, GPIOC_PATH_DC))
1162
//        systemStop();
1163
//      else
1164
//        systemShutdown();
1165
//      //boardStop(0x00u, 0x00u);
1166
//      //chprintf((BaseSequentialStream*) &SD1, "Stop exit\n");
1167
    }
1168
1169
  }
1170
1171
  global.HW_I2C2.stop();
1172
  global.HW_I2C1.stop();
1173
1174
  return 0;
1175
}