BOROSOFTWAREAll work →
scantool/diag_l2_vag.c 860 lines
3 findings in this fileA10L123B21L254B22L820
1/*
2 * freediag - Vehicle Diagnostic Utility
3 *
4 *
5 * Copyright (C) 2001 Richard Almeida & Ibex Ltd ([email protected])
6 * Copyright (C) 2015-2016 Tomasz Kaźmierczak <[email protected]>
7 *
8 * This program is free software: you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation, either version 3 of the License, or
11 * (at your option) any later version.
12 *
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
17 *
18 * You should have received a copy of the GNU General Public License
19 * along with this program. If not, see <http://www.gnu.org/licenses/>.
20 *
21 *************************************************************************
22 *
23 * Diag
24 *
25 * L2 driver for Volkswagen Aktiengesellschaft (VAG) KW1281 protocol
26 * (Keyword 0x01 0x8a)
27 *
28 * This implementation is written according to the SAE J2818 specification,
29 * but with one exception - the response to ECU's No Acknowledge Retry message
30 * uses an incremented sequence number (SAE J2818 says that it shouldn't be
31 * incremented); similarly after sending No Acknowledge Retry message,
32 * the repeated ECU message is expected to have the sequence number incremented
33 * (SAE J2818 says that also the ECU should repeat the message using the
34 * previous sequence number). This is because the code has been tested only
35 * with a European version of a VAG ECU (non-US VAG ECUs do not follow the SAE
36 * specification strictly) - once it is confirmed that US VAG ECUs do follow
37 * the SAE specification with regards to the No Acknowledge Retry behaviour,
38 * the spec-obeying behaviour can be added as an option (or as a default, with
39 * an option to use the non-US behaviour).
40 *
41 * The default baud rate (used when none is set by the user) is 10400, so here
42 * the code follows the SAE J2818 specification, which is mandatory on the US
43 * market, but again - it has not been tested on a US VAG ECU.
44 * European VAG ECUs use 9600 baud rate, so this value should be used if
45 * the default doesn't work (the default most probably won't work outside US).
46 *
47 */
48
49#include <stdint.h>
50#include <stdlib.h>
51#include <string.h>
52#include <assert.h>
53
54#include "diag.h"
55#include "diag_err.h"
56#include "diag_os.h"
57#include "diag_tty.h"
58#include "diag_l1.h"
59#include "diag_l2.h"
60
61#include "diag_l2_vag.h"
62
63/*
64 * ISO vag specific data
65 */
66struct diag_l2_vag {
67 uint8_t seq_nr; //Sequence number
68 uint8_t master; //Master flag, 1 = us, 0 = ECU
69 uint8_t first_telegram_started;
70
71 struct diag_msg *ecu_id_telegram; //a pointer to store the ECU ID telegram received during initiation
72
73 uint8_t rxbuf[MAXRBUF]; //Receive buffer, for building message in
74 int rxoffset; //Offset to write into buffer
75
76 unsigned long long msg_finish_time; //a point in time when the last message finished arriving/departing
77};
78
79/*
80 * Useful internal routines
81 */
82
83/*
84 *
85 * Receives a single Block from the ECU
86 *
87 * Returns 0 on success, errorcode<0 on errors
88 */
89static struct diag_msg *diag_l2_vag_block_recv(struct diag_l2_conn *d_l2_conn, int *errval, int msg_timeout) {
90 int rv;
91 struct diag_l2_vag *dp = (struct diag_l2_vag *)d_l2_conn->diag_l2_proto_data;
92 //prepare a No Acknowledge message - we may need one
93 uint8_t noack_data[1];
94 struct diag_msg noack;
95 memset(&noack, 0, sizeof(noack));
96 noack.type = KWP1281_SID_NO_ACK;
97 noack.data = noack_data;
98 noack.len = 1;
99
100 //clear the offset
101 dp->rxoffset = 0;
102
103 //Set the timeout for the first byte of the awaited message
104 int timeout = msg_timeout;
105
106 while (1) {
107 if (d_l2_conn->diag_link->l1flags & DIAG_L1_DOESL2FRAME) {
108 //for framed L0, must read the whole frame at once
109 rv = diag_l1_recv(d_l2_conn->diag_link->l2_dl0d, dp->rxbuf, MAXRBUF, timeout);
110 DIAG_DBGM(diag_l2_debug, DIAG_DEBUG_PROTO, DIAG_DBGLEVEL_V,
111 FLFMT "after recv, rv=%d\n", FL, rv);
112
113 if (rv < 0) {
114 *errval = rv;
115 return diag_pfwderr(rv);
116 }
117 dp->msg_finish_time = diag_os_gethrt();
118 //currently the only framed L0 for KW1281 is carsim, so don't bother validating sequence number
119 break;
120 }
121
122 //one byte at a time is sent by the ECU
123 uint8_t byte;
124 rv = diag_l1_recv(d_l2_conn->diag_link->l2_dl0d, &byte, 1, timeout);
125 unsigned long long byte_recv_time = diag_os_gethrt();
126 //now set the timeout value for all the remaining awaited bytes
127 timeout = KWP1281_T_R8;
128
129 DIAG_DBGM(diag_l2_debug, DIAG_DEBUG_PROTO, DIAG_DBGLEVEL_V,
130 FLFMT "after recv, rv=%d rxoffset=%d\n",
131 FL, rv, dp->rxoffset);
132
133 if (rv < 0) {
134 if (rv == DIAG_ERR_TIMEOUT) {
135 //a very special case of timeout is when waiting for the first telegram from the ECU;
136 //if it occurs, then it means that the ECU either received wrong KB2 complement
137 //(which is more probable) or didn't receive the KB2 at all (less probable);
138 //since we cannot OR the error code, let's return the more probable one
139 if (dp->first_telegram_started == 0) {
140 *errval = DIAG_ERR_BADRATE; //wrong KB2 value indicates baud rate problems
141 return diag_pseterr(*errval);
142 }
143 //the timeout may occur if the transmitter didn't receive our complement byte
144 //or if that byte was incorrect - in such cases it will retry sending the whole
145 //message again, but only after 2*T_R8 time units since it sent the previous message byte;
146 //we (the receiver) have been waiting already for T_R8 time unit since sending our
147 //complement byte, so the transmitter should re-start the message _within_
148 //_our_ another T_R8 time unit (which started later than the receiver's secont T_R8
149 //time unit);
150 rv = diag_l1_recv(d_l2_conn->diag_link->l2_dl0d, &byte, 1, KWP1281_T_R8);
151 if (rv < 0) {
152 //if we timed out again, then this means that the communication line
153 //has been broken or closed; but with one exception - if we were waiting for
154 //the last byte of the message (the ETX byte), then we should assume that the ETX
155 //byte might have been sent by the transmitter, but got lost on its way,
156 //and we should try to go on as if we have received it
157 if (dp->rxoffset < dp->rxbuf[0] || rv != DIAG_ERR_TIMEOUT) {
158 *errval = rv;
159 return diag_pfwderr(rv);
160 }
161 } else {
162 //the first byte of the re-started message has arrived, so just reset the rxoffset
163 //and go on with the regular code path
164 dp->rxoffset = 0;
165 }
166 } else {
167 *errval = rv;
168 return diag_pfwderr(rv);
169 }
170 }
171 //now we can set the flag indicating that the initialization
172 //has been fully successful
173 if (dp->first_telegram_started == 0) {
174 dp->first_telegram_started = 1;
175 }
176
177 //store the byte
178 dp->rxbuf[dp->rxoffset] = byte;
179 dp->rxoffset++;
180
181 //is this the last byte?
182 if (dp->rxoffset-1 == dp->rxbuf[0]) {
183 dp->msg_finish_time = diag_os_gethrt();
184 //check whether the last byte is correct
185 if (byte != KWP1281_END_BYTE ||
186 //check also whether the sequence number present in the message is correct
187 //(should be odd and be greater than our sequence number by 1)
188 ((dp->rxbuf[1] % 2) == 0 || dp->rxbuf[1] != dp->seq_nr+1)) {
189 //arbitrarily set our sequence number - we could get here because of an incorrect
190 //sequence number sent by the ECU
191 dp->seq_nr += 2;
192 //send a NoAck Retry message by using the sequence number from the ECU's message
193 //(we can be sure that the buffer contains the number that ECU sent us, because when we received it,
194 //we responded with a complement and ECU didn't complain)
195 noack_data[0] = dp->rxbuf[1];
196 //we must flag ourselves as master before calling the send function
197 //(and the send function will re-set the flag to slave)
198 dp->master = 1;
199 rv = diag_l2_send(d_l2_conn, &noack);
200 if (rv < 0) {
201 *errval = rv;
202 return diag_pfwderr(rv);
203 }
204 //set the old sequence number again
205 //NOTE: SAE J2818 says that "The Message number is NOT incremented by the transmitter for a repeated block."
206 // so we should expect that the repeated message will have the same sequence number and thus we should
207 // decrease our own sequence number to the previous value also. However, when testing on an ECU installed
208 // in a European VW, this is not the case - the ECU repeated the message with an increased sequence number.
209 // Can't test this with a VW from USA, so commenting-out for now. If US VWs indeed follow the specification
210 // strictly, then a possible solution would be to set/unset this behaviour based on a flag
211 // (eg. L2_vag specific option for enabling/disabling strict SAE J2818).
212 //dp->seq_nr -= 2;
213 //prepare for receiving the whole message again
214 dp->rxoffset = 0;
215 //time elapsed since receiving last message
216 unsigned long long elapsed_time = diag_os_hrtus(diag_os_gethrt() - dp->msg_finish_time)/1000;
217 //the timeout values are between messages, so decrease the T_RB_MAX timeout
218 //by the time that has elapsed since sending the no-ack message to the ECU
219 timeout = elapsed_time < KWP1281_T_RB_MAX ? KWP1281_T_RB_MAX-elapsed_time : 0;
220 continue;
221 }
222 break;
223 }
224
225 //calculate the complement byte
226 byte = ~byte;
227 //how much time elapsed since receiving another byte?
228 unsigned long long elapsed_time = diag_os_hrtus(diag_os_gethrt() - byte_recv_time)/1000;
229 //give ECU some time before sending the complement byte
230 diag_os_millisleep(elapsed_time < KWP1281_T_R6_MIN ? KWP1281_T_R6_MIN-elapsed_time : 0);
231 rv = diag_l1_send(d_l2_conn->diag_link->l2_dl0d, &byte, 1, 0);
232
233 DIAG_DBGM(diag_l2_debug, DIAG_DEBUG_PROTO, DIAG_DBGLEVEL_V,
234 FLFMT "after send, rv=%d\n", FL, rv);
235
236 if (rv < 0) {
237 *errval = rv;
238 return diag_pfwderr(rv);
239 }
240 }
241
242 //now we are the master (!!)
243 dp->master = 1;
244 //update our sequence number
245 //(the sequence number from the ECU's message has been validated already)
246 dp->seq_nr = dp->rxbuf[1]+1;
247
248 //length of the data inside the block;
249 //the length byte (the first one) doesn't count itself,
250 //so subtract only three bytes: block counter, command title, the end byte
251 uint8_t data_length = dp->rxbuf[0]-3;
252
253 //alloc new message
254 struct diag_msg *tmsg = diag_allocmsg(data_length);
255 if (tmsg == NULL) {
256 *errval = DIAG_ERR_NOMEM;
257 return diag_pseterr(*errval);
258 }
259
260 //copy the message data, if exists
261 if (data_length > 0) {
262 memcpy(tmsg->data, &dp->rxbuf[3], (size_t)data_length);
263 }
264
265 //set the message info
266 tmsg->rxtime = diag_os_getms();
267 tmsg->type = dp->rxbuf[2];
268 tmsg->dest = tmsg->src = 0; //these are not used by the protocol (no such info in message blocks)
269 tmsg->fmt |= DIAG_FMT_CKSUMMED; //no real checksum, but the inverted bytes thing assures data integrity
270 *errval = 0;
271 return tmsg;
272}
273
274/*
275 * Internal function for receiving a full telegram from ECU.
276 *
277 * Will store the received telegram in the d_l2_conn->diag_msg.
278 */
279int diag_l2_vag_int_recv(struct diag_l2_conn *d_l2_conn, unsigned int timeout) {
280 struct diag_l2_vag *dp = (struct diag_l2_vag *)d_l2_conn->diag_l2_proto_data;
281 struct diag_msg ack;
282 unsigned long long elapsed_time, msg_timeout;
283 int rv, na_retry_cnt = 0;
284
285 //Clear out last received message if not done already
286 if (d_l2_conn->diag_msg) {
287 diag_freemsg(d_l2_conn->diag_msg);
288 d_l2_conn->diag_msg = NULL;
289 }
290
291 //ECU can send a telegram consisting of multiple messages, but it will expect us
292 //to send an ACK message after every part (message) of the telegram, so prepare one
293 memset(&ack, 0, sizeof(ack));
294 ack.type = KWP1281_SID_ACK;
295
296 //how much time has elapsed since sending our message to the ECU
297 elapsed_time = diag_os_hrtus(diag_os_gethrt() - dp->msg_finish_time)/1000;
298 //timeout while waiting for a message
299 msg_timeout = elapsed_time < timeout ? timeout-elapsed_time : 0;
300
301 while (1) {
302 //receive another message
303 struct diag_msg *tmsg = diag_l2_vag_block_recv(d_l2_conn, &rv, msg_timeout);
304 if (rv < 0) {
305 if (d_l2_conn->diag_msg) {
306 diag_freemsg(d_l2_conn->diag_msg);
307 d_l2_conn->diag_msg = NULL;
308 }
309 return diag_ifwderr(rv);
310 }
311
312 //if this is the first messag sent by the ECU in the current telegram and this is either
313 //ACK or NO_ACK, then pass it to the caller - we cannot do anything about NO_ACK if it was
314 //caused by something we didn't send; and if ECU responded only with ACK, then the caller should
315 //be informed that there is no other response from the ECU (for instance, the keep-alive routine
316 //will be interested in an ACK reply)
317 if (d_l2_conn->diag_msg == NULL && (tmsg->type == KWP1281_SID_ACK || tmsg->type == KWP1281_SID_NO_ACK)) {
318 diag_l2_addmsg(d_l2_conn, tmsg);
319 DIAG_DBGMDATA(diag_l2_debug, (DIAG_DEBUG_PROTO | DIAG_DEBUG_DATA),
320 DIAG_DBGLEVEL_V, tmsg->data, tmsg->len,
321 FLFMT "Copying %u bytes to data: ", FL, tmsg->len);
322 break;
323 }
324
325 //if the ECU has responded with an ACK message to our ACK message, then it means that
326 //the telegram has finished with the previous received message
327 if (tmsg->type == KWP1281_SID_ACK) {
328 //we don't need the just-received ACK message
329 diag_freemsg(tmsg);
330 break;
331 }
332
333 //if this is a NO_ACK message (sent by the ECU as a response to our ACK),
334 //then we will re-try with that ACK
335 if (tmsg->type == KWP1281_SID_NO_ACK) {
336 //check if it is NO_ACK Retry
337 if (tmsg->data[0] == dp->seq_nr-2) {
338 DIAG_DBGM(diag_l2_debug, DIAG_DEBUG_PROTO, DIAG_DBGLEVEL_V,
339 FLFMT
340 "Received No Acknowledge - Retry message\n",
341 FL);
342
343 //accept at most KWP1281_NA_RETRIES of No Ack Retry messages in a row
344 if (++na_retry_cnt == KWP1281_NA_RETRIES) {
345 DIAG_DBGM(diag_l2_debug, DIAG_DEBUG_PROTO, DIAG_DBGLEVEL_V,
346 FLFMT
347 "\tbut too many Retry "
348 "messages in a row "
349 "already - aborting\n",
350 FL);
351
352 diag_freemsg(d_l2_conn->diag_msg);
353 d_l2_conn->diag_msg = NULL;
354 return diag_iseterr(DIAG_ERR_ECUSAIDNO);
355 }
356 DIAG_DBGM(diag_l2_debug, DIAG_DEBUG_PROTO, DIAG_DBGLEVEL_V,
357 FLFMT "\tso will retry\n", FL);
358
359 //re-send with the previous sequence number
360 //NOTE: SAE J2818 says that "The Message number is NOT incremented by the transmitter for a repeated block."
361 // so we should send the repeated message with the same sequence number as the original message.
362 // However, when testing this on an ECU installed in a European VW the ECU didn't accept such a message
363 // (responded with another NO_ACK Retry) and a repeated message with an incremented sequence number
364 // was accepted.
365 // Can't test this with a VW from USA, so commenting-out for now. If US VWs indeed follow the specification
366 // strictly, then a possible solution would be to set/unset this behaviour based on a flag
367 // (eg. L2_vag specific option for enabling/disabling strict SAE J2818).
368 //dp->seq_nr -= 2;
369 }
370 } else {
371 //add the new block to the telegram
372 diag_l2_addmsg(d_l2_conn, tmsg);
373 if (d_l2_conn->diag_msg == tmsg) {
374 DIAG_DBGMDATA(diag_l2_debug, (DIAG_DEBUG_PROTO | DIAG_DEBUG_DATA),
375 DIAG_DBGLEVEL_V, tmsg->data, tmsg->len,
376 FLFMT "Copying %u bytes to data: ", FL, tmsg->len);
377 }
378 //reset the counter of No Ack Retry messages received in a row
379 na_retry_cnt = 0;
380 }
381
382 //now tell the ECU that we are waiting for morr!
383 rv = diag_l2_send(d_l2_conn, &ack);
384 if (rv < 0) {
385 //clean up and set the error code
386 diag_freemsg(d_l2_conn->diag_msg);
387 d_l2_conn->diag_msg = NULL;
388 return diag_ifwderr(rv);
389 }
390
391 //re-calculate the message timeout
392 elapsed_time = diag_os_hrtus(diag_os_gethrt() - dp->msg_finish_time)/1000;
393 msg_timeout = elapsed_time < KWP1281_T_RB_MAX ? KWP1281_T_RB_MAX-elapsed_time : 0;
394 }
395
396 return 0;
397}
398
399/* External interface */
400
401/*
402 * The complex initialisation routine for ISOvag, which supports
403 * 2 types of initialisation (5-BAUD, FAST) and functional
404 * and physical addressing. The ISOvag spec describes CARB initialisation
405 * which is done in the ISO9141 code
406 */
407
408static int dl2p_vag_startcomms(struct diag_l2_conn *d_l2_conn, UNUSED(flag_type flags),
409 unsigned int bitrate, target_type target, UNUSED(source_type source)) {
410 struct diag_serial_settings set;
411 struct diag_l2_vag *dp;
412 int rv;
413 uint8_t cbuf[MAXRBUF];
414
415 struct diag_l1_initbus_args in;
416
417 rv = diag_calloc(&dp, 1);
418 if (rv != 0) {
419 return diag_ifwderr(rv);
420 }
421
422 d_l2_conn->diag_l2_proto_data = (void *)dp;
423 //set several initial values needed by checks performed in the send/receive code
424 dp->seq_nr = 0;
425 dp->master = 0;
426 dp->ecu_id_telegram = NULL;
427 dp->first_telegram_started = 0;
428
429 if (bitrate == 0) {
430 bitrate = 10400; // default as per SAE J2818
431 }
432 d_l2_conn->diag_l2_speed = bitrate;
433
434 set.speed = bitrate;
435 set.databits = diag_databits_8;
436 set.stopbits = diag_stopbits_1;
437 set.parflag = diag_par_n;
438
439 //Set the speed as shown
440 rv = diag_l2_ioctl(d_l2_conn, DIAG_IOCTL_SETSPEED, &set);
441 if (rv < 0) {
442 free(dp);
443 d_l2_conn->diag_l2_proto_data=NULL;
444 return diag_ifwderr(rv);
445 }
446
447 //Flush unread input, then wait for idle bus.
448 (void)diag_l2_ioctl(d_l2_conn, DIAG_IOCTL_IFLUSH, NULL);
449 diag_os_millisleep(KWP1281_T_R0);
450
451 //Now do 5 baud init of supplied address
452 in.type = DIAG_L1_INITBUS_5BAUD;
453 in.addr = target;
454 //NOTE: there is no way to pass the timeout value into the init function - KWP1281_T_R1_MAX
455 rv = diag_l2_ioctl(d_l2_conn, DIAG_IOCTL_INITBUS, &in);
456 if (rv < 0) {
457 free(dp);
458 d_l2_conn->diag_l2_proto_data=NULL;
459 return diag_ifwderr(rv);
460 }
461
462 //Mode bytes are in 7-Odd-1, read as 8N1 and ignore parity
463 rv = diag_l1_recv(d_l2_conn->diag_link->l2_dl0d, cbuf, 1, KWP1281_T_R2_MAX);
464 if (rv < 0) {
465 free(dp);
466 d_l2_conn->diag_l2_proto_data=NULL;
467 return diag_ifwderr(rv);
468 }
469 rv = diag_l1_recv(d_l2_conn->diag_link->l2_dl0d, &cbuf[1], 1, KWP1281_T_R3_MAX);
470 if (rv < 0) {
471 free(dp);
472 d_l2_conn->diag_l2_proto_data=NULL;
473 return diag_ifwderr(rv);
474 }
475
476 DIAG_DBGM(diag_l2_debug, DIAG_DEBUG_PROTO, DIAG_DBGLEVEL_V,
477 FLFMT
478 "Received KeyWord bytes: KB1: 0x%.2X\tKB2: 0x%.2X\n",
479 FL, cbuf[0], cbuf[1]);
480
481 //Note down the bytes
482 d_l2_conn->diag_l2_kb1 = cbuf[0];
483 d_l2_conn->diag_l2_kb2 = cbuf[1];
484
485 //transmit the inverted KB2 so that the ECU knows we have received it
486 //and can validate if we got it wrong (and can act accordingly, which
487 //essentially means it will timeout us if anything went wrong)
488 if ((d_l2_conn->diag_link->l1flags & DIAG_L1_DOESSLOWINIT) == 0) {
489 //can transmit the invrted KB2 only after R4_MIN,
490 //so that the ECU has time to switch to receive mode
491 diag_os_millisleep(KWP1281_T_R4_MIN);
492 //Now transmit KB2 inverted
493 cbuf[0] = ~d_l2_conn->diag_l2_kb2;
494 rv = diag_l1_send(d_l2_conn->diag_link->l2_dl0d, cbuf, 1, d_l2_conn->diag_l2_p4min);
495 if (rv < 0) {
496 free(dp);
497 d_l2_conn->diag_l2_proto_data=NULL;
498 return diag_ifwderr(rv);
499 }
500 }
501 //update the message finish time so that when waiting for the first ECU message
502 //a correct timeout can be calculated
503 dp->msg_finish_time = diag_os_gethrt();
504
505 //the first ECU telegram should now arrive
506 rv = diag_l2_vag_int_recv(d_l2_conn, KWP1281_T_R5_MAX);
507 if (rv < 0) {
508 //if the error was a timeout while waiting for the very first byte of the telegram,
509 //then the error will be set to DIAG_ERR_BADRATE, which means that the ECU informs
510 //us that we have probably set incorrect baudrate (it must have received incorrect
511 //KB2 complement, and it can happen if we are using incorrect baudrate);
512 //ECU will re-try sending the synchronization byte in a moment, but since we are
513 //using a user-provided baudrate (instead of decoding it from the sync byte), then
514 //we cannot do anything about it here; so just report the error and leave
515 free(dp);
516 d_l2_conn->diag_l2_proto_data=NULL;
517 return diag_ifwderr(rv);
518 }
519 //the first telegram is now stored in d_l2_conn->diag_msg - copy its address
520 //to the dp->ecu_id_telegram pointer
521 dp->ecu_id_telegram = d_l2_conn->diag_msg;
522 d_l2_conn->diag_msg = NULL;
523
524 //message interval for use by external timeout handler for sending keep-alive messages
525 d_l2_conn->tinterval = KWP1281_T_RB/2;
526 return 0;
527}
528
529//free what _startcomms alloc'ed
530static int dl2p_vag_stopcomms(struct diag_l2_conn *d_l2_conn) {
531 //according to SAE J2818 if we want to finish the session
532 //we should just stop sending anything and let the ECU timeout;
533 //but of course l3 can implement the endcomms SID
534 struct diag_l2_vag *dp = (struct diag_l2_vag *)d_l2_conn->diag_l2_proto_data;
535 if (dp != NULL) {
536 if (dp->ecu_id_telegram != NULL) {
537 diag_freemsg(dp->ecu_id_telegram);
538 }
539 free(dp);
540 }
541 d_l2_conn->diag_l2_proto_data = NULL;
542
543 if (d_l2_conn->diag_msg) {
544 diag_freemsg(d_l2_conn->diag_msg);
545 d_l2_conn->diag_msg = NULL;
546 }
547
548 //make sure the ECU detects the timeout
549 diag_os_millisleep(KWP1281_T_RB_MAX);
550 return 0;
551}
552
553/*
554 * Sends a single Block (message) to the ECU
555 */
556static int dl2p_vag_send(struct diag_l2_conn *d_l2_conn, struct diag_msg *msg) {
557
558 DIAG_DBGM(diag_l2_debug, DIAG_DEBUG_WRITE, DIAG_DBGLEVEL_V,
559 FLFMT "diag_l2_vag_send %p msg %p len %u called\n",
560 FL, (void *)d_l2_conn, (void *)msg, msg->len);
561
562 struct diag_l2_vag *dp = (struct diag_l2_vag *)d_l2_conn->diag_l2_proto_data;
563 //if this function is called right after receiving the first ECU telegram,
564 //then it means that the caller doesn't care about the telegram, so delete it
565 if (dp->ecu_id_telegram != NULL) {
566 diag_freemsg(dp->ecu_id_telegram);
567 dp->ecu_id_telegram = NULL;
568 }
569
570 //are we master? if not then the caller should be redesigned/fixed
571 assert(dp->master == 1);
572
573 //the length of the block (counter byte, title byte, data bytes and block end byte)
574 dp->rxbuf[0] = msg->len + 3;
575 //block counter
576 dp->rxbuf[1] = dp->seq_nr;
577 //block title (service identification - SID)
578 dp->rxbuf[2] = msg->type;
579 //data
580 memcpy(&dp->rxbuf[3], msg->data, msg->len);
581 //block end byte
582 dp->rxbuf[3+msg->len] = KWP1281_END_BYTE;
583 dp->rxoffset = 0;
584
585 //time gap between messages
586 unsigned long long elapsed_time = diag_os_hrtus(diag_os_gethrt() - dp->msg_finish_time)/1000;
587 diag_os_millisleep(elapsed_time < KWP1281_T_RB_MIN ? KWP1281_T_RB_MIN-elapsed_time : 0);
588
589 int retries = 0;
590 //send the block to the ECU
591 while (1) {
592 int rv = 0;
593 if (d_l2_conn->diag_link->l1flags & DIAG_L1_DOESL2FRAME) {
594 //for framed L0, must send the whole block at once
595 rv = diag_l1_send(d_l2_conn->diag_link->l2_dl0d, dp->rxbuf, dp->rxbuf[0]+1, d_l2_conn->diag_l2_p4min);
596 DIAG_DBGM(diag_l2_debug, DIAG_DEBUG_PROTO, DIAG_DBGLEVEL_V,
597 FLFMT "after send, rv=%d\n", FL, rv);
598
599 if (rv < 0) {
600 return diag_ifwderr(rv);
601 }
602 dp->msg_finish_time = diag_os_gethrt();
603 break;
604 }
605
606 //send one byte at a time
607 rv = diag_l1_send(d_l2_conn->diag_link->l2_dl0d, &dp->rxbuf[dp->rxoffset], 1,
608 d_l2_conn->diag_l2_p4min);
609 unsigned long long byte_sent_time = diag_os_gethrt();
610
611 DIAG_DBGM(diag_l2_debug, DIAG_DEBUG_PROTO, DIAG_DBGLEVEL_V,
612 FLFMT "after send, rv=%d rtoffset=%d\n",
613 FL, rv, dp->rxoffset);
614
615 if (rv < 0) {
616 return diag_ifwderr(rv);
617 }
618
619 //have we just written the last byte? if so, then no inverted response will arrive
620 if (dp->rxoffset == dp->rxbuf[0]) {
621 dp->msg_finish_time = diag_os_gethrt();
622 break;
623 }
624
625 uint8_t recv_byte;
626 //ECU should respond with an inverted byte at most after t_r8
627 rv = diag_l1_recv(d_l2_conn->diag_link->l2_dl0d, &recv_byte, 1, KWP1281_T_R8);
628 unsigned long long complement_recv_time = diag_os_gethrt();
629
630 DIAG_DBGM(diag_l2_debug, DIAG_DEBUG_PROTO, DIAG_DBGLEVEL_V,
631 FLFMT "after recv, rv=%d\n", FL, rv);
632
633 if (rv < 0) {
634 //finish communication if exceeded the max number of retries or if some other error than timeout
635 if (++retries > KWP1281_TO_RETRIES ||
636 rv != DIAG_ERR_TIMEOUT) {
637 return diag_ifwderr(rv);
638 }
639 //retry sending the message
640 dp->rxoffset = 0;
641 //but only after another t_r8 - we must be sure that the receiver times-out
642 //so that it will expect a re-started message
643 elapsed_time = diag_os_hrtus(diag_os_gethrt() - byte_sent_time)/1000;
644 diag_os_millisleep(elapsed_time < 2*KWP1281_T_R8 ? 2*KWP1281_T_R8-elapsed_time : 0);
645 continue;
646 }
647
648 //check the received byte
649 uint8_t complement = ~dp->rxbuf[dp->rxoffset];
650 if (recv_byte != complement) {
651 DIAG_DBGM(diag_l2_debug, DIAG_DEBUG_PROTO, DIAG_DBGLEVEL_V,
652 FLFMT
653 "Received incorrect inverted byte: "
654 "0x%.2X (expected 0x%.2X)\n",
655 FL, (int)recv_byte, (int)complement);
656 //finish communication if exceeded the max number of retries
657 if (++retries > KWP1281_TO_RETRIES) {
658 return diag_iseterr(DIAG_ERR_BADCSUM);
659 }
660 //retry sending the message
661 dp->rxoffset = 0;
662 //but only after another t_r8 - we must be sure that the receiver times-out
663 //so that it will expect a re-started message
664 elapsed_time = diag_os_hrtus(diag_os_gethrt() - byte_sent_time)/1000;
665 diag_os_millisleep(elapsed_time < 2*KWP1281_T_R8 ? 2*KWP1281_T_R8-elapsed_time : 0);
666 continue;
667 }
668
669 dp->rxoffset++;
670 //how much time elapsed since receiving a correct complement byte?
671 elapsed_time = diag_os_hrtus(diag_os_gethrt() - complement_recv_time)/1000;
672 //give ECU some time before sending next byte
673 diag_os_millisleep(elapsed_time < KWP1281_T_R6_MIN ? KWP1281_T_R6_MIN-elapsed_time : 0);
674 }
675
676 //we are slave now
677 dp->master = 0;
678
679 return 0;
680}
681
682/*
683 * Protocol receive routine
684 */
685static int dl2p_vag_recv(struct diag_l2_conn *d_l2_conn, unsigned int timeout,
686 void (*callback)(void *handle, struct diag_msg *msg),
687 void *handle) {
688 int rv;
689
690 if (timeout != 0) {
691 DIAG_DBGM(diag_l2_debug, DIAG_DEBUG_PROTO, DIAG_DBGLEVEL_V,
692 FLFMT
693 "WARNING! l2_vag will ignore the given timeout! (%u msec)\n",
694 FL, timeout);
695 }
696
697 //if it is the first call to the recv() function since startcomms, then
698 //the message (ECU ID telegram) is already read, so call int_recv() only if the little shiny present
699 //has already been collected
700 struct diag_l2_vag *dp = (struct diag_l2_vag *)d_l2_conn->diag_l2_proto_data;
701 if (dp->ecu_id_telegram == NULL) {
702 //call the internal routine
703 rv = diag_l2_vag_int_recv(d_l2_conn, KWP1281_T_RB_MAX);
704 if (rv < 0) {
705 return rv;
706 }
707 } else {
708 //int_recv() also does this
709 if (d_l2_conn->diag_msg) {
710 diag_freemsg(d_l2_conn->diag_msg);
711 d_l2_conn->diag_msg = NULL;
712 }
713 //copy the ECU ID telegram address
714 d_l2_conn->diag_msg = dp->ecu_id_telegram;
715 //and make sure the pointer is no more
716 dp->ecu_id_telegram = NULL;
717 }
718
719 DIAG_DBGM(diag_l2_debug, DIAG_DEBUG_READ, DIAG_DBGLEVEL_V,
720 FLFMT "calling rcv callback, handle=%p\n",
721 FL, handle);
722
723 //Call user callback routine
724 //NOTE: if ECU returned NO_ACK, then the caller won't know what type it was (retry or unknown)
725 if (callback) {
726 callback(handle, d_l2_conn->diag_msg);
727 }
728
729 //Message no longer needed
730 diag_freemsg(d_l2_conn->diag_msg);
731 d_l2_conn->diag_msg = NULL;
732
733 DIAG_DBGM(diag_l2_debug, DIAG_DEBUG_READ, DIAG_DBGLEVEL_V,
734 FLFMT "rcv callback completed\n", FL);
735
736 return 0;
737}
738
739static struct diag_msg *dl2p_vag_request(struct diag_l2_conn *d_l2_conn, struct diag_msg *msg, int *errval) {
740 int rv, na_retry_cnt = 0;
741 struct diag_msg *rmsg;
742 struct diag_l2_vag *dp = (struct diag_l2_vag *)d_l2_conn->diag_l2_proto_data;
743
744 while (1) {
745 //send the request
746 rv = diag_l2_send(d_l2_conn, msg);
747 if (rv < 0) {
748 *errval = rv;
749 return diag_pfwderr(rv);
750 }
751
752 //and receive the response telegram
753 rv = diag_l2_vag_int_recv(d_l2_conn, KWP1281_T_RB_MAX);
754 if (rv < 0) {
755 *errval = rv;
756 return diag_pfwderr(rv);
757 }
758
759 //if it isn't No Acknowledge - Retry, then ok
760 if (d_l2_conn->diag_msg->type != KWP1281_SID_NO_ACK ||
761 d_l2_conn->diag_msg->data[0] != dp->seq_nr - 2) {
762 break;
763 }
764
765 //but if it is, then we will repeat the request
766 DIAG_DBGM(diag_l2_debug, DIAG_DEBUG_PROTO, DIAG_DBGLEVEL_V,
767 FLFMT
768 "Received No Acknowledge - Retry message\n",
769 FL);
770
771 //accept at most KWP1281_NA_RETRIES of No Ack Retry messages in a row
772 if (++na_retry_cnt == KWP1281_NA_RETRIES) {
773 DIAG_DBGM(diag_l2_debug, DIAG_DEBUG_PROTO, DIAG_DBGLEVEL_V,
774 FLFMT
775 "\tbut too many Retry messages in a "
776 "row already - aborting\n",
777 FL);
778
779 *errval = DIAG_ERR_ECUSAIDNO;
780 return diag_pseterr(*errval);
781 }
782 DIAG_DBGM(diag_l2_debug, DIAG_DEBUG_PROTO, DIAG_DBGLEVEL_V,
783 FLFMT "\tso will retry\n", FL);
784
785 //re-send with the previous sequence number
786 //NOTE: SAE J2818 says that "The Message number is NOT incremented by the transmitter for a repeated block."
787 // so we should send the repeated message with the same sequence number as the original message.
788 // However, when testing this on an ECU installed in a European VW the ECU didn't accept such a message
789 // (responded with another NO_ACK Retry) and a repeated message with an incremented sequence number
790 // was accepted.
791 // Can't test this with a VW from USA, so commenting-out for now. If US VWs indeed follow the specification
792 // strictly, then a possible solution would be to set/unset this behaviour based on a flag
793 // (eg. L2_vag specific option for enabling/disabling strict SAE J2818).
794 //dp->seq_nr -= 2;
795 }
796
797 //now it's the requester's responsibility to take care of the telegram
798 rmsg = d_l2_conn->diag_msg;
799 d_l2_conn->diag_msg = NULL;
800
801 return rmsg;
802}
803
804/*
805 * Timeout, - if we don't send something to the ECU it will timeout soon,
806 * so send it a keepalive message now.
807 */
808static void dl2p_vag_timeout(struct diag_l2_conn *d_l2_conn) {
809 struct diag_msg ack;
810 memset(&ack, 0, sizeof(ack));
811 ack.type = KWP1281_SID_ACK;
812
813 DIAG_DBGM(diag_l2_debug, DIAG_DEBUG_TIMER, DIAG_DBGLEVEL_V,
814 FLFMT "timeout impending for %p\n",
815 FL, (void *)d_l2_conn);
816
817 //store the ECU ID address, so that the telegram won't get deleted by send()
818 //(we don't want it to happen because of the keep-alive exchange)
819 struct diag_l2_vag *dp = (struct diag_l2_vag *)d_l2_conn->diag_l2_proto_data;
820 struct diag_msg *ecu_id_telegram = dp->ecu_id_telegram;
821 dp->ecu_id_telegram = NULL;
822
823 //Send the ACK message; important to use l2_send as it updates the timers
824 int rv = diag_l2_send(d_l2_conn, &ack);
825 if (rv < 0) {
826 DIAG_DBGM(diag_l2_debug, DIAG_DEBUG_TIMER, DIAG_DBGLEVEL_V,
827 FLFMT
828 "KW1281 send keep-alive failed with the "
829 "following error:\n\t%s\n",
830 FL, diag_errlookup(rv));
831 return;
832 }
833
834 //we don't have to worry about ECU responding NoAck - it's just a keep-alive exchange
835 //so it's ok as long as neither side timeouts
836 rv = diag_l2_recv(d_l2_conn, 0, NULL, NULL);
837 if (rv < 0) {
838 DIAG_DBGM(diag_l2_debug, DIAG_DEBUG_TIMER, DIAG_DBGLEVEL_V,
839 FLFMT
840 "KW1281 receive keep-alive failed with the following "
841 "error:\n\t%s\n",
842 FL, diag_errlookup(rv));
843 }
844
845 //copy the ECU ID telegram address back where it belongs
846 dp->ecu_id_telegram = ecu_id_telegram;
847}
848
849const struct diag_l2_proto diag_l2_proto_vag = {
850 DIAG_L2_PROT_VAG,
851 "VAG",
852 DIAG_L2_FLAG_KEEPALIVE,
853 dl2p_vag_startcomms,
854 dl2p_vag_stopcomms,
855 dl2p_vag_send,
856 dl2p_vag_recv,
857 dl2p_vag_request,
858 dl2p_vag_timeout
859};
860