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
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
// Licensed under the Apache License, Version 2.0 or the MIT License.
// SPDX-License-Identifier: Apache-2.0 OR MIT
// Copyright Tock Contributors 2022
// Copyright OxidOS Automotive SRL 2022
//
// Author: Teona Severin <teona.severin@oxidos.io>

//! Low-level CAN driver for STM32F4XX chips
//!

use crate::clocks::{phclk, Stm32f4Clocks};
use core::cell::Cell;
use kernel::deferred_call::{DeferredCall, DeferredCallClient};
use kernel::hil::can::{self, StandardBitTiming};
use kernel::platform::chip::ClockInterface;
use kernel::utilities::cells::{OptionalCell, TakeCell};
use kernel::utilities::registers::interfaces::{ReadWriteable, Readable};
use kernel::utilities::registers::{register_bitfields, register_structs, ReadWrite};
use kernel::utilities::StaticRef;

pub const BRP_MIN_STM32: u32 = 0;
pub const BRP_MAX_STM32: u32 = 1023;

pub const TX_MAILBOX_COUNT: usize = 3;
pub const RX_MAILBOX_COUNT: usize = 2;
pub const FILTER_COUNT: usize = 56;

register_structs! {
    pub Registers {
        /// CAN control and status registers
        (0x000 => can_mcr: ReadWrite<u32, CAN_MCR::Register>),
        /// CAN master status register
        (0x004 => can_msr: ReadWrite<u32, CAN_MSR::Register>),
        /// CAN transmit status register
        (0x008 => can_tsr: ReadWrite<u32, CAN_TSR::Register>),
        /// CAN receive FIFO 0 register
        (0x00c => can_rf0r: ReadWrite<u32, CAN_RF0R::Register>),
        /// CAN receive FIFO 1 registers
        (0x010 => can_rf1r: ReadWrite<u32, CAN_RF1R::Register>),
        /// CAN interrupt enable register
        (0x014 => can_ier: ReadWrite<u32, CAN_IER::Register>),
        /// CAN error status register
        (0x018 => can_esr: ReadWrite<u32, CAN_ESR::Register>),
        /// CAN bit timing register
        (0x01c => can_btr: ReadWrite<u32, CAN_BTR::Register>),
        (0x020 => _reserved0),
        ///
        ///
        /// CAN MAILBOX REGISTERS
        ///
        /// CAN TX mailbox identifier registers
        (0x180 => can_tx_mailbox: [TransmitMailBox; TX_MAILBOX_COUNT]),
        /// CAN RX mailbox identifier registers
        (0x1b0 => can_rx_mailbox: [ReceiveMailBox; RX_MAILBOX_COUNT]),
        (0x1d0 => _reserved1),
        ///
        ///
        /// CAN FILTER REGISTERS
        ///
        ///
        /// CAN filter master register
        (0x200 => can_fmr: ReadWrite<u32, CAN_FMR::Register>),
        /// CAN filter mode register
        (0x204 => can_fm1r: ReadWrite<u32, CAN_FM1R::Register>),
        (0x208 => _reserved2),
        /// CAN filter scale register
        (0x20c => can_fs1r: ReadWrite<u32, CAN_FS1R::Register>),
        (0x210 => _reserved3),
        /// CAN filter FIFO assignment register
        (0x214 => can_ffa1r: ReadWrite<u32, CAN_FFA1R::Register>),
        (0x218 => _reserved4),
        /// CAN filter activation register
        (0x21c => can_fa1r: ReadWrite<u32, CAN_FA1R::Register>),
        (0x220 => _reserved5),
        /// Filter bank 0-27 for register 1-2
        (0x240 => can_firx: [ReadWrite<u32, CAN_FiRx::Register>; FILTER_COUNT]),
        (0x320 => @END),
    },

    TransmitMailBox {
        (0x00 => can_tir: ReadWrite<u32, CAN_TIxR::Register>),
        (0x04 => can_tdtr: ReadWrite<u32, CAN_TDTxR::Register>),
        (0x08 => can_tdlr: ReadWrite<u32, CAN_TDLxR::Register>),
        (0x0c => can_tdhr: ReadWrite<u32, CAN_TDHxR::Register>),
        (0x010 => @END),
    },

    ReceiveMailBox {
        (0x00 => can_rir: ReadWrite<u32, CAN_RIxR::Register>),
        (0x04 => can_rdtr: ReadWrite<u32, CAN_RDTxR::Register>),
        (0x08 => can_rdlr: ReadWrite<u32, CAN_RDLxR::Register>),
        (0x0c => can_rdhr: ReadWrite<u32, CAN_RDHxR::Register>),
        (0x010 => @END),
    }
}

