summaryrefslogtreecommitdiff
path: root/software/mpu/usb-cdc-shell.c
blob: 7b32d8adda03f462052484f3f086b6924dda5a87 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
/*
 *
 *  mur.sat
 *
 *  Somewhen in the year 20xx, mur.at will have a nano satellite launched
 *  into a low earth orbit (310 km above the surface of our planet). The
 *  satellite itself is a TubeSat personal satellite kit, developed and
 *  launched by interorbital systems. mur.sat is a joint venture of mur.at,
 *  ESC im Labor and realraum.
 *
 *  Please visit the project hompage at sat.mur.at for further information.
 *
 *
 *  Copyright (C) 2013-2015 Christian Pointner <equinox@mur.at>
 *
 *  This file is part of mur.sat.
 *
 *  mur.sat is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  any later version.
 *
 *  mur.sat is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with mur.sat. If not, see <http://www.gnu.org/licenses/>.
 *
 */

// this heavily leans on the USB-CDC testhal Demo from chibiOS
/*
    ChibiOS/RT - Copyright (C) 2006-2013 Giovanni Di Sirio

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

        http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.
*/


#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#include "ch.h"
#include "hal.h"
#include "test.h"

#include "shell.h"
#include "chprintf.h"

#include "usb-cdc-shell.h"
#include "usb-cdc-descriptor.h"
#include "board-utils.h"

#include "utils.h"

static SerialUSBDriver SDU1;

/*
 * Handles the GET_DESCRIPTOR callback. All required descriptors must be
 * handled here.
 */
static const USBDescriptor *get_descriptor(USBDriver *usbp, uint8_t dtype, uint8_t dindex, uint16_t lang)
{
  (void)usbp;
  (void)lang;
  switch (dtype) {
  case USB_DESCRIPTOR_DEVICE:
    return &vcom_device_descriptor;
  case USB_DESCRIPTOR_CONFIGURATION:
    return &vcom_configuration_descriptor;
  case USB_DESCRIPTOR_STRING:
    if (dindex < 4)
      return &vcom_strings[dindex];
  }
  return NULL;
}

static USBInEndpointState ep1instate;
static USBOutEndpointState ep1outstate;
static const USBEndpointConfig ep1config = {
  USB_EP_MODE_TYPE_BULK,
  NULL,
  sduDataTransmitted,
  sduDataReceived,
  0x0040,
  0x0040,
  &ep1instate,
  &ep1outstate,
  1,
  NULL
};

static USBInEndpointState ep2instate;
static const USBEndpointConfig ep2config = {
  USB_EP_MODE_TYPE_INTR,
  NULL,
  sduInterruptTransmitted,
  NULL,
  0x0010,
  0x0000,
  &ep2instate,
  NULL,
  1,
  NULL
};

/*
 * Handles the USB driver global events.
 */
static void usb_event(USBDriver *usbp, usbevent_t event)
{
  switch (event) {
  case USB_EVENT_RESET:
    return;
  case USB_EVENT_ADDRESS:
    return;
  case USB_EVENT_CONFIGURED:
    chSysLockFromIsr();

    /* Enables the endpoints specified into the configuration.
       Note, this callback is invoked from an ISR so I-Class functions
       must be used.*/
    usbInitEndpointI(usbp, USBD1_DATA_REQUEST_EP, &ep1config);
    usbInitEndpointI(usbp, USBD1_INTERRUPT_REQUEST_EP, &ep2config);

    /* Resetting the state of the CDC subsystem.*/
    sduConfigureHookI(&SDU1);

    chSysUnlockFromIsr();
    return;
  case USB_EVENT_SUSPEND:
    return;
  case USB_EVENT_WAKEUP:
    return;
  case USB_EVENT_STALLED:
    return;
  }
  return;
}

/*
 * USB driver configuration.
 */
static const USBConfig usbcfg = {
  usb_event,
  get_descriptor,
  sduRequestsHook,
  NULL
};

/*
 * Serial over USB driver configuration.
 */
static const SerialUSBConfig serusbcfg = {
  &USBD1,
  USBD1_DATA_REQUEST_EP,
  USBD1_DATA_AVAILABLE_EP,
  USBD1_INTERRUPT_REQUEST_EP
};

/*===========================================================================*/
/* Command line related.                                                     */
/*===========================================================================*/

static int8_t shell_return_code;

#define SHELL_WA_SIZE   THD_WA_SIZE(2048)
#define TEST_WA_SIZE    THD_WA_SIZE(256)



static const SDCConfig sdccfg = {
  0
};

