summaryrefslogtreecommitdiffhomepage
path: root/digital/zigbit/bitcloud/stack/Components/HAL/drivers/OFD/src/ofdAt45dbDriver.c
blob: f06d765d7060c90a2045994c6525895b91f0d9f9 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
/**************************************************************************//**
\file  ofdAt45dbDriver.c

\brief Implementation of chip-flash interface.

\author
    Atmel Corporation: http://www.atmel.com \n
    Support email: avr@atmel.com

  Copyright (c) 2008-2011, Atmel Corporation. All rights reserved.
  Licensed under Atmel's Limited License Agreement (BitCloudTM).

\internal
  History:
    20/07/10 A. Khromykh - Created
*******************************************************************************/
/******************************************************************************
 *   WARNING: CHANGING THIS FILE MAY AFFECT CORE FUNCTIONALITY OF THE STACK.  *
 *   EXPERT USERS SHOULD PROCEED WITH CAUTION.                                *
 ******************************************************************************/

#ifdef _OTAU_
#if (EXTERNAL_MEMORY == AT45DB041) && (APP_USE_OTAU == 1)
#if APP_USE_FAKE_OFD_DRIVER == 0

/******************************************************************************
                   Includes section
******************************************************************************/
#include <ofdExtMemory.h>
#include <ofdMemoryDriver.h>
#include <spi.h>
#include <eeprom.h>
#include <appTimer.h>

/******************************************************************************
                   Define(s) section
******************************************************************************/
#define SPI_BUSY_POLL_PERIOD      10
// cycles of counting flash crc before context gap.
#define ATOMIC_COUNTING           128
#define EEPROM_OK                  0
#define EEPROM_BUSY                -2
#define ALL_DATA_HAS_BEEN_SAVED   0xFFFFFFFFul

/******************************************************************************
                   Types section
******************************************************************************/
typedef enum
{
  FLASH_BUSY,
  FLASH_READY
} FlashBusyState_t;

typedef enum
{
  FLASH_TRANSACTION,
  EEPROM_TRANSACTION
} DelayedTransactionType_t;

/******************************************************************************
                   Prototypes section
******************************************************************************/
static inline uint8_t ofdReadStatusRegister(void);
static inline void ofdStartPollTimer(DelayedTransactionType_t type);
static void ofdReadImageTable(void);
static void ofdSaveCrcCallback(void);
static void ofdSaveCurrentEepromImage(void);
static void ofdFlushCrcCallback(OFD_Status_t status, OFD_ImageInfo_t *pInfo);
static void ofdSaveCurrentEepromImageContinue(void);
static void ofdPollBusyState(void);
static void ofdStartFlashDelayedTransaction(void);
static void ofdStartEepromDelayedTransaction(void);
static void ofdClearFlashInternalBuffer(void);
uint8_t ofdReadInternalFlash(uint32_t flashAddress);
#if defined(_OFD_DEBUG_)
void ofdReadData(uint32_t address, uint8_t *data, uint16_t size, OFD_Callback_t cb);
#endif

/******************************************************************************
                   External variables section
******************************************************************************/
extern HAL_SpiDescriptor_t spiDesc;
extern OFD_Position_t sectorNumber;
extern OFD_Position_t actionSector;
extern OFD_Callback_t ofdCallback;
extern OFD_Callback_t ofdAuxCallback;
extern OFD_MemoryAccessParam_t localAccessStructure;
extern OFD_ImageInfo_t imageInfo;
extern OfdImageTable_t imageTable;
extern OfdInternalMemoryAccessParam_t internalAccessParam;