register_bitfields![u32,
    CAN_MCR [
        /// Debug freeze
        DBF OFFSET(16) NUMBITS(1) [],
        /// bcXAN software master reset
        RESET OFFSET(15) NUMBITS(1) [],
        /// Time triggered communication mode
        TTCM OFFSET(7) NUMBITS(1) [],
        /// Automatic bus-off management
        ABOM OFFSET(6) NUMBITS(1) [],
        /// Automatic wakeup mode
        AWUM OFFSET(5) NUMBITS(1) [],
        /// No automatic retransmission
        NART OFFSET(4) NUMBITS(1) [],
        /// Receive FIFO locked mode
        RFLM OFFSET(3) NUMBITS(1) [],
        /// Transmit FIFO prioritY
        TXFP OFFSET(2) NUMBITS(1) [],
        /// Sleep mode request
        SLEEP OFFSET(1) NUMBITS(1) [],
        /// Initialization request
        INRQ OFFSET(0) NUMBITS(1) []
    ],
    CAN_MSR [
        /// CAN Rx signal
        RX OFFSET(11) NUMBITS(1) [],
        /// Last sample point
        SAMP OFFSET(10) NUMBITS(1) [],
        /// Receive mode
        RXM OFFSET(9) NUMBITS(1) [],
        /// Transmit mode
        TXM OFFSET(8) NUMBITS(1) [],
        /// Sleep acknowledge interrupt
        SLAKI OFFSET(4) NUMBITS(1) [],
        /// Wakeup interrupt
        WKUI OFFSET(3) NUMBITS(1) [],
        /// Error interrupt
        ERRI OFFSET(2) NUMBITS(1) [],
        /// Sleep acknowledge
        SLAK OFFSET(1) NUMBITS(1) [],
        /// Initialization acknowledge
        INAK OFFSET(0) NUMBITS(1) []
    ],
    CAN_TSR [
        /// Lowest priority flag for mailbox 2
        LOW2 OFFSET(31) NUMBITS(1) [],
        /// Lowest priority flag for mailbox 1
        LOW1 OFFSET(30) NUMBITS(1) [],
        /// Lowest priority flag for mailbox 0
        LOW0 OFFSET(29) NUMBITS(1) [],
        /// Transmit mailbox 2 empty
        TME2 OFFSET(28) NUMBITS(1) [],
        /// Transmit mailbox 1 empty
        TME1 OFFSET(27) NUMBITS(1) [],
        /// Transmit mailbox 0 empty
        TME0 OFFSET(26) NUMBITS(1) [],
        /// Mailbox code
        CODE OFFSET(24) NUMBITS(2) [],
        /// Abort request for mailbox 2
        ABRQ2 OFFSET(23) NUMBITS(1) [],
        /// Transmission error of mailbox 2
        TERR2 OFFSET(19) NUMBITS(1) [],
        /// Arbitration lost for mailbox 2
        ALST2 OFFSET(18) NUMBITS(1) [],
        /// Transmission OK of mailbox 2
        TXOK2 OFFSET(17) NUMBITS(1) [],
        /// Request completed mailbox 2
        RQCP2 OFFSET(16) NUMBITS(1) [],
        /// Abort request for mailbox 1
        ABRQ1 OFFSET(15) NUMBITS(1) [],
        /// Transmission error of mailbox 1
        TERR1 OFFSET(11) NUMBITS(1) [],
        /// Arbitration lost for mailbox 1
        ALST1 OFFSET(10) NUMBITS(1) [],
        /// Transmission OK of mailbox 1
        TXOK1 OFFSET(9) NUMBITS(1) [],
        /// Request completed mailbox 1
        RQCP1 OFFSET(8) NUMBITS(1) [],
        /// Abort request for mailbox 0
        ABRQ0 OFFSET(7) NUMBITS(1) [],
        /// Transmission error of mailbox 0
        TERR0 OFFSET(3) NUMBITS(1) [],
        /// Arbitration lost for mailbox 0
        ALST0 OFFSET(2) NUMBITS(1) [],
        /// Transmission OK of mailbox 0
        TXOK0 OFFSET(1) NUMBITS(1) [],
        /// Request completed mailbox 0
        RQCP0 OFFSET(0) NUMBITS(1) []
    ],
    CAN_RF0R [
        /// Release FIFO 0 output mailbox
        RFOM0 OFFSET(5) NUMBITS(1) [],
        /// FIFO 0 overrun
        FOVR0 OFFSET(4) NUMBITS(1) [],
        /// FIFO 0 full
        FULL0 OFFSET(3) NUMBITS(1) [],
        /// FIFO 0 message pending
        FMP0 OFFSET(0) NUMBITS(2) []
    ],
    CAN_RF1R [
        /// Release FIFO 1 output mailbox
        RFOM1 OFFSET(5) NUMBITS(1) [],
        /// FIFO 1 overrun
        FOVR1 OFFSET(4) NUMBITS(1) [],
        /// FIFO 1 full
        FULL1 OFFSET(3) NUMBITS(1) [],
        /// FIFO 1 message pending
        FMP1 OFFSET(0) NUMBITS(2) []
    ],
    CAN_IER [
        /// Sleep interrupt enable
        SLKIE OFFSET(17) NUMBITS(1) [],
        /// Wakeup interrupt enable
        WKUIE OFFSET(16) NUMBITS(1) [],
        /// Error interrupt enable
        ERRIE OFFSET(15) NUMBITS(1) [],
        /// Last error code interrupt enable
        LECIE OFFSET(11) NUMBITS(1) [],
        /// Bus-off interrupt enable
        BOFIE OFFSET(10) NUMBITS(1) [],
        /// Error passive interrupt enable
        EPVIE OFFSET(9) NUMBITS(1) [],
        /// Error warning interrupt enable
        EWGIE OFFSET(8) NUMBITS(1) [],
        /// FIFO 1 overrun interrupt enable
        FOVIE1 OFFSET(6) NUMBITS(1) [],
        /// FIFO 1 full interrupt enable
        FFIE1 OFFSET(5) NUMBITS(1) [],
        /// FIFO 1 message pending interrupt enable
        FMPIE1 OFFSET(4) NUMBITS(1) [],
        /// FIFO 0 overrun interrupt enable
        FOVIE0 OFFSET(3) NUMBITS(1) [],
        /// FIFO 0 full interrupt enable
        FFIE0 OFFSET(2) NUMBITS(1) [],
        /// FIFO 0 message pending interrupt enable
        FMPIE0 OFFSET(1) NUMBITS(1) [],
        /// Transmit mailbox empty interrupt enable
        TMEIE OFFSET(0) NUMBITS(1) []
    ],
    CAN_ESR [
        /// Receive error counter
        REC OFFSET(24) NUMBITS(8) [],
        /// Least significant byte of the 9-bit transmit error counter
        TEC OFFSET(16) NUMBITS(8) [],
        /// Last error code
        LEC OFFSET(4) NUMBITS(3) [
            NoError = 0,
            StuffError = 1,
            FormError = 2,
            AcknowledgmentError = 3,
            BitRecessiveError = 4,
            BitDominantError = 5,
            CrcError = 6,
            SetBySoftware = 7
        ],
        /// Bus-off flag
        BOFF OFFSET(2) NUMBITS(1) [],
        /// Error passive flag
        EPVF OFFSET(1) NUMBITS(1) [],
        /// Error warning flag
        EWGF OFFSET(0) NUMBITS(1) []
    ],
    CAN_BTR [
        /// Silent mode (debug)
        SILM OFFSET(31) NUMBITS(1) [],
        /// Loop back mode (debug)
        LBKM OFFSET(30) NUMBITS(1) [],
        /// Resynchronization jump width
        SJW OFFSET(24) NUMBITS(2) [],
        /// Time segment 2
        TS2 OFFSET(20) NUMBITS(3) [],
        /// Time segment 1
        TS1 OFFSET(16) NUMBITS(4) [],
        /// Baud rate prescaler
        BRP OFFSET(0) NUMBITS(10) []
    ],
    ///
    ///
    /// CAN mailbox registers
    ///
    ///
    CAN_TIxR [
        /// Standard identifier or extended identifier
        STID OFFSET(21) NUMBITS(11) [],
        /// Extended identifier
        EXID OFFSET(3) NUMBITS(18) [],
        /// Identifier extension
        IDE OFFSET(2) NUMBITS(1) [],
        /// Remote transmission request
        RTR OFFSET(1) NUMBITS(1) [],
        /// Transmit mailbox request
        TXRQ OFFSET(0) NUMBITS(1) []
    ],
    CAN_TDTxR [
        /// Message time stamp
        TIME OFFSET(16) NUMBITS(16) [],
        /// Transmit global time
        TGT OFFSET(8) NUMBITS(1) [],
        /// Data length code
        DLC OFFSET(0) NUMBITS(4) []
    ],
    CAN_TDLxR [
        /// Data byte 3
        DATA3 OFFSET(24) NUMBITS(8) [],
        /// Data byte 2
        DATA2 OFFSET(16) NUMBITS(8) [],
        /// Data byte 1
        DATA1 OFFSET(8) NUMBITS(8) [],
        /// Data byte 0
        DATA0 OFFSET(0) NUMBITS(8) []
    ],
    CAN_TDHxR [
        /// Data byte 7
        DATA7 OFFSET(24) NUMBITS(8) [],
        /// Data byte 6
        DATA6 OFFSET(16) NUMBITS(8) [],
        /// Data byte 5
        DATA5 OFFSET(8) NUMBITS(8) [],
        /// Data byte 4
        DATA4 OFFSET(0) NUMBITS(8) []
    ],
    CAN_RIxR [
        /// Standard identifier or extended identifier
        STID OFFSET(21) NUMBITS(11) [],
        /// Extended identifier
        EXID OFFSET(3) NUMBITS(18) [],
        /// Identifier extension
        IDE OFFSET(2) NUMBITS(1) [],
        /// Remote transmission request
        RTR OFFSET(1) NUMBITS(1) []
    ],
    CAN_RDTxR [
        /// Message time stamp
        TIME OFFSET(16) NUMBITS(16) [],
        /// Filter match index
        FMI OFFSET(8) NUMBITS(8) [],
        /// Data length code
        DLC OFFSET(0) NUMBITS(4) []
    ],
    CAN_RDLxR [
        /// Data byte 3
        DATA3 OFFSET(24) NUMBITS(8) [],
        /// Data byte 2
        DATA2 OFFSET(16) NUMBITS(8) [],
        /// Data byte 1
        DATA1 OFFSET(8) NUMBITS(8) [],
        /// Data byte 0
        DATA0 OFFSET(0) NUMBITS(8) []
    ],
    CAN_RDHxR [
        /// Data byte 7
        DATA7 OFFSET(24) NUMBITS(8) [],
        /// Data byte 6
        DATA6 OFFSET(16) NUMBITS(8) [],
        /// Data byte 5
        DATA5 OFFSET(8) NUMBITS(8) [],
        /// Data byte 4
        DATA4 OFFSET(0) NUMBITS(8) []
    ],
    ///
    ///
    /// CAN filter registers
    ///
    ///
    CAN_FMR [
        /// CAN start bank
        CANSB OFFSET(8) NUMBITS(6) [],
        /// Filter initialization mode
        FINIT OFFSET(0) NUMBITS(1) []
    ],
    /// CAN filter mode register
    CAN_FM1R [
        /// Filter mode
        FBM OFFSET(0) NUMBITS(28) []
    ],
    CAN_FS1R [
        /// Filter scale configuration
        FSC OFFSET(0) NUMBITS(28) []
    ],
    CAN_FFA1R [
        /// Filter FIFO assignment for filter x
        FFA OFFSET(0) NUMBITS(28) []
    ],
    CAN_FA1R [
        /// Filter active
        FACT OFFSET(0) NUMBITS(28) []
    ],
    CAN_FiRx [
        /// Filter bits
        FB OFFSET(0) NUMBITS(32) []
    ]
];

