~aleteoryx/muditaos

ref: 7fa175ddaf0ee4fabe0cae8570f19ceaee7540c1 muditaos/module-bsp/board/rt1051/bsp/eink/ED028TC1.cpp -rw-r--r-- 51.8 KiB
7fa175dd — Marek Niepieklo [EGD-7434] Handle settings for USB stack in USB submodule CMakeLists.txt 4 years ago
                                                                                
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
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
// Copyright (c) 2017-2021, Mudita Sp. z.o.o. All rights reserved.
// For licensing, see https://github.com/mudita/MuditaOS/LICENSE.md

#include "dma_config.h"
#include "fsl_dmamux.h"
#include "fsl_edma.h"
#include "ED028TC1.h"
#include "bsp_eink.h"
#include "board.h"

#include <stdbool.h>
#include <assert.h>
#include <math.h>
#include <string.h>

#include "FreeRTOS.h"
#include "task.h"
#include "semphr.h"
//#include "fat_media.h"
//#include "vfs.h"

//#include "log.h"
#include "board.h"
#include "eink_binarization_luts.h"
#include "macros.h"

#include <magic_enum.hpp>
#include "drivers/pll/DriverPLL.hpp"
#include "drivers/dmamux/DriverDMAMux.hpp"
#include "drivers/dma/DriverDMA.hpp"
#include "bsp/BoardDefinitions.hpp"

#define EPD_BOOSTER_START_PERIOD_10MS 0
#define EPD_BOOSTER_START_PERIOD_20MS 1
#define EPD_BOOSTER_START_PERIOD_30MS 2
#define EPD_BOOSTER_START_PERIOD_40MS 3
#define EPD_BOOSTER_START_PERIOD_POS  6

#define EPD_BOOSTER_DRIVING_STRENGTH_1   0
#define EPD_BOOSTER_DRIVING_STRENGTH_2   1
#define EPD_BOOSTER_DRIVING_STRENGTH_3   2
#define EPD_BOOSTER_DRIVING_STRENGTH_4   3
#define EPD_BOOSTER_DRIVING_STRENGTH_5   4
#define EPD_BOOSTER_DRIVING_STRENGTH_6   5
#define EPD_BOOSTER_DRIVING_STRENGTH_7   6
#define EPD_BOOSTER_DRIVING_STRENGTH_8   7
#define EPD_BOOSTER_DRIVING_STRENGTH_POS 3

#define EPD_BOOSTER_OFF_TIME_GDR_0_27uS 0
#define EPD_BOOSTER_OFF_TIME_GDR_0_34uS 1
#define EPD_BOOSTER_OFF_TIME_GDR_0_40uS 2
#define EPD_BOOSTER_OFF_TIME_GDR_0_54uS 3
#define EPD_BOOSTER_OFF_TIME_GDR_0_80uS 4
#define EPD_BOOSTER_OFF_TIME_GDR_1_54uS 5
#define EPD_BOOSTER_OFF_TIME_GDR_3_34uS 6
#define EPD_BOOSTER_OFF_TIME_GDR_6_58uS 7
#define EPD_BOOSTER_OFF_TIME_GDR_POS    0

#if defined(EINK_ROTATE_90_CLOCKWISE)
#define EINK_DISPLAY_RES_X         (BOARD_EINK_DISPLAY_RES_Y)
#define EINK_DISPLAY_RES_Y         (BOARD_EINK_DISPLAY_RES_X)
#define EINK_DISPLAY_X_AXIS        (BOARD_EINK_DISPLAY_RES_Y - Y - H)
#define EINK_DISPLAY_Y_AXIS        (BOARD_EINK_DISPLAY_RES_X - X - W)
#define EINK_DISPLAY_WINDOW_WIDTH  (H)
#define EINK_DISPLAY_WINDOW_HEIGHT (W)
#else
#define EINK_DISPLAY_RES_X         (BOARD_EINK_DISPLAY_RES_X)
#define EINK_DISPLAY_RES_Y         (BOARD_EINK_DISPLAY_RES_Y)
#define EINK_DISPLAY_X_AXIS        (BOARD_EINK_DISPLAY_RES_X - X - W)
#define EINK_DISPLAY_Y_AXIS        (BOARD_EINK_DISPLAY_RES_Y - Y - H)
#define EINK_DISPLAY_WINDOW_WIDTH  (W)
#define EINK_DISPLAY_WINDOW_HEIGHT (H)
#endif

#define EINK_BLACK_PIXEL_MASK      0x00 // This is the mask for the black pixel value
#define EINK_1BPP_WHITE_PIXEL_MASK 0x01 // This is the mask for the white pixel in 1bpp mode
#define EINK_2BPP_WHITE_PIXEL_MASK 0x03 // This is the mask for the white pixel in 2bpp mode
#define EINK_4BPP_WHITE_PIXEL_MASK 0x0F // This is the mask for the white pixel in 4bpp mode

#define ED028TC1_BUSY_STATE_TIMEOUT_MS 2000 // Time after the display should for sure exit the busy state

#define _delay_ms(ms) vTaskDelay(pdMS_TO_TICKS(ms))

/// This is DMA handle for internal frame buffer memory-to-memory copying operation
static edma_handle_t s_einkMemcpyDma_handle __attribute__((used));

using namespace drivers;
using namespace magic_enum;
static std::shared_ptr<drivers::DriverDMA> dma;
static std::shared_ptr<drivers::DriverDMAMux> dmamux;

/* Internal variable definitions */
static uint8_t s_einkIsPoweredOn = false; //  Variable which contains the state of the power of the EPD display

static EinkWaveforms_e s_einkConfiguredWaveform =
    EinkWaveformGC16; //  This variable contains the current waveform set in the display

static CACHEABLE_SECTION_SDRAM(uint8_t s_einkServiceRotatedBuf[BOARD_EINK_DISPLAY_RES_X * BOARD_EINK_DISPLAY_RES_Y / 2 +
                                                               2]); // Plus 2 for the EPD command and BPP config

/**
 * @brief This lut is used for convertion of the 4bp input grayscale pixel to the 1bpp output pixel
 */
static uint8_t s_einkMaskLut_1Bpp[16] = {0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1};

/**
 * @brief This lut is used for convertion of the 4bp input grayscale pixel to the 2bpp output pixel
 */
static uint8_t s_einkMaskLut_2Bpp[16] = {0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3};

/* External variable definitions */

/* Internal function prototypes */

/**
 *  This function makes rotation of the image from the standard GUI coordinate system to the coord system used by the
 * ED028TC1 display.
 *
 *  @note IT ROTATES only the 1Bpp image
 *
 *  @param uint8_t* dataIn          [in]  - input image to be translated. Each byte of that array must represent the
 * single pixel
 *  @param uint16_t x               [in]  - x coordinate of image in pixels
 *  @param uint16_t y               [in]  - y coordinate of image in pixels
 *  @param uint16_t windowWidthPx   [in]  - width of the image in pixels
 *  @param uint16_t windowHeightPx  [in]  - height of the image in pixels
 *  @param uint8_t* dataOut         [out] - the buffer for rotated image
 *  @param invertColors[in] - true if colors of the image are to be inverted, false otherwise
 *
 * @note Assumed dataIn coordinate system is the standard image coordinates system:
 *
 *   (0,0)   X
 *       *-------->
 *       |
 *     Y |
 *       |
 *       v
 *
 *
 * The result of the function is such a conversion of the dataIn array to make the Eink display show it the very same
 * way in its own coordinate system which is:
 *
 *              displayWidth
 *                 _______  ^
 *                |       | |
 *                |       | |
 *  displayHeight |       | |
 *                |       | |
 *                |_______| |  X
 *                   \ /    |
 *    signal tape -  | |    |
 *                          |
 *                 <--------*
 *                    Y     (0,0)
 *
 * @return
 */
