Statistics
| Branch: | Tag: | Revision:

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

History | View | Annotate | Download (32.276 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
      int idx=0;
384
      while (choosenID[idx] != 0x00) {
385
        if (flashingTargetID > 25 || ((int)choosenID[idx])-48 < 0 || ((int)choosenID[idx])-48 > 9) {
386
          flashingTargetID = 0;
387
          printf("given flashing id too high\n");
388
          return SB_FALSE;
389
        }
390
        flashingTargetID *= 10;
391
        if (flashingTargetID >= 250 && ((int)choosenID[idx])-48 > 5) {
392
          printf("given flashing id too high\n");
393
          return SB_FALSE;
394
        }
395
        flashingTargetID += ((int)choosenID[idx])-48;
396
        idx++;
397
      }
398
      flashingTargetIDs[countFlashingPrograms] = flashingTargetID;
399
    }
400
    /* is this a srec file (a parameter without "-" in the beginning) */
401
    else if (argv[paramIdx][0] != '-')
402
    {
403
      if (countFlashingPrograms >= MAX_COUNT_FLASHING_PROGRAMS) {
404
        printf("too many programs to flash (without -T)\n");
405
        return SB_FALSE;
406
      }
407
      /* srecord file has been found */
408
      if (paramTfound == SB_FALSE) {
409
        paramTfound = SB_TRUE;
410
        flashingTargetIDs[countFlashingPrograms] = 0;
411
        prog_state = PROGSTATE_ORIGIN;
412
      }
413
      srecordFileNames[countFlashingPrograms] = &(argv[paramIdx][0]);
414
      countFlashingPrograms++;
415
      paramTfound = SB_FALSE;
416
      srecordfound = SB_TRUE;
417
    }
418
  }
419

    
420
  /* verify if all parameters were found */
421
  if ( ( ((paramDfound == SB_FALSE) || (paramBfound == SB_FALSE)) && (paramAfound == SB_FALSE)) || (srecordfound == SB_FALSE) )
422
  {
423
    printf("-a, -d, -b or srecord file missing, remember that you can only choose -a or -d\n");
424
    return SB_FALSE;
425
  }
426

    
427
  /* still here so the parsing was successful */
428
  return SB_TRUE;