/******************************************************************************
                   Global variables section
******************************************************************************/
static HAL_AppTimer_t ofdBusyTimer =
{
  .interval = SPI_BUSY_POLL_PERIOD,
  .mode     = TIMER_ONE_SHOT_MODE,
};
void (* delayedTransaction)(void) = NULL;
static uint16_t serviceGapData = 0;
static uint32_t flushedPageAddr = ALL_DATA_HAS_BEEN_SAVED;
#if defined(_OFD_DEBUG_)
static HAL_UsartDescriptor_t usartDescriptor;
static uint32_t debugOffset = 0ul;
static uint8_t  debugBuffer[OFD_BLOCK_SIZE];
#endif

/******************************************************************************
                   Implementations section
******************************************************************************/
/**************************************************************************//**
\brief Checks flash state.

\return flash states: \n
  FLASH_BUSY  \n
  FLASH_READY
******************************************************************************/
static inline FlashBusyState_t ofdCheckBusyState(void)
{
  uint8_t statusReg = ofdReadStatusRegister();

  if (statusReg & RDY)
    return FLASH_READY;

  return FLASH_BUSY;
}

/**************************************************************************//**
\brief Starts flash delayed transaction.
******************************************************************************/
static void ofdStartFlashDelayedTransaction(void)
{
  if (FLASH_READY == ofdCheckBusyState())
    delayedTransaction();
  else
    ofdStartPollTimer(FLASH_TRANSACTION);
}

/**************************************************************************//**
\brief Starts eeprom delayed transaction.
******************************************************************************/
static void ofdStartEepromDelayedTransaction(void)
{
  if (!HAL_IsEepromBusy())
    delayedTransaction();
  else
    ofdStartPollTimer(EEPROM_TRANSACTION);
}

/**************************************************************************//**
\brief Starts timer for start delayed transaction.

\param[in]
  type - transaction type (flash or eeprom)
******************************************************************************/
static inline void ofdStartPollTimer(DelayedTransactionType_t type)
{
  if (FLASH_TRANSACTION == type)
    ofdBusyTimer.callback = ofdStartFlashDelayedTransaction;
  else
    ofdBusyTimer.callback = ofdStartEepromDelayedTransaction;

  HAL_StartAppTimer(&ofdBusyTimer);
}

/**************************************************************************//**
\brief Routine of eeprom access.
\param[in]
   result - result of hal eeprom action
\param[in]
   action - initiator action
\return
   false - incorrect parameters
   true  - eeprom transaction is started
******************************************************************************/
static bool ofdEepromHandler(int result, void(* action)())
{
  switch (result)
  {
    case EEPROM_OK:
      return true;
    case EEPROM_BUSY:
      delayedTransaction = action;
      ofdStartPollTimer(EEPROM_TRANSACTION);
      return true;
    default:
      return false;
  }
}

/**************************************************************************//**
\brief Returns SUCCESS status.
******************************************************************************/
static void ofdReturnSuccessStatus(void)
{
  if (ofdCallback)
    ofdCallback(OFD_STATUS_SUCCESS);
}

/**************************************************************************//**
\brief Reads image table.
******************************************************************************/
static void ofdReadImageTable(void)
{
  HAL_EepromParams_t params;

  params.address = OFD_SERVICE_INFO_SIZE - sizeof(OfdImageTable_t);
  params.data = &imageTable;
  params.length = sizeof(OfdImageTable_t);

  if (!ofdEepromHandler(HAL_ReadEeprom(&params, ofdReturnSuccessStatus), ofdReadImageTable))
    if (ofdCallback)
      ofdCallback(OFD_STATUS_INCORRECT_EEPROM_PARAMETER);
}

/**************************************************************************//**
\brief Reads status register and check unchanged bits.
******************************************************************************/
void ofdFindStorageSpace(void)
{
  if (STATUS_UNCHANGED_BITS == (ofdReadStatusRegister() & STATUS_UNCHANGED_BIT_MASK))
  {
    // read image table to global variable
    ofdReadImageTable();
    return;
  }

  if (ofdCallback)
    ofdCallback(OFD_STATUS_UNKNOWN_EXTERNAL_FLASH_TYPE);
}

