-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathVanBusRx.cpp
1640 lines (1336 loc) · 53.8 KB
/
VanBusRx.cpp
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
/*
* VanBus packet receiver for ESP8266
*
* Written by Erik Tromp
*
* Version 0.4.0 - March, 2024
*
* MIT license, all text above must be included in any redistribution.
*/
#include <limits.h>
#include "VanBusRx.h"
#ifdef ARDUINO_ARCH_ESP32
#include <esp_task_wdt.h>
#define wdt_reset() esp_task_wdt_reset()
#else
#include <Esp.h> // wdt_reset
#endif
static const uint16_t VAN_CRC_POLYNOM = 0x0F9D;
#define VAN_CRC_TABLE_SIZE 256
static uint16_t crcTable[VAN_CRC_TABLE_SIZE] =
{
0x0000, 0x0F9D, 0x1F3A, 0x10A7, 0x3E74, 0x31E9, 0x214E, 0x2ED3,
0x7CE8, 0x7375, 0x63D2, 0x6C4F, 0x429C, 0x4D01, 0x5DA6, 0x523B,
0x764D, 0x79D0, 0x6977, 0x66EA, 0x4839, 0x47A4, 0x5703, 0x589E,
0x0AA5, 0x0538, 0x159F, 0x1A02, 0x34D1, 0x3B4C, 0x2BEB, 0x2476,
0x6307, 0x6C9A, 0x7C3D, 0x73A0, 0x5D73, 0x52EE, 0x4249, 0x4DD4,
0x1FEF, 0x1072, 0x00D5, 0x0F48, 0x219B, 0x2E06, 0x3EA1, 0x313C,
0x154A, 0x1AD7, 0x0A70, 0x05ED, 0x2B3E, 0x24A3, 0x3404, 0x3B99,
0x69A2, 0x663F, 0x7698, 0x7905, 0x57D6, 0x584B, 0x48EC, 0x4771,
0x4993, 0x460E, 0x56A9, 0x5934, 0x77E7, 0x787A, 0x68DD, 0x6740,
0x357B, 0x3AE6, 0x2A41, 0x25DC, 0x0B0F, 0x0492, 0x1435, 0x1BA8,
0x3FDE, 0x3043, 0x20E4, 0x2F79, 0x01AA, 0x0E37, 0x1E90, 0x110D,
0x4336, 0x4CAB, 0x5C0C, 0x5391, 0x7D42, 0x72DF, 0x6278, 0x6DE5,
0x2A94, 0x2509, 0x35AE, 0x3A33, 0x14E0, 0x1B7D, 0x0BDA, 0x0447,
0x567C, 0x59E1, 0x4946, 0x46DB, 0x6808, 0x6795, 0x7732, 0x78AF,
0x5CD9, 0x5344, 0x43E3, 0x4C7E, 0x62AD, 0x6D30, 0x7D97, 0x720A,
0x2031, 0x2FAC, 0x3F0B, 0x3096, 0x1E45, 0x11D8, 0x017F, 0x0EE2,
0x1CBB, 0x1326, 0x0381, 0x0C1C, 0x22CF, 0x2D52, 0x3DF5, 0x3268,
0x6053, 0x6FCE, 0x7F69, 0x70F4, 0x5E27, 0x51BA, 0x411D, 0x4E80,
0x6AF6, 0x656B, 0x75CC, 0x7A51, 0x5482, 0x5B1F, 0x4BB8, 0x4425,
0x161E, 0x1983, 0x0924, 0x06B9, 0x286A, 0x27F7, 0x3750, 0x38CD,
0x7FBC, 0x7021, 0x6086, 0x6F1B, 0x41C8, 0x4E55, 0x5EF2, 0x516F,
0x0354, 0x0CC9, 0x1C6E, 0x13F3, 0x3D20, 0x32BD, 0x221A, 0x2D87,
0x09F1, 0x066C, 0x16CB, 0x1956, 0x3785, 0x3818, 0x28BF, 0x2722,
0x7519, 0x7A84, 0x6A23, 0x65BE, 0x4B6D, 0x44F0, 0x5457, 0x5BCA,
0x5528, 0x5AB5, 0x4A12, 0x458F, 0x6B5C, 0x64C1, 0x7466, 0x7BFB,
0x29C0, 0x265D, 0x36FA, 0x3967, 0x17B4, 0x1829, 0x088E, 0x0713,
0x2365, 0x2CF8, 0x3C5F, 0x33C2, 0x1D11, 0x128C, 0x022B, 0x0DB6,
0x5F8D, 0x5010, 0x40B7, 0x4F2A, 0x61F9, 0x6E64, 0x7EC3, 0x715E,
0x362F, 0x39B2, 0x2915, 0x2688, 0x085B, 0x07C6, 0x1761, 0x18FC,
0x4AC7, 0x455A, 0x55FD, 0x5A60, 0x74B3, 0x7B2E, 0x6B89, 0x6414,
0x4062, 0x4FFF, 0x5F58, 0x50C5, 0x7E16, 0x718B, 0x612C, 0x6EB1,
0x3C8A, 0x3317, 0x23B0, 0x2C2D, 0x02FE, 0x0D63, 0x1DC4, 0x1259,
};
// Above table is generated by:
//
// void _initCrcTable()
// {
// #define VAN_CRC_LENGTH 15
// const uint16_t mask = (1 << (VAN_CRC_LENGTH - 1));
//
// for (int i = 0; i < VAN_CRC_TABLE_SIZE; i++)
// {
// uint16_t crc = i << 7;
// for (uint8_t bit = 0; bit < 8; bit++)
// {
// if (crc & mask) crc = (crc << 1) ^ VAN_CRC_POLYNOM; else crc <<= 1;
// }
// crcTable[i] = crc & 0x7FFF;
// } // for
// } // _initCrcTable
//
// See also: https://github.com/0xCAFEDECAF/VanBus/blob/0ef35582dbcc6809175b3e11802e1eb84c561fb2/VanBusRx.cpp#L30
//
uint16_t _crc(const uint8_t bytes[], int size)
{
uint16_t crc15 = 0x7FFF;
for (int i = 1; i < size - 2; i++) // Skip first byte (SOF, 0x0E) and last 2 (CRC)
{
uint8_t byte = bytes[i];
// XOR-in next input byte into MSB of crc, that's our new intermediate divident
uint8_t pos = (uint8_t)( (crc15 >> 7) ^ byte);
// Shift out the MSB used for division per lookup table and XOR with the remainder
crc15 = (uint16_t)((crc15 << 8) ^ (uint16_t)(crcTable[pos]));
} // for
crc15 ^= 0x7FFF;
crc15 <<= 1; // Shift left 1 bit to turn 15 bit result into 16 bit representation
return crc15;
} // _crc
// Returns the Flags field of a VAN packet
uint8_t TVanPacketRxDesc::CommandFlags() const
{
// Bits:
// 3 : always 1
// 2 (Request AcK, RAK) : 1 = requesting ack; 0 = no ack requested
// 1 (Read/Write, R/W) : 1 = read; 0 = write
// 0 (Remote Transmission Request, RTR; only when R/W == 1) : 1 = request for in-frame response
return bytes[2] & 0x0F;
} // TVanPacketRxDesc::Flags
// Returns a pointer to the data bytes of a VAN packet
const uint8_t* TVanPacketRxDesc::Data() const
{
return bytes + 3;
} // TVanPacketRxDesc::Data
// Returns the data length of a VAN packet
int TVanPacketRxDesc::DataLen() const
{
// Total size minus SOF (1 byte), IDEN (1.5 bytes), COM (0.5 bytes) and CRC + EOD (2 bytes)
return size - 5;
} // TVanPacketRxDesc::DataLen
// Calculates the CRC of a VAN packet
uint16_t TVanPacketRxDesc::Crc() const
{
return _crc(bytes, size);
} // TVanPacketRxDesc::Crc
// Checks the CRC value of a VAN packet
bool TVanPacketRxDesc::CheckCrc() const
{
uint16_t crc15 = 0x7FFF;
for (int i = 1; i < size; i++) // Skip first byte (SOF, 0x0E)
{
uint8_t byte = bytes[i];
// XOR-in next input byte into MSB of crc, that's our new intermediate divident
uint8_t pos = (uint8_t)( (crc15 >> 7) ^ byte);
// Shift out the MSB used for division per lookup table and XOR with the remainder
crc15 = (uint16_t)((crc15 << 8) ^ (uint16_t)(crcTable[pos]));
} // for
crc15 &= 0x7FFF;
// Packet is OK if crc15 == 0x19B7
return crc15 == 0x19B7;
} // TVanPacketRxDesc::CheckCrc
// Checks the CRC value of a VAN packet. If not, tries to repair it by flipping each bit.
// Yes, we can sometimes repair a corrupt packet by flipping one or two bits :-)
// Optional parameter 'wantToCount' is a pointer-to-method of class TVanPacketRxDesc, returning a boolean.
// It can be used to limit the repair statistics to take only specific types of packets into account.
//
// Example of invocation:
//
// if (! pkt.CheckCrcAndRepair(&TVanPacketRxDesc::IsSatnavPacket)) return -1; // Unrecoverable CRC error
//
// Note: let's keep the counters sane by calling this only once.
bool TVanPacketRxDesc::CheckCrcAndRepair(bool (TVanPacketRxDesc::*wantToCount)() const)
{
// TODO - if this fixes the packet, VanBusRx.nCorrupt and VanBusRx.nRepaired are not increased
bytes[size - 1] &= 0xFE; // Last bit of last byte (LSB of CRC) is always 0
if (CheckCrc()) return true;
if (uncertainBit1 != NO_UNCERTAIN_BIT)
{
// Flip the bit which is at the position that is marked as "uncertain"
int uncertainAtByte = (uncertainBit1 - 1) >> 3;
int uncertainAtBit = (uncertainBit1 - 1) & 0x07; // 0 = MSB, 7 = LSB
uncertainAtBit = 7 - uncertainAtBit; // 0 = LSB, 7 = MSB
uint8_t uncertainMask = 1 << uncertainAtBit;
bytes[uncertainAtByte] ^= uncertainMask; // Flip
if (CheckCrc())
{
if (wantToCount == 0 || (this->*wantToCount)())
{
VanBusRx.nRepaired++;
VanBusRx.nOneBitErrors++;
VanBusRx.nUncertainBitErrors++;
VanBusRx.nCorrupt++;
} // if
return true;
} // if
bytes[uncertainAtByte] ^= uncertainMask; // Flip back
} // if
// One cycle without the uncertain bit flipped, plus (optionally) one cycle with the uncertain bit flipped
for (int i = 0; i < (uncertainBit1 == NO_UNCERTAIN_BIT ? 1 : 2); i++)
{
int uncertainAtByte;
uint8_t uncertainMask;
// Second cycle?
if (i == 1)
{
// Flip the bit which is at the position that is marked as "uncertain"
uncertainAtByte = (uncertainBit1 - 1) >> 3;
int uncertainAtBit = (uncertainBit1 - 1) & 0x07; // 0 = MSB, 7 = LSB
uncertainAtBit = 7 - uncertainAtBit; // 0 = LSB, 7 = MSB
uncertainMask = 1 << uncertainAtBit;
bytes[uncertainAtByte] ^= uncertainMask; // Flip
} // if
// Byte 0 can be skipped; it does not count for CRC
for (int atByte = 1; atByte < size; atByte++)
{
for (int atBit = 0; atBit < 8; atBit++)
{
uint8_t mask = 1 << atBit;
bytes[atByte] ^= mask; // Flip
// Is there a way to quickly re-calculate the CRC value when bit is flipped?
if (CheckCrc())
{
if (wantToCount == 0 || (this->*wantToCount)())
{
VanBusRx.nRepaired++;
VanBusRx.nOneBitErrors++;
if (i == 1) VanBusRx.nUncertainBitErrors++;
VanBusRx.nCorrupt++;
} // if
return true;
} // if
// Try also to flip the preceding bit
if (atBit != 7)
{
uint8_t mask2 = 1 << (atBit + 1);
bytes[atByte] ^= mask2; // Flip
if (CheckCrc())
{
if (wantToCount == 0 || (this->*wantToCount)())
{
VanBusRx.nRepaired++;
VanBusRx.nTwoConsecutiveBitErrors++;
if (i == 1) VanBusRx.nUncertainBitErrors++;
VanBusRx.nCorrupt++;
} // if
return true;
} // if
bytes[atByte] ^= mask2; // Flip back
}
else // atBit == 7
{
// atByte > 0, so atByte - 1 is safe
bytes[atByte - 1] ^= 1 << 0; // Flip
if (CheckCrc())
{
if (wantToCount == 0 || (this->*wantToCount)())
{
VanBusRx.nRepaired++;
VanBusRx.nTwoConsecutiveBitErrors++;
if (i == 1) VanBusRx.nUncertainBitErrors++;
VanBusRx.nCorrupt++;
} // if
return true;
} // if
bytes[atByte - 1] ^= 1 << 0; // Flip back
} // if
bytes[atByte] ^= mask; // Flip back
} // for
} // for
if (i == 1) bytes[uncertainAtByte] ^= uncertainMask; // Flip back
} // for
// Flip two bits. Getting to this point happens very rarely, luckily...
bool prevBit1 = false;
for (int atByte1 = 1; atByte1 < size; atByte1++)
{
// This may take really long...
wdt_reset();
for (int atBit1 = 7; atBit1 >= 0; atBit1--)
{
// Only flip the last bit in a sequence of equal bits; take into account the Manchester bits
uint8_t currMask1 = 1 << atBit1;
bool currBit1 = (bytes[atByte1] & currMask1) != 0;
bool skip1 = prevBit1 != currBit1;
// After bit 4 or bit 0, there was the Manchester bit
if (atBit1 == 4 || atBit1 == 0)
{
prevBit1 = ! currBit1;
}
else
{
prevBit1 = currBit1;
uint8_t nextMask1 = 1 << (atBit1 - 1);
bool nextBit1 = (bytes[atByte1] & nextMask1) != 0;
skip1 = skip1 || (currBit1 == nextBit1);
} // if
if (skip1) continue;
bytes[atByte1] ^= currMask1; // Flip
// Flip second bit
bool prevBit2 = false;
for (int atByte2 = atByte1; atByte2 < size; atByte2++)
{
for (int atBit2 = 7; atBit2 >= 0; atBit2--)
{
// Only flip the last bit in a sequence of equal bits; take into account the Manchester bits
uint8_t currMask2 = 1 << atBit2;
bool currBit2 = (bytes[atByte2] & currMask2) != 0;
bool skip2 = prevBit2 != currBit2;
// After bit 4 or bit 0, there was the Manchester bit
if (atBit2 == 4 || atBit2 == 0)
{
prevBit2 = ! currBit2;
}
else
{
prevBit2 = currBit2;
uint8_t nextMask2 = 1 << (atBit2 - 1);
bool nextBit2 = (bytes[atByte2] & nextMask2) != 0;
skip2 = skip2 || (currBit2 == nextBit2);
} // if
if (skip2) continue;
bytes[atByte2] ^= currMask2; // Flip
if (CheckCrc())
{
if (wantToCount == 0 || (this->*wantToCount)())
{
VanBusRx.nRepaired++;
VanBusRx.nTwoSeparateBitErrors++;
VanBusRx.nCorrupt++;
} // if
return true;
} // if
bytes[atByte2] ^= currMask2; // Flip back
} // for
} // for
bytes[atByte1] ^= currMask1; // Flip back
} // for
} // for
// Flip three equal bits in a row (seen this only once, ever)
for (int atByte = 1; atByte < size; atByte++)
{
const int atBits[] = {7, 6, 3, 2}; // No use to flip around the Manchester bits
for (int i = 0; i < 4; i++)
{
int atBit = atBits[i];
// Guess the compiler will be really good at optimizing this
uint8_t mask = 1 << atBit--;
mask |= 1 << atBit--;
mask |= 1 << atBit;
uint8_t bits = (bytes[atByte] & mask) >> atBit;
// Only proceed if we see three consecutive same bit values
if (bits != 0x00 && bits != 0x07) break;
bytes[atByte] ^= mask; // Flip
if (CheckCrc())
{
if (wantToCount == 0 || (this->*wantToCount)())
{
VanBusRx.nRepaired++;
VanBusRx.nThreeConsecutiveSameBitErrors++;
VanBusRx.nCorrupt++;
} // if
return true;
} // if
bytes[atByte] ^= mask; // Flip back
} // for
} // for
if (wantToCount == 0 || (this->*wantToCount)()) VanBusRx.nCorrupt++;
return false;
} // TVanPacketRxDesc::CheckCrcAndRepair
// Dumps the raw packet bytes to a stream (e.g. 'Serial').
// Optionally specify the last character; default is "\n" (newline).
// If the last character is "\n", will also print the ASCII representation of each byte (if possible).
void TVanPacketRxDesc::DumpRaw(Stream& s, char last) const
{
s.printf("Raw: #%04" PRIu32 " (%*" PRIu16 "/%d) %2d(%2d) ",
seqNo % 10000,
VanBusRx.size > 100 ? 3 : VanBusRx.size > 10 ? 2 : 1,
slot + 1,
VanBusRx.size,
size - 5 < 0 ? 0 : size - 5,
size);
if (size >= 1) s.printf("%02" PRIX8 " ", bytes[0]); // SOF
if (size >= 3) s.printf("%03" PRIX16 " %1" PRIX8 " (%s) ", Iden(), CommandFlags(), CommandFlagsStr());
for (int i = 3; i < size; i++) s.printf("%02" PRIX8 "%c", bytes[i], i == size - 3 ? ':' : i < size - 1 ? '-' : ' ');
s.print(AckStr());
s.print(" ");
s.print(ResultStr());
s.printf(" %04X", Crc());
s.printf(" %s", CheckCrc() ? "CRC_OK" : "CRC_ERROR");
if (uncertainBit1 != NO_UNCERTAIN_BIT) s.printf(" uBit=%d", uncertainBit1);
if (last == '\n')
{
// Print also ASCII character representation of each byte, if possible, otherwise a small center-dot
s.printf("\n%*s", VanBusRx.size > 100 ? 43 : VanBusRx.size > 10 ? 41 : 39, " ");
for (int i = 3; i < size - 2; i++)
{
if (bytes[i] >= 0x20 && bytes[i] <= 0x7E) s.printf("%2c ", bytes[i]); else s.print(" \u00b7 ");
} // for
} // if
s.print(last);
} // TVanPacketRxDesc::DumpRaw
// Normal bit time (8 microseconds), expressed as number of CPU cycles
#define VAN_NORMAL_BIT_TIME_CPU_CYCLES (CPU_CYCLES(667))
inline __attribute__((always_inline)) unsigned int nBits(uint32_t nCycles)
{
return (nCycles + CPU_CYCLES(200)) / VAN_NORMAL_BIT_TIME_CPU_CYCLES;
} // nBits
uint32_t averageOneBitTime = 0;
// Calculate number of bits from a number of elapsed CPU cycles
inline __attribute__((always_inline)) unsigned int nBitsTakingIntoAccountJitter(uint32_t nCycles, uint32_t& jitter)
{
// Here is the heart of the machine; lots of voodoo magic here...
// Theory:
// - VAN bus rate = 125 kbit/sec = 125 000 bits/sec
// 1 bit = 1/125000 = 0.000008 sec = 8.0 usec
// - CPU rate is 80 MHz
// 1 cycle @ 80 MHz = 0.0000000125 sec = 0.0125 usec
// --> So, 1 VAN-bus bit is 8.0 / 0.0125 = 640 cycles
// Sometimes, samples are stretched, because the ISR is called too late: ESP8266 interrupt service latency can
// vary. If that happens, we must compress the "sample time" for the next bit.
// All timing values were found by trial and error
jitter = 0;
if (nCycles < CPU_CYCLES(560))
{
if (nCycles > CPU_CYCLES(112)) jitter = nCycles - CPU_CYCLES(112);
return 0;
} // if
#define ONE_BIT_BOUNDARY CPU_CYCLES(1281)
if (nCycles < ONE_BIT_BOUNDARY)
{
if (nCycles > CPU_CYCLES(712)) jitter = nCycles - CPU_CYCLES(712); // 712 --> 1281 = 569
return 1;
} // if
if (nCycles < CPU_CYCLES(1863))
{
if (nCycles > CPU_CYCLES(1349)) jitter = nCycles - CPU_CYCLES(1349); // 1349 --> 1863 = 514
return 2;
} // if
#define THREE_BIT_BOUNDARY CPU_CYCLES(2500)
if (nCycles < THREE_BIT_BOUNDARY)
{
if (nCycles > CPU_CYCLES(1998)) jitter = nCycles - CPU_CYCLES(1998); // 1998 --> 2500 = 502
return 3;
} // if
if (nCycles < CPU_CYCLES(3166))
{
if (nCycles > CPU_CYCLES(2636)) jitter = nCycles - CPU_CYCLES(2636); // 2636 --> 3166 = 530
return 4;
} // if
if (nCycles < CPU_CYCLES(3819))
{
if (nCycles > CPU_CYCLES(3262)) jitter = nCycles - CPU_CYCLES(3262); // 3262 --> 3819 = 557
return 5;
} // if
// We hardly ever get to this point
if (nCycles < CPU_CYCLES(4468))
{
if (nCycles > CPU_CYCLES(3930)) jitter = nCycles - CPU_CYCLES(3930); // 3930 --> 4468 = 538
return 6;
} // if
const unsigned int _nBits = nBits(nCycles);
if (nCycles > _nBits * VAN_NORMAL_BIT_TIME_CPU_CYCLES) jitter = nCycles - _nBits * VAN_NORMAL_BIT_TIME_CPU_CYCLES;
return _nBits;
} // nBitsTakingIntoAccountJitter
void ICACHE_RAM_ATTR SetTxBitTimer()
{
#ifdef ARDUINO_ARCH_ESP32
timerAlarmDisable(timer);
#else // ! ARDUINO_ARCH_ESP32
timer1_disable();
#endif // ARDUINO_ARCH_ESP32
if (VanBusRx.txTimerIsr)
{
// Turn on the Tx bit timer
#ifdef ARDUINO_ARCH_ESP32
timerAttachInterrupt(timer, VanBusRx.txTimerIsr, true);
timerAlarmWrite(timer, VanBusRx.txTimerTicks, true);
timerAlarmEnable(timer);
#else // ! ARDUINO_ARCH_ESP32
timer1_attachInterrupt(VanBusRx.txTimerIsr);
// Clock to timer (prescaler) is always 80MHz, even F_CPU is 160 MHz
timer1_enable(TIM_DIV16, TIM_EDGE, TIM_LOOP);
timer1_write(VanBusRx.txTimerTicks);
#endif // ARDUINO_ARCH_ESP32
} // if
} // SetTxBitTimer
// If the timeout expires, the packet is VAN_RX_DONE. 'ack' has already been initially set to VAN_NO_ACK,
// and then to VAN_ACK if a new bit was received within the time-out period.
void ICACHE_RAM_ATTR WaitAckIsr()
{
SetTxBitTimer();
NO_INTERRUPTS;
if (VanBusRx._head->state == VAN_RX_WAITING_ACK) VanBusRx._AdvanceHead();
INTERRUPTS;
} // WaitAckIsr
#ifdef ARDUINO_ARCH_ESP32
hw_timer_t * timer = NULL;
portMUX_TYPE mux = portMUX_INITIALIZER_UNLOCKED;
#define EXIT_CRITICAL_ISR portEXIT_CRITICAL_ISR(&mux)
#else // ! ARDUINO_ARCH_ESP32
#define EXIT_CRITICAL_ISR
#endif // ARDUINO_ARCH_ESP32
// Pin level change interrupt handler
void ICACHE_RAM_ATTR RxPinChangeIsr()
{
// Pin levels
// The logic is:
// - if pinLevel == VAN_LOGICAL_HIGH, we've just had a series of VAN_LOGICAL_LOW bits.
// - if pinLevel == VAN_LOGICAL_LOW, we've just had a series of VAN_LOGICAL_HIGH bits.
#ifdef ARDUINO_ARCH_ESP32
#define GPIP(X_) digitalRead(X_)
#endif // ARDUINO_ARCH_ESP32
const int pinLevel = GPIP(VanBusRx.pin);
static int prevPinLevel = VAN_BIT_RECESSIVE;
static bool pinLevelChangedDuringInterruptHandling = false;
// Number of elapsed CPU cycles
static uint32_t prev = 0;
const uint32_t curr = ESP.getCycleCount(); // Store CPU cycle counter value as soon as possible
const uint32_t nCyclesMeasured = curr - prev; // Arithmetic has safe roll-over
prev = curr;
const bool samePinLevel = (pinLevel == prevPinLevel);
// Prevent CPU monopolization by noise on bus
static int noiseCounter = 0;
if (nCyclesMeasured < 510 || samePinLevel)
{
if (++noiseCounter > 30)
{
VanBusRx.Disable();
return;
} // if
}
else
{
noiseCounter = 0;
} // if
// Retrieve context
TVanPacketRxDesc* rxDesc = VanBusRx._head;
const PacketReadState_t state = rxDesc->state;
// Conversion from elapsed CPU cycles to number of bits, including built-up jitter
static uint32_t jitter = 0;
uint32_t nCycles = nCyclesMeasured + jitter;
// Experiment
if (nCyclesMeasured > CPU_CYCLES(600) && nCyclesMeasured < CPU_CYCLES(800))
{
averageOneBitTime = averageOneBitTime == 0 ? CPU_CYCLES(700) : (averageOneBitTime * 99 + nCyclesMeasured + 50) / 100;
} // if
#if 0
if (averageOneBitTime > CPU_CYCLES(660))
{
if (averageOneBitTime < CPU_CYCLES(693))
{
//nCycles = (4 * nCycles + CPU_CYCLES(700) - averageOneBitTime + 2) / 4;
nCycles += CPU_CYCLES(5);
}
else if (averageOneBitTime > CPU_CYCLES(714))
{
nCycles -= CPU_CYCLES(10);
} // if
} // if
#endif
if (state == VAN_RX_VACANT || state == VAN_RX_SEARCHING)
{
// During SOF, timing is slightly different. Timing values were found by trial and error.
#define FOUR_BITS THREE_BIT_BOUNDARY + CPU_CYCLES(10)
if (nCycles > CPU_CYCLES(2284) && nCycles < FOUR_BITS) nCycles = FOUR_BITS;
//else if (nCycles > CPU_CYCLES(600) && nCycles < CPU_CYCLES(800)) nCycles -= CPU_CYCLES(20);
else if (nCycles > CPU_CYCLES(1100) && nCycles < ONE_BIT_BOUNDARY) nCycles -= CPU_CYCLES(20);
}
else
{
// Sometimes, one long bit is in fact two bits
if (jitter < CPU_CYCLES(300))
{
#define MOVE_TOWARDS_TWO_BITS_AT CPU_CYCLES(1235)
#define MOVE_TOWARDS_TWO_BITS ONE_BIT_BOUNDARY - MOVE_TOWARDS_TWO_BITS_AT
if (nCyclesMeasured > CPU_CYCLES(987) && nCyclesMeasured < ONE_BIT_BOUNDARY && nCycles >= CPU_CYCLES(1220))
{
nCycles += MOVE_TOWARDS_TWO_BITS;
} // if
}
else if (jitter < CPU_CYCLES(400))
{
if (nCyclesMeasured > CPU_CYCLES(900) && nCyclesMeasured < CPU_CYCLES(988))
{
nCycles += CPU_CYCLES(22);
} // if
} // if
} // if
const uint32_t prevJitter = jitter;
unsigned int nBits = nBitsTakingIntoAccountJitter(nCycles, jitter);
// Experiment
#define SMALLEST_JITTER CPU_CYCLES(20)
if (jitter < SMALLEST_JITTER)
{
jitter = 0;
}
else if (jitter <= CPU_CYCLES(200))
{
#define SMALL_JITTER_RUNDOWN SMALLEST_JITTER
if (jitter > prevJitter - CPU_CYCLES(15) && jitter < prevJitter + CPU_CYCLES(18)) jitter -= SMALL_JITTER_RUNDOWN;
}
else
{
#define LARGE_JITTER_RUNDOWN CPU_CYCLES(30)
if (jitter > prevJitter - CPU_CYCLES(30) && jitter < prevJitter + CPU_CYCLES(5)) jitter -= LARGE_JITTER_RUNDOWN;
} // if
#ifdef VAN_RX_ISR_DEBUGGING
// Record some data to be used for debugging outside this ISR
TIsrDebugPacket* isrDebugPacket = rxDesc->isrDebugPacket;
isrDebugPacket->slot = rxDesc->slot;
TIsrDebugData* debugIsr =
isrDebugPacket->at < VAN_ISR_DEBUG_BUFFER_SIZE ?
isrDebugPacket->samples + isrDebugPacket->at :
NULL;
// Only write into sample buffer if there is space
if (debugIsr != NULL)
{
debugIsr->nCyclesMeasured = _min(nCyclesMeasured / CPU_F_FACTOR, USHRT_MAX);
debugIsr->fromJitter = _min(prevJitter / CPU_F_FACTOR, (1 << 10) - 1);
debugIsr->nBits = _min(nBits, UCHAR_MAX);
debugIsr->prevPinLevel = prevPinLevel;
debugIsr->pinLevel = pinLevel;
debugIsr->fromState = state;
debugIsr->readBits = 0;
} // if
// Macros useful for debugging
// Just before returning from this ISR, record the pin level, plus some data for debugging
#define RETURN \
{ \
const int pinLevelAtReturnFromIsr = GPIP(VanBusRx.pin); \
pinLevelChangedDuringInterruptHandling = jitter < CPU_CYCLES(100) && pinLevelAtReturnFromIsr != pinLevel; \
\
if (debugIsr != NULL) \
{ \
debugIsr->toJitter = _min(jitter / CPU_F_FACTOR, (1 << 10) - 1); \
debugIsr->flipBits = flipBits; \
debugIsr->toState = rxDesc->state; \
debugIsr->pinLevelAtReturnFromIsr = pinLevelAtReturnFromIsr; \
debugIsr->atBit = atBit; \
isrDebugPacket->at++; \
} \
EXIT_CRITICAL_ISR; \
return; \
}
#define DEBUG_ISR(TO_, FROM_) if (debugIsr != NULL) debugIsr->TO_ = (FROM_);
#define DEBUG_ISR_M(TO_, FROM_, MAX_) if (debugIsr != NULL) debugIsr->TO_ = _min((FROM_), (MAX_));
#else
// Just before returning from this ISR, record the pin level
#define RETURN \
{ \
const int pinLevelAtReturnFromIsr = GPIP(VanBusRx.pin); \
pinLevelChangedDuringInterruptHandling = jitter < CPU_CYCLES(100) && pinLevelAtReturnFromIsr != pinLevel; \
EXIT_CRITICAL_ISR; \
return; \
}
#define DEBUG_ISR(TO_, FROM_)
#define DEBUG_ISR_M(TO_, FROM_, MAX_)
#endif // VAN_RX_ISR_DEBUGGING
prevPinLevel = pinLevel;
uint16_t flipBits = 0;
#ifdef ARDUINO_ARCH_ESP32
portENTER_CRITICAL_ISR(&mux);
#endif // ARDUINO_ARCH_ESP32
// Media access detection for packet transmission
if (pinLevel == VAN_BIT_RECESSIVE)
{
// Pin level just changed to 'recessive', so that was the end of the media access ('dominant')
VanBusRx.lastMediaAccessAt = curr;
} // if
static unsigned int atBit = 0;
static uint16_t readBits = 0;
#ifdef VAN_RX_IFS_DEBUGGING
TIfsDebugPacket* ifsDebugPacket = &rxDesc->ifsDebugPacket;
TIfsDebugData* debugIfs =
ifsDebugPacket->at < VAN_IFS_DEBUG_BUFFER_SIZE ?
ifsDebugPacket->samples + ifsDebugPacket->at :
NULL;
if (state == VAN_RX_VACANT || state == VAN_RX_SEARCHING)
{
// Only write into sample buffer if there is space
if (debugIfs != NULL)
{
debugIfs->nCyclesMeasured = _min(nCyclesMeasured / CPU_F_FACTOR, USHRT_MAX);
debugIfs->nBits = _min(nBits, UCHAR_MAX);
debugIfs->pinLevel = pinLevel;
debugIfs->fromState = state;
debugIfs->toState = state; // Can be overwritten later
ifsDebugPacket->at++;
} // if
} // if
// Macro useful for debugging
#define DEBUG_IFS(TO_, FROM_) if (debugIfs != NULL) debugIfs->TO_ = (FROM_);
#else
#define DEBUG_IFS(TO, FROM)
#endif // VAN_RX_IFS_DEBUGGING
if (state == VAN_RX_WAITING_ACK)
{
if (
// If another bit came after the "ACK", it is not an "ACK" but the first "1" bit of the next byte
(rxDesc->ack == VAN_ACK && pinLevel == VAN_LOGICAL_LOW)
// If the "ACK" came too soon or lasted more than 1 time slot, it is not an "ACK" but the first
// "1" bit of the next byte
|| pinLevelChangedDuringInterruptHandling
|| nCycles < CPU_CYCLES(650)
|| nCycles > CPU_CYCLES(1000)
)
{
#ifdef ARDUINO_ARCH_ESP32
timerAlarmDisable(timer);
#else // ! ARDUINO_ARCH_ESP32
timer1_disable();
#endif // ARDUINO_ARCH_ESP32
// Go back to state VAN_RX_LOADING
rxDesc->state = VAN_RX_LOADING;
DEBUG_IFS(toState, VAN_RX_LOADING);
rxDesc->ack = VAN_NO_ACK;
}
else
{
// TODO - move (under condition) into timer ISR 'WaitAckIsr'?
rxDesc->ack = VAN_ACK;
// The timer ISR 'WaitAckIsr' will call 'VanBusRx._AdvanceHead()'
} // if
} // if
if (state == VAN_RX_VACANT)
{
readBits = 0;
if (pinLevel == VAN_LOGICAL_LOW)
{
// Normal detection: we've seen a series of VAN_LOGICAL_HIGH bits
rxDesc->state = VAN_RX_SEARCHING;
DEBUG_IFS(toState, VAN_RX_SEARCHING);
if (nBits == 7 || nBits == 8) atBit = nBits; else atBit = 0;
jitter = 0;
pinLevelChangedDuringInterruptHandling = false;
}
else if (pinLevel == VAN_LOGICAL_HIGH)
{
if (nBits >= 2 && nBits <= 8)
{
// Late detection
rxDesc->state = VAN_RX_SEARCHING;
DEBUG_IFS(toState, VAN_RX_SEARCHING);
atBit = nBits;
if (nBits > 5) jitter = 0;
} // if
} // if
RETURN;
} // if
// If the current head packet is already VAN_RX_DONE, the circular buffer is completely full
if (state == VAN_RX_DONE)
{
VanBusRx._overrun = true;
RETURN;
} // if
// During packet reception, the "Enhanced Manchester" encoding guarantees at most 5 bits are the same,
// except during EOD when it can be 6.
// However, sometimes the Manchester bit is missed. Let's be tolerant with that, and just pretend it
// was there, by accepting up to 10 equal bits.
if (nBits > 10)
{
jitter = 0;
if (state == VAN_RX_SEARCHING)
{
readBits = 0;
atBit = 0;
rxDesc->size = 0;
RETURN;
} // if
if (atBit == 9)
{
uint16_t currentByte = readBits << 1;
uint8_t readByte = (currentByte >> 2 & 0xF0) | (currentByte >> 1 & 0x0F);
rxDesc->bytes[rxDesc->size++] = readByte;
}
else
{
rxDesc->result = VAN_RX_ERROR_NBITS;
} // if
VanBusRx._AdvanceHead();
RETURN;
} // if
// Experimental handling of special situations caused by a missed interrupt or a very late ISR invocation.
// All cases were found by trial and error.
if (nBits == 0)
{
if (state == VAN_RX_SEARCHING)
{
nBits = 1;
DEBUG_ISR(nBits, 1);
jitter = 0;
}
else if (atBit > 0)
{
const uint16_t prev = readBits;
// Set or clear the last read bit
readBits = pinLevel == VAN_LOGICAL_LOW ? readBits | 0x0001 : readBits & 0xFFFE;
// If last bit was actually flipped, reset jitter
//if (atBit > 0 && prev != readBits) jitter = 0;
if (prev != readBits) jitter -= _min(jitter, CPU_CYCLES(157U));
} // if
}
else if (samePinLevel)
{
if (nBits == 1)
{
flipBits = 0x0001;
}
else if (nBits == 2)
{
// Flip the last 'nBits' except the very last bit, e.g. flip the bits -- ---- --X-
flipBits = 0x0002;
}
else if (nBits > 2)
{
// Flip the last 'nBits' except the very last bit, e.g. if nBits == 4 ==> flip the bits -- ---- XXX-
flipBits = (1 << nBits) - 1 - 1;
// If the interrupt was so late that the pin level has already changed again, then flip also the very
// last bit
if (jitter > CPU_CYCLES(280)) flipBits |= 0x0001;
} // if
if ((flipBits & 0x0001) == 0x0001) prevPinLevel = 2; // next ISR, samePinLevel must always be false.
} // if
readBits <<= nBits;
atBit += nBits;
// Calculate the position of the last received bit (in order of reception: MSB first)
int bitPosition = rxDesc->size * 8 + atBit;
// Count only the "real" bits, not the Manchester bits
if (atBit > 4) bitPosition--;
if (atBit > 9) bitPosition--;
if (pinLevel == VAN_LOGICAL_LOW)
{
// Just had a series of VAN_LOGICAL_HIGH bits
uint16_t pattern = (1 << nBits) - 1;
readBits |= pattern;
} // if
if (flipBits == 0 && nBits == 3 && (atBit == 5 || atBit == 10) && rxDesc->uncertainBit1 == NO_UNCERTAIN_BIT)
{
// 4-th or 8-th bit same as Manchester bit? Then mark that bit position as candidate for
// later repair by the CheckCrcAndRepair(...) method.
rxDesc->uncertainBit1 = bitPosition; // Position 1 = MSB, bit 8 = LSB
} // if
if (flipBits != 0)
{
readBits ^= flipBits;
if (nBits > 1 && rxDesc->uncertainBit1 == NO_UNCERTAIN_BIT)
{
// The last bit is very uncertain: mark the bit position as candidate for later repair by the