429
} /*** end of ParseCommandLine ***/
430

    
431

    
432

    
433

    
434

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

    
474

    
475

    
476

    
477

    
478
static sb_int32 startFlashMode(void) {
479

    
480
  /* -------------------- start flashing mode ---------------------------------------- */
481
  printf("Set main device on flashing mode\n");
482

    
483
  /* -------------------- open connection -------------------------------------------- */
484
  if (buildConnection(1) == PROG_RESULT_ERROR) {
485
    return PROG_RESULT_ERROR;
486
  }
487

    
488
  //printf("close...");
489

    
490
  /* -------------------- close connection ------------------------------------------- */
491
  if(closeConnection(NULL) == PROG_RESULT_ERROR) {
492
    return PROG_RESULT_ERROR;
493
  }
494

    
495
  /* all done */
496
  printf("Main device is now in flashing mode!\n\n");
497

    
498
  return PROG_RESULT_OK;
499
}
500

    
501

    
502

    
503
static sb_int32 flashProgram(void) {
504
  sb_file hSrecord;
505
  tSrecordParseResults fileParseResults;
506
  tSrecordLineParseResults lineParseResults;
507

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

    
512
  /* -------------------- prepare programming session -------------------------------- */
513
  if (prepareProgrammingSession(&hSrecord, &fileParseResults) == PROG_RESULT_ERROR) {
514
    errorDetected = ERROR_FILE;
515
    return PROG_RESULT_ERROR;
516
  }
517

    
518
  /* -------------------- open connection -------------------------------------------- */
519
  if (buildConnection(0) == PROG_RESULT_ERROR) {
520
    errorDetected = ERROR_DEVICE;
521
    return PROG_RESULT_ERROR;
522
  }
523

    
524
  /* -------------------- programming code ------------------------------------------- */
525
  if (programCode(&hSrecord, &fileParseResults, &lineParseResults) == PROG_RESULT_ERROR) {
526
    errorDetected = ERROR_UNKNOWN;
527
    return PROG_RESULT_ERROR;
528
  }
529

    
530
  /* -------------------- close connection ------------------------------------------- */
531
  if (closeConnection(&hSrecord) == PROG_RESULT_ERROR) {
532
    errorDetected = ERROR_UNKNOWN;
533
    return PROG_RESULT_ERROR;
534
  }
535

    
536
  /* -------------------- close the S-record file ------------------------------------ */
537
  SrecordClose(hSrecord);
538
  printf("Closed S-record file \"%s\"\n", srecordFileName);
539

    
540
  /* all done */
541
  printf("Firmware successfully updated!\n\n");
542

    
543
  return PROG_RESULT_OK;
544
}
545

    
546

    
547

    
548

    
549

    
550

    
551
static sb_int32 startUserProgram(void) {
552
  /* -------------------- start the user program ------------------------------------- */
553
  printf("Resetting all using %s @ %u bits/s\n", serialDeviceName, serialBaudrate);
554

    
555
  /* -------------------- open connection -------------------------------------------- */
556
  if (buildConnection(0) == PROG_RESULT_ERROR) {
557
    return PROG_RESULT_ERROR;
558
  }
559

    
560
  /* -------------------- close connection and reset --------------------------------- */
561
  if (closeConnectionWithReset(NULL) == PROG_RESULT_ERROR) {
562
    return PROG_RESULT_ERROR;
563
  }
564

    
565
  /* all done */
566
  printf("User programs have been started!\n\n");
567

    
568
  return PROG_RESULT_OK;
569
}
570

    
571

    
572

    
573

    
574
static sb_int32 originalMainPart(void) {
575
  sb_file hSrecord;
576
  tSrecordParseResults fileParseResults;
577
  tSrecordLineParseResults lineParseResults;
578

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

    
582
  /* -------------------- prepare programming session -------------------------------- */
583
  if (prepareProgrammingSession(&hSrecord, &fileParseResults) == PROG_RESULT_ERROR) {
584
    return PROG_RESULT_ERROR;
585
  }
586

    
587
  /* -------------------- open serial port and open connection ----------------------- */
588
  if (openSerialPortConnect(0) == PROG_RESULT_ERROR) {
589
    return PROG_RESULT_ERROR;
590
  }
591

    
592
  /* -------------------- open connection -------------------------------------------- */
593
//  if (buildConnection(0) == PROG_RESULT_ERROR) {
594
//    return PROG_RESULT_ERROR;
595
//  }
596

    
597
  /* -------------------- programming code ------------------------------------------- */
598
  if (programCode(&hSrecord, &fileParseResults, &lineParseResults) == PROG_RESULT_ERROR) {
599
    return PROG_RESULT_ERROR;
600
  }
601

    
602
  /* -------------------- close connection and reset --------------------------------- */
603
  if (closeConnectionWithReset(&hSrecord) == PROG_RESULT_ERROR) {
604
    return PROG_RESULT_ERROR;
605
  }
606

    
607
  /* -------------------- close the S-record file ------------------------------------ */
608
  SrecordClose(hSrecord);
609
  printf("Closed S-record file \"%s\"\n", srecordFileName);
610

    
611
  /* all done */
612
  printf("Firmware successfully updated!\n\n");
613

    
614
  return PROG_RESULT_OK;
615
}
616

    
617

    
618

    
619

    
620

    
621
static sb_int32 openSerialPort(void) {
622
  /* -------------------- Open the serial port --------------------------------------- */
623
//  printf("Opening serial port %s...", serialDeviceName);
624
  if (XcpMasterInit(serialDeviceName, serialBaudrate, comIsUart) == SB_FALSE)
625
  {
626
    printf("ERROR\n");
627
    return PROG_RESULT_ERROR;
628
  }
629
//  printf("OK\n");
630
  return PROG_RESULT_OK;
631
}
632

    
633

    
634

    
635

    
636

    
637
static sb_int32 closeSerialPort(void) {
638
  /* -------------------- close the serial port -------------------------------------- */
639
  XcpMasterDeinit();
640
  return PROG_RESULT_OK;
641
}
642

    
643

    
644

    
645

    
646

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

    
690
  return PROG_RESULT_OK;
691
}
692

    
693

    
694

    
695

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

    
727
  return PROG_RESULT_OK;
