summaryrefslogtreecommitdiffhomepage
path: root/digital/zigbit/bitcloud/stack/Components/HAL/avr/common/src/usart.c
blob: 53a63927340a2aba7665f58586a92e3f88fd3693 (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
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
/**************************************************************************//**
\file  usart.c

\brief USART implementation. Asynchronous mode.

\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:
    29/05/07 E. Ivanov - Created
    18/02/09 A. Luzhetsky - Corretced.
*******************************************************************************/
/******************************************************************************
 *   WARNING: CHANGING THIS FILE MAY AFFECT CORE FUNCTIONALITY OF THE STACK.  *
 *   EXPERT USERS SHOULD PROCEED WITH CAUTION.                                *
 ******************************************************************************/
/******************************************************************************
                   Includes section
******************************************************************************/
#include <halDbg.h>
#include <usart.h>
#include <appTimer.h>
#include <halDiagnostic.h>

/******************************************************************************
                   Define(s) section
******************************************************************************/
#define HANDLERS_GET(A, I) memcpy_P(A, &halUsartHandlers[I], sizeof(HalUsartTask_t))
/** \brief Amount of reserved bytes in received buffer. Some clients (PC Windows for example)
  send few more bytes after CTS setting, so we need to reserve some space for them.
  Reserved space = Buffer Size / 2^BUFFER_RESERV. */
#define BUFFER_RESERV    1
#define USART_HW_CONTROLLER_TIMER_PERIOD 10
#if defined(_USE_USART_ERROR_EVENT_)
  #define HAL_BM_FRAME_ERROR     (1 << 4)
  #define HAL_BM_DATA_OVERRUN    (1 << 3)
  #define HAL_BM_PARITY_ERROR    (1 << 2)
#endif
#if NUM_USART_CHANNELS == 0
  #error 'USART channels is not alowed.'
#endif

/******************************************************************************
                   Types definition section
******************************************************************************/
/**************************************************************************//**
  \brief HAL USART tasks bit mask.
******************************************************************************/
typedef volatile uint8_t HalUsartTaskBitMask_t;

/**************************************************************************//**
  \brief HAL USART task type declaration.
******************************************************************************/
typedef void (* HalUsartTask_t)(void);

/******************************************************************************
                   Global functions prototypes section
******************************************************************************/
void halSigUsartHandler(void);
void halSetUsartConfig(HAL_UsartDescriptor_t *usartmode);
void halPostUsartTask(HalUsartTaskId_t taskId);
#ifdef HW_CONTROL_PINS_PORT_ASSIGNMENT
  void hwControlPinsPollCallback(void);
#endif // HW_CONTROL_PINS_PORT_ASSIGNMENT

/******************************************************************************
                   Static function prototypes section
******************************************************************************/
#if defined(HAL_USE_USART_CHANNEL_0)
  static void halUsartTaskUsart0Dre(void);
  static void halUsartTaskUsart0Txc(void);
  static void halUsartTaskUsart0Rxc(void);
  #if defined(_USE_USART_ERROR_EVENT_)
    static void halUsartTaskUsart0Err(void);
  #endif
#endif

#if defined(HAL_USE_USART_CHANNEL_1)
  static void halUsartTaskUsart1Dre(void);
  static void halUsartTaskUsart1Txc(void);
  static void halUsartTaskUsart1Rxc(void);
  #if defined(_USE_USART_ERROR_EVENT_)
    static void halUsartTaskUsart1Err(void);
  #endif
#endif

static void halUsartHwController(UsartChannel_t tty);
static void halSigUsartReceptionComplete(UsartChannel_t tty);
static void halSetUsartClockPinDirection(HAL_UsartDescriptor_t *descriptor);

/******************************************************************************
                   Static variables section
******************************************************************************/
#ifdef HW_CONTROL_PINS_PORT_ASSIGNMENT
  static HAL_AppTimer_t halUsartAppTimer;
#endif // HW_CONTROL_PINS_PORT_ASSIGNMENT
HAL_UsartDescriptor_t *halPointDescrip[NUM_USART_CHANNELS] =
{
  #if defined(HAL_USE_USART_CHANNEL_0)
    NULL,
  #endif
  #if defined(HAL_USE_USART_CHANNEL_1)
    NULL
  #endif
};
static volatile HalUsartTaskBitMask_t halUsartTaskBitMask = 0; // HAL USART tasks' bit mask.
static const HalUsartTask_t PROGMEM_DECLARE(halUsartHandlers[HAL_USART_TASKS_NUMBER]) =
{
  #if defined(HAL_USE_USART_CHANNEL_0)
    halUsartTaskUsart0Dre,
    halUsartTaskUsart0Txc,
    halUsartTaskUsart0Rxc,
    #if defined(_USE_USART_ERROR_EVENT_)
      halUsartTaskUsart0Err,
    #endif
  #endif

  #if defined(HAL_USE_USART_CHANNEL_1)
    halUsartTaskUsart1Dre,
    halUsartTaskUsart1Txc,
    halUsartTaskUsart1Rxc,
    #if defined(_USE_USART_ERROR_EVENT_)
      halUsartTaskUsart1Err,
    #endif
  #endif
}; // List Of possible HAL USART tasks.

/******************************************************************************
  DTR service
******************************************************************************/
volatile bool halEnableDtrWakeUp = false;
void (* dtrWakeUpCallback)(void) = NULL;

/******************************************************************************
                   Implementations section
******************************************************************************/
/**************************************************************************//**
\brief  HAL USART task. Exact action depends on USART internal task.
******************************************************************************/
void halSigUsartHandler(void)
{
  HalUsartTask_t         handler;
  HalUsartTaskBitMask_t  mask = 1;
  HalUsartTaskId_t       index = 0;

  for ( ; index < HAL_USART_TASKS_NUMBER; index++, mask <<= 1)
  {
    if (halUsartTaskBitMask & mask)
    {
      ATOMIC_SECTION_ENTER
      halUsartTaskBitMask ^= mask;
      ATOMIC_SECTION_LEAVE
      HANDLERS_GET(&handler, index);
      handler();
    }
  }
}

/**************************************************************************//**
\brief Posts specific USART task.

\param[in]
  taskId - unique identifier of the task to be posted.
******************************************************************************/
void halPostUsartTask(HalUsartTaskId_t taskId)
{
  halUsartTaskBitMask |= (HalUsartTaskBitMask_t)1 << taskId;
  halPostTask2(HAL_TASK_USART);
}

/**************************************************************************//**
\brief Puts the byte received to the cyclic buffer.

\param[in]
  tty - channel number.
\param[in]
  data - data to put.
******************************************************************************/
void halUsartRxBufferFiller(UsartChannel_t tty, uint8_t data)
{
  uint16_t           old;
  uint8_t            i;
  HalUsartService_t *halUsartControl;

  i = HAL_GET_INDEX_BY_CHANNEL(tty);
  if (NULL == halPointDescrip[i])
  {// abnormal
    halDisableUsartRxcInterrupt(tty); // disable usart
    return;
  }

  if (halPointDescrip[i]->flowControl & USART_SPI_WRITE_MODE)
    return;

  if (halPointDescrip[i]->flowControl & USART_SPI_READ_MODE)
  { // For spi mode.
    *(uint8_t*)(halPointDescrip[i]->rxBuffer) = data;
    halPointDescrip[i]->rxBuffer++;
    return;
  } // For spi mode.

  halUsartControl = &halPointDescrip[i]->service;
  if (NULL != halPointDescrip[i]->rxBuffer)
  {
    old = halUsartControl->rxPointOfWrite;

    if (++halUsartControl->rxPointOfWrite == halPointDescrip[i]->rxBufferLength)
      halUsartControl->rxPointOfWrite = 0;

    if (halUsartControl->rxPointOfWrite == halUsartControl->rxPointOfRead)
    { // Buffer full.
      halUsartControl->rxPointOfWrite = old;
      return;
    } // Buffer full.

    halPointDescrip[i]->rxBuffer[old] = data;
    halUsartControl->rxBytesInBuffer++;

#ifdef HW_CONTROL_PINS_PORT_ASSIGNMENT
    if ((halPointDescrip[i]->flowControl & USART_FLOW_CONTROL_HARDWARE) && (HW_CONTROL_PINS_PORT_ASSIGNMENT == halPointDescrip[i]->tty))
    {
      if (halUsartControl->rxBytesInBuffer > (halPointDescrip[i]->rxBufferLength >> BUFFER_RESERV))
        GPIO_USART_CTS_set();// CTS_ON
    }
#endif // HW_CONTROL_PINS_PORT_ASSIGNMENT
  }
}

#if defined(_USE_USART_ERROR_EVENT_)
/**************************************************************************//**
\brief Save status register for analyzing of the error reason.

\param[in]
  tty - channel number.
\param[in]
  status - usart status register.
******************************************************************************/
void halUsartSaveErrorReason(UsartChannel_t tty, uint8_t status)
{
  HalUsartService_t *halUsartControl;
  uint8_t            i;

  i = HAL_GET_INDEX_BY_CHANNEL(tty);
  if (NULL == halPointDescrip[i])
  {// abnormal
    halDisableUsartRxcInterrupt(tty); // disable usart
    return;
  }

  halUsartControl = &halPointDescrip[i]->service;
  halUsartControl->errorReason = status;
}
#endif

/**************************************************************************//**
\brief Registers uasrt's event handlers. Performs configuration
of usart registers. Performs configuration of RTS, CTS and DTR pins.

\param[in]
  descriptor - pointer to HAL_UsartDescriptor_t structure

\return
  Returns positive usart descriptor on success or -1 in cases: \n
    - bad usart channel. \n
    - unsupported parameters. \n
    - the channel was already opened. \n
    - there are not enough resources. \n
******************************************************************************/
int HAL_OpenUsart(HAL_UsartDescriptor_t *descriptor)
{
  uint8_t i; // Descriptor index

  if (NULL == descriptor)
    return -1;
  if (false == halIsUsartChannelCorrect(descriptor->tty))
    return -1;

#ifdef HW_CONTROL_PINS_PORT_ASSIGNMENT
  if ((descriptor->flowControl & USART_FLOW_CONTROL_HARDWARE) &&
      (HW_CONTROL_PINS_PORT_ASSIGNMENT != descriptor->tty))
    return -1; // Hardware control cannot be used for this channel.
#endif // HW_CONTROL_PINS_PORT_ASSIGNMENT

  i = HAL_GET_INDEX_BY_CHANNEL(descriptor->tty);
  if (NULL != halPointDescrip[i])
    return -1; // Channel is already opened.

  halPointDescrip[i] = descriptor;
#ifdef HW_CONTROL_PINS_PORT_ASSIGNMENT
  if (HW_CONTROL_PINS_PORT_ASSIGNMENT == descriptor->tty)
  {
    if (descriptor->flowControl & USART_DTR_CONTROL)
      GPIO_USART_DTR_make_in();
    if (descriptor->flowControl & USART_FLOW_CONTROL_HARDWARE)
    {
      GPIO_USART_CTS_make_out();
      GPIO_USART_RTS_make_in();
      if (NULL == descriptor->rxBuffer)
        GPIO_USART_CTS_set(); // CTS_ON
      else
        GPIO_USART_CTS_clr(); // CTS_OFF
    }
  }
#endif // HW_CONTROL_PINS_PORT_ASSIGNMENT

  if (USART_MODE_SYNC == descriptor->mode)
    halSetUsartClockPinDirection(descriptor);

  descriptor->service.txPointOfRead = 0;
  descriptor->service.txPointOfWrite = 0;
  if (NULL == descriptor->rxBuffer)
    descriptor->rxBufferLength = 0;
  if (NULL == descriptor->txBuffer)
    descriptor->txBufferLength = 0;
  descriptor->service.rxPointOfRead = 0;
  descriptor->service.rxPointOfWrite = 0;
  descriptor->service.usartShiftRegisterEmpty = 1;

  halSetUsartConfig(descriptor);

  return descriptor->tty;
}

/**************************************************************************//**
\brief Frees the usart channel and pins, if hardware flow control was used.

\param[in]
  descriptor - the usart descriptor.
\return
   0 on success, \n
  -1 if bad descriptor or channel is already closed.
******************************************************************************/
int HAL_CloseUsart(HAL_UsartDescriptor_t *descriptor)
{
  uint8_t i;

  if (NULL == descriptor)
    return -1;
  if (false == halIsUsartChannelCorrect(descriptor->tty))
    return -1;
  i = HAL_GET_INDEX_BY_CHANNEL(descriptor->tty);
  if (NULL == halPointDescrip[i])
    return -1; // Channel is already closed.

  halCloseUsart(halPointDescrip[i]->tty);
#ifdef HW_CONTROL_PINS_PORT_ASSIGNMENT
  if (halPointDescrip[i]->flowControl & USART_FLOW_CONTROL_HARDWARE)
    GPIO_USART_CTS_make_in();
#endif // HW_CONTROL_PINS_PORT_ASSIGNMENT

  if (USART_MODE_SYNC == halPointDescrip[i]->mode)
  {
    halPointDescrip[i]->syncMode = USART_CLK_MODE_SLAVE;
    halSetUsartClockPinDirection(halPointDescrip[i]);
  }
  halPointDescrip[i] = NULL;

  return 0;
}

/**************************************************************************//**
\brief Controls RTS and DTR the pins and makes decision if the usart can transmit
 byte.

\param[in]
  tty - channel number.
******************************************************************************/
static void halUsartHwController(UsartChannel_t tty)
{
  uint8_t            i;
  HalUsartService_t *halUsartControl;

  i = HAL_GET_INDEX_BY_CHANNEL(tty);
  if (NULL == halPointDescrip[i])
    return; // Port closed.

  halUsartControl = &halPointDescrip[i]->service;
#ifdef HW_CONTROL_PINS_PORT_ASSIGNMENT
  if (HW_CONTROL_PINS_PORT_ASSIGNMENT == tty)
  {
    uint8_t hw1 = 0;
    uint8_t hw2 = 0;

    if (halPointDescrip[i]->flowControl & USART_DTR_CONTROL)
      hw1 = GPIO_USART_DTR_read();

    if (halPointDescrip[i]->flowControl & USART_FLOW_CONTROL_HARDWARE)
      hw2 = GPIO_USART_RTS_read();

    if (hw1 || hw2)
    {
      halUsartAppTimer.interval = USART_HW_CONTROLLER_TIMER_PERIOD;
      halUsartAppTimer.mode = TIMER_ONE_SHOT_MODE;
      halUsartAppTimer.callback = hwControlPinsPollCallback;
      HAL_StartAppTimer(&halUsartAppTimer);
      return;
    }
  }
#endif // HW_CONTROL_PINS_PORT_ASSIGNMENT

  uint16_t poW;
  uint16_t poR;

  ATOMIC_SECTION_ENTER
  BEGIN_MEASURE
    poW = halUsartControl->txPointOfWrite;
    poR = halUsartControl->txPointOfRead;
  END_MEASURE(HAL_USART_HW_CONTROLLER_LIMIT)
  ATOMIC_SECTION_LEAVE

  if (poW != poR)
  {
    halSendUsartByte(tty, halPointDescrip[i]->txBuffer[poR++]);
    if (poR == halPointDescrip[i]->txBufferLength)
      poR = 0;
    halEnableUsartDremInterrupt(tty);

    ATOMIC_SECTION_ENTER
    BEGIN_MEASURE
      halUsartControl->txPointOfRead = poR;
    END_MEASURE(HAL_USART_HW_CONTROLLER_LIMIT)
    ATOMIC_SECTION_LEAVE

  }
  else
  {
    // data register empty interrupt was disabled
    halEnableUsartTxcInterrupt(tty);// TX Complete interrupt enable
  }
}

/**************************************************************************//**
\brief Writes a number of bytes to a usart channel.
txCallback function will be used to notify when the transmission is finished.
If hardware flow control is used for transmitting then RTS and DTR pins will
be tested during transmission.

\param[in]
  descriptor - pointer to HAL_UsartDescriptor_t structure;

\param[in]
  buffer - pointer to the application data buffer;

\param[in]
  length - number of bytes to transfer;

\return
  -1 - bad descriptor; \n
   Number of bytes placed to the buffer - success.
******************************************************************************/
int HAL_WriteUsart(HAL_UsartDescriptor_t *descriptor, uint8_t *buffer, uint16_t length)
{
  uint8_t            i;
  uint16_t           poW;
  uint16_t           poR;
  uint16_t           old;
  uint16_t           wasWrote = 0;
  bool               needStartTrmt = false;
  HalUsartService_t *halUsartControl;

  if (NULL == descriptor)
    return -1;
  if (false == halIsUsartChannelCorrect(descriptor->tty))
    return -1;
  if (!buffer || !length)
    return -1;
  i = HAL_GET_INDEX_BY_CHANNEL(descriptor->tty);
  if (descriptor != halPointDescrip[i])
    return -1; // Channel is not opened.

  halUsartControl = &descriptor->service;
  if (0 == descriptor->txBufferLength)
  { // Callback mode
    if (halUsartControl->txPointOfWrite != halUsartControl->txPointOfRead)
      return -1; // there is unsent data
    descriptor->txBuffer = buffer;
    halUsartControl->txPointOfWrite = length;
    halUsartControl->txPointOfRead = 0;
    needStartTrmt = true;
    wasWrote = length;
  } // Callback mode.
  else
  { // Polling mode.
    ATOMIC_SECTION_ENTER
    BEGIN_MEASURE
      poW = halUsartControl->txPointOfWrite;
      poR = halUsartControl->txPointOfRead;
    END_MEASURE(HALATOM_WRITE_USART_TIME_LIMIT)
    ATOMIC_SECTION_LEAVE

    if (poW == poR)
      needStartTrmt = true; // Buffer empty.

    while (wasWrote < length)
    {
      old = poW;

      if (++poW == descriptor->txBufferLength)
        poW = 0;

      if (poW == poR)
      { // Buffer full.
        poW = old;
        break;
      } // Buffer full.

      descriptor->txBuffer[old] = buffer[wasWrote++];
    }

    ATOMIC_SECTION_ENTER
    BEGIN_MEASURE
      halUsartControl->txPointOfWrite = poW;
    END_MEASURE(HALATOM_WRITE_USART_TIME_LIMIT)
    ATOMIC_SECTION_LEAVE
  } // Polling mode

  if (needStartTrmt)
  {
    halUsartControl->usartShiftRegisterEmpty = 0; // Buffer and shift register is full
    // Enable interrupt. Transaction will be launched in the callback.
    halEnableUsartDremInterrupt(descriptor->tty);
  }

  return wasWrote;
}

/*************************************************************************//**
\brief Reads length bytes from usart and places ones to buffer.

\param[in]
  descriptor - usart descriptor;
\param[out]
  buffer - pointer to a application buffer;
\param[in]
  length - the number of bytes which should be placed to buffer

\return
  -1 - bad descriptor, bad number to read or number of bytes that \n
  were placed to buffer.
*****************************************************************************/
int HAL_ReadUsart(HAL_UsartDescriptor_t *descriptor, uint8_t *buffer, uint16_t length)
{
  uint8_t            i = 0;
  uint16_t           wasRead = 0;
  uint16_t           poW;
  uint16_t           poR;
  HalUsartService_t *halUsartControl;
#ifdef HW_CONTROL_PINS_PORT_ASSIGNMENT
  uint16_t           number;
#endif // HW_CONTROL_PINS_PORT_ASSIGNMENT

  if (NULL == descriptor)
    return -1;
  if (false == halIsUsartChannelCorrect(descriptor->tty))
    return -1;
  if (!buffer || !length)
    return -1;
  i = HAL_GET_INDEX_BY_CHANNEL(descriptor->tty);
  if (descriptor != halPointDescrip[i])
    return -1; // Channel is not opened.

  halUsartControl = &halPointDescrip[i]->service;
  ATOMIC_SECTION_ENTER
  BEGIN_MEASURE
    poW = halUsartControl->rxPointOfWrite;
    poR = halUsartControl->rxPointOfRead;
  END_MEASURE(HALATOM_READ_USART_TIME_LIMIT)
  ATOMIC_SECTION_LEAVE

  while ((poR != poW) && (wasRead < length))
  {
    buffer[wasRead] = descriptor->rxBuffer[poR];
    if (++poR == descriptor->rxBufferLength)
      poR = 0;
    wasRead++;
  }

  ATOMIC_SECTION_ENTER
  BEGIN_MEASURE
    halUsartControl->rxPointOfRead = poR;
    halUsartControl->rxBytesInBuffer -= wasRead;
#ifdef HW_CONTROL_PINS_PORT_ASSIGNMENT
    number = halUsartControl->rxBytesInBuffer;
#endif // HW_CONTROL_PINS_PORT_ASSIGNMENT
  END_MEASURE(HALATOM_READ_USART_TIME_LIMIT)
  ATOMIC_SECTION_LEAVE

#ifdef HW_CONTROL_PINS_PORT_ASSIGNMENT
  if ((HW_CONTROL_PINS_PORT_ASSIGNMENT == descriptor->tty) && (descriptor->flowControl & USART_FLOW_CONTROL_HARDWARE))
    if (number <= (descriptor->rxBufferLength >> BUFFER_RESERV))
      GPIO_USART_CTS_clr();
#endif // HW_CONTROL_PINS_PORT_ASSIGNMENT

  return wasRead;
}

/**************************************************************************//**
\brief Forbids to the host data transmiting. Only HW_CONTROL_PINS_PORT_ASSIGNMENT
         port can be used for hardware flow control.

\param[in]
  descriptor - usart descriptor.

\return
  -1 - bad descriptor, bad usart, unsupported mode;
   0 - on success.
******************************************************************************/
#ifdef HW_CONTROL_PINS_PORT_ASSIGNMENT
int HAL_OnUsartCts(HAL_UsartDescriptor_t *descriptor)
{
  uint8_t i;

  if (NULL == descriptor)
    return -1;

  if (false == halIsUsartChannelCorrect(descriptor->tty))
    return -1;

  i = HAL_GET_INDEX_BY_CHANNEL(descriptor->tty);
  if (descriptor != halPointDescrip[i])
    return -1; // Channel is not opened.

  if (HW_CONTROL_PINS_PORT_ASSIGNMENT != descriptor->tty)
    return -1;

  GPIO_USART_CTS_set();// CTS_ON

  return 0;
}
#endif // HW_CONTROL_PINS_PORT_ASSIGNMENT

/**************************************************************************//**
\brief Allows to transfer a host data. Only HW_CONTROL_PINS_PORT_ASSIGNMENT
can be used for hardware flow control.

\param[in]
  descriptor - usart descriptor.

\return
  -1 - bad descriptor, bad usart, unsupported mode;
   0 - on success.
******************************************************************************/
#ifdef HW_CONTROL_PINS_PORT_ASSIGNMENT
int HAL_OffUsartCts(HAL_UsartDescriptor_t *descriptor)
{
  uint8_t i;

  if (NULL == descriptor)
    return -1;

  if (false == halIsUsartChannelCorrect(descriptor->tty))
    return -1;

  i = HAL_GET_INDEX_BY_CHANNEL(descriptor->tty);
  if (descriptor != halPointDescrip[i])
    return -1; // Channel is not opened.

  if (HW_CONTROL_PINS_PORT_ASSIGNMENT != descriptor->tty)
    return -1;

  GPIO_USART_CTS_clr(); // CTS_OFF

  return 0;
}
#endif // HW_CONTROL_PINS_PORT_ASSIGNMENT

/**************************************************************************//**
\brief Fills UsartHardwareControl_t variable by potential of RTS pin. Only
  HW_CONTROL_PINS_PORT_ASSIGNMENT can be used for hardware flow control.

\param[in]
  descriptor - usart descriptor.
\return
  -1 - bad descriptor, bad usart, unsupported mode;
   0 - on success.
******************************************************************************/
#ifdef HW_CONTROL_PINS_PORT_ASSIGNMENT
int HAL_ReadUsartRts(HAL_UsartDescriptor_t *descriptor)
{
  uint8_t i;

  if (NULL == descriptor)
    return -1;

  if (false == halIsUsartChannelCorrect(descriptor->tty))
    return -1;

  i = HAL_GET_INDEX_BY_CHANNEL(descriptor->tty);
  if (descriptor != halPointDescrip[i])
    return -1; // Channel is not opened.

  if (HW_CONTROL_PINS_PORT_ASSIGNMENT != descriptor->tty)
    return -1;

  return GPIO_USART_RTS_read();
}
#endif // HW_CONTROL_PINS_PORT_ASSIGNMENT

/**************************************************************************//**
\brief Fills UsartHardwareControl_t variable by potential of DTR pin. Only
  HW_CONTROL_PINS_PORT_ASSIGNMENT can be used for hardware flow control.

\param[in]
  descriptor - usart descriptor.
\return
  -1 - bad descriptor, bad usart, unsupported mode;
   0 - on success.
******************************************************************************/
#ifdef HW_CONTROL_PINS_PORT_ASSIGNMENT
int HAL_ReadUsartDtr(HAL_UsartDescriptor_t *descriptor)
{
  uint8_t i;

  if (NULL == descriptor)
    return -1;

  if (false == halIsUsartChannelCorrect(descriptor->tty))
    return -1;

  i = HAL_GET_INDEX_BY_CHANNEL(descriptor->tty);
  if (descriptor != halPointDescrip[i])
    return -1; // Channel is not opened.

  if (HW_CONTROL_PINS_PORT_ASSIGNMENT != descriptor->tty)
    return -1;

  return GPIO_USART_DTR_read();
}
#endif // HW_CONTROL_PINS_PORT_ASSIGNMENT

// Interrupt handlers
/**************************************************************************//**
\brief Hardware Control pins polling timer callback.
******************************************************************************/
#ifdef HW_CONTROL_PINS_PORT_ASSIGNMENT
void hwControlPinsPollCallback(void)
{
  halUsartHwController(HW_CONTROL_PINS_PORT_ASSIGNMENT);
}
#endif // HW_CONTROL_PINS_PORT_ASSIGNMENT

/**************************************************************************//**
\brief Transmission complete interrupt handler.

\param[in]
  tty - USART channel identifier.
******************************************************************************/
void halSigUsartTransmissionComplete(UsartChannel_t tty)
{
  uint8_t            i;
  HalUsartService_t *halUsartControl;
  uint16_t           poW;
  uint16_t           poR;

  i = HAL_GET_INDEX_BY_CHANNEL(tty);
  if (NULL == halPointDescrip[i])
  {
    assert(false, USARTC_HALSIGUSARTTRANSMISSIONCOMPLETE_0);
    return; // Descriptor with "tty" channel is not found.
  }

  halUsartControl = &halPointDescrip[i]->service;

  ATOMIC_SECTION_ENTER
  BEGIN_MEASURE
    poW = halUsartControl->txPointOfWrite;
    poR = halUsartControl->txPointOfRead;
  END_MEASURE(HAL_USART_TRANS_COMPLETE_LIMIT)
  ATOMIC_SECTION_LEAVE

  if (poW == poR)
    halUsartControl->usartShiftRegisterEmpty = 1; // Buffer is empty, shift register is empty too.

  if (0 == halPointDescrip[i]->txBufferLength)
    halPointDescrip[i]->txBuffer = NULL; // nulling pointer for callback mode

  if (NULL != halPointDescrip[i]->txCallback)
    halPointDescrip[i]->txCallback();
}

/**************************************************************************//**
\brief Reception complete interrupt handler.

\param[in]
  tty - USART channel identifier.
******************************************************************************/
static void halSigUsartReceptionComplete(UsartChannel_t tty)
{
  uint8_t            i;
  HalUsartService_t *halUsartControl;
  uint16_t           number;

  i = HAL_GET_INDEX_BY_CHANNEL(tty);
  if (NULL == halPointDescrip[i])
  {
    assert(false, USARTC_HALSIGUSARTRECEPTIONCOMPLETE_0);
    return; // Descriptor with "tty" channel is not found.
  }

  if (halPointDescrip[i]->flowControl & (USART_SPI_READ_MODE | USART_SPI_WRITE_MODE))
    return; // for spi mode

  halUsartControl = &halPointDescrip[i]->service;
  ATOMIC_SECTION_ENTER
  BEGIN_MEASURE
    number = halUsartControl->rxBytesInBuffer;
  END_MEASURE(HALATOM_USART_RX_COMPLETE_TIME_LIMIT)
  ATOMIC_SECTION_LEAVE

  if (number)
    if (NULL != halPointDescrip[i]->rxCallback)
      halPointDescrip[i]->rxCallback(number);
}

#if defined(_USE_USART_ERROR_EVENT_)
/**************************************************************************//**
\brief Error occurred action handler.

\param[in]
  tty - USART channel identifier.
******************************************************************************/
static void halSigUsartErrorOccurred(UsartChannel_t tty)
{
  uint8_t            i;
  HalUsartService_t *halUsartControl;
  UsartErrorReason_t errReason = FRAME_ERROR;

  i = HAL_GET_INDEX_BY_CHANNEL(tty);
  if (NULL == halPointDescrip[i])
  {
    assert(false, USARTC_HALSIGUSARTERROROCCURED_0);
    return; // Descriptor with "tty" channel is not found.
  }

  halUsartControl = &halPointDescrip[i]->service;
  if (halUsartControl->errorReason & HAL_BM_FRAME_ERROR)
    errReason = FRAME_ERROR;
  else if (halUsartControl->errorReason & HAL_BM_DATA_OVERRUN)
    errReason = DATA_OVERRUN;
  else if (halUsartControl->errorReason & HAL_BM_PARITY_ERROR)
    errReason = PARITY_ERROR;
  else
  {
    assert(false, USARTC_HALUNKNOWNERRORREASON_0);
  }

  if (NULL != halPointDescrip[i]->errCallback)
    halPointDescrip[i]->errCallback(errReason);
}
#endif

/**************************************************************************//**
\brief Enables DTR wake up.

\param[in] callback - callback method pointer.
******************************************************************************/
void HAL_EnableDtrWakeUp(void (* callback)(void))
{
  dtrWakeUpCallback = callback;
  halEnableDtrWakeUp = true;
}

/**************************************************************************//**
\brief Disables DTR wake up.
******************************************************************************/
void HAL_DisableDtrWakeUp(void)
{
  halEnableDtrWakeUp = false;
}

/**************************************************************************//**
\brief Checks the status of tx buffer.

\param[in]
  descriptor - pointer to HAL_UsartDescriptor_t structure;

\return
  -1 - bad descriptor, no tx buffer; \n
   1 - tx buffer is empty; \n
   0 - tx buffer is not empty;
******************************************************************************/
int HAL_IsTxEmpty(HAL_UsartDescriptor_t *descriptor)
{
  uint8_t            i;
  HalUsartService_t *halUsartControl;
  uint16_t           poW;
  uint16_t           poR;

  if (NULL == descriptor)
     return -1;
  if (false == halIsUsartChannelCorrect(descriptor->tty))
     return -1;
  i = HAL_GET_INDEX_BY_CHANNEL(descriptor->tty);
  if (descriptor != halPointDescrip[i])
     return -1; // Channel is not opened.

  halUsartControl = &halPointDescrip[i]->service;
  ATOMIC_SECTION_ENTER
  BEGIN_MEASURE
    poW = halUsartControl->txPointOfWrite;
    poR = halUsartControl->txPointOfRead;
  END_MEASURE(HAL_USART_TX_EMPTY_LIMIT)
  ATOMIC_SECTION_LEAVE
  if (poW == poR)
    return halUsartControl->usartShiftRegisterEmpty;
  return 0;
}

/**************************************************************************//**
\brief Checks the channel number.

\param[in]
  channel - channel to be verified.

\return
  true if channel is possible, \n
  false otherwise.
******************************************************************************/
bool halIsUsartChannelCorrect(UsartChannel_t channel)
{
  switch (channel)
  {
#ifdef USART_CHANNEL_0
    case USART_CHANNEL_0:
#endif // USART_CHANNEL_0
#ifdef USART_CHANNEL_1
    case USART_CHANNEL_1:
#endif // USART_CHANNEL_0
#if defined(USART_CHANNEL_0) || defined(USART_CHANNEL_1)
      return true;
#endif
    default:
      return false;
  }
}

/**************************************************************************//**
\brief Set clock pin direction for synchronous mode.

\param[in]
  descriptor - pointer to usart channel descriptor.
******************************************************************************/
static void halSetUsartClockPinDirection(HAL_UsartDescriptor_t *descriptor)
{
  if (USART_CLK_MODE_MASTER == descriptor->syncMode)
  {
    switch (descriptor->tty)
    {
#ifdef USART_CHANNEL_0
      case USART_CHANNEL_0:
        GPIO_USART0_EXTCLK_make_out();
        break;
#endif // USART_CHANNEL_0
#ifdef USART_CHANNEL_1
      case USART_CHANNEL_1:
        GPIO_USART1_EXTCLK_make_out();
        break;
#endif // USART_CHANNEL_1
      default:
        break;
    }
  }
  else
  {
    switch (descriptor->tty)
    {
#ifdef USART_CHANNEL_0
      case USART_CHANNEL_0:
        GPIO_USART0_EXTCLK_make_in();
        GPIO_USART0_EXTCLK_make_pullup();
        break;
#endif // USART_CHANNEL_0
#ifdef USART_CHANNEL_1
      case USART_CHANNEL_1:
        GPIO_USART1_EXTCLK_make_in();
        GPIO_USART1_EXTCLK_make_pullup();
        break;
#endif // USART_CHANNEL_1
      default:
      break;
    }
  }
}

#if defined(HAL_USE_USART_CHANNEL_0)
/**************************************************************************//**
\brief Wrapper for data empty handler for usart channel 0
******************************************************************************/
static void halUsartTaskUsart0Dre(void)
{
  halUsartHwController(USART_CHANNEL_0);
}

/**************************************************************************//**
\brief Wrapper for transmit complete handler for usart channel 0
******************************************************************************/
static void halUsartTaskUsart0Txc(void)
{
  halSigUsartTransmissionComplete(USART_CHANNEL_0);
}

/**************************************************************************//**
\brief Wrapper for receive complete handler for usart channel 0
******************************************************************************/
static void halUsartTaskUsart0Rxc(void)
{
  halSigUsartReceptionComplete(USART_CHANNEL_0);
}

#if defined(_USE_USART_ERROR_EVENT_)
/**************************************************************************//**
\brief Wrapper for error occurred handler for usart channel 0
******************************************************************************/
static void halUsartTaskUsart0Err(void)
{
  halSigUsartErrorOccurred(USART_CHANNEL_0);
}
#endif // defined(_USE_USART_ERROR_EVENT_)
#endif // defined(HAL_USE_USART_CHANNEL_0)

#if defined(HAL_USE_USART_CHANNEL_1)
/**************************************************************************//**
\brief Wrapper for data empty handler for usart channel 1
******************************************************************************/
static void halUsartTaskUsart1Dre(void)
{
  halUsartHwController(USART_CHANNEL_1);
}

/**************************************************************************//**
\brief Wrapper for transmit complete handler for usart channel 1
******************************************************************************/
static void halUsartTaskUsart1Txc(void)
{
  halSigUsartTransmissionComplete(USART_CHANNEL_1);
}

/**************************************************************************//**
\brief Wrapper for receive complete handler for usart channel 0
******************************************************************************/
static void halUsartTaskUsart1Rxc(void)
{
  halSigUsartReceptionComplete(USART_CHANNEL_1);
}

#if defined(_USE_USART_ERROR_EVENT_)
/**************************************************************************//**
\brief Wrapper for error occurred handler for usart channel 1
******************************************************************************/
static void halUsartTaskUsart1Err(void)
{
  halSigUsartErrorOccurred(USART_CHANNEL_1);
}
#endif // defined(_USE_USART_ERROR_EVENT_)
#endif // defined(HAL_USE_USART_CHANNEL_1)
//eof usart.c