/**************************************************************************//**
\brief Reads status register from the external flash.

\return status register
******************************************************************************/
static inline uint8_t ofdReadStatusRegister(void)
{
  uint16_t regStatus = RDSR;

  GPIO_EXT_MEM_CS_clr();
  HAL_ReadSpi(&spiDesc, (uint8_t *)&regStatus, sizeof(uint16_t));
  GPIO_EXT_MEM_CS_set();

  return (uint8_t)(regStatus >> 8);
}

/**************************************************************************//**
\brief Starts physical block(8 pages) erasing in the external memory.

\param[in]
  blockNumber - address of the erased block
******************************************************************************/
void ofdEraseBlock(uint8_t blockNumber)
{
  uint32_t erasedBlock = OFD_LITTLE_TO_BIG_ENDIAN((uint32_t)blockNumber << 4);

  erasedBlock >>= 8;
  erasedBlock |= BLOCK_ERASE;

  GPIO_EXT_MEM_CS_clr();
  HAL_WriteSpi(&spiDesc, (uint8_t *)&erasedBlock, sizeof(uint32_t));
  GPIO_EXT_MEM_CS_set();
}

/**************************************************************************//**
\brief Starts image erasing in the external memory.
******************************************************************************/
void ofdEraseImage(void)
{
  if (FLASH_BUSY == ofdCheckBusyState())
  { // waits till flash ready
    delayedTransaction = ofdEraseImage;
    ofdStartPollTimer(FLASH_TRANSACTION);
    return;
  }

  if (OFD_POSITION_1 == sectorNumber)
    ofdEraseBlock(FIRST_HALF_BLOCK_NUMBER + serviceGapData++);
  else
    ofdEraseBlock(SECOND_HALF_BLOCK_NUMBER + serviceGapData++);

  if (serviceGapData < OFD_USED_BLOCKS_AMOUNT)
  {
    delayedTransaction = ofdEraseImage;
    ofdStartPollTimer(FLASH_TRANSACTION);
  }
  else
  {
    serviceGapData = 0;
    ofdReturnSuccessStatus();
  }
}

/**************************************************************************//**
\brief Writes data to the external memory.
******************************************************************************/
void ofdWriteData(void)
{
  uint8_t *dataPointer;
  uint16_t dataLength;
  uint32_t address;
  uint32_t pageAddr;
  uint32_t byteAddr;

  if (!localAccessStructure.length)
  {
    ofdReturnSuccessStatus();
    return;
  }

  if (FLASH_BUSY == ofdCheckBusyState())
  { // waits till flash ready
    delayedTransaction = ofdWriteData;
    ofdStartPollTimer(FLASH_TRANSACTION);
    return;
  }

  pageAddr = localAccessStructure.offset / PAGE_SIZE;

  if ((pageAddr > flushedPageAddr) && (ALL_DATA_HAS_BEEN_SAVED != flushedPageAddr))
  { // there is gap in the image address map.
    ofdFlushData();
    delayedTransaction = ofdClearFlashInternalBuffer;
    ofdStartPollTimer(FLASH_TRANSACTION);
    return;
  }

  flushedPageAddr = pageAddr;
  byteAddr = localAccessStructure.offset % PAGE_SIZE;
  dataPointer = localAccessStructure.data;

  if ((byteAddr + localAccessStructure.length) > PAGE_SIZE)
    dataLength = PAGE_SIZE - byteAddr;
  else
    dataLength = localAccessStructure.length;

  localAccessStructure.data += dataLength;
  localAccessStructure.offset += dataLength;
  localAccessStructure.length -= dataLength;

  address = OFD_LITTLE_TO_BIG_ENDIAN(byteAddr);
  address |= WRITE_BUF1;

  GPIO_EXT_MEM_CS_clr();
  HAL_WriteSpi(&spiDesc, (uint8_t *)&address, sizeof(uint32_t));
  HAL_WriteSpi(&spiDesc, dataPointer, dataLength);
  GPIO_EXT_MEM_CS_set();

  if (PAGE_SIZE == (byteAddr + dataLength))
  {
    ofdFlushData();
    delayedTransaction = ofdClearFlashInternalBuffer;
    ofdStartPollTimer(FLASH_TRANSACTION);
    return;
  }

  ofdReturnSuccessStatus();
}

