Statistics
| Branch: | Tag: | Revision:

amiro-blt / Host / Source / SerialBoot / main.c @ ac7f321b

History | View | Annotate | Download (32.74 KB)

1
/************************************************************************************//**
2
* \file         main.c
3
* \brief        SerialBoot command line demonstration program for OpenBLT.
4
* \ingroup      SerialBoot
5
* \internal
6
*----------------------------------------------------------------------------------------
7
*                          C O P Y R I G H T
8
*----------------------------------------------------------------------------------------
9
*   Copyright (c) 2014  by Feaser    http://www.feaser.com    All rights reserved
10
*
11
*----------------------------------------------------------------------------------------
12
*                            L I C E N S E
13
*----------------------------------------------------------------------------------------
14
* This file is part of OpenBLT. OpenBLT is free software: you can redistribute it and/or
15
* modify it under the terms of the GNU General Public License as published by the Free
16
* Software Foundation, either version 3 of the License, or (at your option) any later
17
* version.
18
*
19
* OpenBLT is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
20
* without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
21
* PURPOSE. See the GNU General Public License for more details.
22
*
23
* You should have received a copy of the GNU General Public License along with OpenBLT.
24
* If not, see <http://www.gnu.org/licenses/>.
25
*
26
* A special exception to the GPL is included to allow you to distribute a combined work
27
* that includes OpenBLT without being obliged to provide the source code for any
28
* proprietary components. The exception text is included at the bottom of the license
29
* file <license.html>.
30
*
31
* \endinternal
32
****************************************************************************************/
33

    
34

    
35
/****************************************************************************************
36
* Include files
37
****************************************************************************************/
38
#include <assert.h>                                   /* assertion module              */
39
#include <sb_types.h>                                 /* C types                       */
40
#include <stdio.h>                                    /* standard I/O library          */
41
#include <string.h>                                   /* string library                */
42
#include "xcpmaster.h"                                /* XCP master protocol module    */
43
#include "srecord.h"                                  /* S-record file handling        */
44
#include "timeutil.h"                                 /* time utility module           */
45
#include "stdlib.h"                                   /* ascii to integral conversion  */
46

    
47

    
48
/****************************************************************************************
49
* Function prototypes
50
****************************************************************************************/
51
static void     DisplayProgramInfo(void);
52
static void     DisplayProgramUsage(void);
53
static void     DisplayProgramInput(void);
54
static void     printErrors(void);
55
static sb_uint8 ParseCommandLine(sb_int32 argc, sb_char *argv[]);
56
static sb_int32 startFlashMode(void);
57
static sb_int32 flashProgram(void);
58
static sb_int32 startUserProgram(void);
59
static sb_int32 originalMainPart(void);
60
static sb_int32 openSerialPort(void);
61
static sb_int32 openSerialPortConnect(sb_uint8 start);
62
static sb_int32 closeSerialPort(void);
63
static sb_int32 buildConnection(sb_uint8 start);
64
static sb_int32 closeConnection(sb_file *hSrecord);
65
static sb_int32 closeConnectionWithReset(sb_file *hSrecord);
66
static sb_int32 prepareProgrammingSession(sb_file *hSrecord, tSrecordParseResults *fileParseResults);
67
static sb_int32 programCode(sb_file *hSrecord, tSrecordParseResults *fileParseResults, tSrecordLineParseResults *lineParseResults);
68

    
69
/****************************************************************************************
70
* Macro definitions
71
****************************************************************************************/
72
/** \brief Program return code if all went ok. */
73
#define PROG_RESULT_OK    (0)
74

    
75
/** \brief Program return code if an error occurred. */
76
#define PROG_RESULT_ERROR (1)
77

    
78
/* mode definitions of the program status */
79
#define PROGSTATE_ORIGIN           0
80
#define PROGSTATE_STARTFLASHMODE   1
81
#define PROGSTATE_RESET            2
82
#define PROGSTATE_FLASHPROGRAM     3
83
#define PROGSTATE_SETFLAGS         4
84

    
85
/* error definitions */
86
#define ERROR_NO                   0
87
#define ERROR_FILE                 1
88
#define ERROR_DEVICE               2
89
#define ERROR_UNKNOWN              255
90

    
91
/* maximal space for flashing programs */
92
#define MAX_COUNT_FLASHING_PROGRAMS 5
93

    
94

    
95
/****************************************************************************************
96
* Local data declarations
97
****************************************************************************************/
98
/** \brief Name of the serial device, such as COM4 or /dev/ttyUSB0. */
99
static sb_char serialDeviceName[32];
100

    
101
/** \brief Id of the bluetooth device, such as 01:23:45:67:89:AB. */
102
static sb_char bluetoothID[18];
103

    
104
/** \brief Serial communication speed in bits per second. */
105
static sb_uint32 serialBaudrate;
106

    
107
/** \brief Name of the S-record file. */
108
static sb_char *srecordFileName;
109

    
110
/* program status */
111
static sb_uint8 prog_state = 1;
112

    
113
/* id of flashing target */
114
static sb_uint32 flashingTargetID = 0;
115

    
116
/* list of program names */
117
static sb_char *srecordFileNames[MAX_COUNT_FLASHING_PROGRAMS];
118

    
119
/* list of target ids */
120
static sb_uint32 flashingTargetIDs[MAX_COUNT_FLASHING_PROGRAMS];
121

    
122
/* list of errors */
123
static sb_uint8 errors[MAX_COUNT_FLASHING_PROGRAMS];
124

    
125
/* last error */
126
static sb_uint8 errorDetected = ERROR_NO;
127

    
128
/* program counter */
129
static sb_uint8 countFlashingPrograms = 0;
130

    
131
/* RTS register value */
132
static sb_uint8 registerRTSvalue = 0;
133

    
134
/* Type of communication is about UART, not Bluetooth */
135
static sb_uint8 comIsUart = SB_TRUE;
136

    
137

    
138
/************************************************************************************//**
139
** \brief     Program entry point.
140
** \param     argc Number of program parameters.
141
** \param     argv array to program parameter strings.
142
** \return    0 on success, > 0 on error.
143
**
144
****************************************************************************************/
145
sb_int32 main(sb_int32 argc, sb_char *argv[])
146
{
147
  /* disable buffering for the standard output to make sure printf does not wait until
148
   * a newline character is detected before outputting text on the console.
149
   */
150
  setbuf(stdout, SB_NULL);
151

    
152
  /* inform user about the program */
153
  DisplayProgramInfo();
154

    
155
  /* start out by making sure program was started with the correct parameters */
156
  if (ParseCommandLine(argc, argv) == SB_FALSE)
157
  {
158
    /* parameters invalid. inform user about how this program works */
159
    DisplayProgramUsage();
160
    return PROG_RESULT_ERROR;
161
  }
162

    
163
  DisplayProgramInput();
164

    
165
  if (openSerialPortConnect(0) == PROG_RESULT_ERROR) {
166
    return PROG_RESULT_ERROR;
167
  }
168

    
169
  /* initialize errors */
170
  sb_uint8 errorIdx;
171
  for (errorIdx=0; errorIdx<MAX_COUNT_FLASHING_PROGRAMS; errorIdx++) {
172
    errors[errorIdx] = ERROR_NO;
173
  }
174

    
175
  flashingTargetID = 0;
176
  if (startFlashMode() == PROG_RESULT_ERROR) {
177
    return PROG_RESULT_ERROR;
178
  }
179

    
180
  sb_uint8 flashIdx;
181
  for (flashIdx=0; flashIdx<countFlashingPrograms; flashIdx++) {
182
    errorDetected = ERROR_NO;
183
    flashingTargetID = flashingTargetIDs[flashIdx];
184
    srecordFileName = srecordFileNames[flashIdx];
185
    printf("\nFlash %i: Flashing %s on device 0x%08X\n\n", flashIdx+1, srecordFileName, flashingTargetID);
186

    
187
    if (flashProgram() == PROG_RESULT_ERROR) {
188
      closeSerialPort();
189
      openSerialPortConnect(0);
190
    }
191
    errors[flashIdx] = errorDetected;
192
  }
193

    
194
  flashingTargetID = 0;
195
  if (startUserProgram() == PROG_RESULT_ERROR) {
196
    return PROG_RESULT_ERROR;
197
  }
198

    
199
  printErrors();
200

    
201

    
202
  return PROG_RESULT_OK;
203
} /*** end of main ***/
204

    
205

    
206
/************************************************************************************//**
207
** \brief     Outputs information to the user about this program.
208
** \return    none.
209
**
210
****************************************************************************************/
211
static void DisplayProgramInfo(void)
212
{
213
  printf("---------------------------------------------------------------------------\n");
214
  printf("SerialBoot version 1.01. Performs firmware updates via the serial port     \n");
215
  printf("for a microcontroller based system that runs the OpenBLT bootloader.       \n");
216
  printf("                                                                           \n");
217
  printf("Copyright (c) by Feaser  http://www.feaser.com                             \n");
218
  printf("---------------------------------------------------------------------------\n");
219
  printf("This tool was modified for the 'Autonomous Mini Robot' - AMiRo.            \n");
220
  printf("Copyright (c) 2016..2018  Marvin Barther, Thomas Schoepping, and Stefan    \n");
221
  printf("                          Herbrechtsmeier                                  \n");
222
  printf("This is free software; see the source for copying conditions. There is NO  \n");
223
  printf("warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n");
224
  printf("The development of this software was supported by the Excellence Cluster   \n");
225
  printf("EXC 227 Cognitive Interaction Technology. The Excellence Cluster EXC 227 is\n");
226
  printf("a grant of the Deutsche Forschungsgemeinschaft (DFG) in the context of the \n");
227
  printf("German Excellence Initiative.                                              \n");
228
  printf("---------------------------------------------------------------------------\n");
229
} /*** end of DisplayProgramInfo ***/
230

    
231

    
232
/************************************************************************************//**
233
** \brief     Outputs information to the user about how to use this program.
234
** \return    none.
235
**
236
****************************************************************************************/
237
static void DisplayProgramUsage(void)
238
{
239
  printf("Usage: SerialBoot -d<device> -b<baudrate> <s-record file>/(-T<flash-id> <s-record file>)\n\n");
240
  printf("Example 1:  SerialBoot -h\n");
241
#ifdef PLATFORM_WIN32
242
  printf("Example 2:  SerialBoot -dCOM4 -b57600 -T3 firmware.srec\n");
243
  printf("Example 3:  SerialBoot -dCOM4 -b57600 -T0 firm1.srec -T3 firm2.srec\n");
244
  printf("Example 4:  SerialBoot -dCOM4 -b57600 firmware.srec\n\n");
245
  printf("WARNING: SerialBoot is not really functional with windows! Please use\n");
246
  printf("         the Linux version.\n\n");
247
  printf("  -> In all four cases it connects to COM4 and configures a communication\n");
248
#else
249
  printf("Example 2:  SerialBoot -d/dev/ttyUSB0 -b57600 -T3 firmware.srec\n");
250
  printf("Example 3:  SerialBoot -d/dev/ttyUSB0 -b57600 -T0 firm1.srec -T3 firm2.srec\n");
251
  printf("Example 4:  SerialBoot -d/dev/ttyUSB0 -b57600 firmware.srec\n\n");
252
  printf("  -> In all four cases it connects to ttyUSB0 and configures a communication\n");
253
#endif
254
  printf("     speed of 57600 bits/second. The bootloaders will be set into flashing\n");
255
  printf("     mode and will be reset after flashing the last binary file.\n");
256
  printf("  -> In the first example this help will be opened\n");
257
  printf("  -> In the second example the binary file 'firmware.srec' will be flashed on\n");
258
  printf("     device 0x03.\n");
259
  printf("  -> In the third example the binary file 'firm1.srec' will be flashed on\n");
260
  printf("     device 0x00 and the other binary file 'firm2.srec' on device 0x03.\n");
261
  printf("  -> In the last example the standard configuration is shown. The binary file\n");
262
  printf("     'firmware.srec' will be flashed on device 0x00. It equals the\n");
263
  printf("     configuration '-T0 firmware.srec'.\n");
264
  printf("  -> Don't forget that you always have to give the parameters -d and -b.\n");
265
  printf("  -> There is also the parameter -a for giving an address for bluetooth\n");
266
  printf("     communication, but this part is not functional yet.\n");
267
  printf("--------------------------------------------------------------------------------\n");
268
} /*** end of DisplayProgramUsage ***/
269

    
270

    
271

    
272
static void DisplayProgramInput(void) {
273
#ifdef PLATFORM_WIN32
274
  printf("WARNING: SerialBoot is designed for Linux. While using Windows the correct\n");
275
  printf("         functionality can not be guaranteed! Please use Linux for using best\n");
276
  printf("         performance and savety.\n");
277
  printf("\n--------------------------------------------------------------------------------\n\n");
278
#endif
279
  printf("\nOpen device at %s @ %u bits/s and RTS=%i\n\n", serialDeviceName, serialBaudrate, registerRTSvalue);
280
  printf("Programming will start immediately in following order:\n");
281
  sb_uint8 idx;
282
  for (idx=0; idx<countFlashingPrograms; idx++) {
283
    printf("  %i) device 0x%08X: %s\n", idx+1, flashingTargetIDs[idx], srecordFileNames[idx]);
284
  }
285
}
286

    
287

    
288
/************************************************************************************//**
289
** \brief     Parses the command line arguments. A fixed amount of arguments is expected.
290
**            The program should be called as:
291
**              SerialBoot -d[device] -b[baudrate] [s-record file]
292
** \param     argc Number of program parameters.
293
** \param     argv array to program parameter strings.
294
** \return    SB_TRUE on success, SB_FALSE otherwise.
295
**
296
****************************************************************************************/
297
static sb_uint8 ParseCommandLine(sb_int32 argc, sb_char *argv[])
298
{
299
  sb_uint8 paramIdx;
300
  sb_uint8 paramAfound = SB_FALSE;
301
  sb_uint8 paramDfound = SB_FALSE;
302
  sb_uint8 paramBfound = SB_FALSE;
303
  sb_uint8 paramTfound = SB_FALSE;
304
  sb_uint8 paramRTSfound = SB_FALSE;
305
  sb_uint8 paramXfound = SB_FALSE;
306
  sb_uint8 srecordfound = SB_FALSE;
307

    
308
  /* make sure the right amount of arguments are given */
309
  if (argc < 4 || argc > 14)
310
  {
311
    return SB_FALSE;
312
  }
313

    
314
  /* loop through all the command lina parameters, just skip the 1st one because this
315
   * is the name of the program, which we are not interested in.
316
   */
317
  for (paramIdx=1; paramIdx<argc; paramIdx++)
318
  {
319
    /* is this the device name? */
320
    if ( (argv[paramIdx][0] == '-') && (argv[paramIdx][1] == 'd') && (paramDfound == SB_FALSE) && (paramTfound == SB_FALSE) && (paramAfound == SB_FALSE))
321
    {
322
      /* copy the device name and set flag that this parameter was found */
323
      strcpy(serialDeviceName, &argv[paramIdx][2]);
324
      paramDfound = SB_TRUE;
325
      comIsUart = SB_TRUE;
326
    }
327
    /* is this the bluetooth id? */
328
/*
329
    else if ( (argv[paramIdx][0] == '-') && (argv[paramIdx][1] == 'a') && (paramDfound == SB_FALSE) && (paramTfound == SB_FALSE) && (paramAfound == SB_FALSE))
330
    {
331
      if ((argv[paramIdx][4] != ':') || (argv[paramIdx][7] != ':') || (argv[paramIdx][10] != ':') || (argv[paramIdx][13] != ':') || (argv[paramIdx][16] != ':')) {
332
        printf("The bluetooth ID %s has not the format xx:xx:xx:xx:xx:xx\n", &argv[paramIdx][2]);
333
        return SB_FALSE;
334
      }
335
      // copy the bluetooth id and set flag that this parameter was found
336
      strcpy(serialDeviceName, &argv[paramIdx][2]);
337
      paramAfound = SB_TRUE;
338
      comIsUart = SB_FALSE;
339
      // TODO accept bluetooth communication
340
      printf("Bluetooth communication is not available yet!");
341
      return SB_FALSE;
342
    }
343
*/
344
    /* is this the baudrate? */
345
    else if ( (argv[paramIdx][0] == '-') && (argv[paramIdx][1] == 'b') && (paramBfound == SB_FALSE) && (paramTfound == SB_FALSE) )
346
    {
347
      /* extract the baudrate and set flag that this parameter was found */
348
      sscanf(&argv[paramIdx][2], "%u", &serialBaudrate);
349
      paramBfound = SB_TRUE;
350
    }
351
    /* is this the RTS flag? */
352
    else if ( (argv[paramIdx][0] == '-') && (argv[paramIdx][1] == 'R') && (argv[paramIdx][2] == 'T') && (argv[paramIdx][3] == 'S') && (paramRTSfound == SB_FALSE) && (paramTfound == SB_FALSE) )
353
    {
354
      /* extract RTS flag [0,1] and set that this parameter was found */
355
      sb_char setValue[2];
356
      strcpy(setValue, &argv[paramIdx][4]);
357
      if (setValue[0] == 0x0) {
358
        registerRTSvalue = 0;
359
      } else {
360
        registerRTSvalue = ((int)setValue[0])-48;
361
      }
362
      if (registerRTSvalue > 1 || registerRTSvalue < 0 || setValue[1] != 0x0) {
363
        registerRTSvalue = 0;
364
        printf("Not allowed value for RTS register. RTS=[0,1]\n");
365
        return SB_FALSE;
366
      }
367
      paramRTSfound = SB_TRUE;
368
    }
369
    /* is this the target number? */
370
    else if ( (argv[paramIdx][0] == '-') && (argv[paramIdx][1] == 'T') && (paramTfound == SB_FALSE) && (paramXfound == SB_FALSE) && (paramDfound == SB_TRUE) && (paramBfound == SB_TRUE) )
371
    {
372
      if (countFlashingPrograms >= MAX_COUNT_FLASHING_PROGRAMS) {
373
        printf("too many programs to flash (-T)\n");
374
        return SB_FALSE;
375
      }
376
      /* prog status has to be set in flashing mode */
377
      paramTfound = SB_TRUE;
378
      prog_state = PROGSTATE_FLASHPROGRAM;
379
      sb_char choosenID[128];
380
      strcpy(choosenID, &argv[paramIdx][2]);
381
      /* Transform ascii numbers in string to an integer */
382
      flashingTargetID = 0;
383
      if (choosenID[0] == '0' && (choosenID[1] < '0' || choosenID[1] > '9')) {  // if the ID is something like "0x..." or "0o..."
384
        switch (choosenID[1]) {
385
          case 'x':
386
          case 'X':
387
            flashingTargetID = strtoul(&choosenID[2], NULL, 16);
388
            break;
389
          case 'o':
390
          case 'O':
391
            flashingTargetID = strtoul(&choosenID[2], NULL, 8);
392
            break;
393
          case 'b':
394
          case 'B':
395
            flashingTargetID = strtoul(&choosenID[2], NULL, 2);
396
            break;
397
          case 'd':
398
          case 'D':
399
            flashingTargetID = strtoul(&choosenID[2], NULL, 10);
400
            break;
401
          default:
402
            printf("could not interprete target ID\n");
403
            return SB_FALSE;
404
            break;
405
        }
406
      } else {
407
        flashingTargetID = strtoul(choosenID, NULL, 10);
408
      }
409
      if (flashingTargetID == 0) {
410
        printf("target ID invalid (0x%08X)\n", flashingTargetID);
411
        return SB_FALSE;
412
      }
413
      flashingTargetIDs[countFlashingPrograms] = flashingTargetID;
414
    }
415
    /* is this a srec file (a parameter without "-" in the beginning) */
416
    else if (argv[paramIdx][0] != '-')
417
    {
418
      if (countFlashingPrograms >= MAX_COUNT_FLASHING_PROGRAMS) {
419
        printf("too many programs to flash (without -T)\n");
420
        return SB_FALSE;
421
      }
422
      /* srecord file has been found */
423
      if (paramTfound == SB_FALSE) {
424
        paramTfound = SB_TRUE;
425
        flashingTargetIDs[countFlashingPrograms] = 0;
426
        prog_state = PROGSTATE_ORIGIN;
427
      }
428
      srecordFileNames[countFlashingPrograms] = &(argv[paramIdx][0]);
429
      countFlashingPrograms++;
430
      paramTfound = SB_FALSE;
431
      srecordfound = SB_TRUE;
432
    }
433
  }
434

    
435
  /* verify if all parameters were found */
436
  if ( ( ((paramDfound == SB_FALSE) || (paramBfound == SB_FALSE)) && (paramAfound == SB_FALSE)) || (srecordfound == SB_FALSE) )
437
  {
438
    printf("-a, -d, -b or srecord file missing, remember that you can only choose -a or -d\n");
439
    return SB_FALSE;
440
  }
441

    
442
  /* still here so the parsing was successful */
443
  return SB_TRUE;
444
} /*** end of ParseCommandLine ***/
445

    
446

    
447

    
448

    
449

    
450
static void printErrors(void) {
451
  sb_uint8 detected = 0;
452
  sb_uint8 errorIdx;
453
  for (errorIdx=0; errorIdx<MAX_COUNT_FLASHING_PROGRAMS; errorIdx++) {
454
    if (errors[errorIdx] != ERROR_NO) {
455
      detected++;
456
    }
457
  }
458
  if (detected == 0) {
459
    printf("\nEvery firmware successfully updated.\nSerialBoot finished without any errors.\n\n");
460
  } else {
461
    if (detected < countFlashingPrograms) {
462
      printf("\n%i ERRORs detected!\nOnly in the following %i cases SerialBoot updated the firmware:\n", detected, countFlashingPrograms-detected);
463
      for (errorIdx=0; errorIdx<countFlashingPrograms; errorIdx++) {
464
        if (errors[errorIdx] == ERROR_NO) {
465
          printf(" * Flash %i: %s on device 0x%08X\n", errorIdx+1, srecordFileNames[errorIdx], flashingTargetIDs[errorIdx]);
466
        }
467
      }
468
      printf("In the following %i cases SerialBoot could not update the firmware:\n", detected);
469
    } else {
470
      printf("\nERRORs detected!\nEvery firmware update by SerialBoot failed:\n");
471
    }
472
    for (errorIdx=0; errorIdx<countFlashingPrograms; errorIdx++) {
473
      if (errors[errorIdx] != ERROR_NO) {
474
        printf(" * ERROR in Flash %i: ", errorIdx+1);
475
        switch (errors[errorIdx]) {
476
          case ERROR_FILE:
477
            printf("The file %s couldn't be read!\n", srecordFileNames[errorIdx]); break;
478
          case ERROR_DEVICE:
479
            printf("No connection to device 0x%08X!\n", flashingTargetIDs[errorIdx]); break;
480
          default:
481
            printf("Couldn't specify the error. Please check output above!\n"); break;
482
        }
483
      }
484
    }
485
    printf("Please check the errors before trying to update again.\n\n");
486
  }
487
}
488

    
489

    
490

    
491

    
492

    
493
static sb_int32 startFlashMode(void) {
494

    
495
  /* -------------------- start flashing mode ---------------------------------------- */
496
  printf("Set main device on flashing mode\n");
497

    
498
  /* -------------------- open connection -------------------------------------------- */
499
  if (buildConnection(1) == PROG_RESULT_ERROR) {
500
    return PROG_RESULT_ERROR;
501
  }
502

    
503
  //printf("close...");
504

    
505
  /* -------------------- close connection ------------------------------------------- */
506
  if(closeConnection(NULL) == PROG_RESULT_ERROR) {
507
    return PROG_RESULT_ERROR;
508
  }
509

    
510
  /* all done */
511
  printf("Main device is now in flashing mode!\n\n");
512

    
513
  return PROG_RESULT_OK;
514
}
515

    
516

    
517

    
518
static sb_int32 flashProgram(void) {
519
  sb_file hSrecord;
520
  tSrecordParseResults fileParseResults;
521
  tSrecordLineParseResults lineParseResults;
522

    
523
  /* -------------------- start the firmware update procedure ------------------------ */
524
  printf("Starting firmware update for \"%s\" on device 0x%08X\n", srecordFileName, flashingTargetID);
525
  printf("Using %s @ %u bits/s\n", serialDeviceName, serialBaudrate);
526

    
527
  /* -------------------- prepare programming session -------------------------------- */
528
  if (prepareProgrammingSession(&hSrecord, &fileParseResults) == PROG_RESULT_ERROR) {
529
    errorDetected = ERROR_FILE;
530
    return PROG_RESULT_ERROR;
531
  }
532

    
533
  /* -------------------- open connection -------------------------------------------- */
534
  if (buildConnection(0) == PROG_RESULT_ERROR) {
535
    errorDetected = ERROR_DEVICE;
536
    return PROG_RESULT_ERROR;
537
  }
538

    
539
  /* -------------------- programming code ------------------------------------------- */
540
  if (programCode(&hSrecord, &fileParseResults, &lineParseResults) == PROG_RESULT_ERROR) {
541
    errorDetected = ERROR_UNKNOWN;
542
    return PROG_RESULT_ERROR;
543
  }
544

    
545
  /* -------------------- close connection ------------------------------------------- */
546
  if (closeConnection(&hSrecord) == PROG_RESULT_ERROR) {
547
    errorDetected = ERROR_UNKNOWN;
548
    return PROG_RESULT_ERROR;
549
  }
550

    
551
  /* -------------------- close the S-record file ------------------------------------ */
552
  SrecordClose(hSrecord);
553
  printf("Closed S-record file \"%s\"\n", srecordFileName);
554

    
555
  /* all done */
556
  printf("Firmware successfully updated!\n\n");
557

    
558
  return PROG_RESULT_OK;
559
}
560

    
561

    
562

    
563

    
564

    
565

    
566
static sb_int32 startUserProgram(void) {
567
  /* -------------------- start the user program ------------------------------------- */
568
  printf("Resetting all using %s @ %u bits/s\n", serialDeviceName, serialBaudrate);
569

    
570
  /* -------------------- open connection -------------------------------------------- */
571
  if (buildConnection(0) == PROG_RESULT_ERROR) {
572
    return PROG_RESULT_ERROR;
573
  }
574

    
575
  /* -------------------- close connection and reset --------------------------------- */
576
  if (closeConnectionWithReset(NULL) == PROG_RESULT_ERROR) {
577
    return PROG_RESULT_ERROR;
578
  }
579

    
580
  /* all done */
581
  printf("User programs have been started!\n\n");
582

    
583
  return PROG_RESULT_OK;
584
}
585

    
586

    
587

    
588

    
589
static sb_int32 originalMainPart(void) {
590
  sb_file hSrecord;
591
  tSrecordParseResults fileParseResults;
592
  tSrecordLineParseResults lineParseResults;
593

    
594
  /* -------------------- start the firmware update procedure ------------------------ */
595
  printf("Starting firmware update for \"%s\" using %s @ %u bits/s\n", srecordFileName, serialDeviceName, serialBaudrate);
596

    
597
  /* -------------------- prepare programming session -------------------------------- */
598
  if (prepareProgrammingSession(&hSrecord, &fileParseResults) == PROG_RESULT_ERROR) {
599
    return PROG_RESULT_ERROR;
600
  }
601

    
602
  /* -------------------- open serial port and open connection ----------------------- */
603
  if (openSerialPortConnect(0) == PROG_RESULT_ERROR) {
604
    return PROG_RESULT_ERROR;
605
  }
606

    
607
  /* -------------------- open connection -------------------------------------------- */
608
//  if (buildConnection(0) == PROG_RESULT_ERROR) {
609
//    return PROG_RESULT_ERROR;
610
//  }
611

    
612
  /* -------------------- programming code ------------------------------------------- */
613
  if (programCode(&hSrecord, &fileParseResults, &lineParseResults) == PROG_RESULT_ERROR) {
614
    return PROG_RESULT_ERROR;
615
  }
616

    
617
  /* -------------------- close connection and reset --------------------------------- */
618
  if (closeConnectionWithReset(&hSrecord) == PROG_RESULT_ERROR) {
619
    return PROG_RESULT_ERROR;
620
  }
621

    
622
  /* -------------------- close the S-record file ------------------------------------ */
623
  SrecordClose(hSrecord);
624
  printf("Closed S-record file \"%s\"\n", srecordFileName);
625

    
626
  /* all done */
627
  printf("Firmware successfully updated!\n\n");
628

    
629
  return PROG_RESULT_OK;
630
}
631

    
632

    
633

    
634

    
635

    
636
static sb_int32 openSerialPort(void) {
637
  /* -------------------- Open the serial port --------------------------------------- */
638
//  printf("Opening serial port %s...", serialDeviceName);
639
  if (XcpMasterInit(serialDeviceName, serialBaudrate, comIsUart) == SB_FALSE)
640
  {
641
    printf("ERROR\n");
642
    return PROG_RESULT_ERROR;
643
  }
644
//  printf("OK\n");
645
  return PROG_RESULT_OK;
646
}
647

    
648

    
649

    
650

    
651

    
652
static sb_int32 closeSerialPort(void) {
653
  /* -------------------- close the serial port -------------------------------------- */
654
  XcpMasterDeinit();
655
  return PROG_RESULT_OK;
656
}
657

    
658

    
659

    
660

    
661

    
662
static sb_int32 openSerialPortConnect(sb_uint8 start) {
663
  /* -------------------- Connect to XCP slave --------------------------------------- */
664
//  printf("Connecting to bootloader...");
665
  sb_uint8 connections = 0;
666
  if (XcpMasterInit(serialDeviceName, serialBaudrate, comIsUart) == SB_FALSE) {
667
    printf("Could not open serial port\n");
668
  } else {
669
    if (XcpMasterConnect(0) == SB_FALSE) {
670
      connections++;
671
      /* no response. prompt the user to reset the system */
672
      if (flashingTargetID == 0 && start > 0) {
673
        printf("Please connect main device to serial port %s...", serialDeviceName);
674
      } else  {
675
        printf("Try to connect to device...");
676
      }
677
    }
678
  }
679
  /* now keep retrying until we get a response */
680
  sb_uint16 timeoutIdx = 0;
681
  sb_uint16 timeoutEnd = 60;
682
  sb_uint8 noConnectionYet = SB_TRUE;
683
  while (noConnectionYet == SB_TRUE) {
684
    if (XcpMasterInit(serialDeviceName, serialBaudrate, comIsUart) == SB_FALSE) {
685
      if (timeoutIdx == timeoutEnd) {
686
        printf("\nTIMEOUT in building connection. Please start serial port of the main device ...");
687
      }
688
    } else {
689
      if (XcpMasterConnect(0) == SB_FALSE) {
690
        if (timeoutIdx == timeoutEnd) {
691
          printf("\nTIMEOUT in reset. Please reset the main device ...");
692
        }
693
      } else {
694
        noConnectionYet = SB_FALSE;
695
      }
696
    }
697
    /* delay a bit to not pump up the CPU load */
698
    TimeUtilDelayMs(20);
699
    timeoutIdx++;
700
  }
701
  if (connections > 0) {
702
    printf("OK\n");
703
  }
704

    
705
  return PROG_RESULT_OK;
706
}
707

    
708

    
709

    
710

    
711
static sb_int32 buildConnection(sb_uint8 start) {
712
  /* -------------------- Connect to XCP slave --------------------------------------- */
713
//  printf("Connecting to bootloader...");
714
  sb_uint8 connections = 0;
715
  if (XcpMasterConnect(flashingTargetID) == SB_FALSE) {
716
    connections++;
717
    /* no response. prompt the user to reset the system */
718
    if (flashingTargetID == 0 && start > 0) {
719
      printf("Please connect main device to serial port %s...", serialDeviceName);
720
    } else if (flashingTargetID == 0) {
721
      printf("Try to connect to device...");
722
    } else {
723
      printf("Try to connect to device 0x%08X...", flashingTargetID);
724
    }
725
  }
726
  /* now keep retrying until we get a response */
727
  sb_uint16 timeoutIdx = 0;
728
  sb_uint16 timeoutEnd = 50;
729
  while (XcpMasterConnect(flashingTargetID) == SB_FALSE) {
730
    if (timeoutIdx == timeoutEnd) {
731
      printf("\nTIMEOUT: No connection possible.\n\n");
732
      return PROG_RESULT_ERROR;
733
    }
734
    /* delay a bit to not pump up the CPU load */
735
    TimeUtilDelayMs(20);
736
    timeoutIdx++;
737
  }
738
  if (connections > 0) {
739
    printf("OK\n");
740
  }
741

    
742
  return PROG_RESULT_OK;
743
}
744

    
745

    
746

    
747

    
748
static sb_int32 closeConnection(sb_file *hSrecord) {
749
  /* -------------------- Disconnect from XCP slave and perform software reset ------- */
750
//  printf("Performing software reset...");
751
  if (XcpMasterDisconnect() == SB_FALSE)
752
  {
753
    printf("ERROR\n");
754
    if (hSrecord != NULL) {
755
      SrecordClose(*hSrecord);
756
    }
757
    return PROG_RESULT_ERROR;
758
  }
759
//  printf("OK\n");
760

    
761
  return PROG_RESULT_OK;
762
}
763

    
764

    
765

    
766

    
767
static sb_int32 closeConnectionWithReset(sb_file *hSrecord) {
768
  /* -------------------- Disconnect from XCP slave ---------------------------------- */
769
  printf("Resetting...");
770
  if (XcpMasterProgramReset() == SB_FALSE)
771
  {
772
    printf("ERROR\n");
773
    XcpMasterDisconnect();
774
    if (hSrecord != NULL) {
775
      SrecordClose(*hSrecord);
776
    }
777
    return PROG_RESULT_ERROR;
778
  }
779
  printf("OK\n");
780

    
781
  closeSerialPort();
782
  printf("Closed serial port %s\n", serialDeviceName);
783

    
784
  return PROG_RESULT_OK;
785
}
786

    
787

    
788

    
789

    
790
static sb_int32 prepareProgrammingSession(sb_file *hSrecord, tSrecordParseResults *fileParseResults) {
791
  /* -------------------- validating the S-record file ------------------------------- */
792
  printf("Checking formatting of S-record file \"%s\"...", srecordFileName);
793
  if (SrecordIsValid(srecordFileName) == SB_FALSE)
794
  {
795
    printf("ERROR\n\n");
796
    return PROG_RESULT_ERROR;
797
  }
798
  printf("OK\n");
799

    
800
  /* -------------------- opening the S-record file ---------------------------------- */
801
  printf("Opening S-record file \"%s\"...", srecordFileName);
802
  if ((*hSrecord = SrecordOpen(srecordFileName)) == SB_NULL)
803
  {
804
    printf("ERROR\n\n");
805
    return PROG_RESULT_ERROR;
806
  }
807
  printf("OK\n");
808

    
809
  /* -------------------- parsing the S-record file ---------------------------------- */
810
  printf("Parsing S-record file \"%s\"...", srecordFileName);
811
  SrecordParse(*hSrecord, fileParseResults);
812
  printf("OK\n");
813
  printf("-> Lowest memory address:  0x%08x\n", fileParseResults->address_low);
814
  printf("-> Highest memory address: 0x%08x\n", fileParseResults->address_high);
815
  printf("-> Total data bytes: %u\n", fileParseResults->data_bytes_total);
816

    
817
  return PROG_RESULT_OK;
818
}
819

    
820

    
821

    
822

    
823
static sb_int32 programCode(sb_file *hSrecord, tSrecordParseResults *fileParseResults, tSrecordLineParseResults *lineParseResults) {
824
  /* -------------------- Prepare the programming session ---------------------------- */
825
  printf("Initializing programming session...");
826
  if (XcpMasterStartProgrammingSession() == SB_FALSE)
827
  {
828
    printf("ERROR\n");
829
    XcpMasterDisconnect();
830
    SrecordClose(*hSrecord);
831
    return PROG_RESULT_ERROR;
832
  }
833
  printf("OK\n");
834

    
835
  /* -------------------- Erase memory ----------------------------------------------- */
836
  printf("Erasing %u bytes starting at 0x%08x...", fileParseResults->data_bytes_total, fileParseResults->address_low);
837
  if (XcpMasterClearMemory(fileParseResults->address_low, (fileParseResults->address_high - fileParseResults->address_low)) == SB_FALSE)
838
  {
839
    printf("ERROR\n");
840
    XcpMasterDisconnect();
841
    SrecordClose(*hSrecord);
842
    return PROG_RESULT_ERROR;
843
  }
844
  printf("OK\n");
845

    
846
  /* -------------------- Program data ----------------------------------------------- */
847
  printf("Programming data. Please wait...");
848
  /* loop through all S-records with program data */
849
  while (SrecordParseNextDataLine(*hSrecord, lineParseResults) == SB_TRUE)
850
  {
851
    if (XcpMasterProgramData(lineParseResults->address, lineParseResults->length, lineParseResults->data) == SB_FALSE)
852
    {
853
      printf("ERROR\n");
854
      XcpMasterDisconnect();
855
      SrecordClose(*hSrecord);
856
      return PROG_RESULT_ERROR;
857
    }
858
  }
859
  printf("OK\n");
860

    
861
  /* -------------------- Stop the programming session ------------------------------- */
862
  printf("Finishing programming session...");
863
  if (XcpMasterStopProgrammingSession() == SB_FALSE)
864
  {
865
    printf("ERROR\n");
866
    XcpMasterDisconnect();
867
    SrecordClose(*hSrecord);
868
    return PROG_RESULT_ERROR;
869
  }
870
  printf("OK\n");
871

    
872
  return PROG_RESULT_OK;
873
}
874

    
875

    
876

    
877
/*********************************** end of main.c *************************************/