#[derive(Copy, Clone, PartialEq)]
enum CanState {
    Initialization,
    Normal,
    Sleep,
    RunningError(can::Error),
}

// The 4 possbile actions that the deferred call task can do.
#[derive(Copy, Clone, PartialEq)]
enum AsyncAction {
    Enable,
    AbortReceive,
    Disabled,
    EnableError(kernel::ErrorCode),
}

#[repr(u32)]
enum BitSegment1 {
    CanBtrTs1Min = 0b0000,
    CanBtrTs1Max = 0b1111,
}

#[repr(u32)]
enum BitSegment2 {
    CanBtrTs2Min = 0b0000,
    CanBtrTs2Max = 0b0111,
}

#[repr(u32)]
enum SynchronizationJumpWidth {
    CanBtrSjwMin = 0b00,
    CanBtrSjwMax = 0b11,
}

#[derive(Copy, Clone, PartialEq)]
pub enum CanInterruptMode {
    TransmitInterrupt,
    Fifo0Interrupt,
    Fifo1Interrupt,
    ErrorAndStatusChangeInterrupt,
}

impl From<CanState> for can::State {
    fn from(state: CanState) -> Self {
        match state {
            CanState::Initialization | CanState::Sleep => can::State::Disabled,
            CanState::Normal => can::State::Running,
            CanState::RunningError(err) => can::State::Error(err),
        }
    }
}

pub struct Can<'a> {
    registers: StaticRef<Registers>,
    clock: CanClock<'a>,
    can_state: Cell<CanState>,
    error_interrupt_counter: Cell<u32>,
    fifo0_interrupt_counter: Cell<u32>,
    fifo1_interrupt_counter: Cell<u32>,
    failed_messages: Cell<u32>,

    // communication parameters
    automatic_retransmission: Cell<bool>,
    automatic_wake_up: Cell<bool>,
    operating_mode: OptionalCell<can::OperationMode>,
    bit_timing: OptionalCell<can::BitTiming>,

    // clients
    controller_client: OptionalCell<&'static dyn can::ControllerClient>,
    receive_client:
        OptionalCell<&'static dyn can::ReceiveClient<{ can::STANDARD_CAN_PACKET_SIZE }>>,
    transmit_client:
        OptionalCell<&'static dyn can::TransmitClient<{ can::STANDARD_CAN_PACKET_SIZE }>>,

    // buffers for transmission and reception
    rx_buffer: TakeCell<'static, [u8; can::STANDARD_CAN_PACKET_SIZE]>,
    tx_buffer: TakeCell<'static, [u8; can::STANDARD_CAN_PACKET_SIZE]>,

    deferred_call: DeferredCall,
    // deferred call task action
    deferred_action: OptionalCell<AsyncAction>,
}