static uint8_t *s_EinkTransformFrameCoordinateSystem_1Bpp(uint8_t *dataIn,
                                                          uint16_t windowWidthPx,
                                                          uint16_t windowHeightPx,
                                                          uint8_t *dataOut,
                                                          EinkDisplayColorMode_e invertColors);

/**
 *  This function makes rotation of the image from the standard GUI coordinate system to the coord system used by the
 * ED028TC1 display.
 *
 *  @note IT ROTATES only the 2Bpp image
 *
 *  @param uint8_t* dataIn          [in]  - input image to be translated. Each byte of that array must represent the
 * single pixel
 *  @param uint16_t x               [in]  - x coordinate of image in pixels
 *  @param uint16_t y               [in]  - y coordinate of image in pixels
 *  @param uint16_t windowWidthPx   [in]  - width of the image in pixels
 *  @param uint16_t windowHeightPx  [in]  - height of the image in pixels
 *  @param uint8_t* dataOut         [out] - the buffer for rotated image
 *  @param invertColors[in] - true if colors of the image are to be inverted, false otherwise
 *
 * @note Assumed dataIn coordinate system is the standard image coordinates system:
 *
 *   (0,0)   X
 *       *-------->
 *       |
 *     Y |
 *       |
 *       v
 *
 *
 * The result of the function is such a conversion of the dataIn array to make the Eink display show it the very same
 * way in its own coordinate system which is:
 *
 *              displayWidth
 *                 _______  ^
 *                |       | |
 *                |       | |
 *  displayHeight |       | |
 *                |       | |
 *                |_______| |  X
 *                   \ /    |
 *    signal tape -  | |    |
 *                          |
 *                 <--------*
 *                    Y     (0,0)
 *
 * @return
 */
static uint8_t *s_EinkTransformFrameCoordinateSystem_2Bpp(uint8_t *dataIn,
                                                          uint16_t windowWidthPx,
                                                          uint16_t windowHeightPx,
                                                          uint8_t *dataOut,
                                                          EinkDisplayColorMode_e invertColors);

/**
 *  This function makes rotation of the image from the standard GUI coordinate system to the coord system used by the
 * ED028TC1 display.
 *
 *  @note IT ROTATES only the 3Bpp image
 *
 *  @param uint8_t* dataIn          [in]  - input image to be translated. Each byte of that array must represent the
 * single pixel
 *  @param uint16_t x               [in]  - x coordinate of image in pixels
 *  @param uint16_t y               [in]  - y coordinate of image in pixels
 *  @param uint16_t windowWidthPx   [in]  - width of the image in pixels
 *  @param uint16_t windowHeightPx  [in]  - height of the image in pixels
 *  @param uint8_t* dataOut         [out] - the buffer for rotated image
 *  @param invertColors[in] - true if colors of the image are to be inverted, false otherwise
 *
 * @note Assumed dataIn coordinate system is the standard image coordinates system:
 *
 *   (0,0)   X
 *       *-------->
 *       |
 *     Y |
 *       |
 *       v
 *
 *
 * The result of the function is such a conversion of the dataIn array to make the Eink display show it the very same
 * way in its own coordinate system which is:
 *
 *              displayWidth
 *                 _______  ^
 *                |       | |
 *                |       | |
 *  displayHeight |       | |
 *                |       | |
 *                |_______| |  X
 *                   \ /    |
 *    signal tape -  | |    |
 *                          |
 *                 <--------*
 *                    Y     (0,0)
 *
 * @return
 */
static uint8_t *s_EinkTransformFrameCoordinateSystem_3Bpp(uint8_t *dataIn,
                                                          uint16_t windowWidthPx,
                                                          uint16_t windowHeightPx,
                                                          uint8_t *dataOut,
                                                          EinkDisplayColorMode_e invertColors);

/**
 *  This function makes rotation of the image from the standard GUI coordinate system to the coord system used by the
 * ED028TC1 display.
 *
 *  @note IT ROTATES only the 4Bpp image
 *
 *  @param uint8_t* dataIn          [in]  - input image to be translated. Each byte of that array must represent the
 * single pixel
 *  @param uint16_t x               [in]  - x coordinate of image in pixels
 *  @param uint16_t y               [in]  - y coordinate of image in pixels
 *  @param uint16_t windowWidthPx   [in]  - width of the image in pixels
 *  @param uint16_t windowHeightPx  [in]  - height of the image in pixels
 *  @param uint8_t* dataOut         [out] - the buffer for rotated image
 *  @param invertColors[in] - true if colors of the image are to be inverted, false otherwise
 *
 * @note Assumed dataIn coordinate system is the standard image coordinates system:
 *
 *   (0,0)   X
 *       *-------->
 *       |
 *     Y |
 *       |
 *       v
 *
 *
 * The result of the function is such a conversion of the dataIn array to make the Eink display show it the very same
 * way in its own coordinate system which is:
 *
 *              displayWidth
 *                 _______  ^
 *                |       | |
 *                |       | |
 *  displayHeight |       | |
 *                |       | |
 *                |_______| |  X
 *                   \ /    |
 *    signal tape -  | |    |
 *                          |
 *                 <--------*
 *                    Y     (0,0)
 *
 * @return
 */
static uint8_t *s_EinkTransformFrameCoordinateSystem_4Bpp(uint8_t *dataIn,
                                                          uint16_t windowWidthPx,
                                                          uint16_t windowHeightPx,
                                                          uint8_t *dataOut,
                                                          EinkDisplayColorMode_e invertColors);

/**
 *  This function makes rotation of the image from the standard GUI coordinate system to the coord system used by the
 * ED028TC1 display.
 *
 *  @note IT ROTATES only the 1Bpp image. It also makes sure that the image is black and white only
 *
 *  @param uint8_t* dataIn          [in]  - input image to be translated. Each byte of that array must represent the
 * single pixel
 *  @param uint16_t x               [in]  - x coordinate of image in pixels
 *  @param uint16_t y               [in]  - y coordinate of image in pixels
 *  @param uint16_t windowWidthPx   [in]  - width of the image in pixels
 *  @param uint16_t windowHeightPx  [in]  - height of the image in pixels
 *  @param uint8_t* dataOut         [out] - the buffer for rotated image
 *  @param invertColors[in] - true if colors of the image are to be inverted, false otherwise
 *
 * @note Assumed dataIn coordinate system is the standard image coordinates system:
 *
 *   (0,0)   X
 *       *-------->
 *       |
 *     Y |
 *       |
 *       v
 *
 *
 * The result of the function is such a conversion of the dataIn array to make the Eink display show it the very same
 * way in its own coordinate system which is:
 *
 *              displayWidth
 *                 _______  ^
 *                |       | |
 *                |       | |
 *  displayHeight |       | |
 *                |       | |
 *                |_______| |  X
 *                   \ /    |
 *    signal tape -  | |    |
 *                          |
 *                 <--------*
 *                    Y     (0,0)
 *
 * @return
 */
static uint8_t *s_EinkTransformAnimationFrameCoordinateSystem_1Bpp(uint8_t *dataIn,
                                                                   uint16_t windowWidthPx,
                                                                   uint16_t windowHeightPx,
                                                                   uint8_t *dataOut,
                                                                   EinkDisplayColorMode_e invertColors);

