Move a few things about to make compiling with other projects possible.
[apps/low-level-can-service.git] / src / isotp / receive.c
1 #include <isotp/receive.h>
2 #include <bitfield/bitfield.h>
3 #include <string.h>
4
5 static void isotp_complete_receive(IsoTpReceiveHandle* handle, IsoTpMessage* message) {
6     if(handle->message_received_callback != NULL) {
7         handle->message_received_callback(message);
8     }
9 }
10
11 bool isotp_handle_single_frame(IsoTpReceiveHandle* handle, IsoTpMessage* message) {
12     isotp_complete_receive(handle, message);
13     return true;
14 }
15
16 IsoTpReceiveHandle isotp_receive(IsoTpShims* shims,
17         const uint16_t arbitration_id, IsoTpMessageReceivedHandler callback) {
18     IsoTpReceiveHandle handle = {
19         success: false,
20         completed: false,
21         arbitration_id: arbitration_id,
22         message_received_callback: callback
23     };
24
25     return handle;
26 }
27
28 IsoTpMessage isotp_continue_receive(IsoTpShims* shims,
29         IsoTpReceiveHandle* handle, const uint16_t arbitration_id,
30         const uint8_t data[], const uint8_t size) {
31     IsoTpMessage message = {
32         arbitration_id: arbitration_id,
33         completed: false,
34         payload: {0},
35         size: 0
36     };
37
38     if(size < 1) {
39         return message;
40     }
41
42     if(handle->arbitration_id != arbitration_id) {
43         if(shims->log != NULL)  {
44             shims->log("The arb ID 0x%x doesn't match the expected rx ID 0x%x",
45                     arbitration_id, handle->arbitration_id);
46         }
47         return message;
48     }
49
50     IsoTpProtocolControlInformation pci = (IsoTpProtocolControlInformation)
51             get_nibble(data, size, 0);
52
53     uint8_t payload_length = get_nibble(data, size, 1);
54     uint8_t payload[payload_length];
55     if(payload_length > 0 && size > 0) {
56         memcpy(payload, &data[1], payload_length);
57     }
58
59     // TODO this is set up to handle rx a response with a payload, but not to
60     // handle flow control responses for multi frame messages that we're in the
61     // process of sending
62
63     switch(pci) {
64         case PCI_SINGLE: {
65             if(payload_length > 0) {
66                 memcpy(message.payload, payload, payload_length);
67             }
68             message.size = payload_length;
69             message.completed = true;
70             handle->success = true;
71             handle->completed = true;
72             isotp_handle_single_frame(handle, &message);
73             break;
74          }
75         default:
76             shims->log("Only single frame messages are supported");
77             break;
78     }
79     return message;
80 }