impl<'a> Can<'a> {
    pub fn new(clocks: &'a dyn Stm32f4Clocks, registers: StaticRef<Registers>) -> Can<'a> {
        Can {
            registers,
            clock: CanClock(phclk::PeripheralClock::new(
                phclk::PeripheralClockType::APB1(phclk::PCLK1::CAN1),
                clocks,
            )),
            can_state: Cell::new(CanState::Sleep),
            error_interrupt_counter: Cell::new(0),
            fifo0_interrupt_counter: Cell::new(0),
            fifo1_interrupt_counter: Cell::new(0),
            failed_messages: Cell::new(0),
            automatic_retransmission: Cell::new(false),
            automatic_wake_up: Cell::new(false),
            operating_mode: OptionalCell::empty(),
            bit_timing: OptionalCell::empty(),
            controller_client: OptionalCell::empty(),
            receive_client: OptionalCell::empty(),
            transmit_client: OptionalCell::empty(),
            rx_buffer: TakeCell::empty(),
            tx_buffer: TakeCell::empty(),
            deferred_call: DeferredCall::new(),
            deferred_action: OptionalCell::empty(),
        }
    }

    /// This function is used for busy waiting and checks if the closure
    /// received as an argument returns a true value for `times` times.
    ///
    /// Usage: check is the INAK bit in the CAN_MSR is set for 200_000 times.
    /// ```ignore
    ///    Can::wait_for(200_000, || self.registers.can_msr.is_set(CAN_MSR::INAK))
    /// ```
    fn wait_for(times: usize, f: impl Fn() -> bool) -> bool {
        for _ in 0..times {
            if f() {
                return true;
            }
        }

        false
    }

    /// Enable the peripheral with the stored communication parameters:
    /// bit timing settings and communication mode
    pub fn enable(&self) -> Result<(), kernel::ErrorCode> {
        // leave Sleep Mode
        self.registers.can_mcr.modify(CAN_MCR::SLEEP::CLEAR);

        // request to enter the initialization mode
        self.registers.can_mcr.modify(CAN_MCR::INRQ::SET);

        // After requesting to enter the initialization mode, the driver
        // must wait for ACK from the peripheral - the INAK bit to be set
        // (as explained in RM0090 Reference Manual, Chapter 32.4.1).
        // This is done by checking the INAK bit 20_000 times or until it is set.
        if !Can::wait_for(20000, || self.registers.can_msr.is_set(CAN_MSR::INAK)) {
            return Err(kernel::ErrorCode::FAIL);
        }

        self.can_state.set(CanState::Initialization);

        // After requesting to enter the initialization mode, the driver
        // must wait for ACK from the peripheral - the SLAK bit to be cleared
        // (as explained in RM0090 Reference Manual, Chapter 32.4, Figure 336).
        // This is done by checking the SLAK bit 20_000 times or until it is cleared.
        if !Can::wait_for(20000, || !self.registers.can_msr.is_set(CAN_MSR::SLAK)) {
            return Err(kernel::ErrorCode::FAIL);
        }

        // set communication mode
        self.registers.can_mcr.modify(CAN_MCR::TTCM::CLEAR);
        self.registers.can_mcr.modify(CAN_MCR::ABOM::CLEAR);
        self.registers.can_mcr.modify(CAN_MCR::RFLM::CLEAR);
        self.registers.can_mcr.modify(CAN_MCR::TXFP::CLEAR);

        match self.automatic_retransmission.get() {
            true => self.registers.can_mcr.modify(CAN_MCR::AWUM::SET),
            false => self.registers.can_mcr.modify(CAN_MCR::AWUM::CLEAR),
        }

        match self.automatic_wake_up.get() {
            true => self.registers.can_mcr.modify(CAN_MCR::NART::CLEAR),
            false => self.registers.can_mcr.modify(CAN_MCR::NART::SET),
        }

        if let Some(operating_mode_settings) = self.operating_mode.get() {
            match operating_mode_settings {
                can::OperationMode::Loopback => self.registers.can_btr.modify(CAN_BTR::LBKM::SET),
                can::OperationMode::Monitoring => self.registers.can_btr.modify(CAN_BTR::SILM::SET),
                can::OperationMode::Freeze => return Err(kernel::ErrorCode::INVAL),
                _ => {}
            }
        }

        // set bit timing mode
        if let Some(bit_timing_settings) = self.bit_timing.get() {
            self.registers
                .can_btr
                .modify(CAN_BTR::TS1.val(bit_timing_settings.segment1 as u32));
            self.registers
                .can_btr
                .modify(CAN_BTR::TS2.val(bit_timing_settings.segment2 as u32));
            self.registers
                .can_btr
                .modify(CAN_BTR::SJW.val(bit_timing_settings.sync_jump_width));
            self.registers
                .can_btr
                .modify(CAN_BTR::BRP.val(bit_timing_settings.baud_rate_prescaler));
        } else {
            self.enter_sleep_mode();
            return Err(kernel::ErrorCode::INVAL);
        }

        Ok(())
    }

    /// Configure a filter to receive messages
    pub fn config_filter(&self, filter_info: can::FilterParameters, enable: bool) {
        // get position of the filter number
        let filter_number = 1 << filter_info.number;

        // start filter configuration
        self.registers.can_fmr.modify(CAN_FMR::FINIT::SET);

        // request filter number filter_number
        self.registers.can_fa1r.modify(
            CAN_FA1R::FACT.val(self.registers.can_fa1r.read(CAN_FA1R::FACT) & !filter_number),
        );

        // request filter width to be 32 or 16 bits
        match filter_info.scale_bits {
            can::ScaleBits::Bits16 => {
                self.registers.can_fs1r.modify(
                    CAN_FS1R::FSC.val(self.registers.can_fs1r.read(CAN_FS1R::FSC) | filter_number),
                );
            }
            can::ScaleBits::Bits32 => {
                self.registers.can_fs1r.modify(
                    CAN_FS1R::FSC.val(self.registers.can_fs1r.read(CAN_FS1R::FSC) & !filter_number),
                );
            }
        }

        self.registers.can_firx[(filter_info.number as usize) * 2].modify(CAN_FiRx::FB.val(0));
        self.registers.can_firx[(filter_info.number as usize) * 2 + 1].modify(CAN_FiRx::FB.val(0));

        // request filter mode to be mask or list
        match filter_info.identifier_mode {
            can::IdentifierMode::List => {
                self.registers.can_fm1r.modify(
                    CAN_FM1R::FBM.val(self.registers.can_fm1r.read(CAN_FM1R::FBM) | filter_number),
                );
            }
            can::IdentifierMode::Mask => {
                self.registers.can_fm1r.modify(
                    CAN_FM1R::FBM.val(self.registers.can_fm1r.read(CAN_FM1R::FBM) & !filter_number),
                );
            }
        }

        // request fifo0 or fifo1
        if filter_info.fifo_number == 0 {
            self.registers.can_ffa1r.modify(
                CAN_FFA1R::FFA.val(self.registers.can_ffa1r.read(CAN_FFA1R::FFA) & !filter_number),
            );
        } else {
            self.registers.can_ffa1r.modify(
                CAN_FFA1R::FFA.val(self.registers.can_ffa1r.read(CAN_FFA1R::FFA) | filter_number),
            );
        }

        if enable {
            self.registers.can_fa1r.modify(
                CAN_FA1R::FACT.val(self.registers.can_fa1r.read(CAN_FA1R::FACT) | filter_number),
            );
        } else {
            self.registers.can_fa1r.modify(
                CAN_FA1R::FACT.val(self.registers.can_fa1r.read(CAN_FA1R::FACT) & !filter_number),
            );
        }
    }

    pub fn enable_filter_config(&self) {
        // activate the filter configuration
        self.registers.can_fmr.modify(CAN_FMR::FINIT::CLEAR);
    }

    pub fn enter_normal_mode(&self) -> Result<(), kernel::ErrorCode> {
        // request to enter normal mode by clearing INRQ bit
        self.registers.can_mcr.modify(CAN_MCR::INRQ::CLEAR);

        // After requesting to enter the normal mode, the driver
        // must wait for ACK from the peripheral - the INAK bit to be cleared
        // (as explained in RM0090 Reference Manual, Chapter 32.4.2).
        // This is done by checking the INAK bit 20_000 times or until it is cleared.
        if !Can::wait_for(20000, || !self.registers.can_msr.is_set(CAN_MSR::INAK)) {
            return Err(kernel::ErrorCode::FAIL);
        }

        self.can_state.set(CanState::Normal);
        Ok(())
    }

    pub fn enter_sleep_mode(&self) {
        // request to enter sleep mode by setting SLEEP bit
        self.disable_irqs();
        self.registers.can_mcr.modify(CAN_MCR::SLEEP::SET);
        self.can_state.set(CanState::Sleep);
    }

    /// This function sends an 8-byte message
    pub fn send_8byte_message(
        &self,
        id: can::Id,
        dlc: usize,
        rtr: u8,
    ) -> Result<(), kernel::ErrorCode> {
        self.enable_irq(CanInterruptMode::ErrorAndStatusChangeInterrupt);
        if self.can_state.get() == CanState::Normal {
            if let Some(tx_mailbox) = self.find_empty_mailbox() {
                // set extended or standard id in registers
                match id {
                    can::Id::Standard(id) => {
                        self.registers.can_tx_mailbox[tx_mailbox]
                            .can_tir
                            .modify(CAN_TIxR::IDE::CLEAR);
                        self.registers.can_tx_mailbox[tx_mailbox]
                            .can_tir
                            .modify(CAN_TIxR::STID.val(id as u32 & 0xeff));
                        self.registers.can_tx_mailbox[tx_mailbox]
                            .can_tir
                            .modify(CAN_TIxR::EXID.val(0));
                    }
                    can::Id::Extended(id) => {
                        self.registers.can_tx_mailbox[tx_mailbox]
                            .can_tir
                            .modify(CAN_TIxR::IDE::SET);
                        self.registers.can_tx_mailbox[tx_mailbox]
                            .can_tir
                            .modify(CAN_TIxR::STID.val((id & 0xffc0000) >> 18));
                        self.registers.can_tx_mailbox[tx_mailbox]
                            .can_tir
                            .modify(CAN_TIxR::EXID.val(id & 0x003fffff));
                    }
                }
                // write rtr
                self.registers.can_tx_mailbox[tx_mailbox]
                    .can_tir
                    .modify(CAN_TIxR::RTR.val(rtr.into()));
                // write dlc
                self.registers.can_tx_mailbox[tx_mailbox]
                    .can_tdtr
                    .modify(CAN_TDTxR::DLC.val(dlc as u32));
                // write first 4 bytes of the data
                match self.tx_buffer.map(|tx| {
                    self.registers.can_tx_mailbox[tx_mailbox]
                        .can_tdlr
                        .modify(CAN_TDLxR::DATA0.val(tx[0].into()));
                    self.registers.can_tx_mailbox[tx_mailbox]
                        .can_tdlr
                        .modify(CAN_TDLxR::DATA1.val(tx[1].into()));
                    self.registers.can_tx_mailbox[tx_mailbox]
                        .can_tdlr
                        .modify(CAN_TDLxR::DATA2.val(tx[2].into()));
                    self.registers.can_tx_mailbox[tx_mailbox]
                        .can_tdlr
                        .modify(CAN_TDLxR::DATA3.val(tx[3].into()));
                    // write the last 4 bytes of the data
                    self.registers.can_tx_mailbox[tx_mailbox]
                        .can_tdhr
                        .modify(CAN_TDHxR::DATA4.val(tx[4].into()));
                    self.registers.can_tx_mailbox[tx_mailbox]
                        .can_tdhr
                        .modify(CAN_TDHxR::DATA5.val(tx[5].into()));
                    self.registers.can_tx_mailbox[tx_mailbox]
                        .can_tdhr
                        .modify(CAN_TDHxR::DATA6.val(tx[6].into()));
                    self.registers.can_tx_mailbox[tx_mailbox]
                        .can_tdhr
                        .modify(CAN_TDHxR::DATA7.val(tx[7].into()));

                    self.registers.can_tx_mailbox[tx_mailbox]
                        .can_tir
                        .modify(CAN_TIxR::TXRQ::SET);
                }) {
                    Some(()) => Ok(()),
                    None => Err(kernel::ErrorCode::FAIL),
                }
            } else {
                // no mailbox empty
                self.failed_messages.replace(self.failed_messages.get() + 1);
                Err(kernel::ErrorCode::BUSY)
            }
        } else {
            Err(kernel::ErrorCode::OFF)
        }
    }

    pub fn find_empty_mailbox(&self) -> Option<usize> {
        if self.registers.can_tsr.read(CAN_TSR::TME0) == 1 {
            Some(0)
        } else if self.registers.can_tsr.read(CAN_TSR::TME1) == 1 {
            Some(1)
        } else if self.registers.can_tsr.read(CAN_TSR::TME2) == 1 {
            Some(2)
        } else {
            None
        }
    }

    pub fn is_enabled_clock(&self) -> bool {
        self.clock.is_enabled()
    }

    pub fn enable_clock(&self) {
        self.clock.enable();
    }

    pub fn disable_clock(&self) {
        self.clock.disable();
    }

    /// Handle the transmit interrupt. Check the status register for each
    /// transmit mailbox to find out the mailbox that the message was sent from.
    pub fn handle_transmit_interrupt(&self) {
        let mut state = Ok(());
        if self.registers.can_esr.read(CAN_ESR::BOFF) == 1 {
            state = Err(can::Error::BusOff)
        } else {
            if self.registers.can_tsr.read(CAN_TSR::RQCP0) == 1 {
                // check status
                state = if self.registers.can_tsr.read(CAN_TSR::TXOK0) == 1 {
                    Ok(())
                } else if self.registers.can_tsr.read(CAN_TSR::TERR0) == 1 {
                    Err(can::Error::Transmission)
                } else if self.registers.can_tsr.read(CAN_TSR::ALST0) == 1 {
                    Err(can::Error::ArbitrationLost)
                } else {
                    Ok(())
                };
                // mark the interrupt as handled
                self.registers.can_tsr.modify(CAN_TSR::RQCP0::SET);
            }
            if self.registers.can_tsr.read(CAN_TSR::RQCP1) == 1 {
                state = if self.registers.can_tsr.read(CAN_TSR::TXOK1) == 1 {
                    Ok(())
                } else if self.registers.can_tsr.read(CAN_TSR::TERR1) == 1 {
                    Err(can::Error::Transmission)
                } else if self.registers.can_tsr.read(CAN_TSR::ALST1) == 1 {
                    Err(can::Error::ArbitrationLost)
                } else {
                    Ok(())
                };
                // mark the interrupt as handled
                self.registers.can_tsr.modify(CAN_TSR::RQCP1::SET);
            }
            if self.registers.can_tsr.read(CAN_TSR::RQCP2) == 1 {
                state = if self.registers.can_tsr.read(CAN_TSR::TXOK2) == 1 {
                    Ok(())
                } else if self.registers.can_tsr.read(CAN_TSR::TERR2) == 1 {
                    Err(can::Error::Transmission)
                } else if self.registers.can_tsr.read(CAN_TSR::ALST2) == 1 {
                    Err(can::Error::ArbitrationLost)
                } else {
                    Ok(())
                };
                // mark the interrupt as handled
                self.registers.can_tsr.modify(CAN_TSR::RQCP2::SET);
            }
        }

        match state {
            Err(err) => self.can_state.set(CanState::RunningError(err)),
            _ => {}
        }

        self.transmit_client
            .map(|transmit_client| match self.tx_buffer.take() {
                Some(buf) => transmit_client.transmit_complete(state, buf),
                None => {}
            });
    }

    pub fn process_received_message(
        &self,
        rx_mailbox: usize,
    ) -> (can::Id, usize, [u8; can::STANDARD_CAN_PACKET_SIZE]) {
        let message_id = if self.registers.can_rx_mailbox[rx_mailbox]
            .can_rir
            .read(CAN_RIxR::IDE)
            == 0
        {
            can::Id::Standard(
                self.registers.can_rx_mailbox[rx_mailbox]
                    .can_rir
                    .read(CAN_RIxR::STID) as u16,
            )
        } else {
            can::Id::Extended(
                (self.registers.can_rx_mailbox[rx_mailbox]
                    .can_rir
                    .read(CAN_RIxR::STID)
                    << 18)
                    | (self.registers.can_rx_mailbox[rx_mailbox]
                        .can_rir
                        .read(CAN_RIxR::EXID)),
            )
        };
        let message_length = self.registers.can_rx_mailbox[rx_mailbox]
            .can_rdtr
            .read(CAN_RDTxR::DLC) as usize;
        let recv: u64 = ((self.registers.can_rx_mailbox[0].can_rdhr.get() as u64) << 32)
            | (self.registers.can_rx_mailbox[0].can_rdlr.get() as u64);
        let rx_buf = recv.to_le_bytes();
        self.rx_buffer.map(|rx| {
            rx[..8].copy_from_slice(&rx_buf[..8]);
        });

        (message_id, message_length, rx_buf)
    }

    pub fn handle_fifo0_interrupt(&self) {
        if self.registers.can_rf0r.read(CAN_RF0R::FULL0) == 1 {
            self.registers.can_rf0r.modify(CAN_RF0R::FULL0::SET);
        }

        if self.registers.can_rf0r.read(CAN_RF0R::FOVR0) == 1 {
            self.registers.can_rf0r.modify(CAN_RF0R::FOVR0::SET);
        }

        if self.registers.can_rf0r.read(CAN_RF0R::FMP0) != 0 {
            let (message_id, message_length, mut rx_buf) = self.process_received_message(0);

            self.receive_client.map(|receive_client| {
                receive_client.message_received(message_id, &mut rx_buf, message_length, Ok(()))
            });
            self.fifo0_interrupt_counter
                .replace(self.fifo0_interrupt_counter.get() + 1);

            // mark the interrupt as handled
            self.registers.can_rf0r.modify(CAN_RF0R::RFOM0::SET);
        }
    }

    pub fn handle_fifo1_interrupt(&self) {
        if self.registers.can_rf1r.read(CAN_RF1R::FULL1) == 1 {
            self.registers.can_rf1r.modify(CAN_RF1R::FULL1::SET);
        }

        if self.registers.can_rf1r.read(CAN_RF1R::FOVR1) == 1 {
            self.registers.can_rf1r.modify(CAN_RF1R::FOVR1::SET);
        }

        if self.registers.can_rf1r.read(CAN_RF1R::FMP1) != 0 {
            self.fifo1_interrupt_counter
                .replace(self.fifo1_interrupt_counter.get() + 1);
            let (message_id, message_length, mut rx_buf) = self.process_received_message(1);
            self.receive_client.map(|receive_client| {
                receive_client.message_received(message_id, &mut rx_buf, message_length, Ok(()))
            });

            // mark the interrupt as handled
            self.registers.can_rf1r.modify(CAN_RF1R::RFOM1::SET);
        }
    }

    pub fn handle_error_status_interrupt(&self) {
        // Check if there is a status change interrupt
        if self.registers.can_msr.read(CAN_MSR::WKUI) == 1 {
            // mark the interrupt as handled
            self.registers.can_msr.modify(CAN_MSR::WKUI::SET);
        }
        if self.registers.can_msr.read(CAN_MSR::SLAKI) == 1 {
            // mark the interrupt as handled
            self.registers.can_msr.modify(CAN_MSR::SLAKI::SET);
        }

        // Check if there is an error interrupt
        // Warning flag
        if self.registers.can_esr.read(CAN_ESR::EWGF) == 1 {
            self.can_state
                .set(CanState::RunningError(can::Error::Warning));
        }
        // Passive flag
        if self.registers.can_esr.read(CAN_ESR::EPVF) == 1 {
            self.can_state
                .set(CanState::RunningError(can::Error::Passive));
        }
        // Bus-off flag
        if self.registers.can_esr.read(CAN_ESR::BOFF) == 1 {
            self.can_state
                .set(CanState::RunningError(can::Error::BusOff));
        }
        // Last Error Code
        match self.registers.can_esr.read(CAN_ESR::LEC) {
            0x001 => self
                .can_state
                .set(CanState::RunningError(can::Error::Stuff)),
            0x010 => self.can_state.set(CanState::RunningError(can::Error::Form)),
            0x011 => self.can_state.set(CanState::RunningError(can::Error::Ack)),
            0x100 => self
                .can_state
                .set(CanState::RunningError(can::Error::BitRecessive)),
            0x101 => self
                .can_state
                .set(CanState::RunningError(can::Error::BitDominant)),
            0x110 => self.can_state.set(CanState::RunningError(can::Error::Crc)),
            0x111 => self
                .can_state
                .set(CanState::RunningError(can::Error::SetBySoftware)),
            _ => {}
        }

        self.error_interrupt_counter
            .replace(self.error_interrupt_counter.get() + 1);

        match self.can_state.get() {
            CanState::RunningError(err) => {
                self.controller_client.map(|controller_client| {
                    controller_client.state_changed(kernel::hil::can::State::Error(err));
                });
            }
            _ => {}
        }
    }

    pub fn enable_irq(&self, interrupt: CanInterruptMode) {
        match interrupt {
            CanInterruptMode::TransmitInterrupt => {
                self.registers.can_ier.modify(CAN_IER::TMEIE::SET);
            }
            CanInterruptMode::Fifo0Interrupt => {
                self.registers.can_ier.modify(CAN_IER::FMPIE0::SET);
                self.registers.can_ier.modify(CAN_IER::FFIE0::SET);
                self.registers.can_ier.modify(CAN_IER::FOVIE0::SET);
            }
            CanInterruptMode::Fifo1Interrupt => {
                self.registers.can_ier.modify(CAN_IER::FMPIE1::SET);
                self.registers.can_ier.modify(CAN_IER::FFIE1::SET);
                self.registers.can_ier.modify(CAN_IER::FOVIE1::SET);
            }
            CanInterruptMode::ErrorAndStatusChangeInterrupt => {
                self.registers.can_ier.modify(CAN_IER::ERRIE::SET);
                self.registers.can_ier.modify(CAN_IER::EWGIE::SET);
                self.registers.can_ier.modify(CAN_IER::EPVIE::SET);
                self.registers.can_ier.modify(CAN_IER::BOFIE::SET);
                self.registers.can_ier.modify(CAN_IER::LECIE::SET);
                self.registers.can_ier.modify(CAN_IER::WKUIE::SET);
                self.registers.can_ier.modify(CAN_IER::SLKIE::SET);
            }
        }
    }

    pub fn disable_irq(&self, interrupt: CanInterruptMode) {
        match interrupt {
            CanInterruptMode::TransmitInterrupt => {
                self.registers.can_ier.modify(CAN_IER::TMEIE::CLEAR);
            }
            CanInterruptMode::Fifo0Interrupt => {
                self.registers.can_ier.modify(CAN_IER::FMPIE0::CLEAR);
                self.registers.can_ier.modify(CAN_IER::FFIE0::CLEAR);
                self.registers.can_ier.modify(CAN_IER::FOVIE0::CLEAR);
            }
            CanInterruptMode::Fifo1Interrupt => {
                self.registers.can_ier.modify(CAN_IER::FMPIE1::CLEAR);
                self.registers.can_ier.modify(CAN_IER::FFIE1::CLEAR);
                self.registers.can_ier.modify(CAN_IER::FOVIE1::CLEAR);
            }
            CanInterruptMode::ErrorAndStatusChangeInterrupt => {
                self.registers.can_ier.modify(CAN_IER::ERRIE::CLEAR);
                self.registers.can_ier.modify(CAN_IER::EWGIE::CLEAR);
                self.registers.can_ier.modify(CAN_IER::EPVIE::CLEAR);
                self.registers.can_ier.modify(CAN_IER::BOFIE::CLEAR);
                self.registers.can_ier.modify(CAN_IER::LECIE::CLEAR);
                self.registers.can_ier.modify(CAN_IER::WKUIE::CLEAR);
                self.registers.can_ier.modify(CAN_IER::SLKIE::CLEAR);
            }
        }
    }

    pub fn enable_irqs(&self) {
        self.enable_irq(CanInterruptMode::TransmitInterrupt);
        self.enable_irq(CanInterruptMode::Fifo0Interrupt);
        self.enable_irq(CanInterruptMode::Fifo1Interrupt);
        self.enable_irq(CanInterruptMode::ErrorAndStatusChangeInterrupt);
    }

    pub fn disable_irqs(&self) {
        self.disable_irq(CanInterruptMode::TransmitInterrupt);
        self.disable_irq(CanInterruptMode::Fifo0Interrupt);
        self.disable_irq(CanInterruptMode::Fifo1Interrupt);
        self.disable_irq(CanInterruptMode::ErrorAndStatusChangeInterrupt);
    }
}

impl DeferredCallClient for Can<'_> {
    fn register(&'static self) {
        self.deferred_call.register(self)
    }