/**
 *  This function makes rotation of the image from the standard GUI coordinate system to the coord system used by the
 * ED028TC1 display.
 *
 *  @note IT ROTATES only the 2Bpp image. It also makes sure that the image is black and white only
 *
 *  @param uint8_t* dataIn          [in]  - input image to be translated. Each byte of that array must represent the
 * single pixel
 *  @param uint16_t x               [in]  - x coordinate of image in pixels
 *  @param uint16_t y               [in]  - y coordinate of image in pixels
 *  @param uint16_t windowWidthPx   [in]  - width of the image in pixels
 *  @param uint16_t windowHeightPx  [in]  - height of the image in pixels
 *  @param uint8_t* dataOut         [out] - the buffer for rotated image
 *  @param invertColors[in] - true if colors of the image are to be inverted, false otherwise
 *
 * @note Assumed dataIn coordinate system is the standard image coordinates system:
 *
 *   (0,0)   X
 *       *-------->
 *       |
 *     Y |
 *       |
 *       v
 *
 *
 * The result of the function is such a conversion of the dataIn array to make the Eink display show it the very same
 * way in its own coordinate system which is:
 *
 *              displayWidth
 *                 _______  ^
 *                |       | |
 *                |       | |
 *  displayHeight |       | |
 *                |       | |
 *                |_______| |  X
 *                   \ /    |
 *    signal tape -  | |    |
 *                          |
 *                 <--------*
 *                    Y     (0,0)
 *
 * @return
 */
static uint8_t *s_EinkTransformAnimationFrameCoordinateSystem_2Bpp(uint8_t *dataIn,
                                                                   uint16_t windowWidthPx,
                                                                   uint16_t windowHeightPx,
                                                                   uint8_t *dataOut,
                                                                   EinkDisplayColorMode_e invertColors);

/**
 *  This function makes rotation of the image from the standard GUI coordinate system to the coord system used by the
 * ED028TC1 display.
 *
 *  @note IT ROTATES only the 3Bpp image. It also makes sure that the image is black and white only
 *
 *  @param uint8_t* dataIn          [in]  - input image to be translated. Each byte of that array must represent the
 * single pixel
 *  @param uint16_t x               [in]  - x coordinate of image in pixels
 *  @param uint16_t y               [in]  - y coordinate of image in pixels
 *  @param uint16_t windowWidthPx   [in]  - width of the image in pixels
 *  @param uint16_t windowHeightPx  [in]  - height of the image in pixels
 *  @param uint8_t* dataOut         [out] - the buffer for rotated image
 *  @param invertColors[in] - true if colors of the image are to be inverted, false otherwise
 *
 * @note Assumed dataIn coordinate system is the standard image coordinates system:
 *
 *   (0,0)   X
 *       *-------->
 *       |
 *     Y |
 *       |
 *       v
 *
 *
 * The result of the function is such a conversion of the dataIn array to make the Eink display show it the very same
 * way in its own coordinate system which is:
 *
 *              displayWidth
 *                 _______  ^
 *                |       | |
 *                |       | |
 *  displayHeight |       | |
 *                |       | |
 *                |_______| |  X
 *                   \ /    |
 *    signal tape -  | |    |
 *                          |
 *                 <--------*
 *                    Y     (0,0)
 *
 * @return
 */
static uint8_t *s_EinkTransformAnimationFrameCoordinateSystem_3Bpp(uint8_t *dataIn,
                                                                   uint16_t windowWidthPx,
                                                                   uint16_t windowHeightPx,
                                                                   uint8_t *dataOut,
                                                                   EinkDisplayColorMode_e invertColors);

/**
 *  This function makes rotation of the image from the standard GUI coordinate system to the coord system used by the
 * ED028TC1 display.
 *
 *  @note IT ROTATES only the 4Bpp image. It also makes sure that the image is black and white only
 *
 *  @param uint8_t* dataIn          [in]  - input image to be translated. Each byte of that array must represent the
 * single pixel
 *  @param uint16_t x               [in]  - x coordinate of image in pixels
 *  @param uint16_t y               [in]  - y coordinate of image in pixels
 *  @param uint16_t windowWidthPx   [in]  - width of the image in pixels
 *  @param uint16_t windowHeightPx  [in]  - height of the image in pixels
 *  @param uint8_t* dataOut         [out] - the buffer for rotated image
 *  @param invertColors[in] - true if colors of the image are to be inverted, false otherwise
 *
 * @note Assumed dataIn coordinate system is the standard image coordinates system:
 *
 *   (0,0)   X
 *       *-------->
 *       |
 *     Y |
 *       |
 *       v
 *
 *
 * The result of the function is such a conversion of the dataIn array to make the Eink display show it the very same
 * way in its own coordinate system which is:
 *
 *              displayWidth
 *                 _______  ^
 *                |       | |
 *                |       | |
 *  displayHeight |       | |
 *                |       | |
 *                |_______| |  X
 *                   \ /    |
 *    signal tape -  | |    |
 *                          |
 *                 <--------*
 *                    Y     (0,0)
 *
 * @return
 */

/*
 * Not rotating version of s_EinkTransformAnimationFrameCoordinateSystem_4Bpp.
 * It is used when EINK_ROTATE_90_CLOCKWISE is not defined.
 */

static uint8_t *s_EinkTransformFrameCoordinateSystemNoRotation_4Bpp(uint8_t *dataIn,
                                                                    uint16_t windowWidthPx,
                                                                    uint16_t windowHeightPx,
                                                                    uint8_t *dataOut,
                                                                    EinkDisplayColorMode_e invertColors);

/* Function bodies */

void EinkChangeDisplayUpdateTimings(EinkDisplayTimingsMode_e timingsMode)
{
    char tmpbuf[4];
    tmpbuf[0] = EinkTCONSetting; // 0x60

    switch (timingsMode) {
    case EinkDisplayTimingsFastRefreshMode: {
        tmpbuf[1] = 0x10;
        tmpbuf[2] = 0x08;
        tmpbuf[3] = 0x08;
    } break;

    case EinkDisplayTimingsHighContrastMode: {
        tmpbuf[1] = 0x3F;
        tmpbuf[2] = 0x09;
        tmpbuf[3] = 0x2D;
    } break;

    case EinkDisplayTimingsDeepCleanMode: {
        tmpbuf[1] = 0x3F;
        tmpbuf[2] = 0x09;
        tmpbuf[3] = 0x50;
    } break;
    }

    if (BSP_EinkWriteData(tmpbuf, 4, SPI_AUTOMATIC_CS) != 0) {
        EinkResetAndInitialize();
        return;
    }
}

uint8_t EinkIsPoweredOn()
{
    return s_einkIsPoweredOn;
}

void EinkPowerOn()
{
    if (!s_einkIsPoweredOn) {
        uint8_t cmd = EinkPowerON; // 0x04
        if (BSP_EinkWriteData(&cmd, sizeof(cmd), SPI_AUTOMATIC_CS) != 0) {
            EinkResetAndInitialize();
            return;
        }

        BSP_EinkWaitUntilDisplayBusy(pdMS_TO_TICKS(BSP_EinkBusyTimeout));
        s_einkIsPoweredOn = true;
    }
}

void EinkPowerOff()
{
    if (s_einkIsPoweredOn) {
        uint8_t cmd = EinkPowerOFF; // 0x02
        if (BSP_EinkWriteData(&cmd, sizeof(cmd), SPI_AUTOMATIC_CS) != 0) {
            EinkResetAndInitialize();
            return;
        }

        BSP_EinkWaitUntilDisplayBusy(pdMS_TO_TICKS(BSP_EinkBusyTimeout));
        s_einkIsPoweredOn = false;
    }
}

void EinkPowerDown(void)
{
    EinkPowerOff();
    BSP_EinkDeinit();
}