/**************************************************************************//**
\brief Calls callback about end of eeprom saving.
******************************************************************************/
static void ofdSaveCrcCallback(void)
{
  if (ofdCallback)
    ((OFD_InfoCallback_t)ofdCallback)(OFD_STATUS_SUCCESS, &imageInfo);
}

/**************************************************************************//**
\brief Saves image table to the internal eeprom.
******************************************************************************/
void ofdSaveImageTable(void)
{
  HAL_EepromParams_t params;

  params.address = OFD_SERVICE_INFO_SIZE-1;
  params.data = &imageTable;
  params.length = sizeof(OfdImageTable_t);

  if (!ofdEepromHandler(HAL_WriteEeprom(&params, ofdSaveCrcCallback), ofdSaveImageTable))
    if (ofdCallback)
      ((OFD_InfoCallback_t)ofdCallback)(OFD_STATUS_INCORRECT_EEPROM_PARAMETER, &imageInfo);
}

/**************************************************************************//**
\brief Saves crc to the internal eeprom.
******************************************************************************/
void ofdSaveCrc(void)
{
  HAL_EepromParams_t params;

  params.address = sectorNumber + 1;
  params.data = &imageInfo.crc;
  params.length = sizeof(uint8_t);

  if (!ofdEepromHandler(HAL_WriteEeprom(&params, ofdSaveImageTable), ofdSaveCrc))
    if (ofdCallback)
      ((OFD_InfoCallback_t)ofdCallback)(OFD_STATUS_INCORRECT_EEPROM_PARAMETER, &imageInfo);
}

/**************************************************************************//**
\brief Clears internal flash buffer.
******************************************************************************/
static void ofdClearFlashInternalBuffer(void)
{
  uint32_t address = 0ul;
  uint64_t data;
  uint8_t itr;

  if (FLASH_BUSY == ofdCheckBusyState())
  { // waits till flash ready
    delayedTransaction = ofdClearFlashInternalBuffer;
    ofdStartPollTimer(FLASH_TRANSACTION);
    return;
  }

  memset((uint8_t *)&data, 0xFF, sizeof(uint64_t));

  address |= WRITE_BUF1;
  GPIO_EXT_MEM_CS_clr();
  HAL_WriteSpi(&spiDesc, (uint8_t *)&address, sizeof(uint32_t));
  for (itr = 0; itr < (PAGE_SIZE / sizeof(uint64_t)); itr++)
     HAL_WriteSpi(&spiDesc, (uint8_t *)&data, sizeof(uint64_t));
  GPIO_EXT_MEM_CS_set();

  ofdWriteData();
}

/**************************************************************************//**
\brief Flushs memory buffer to flash.
******************************************************************************/
void ofdFlushData(void)
{
  if (ALL_DATA_HAS_BEEN_SAVED == flushedPageAddr)
    return;

  flushedPageAddr = OFD_LITTLE_TO_BIG_ENDIAN(flushedPageAddr << 1);
  flushedPageAddr >>= 8;
  flushedPageAddr |= PROGRAM_BUF1;
  GPIO_EXT_MEM_CS_clr();
  HAL_WriteSpi(&spiDesc, (uint8_t *)&flushedPageAddr, sizeof(uint32_t));
  GPIO_EXT_MEM_CS_set();
  flushedPageAddr = ALL_DATA_HAS_BEEN_SAVED;
}