static char* blkstate_to_string(blkstate_t state)
{
  switch(state) {
  case BLK_UNINIT: return "Not initialized.";
  case BLK_STOP: return "Stopped.";
  case BLK_ACTIVE: return "Interface active.";
  case BLK_CONNECTING: return "Connection in progress.";
  case BLK_DISCONNECTING: return "Disconnection in progress.";
  case BLK_READY: return "Device ready.";
  case BLK_READING: return "Read operation in progress.";
  case BLK_WRITING: return "Write operation in progress.";
  case BLK_SYNCING: return "Sync. operation in progress. ";
  }
  return "unkown";
}

static void sdc_read_test(BaseSequentialStream *chp, const uint32_t sector)
{
  chprintf(chp, "Running SDCard Read Test\r\n");
  chprintf(chp, "------------------------\r\n\r\n");

  unsigned int n;
  chprintf(chp, "waiting for card .");
  for(n = 0; n < 20; n++) {
    if(blkIsInserted(&SDCD1)) {
      chprintf(chp, " found\r\n");
      chprintf(chp, "write protection: %s\r\n", blkIsWriteProtected(&SDCD1) ? "ON" : "OFF");

            // Connect
      if(blkConnect(&SDCD1) == CH_SUCCESS) {
        chprintf(chp, "connecting ...");
        while(blkGetDriverState(&SDCD1) == BLK_CONNECTING) {
          chThdSleepMilliseconds(100);
          chprintf(chp, ".");
        }
        if(blkGetDriverState(&SDCD1) != BLK_READY) {
          chprintf(chp, "error.\r\nERROR driver not ready (state now: %s)\r\n", blkstate_to_string((blkGetDriverState(&SDCD1))));
          return;
        }
        chprintf(chp, "done.\r\n");

        BlockDeviceInfo bi;
        if(blkGetInfo(&SDCD1, &bi) == CH_FAILED) {
          chprintf(chp, "ERROR: reading device info\r\n");
          return;
        }
        chprintf(chp, "Device: blocksize=%d, blocknum=%d\r\n", bi.blk_size, bi.blk_num);

        if(bi.blk_num <= sector) {
          chprintf(chp, "Requested sector (%d) is after end of device\r\n", sector);
          return;
        }

            // Read
        chprintf(chp, "\r\nReading Block %ld: \r\n", sector);

        uint8_t buf[1024];
        if(sizeof(buf) < bi.blk_size) {
          chprintf(chp, "Your read buffer ist too small - aborting...\r\n");
          return;
        }
        memset(buf, 0, sizeof(buf));
        if(blkRead(&SDCD1, sector, buf, 1) == CH_FAILED) {
          chprintf(chp, "ERROR: blkRead returned with error\r\n");
          return;
        }

        uint32_t i;
        for(i=0; i<bi.blk_size; i++) {
          chprintf(chp, "%02X ", buf[i]);
          if(((i+1)%16) == 0) chprintf(chp, "\r\n");
          else if(((i+1)%8) == 0) chprintf(chp, " ");
        }
        chprintf(chp, "\r\n\r\n");


            // Disconnect
        if(blkDisconnect(&SDCD1) == CH_FAILED) {
          chprintf(chp, "ERROR: blkDisconnect returned whith error\r\n");
          return;
        }
        chprintf(chp, "disconnecting ...");
        while(blkGetDriverState(&SDCD1) == BLK_DISCONNECTING) {
          chThdSleepMilliseconds(100);
          chprintf(chp, ".");
        }
        if(blkGetDriverState(&SDCD1) != BLK_ACTIVE) {
          chprintf(chp, "error.\r\nERROR driver not ready (state now: %s)\r\n", blkstate_to_string((blkGetDriverState(&SDCD1))));
          return;
        }
        chprintf(chp, "done.\r\n");
      }
      else {
        chprintf(chp, "ERROR: blkConnect returned with error\r\n");
      }
      return;
    }
    chprintf(chp, ".");
    chThdSleepMilliseconds(1000);
  }

  chprintf(chp, " timeout\r\n");
}

static void cmd_sdcr(BaseSequentialStream *chp, int argc, char *argv[])
{
  (void)argv;
  if (argc != 1) {
    chprintf(chp, "Usage: sdcr <sector>\r\n");
    return;
  }

  sdcStart(&SDCD1, &sdccfg);
  sdc_read_test(chp, strtoul(argv[0], NULL, 10));
  sdcStop(&SDCD1);
}

