Statistics
| Branch: | Tag: | Revision:

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

History | View | Annotate | Download (32.6 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.00. 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
      flashingTargetIDs[countFlashingPrograms] = flashingTargetID;
410
    }
411
    /* is this a srec file (a parameter without "-" in the beginning) */
412
    else if (argv[paramIdx][0] != '-')
413
    {
414
      if (countFlashingPrograms >= MAX_COUNT_FLASHING_PROGRAMS) {
415
        printf("too many programs to flash (without -T)\n");
416
        return SB_FALSE;
417
      }
418
      /* srecord file has been found */
419
      if (paramTfound == SB_FALSE) {
420
        paramTfound = SB_TRUE;
421
        flashingTargetIDs[countFlashingPrograms] = 0;
422
        prog_state = PROGSTATE_ORIGIN;
423
      }
424
      srecordFileNames[countFlashingPrograms] = &(argv[paramIdx][0]);
425
      countFlashingPrograms++;
426
      paramTfound = SB_FALSE;
427
      srecordfound = SB_TRUE;
428
    }
429
  }
430

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

    
438
  /* still here so the parsing was successful */
439
  return SB_TRUE;
440
} /*** end of ParseCommandLine ***/
441

    
442

    
443

    
444

    
445

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

    
485

    
486

    
487

    
488

    
489
static sb_int32 startFlashMode(void) {
490

    
491
  /* -------------------- start flashing mode ---------------------------------------- */
492
  printf("Set main device on flashing mode\n");
493

    
494
  /* -------------------- open connection -------------------------------------------- */
495
  if (buildConnection(1) == PROG_RESULT_ERROR) {
496
    return PROG_RESULT_ERROR;
497
  }
498

    
499
  //printf("close...");
500

    
501
  /* -------------------- close connection ------------------------------------------- */
502
  if(closeConnection(NULL) == PROG_RESULT_ERROR) {
503
    return PROG_RESULT_ERROR;
504
  }
505

    
506
  /* all done */
507
  printf("Main device is now in flashing mode!\n\n");
508

    
509
  return PROG_RESULT_OK;
510
}
511

    
512

    
513

    
514
static sb_int32 flashProgram(void) {
515
  sb_file hSrecord;
516
  tSrecordParseResults fileParseResults;
517
  tSrecordLineParseResults lineParseResults;
518

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

    
523
  /* -------------------- prepare programming session -------------------------------- */
524
  if (prepareProgrammingSession(&hSrecord, &fileParseResults) == PROG_RESULT_ERROR) {
525
    errorDetected = ERROR_FILE;
526
    return PROG_RESULT_ERROR;
527
  }
528

    
529
  /* -------------------- open connection -------------------------------------------- */
530
  if (buildConnection(0) == PROG_RESULT_ERROR) {
531
    errorDetected = ERROR_DEVICE;
532
    return PROG_RESULT_ERROR;
533
  }
534

    
535
  /* -------------------- programming code ------------------------------------------- */
536
  if (programCode(&hSrecord, &fileParseResults, &lineParseResults) == PROG_RESULT_ERROR) {
537
    errorDetected = ERROR_UNKNOWN;
538
    return PROG_RESULT_ERROR;
539
  }
540

    
541
  /* -------------------- close connection ------------------------------------------- */
542
  if (closeConnection(&hSrecord) == PROG_RESULT_ERROR) {
543
    errorDetected = ERROR_UNKNOWN;
544
    return PROG_RESULT_ERROR;
545
  }
546

    
547
  /* -------------------- close the S-record file ------------------------------------ */
548
  SrecordClose(hSrecord);
549
  printf("Closed S-record file \"%s\"\n", srecordFileName);
550

    
551
  /* all done */
552
  printf("Firmware successfully updated!\n\n");
553

    
554
  return PROG_RESULT_OK;
555
}
556

    
557

    
558

    
559

    
560

    
561

    
562
static sb_int32 startUserProgram(void) {
563
  /* -------------------- start the user program ------------------------------------- */
564
  printf("Resetting all using %s @ %u bits/s\n", serialDeviceName, serialBaudrate);
565

    
566
  /* -------------------- open connection -------------------------------------------- */
567
  if (buildConnection(0) == PROG_RESULT_ERROR) {
568
    return PROG_RESULT_ERROR;
569
  }
570

    
571
  /* -------------------- close connection and reset --------------------------------- */
572
  if (closeConnectionWithReset(NULL) == PROG_RESULT_ERROR) {
573
    return PROG_RESULT_ERROR;
574
  }
575

    
576
  /* all done */
577
  printf("User programs have been started!\n\n");
578

    
579
  return PROG_RESULT_OK;
580
}
581

    
582

    
583

    
584

    
585
static sb_int32 originalMainPart(void) {
586
  sb_file hSrecord;
587
  tSrecordParseResults fileParseResults;
588
  tSrecordLineParseResults lineParseResults;
589

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

    
593
  /* -------------------- prepare programming session -------------------------------- */
594
  if (prepareProgrammingSession(&hSrecord, &fileParseResults) == PROG_RESULT_ERROR) {
595
    return PROG_RESULT_ERROR;
596
  }
597

    
598
  /* -------------------- open serial port and open connection ----------------------- */
599
  if (openSerialPortConnect(0) == PROG_RESULT_ERROR) {
600
    return PROG_RESULT_ERROR;
601
  }
602

    
603
  /* -------------------- open connection -------------------------------------------- */
604
//  if (buildConnection(0) == PROG_RESULT_ERROR) {
605
//    return PROG_RESULT_ERROR;
606
//  }
607

    
608
  /* -------------------- programming code ------------------------------------------- */
609
  if (programCode(&hSrecord, &fileParseResults, &lineParseResults) == PROG_RESULT_ERROR) {
610
    return PROG_RESULT_ERROR;
611
  }
612

    
613
  /* -------------------- close connection and reset --------------------------------- */
614
  if (closeConnectionWithReset(&hSrecord) == PROG_RESULT_ERROR) {
615
    return PROG_RESULT_ERROR;
616
  }
617

    
618
  /* -------------------- close the S-record file ------------------------------------ */
619
  SrecordClose(hSrecord);
620
  printf("Closed S-record file \"%s\"\n", srecordFileName);
621

    
622
  /* all done */
623
  printf("Firmware successfully updated!\n\n");
624

    
625
  return PROG_RESULT_OK;
626
}
627

    
628

    
629

    
630

    
631

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

    
644

    
645

    
646

    
647

    
648
static sb_int32 closeSerialPort(void) {
649
  /* -------------------- close the serial port -------------------------------------- */
650
  XcpMasterDeinit();
651
  return PROG_RESULT_OK;
652
}
653

    
654

    
655

    
656

    
657

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

    
701
  return PROG_RESULT_OK;
702
}
703

    
704

    
705

    
706

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

    
738
  return PROG_RESULT_OK;
739
}
740

    
741

    
742

    
743

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

    
757
  return PROG_RESULT_OK;
758
}
759

    
760

    
761

    
762

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

    
777
  closeSerialPort();
778
  printf("Closed serial port %s\n", serialDeviceName);
779

    
780
  return PROG_RESULT_OK;
781
}
782

    
783

    
784

    
785

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

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

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

    
813
  return PROG_RESULT_OK;
814
}
815

    
816

    
817

    
818

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

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

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

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

    
868
  return PROG_RESULT_OK;
869
}
870

    
871

    
872

    
873
/*********************************** end of main.c *************************************/