int16_t EinkGetTemperatureInternal()
{
    uint8_t cmd[1];
    int8_t temp[2] = {0, 0};

    cmd[0] = EinkTemperatureSensorCalibration;

    BSP_EinkWriteCS(BSP_Eink_CS_Clr);

    if (BSP_EinkWriteData(cmd, sizeof(cmd), SPI_MANUAL_CS) != 0) {
        BSP_EinkWriteCS(BSP_Eink_CS_Set);
        EinkResetAndInitialize();
        return -1;
    }

    BSP_EinkWaitUntilDisplayBusy(pdMS_TO_TICKS(BSP_EinkBusyTimeout));

    if (BSP_EinkReadData(temp, sizeof(temp), SPI_MANUAL_CS) != 0) {
        BSP_EinkWriteCS(BSP_Eink_CS_Set);
        EinkResetAndInitialize();
        return -1;
    }

    BSP_EinkWriteCS(BSP_Eink_CS_Set);

    // First byte of the temp describes the integer part of the temperature in degrees Celsius
    int8_t temperatureInteger = temp[0];
    // The MSB bit of the second byte describes the fraction of the temperature. Bit value of 1 means .5 degree Celsius,
    // bit value of 0 means .0 degree Celsius
    // int8_t temperatureFraction =    ((temp[1] & 0x80) >> 7);

    return temperatureInteger;
}

static void s_EinkSetGateOrder()
{
    uint8_t buf[3];

    // Set the order of gate refreshing
    buf[0] = EinkGDOrderSetting;
    buf[1] = 0x02; // Magic value required by the ED028TC1 display manufacturer
    buf[2] = 0x00;
    if (BSP_EinkWriteData(buf, 3, SPI_AUTOMATIC_CS) != 0) {
        EinkResetAndInitialize();
        return;
    }
}

static void s_EinkSetInitialConfig()
{
    // send initialization data
    unsigned char tmpbuf[10];

    tmpbuf[0] = EinkPowerSetting; // 0x01
    tmpbuf[1] = 0x03;
    tmpbuf[2] = 0x04;
    tmpbuf[3] = 0x00; // 0x06
    tmpbuf[4] = 0x00;
    if (BSP_EinkWriteData(tmpbuf, 5, SPI_AUTOMATIC_CS) != 0) {
        return;
    }

    tmpbuf[0] = EinkPanelSetting;      // 0x00
    tmpbuf[1] = LUT_SEL | SHL | RST_N; // 0x25 -> _XON _RES0 LUT_SEL _DM - SHL _SPIWM RST_N
                                       // If 0x35 (DM - 1 is used (2bpp)) the SPI speed can be 25MHz
    tmpbuf[2] = 0x00;
    if (BSP_EinkWriteData(tmpbuf, 3, SPI_AUTOMATIC_CS) != 0) {
        return;
    }

    tmpbuf[0] = EinkPowerSaving; // 0x26
    tmpbuf[1] = 0x82;            // B2
    if (BSP_EinkWriteData(tmpbuf, 2, SPI_AUTOMATIC_CS) != 0) {
        return;
    }

    tmpbuf[0] = EinkPowerOFFSequenceSetting; // 0x03
    tmpbuf[1] = 0x01;                        // 0x00;//0x03;
    if (BSP_EinkWriteData(tmpbuf, 2, SPI_AUTOMATIC_CS) != 0) {
        return;
    }

    tmpbuf[0] = EinkBoosterSoftStart; // 0x07
    tmpbuf[1] = (EPD_BOOSTER_OFF_TIME_GDR_6_58uS << EPD_BOOSTER_OFF_TIME_GDR_POS) |
                (EPD_BOOSTER_DRIVING_STRENGTH_6 << EPD_BOOSTER_DRIVING_STRENGTH_POS) |
                (EPD_BOOSTER_START_PERIOD_10MS << EPD_BOOSTER_START_PERIOD_POS);

    tmpbuf[2] = (EPD_BOOSTER_OFF_TIME_GDR_6_58uS << EPD_BOOSTER_OFF_TIME_GDR_POS) |
                (EPD_BOOSTER_DRIVING_STRENGTH_6 << EPD_BOOSTER_DRIVING_STRENGTH_POS) |
                (EPD_BOOSTER_START_PERIOD_10MS << EPD_BOOSTER_START_PERIOD_POS);

    tmpbuf[3] = (EPD_BOOSTER_OFF_TIME_GDR_0_40uS << EPD_BOOSTER_OFF_TIME_GDR_POS) |
                (EPD_BOOSTER_DRIVING_STRENGTH_7 << EPD_BOOSTER_DRIVING_STRENGTH_POS) |
                (EPD_BOOSTER_START_PERIOD_10MS << EPD_BOOSTER_START_PERIOD_POS);
    if (BSP_EinkWriteData(tmpbuf, 4, SPI_AUTOMATIC_CS) != 0) {
        return;
    }

    tmpbuf[0] = EinkPLLControl; // 0x30
    tmpbuf[1] = 0x0E;
    if (BSP_EinkWriteData(tmpbuf, 2, SPI_AUTOMATIC_CS) != 0) {
        return;
    }

    tmpbuf[0] = EinkTemperatureSensorSelection;              // Temp. sensor setting TSE
    tmpbuf[1] = EINK_TEMPERATURE_SENSOR_USE_INTERNAL | 0x00; // Temperature offset
    tmpbuf[2] = 0x00;                                        // Host forced temperature value
    if (BSP_EinkWriteData(tmpbuf, 3, SPI_AUTOMATIC_CS) != 0) {
        return;
    }

    tmpbuf[0] = EinkVcomAndDataIntervalSetting; // 0x50
    tmpbuf[1] = DDX;                            // 0x01;   // 0x0D
    tmpbuf[2] = 0x00;                           // 0x22;
    if (BSP_EinkWriteData(tmpbuf, 3, SPI_AUTOMATIC_CS) != 0) {
        return;
    }

    tmpbuf[0] = EinkTCONSetting; // 0x60
    tmpbuf[1] = 0x3F;
    tmpbuf[2] = 0x09;
    tmpbuf[3] = 0x2D;
    if (BSP_EinkWriteData(tmpbuf, 4, SPI_AUTOMATIC_CS) != 0) {
        return;
    }

    tmpbuf[0] = EinkResolutionSetting; // 0x61
    tmpbuf[1] = 0x02;                  // 0x02
    tmpbuf[2] = 0x60;                  // 0x60
    tmpbuf[3] = 0x01;                  // 0x01
    tmpbuf[4] = 0xE0;                  // 0xE0
    if (BSP_EinkWriteData(tmpbuf, 5, SPI_AUTOMATIC_CS) != 0) {
        return;
    }

    tmpbuf[0] = EinkVCM_DCSetting; // 0x82
    tmpbuf[1] = 0x30;
    if (BSP_EinkWriteData(tmpbuf, 2, SPI_AUTOMATIC_CS) != 0) {
        return;
    }
}

EinkStatus_e EinkResetAndInitialize()
{
    // Initialize the synchronization resources, SPI and GPIOs for the Eink BSP
    BSP_EinkInit(NULL);
    // Reset the display
    BSP_EinkResetDisplayController();
    // Set the initial configuration of the eink registers after reset
    s_EinkSetInitialConfig();

    // After the reset the display is powered off
    s_einkIsPoweredOn = false;
    return EinkOK;
}

EinkStatus_e EinkUpdateWaveform(const EinkWaveformSettings_t *settings)
{
    /// LUTD
    if (BSP_EinkWriteData(settings->LUTDData, settings->LUTDSize, SPI_AUTOMATIC_CS) != 0) {
        EinkResetAndInitialize();
        return EinkSPIErr;
    }

    /// LUTC
    if (BSP_EinkWriteData(settings->LUTCData, settings->LUTCSize + 1, SPI_AUTOMATIC_CS) != 0) {
        EinkResetAndInitialize();
        return EinkSPIErr;
    }

    s_einkConfiguredWaveform = settings->mode;

    return EinkOK;
}