    fn handle_deferred_call(&self) {
        match self.deferred_action.take() {
            Some(action) => match action {
                AsyncAction::Enable => {
                    if let Err(enable_err) = self.enter_normal_mode() {
                        self.controller_client.map(|controller_client| {
                            controller_client.state_changed(self.can_state.get().into());
                            controller_client.enabled(Err(enable_err));
                        });
                    }
                    self.controller_client.map(|controller_client| {
                        controller_client.state_changed(can::State::Running);
                        controller_client.enabled(Ok(()));
                    });
                }
                AsyncAction::AbortReceive => {
                    if let Some(rx) = self.rx_buffer.take() {
                        self.receive_client
                            .map(|receive_client| receive_client.stopped(rx));
                    }
                }
                AsyncAction::Disabled => {
                    self.controller_client.map(|controller_client| {
                        controller_client.state_changed(self.can_state.get().into());
                        controller_client.disabled(Ok(()));
                    });
                }
                AsyncAction::EnableError(err) => {
                    self.controller_client.map(|controller_client| {
                        controller_client.state_changed(self.can_state.get().into());
                        controller_client.enabled(Err(err));
                    });
                }
            },
            // todo no action set
            None => todo!(),
        }
    }
}

struct CanClock<'a>(phclk::PeripheralClock<'a>);