static void sdc_write_test(BaseSequentialStream *chp, const uint32_t sector)
{
  chprintf(chp, "Running SDCard Write Test\r\n");
  chprintf(chp, "-------------------------\r\n\r\n");

  unsigned int n;
  chprintf(chp, "waiting for card .");
  for(n = 0; n < 20; n++) {
    if(blkIsInserted(&SDCD1)) {
      chprintf(chp, " found\r\n");
      chprintf(chp, "write protection: %s\r\n", blkIsWriteProtected(&SDCD1) ? "ON" : "OFF");
      if(blkIsWriteProtected(&SDCD1)) {
        chprintf(chp, "aborting due to write protection!\r\n");
        return;
      }

            // Connect
      if(blkConnect(&SDCD1) == CH_SUCCESS) {
        chprintf(chp, "connecting ...");
        while(blkGetDriverState(&SDCD1) == BLK_CONNECTING) {
          chThdSleepMilliseconds(100);
          chprintf(chp, ".");
        }
        if(blkGetDriverState(&SDCD1) != BLK_READY) {
          chprintf(chp, "error.\r\nERROR driver not ready (state now: %s)\r\n", blkstate_to_string((blkGetDriverState(&SDCD1))));
          return;
        }
        chprintf(chp, "done.\r\n");

        BlockDeviceInfo bi;
        if(blkGetInfo(&SDCD1, &bi) == CH_FAILED) {
          chprintf(chp, "ERROR: reading device info\r\n");
          return;
        }
        chprintf(chp, "Device: blocksize=%d, blocknum=%d\r\n", bi.blk_size, bi.blk_num);

        if(bi.blk_num <= sector) {
          chprintf(chp, "Requested sector (%d) is after end of device\r\n", sector);
          return;
        }

            // Write
        chprintf(chp, "\r\nWriting Block %ld: \r\n", sector);

        uint8_t buf[1024];
        if(sizeof(buf) < bi.blk_size) {
          chprintf(chp, "Your write buffer ist too small - aborting...\r\n");
          return;
        }
        uint32_t i;
        for(i=0; i<sizeof(buf); ++i) {
          buf[i] = (uint8_t)i;
        }

        if(blkWrite(&SDCD1, sector, buf, 1) == CH_FAILED) {
          chprintf(chp, "ERROR: blkWrite returned with error\r\n");
          return;
        }

            // Disconnect
        if(blkDisconnect(&SDCD1) == CH_FAILED) {
          chprintf(chp, "ERROR: blkDisconnect returned whith error\r\n");
          return;
        }
        chprintf(chp, "disconnecting ...");
        while(blkGetDriverState(&SDCD1) == BLK_DISCONNECTING) {
          chThdSleepMilliseconds(100);
          chprintf(chp, ".");
        }
        if(blkGetDriverState(&SDCD1) != BLK_ACTIVE) {
          chprintf(chp, "error.\r\nERROR driver not ready (state now: %s)\r\n", blkstate_to_string((blkGetDriverState(&SDCD1))));
          return;
        }
        chprintf(chp, "done.\r\n");
      }
      else {
        chprintf(chp, "ERROR: blkConnect returned with error\r\n");
      }
      return;
    }
    chprintf(chp, ".");
    chThdSleepMilliseconds(1000);
  }

  chprintf(chp, " timeout\r\n");
}

static void cmd_sdcw(BaseSequentialStream *chp, int argc, char *argv[])
{
  (void)argv;
  if (argc != 1) {
    chprintf(chp, "Usage: sdcw <sector>\r\n");
    return;
  }

  sdcStart(&SDCD1, &sdccfg);
  sdc_write_test(chp, strtoul(argv[0], NULL, 10));
  sdcStop(&SDCD1);
}

static void cmd_mem(BaseSequentialStream *chp, int argc, char *argv[])
{
  size_t n, size;

  (void)argv;
  if (argc > 0) {
    chprintf(chp, "Usage: mem\r\n");
    return;
  }
  n = chHeapStatus(NULL, &size);
  chprintf(chp, "core free memory : %u bytes\r\n", chCoreStatus());
  chprintf(chp, "heap fragments   : %u\r\n", n);
  chprintf(chp, "heap free total  : %u bytes\r\n", size);
}

static void cmd_threads(BaseSequentialStream *chp, int argc, char *argv[])
{
  static const char *states[] = {THD_STATE_NAMES};
  Thread *tp;

  (void)argv;
  if (argc > 0) {
    chprintf(chp, "Usage: threads\r\n");
    return;
  }
  chprintf(chp, "    addr    stack prio refs     state     time name\r\n");
  tp = chRegFirstThread();
  do {
    chprintf(chp, "%.8lx %.8lx %4lu %4lu %9s %8lu %s\r\n",
            (uint32_t)tp, (uint32_t)tp->p_ctx.r13,
            (uint32_t)tp->p_prio, (uint32_t)(tp->p_refs - 1),
             states[tp->p_state], (uint32_t)tp->p_time,
             (tp->p_name == NULL) ? "-" : tp->p_name);
    tp = chRegNextThread(tp);
  } while (tp != NULL);
}