static EinkStatus_e s_EinkReadFlagsRegister(uint16_t *flags)
{
    uint8_t cmd = EinkFLG;

    BSP_EinkWriteCS(BSP_Eink_CS_Clr);

    if (BSP_EinkWriteData(&cmd, sizeof(cmd), SPI_MANUAL_CS) != 0) {
        BSP_EinkWriteCS(BSP_Eink_CS_Set);
        EinkResetAndInitialize();
        return EinkSPIErr;
    }

    if (BSP_EinkReadData(flags, sizeof(uint16_t), SPI_MANUAL_CS) != 0) {
        BSP_EinkWriteCS(BSP_Eink_CS_Set);
        EinkResetAndInitialize();
        return EinkSPIErr;
    }

    BSP_EinkWriteCS(BSP_Eink_CS_Set);

    return EinkOK;
}

EinkStatus_e EinkWaitTillPipelineBusy()
{
    uint16_t flags = 0;

    s_EinkReadFlagsRegister(&flags);

    while ((flags & EINK_FLAG_PIPELINE_BUSY)) {
        vTaskDelay(pdMS_TO_TICKS(1));
        s_EinkReadFlagsRegister(&flags);
    }

    return EinkOK;
}

EinkStatus_e EinkDitherDisplay()
{
    uint8_t cmdWithArgs[2] = {EinkDPC, EINK_DITHER_4BPP_MODE | EINK_DITHER_START};

    if (BSP_EinkWriteData(cmdWithArgs, sizeof(cmdWithArgs), SPI_AUTOMATIC_CS) != 0) {
        EinkResetAndInitialize();
        return EinkSPIErr;
    }

    uint16_t flags = 0;

    s_EinkReadFlagsRegister(&flags);

    // Wait for the dither operation finish
    while (flags & EINK_FLAG_DITHER_IN_PROGRESS) {
        vTaskDelay(pdMS_TO_TICKS(1));
        s_EinkReadFlagsRegister(&flags);
    }

    return EinkOK;
}

EinkStatus_e EinkUpdateFrame(
    uint16_t X, uint16_t Y, uint16_t W, uint16_t H, uint8_t *buffer, EinkBpp_e bpp, EinkDisplayColorMode_e invertColors)
{
    uint8_t buf[10];
    uint8_t pixelsInByte = 8 / bpp;

    s_einkServiceRotatedBuf[0] = EinkDataStartTransmission1;
    s_einkServiceRotatedBuf[1] = bpp - 1; //  0 - 1Bpp, 1 - 2Bpp, 2 - 3Bpp, 3 - 4Bpp

    if ((s_einkConfiguredWaveform == EinkWaveformA2) || (s_einkConfiguredWaveform == EinkWaveformDU2)) {
        switch (bpp) {
        case Eink1Bpp: {
            s_EinkTransformAnimationFrameCoordinateSystem_1Bpp(buffer, W, H, s_einkServiceRotatedBuf + 2, invertColors);
        } break;
        case Eink2Bpp: {
            s_EinkTransformAnimationFrameCoordinateSystem_2Bpp(buffer, W, H, s_einkServiceRotatedBuf + 2, invertColors);
        } break;
        case Eink3Bpp: {
            s_EinkTransformAnimationFrameCoordinateSystem_3Bpp(buffer, W, H, s_einkServiceRotatedBuf + 2, invertColors);
        } break;
        case Eink4Bpp: {
#if defined(EINK_ROTATE_90_CLOCKWISE)
            s_EinkTransformFrameCoordinateSystem_4Bpp(buffer, W, H, s_einkServiceRotatedBuf + 2, invertColors);
#else
            s_EinkTransformFrameCoordinateSystemNoRotation_4Bpp(
                buffer, W, H, s_einkServiceRotatedBuf + 2, invertColors);
#endif
        } break;
        }
    }
    else {
        switch (bpp) {
        case Eink1Bpp: {
            s_EinkTransformFrameCoordinateSystem_1Bpp(buffer, W, H, s_einkServiceRotatedBuf + 2, invertColors);
        } break;
        case Eink2Bpp: {
            s_EinkTransformFrameCoordinateSystem_2Bpp(buffer, W, H, s_einkServiceRotatedBuf + 2, invertColors);
        } break;
        case Eink3Bpp: {
            s_EinkTransformFrameCoordinateSystem_3Bpp(buffer, W, H, s_einkServiceRotatedBuf + 2, invertColors);
        } break;
        case Eink4Bpp: {
#if defined(EINK_ROTATE_90_CLOCKWISE)
            s_EinkTransformFrameCoordinateSystem_4Bpp(buffer, W, H, s_einkServiceRotatedBuf + 2, invertColors);
#else
            s_EinkTransformFrameCoordinateSystemNoRotation_4Bpp(
                buffer, W, H, s_einkServiceRotatedBuf + 2, invertColors);
#endif
        } break;
        }
    }

    buf[0] = EinkDataStartTransmissionWindow;           // set display window
    buf[1] = (uint8_t)(EINK_DISPLAY_X_AXIS >> 8);       // MSB of the X axis in the EPD display. Value converted
                                                        // from the standard GUI coords system to the ED028TC1 one
    buf[2] = (uint8_t)EINK_DISPLAY_X_AXIS;              // LSB of the X axis in the EPD display. Value converted from
                                                        // the standard GUI coords system to the ED028TC1 one
    buf[3] = (uint8_t)(EINK_DISPLAY_Y_AXIS >> 8);       // MSB of the Y axis in the EPD display. Value converted
                                                        // from the standard GUI coords system to the ED028TC1 one
    buf[4] = (uint8_t)EINK_DISPLAY_Y_AXIS;              // LSB of the Y axis in the EPD display. Value converted from
                                                        // the standard GUI coords system to the ED028TC1 one
    buf[5] = (uint8_t)(EINK_DISPLAY_WINDOW_WIDTH >> 8); // MSB of the window height in the EPD display. Value converted
                                                        // from the standard GUI coords system to the ED028TC1 one
    buf[6] = (uint8_t)EINK_DISPLAY_WINDOW_WIDTH; // LSB of the window height in the EPD display. Value converted from
                                                 // the standard GUI coords system to the ED028TC1 one
    buf[7] = (uint8_t)(EINK_DISPLAY_WINDOW_HEIGHT >> 8); // MSB of the window width in the EPD display. Value converted
                                                         // from the standard GUI coords system to the ED028TC1 one
    buf[8] = (uint8_t)EINK_DISPLAY_WINDOW_HEIGHT; // LSB of the window width in the EPD display. Value converted from
                                                  // the standard GUI coords system to the ED028TC1 one

    if (BSP_EinkWriteData(buf, 9, SPI_AUTOMATIC_CS) != 0) {
        EinkResetAndInitialize();
        return EinkSPIErr;
    }

    uint32_t msgSize = 2 + ((uint32_t)W * (uint32_t)H /
                            pixelsInByte); // command (1 byte) + bpp (1 byte) + dataSize(W*H/pixelsInByte bytes)
    // Send the part of the image to the display memory

    if (BSP_EinkWriteData(s_einkServiceRotatedBuf, msgSize, SPI_AUTOMATIC_CS) != 0) {
        EinkResetAndInitialize();
        return EinkSPIErr;
    }

    return (EinkOK);
}