728
}
729

    
730

    
731

    
732

    
733
static sb_int32 closeConnection(sb_file *hSrecord) {
734
  /* -------------------- Disconnect from XCP slave and perform software reset ------- */
735
//  printf("Performing software reset...");
736
  if (XcpMasterDisconnect() == SB_FALSE)
737
  {
738
    printf("ERROR\n");
739
    if (hSrecord != NULL) {
740
      SrecordClose(*hSrecord);
741
    }
742
    return PROG_RESULT_ERROR;
743
  }
744
//  printf("OK\n");
745

    
746
  return PROG_RESULT_OK;
747
}
748

    
749

    
750

    
751

    
752
static sb_int32 closeConnectionWithReset(sb_file *hSrecord) {
753
  /* -------------------- Disconnect from XCP slave ---------------------------------- */
754
  printf("Resetting...");
755
  if (XcpMasterProgramReset() == SB_FALSE)
756
  {
757
    printf("ERROR\n");
758
    XcpMasterDisconnect();
759
    if (hSrecord != NULL) {
760
      SrecordClose(*hSrecord);
761
    }
762
    return PROG_RESULT_ERROR;
763
  }
764
  printf("OK\n");
765

    
766
  closeSerialPort();
767
  printf("Closed serial port %s\n", serialDeviceName);
768

    
769
  return PROG_RESULT_OK;
770
}
771

    
772

    
773

    
774

    
775
static sb_int32 prepareProgrammingSession(sb_file *hSrecord, tSrecordParseResults *fileParseResults) {
776
  /* -------------------- validating the S-record file ------------------------------- */
777
  printf("Checking formatting of S-record file \"%s\"...", srecordFileName);
778
  if (SrecordIsValid(srecordFileName) == SB_FALSE)
779
  {
780
    printf("ERROR\n\n");
781
    return PROG_RESULT_ERROR;
782
  }
783
  printf("OK\n");
784

    
785
  /* -------------------- opening the S-record file ---------------------------------- */
786
  printf("Opening S-record file \"%s\"...", srecordFileName);
787
  if ((*hSrecord = SrecordOpen(srecordFileName)) == SB_NULL)
788
  {
789
    printf("ERROR\n\n");
790
    return PROG_RESULT_ERROR;
791
  }
792
  printf("OK\n");
793

    
794
  /* -------------------- parsing the S-record file ---------------------------------- */
795
  printf("Parsing S-record file \"%s\"...", srecordFileName);
796
  SrecordParse(*hSrecord, fileParseResults);
797
  printf("OK\n");
798
  printf("-> Lowest memory address:  0x%08x\n", fileParseResults->address_low);
799
  printf("-> Highest memory address: 0x%08x\n", fileParseResults->address_high);
800
  printf("-> Total data bytes: %u\n", fileParseResults->data_bytes_total);
801

    
802
  return PROG_RESULT_OK;
803
}
804

    
805

    
806

    
807

    
808
static sb_int32 programCode(sb_file *hSrecord, tSrecordParseResults *fileParseResults, tSrecordLineParseResults *lineParseResults) {
809
  /* -------------------- Prepare the programming session ---------------------------- */
810
  printf("Initializing programming session...");
811
  if (XcpMasterStartProgrammingSession() == SB_FALSE)
812
  {
813
    printf("ERROR\n");
814
    XcpMasterDisconnect();
815
    SrecordClose(*hSrecord);
816
    return PROG_RESULT_ERROR;
817
  }
818
  printf("OK\n");
819

    
820
  /* -------------------- Erase memory ----------------------------------------------- */
821
  printf("Erasing %u bytes starting at 0x%08x...", fileParseResults->data_bytes_total, fileParseResults->address_low);
822
  if (XcpMasterClearMemory(fileParseResults->address_low, (fileParseResults->address_high - fileParseResults->address_low)) == SB_FALSE)
823
  {
824
    printf("ERROR\n");
825
    XcpMasterDisconnect();
826
    SrecordClose(*hSrecord);
827
    return PROG_RESULT_ERROR;
828
  }
829
  printf("OK\n");
830

    
831
  /* -------------------- Program data ----------------------------------------------- */
832
  printf("Programming data. Please wait...");
833
  /* loop through all S-records with program data */
834
  while (SrecordParseNextDataLine(*hSrecord, lineParseResults) == SB_TRUE)
835
  {
836
    if (XcpMasterProgramData(lineParseResults->address, lineParseResults->length, lineParseResults->data) == SB_FALSE)
837
    {
838
      printf("ERROR\n");
839
      XcpMasterDisconnect();
840
      SrecordClose(*hSrecord);
841
      return PROG_RESULT_ERROR;
842
    }
843
  }
844
  printf("OK\n");
845

    
846
  /* -------------------- Stop the programming session ------------------------------- */
847
  printf("Finishing programming session...");
848
  if (XcpMasterStopProgrammingSession() == SB_FALSE)
849
  {
850
    printf("ERROR\n");
851
    XcpMasterDisconnect();
852
    SrecordClose(*hSrecord);
853
    return PROG_RESULT_ERROR;
854
  }
855
  printf("OK\n");
856

    
857
  return PROG_RESULT_OK;
858
}
859

    
860

    
861

    
862
/*********************************** end of main.c *************************************/