/**************************************************************************//**
\brief Checks image crc.
******************************************************************************/
void ofdCheckCrc(void)
{
  uint32_t address;
  uint32_t pageAddr;
  uint32_t byteAddr;
  uint8_t atomicCounting = ATOMIC_COUNTING;

  if (FLASH_BUSY == ofdCheckBusyState())
  { // waits till flash ready
    delayedTransaction = ofdCheckCrc;
    ofdStartPollTimer(FLASH_TRANSACTION);
    return;
  }

  while (atomicCounting--)
  {
    pageAddr = localAccessStructure.offset / PAGE_SIZE;
    byteAddr = localAccessStructure.offset % PAGE_SIZE;
    address = byteAddr | (pageAddr << 9) | ((uint32_t)READ << 24);
    address = OFD_LITTLE_TO_BIG_ENDIAN(address);
    GPIO_EXT_MEM_CS_clr();
    HAL_WriteSpi(&spiDesc, (uint8_t *)&address, sizeof(uint32_t));
    // load 32 don't care bits
    HAL_WriteSpi(&spiDesc, (uint8_t *)&address, sizeof(uint32_t));
    HAL_ReadSpi(&spiDesc, localAccessStructure.data, OFD_BLOCK_FOR_CHECK_CRC);
    GPIO_EXT_MEM_CS_set();  // release spi cs
    imageInfo.crc = ofdCrc(imageInfo.crc, localAccessStructure.data, OFD_BLOCK_FOR_CHECK_CRC);
    localAccessStructure.offset += OFD_BLOCK_FOR_CHECK_CRC;
    localAccessStructure.length -= OFD_BLOCK_FOR_CHECK_CRC;
    if (!localAccessStructure.length)
    {
      ofdSaveCrc();
      return;
    }
  }
  // context gap
  delayedTransaction = ofdCheckCrc;
  ofdStartPollTimer(FLASH_TRANSACTION);
}

/**************************************************************************//**
\brief Callback for saving internal flash.

\param[in] status - status of the data flash writing
******************************************************************************/
void ofdWriteFlashDataCallback(OFD_Status_t status)
{
  uint32_t maxOffset;

  if (OFD_STATUS_SUCCESS != status)
  {
    if (ofdAuxCallback)
      ofdAuxCallback(status);
    return;
  }
  if (OFD_POSITION_1 == sectorNumber)
    maxOffset = OFD_IMAGE1_START_ADDRESS + OFD_EEPROM_OFFSET_WITHIN_IMAGE;
  else
    maxOffset = OFD_IMAGE2_START_ADDRESS + OFD_EEPROM_OFFSET_WITHIN_IMAGE;

  if (localAccessStructure.offset < maxOffset)
  { // save mcu flash
    ofdSaveCurrentFlashImage();
    return;
  }

  internalAccessParam.eepromOffset = 0;
  // save eeprom image
  ofdSaveCurrentEepromImage();
}

/**************************************************************************//**
\brief Starts saving internal flash.
******************************************************************************/
void ofdSaveCurrentFlashImage(void)
{
  uint16_t itr;

  localAccessStructure.length = OFD_BLOCK_FOR_CHECK_CRC;
  localAccessStructure.data = internalAccessParam.data;
  for (itr = 0; itr < OFD_BLOCK_FOR_CHECK_CRC; itr++)
  {
    OFD_LOAD_NO_COMMAND_TO_NVM;
    internalAccessParam.data[itr] = ofdReadInternalFlash(internalAccessParam.flashOffset++);
  }
  internalAccessParam.length -= OFD_BLOCK_FOR_CHECK_CRC;
  ofdCallback = ofdWriteFlashDataCallback;
  ofdWriteData();
}