EinkStatus_e EinkFillScreenWithColor(EinkDisplayColorFilling_e colorFill)
{
    uint8_t buf[10];

    // Set the window to the entire screen
    buf[0] = EinkDataStartTransmissionWindow; // 0x83
    buf[1] = 0x00;
    buf[2] = 0x00;
    buf[3] = 0x00;
    buf[4] = 0x00;
    buf[5] = (EINK_DISPLAY_RES_X & 0xFF00) >> 8;
    buf[6] = EINK_DISPLAY_RES_X & 0x00FF;
    buf[7] = (EINK_DISPLAY_RES_Y & 0xFF00) >> 8;
    buf[8] = EINK_DISPLAY_RES_Y & 0x00FF;

    if (BSP_EinkWriteData(buf, 9, SPI_AUTOMATIC_CS) != 0) {
        EinkResetAndInitialize();
        return EinkSPIErr;
    }

    BSP_EinkWriteCS(BSP_Eink_CS_Clr);

    buf[0] = EinkDataStartTransmission1; // 0x10
    buf[1] = Eink1Bpp - 1;
    if (BSP_EinkWriteData(buf, 2, SPI_MANUAL_CS) != 0) {
        BSP_EinkWriteCS(BSP_Eink_CS_Set);
        EinkResetAndInitialize();
        return EinkSPIErr;
    }

    uint8_t background = colorFill;

    std::unique_ptr<char[]> bg;
    try {
        bg = std::unique_ptr<char[]>(new char[BOARD_EINK_DISPLAY_RES_Y * BOARD_EINK_DISPLAY_RES_X / 8]);
    }
    catch (const std::bad_alloc &exception) {
        LOG_ERROR("Could not create the buffer for the background plane");
        return EinkNoMem;
    }

    memset(bg.get(), background, BOARD_EINK_DISPLAY_RES_Y * BOARD_EINK_DISPLAY_RES_X / 8);

    if (BSP_EinkWriteData(bg.get(), BOARD_EINK_DISPLAY_RES_Y * BOARD_EINK_DISPLAY_RES_X / 8, SPI_MANUAL_CS) != 0) {
        BSP_EinkWriteCS(BSP_Eink_CS_Set);
        EinkResetAndInitialize();
        return EinkSPIErr;
    }

    BSP_EinkWriteCS(BSP_Eink_CS_Set);

    EinkRefreshImage(0, 0, BOARD_EINK_DISPLAY_RES_X, BOARD_EINK_DISPLAY_RES_Y, EinkDisplayTimingsDeepCleanMode);

    return EinkOK;
}

EinkStatus_e EinkRefreshImage(
    uint16_t X, uint16_t Y, uint16_t W, uint16_t H, EinkDisplayTimingsMode_e refreshTimingsMode)
{
    EinkChangeDisplayUpdateTimings(refreshTimingsMode);

    s_EinkSetGateOrder();

    uint8_t buf[10];

    buf[0] = EinkDisplayRefresh;
    buf[1] = UPD_CPY_TO_PRE;

    buf[2] = (uint8_t)(EINK_DISPLAY_X_AXIS >> 8);       // MSB of the X axis in the EPD display. Value converted
                                                        // from the standard GUI coords system to the ED028TC1 one
    buf[3] = (uint8_t)EINK_DISPLAY_X_AXIS;              // LSB of the X axis in the EPD display. Value converted from
                                                        // the standard GUI coords system to the ED028TC1 one
    buf[4] = (uint8_t)(EINK_DISPLAY_Y_AXIS >> 8);       // MSB of the Y axis in the EPD display. Value converted
                                                        // from the standard GUI coords system to the ED028TC1 one
    buf[5] = (uint8_t)EINK_DISPLAY_Y_AXIS;              // LSB of the Y axis in the EPD display. Value converted from
                                                        // the standard GUI coords system to the ED028TC1 one
    buf[6] = (uint8_t)(EINK_DISPLAY_WINDOW_WIDTH >> 8); // MSB of the window height in the EPD display. Value converted
                                                        // from the standard GUI coords system to the ED028TC1 one
    buf[7] = (uint8_t)EINK_DISPLAY_WINDOW_WIDTH; // LSB of the window height in the EPD display. Value converted from
                                                 // the standard GUI coords system to the ED028TC1 one
    buf[8] = (uint8_t)(EINK_DISPLAY_WINDOW_HEIGHT >> 8); // MSB of the window width in the EPD display. Value converted
                                                         // from the standard GUI coords system to the ED028TC1 one
    buf[9] = (uint8_t)EINK_DISPLAY_WINDOW_HEIGHT; // LSB of the window width in the EPD display. Value converted from
                                                  // the standard GUI coords system to the ED028TC1 one

    if (BSP_EinkWriteData(buf, sizeof(buf), SPI_AUTOMATIC_CS) != 0) {
        EinkResetAndInitialize();
        return EinkSPIErr;
    }

    BSP_EinkWaitUntilDisplayBusy(pdMS_TO_TICKS(BSP_EinkBusyTimeout));

    return EinkOK;
}

__attribute__((optimize("O3"))) void EinkARGBToLuminance(uint8_t *dataIn,
                                                         uint8_t *dataOut,
                                                         uint32_t displayWidth,
                                                         uint32_t displayHeight)
{
    //    uint32_t i, j;
    uint8_t r, g, b;
    float fi;
    uint32_t *src;
    uint8_t *dst;

    src = (uint32_t *)dataIn;
    dst = (uint8_t *)dataOut;

    for (uint32_t i = 0; i < (displayWidth * displayHeight);
         i += 2) // increase by 8 pixels - 32bit word is 8 pixels in 4BPP
    {
        *dst = 0x00000000;
        for (uint8_t j = 0; j < 8; j += 4) {
            r  = (uint8_t)((*(src)) >> 16);
            g  = (uint8_t)((*(src)) >> 8);
            b  = (uint8_t) * (src);
            fi = (r + g + b) / 3;

            *dst |= ((uint32_t)(floor(fi / 16))) << (4 - j);

            src++;
        }
        dst++;
    }
}

__attribute__((optimize("O1"))) static uint8_t *s_EinkTransformFrameCoordinateSystem_1Bpp(
    uint8_t *dataIn,
    uint16_t windowWidthPx,
    uint16_t windowHeightPx,
    uint8_t *dataOut,
    EinkDisplayColorMode_e invertColors)
{
    // In 1bpp mode there are 8 pixels in the byte
    const uint8_t pixelsInByte = 8;

    uint8_t pixels    = 0;
    uint8_t *outArray = dataOut;

    for (int32_t inputCol = windowWidthPx - 1; inputCol >= 0; --inputCol) {
        for (int32_t inputRow = windowHeightPx - 1; inputRow >= 7; inputRow -= pixelsInByte) {
            // HACK: Did not create the loop for accessing pixels and merging them in the single byte for better
            // performance.
            //       Wanted to avoid unneeded loop count increasing and jump operations which for large amount of data
            //       take considerable amount of time.
            uint32_t index = inputRow * BOARD_EINK_DISPLAY_RES_X + inputCol;

            // Use the LUT to convert the input pixel from 4bpp to 1bpp
            uint8_t firstPixel   = s_einkMaskLut_1Bpp[dataIn[index - 0 * BOARD_EINK_DISPLAY_RES_X]];
            uint8_t secondPixel  = s_einkMaskLut_1Bpp[dataIn[index - 1 * BOARD_EINK_DISPLAY_RES_X]];
            uint8_t thirdPixel   = s_einkMaskLut_1Bpp[dataIn[index - 2 * BOARD_EINK_DISPLAY_RES_X]];
            uint8_t fourthPixel  = s_einkMaskLut_1Bpp[dataIn[index - 3 * BOARD_EINK_DISPLAY_RES_X]];
            uint8_t fifthPixel   = s_einkMaskLut_1Bpp[dataIn[index - 4 * BOARD_EINK_DISPLAY_RES_X]];
            uint8_t sixthPixel   = s_einkMaskLut_1Bpp[dataIn[index - 5 * BOARD_EINK_DISPLAY_RES_X]];
            uint8_t seventhPixel = s_einkMaskLut_1Bpp[dataIn[index - 6 * BOARD_EINK_DISPLAY_RES_X]];
            uint8_t eightPixel   = s_einkMaskLut_1Bpp[dataIn[index - 7 * BOARD_EINK_DISPLAY_RES_X]];

            // Put the pixels in order: Most left positioned pixel at the most significant side of byte
            pixels = (firstPixel << 7) | (secondPixel << 6) | (thirdPixel << 5) | (fourthPixel << 4) |
                     (fifthPixel << 3) | (sixthPixel << 2) | (seventhPixel << 1) | (eightPixel << 0);

            if (invertColors) {
                pixels = ~pixels;
            }

            *outArray = pixels;
            ++outArray;
        }
    }

    return dataOut;
}