static void cmd_test(BaseSequentialStream *chp, int argc, char *argv[])
{
  Thread *tp;

  (void)argv;
  if (argc > 0) {
    chprintf(chp, "Usage: test\r\n");
    return;
  }
  tp = chThdCreateFromHeap(NULL, TEST_WA_SIZE, chThdGetPriority(),
                           TestThread, chp);
  if (tp == NULL) {
    chprintf(chp, "out of memory\r\n");
    return;
  }
  chThdWait(tp);
}

static void cmd_flash(BaseSequentialStream *chp, int argc, char *argv[])
{
  (void)argv;
  if (argc != 1) {
    chprintf(chp, "Usage: flash (ihu|ctr|bat)\r\n");
    return;
  }
  chprintf(chp, "connecting to bootloader of '%s' .. ", argv[0]);
  if(!strcmp("ihu", argv[0])) {
        // TODO: prepare IHU
    chprintf(chp, "done\r\n");
  } else if(!strcmp("ctr",argv[0])) {
        // TODO: prepare CTR
    chprintf(chp, "done\r\n");
  } else if(!strcmp("bat", argv[0])) {
        // TODO: prepare BAT
    chprintf(chp, "done\r\n");
  } else {
    chprintf(chp, "error: target unknown\r\n");
    return;
  }

  chprintf(chp, " after downloading and flashing has been finished\r\n", argv[0]);
  chprintf(chp, " disconnect and reconnect the USB cable to restart shell\r\n", argv[0]);
}

static void cmd_halt(BaseSequentialStream *chp, int argc, char *argv[])
{
  (void)argv;
  if (argc > 0) {
    chprintf(chp, "Usage: halt\r\n");
    return;
  }
  shell_return_code = MPU_HALT;
  chprintf(chp, "halting system.\r\n");

  shellExit(RDY_OK);
}

static void cmd_reboot(BaseSequentialStream *chp, int argc, char *argv[])
{
  (void)argv;
  if (argc > 0) {
    chprintf(chp, "Usage: reboot\r\n");
    return;
  }
  shell_return_code = MPU_REBOOT;
  chprintf(chp, "rebooting system ...\r\n");

  shellExit(RDY_OK);
}

/* static void cmd_bootloader(BaseSequentialStream *chp, int argc, char *argv[]) */
/* { */
/*   (void)argv; */
/*   if (argc > 0) { */
/*     chprintf(chp, "Usage: bootloader\r\n"); */
/*     return; */
/*   } */
/*   shell_return_code = MPU_BOOTLOADER; */
/*   chprintf(chp, "rebooting to bootloader ... ignored - not implemented!!\r\n"); */

/*   /\* shellExit(RDY_OK); *\/ */
/* } */

static const ShellCommand commands[] = {
  {"sdcr", cmd_sdcr},
  {"sdcw", cmd_sdcw},
  {"mem", cmd_mem},
  {"threads", cmd_threads},
  {"test", cmd_test},
  {"flash", cmd_flash},
  {"halt", cmd_halt},
  {"reboot", cmd_reboot},
//  {"bootloader", cmd_bootloader},
  {NULL, NULL}
};

static const ShellConfig shell_cfg1 = {
  (BaseSequentialStream *)&SDU1,
  commands
};

/*===========================================================================*/
/* Public Interface.                                                         */
/*===========================================================================*/

int8_t usbCDCShellRun(void)
{
  sduObjectInit(&SDU1);
  sduStart(&SDU1, &serusbcfg);
  usbStart(serusbcfg.usbp, &usbcfg);
  usbConnect(serusbcfg.usbp);

  shellInit();

  shell_return_code = MPU_CONTINUE;
  Thread *shelltp = NULL;
  while (TRUE) {
    if (!shelltp && (SDU1.config->usbp->state == USB_ACTIVE))
      shelltp = shellCreate(&shell_cfg1, SHELL_WA_SIZE, NORMALPRIO);
    else if (chThdTerminated(shelltp)) {
      chThdRelease(shelltp);    /* Recovers memory of the previous shell.   */
      shelltp = NULL;           /* Triggers spawning of a new shell.        */
      if (shell_return_code != MPU_CONTINUE) break;
    }
    chThdSleepMilliseconds(1000);
  }

  usbDisconnect(serusbcfg.usbp);
  usbStop(serusbcfg.usbp);
  sduStop(&SDU1);

  return shell_return_code;
}