/**************************************************************************//**
\brief Callback for saving internal eeprom.

\param[in] status - status of the data eeprom writing
******************************************************************************/
void ofdWriteEepromDataCallback(OFD_Status_t status)
{
  uint32_t maxOffset;

  if (OFD_STATUS_SUCCESS != status)
  {
    if (ofdAuxCallback)
      ofdAuxCallback(status);
    return;
  }
  if (OFD_POSITION_1 == sectorNumber)
    maxOffset = OFD_IMAGE1_START_ADDRESS + OFD_IMAGE_SIZE;
  else
    maxOffset = OFD_IMAGE2_START_ADDRESS + OFD_IMAGE_SIZE;

  if (localAccessStructure.offset < maxOffset)
  { // save mcu eeprom
    ofdSaveCurrentEepromImage();
    return;
  }

  // start check crc
  OFD_FlushAndCheckCrc(sectorNumber, internalAccessParam.data, ofdFlushCrcCallback);
}

/**************************************************************************//**
\brief Starts saving internal eeprom.
******************************************************************************/
static void ofdSaveCurrentEepromImage(void)
{
  HAL_EepromParams_t params;

  params.address = internalAccessParam.eepromOffset;
  params.data = internalAccessParam.data;
  params.length = OFD_BLOCK_FOR_CHECK_CRC;

  if (!ofdEepromHandler(HAL_ReadEeprom(&params, ofdSaveCurrentEepromImageContinue), ofdSaveCurrentEepromImage))
    if (ofdAuxCallback)
      ofdAuxCallback(OFD_STATUS_INCORRECT_EEPROM_PARAMETER);
}

/**************************************************************************//**
\brief Continues saving internal flash.
******************************************************************************/
static void ofdSaveCurrentEepromImageContinue(void)
{
  localAccessStructure.length = OFD_BLOCK_FOR_CHECK_CRC;
  localAccessStructure.data = internalAccessParam.data;
  if (0 == internalAccessParam.eepromOffset)
    memset(internalAccessParam.data, 0xFF, OFD_SERVICE_INFO_SIZE);

  internalAccessParam.eepromOffset += OFD_BLOCK_FOR_CHECK_CRC;
  internalAccessParam.length -= OFD_BLOCK_FOR_CHECK_CRC;
  ofdCallback = ofdWriteEepromDataCallback;
  ofdWriteData();
}

/**************************************************************************//**
\brief Callback for start of saving of action for bootloader.

\param[in]
   status - status of the crc saving to eeprom
\param[in]
   pInfo - ponter to image information
******************************************************************************/
static void ofdFlushCrcCallback(OFD_Status_t status, OFD_ImageInfo_t *pInfo)
{
  (void)pInfo;

  if (OFD_STATUS_SUCCESS != status)
  {
    if (ofdAuxCallback)
      ofdAuxCallback(status);
    return;
  }
  ofdSetActionForBootloader();
}

/**************************************************************************//**
\brief Sets action for internal bootloader.
******************************************************************************/
void ofdSetActionForBootloader(void)
{
  HAL_EepromParams_t params;

  params.address = 0;
  params.data = (uint8_t *)&actionSector;
  params.length = sizeof(OFD_Position_t);

  if (!ofdEepromHandler(HAL_WriteEeprom(&params, ofdPollBusyState), ofdSetActionForBootloader))
    if (ofdAuxCallback)
      ofdAuxCallback(OFD_STATUS_INCORRECT_EEPROM_PARAMETER);
}

/**************************************************************************//**
\brief Waits for end of image saving.
******************************************************************************/
static void ofdPollBusyState(void)
{
  if (FLASH_BUSY == ofdCheckBusyState())
  { // waits till flash ready
    delayedTransaction = ofdPollBusyState;
    ofdStartPollTimer(FLASH_TRANSACTION);
    return;
  }

  if (ofdAuxCallback)
    ofdAuxCallback(OFD_STATUS_SUCCESS);
}

/**************************************************************************//**
\brief Reads image crc from internal eeprom.
******************************************************************************/
void ofdReadCrc(void)
{
  HAL_EepromParams_t params;

  params.address = sectorNumber + 1;
  params.data = &imageInfo.crc;
  params.length = sizeof(uint8_t);

  if (!ofdEepromHandler(HAL_ReadEeprom(&params, ofdSaveCrcCallback), ofdReadCrc))
    if (ofdCallback)
      ((OFD_InfoCallback_t)ofdCallback)(OFD_STATUS_INCORRECT_EEPROM_PARAMETER, &imageInfo);
}