__attribute__((optimize("O1"))) static uint8_t *s_EinkTransformFrameCoordinateSystem_2Bpp(
    uint8_t *dataIn,
    uint16_t windowWidthPx,
    uint16_t windowHeightPx,
    uint8_t *dataOut,
    EinkDisplayColorMode_e invertColors)
{
    // In 2bpp mode there are 4 pixels in the byte
    const uint8_t pixelsInByte = 8;
    uint16_t pixels            = 0;
    uint16_t *outArray         = (uint16_t *)dataOut;
    uint8_t temp               = 0;

    for (int32_t inputCol = windowWidthPx - 1; inputCol >= 0; --inputCol) {
        for (int32_t inputRow = windowHeightPx - 1; inputRow >= 7; inputRow -= pixelsInByte) {
            // HACK: Did not create the loop for accessing pixels and merging them in the single byte for better
            // performance.
            //       Wanted to avoid unneeded loop count increasing and jump operations which for large amount of data
            //       take considerable amount of time.
            uint32_t index = inputRow * BOARD_EINK_DISPLAY_RES_X + inputCol;

            // Use the LUT to convert the input pixel from 4bpp to 2bpp and put 4 pixels in single byte
            temp = (s_einkMaskLut_2Bpp[dataIn[index - 0 * BOARD_EINK_DISPLAY_RES_X]] << 6);
            temp |= (s_einkMaskLut_2Bpp[dataIn[index - 1 * BOARD_EINK_DISPLAY_RES_X]] << 4);
            temp |= (s_einkMaskLut_2Bpp[dataIn[index - 2 * BOARD_EINK_DISPLAY_RES_X]] << 2);
            temp |= (s_einkMaskLut_2Bpp[dataIn[index - 3 * BOARD_EINK_DISPLAY_RES_X]] << 0);

            // Push the 4 pixels into the proper place in the uint16_t
            pixels = temp << 0;

            // Use the LUT to convert the input pixel from 4bpp to 2bpp and put 4 pixels in single byte
            temp = (s_einkMaskLut_2Bpp[dataIn[index - 4 * BOARD_EINK_DISPLAY_RES_X]] << 6);
            temp |= (s_einkMaskLut_2Bpp[dataIn[index - 5 * BOARD_EINK_DISPLAY_RES_X]] << 4);
            temp |= (s_einkMaskLut_2Bpp[dataIn[index - 6 * BOARD_EINK_DISPLAY_RES_X]] << 2);
            temp |= (s_einkMaskLut_2Bpp[dataIn[index - 7 * BOARD_EINK_DISPLAY_RES_X]] << 0);

            // Push the 4 pixels into the proper place in the uint16_t
            pixels |= temp << 8;

            if (invertColors) {
                pixels = ~pixels;
            }

            *outArray = pixels;
            ++outArray;
        }
    }

    return dataOut;
}

__attribute__((optimize("O1"))) static uint8_t *s_EinkTransformFrameCoordinateSystem_3Bpp(
    uint8_t *dataIn,
    uint16_t windowWidthPx,
    uint16_t windowHeightPx,
    uint8_t *dataOut,
    EinkDisplayColorMode_e invertColors)
{
    // The 4bpp is coded the same way as the 3bpp
    return s_EinkTransformFrameCoordinateSystem_4Bpp(dataIn, windowWidthPx, windowHeightPx, dataOut, invertColors);
}

__attribute__((optimize("O1"))) static uint8_t *s_EinkTransformAnimationFrameCoordinateSystem_1Bpp(
    uint8_t *dataIn,
    uint16_t windowWidthPx,
    uint16_t windowHeightPx,
    uint8_t *dataOut,
    EinkDisplayColorMode_e invertColors)
{
    // In 1bpp mode there are 8 pixels in the byte
    const uint8_t pixelsInByte = 8;
    uint8_t pixels             = 0;
    uint8_t *outArray          = dataOut;

    for (int32_t inputCol = windowWidthPx - 1; inputCol >= 0; --inputCol) {
        for (int32_t inputRow = windowHeightPx - 1; inputRow >= 7; inputRow -= pixelsInByte) {
            // HACK: Did not create the loop for accessing pixels and merging them in the single byte for better
            // performance.
            //       Wanted to avoid unneeded loop count increasing and jump operations which for large amount of data
            //       take considerable amount of time.

            uint32_t index = inputRow * BOARD_EINK_DISPLAY_RES_X + inputCol;

            // Use the LUT to convert the input pixel from 4bpp to 1bpp
            uint8_t firstPixel   = s_einkMaskLut_1Bpp[dataIn[index - 0 * BOARD_EINK_DISPLAY_RES_X]];
            uint8_t secondPixel  = s_einkMaskLut_1Bpp[dataIn[index - 1 * BOARD_EINK_DISPLAY_RES_X]];
            uint8_t thirdPixel   = s_einkMaskLut_1Bpp[dataIn[index - 2 * BOARD_EINK_DISPLAY_RES_X]];
            uint8_t fourthPixel  = s_einkMaskLut_1Bpp[dataIn[index - 3 * BOARD_EINK_DISPLAY_RES_X]];
            uint8_t fifthPixel   = s_einkMaskLut_1Bpp[dataIn[index - 4 * BOARD_EINK_DISPLAY_RES_X]];
            uint8_t sixthPixel   = s_einkMaskLut_1Bpp[dataIn[index - 5 * BOARD_EINK_DISPLAY_RES_X]];
            uint8_t seventhPixel = s_einkMaskLut_1Bpp[dataIn[index - 6 * BOARD_EINK_DISPLAY_RES_X]];
            uint8_t eightPixel   = s_einkMaskLut_1Bpp[dataIn[index - 7 * BOARD_EINK_DISPLAY_RES_X]];

            // Put the pixels in order: Most left positioned pixel at the most significant side of byte
            pixels = (firstPixel << 7) | (secondPixel << 6) | (thirdPixel << 5) | (fourthPixel << 4) |
                     (fifthPixel << 3) | (sixthPixel << 2) | (seventhPixel << 1) | (eightPixel << 0);

            if (invertColors) {
                pixels = ~pixels;
            }

            *outArray = pixels;
            ++outArray;
        }
    }

    return dataOut;
}

