Draft reworking of API.
[apps/agl-service-can-low-level.git] / src / isotp / isotp.c
1 #include <isotp/isotp.h>
2 #include <isotp/receive.h>
3 #include <bitfield/bitfield.h>
4
5 const uint16_t MAX_ISO_TP_MESSAGE_SIZE = 4096;
6 const uint16_t MAX_CAN_FRAME_SIZE = 8;
7 const uint8_t ISO_TP_DEFAULT_RESPONSE_TIMEOUT = 100;
8 const bool ISO_TP_DEFAULT_FRAME_PADDING_STATUS = true;
9
10 // TODO why isn't this picked up from the header?
11 extern IsoTpHandle isotp_receive(IsoTpShims* shims, const uint16_t arbitration_id,
12         IsoTpMessageReceivedHandler callback);
13
14
15 /* void isotp_set_timeout(IsoTpHandler* handler, uint16_t timeout_ms) { */
16     /* handler->timeout_ms = timeout_ms; */
17 /* } */
18
19 IsoTpShims isotp_init_shims(LogShim log, SendCanMessageShim send_can_message,
20         SetTimerShim set_timer) {
21     IsoTpShims shims = {
22         log: log,
23         send_can_message: send_can_message,
24         set_timer: set_timer
25     };
26     return shims;
27 }
28
29 void isotp_message_to_string(const IsoTpMessage* message, char* destination,
30         size_t destination_length) {
31     snprintf(destination, destination_length,"ID: 0x%02x, Payload: 0x%llx",
32             // TODO the payload may be backwards here
33             message->arbitration_id, message->payload);
34 }
35
36 void isotp_receive_can_frame(IsoTpShims* shims, IsoTpHandle* handle,
37         const uint16_t arbitration_id, const uint8_t data[],
38         const uint8_t data_length) {
39     if(data_length < 1) {
40         return;
41     }
42
43     if(handle->type == ISOTP_HANDLE_RECEIVING) {
44         if(handle->receive_handle.arbitration_id != arbitration_id) {
45             return;
46         }
47     } else if(handle->type == ISOTP_HANDLE_SENDING) {
48         if(handle->send_handle.receiving_arbitration_id != arbitration_id) {
49             return;
50         }
51     } else {
52         shims->log("The ISO-TP handle is corrupt");
53     }
54
55     IsoTpProtocolControlInformation pci = (IsoTpProtocolControlInformation)
56             get_nibble(data, data_length, 0);
57
58     uint8_t payload_length = get_nibble(data, data_length, 1);
59     uint8_t payload[payload_length];
60     if(payload_length > 0 && data_length > 0) {
61         memcpy(payload, &data[1], payload_length);
62     }
63
64     // TODO this is set up to handle rx a response with a payload, but not to
65     // handle flow control responses for multi frame messages that we're in the
66     // process of sending
67
68     switch(pci) {
69         case PCI_SINGLE: {
70             IsoTpMessage message = {
71                 arbitration_id: arbitration_id,
72                 payload: payload,
73                 size: payload_length
74             };
75
76             isotp_handle_single_frame(handle, &message);
77             break;
78          }
79         default:
80             shims->log("Only single frame messages are supported");
81             break;
82     }
83 }