forked from dronecan/libcanard
-
Notifications
You must be signed in to change notification settings - Fork 0
/
canard.c
1890 lines (1658 loc) · 59.1 KB
/
canard.c
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
/*
* Copyright (c) 2016-2019 UAVCAN Team
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
* Contributors: https://github.com/UAVCAN/libcanard/contributors
*
* Documentation: http://uavcan.org/Implementations/Libcanard
*/
#include "canard_internals.h"
#include <string.h>
#undef MIN
#undef MAX
#define MIN(a, b) (((a) < (b)) ? (a) : (b))
#define MAX(a, b) (((a) > (b)) ? (a) : (b))
#define TRANSFER_TIMEOUT_USEC 2000000U
#define IFACE_SWITCH_DELAY_USEC 1000000U
#define TRANSFER_ID_BIT_LEN 5U
#define ANON_MSG_DATA_TYPE_ID_BIT_LEN 2U
#define SOURCE_ID_FROM_ID(x) ((uint8_t) (((x) >> 0U) & 0x7FU))
#define SERVICE_NOT_MSG_FROM_ID(x) ((bool) (((x) >> 7U) & 0x1U))
#define REQUEST_NOT_RESPONSE_FROM_ID(x) ((bool) (((x) >> 15U) & 0x1U))
#define DEST_ID_FROM_ID(x) ((uint8_t) (((x) >> 8U) & 0x7FU))
#define PRIORITY_FROM_ID(x) ((uint8_t) (((x) >> 24U) & 0x1FU))
#define MSG_TYPE_FROM_ID(x) ((uint16_t)(((x) >> 8U) & 0xFFFFU))
#define SRV_TYPE_FROM_ID(x) ((uint8_t) (((x) >> 16U) & 0xFFU))
#define MAKE_TRANSFER_DESCRIPTOR(data_type_id, transfer_type, src_node_id, dst_node_id) \
(((uint32_t)(data_type_id)) | (((uint32_t)(transfer_type)) << 16U) | \
(((uint32_t)(src_node_id)) << 18U) | (((uint32_t)(dst_node_id)) << 25U))
#define TRANSFER_ID_FROM_TAIL_BYTE(x) ((uint8_t)((x) & 0x1FU))
// The extra cast to unsigned is needed to squelch warnings from clang-tidy
#define IS_START_OF_TRANSFER(x) ((bool)(((uint32_t)(x) >> 7U) & 0x1U))
#define IS_END_OF_TRANSFER(x) ((bool)(((uint32_t)(x) >> 6U) & 0x1U))
#define TOGGLE_BIT(x) ((bool)(((uint32_t)(x) >> 5U) & 0x1U))
/*
* API functions
*/
void canardInit(CanardInstance* out_ins,
void* mem_arena,
size_t mem_arena_size,
CanardOnTransferReception on_reception,
CanardShouldAcceptTransfer should_accept,
void* user_reference)
{
CANARD_ASSERT(out_ins != NULL);
/*
* Checking memory layout.
* This condition is supposed to be true for all 32-bit and smaller platforms.
* If your application fails here, make sure it's not built in 64-bit mode.
* Refer to the design documentation for more info.
*/
CANARD_ASSERT(CANARD_MULTIFRAME_RX_PAYLOAD_HEAD_SIZE >= 5);
memset(out_ins, 0, sizeof(*out_ins));
out_ins->node_id = CANARD_BROADCAST_NODE_ID;
out_ins->on_reception = on_reception;
out_ins->should_accept = should_accept;
out_ins->rx_states = NULL;
out_ins->tx_queue = NULL;
out_ins->user_reference = user_reference;
#if CANARD_ENABLE_TAO_OPTION
out_ins->tao_disabled = false;
#endif
size_t pool_capacity = mem_arena_size / CANARD_MEM_BLOCK_SIZE;
if (pool_capacity > 0xFFFFU)
{
pool_capacity = 0xFFFFU;
}
initPoolAllocator(&out_ins->allocator, mem_arena, (uint16_t)pool_capacity);
}
void* canardGetUserReference(CanardInstance* ins)
{
CANARD_ASSERT(ins != NULL);
return ins->user_reference;
}
void canardSetLocalNodeID(CanardInstance* ins, uint8_t self_node_id)
{
CANARD_ASSERT(ins != NULL);
if ((ins->node_id == CANARD_BROADCAST_NODE_ID) &&
(self_node_id >= CANARD_MIN_NODE_ID) &&
(self_node_id <= CANARD_MAX_NODE_ID))
{
ins->node_id = self_node_id;
}
else
{
CANARD_ASSERT(false);
}
}
uint8_t canardGetLocalNodeID(const CanardInstance* ins)
{
return ins->node_id;
}
void canardForgetLocalNodeID(CanardInstance* ins) {
ins->node_id = CANARD_BROADCAST_NODE_ID;
}
void canardInitTxTransfer(CanardTxTransfer* transfer)
{
CANARD_ASSERT(transfer != NULL);
memset(transfer, 0, sizeof(*transfer));
}
int16_t canardBroadcast(CanardInstance* ins,
uint64_t data_type_signature,
uint16_t data_type_id,
uint8_t* inout_transfer_id,
uint8_t priority,
const void* payload,
uint16_t payload_len
#if CANARD_ENABLE_DEADLINE
,uint64_t tx_deadline
#endif
#if CANARD_MULTI_IFACE
,uint8_t iface_mask
#endif
#if CANARD_ENABLE_CANFD
,bool canfd
#endif
)
{
// create transfer object
CanardTxTransfer transfer_object = {
.data_type_signature = data_type_signature,
.data_type_id = data_type_id,
.inout_transfer_id = inout_transfer_id,
.priority = priority,
.payload = (uint8_t*)payload,
.payload_len = payload_len,
#if CANARD_ENABLE_DEADLINE
.deadline_usec = tx_deadline,
#endif
#if CANARD_MULTI_IFACE
.iface_mask = iface_mask,
#endif
#if CANARD_ENABLE_CANFD
.canfd = canfd,
#endif
};
return canardBroadcastObj(ins, &transfer_object);
}
int16_t canardBroadcastObj(CanardInstance* ins, CanardTxTransfer* transfer_object)
{
if (transfer_object->payload == NULL && transfer_object->payload_len > 0)
{
return -CANARD_ERROR_INVALID_ARGUMENT;
}
if (transfer_object->priority > CANARD_TRANSFER_PRIORITY_LOWEST)
{
return -CANARD_ERROR_INVALID_ARGUMENT;
}
uint32_t can_id = 0;
uint16_t crc = 0xFFFFU;
if (canardGetLocalNodeID(ins) == 0)
{
if (transfer_object->payload_len > 7)
{
return -CANARD_ERROR_NODE_ID_NOT_SET;
}
static const uint16_t DTIDMask = (1U << ANON_MSG_DATA_TYPE_ID_BIT_LEN) - 1U;
if ((transfer_object->data_type_id & DTIDMask) != transfer_object->data_type_id)
{
return -CANARD_ERROR_INVALID_ARGUMENT;
}
// anonymous transfer, random discriminator
const uint16_t discriminator = (uint16_t)((crcAdd(0xFFFFU, transfer_object->payload, transfer_object->payload_len)) & 0x7FFEU);
can_id = ((uint32_t) transfer_object->priority << 24U) | ((uint32_t) discriminator << 9U) |
((uint32_t) (transfer_object->data_type_id & DTIDMask) << 8U) | (uint32_t) canardGetLocalNodeID(ins);
}
else
{
can_id = ((uint32_t) transfer_object->priority << 24U) | ((uint32_t) transfer_object->data_type_id << 8U) | (uint32_t) canardGetLocalNodeID(ins);
crc = calculateCRC(transfer_object);
}
const int16_t result = enqueueTxFrames(ins, can_id, crc, transfer_object);
if (result > 0) {
incrementTransferID(transfer_object->inout_transfer_id);
}
return result;
}
/*
the following FromIdx and ToIdx functions allow for the
CanardBufferBlock and CanartRxState structures to have the same size
on 32 bit and 64 bit platforms, which allows for easier testing in
simulator environments
*/
CANARD_INTERNAL CanardBufferBlock *canardBufferFromIdx(CanardPoolAllocator* allocator, canard_buffer_idx_t idx)
{
#if CANARD_64_BIT
if (idx == CANARD_BUFFER_IDX_NONE) {
return NULL;
}
return (CanardBufferBlock *)(uintptr_t)&((uint8_t *)allocator->arena)[idx-1];
#else
(void)allocator;
return (CanardBufferBlock *)idx;
#endif
}
CANARD_INTERNAL canard_buffer_idx_t canardBufferToIdx(CanardPoolAllocator* allocator, const CanardBufferBlock *buf)
{
#if CANARD_64_BIT
if (buf == NULL) {
return CANARD_BUFFER_IDX_NONE;
}
return 1U+((canard_buffer_idx_t)((uint8_t *)buf - (uint8_t *)allocator->arena));
#else
(void)allocator;
return (canard_buffer_idx_t)buf;
#endif
}
CANARD_INTERNAL CanardRxState *canardRxFromIdx(CanardPoolAllocator* allocator, canard_buffer_idx_t idx)
{
#if CANARD_64_BIT
if (idx == CANARD_BUFFER_IDX_NONE) {
return NULL;
}
return (CanardRxState *)(uintptr_t)&((uint8_t *)allocator->arena)[idx-1];
#else
(void)allocator;
return (CanardRxState *)idx;
#endif
}
CANARD_INTERNAL canard_buffer_idx_t canardRxToIdx(CanardPoolAllocator* allocator, const CanardRxState *rx)
{
#if CANARD_64_BIT
if (rx == NULL) {
return CANARD_BUFFER_IDX_NONE;
}
return 1U+((canard_buffer_idx_t)((uint8_t *)rx - (uint8_t *)allocator->arena));
#else
(void)allocator;
return (canard_buffer_idx_t)rx;
#endif
}
CANARD_INTERNAL uint16_t calculateCRC(const CanardTxTransfer* transfer_object)
{
uint16_t crc = 0xFFFFU;
#if CANARD_ENABLE_CANFD
if ((transfer_object->payload_len > 7 && !transfer_object->canfd) ||
(transfer_object->payload_len > 63 && transfer_object->canfd))
#else
if (transfer_object->payload_len > 7)
#endif
{
crc = crcAddSignature(crc, transfer_object->data_type_signature);
crc = crcAdd(crc, transfer_object->payload, transfer_object->payload_len);
#if CANARD_ENABLE_CANFD
if (transfer_object->payload_len > 63 && transfer_object->canfd) {
uint8_t empty = 0;
uint8_t padding = (uint8_t)dlcToDataLength(dataLengthToDlc((uint16_t)((transfer_object->payload_len+2) % 63)+1))-1;
padding -= (uint8_t)((transfer_object->payload_len+2) % 63);
for (uint8_t i=0; i<padding; i++) {
crc = crcAddByte(crc, empty);
}
}
#endif
}
return crc;
}
int16_t canardRequestOrRespond(CanardInstance* ins,
uint8_t destination_node_id,
uint64_t data_type_signature,
uint8_t data_type_id,
uint8_t* inout_transfer_id,
uint8_t priority,
CanardRequestResponse kind,
const void* payload,
uint16_t payload_len
#if CANARD_ENABLE_DEADLINE
,uint64_t tx_deadline
#endif
#if CANARD_MULTI_IFACE
,uint8_t iface_mask
#endif
#if CANARD_ENABLE_CANFD
,bool canfd
#endif
)
{
CanardTxTransfer transfer_object = {
.data_type_signature = data_type_signature,
.data_type_id = data_type_id,
.inout_transfer_id = inout_transfer_id,
.priority = priority,
.transfer_type = kind == CanardRequest ? CanardTransferTypeRequest : CanardTransferTypeResponse,
.payload = payload,
.payload_len = payload_len,
#if CANARD_ENABLE_DEADLINE
.deadline_usec = tx_deadline,
#endif
#if CANARD_MULTI_IFACE
.iface_mask = iface_mask,
#endif
#if CANARD_ENABLE_CANFD
.canfd = canfd,
#endif
};
return canardRequestOrRespondObj(ins, destination_node_id, &transfer_object);
}
int16_t canardRequestOrRespondObj(CanardInstance* ins, uint8_t destination_node_id, CanardTxTransfer* transfer_object)
{
if (transfer_object->payload == NULL && transfer_object->payload_len > 0)
{
return -CANARD_ERROR_INVALID_ARGUMENT;
}
if (transfer_object->priority > CANARD_TRANSFER_PRIORITY_LOWEST)
{
return -CANARD_ERROR_INVALID_ARGUMENT;
}
if (canardGetLocalNodeID(ins) == 0)
{
return -CANARD_ERROR_NODE_ID_NOT_SET;
}
const uint32_t can_id = ((uint32_t) transfer_object->priority << 24U) | ((uint32_t) transfer_object->data_type_id << 16U) |
((uint32_t) transfer_object->transfer_type << 15U) | ((uint32_t) destination_node_id << 8U) |
(1U << 7U) | (uint32_t) canardGetLocalNodeID(ins);
uint16_t crc = calculateCRC(transfer_object);
const int16_t result = enqueueTxFrames(ins, can_id, crc, transfer_object);
if (result > 0 && transfer_object->transfer_type == CanardTransferTypeRequest) // Response Transfer ID must not be altered
{
incrementTransferID(transfer_object->inout_transfer_id);
}
return result;
}
CanardCANFrame* canardPeekTxQueue(const CanardInstance* ins)
{
if (ins->tx_queue == NULL)
{
return NULL;
}
return &ins->tx_queue->frame;
}
void canardPopTxQueue(CanardInstance* ins)
{
CanardTxQueueItem* item = ins->tx_queue;
ins->tx_queue = item->next;
freeBlock(&ins->allocator, item);
}
int16_t canardHandleRxFrame(CanardInstance* ins, const CanardCANFrame* frame, uint64_t timestamp_usec)
{
const CanardTransferType transfer_type = extractTransferType(frame->id);
const uint8_t destination_node_id = (transfer_type == CanardTransferTypeBroadcast) ?
(uint8_t)CANARD_BROADCAST_NODE_ID :
DEST_ID_FROM_ID(frame->id);
// TODO: This function should maintain statistics of transfer errors and such.
if ((frame->id & CANARD_CAN_FRAME_EFF) == 0 ||
(frame->id & CANARD_CAN_FRAME_RTR) != 0 ||
(frame->id & CANARD_CAN_FRAME_ERR) != 0 ||
(frame->data_len < 1))
{
return -CANARD_ERROR_RX_INCOMPATIBLE_PACKET;
}
if (transfer_type != CanardTransferTypeBroadcast &&
destination_node_id != canardGetLocalNodeID(ins))
{
return -CANARD_ERROR_RX_WRONG_ADDRESS;
}
const uint8_t priority = PRIORITY_FROM_ID(frame->id);
const uint8_t source_node_id = SOURCE_ID_FROM_ID(frame->id);
const uint16_t data_type_id = extractDataType(frame->id);
const uint32_t transfer_descriptor =
MAKE_TRANSFER_DESCRIPTOR(data_type_id, transfer_type, source_node_id, destination_node_id);
const uint8_t tail_byte = frame->data[frame->data_len - 1];
uint64_t data_type_signature = 0;
CanardRxState* rx_state = NULL;
if (IS_START_OF_TRANSFER(tail_byte))
{
if (ins->should_accept(ins, &data_type_signature, data_type_id, transfer_type, source_node_id))
{
rx_state = traverseRxStates(ins, transfer_descriptor);
if(rx_state == NULL)
{
return -CANARD_ERROR_OUT_OF_MEMORY;
}
}
else
{
return -CANARD_ERROR_RX_NOT_WANTED;
}
}
else
{
rx_state = findRxState(ins, transfer_descriptor);
if (rx_state == NULL)
{
return -CANARD_ERROR_RX_MISSED_START;
}
}
CANARD_ASSERT(rx_state != NULL); // All paths that lead to NULL should be terminated with return above
// Resolving the state flags:
const bool not_initialized = rx_state->timestamp_usec == 0;
const bool tid_timed_out = (timestamp_usec - rx_state->timestamp_usec) > TRANSFER_TIMEOUT_USEC;
const bool same_iface = frame->iface_id == rx_state->iface_id;
const bool first_frame = IS_START_OF_TRANSFER(tail_byte);
const bool not_previous_tid =
computeTransferIDForwardDistance((uint8_t) rx_state->transfer_id, TRANSFER_ID_FROM_TAIL_BYTE(tail_byte)) > 1;
const bool iface_switch_allowed = (timestamp_usec - rx_state->timestamp_usec) > IFACE_SWITCH_DELAY_USEC;
const bool non_wrapped_tid = computeTransferIDForwardDistance(TRANSFER_ID_FROM_TAIL_BYTE(tail_byte), (uint8_t) rx_state->transfer_id) < (1 << (TRANSFER_ID_BIT_LEN-1));
const bool incomplete_frame = rx_state->buffer_blocks != CANARD_BUFFER_IDX_NONE;
const bool need_restart =
(not_initialized) ||
(tid_timed_out) ||
(same_iface && first_frame && (not_previous_tid || incomplete_frame)) ||
(iface_switch_allowed && first_frame && non_wrapped_tid);
if (need_restart)
{
rx_state->transfer_id = TRANSFER_ID_FROM_TAIL_BYTE(tail_byte);
rx_state->next_toggle = 0;
releaseStatePayload(ins, rx_state);
rx_state->iface_id = frame->iface_id;
if (!IS_START_OF_TRANSFER(tail_byte))
{
rx_state->transfer_id++;
return -CANARD_ERROR_RX_MISSED_START;
}
}
if (frame->iface_id != rx_state->iface_id)
{
// drop frame if coming from unexpected interface
return CANARD_OK;
}
if (IS_START_OF_TRANSFER(tail_byte) && IS_END_OF_TRANSFER(tail_byte)) // single frame transfer
{
rx_state->timestamp_usec = timestamp_usec;
CanardRxTransfer rx_transfer = {
.timestamp_usec = timestamp_usec,
.payload_head = frame->data,
.payload_len = (uint8_t)(frame->data_len - 1U),
.data_type_id = data_type_id,
.transfer_type = (uint8_t)transfer_type,
.transfer_id = TRANSFER_ID_FROM_TAIL_BYTE(tail_byte),
.priority = priority,
.source_node_id = source_node_id,
#if CANARD_ENABLE_CANFD
.canfd = frame->canfd,
.tao = !(frame->canfd || ins->tao_disabled)
#elif CANARD_ENABLE_TAO_OPTION
.tao = !ins->tao_disabled
#endif
};
ins->on_reception(ins, &rx_transfer);
prepareForNextTransfer(rx_state);
return CANARD_OK;
}
if (TOGGLE_BIT(tail_byte) != rx_state->next_toggle)
{
return -CANARD_ERROR_RX_WRONG_TOGGLE;
}
if (TRANSFER_ID_FROM_TAIL_BYTE(tail_byte) != rx_state->transfer_id)
{
return -CANARD_ERROR_RX_UNEXPECTED_TID;
}
if (IS_START_OF_TRANSFER(tail_byte) && !IS_END_OF_TRANSFER(tail_byte)) // Beginning of multi frame transfer
{
if (frame->data_len <= 3)
{
return -CANARD_ERROR_RX_SHORT_FRAME;
}
// take off the crc and store the payload
rx_state->timestamp_usec = timestamp_usec;
const int16_t ret = bufferBlockPushBytes(&ins->allocator, rx_state, frame->data + 2,
(uint8_t) (frame->data_len - 3));
if (ret < 0)
{
releaseStatePayload(ins, rx_state);
prepareForNextTransfer(rx_state);
return -CANARD_ERROR_OUT_OF_MEMORY;
}
rx_state->payload_crc = (uint16_t)(((uint16_t) frame->data[0]) | (uint16_t)((uint16_t) frame->data[1] << 8U));
rx_state->calculated_crc = crcAddSignature(0xFFFFU, data_type_signature);
rx_state->calculated_crc = crcAdd((uint16_t)rx_state->calculated_crc,
frame->data + 2, (uint8_t)(frame->data_len - 3));
}
else if (!IS_START_OF_TRANSFER(tail_byte) && !IS_END_OF_TRANSFER(tail_byte)) // Middle of a multi-frame transfer
{
const int16_t ret = bufferBlockPushBytes(&ins->allocator, rx_state, frame->data,
(uint8_t) (frame->data_len - 1));
if (ret < 0)
{
releaseStatePayload(ins, rx_state);
prepareForNextTransfer(rx_state);
return -CANARD_ERROR_OUT_OF_MEMORY;
}
rx_state->calculated_crc = crcAdd((uint16_t)rx_state->calculated_crc,
frame->data, (uint8_t)(frame->data_len - 1));
}
else // End of a multi-frame transfer
{
const uint8_t frame_payload_size = (uint8_t)(frame->data_len - 1);
uint8_t tail_offset = 0;
if (rx_state->payload_len < CANARD_MULTIFRAME_RX_PAYLOAD_HEAD_SIZE)
{
// Copy the beginning of the frame into the head, point the tail pointer to the remainder
for (size_t i = rx_state->payload_len;
(i < CANARD_MULTIFRAME_RX_PAYLOAD_HEAD_SIZE) && (tail_offset < frame_payload_size);
i++, tail_offset++)
{
rx_state->buffer_head[i] = frame->data[tail_offset];
}
}
else
{
// Like above, except that the beginning goes into the last block of the storage
CanardBufferBlock* block = canardBufferFromIdx(&ins->allocator, rx_state->buffer_blocks);
if (block != NULL)
{
size_t offset = CANARD_MULTIFRAME_RX_PAYLOAD_HEAD_SIZE; // Payload offset of the first block
while (block->next != NULL)
{
block = block->next;
offset += CANARD_BUFFER_BLOCK_DATA_SIZE;
}
CANARD_ASSERT(block != NULL);
const size_t offset_within_block = rx_state->payload_len - offset;
CANARD_ASSERT(offset_within_block <= CANARD_BUFFER_BLOCK_DATA_SIZE);
for (size_t i = offset_within_block;
(i < CANARD_BUFFER_BLOCK_DATA_SIZE) && (tail_offset < frame_payload_size);
i++, tail_offset++)
{
block->data[i] = frame->data[tail_offset];
}
}
}
CanardRxTransfer rx_transfer = {
.timestamp_usec = timestamp_usec,
.payload_head = rx_state->buffer_head,
.payload_middle = canardBufferFromIdx(&ins->allocator, rx_state->buffer_blocks),
.payload_tail = (tail_offset >= frame_payload_size) ? NULL : (&frame->data[tail_offset]),
.payload_len = (uint16_t)(rx_state->payload_len + frame_payload_size),
.data_type_id = data_type_id,
.transfer_type = (uint8_t)transfer_type,
.transfer_id = TRANSFER_ID_FROM_TAIL_BYTE(tail_byte),
.priority = priority,
.source_node_id = source_node_id,
#if CANARD_ENABLE_CANFD
.canfd = frame->canfd,
.tao = !(frame->canfd || ins->tao_disabled)
#elif CANARD_ENABLE_TAO_OPTION
.tao = !ins->tao_disabled
#endif
};
rx_state->buffer_blocks = CANARD_BUFFER_IDX_NONE; // Block list ownership has been transferred to rx_transfer!
// CRC validation
rx_state->calculated_crc = crcAdd((uint16_t)rx_state->calculated_crc, frame->data, frame->data_len - 1U);
if (rx_state->calculated_crc == rx_state->payload_crc)
{
ins->on_reception(ins, &rx_transfer);
}
// Making sure the payload is released even if the application didn't bother with it
canardReleaseRxTransferPayload(ins, &rx_transfer);
prepareForNextTransfer(rx_state);
if (rx_state->calculated_crc == rx_state->payload_crc)
{
return CANARD_OK;
}
else
{
return -CANARD_ERROR_RX_BAD_CRC;
}
}
rx_state->next_toggle = rx_state->next_toggle ? 0 : 1;
return CANARD_OK;
}
void canardCleanupStaleTransfers(CanardInstance* ins, uint64_t current_time_usec)
{
CanardRxState* prev = ins->rx_states, * state = ins->rx_states;
while (state != NULL)
{
if ((current_time_usec - state->timestamp_usec) > TRANSFER_TIMEOUT_USEC)
{
if (state == ins->rx_states)
{
releaseStatePayload(ins, state);
ins->rx_states = canardRxFromIdx(&ins->allocator, ins->rx_states->next);
freeBlock(&ins->allocator, state);
state = ins->rx_states;
prev = state;
}
else
{
releaseStatePayload(ins, state);
prev->next = state->next;
freeBlock(&ins->allocator, state);
state = canardRxFromIdx(&ins->allocator, prev->next);
}
}
else
{
prev = state;
state = canardRxFromIdx(&ins->allocator, state->next);
}
}
#if CANARD_MULTI_IFACE || CANARD_ENABLE_DEADLINE
// remove stale TX transfers
CanardTxQueueItem* prev_item = ins->tx_queue, * item = ins->tx_queue;
while (item != NULL)
{
#if CANARD_MULTI_IFACE && CANARD_ENABLE_DEADLINE
if ((current_time_usec > item->frame.deadline_usec) || item->frame.iface_mask == 0)
#elif CANARD_MULTI_IFACE
if (item->frame.iface_mask == 0)
#else
if (current_time_usec > item->frame.deadline_usec)
#endif
{
if (item == ins->tx_queue)
{
ins->tx_queue = ins->tx_queue->next;
freeBlock(&ins->allocator, item);
item = ins->tx_queue;
prev_item = item;
}
else
{
prev_item->next = item->next;
freeBlock(&ins->allocator, item);
item = prev_item->next;
}
}
else
{
prev_item = item;
item = item->next;
}
}
#endif
}
int16_t canardDecodeScalar(const CanardRxTransfer* transfer,
uint32_t bit_offset,
uint8_t bit_length,
bool value_is_signed,
void* out_value)
{
if (transfer == NULL || out_value == NULL)
{
return -CANARD_ERROR_INVALID_ARGUMENT;
}
if (bit_length < 1 || bit_length > 64)
{
return -CANARD_ERROR_INVALID_ARGUMENT;
}
if (bit_length == 1 && value_is_signed)
{
return -CANARD_ERROR_INVALID_ARGUMENT;
}
/*
* Reading raw bytes into the temporary storage.
* Luckily, C guarantees that every element is aligned at the beginning (lower address) of the union.
*/
union
{
bool boolean; ///< sizeof(bool) is implementation-defined, so it has to be handled separately
uint8_t u8; ///< Also char
int8_t s8;
uint16_t u16;
int16_t s16;
uint32_t u32;
int32_t s32; ///< Also float, possibly double, possibly long double (depends on implementation)
uint64_t u64;
int64_t s64; ///< Also double, possibly float, possibly long double (depends on implementation)
uint8_t bytes[8];
} storage;
memset(&storage, 0, sizeof(storage)); // This is important
const int16_t result = descatterTransferPayload(transfer, bit_offset, bit_length, &storage.bytes[0]);
if (result <= 0)
{
return result;
}
CANARD_ASSERT((result > 0) && (result <= 64) && (result <= bit_length));
/*
* The bit copy algorithm assumes that more significant bits have lower index, so we need to shift some.
* Extra most significant bits will be filled with zeroes, which is fine.
* Coverity Scan mistakenly believes that the array may be overrun if bit_length == 64; however, this branch will
* not be taken if bit_length == 64, because 64 % 8 == 0.
*/
if ((bit_length % 8) != 0)
{
// coverity[overrun-local]
storage.bytes[bit_length / 8U] = (uint8_t)(storage.bytes[bit_length / 8U] >> ((8U - (bit_length % 8U)) & 7U));
}
/*
* Determining the closest standard byte length - this will be needed for byte reordering and sign bit extension.
*/
uint8_t std_byte_length = 0;
if (bit_length == 1) { std_byte_length = sizeof(bool); }
else if (bit_length <= 8) { std_byte_length = 1; }
else if (bit_length <= 16) { std_byte_length = 2; }
else if (bit_length <= 32) { std_byte_length = 4; }
else if (bit_length <= 64) { std_byte_length = 8; }
else
{
CANARD_ASSERT(false);
return -CANARD_ERROR_INTERNAL;
}
CANARD_ASSERT((std_byte_length > 0) && (std_byte_length <= 8));
/*
* Flipping the byte order if needed.
*/
if (isBigEndian())
{
swapByteOrder(&storage.bytes[0], std_byte_length);
}
/*
* Extending the sign bit if needed. I miss templates.
* Note that we operate on unsigned values in order to avoid undefined behaviors.
*/
if (value_is_signed && (std_byte_length * 8 != bit_length))
{
if (bit_length <= 8)
{
if ((storage.u8 & (1U << (bit_length - 1U))) != 0) // If the sign bit is set...
{
storage.u8 |= (uint8_t) 0xFFU & (uint8_t) ~((1U << bit_length) - 1U); // ...set all bits above it.
}
}
else if (bit_length <= 16)
{
if ((storage.u16 & (1U << (bit_length - 1U))) != 0)
{
storage.u16 |= (uint16_t) 0xFFFFU & (uint16_t) ~((1U << bit_length) - 1U);
}
}
else if (bit_length <= 32)
{
if ((storage.u32 & (((uint32_t) 1) << (bit_length - 1U))) != 0)
{
storage.u32 |= (uint32_t) 0xFFFFFFFFUL & (uint32_t) ~((((uint32_t) 1) << bit_length) - 1U);
}
}
else if (bit_length < 64) // Strictly less, this is not a typo
{
if ((storage.u64 & (((uint64_t) 1) << (bit_length - 1U))) != 0)
{
storage.u64 |= (uint64_t) 0xFFFFFFFFFFFFFFFFULL & (uint64_t) ~((((uint64_t) 1) << bit_length) - 1U);
}
}
else
{
CANARD_ASSERT(false);
return -CANARD_ERROR_INTERNAL;
}
}
/*
* Copying the result out.
*/
if (value_is_signed)
{
if (bit_length <= 8) { *( (int8_t*) out_value) = storage.s8; }
else if (bit_length <= 16) { *((int16_t*) out_value) = storage.s16; }
else if (bit_length <= 32) { *((int32_t*) out_value) = storage.s32; }
else if (bit_length <= 64) { *((int64_t*) out_value) = storage.s64; }
else
{
CANARD_ASSERT(false);
return -CANARD_ERROR_INTERNAL;
}
}
else
{
if (bit_length == 1) { *( (bool*) out_value) = storage.boolean; }
else if (bit_length <= 8) { *( (uint8_t*) out_value) = storage.u8; }
else if (bit_length <= 16) { *((uint16_t*) out_value) = storage.u16; }
else if (bit_length <= 32) { *((uint32_t*) out_value) = storage.u32; }
else if (bit_length <= 64) { *((uint64_t*) out_value) = storage.u64; }
else
{
CANARD_ASSERT(false);
return -CANARD_ERROR_INTERNAL;
}
}
CANARD_ASSERT(result <= bit_length);
CANARD_ASSERT(result > 0);
return result;
}
void canardEncodeScalar(void* destination,
uint32_t bit_offset,
uint8_t bit_length,
const void* value)
{
/*
* This function can only fail due to invalid arguments, so it was decided to make it return void,
* and in the case of bad arguments try the best effort or just trigger an CANARD_ASSERTion failure.
* Maybe not the best solution, but it simplifies the API.
*/
CANARD_ASSERT(destination != NULL);
CANARD_ASSERT(value != NULL);
if (bit_length > 64)
{
CANARD_ASSERT(false);
bit_length = 64;
}
if (bit_length < 1)
{
CANARD_ASSERT(false);
bit_length = 1;
}
/*
* Preparing the data in the temporary storage.
*/
union
{
bool boolean;
uint8_t u8;
uint16_t u16;
uint32_t u32;
uint64_t u64;
uint8_t bytes[8];
} storage;
memset(&storage, 0, sizeof(storage));
uint8_t std_byte_length = 0;
// Extra most significant bits can be safely ignored here.
if (bit_length == 1) { std_byte_length = sizeof(bool); storage.boolean = (*((bool*) value) != 0); }
else if (bit_length <= 8) { std_byte_length = 1; storage.u8 = *((uint8_t*) value); }
else if (bit_length <= 16) { std_byte_length = 2; storage.u16 = *((uint16_t*) value); }
else if (bit_length <= 32) { std_byte_length = 4; storage.u32 = *((uint32_t*) value); }
else if (bit_length <= 64) { std_byte_length = 8; storage.u64 = *((uint64_t*) value); }
else
{
CANARD_ASSERT(false);
}
CANARD_ASSERT(std_byte_length > 0);
if (isBigEndian())
{
swapByteOrder(&storage.bytes[0], std_byte_length);
}
/*
* The bit copy algorithm assumes that more significant bits have lower index, so we need to shift some.
* Extra least significant bits will be filled with zeroes, which is fine.
* Extra most significant bits will be discarded here.
* Coverity Scan mistakenly believes that the array may be overrun if bit_length == 64; however, this branch will
* not be taken if bit_length == 64, because 64 % 8 == 0.
*/
if ((bit_length % 8) != 0)
{
// coverity[overrun-local]
storage.bytes[bit_length / 8U] = (uint8_t)(storage.bytes[bit_length / 8U] << ((8U - (bit_length % 8U)) & 7U));
}
/*
* Now, the storage contains properly serialized scalar. Copying it out.
*/
copyBitArray(&storage.bytes[0], 0, bit_length, (uint8_t*) destination, bit_offset);
}
void canardReleaseRxTransferPayload(CanardInstance* ins, CanardRxTransfer* transfer)
{
while (transfer->payload_middle != NULL)
{
CanardBufferBlock* const temp = transfer->payload_middle->next;
freeBlock(&ins->allocator, transfer->payload_middle);
transfer->payload_middle = temp;
}
transfer->payload_middle = NULL;
transfer->payload_head = NULL;
transfer->payload_tail = NULL;
transfer->payload_len = 0;
}
CanardPoolAllocatorStatistics canardGetPoolAllocatorStatistics(CanardInstance* ins)
{
return ins->allocator.statistics;
}
uint16_t canardConvertNativeFloatToFloat16(float value)
{
CANARD_ASSERT(sizeof(float) == 4);
union FP32
{
uint32_t u;
float f;
};
const union FP32 f32inf = { 255UL << 23U };
const union FP32 f16inf = { 31UL << 23U };