Use proper format specifier for uint32_t.
[apps/agl-service-can-low-level.git] / src / uds / uds.c
1 #include <uds/uds.h>
2 #include <bitfield/bitfield.h>
3 #include <canutil/read.h>
4 #include <string.h>
5 #include <limits.h>
6 #include <stddef.h>
7 #include <sys/param.h>
8 #include <inttypes.h>
9
10 #define ARBITRATION_ID_OFFSET 0x8
11 #define MODE_RESPONSE_OFFSET 0x40
12 #define NEGATIVE_RESPONSE_MODE 0x7f
13 #define MAX_DIAGNOSTIC_PAYLOAD_SIZE 6
14 #define MODE_BYTE_INDEX 0
15 #define PID_BYTE_INDEX 1
16 #define NEGATIVE_RESPONSE_MODE_INDEX 1
17 #define NEGATIVE_RESPONSE_NRC_INDEX 2
18
19 #ifndef MAX
20 #define MAX(x, y) (((x) > (y)) ? (x) : (y))
21 #endif
22
23 DiagnosticShims diagnostic_init_shims(LogShim log,
24         SendCanMessageShim send_can_message,
25         SetTimerShim set_timer) {
26     DiagnosticShims shims = {
27         log: log,
28         send_can_message: send_can_message,
29         set_timer: set_timer
30     };
31     return shims;
32 }
33
34 static void setup_receive_handle(DiagnosticRequestHandle* handle) {
35     if(handle->request.arbitration_id == OBD2_FUNCTIONAL_BROADCAST_ID) {
36         uint32_t response_id;
37         for(response_id = 0;
38                 response_id < OBD2_FUNCTIONAL_RESPONSE_COUNT; ++response_id) {
39             handle->isotp_receive_handles[response_id] = isotp_receive(
40                     &handle->isotp_shims,
41                     OBD2_FUNCTIONAL_RESPONSE_START + response_id,
42                     NULL);
43         }
44         handle->isotp_receive_handle_count = OBD2_FUNCTIONAL_RESPONSE_COUNT;
45     } else {
46         handle->isotp_receive_handle_count = 1;
47         handle->isotp_receive_handles[0] = isotp_receive(&handle->isotp_shims,
48                 handle->request.arbitration_id + ARBITRATION_ID_OFFSET,
49                 NULL);
50     }
51 }
52
53 static uint16_t autoset_pid_length(uint8_t mode, uint16_t pid,
54         uint8_t pid_length) {
55     if(pid_length == 0) {
56         if(pid > 0xffff || mode > 10) {
57             pid_length = 2;
58         } else {
59             pid_length = 1;
60         }
61     }
62     return pid_length;
63 }
64
65 static void send_diagnostic_request(DiagnosticShims* shims,
66         DiagnosticRequestHandle* handle) {
67     uint8_t payload[MAX_DIAGNOSTIC_PAYLOAD_SIZE] = {0};
68     payload[MODE_BYTE_INDEX] = handle->request.mode;
69     if(handle->request.has_pid) {
70         handle->request.pid_length = autoset_pid_length(handle->request.mode,
71                 handle->request.pid, handle->request.pid_length);
72         handle->request.pid_length = handle->request.pid_length;
73         set_bitfield(handle->request.pid, PID_BYTE_INDEX * CHAR_BIT,
74                 handle->request.pid_length * CHAR_BIT, payload,
75                 sizeof(payload));
76     }
77
78     if(handle->request.payload_length > 0) {
79         memcpy(&payload[PID_BYTE_INDEX + handle->request.pid_length],
80                 handle->request.payload, handle->request.payload_length);
81     }
82
83     handle->isotp_send_handle = isotp_send(&handle->isotp_shims,
84             handle->request.arbitration_id, payload,
85             1 + handle->request.payload_length + handle->request.pid_length,
86             NULL);
87     if(shims->log != NULL) {
88         char request_string[128] = {0};
89         diagnostic_request_to_string(&handle->request, request_string,
90                 sizeof(request_string));
91         shims->log("Sending diagnostic request: %s", request_string);
92     }
93 }
94
95 void start_diagnostic_request(DiagnosticShims* shims,
96         DiagnosticRequestHandle* handle) {
97     handle->success = false;
98     handle->completed = false;
99     send_diagnostic_request(shims, handle);
100     setup_receive_handle(handle);
101 }
102
103 DiagnosticRequestHandle generate_diagnostic_request(DiagnosticShims* shims,
104         DiagnosticRequest* request, DiagnosticResponseReceived callback) {
105     DiagnosticRequestHandle handle = {
106         request: *request,
107         callback: callback,
108         success: false,
109         completed: false
110     };
111
112     handle.isotp_shims = isotp_init_shims(shims->log,
113             shims->send_can_message,
114             shims->set_timer);
115     handle.isotp_shims.frame_padding = !request->no_frame_padding;
116
117     return handle;
118     // TODO notes on multi frame:
119     // TODO what are the timers for exactly?
120     //
121     // when sending multi frame, send 1 frame, wait for a response
122     // if it says send all, send all right away
123     // if it says flow control, set the time for the next send
124     // instead of creating a timer with an async callback, add a process_handle
125     // function that's called repeatedly in the main loop - if it's time to
126     // send, we do it. so there's a process_handle_send and receive_can_frame
127     // that are just called continuously from the main loop. it's a waste of a
128     // few cpu cycles but it may be more  natural than callbacks.
129     //
130     // what would a timer callback look like...it would need to pass the handle
131     // and that's all. seems like a context void* would be able to capture all
132     // of the information but arg, memory allocation. look at how it's done in
133     // the other library again
134     //
135 }
136
137 DiagnosticRequestHandle diagnostic_request(DiagnosticShims* shims,
138         DiagnosticRequest* request, DiagnosticResponseReceived callback) {
139     DiagnosticRequestHandle handle = generate_diagnostic_request(
140             shims, request, callback);
141     start_diagnostic_request(shims, &handle);
142     return handle;
143 }
144
145 DiagnosticRequestHandle diagnostic_request_pid(DiagnosticShims* shims,
146         DiagnosticPidRequestType pid_request_type, uint32_t arbitration_id,
147         uint16_t pid, DiagnosticResponseReceived callback) {
148     DiagnosticRequest request = {
149         arbitration_id: arbitration_id,
150         mode: pid_request_type == DIAGNOSTIC_STANDARD_PID ? 0x1 : 0x22,
151         has_pid: true,
152         pid: pid
153     };
154
155     return diagnostic_request(shims, &request, callback);
156 }
157
158 static bool handle_negative_response(IsoTpMessage* message,
159         DiagnosticResponse* response, DiagnosticShims* shims) {
160     bool response_was_negative = false;
161     if(response->mode == NEGATIVE_RESPONSE_MODE) {
162         response_was_negative = true;
163         if(message->size > NEGATIVE_RESPONSE_MODE_INDEX) {
164             response->mode = message->payload[NEGATIVE_RESPONSE_MODE_INDEX];
165         }
166
167         if(message->size > NEGATIVE_RESPONSE_NRC_INDEX) {
168             response->negative_response_code =
169                     message->payload[NEGATIVE_RESPONSE_NRC_INDEX];
170         }
171
172         response->success = false;
173         response->completed = true;
174     }
175     return response_was_negative;
176 }
177
178 static bool handle_positive_response(DiagnosticRequestHandle* handle,
179         IsoTpMessage* message, DiagnosticResponse* response,
180         DiagnosticShims* shims) {
181     bool response_was_positive = false;
182     if(response->mode == handle->request.mode + MODE_RESPONSE_OFFSET) {
183         response_was_positive = true;
184         // hide the "response" version of the mode from the user
185         // if it matched
186         response->mode = handle->request.mode;
187         response->has_pid = false;
188         if(handle->request.has_pid && message->size > 1) {
189             response->has_pid = true;
190             if(handle->request.pid_length == 2) {
191                 response->pid = get_bitfield(message->payload, message->size,
192                         PID_BYTE_INDEX * CHAR_BIT, sizeof(uint16_t) * CHAR_BIT);
193             } else {
194                 response->pid = message->payload[PID_BYTE_INDEX];
195             }
196
197         }
198
199         if((!handle->request.has_pid && !response->has_pid)
200                 || response->pid == handle->request.pid) {
201             response->success = true;
202             response->completed = true;
203
204             uint8_t payload_index = 1 + handle->request.pid_length;
205             response->payload_length = MAX(0, message->size - payload_index);
206             if(response->payload_length > 0) {
207                 memcpy(response->payload, &message->payload[payload_index],
208                         response->payload_length);
209             }
210         } else {
211             response_was_positive = false;
212         }
213     }
214     return response_was_positive;
215 }
216
217 DiagnosticResponse diagnostic_receive_can_frame(DiagnosticShims* shims,
218         DiagnosticRequestHandle* handle, const uint32_t arbitration_id,
219         const uint8_t data[], const uint8_t size) {
220
221     DiagnosticResponse response = {
222         arbitration_id: arbitration_id,
223         success: false,
224         completed: false
225     };
226
227     if(!handle->isotp_send_handle.completed) {
228         isotp_continue_send(&handle->isotp_shims,
229                 &handle->isotp_send_handle, arbitration_id, data, size);
230     } else {
231         uint8_t i;
232         for(i = 0; i < handle->isotp_receive_handle_count; ++i) {
233             IsoTpMessage message = isotp_continue_receive(&handle->isotp_shims,
234                     &handle->isotp_receive_handles[i], arbitration_id, data,
235                     size);
236
237             if(message.completed) {
238                 if(message.size > 0) {
239                     response.mode = message.payload[0];
240                     if(handle_negative_response(&message, &response, shims) ||
241                             handle_positive_response(handle, &message,
242                                 &response, shims)) {
243                         if(shims->log != NULL) {
244                             char response_string[128] = {0};
245                             diagnostic_response_to_string(&response,
246                                     response_string, sizeof(response_string));
247                             shims->log("Diagnostic response received: %s",
248                                     response_string);
249                         }
250
251                         handle->success = true;
252                         handle->completed = true;
253                     }
254                 } else {
255                     if(shims->log != NULL) {
256                         shims->log("Received an empty response on arb ID 0x%x",
257                                 response.arbitration_id);
258                     }
259                 }
260
261                 if(handle->completed && handle->callback != NULL) {
262                     handle->callback(&response);
263                 }
264
265                 break;
266             }
267         }
268     }
269     return response;
270 }
271
272 int diagnostic_payload_to_integer(const DiagnosticResponse* response) {
273     return get_bitfield(response->payload, response->payload_length, 0,
274             response->payload_length * CHAR_BIT);
275 }
276
277 float diagnostic_decode_obd2_pid(const DiagnosticResponse* response) {
278     // handles on the single number values, not the bit encoded ones
279     switch(response->pid) {
280         case 0xa:
281             return response->payload[0] * 3;
282         case 0xc:
283             return (response->payload[0] * 256 + response->payload[1]) / 4.0;
284         case 0xd:
285         case 0x33:
286         case 0xb:
287             return response->payload[0];
288         case 0x10:
289             return (response->payload[0] * 256 + response->payload[1]) / 100.0;
290         case 0x11:
291         case 0x2f:
292         case 0x45:
293         case 0x4c:
294         case 0x52:
295         case 0x5a:
296         case 0x4:
297             return response->payload[0] * 100.0 / 255.0;
298         case 0x46:
299         case 0x5c:
300         case 0xf:
301         case 0x5:
302             return response->payload[0] - 40;
303         case 0x62:
304             return response->payload[0] - 125;
305         default:
306             return 0;
307     }
308 }
309
310 void diagnostic_response_to_string(const DiagnosticResponse* response,
311         char* destination, size_t destination_length) {
312     int bytes_used = snprintf(destination, destination_length,
313             "arb_id: 0x%" SCNd32 ", mode: 0x%x, ",
314             response->arbitration_id,
315             response->mode);
316
317     if(response->has_pid) {
318         bytes_used += snprintf(destination + bytes_used,
319                 destination_length - bytes_used,
320                 "pid: 0x%x, ",
321                 response->pid);
322     }
323
324     if(!response->success) {
325         bytes_used += snprintf(destination + bytes_used,
326                 destination_length - bytes_used,
327                 "nrc: 0x%x, ",
328                 response->negative_response_code);
329     }
330
331     if(response->payload_length > 0) {
332         snprintf(destination + bytes_used, destination_length - bytes_used,
333                 "payload: 0x%02x%02x%02x%02x%02x%02x%02x",
334                 response->payload[0],
335                 response->payload[1],
336                 response->payload[2],
337                 response->payload[3],
338                 response->payload[4],
339                 response->payload[5],
340                 response->payload[6]);
341     } else {
342         snprintf(destination + bytes_used, destination_length - bytes_used,
343                 "no payload");
344     }
345 }
346
347 void diagnostic_request_to_string(const DiagnosticRequest* request,
348         char* destination, size_t destination_length) {
349     int bytes_used = snprintf(destination, destination_length,
350             "arb_id: 0x%" SCNd32 ", mode: 0x%x, ",
351             request->arbitration_id,
352             request->mode);
353
354     if(request->has_pid) {
355         bytes_used += snprintf(destination + bytes_used,
356                 destination_length - bytes_used,
357                 "pid: 0x%x, ",
358                 request->pid);
359     }
360
361     int remaining_space = destination_length - bytes_used;
362     if(request->payload_length > 0) {
363         snprintf(destination + bytes_used, remaining_space,
364                 "payload: 0x%02x%02x%02x%02x%02x%02x%02x",
365                 request->payload[0],
366                 request->payload[1],
367                 request->payload[2],
368                 request->payload[3],
369                 request->payload[4],
370                 request->payload[5],
371                 request->payload[6]);
372     } else {
373         snprintf(destination + bytes_used, remaining_space, "no payload");
374     }
375 }
376
377 bool diagnostic_request_equals(const DiagnosticRequest* ours,
378         const DiagnosticRequest* theirs) {
379     bool equals = ours->arbitration_id == theirs->arbitration_id &&
380         ours->mode == theirs->mode;
381     equals &= ours->has_pid == theirs->has_pid;
382     equals &= ours->pid == theirs->pid;
383     return equals;
384 }