impl ClockInterface for CanClock<'_> {
    fn is_enabled(&self) -> bool {
        self.0.is_enabled()
    }

    fn enable(&self) {
        self.0.enable();
    }

    fn disable(&self) {
        self.0.disable();
    }
}

impl can::Configure for Can<'_> {
    const MIN_BIT_TIMINGS: can::BitTiming = can::BitTiming {
        segment1: BitSegment1::CanBtrTs1Min as u8,
        segment2: BitSegment2::CanBtrTs2Min as u8,
        propagation: 0,
        sync_jump_width: SynchronizationJumpWidth::CanBtrSjwMin as u32,
        baud_rate_prescaler: BRP_MIN_STM32,
    };

    const MAX_BIT_TIMINGS: can::BitTiming = can::BitTiming {
        segment1: BitSegment1::CanBtrTs1Max as u8,
        segment2: BitSegment2::CanBtrTs2Max as u8,
        propagation: 0,
        sync_jump_width: SynchronizationJumpWidth::CanBtrSjwMax as u32,
        baud_rate_prescaler: BRP_MAX_STM32,
    };

    const SYNC_SEG: u8 = 1;

    fn set_bitrate(&self, bitrate: u32) -> Result<(), kernel::ErrorCode> {
        let bit_timing = Self::bit_timing_for_bitrate(16_000_000, bitrate)?;
        self.set_bit_timing(bit_timing)
    }

    fn set_bit_timing(&self, bit_timing: can::BitTiming) -> Result<(), kernel::ErrorCode> {
        match self.can_state.get() {
            CanState::Sleep => {
                self.bit_timing.set(bit_timing);
                Ok(())
            }
            CanState::Normal | CanState::Initialization | CanState::RunningError(_) => {
                Err(kernel::ErrorCode::BUSY)
            }
        }
    }

    fn set_operation_mode(&self, mode: can::OperationMode) -> Result<(), kernel::ErrorCode> {
        match self.can_state.get() {
            CanState::Sleep => {
                self.operating_mode.set(mode);
                Ok(())
            }
            CanState::Normal | CanState::Initialization | CanState::RunningError(_) => {
                Err(kernel::ErrorCode::BUSY)
            }
        }
    }

    fn get_bit_timing(&self) -> Result<can::BitTiming, kernel::ErrorCode> {
        if let Some(bit_timing) = self.bit_timing.get() {
            Ok(bit_timing)
        } else {
            Err(kernel::ErrorCode::INVAL)
        }
    }

    fn get_operation_mode(&self) -> Result<can::OperationMode, kernel::ErrorCode> {
        if let Some(operation_mode) = self.operating_mode.get() {
            Ok(operation_mode)
        } else {
            Err(kernel::ErrorCode::INVAL)
        }
    }

    fn set_automatic_retransmission(&self, automatic: bool) -> Result<(), kernel::ErrorCode> {
        match self.can_state.get() {
            CanState::Sleep => {
                self.automatic_retransmission.replace(automatic);
                Ok(())
            }
            CanState::Normal | CanState::Initialization | CanState::RunningError(_) => {
                Err(kernel::ErrorCode::BUSY)
            }
        }
    }

    fn set_wake_up(&self, wake_up: bool) -> Result<(), kernel::ErrorCode> {
        match self.can_state.get() {
            CanState::Sleep => {
                self.automatic_wake_up.replace(wake_up);
                Ok(())
            }
            CanState::Normal | CanState::Initialization | CanState::RunningError(_) => {
                Err(kernel::ErrorCode::BUSY)
            }
        }
    }

    fn get_automatic_retransmission(&self) -> Result<bool, kernel::ErrorCode> {
        Ok(self.automatic_retransmission.get())
    }

    fn get_wake_up(&self) -> Result<bool, kernel::ErrorCode> {
        Ok(self.automatic_wake_up.get())
    }

    fn receive_fifo_count(&self) -> usize {
        2
    }
}