__attribute__((optimize("O1"))) static uint8_t *s_EinkTransformAnimationFrameCoordinateSystem_2Bpp(
    uint8_t *dataIn,
    uint16_t windowWidthPx,
    uint16_t windowHeightPx,
    uint8_t *dataOut,
    EinkDisplayColorMode_e invertColors)
{
    // In 2bpp mode there are 4 pixels in the byte
    const uint8_t pixelsInByte = 8;
    uint16_t pixels            = 0;
    uint16_t *outArray         = (uint16_t *)dataOut;
    uint8_t temp               = 0;
    for (int32_t inputCol = windowWidthPx - 1; inputCol >= 0; --inputCol) {
        for (int32_t inputRow = windowHeightPx - 1; inputRow >= 7; inputRow -= pixelsInByte) {
            // HACK: Did not create the loop for accessing pixels and merging them in the single byte for better
            // performance.
            //       Wanted to avoid unneeded loop count increasing and jump operations which for large amount of data
            //       take considerable amount of time.
            uint32_t index = inputRow * BOARD_EINK_DISPLAY_RES_X + inputCol;

            // Use the LUT to convert the input pixel from 4bpp to 2bpp and put 4 pixels in single byte
            temp = (s_einkMaskLut_2Bpp[dataIn[index - 0 * BOARD_EINK_DISPLAY_RES_X]] << 6);
            temp |= (s_einkMaskLut_2Bpp[dataIn[index - 1 * BOARD_EINK_DISPLAY_RES_X]] << 4);
            temp |= (s_einkMaskLut_2Bpp[dataIn[index - 2 * BOARD_EINK_DISPLAY_RES_X]] << 2);
            temp |= (s_einkMaskLut_2Bpp[dataIn[index - 3 * BOARD_EINK_DISPLAY_RES_X]] << 0);

            // Use the LUT to binarize the 2bpp pixels value and push them into the proper place in the uint16_t
            pixels = einkBinarizationLUT_2bpp[temp] << 0;

            // Use the LUT to convert the input pixel from 4bpp to 2bpp and put 4 pixels in single byte
            temp = (s_einkMaskLut_2Bpp[dataIn[index - 4 * BOARD_EINK_DISPLAY_RES_X]] << 6);
            temp |= (s_einkMaskLut_2Bpp[dataIn[index - 5 * BOARD_EINK_DISPLAY_RES_X]] << 4);
            temp |= (s_einkMaskLut_2Bpp[dataIn[index - 6 * BOARD_EINK_DISPLAY_RES_X]] << 2);
            temp |= (s_einkMaskLut_2Bpp[dataIn[index - 7 * BOARD_EINK_DISPLAY_RES_X]] << 0);

            // Use the LUT to binarize the 2bpp pixels value and push them into the proper place in the uint16_t
            pixels |= einkBinarizationLUT_2bpp[temp] << 8;
            if (invertColors) {
                pixels = ~pixels;
            }

            *outArray = pixels;
            ++outArray;
        }
    }

    return dataOut;
}

__attribute__((optimize("O3"))) static uint8_t *s_EinkTransformAnimationFrameCoordinateSystem_3Bpp(
    uint8_t *dataIn,
    uint16_t windowWidthPx,
    uint16_t windowHeightPx,
    uint8_t *dataOut,
    EinkDisplayColorMode_e invertColors)
{
    // The 4bpp is coded the same way as the 3bpp
    return s_EinkTransformFrameCoordinateSystem_4Bpp(dataIn, windowWidthPx, windowHeightPx, dataOut, invertColors);
}

__attribute__((optimize("O1"))) static uint8_t *s_EinkTransformFrameCoordinateSystem_4Bpp(
    uint8_t *dataIn,
    uint16_t windowWidthPx,
    uint16_t windowHeightPx,
    uint8_t *dataOut,
    EinkDisplayColorMode_e invertColors)
{
    // In 3bpp and 4bpp modes there are 2 pixels in the byte. Using 8bpp to process the whole uint32_t at once for
    // faster execution
    const uint8_t pixelsInByte = 8;

    uint32_t pixels    = 0;
    uint32_t *outArray = (uint32_t *)dataOut;

    for (int32_t inputCol = windowWidthPx - 1; inputCol >= 0; --inputCol) {
        for (int32_t inputRow = windowHeightPx - 1; inputRow >= 7; inputRow -= pixelsInByte) {
            // HACK: Did not create the loop for accessing pixels and merging them in the single byte for better
            // performance.
            //       Wanted to avoid unneeded loop count increasing and jump operations which for large amount of data
            //       take considerable amount of time. Using 8 pixels at a time for better performance
            uint32_t index = inputRow * BOARD_EINK_DISPLAY_RES_X + inputCol;

            uint8_t firstPixelPair =
                (dataIn[index - 0 * BOARD_EINK_DISPLAY_RES_X] << 4) | dataIn[index - 1 * BOARD_EINK_DISPLAY_RES_X];
            uint8_t secondPixelPair =
                (dataIn[index - 2 * BOARD_EINK_DISPLAY_RES_X] << 4) | dataIn[index - 3 * BOARD_EINK_DISPLAY_RES_X];
            uint8_t thirdPixelPair =
                (dataIn[index - 4 * BOARD_EINK_DISPLAY_RES_X] << 4) | dataIn[index - 5 * BOARD_EINK_DISPLAY_RES_X];
            uint8_t fourthPixelPair =
                (dataIn[index - 6 * BOARD_EINK_DISPLAY_RES_X] << 4) | dataIn[index - 7 * BOARD_EINK_DISPLAY_RES_X];

            // Put the pixels in the uint32_t for faster processing
            pixels = firstPixelPair | (secondPixelPair << 8) | (thirdPixelPair << 16) | (fourthPixelPair << 24);

            if (invertColors) {
                pixels = ~pixels;
            }

            // Put the pixels in order: Most left positioned pixel at the most significant side of byte
            *outArray = pixels;
            ++outArray;
        }
    }

    return dataOut;
}

__attribute__((optimize("O1"))) static uint8_t *s_EinkTransformFrameCoordinateSystemNoRotation_4Bpp(
    uint8_t *dataIn,
    uint16_t windowWidthPx,
    uint16_t windowHeightPx,
    uint8_t *dataOut,
    EinkDisplayColorMode_e invertColors)
{
    // In 3bpp and 4bpp modes there are 2 pixels in the byte. Using 8bpp to process the whole uint32_t at once for
    // faster execution
    const uint8_t pixelsInByte = 8;

    uint32_t pixels    = 0;
    uint32_t *outArray = (uint32_t *)dataOut;
    int32_t inputRow   = 0;
    int32_t inputCol   = 0;

    for (inputRow = windowHeightPx - 1; inputRow >= 0; --inputRow) {
        for (inputCol = 0; inputCol < windowWidthPx - 7; inputCol += pixelsInByte) {
            // HACK: Did not create the loop for accessing pixels and merging them in the single byte for better
            // performance.
            //       Wanted to avoid unneeded loop count increasing and jump operations which for large amount of data
            //       take considerable amount of time. Using 8 pixels at a time for better performance
            uint32_t index = inputRow * BOARD_EINK_DISPLAY_RES_X + inputCol;

            // Get 4x 2 adjacent pixels to process them as uint32_t for better execution timings
            uint8_t firstPixelPair  = (dataIn[index] << 4) | dataIn[index + 1];
            uint8_t secondPixelPair = (dataIn[index + 2] << 4) | dataIn[index + 3];
            uint8_t thirdPixelPair  = (dataIn[index + 4] << 4) | dataIn[index + 5];
            uint8_t fourthPixelPair = (dataIn[index + 6] << 4) | dataIn[index + 7];

            // Put the pixels in the uint32_t for faster processing
            pixels = (firstPixelPair) | (secondPixelPair << 8) | (thirdPixelPair << 16) | (fourthPixelPair << 24);

            if (invertColors) {
                pixels = ~pixels;
            }

            // Put the pixels in order: Most left positioned pixel at the most significant side of byte
            *outArray = pixels;
            ++outArray;
        }
    }

    return dataOut;
}