#if defined(_OFD_DEBUG_)
/**************************************************************************//**
\brief Flash read callback.
******************************************************************************/
void ofdReadConfirm(OFD_Status_t status)
{
  HAL_WriteUsart(&usartDescriptor, debugBuffer, OFD_BLOCK_SIZE);
}

/**************************************************************************//**
\brief Usart write callback.
******************************************************************************/
void usartWriteConfirm(void)
{
  debugOffset += OFD_BLOCK_SIZE;
  if (debugOffset < OFD_IMAGE_SIZE)
  {
    ofdReadData(debugOffset, debugBuffer, OFD_BLOCK_SIZE, ofdReadConfirm);
  }
}

/**************************************************************************//**
\brief Initialization of usart for consinsting of flash transmitting.
******************************************************************************/
void ofdInitDebugInterface(void)
{
#if defined(ATMEGA1281) || defined(ATMEGA128RFA1)
  usartDescriptor.tty            = USART_CHANNEL_1;
#elif  defined(ATXMEGA256A3) || defined(ATXMEGA256D3)
  usartDescriptor.tty            = USART_CHANNEL_F0;
#endif
  usartDescriptor.mode           = USART_MODE_ASYNC;
  usartDescriptor.flowControl    = USART_FLOW_CONTROL_NONE;
  usartDescriptor.baudrate       = USART_BAUDRATE_38400;
  usartDescriptor.dataLength     = USART_DATA8;
  usartDescriptor.parity         = USART_PARITY_NONE;
  usartDescriptor.stopbits       = USART_STOPBIT_1;
  usartDescriptor.rxBuffer       = NULL;
  usartDescriptor.rxBufferLength = 0;
  usartDescriptor.txBuffer       = NULL;
  usartDescriptor.txBufferLength = 0;
  usartDescriptor.rxCallback     = NULL;
  usartDescriptor.txCallback     = usartWriteConfirm;

  HAL_OpenUsart(&usartDescriptor);
  ofdReadData(debugOffset, debugBuffer, OFD_BLOCK_SIZE, ofdReadConfirm);
}

/**************************************************************************//**
\brief Reads data from the external memory.

\param[in]
  address - flash cell address
\param[out]
  data - pointer to memory buffer
\param[in]
  size - size of memory buffer
\param[in]
  cb - pointer to callback
******************************************************************************/
void ofdReadData(uint32_t address, uint8_t *data, uint16_t size, OFD_Callback_t cb)
{
  uint32_t pageAddr;
  uint32_t byteAddr;


  while (FLASH_BUSY == ofdCheckBusyState())
  {;}// waits till flash ready
  pageAddr = address / PAGE_SIZE;
  byteAddr = address % PAGE_SIZE;
  address = byteAddr | (pageAddr << 9) | ((uint32_t)READ << 24);
  address = OFD_LITTLE_TO_BIG_ENDIAN(address);
  GPIO_EXT_MEM_CS_clr();
  HAL_WriteSpi(&spiDesc, (uint8_t *)&address, sizeof(uint32_t));
  // load 32 don't care bits
  HAL_WriteSpi(&spiDesc, (uint8_t *)&address, sizeof(uint32_t));
  HAL_ReadSpi(&spiDesc, data, size);
  GPIO_EXT_MEM_CS_set();
  if (cb)
    cb(OFD_STATUS_SUCCESS);
}
#endif // defined(_OFD_DEBUG_)

#endif // APP_USE_FAKE_OFD_DRIVER == 0
#endif // (EXTERNAL_MEMORY == AT45DB041) && (APP_USE_OTAU == 1)
#endif // _OTAU_
// eof ofdAt25fDriver.c