impl can::Controller for Can<'_> {
    fn set_client(&self, client: Option<&'static dyn can::ControllerClient>) {
        if let Some(client) = client {
            self.controller_client.replace(client);
        } else {
            self.controller_client.clear();
        }
    }

    fn enable(&self) -> Result<(), kernel::ErrorCode> {
        match self.can_state.get() {
            CanState::Sleep => {
                if self.bit_timing.is_none() || self.operating_mode.is_none() {
                    Err(kernel::ErrorCode::INVAL)
                } else {
                    let r = self.enable();
                    // there is another deferred action that must be completed
                    if self.deferred_action.is_some() {
                        Err(kernel::ErrorCode::BUSY)
                    } else {
                        // set an Enable or an EnableError deferred action
                        match r {
                            Ok(()) => {
                                self.deferred_action.set(AsyncAction::Enable);
                            }
                            Err(err) => {
                                self.deferred_action.set(AsyncAction::EnableError(err));
                            }
                        }
                        self.deferred_call.set();
                        r
                    }
                }
            }
            CanState::Normal | CanState::Initialization => Err(kernel::ErrorCode::ALREADY),
            CanState::RunningError(_) => Err(kernel::ErrorCode::FAIL),
        }
    }

    fn disable(&self) -> Result<(), kernel::ErrorCode> {
        match self.can_state.get() {
            CanState::Normal | CanState::RunningError(_) => {
                self.enter_sleep_mode();
                if self.deferred_action.is_some() {
                    // there is another deferred action that must be completed
                    return Err(kernel::ErrorCode::BUSY);
                } else {
                    // set a Disable deferred action
                    self.deferred_action.set(AsyncAction::Disabled);
                    self.deferred_call.set();
                }
                Ok(())
            }
            CanState::Sleep | CanState::Initialization => Err(kernel::ErrorCode::OFF),
        }
    }

    fn get_state(&self) -> Result<can::State, kernel::ErrorCode> {
        Ok(self.can_state.get().into())
    }
}

impl can::Transmit<{ can::STANDARD_CAN_PACKET_SIZE }> for Can<'_> {
    fn set_client(
        &self,
        client: Option<&'static dyn can::TransmitClient<{ can::STANDARD_CAN_PACKET_SIZE }>>,
    ) {
        if let Some(client) = client {
            self.transmit_client.set(client);
        } else {
            self.transmit_client.clear();
        }
    }

    fn send(
        &self,
        id: can::Id,
        buffer: &'static mut [u8; can::STANDARD_CAN_PACKET_SIZE],
        len: usize,
    ) -> Result<
        (),
        (
            kernel::ErrorCode,
            &'static mut [u8; can::STANDARD_CAN_PACKET_SIZE],
        ),
    > {
        match self.can_state.get() {
            CanState::Normal | CanState::RunningError(_) => {
                self.tx_buffer.replace(buffer);
                self.enable_irq(CanInterruptMode::TransmitInterrupt);
                self.can_state.set(CanState::Normal);
                match self.send_8byte_message(id, len, 0) {
                    Ok(()) => Ok(()),
                    Err(err) => Err((err, self.tx_buffer.take().unwrap())),
                }
            }
            CanState::Sleep | CanState::Initialization => Err((kernel::ErrorCode::OFF, buffer)),
        }
    }
}

impl can::Receive<{ can::STANDARD_CAN_PACKET_SIZE }> for Can<'_> {
    fn set_client(
        &self,
        client: Option<&'static dyn can::ReceiveClient<{ can::STANDARD_CAN_PACKET_SIZE }>>,
    ) {
        if let Some(client) = client {
            self.receive_client.set(client);
        } else {
            self.receive_client.clear();
        }
    }

    fn start_receive_process(
        &self,
        buffer: &'static mut [u8; can::STANDARD_CAN_PACKET_SIZE],
    ) -> Result<
        (),
        (
            kernel::ErrorCode,
            &'static mut [u8; can::STANDARD_CAN_PACKET_SIZE],
        ),
    > {
        match self.can_state.get() {
            CanState::Normal | CanState::RunningError(_) => {
                self.can_state.set(CanState::Normal);
                self.config_filter(
                    can::FilterParameters {
                        number: 0,
                        scale_bits: can::ScaleBits::Bits32,
                        identifier_mode: can::IdentifierMode::Mask,
                        fifo_number: 0,
                    },
                    true,
                );
                self.config_filter(
                    can::FilterParameters {
                        number: 1,
                        scale_bits: can::ScaleBits::Bits32,
                        identifier_mode: can::IdentifierMode::Mask,
                        fifo_number: 1,
                    },
                    true,
                );
                self.enable_filter_config();
                self.enable_irq(CanInterruptMode::Fifo0Interrupt);
                self.enable_irq(CanInterruptMode::Fifo1Interrupt);
                self.rx_buffer.put(Some(buffer));
                Ok(())
            }
            CanState::Sleep | CanState::Initialization => Err((kernel::ErrorCode::OFF, buffer)),
        }
    }

    fn stop_receive(&self) -> Result<(), kernel::ErrorCode> {
        match self.can_state.get() {
            CanState::Normal | CanState::RunningError(_) => {
                self.can_state.set(CanState::Normal);
                self.config_filter(
                    can::FilterParameters {
                        number: 0,
                        scale_bits: can::ScaleBits::Bits32,
                        identifier_mode: can::IdentifierMode::Mask,
                        fifo_number: 0,
                    },
                    false,
                );
                self.config_filter(
                    can::FilterParameters {
                        number: 1,
                        scale_bits: can::ScaleBits::Bits32,
                        identifier_mode: can::IdentifierMode::Mask,
                        fifo_number: 1,
                    },
                    false,
                );
                self.enable_filter_config();
                self.disable_irq(CanInterruptMode::Fifo0Interrupt);
                self.disable_irq(CanInterruptMode::Fifo1Interrupt);
                // there is another deferred action that must be completed
                if self.deferred_action.is_some() {
                    Err(kernel::ErrorCode::BUSY)
                // the chip does not own the buffer from the capsule
                } else if self.rx_buffer.is_none() {
                    Err(kernel::ErrorCode::SIZE)
                } else {
                    // set a AbortReceive deferred action
                    self.deferred_action.set(AsyncAction::AbortReceive);
                    self.deferred_call.set();
                    Ok(())
                }
            }
            CanState::Sleep | CanState::Initialization => Err(kernel::ErrorCode::OFF),
        }
    }
}