forked from driftregion/iso14229
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathiso14229.c
1913 lines (1688 loc) · 62.1 KB
/
iso14229.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
#include "iso14229.h"
#include <stdarg.h>
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include <assert.h>
// ISO-14229-1:2013 Table 2
#define UDS_MAX_DIAGNOSTIC_SERVICES 0x7F
#define UDS_RESPONSE_SID_OF(request_sid) (request_sid + 0x40)
#define UDS_REQUEST_SID_OF(response_sid) (response_sid - 0x40)
#define UDS_NEG_RESP_LEN 3U
#define UDS_0X10_REQ_LEN 2U
#define UDS_0X10_RESP_LEN 6U
#define UDS_0X11_REQ_MIN_LEN 2U
#define UDS_0X11_RESP_BASE_LEN 2U
#define UDS_0X22_RESP_BASE_LEN 1U
#define UDS_0X27_REQ_BASE_LEN 2U
#define UDS_0X27_RESP_BASE_LEN 2U
#define UDS_0X28_REQ_BASE_LEN 3U
#define UDS_0X28_RESP_LEN 2U
#define UDS_0X2E_REQ_BASE_LEN 3U
#define UDS_0X2E_REQ_MIN_LEN 4U
#define UDS_0X2E_RESP_LEN 3U
#define UDS_0X31_REQ_MIN_LEN 4U
#define UDS_0X31_RESP_MIN_LEN 4U
#define UDS_0X34_REQ_BASE_LEN 3U
#define UDS_0X34_RESP_BASE_LEN 2U
#define UDS_0X35_REQ_BASE_LEN 3U
#define UDS_0X36_REQ_BASE_LEN 2U
#define UDS_0X36_RESP_BASE_LEN 2U
#define UDS_0X37_REQ_BASE_LEN 1U
#define UDS_0X37_RESP_BASE_LEN 1U
#define UDS_0X3E_REQ_MIN_LEN 2U
#define UDS_0X3E_RESP_LEN 2U
#define UDS_0X85_REQ_BASE_LEN 2U
#define UDS_0X85_RESP_LEN 2U
enum UDSDiagnosticServiceId {
kSID_DIAGNOSTIC_SESSION_CONTROL = 0x10,
kSID_ECU_RESET = 0x11,
kSID_CLEAR_DIAGNOSTIC_INFORMATION = 0x14,
kSID_READ_DTC_INFORMATION = 0x19,
kSID_READ_DATA_BY_IDENTIFIER = 0x22,
kSID_READ_MEMORY_BY_ADDRESS = 0x23,
kSID_READ_SCALING_DATA_BY_IDENTIFIER = 0x24,
kSID_SECURITY_ACCESS = 0x27,
kSID_COMMUNICATION_CONTROL = 0x28,
kSID_READ_PERIODIC_DATA_BY_IDENTIFIER = 0x2A,
kSID_DYNAMICALLY_DEFINE_DATA_IDENTIFIER = 0x2C,
kSID_WRITE_DATA_BY_IDENTIFIER = 0x2E,
kSID_INPUT_CONTROL_BY_IDENTIFIER = 0x2F,
kSID_ROUTINE_CONTROL = 0x31,
kSID_REQUEST_DOWNLOAD = 0x34,
kSID_REQUEST_UPLOAD = 0x35,
kSID_TRANSFER_DATA = 0x36,
kSID_REQUEST_TRANSFER_EXIT = 0x37,
kSID_REQUEST_FILE_TRANSFER = 0x38,
kSID_WRITE_MEMORY_BY_ADDRESS = 0x3D,
kSID_TESTER_PRESENT = 0x3E,
kSID_ACCESS_TIMING_PARAMETER = 0x83,
kSID_SECURED_DATA_TRANSMISSION = 0x84,
kSID_CONTROL_DTC_SETTING = 0x85,
kSID_RESPONSE_ON_EVENT = 0x86,
};
// ========================================================================
// Transports
// ========================================================================
#if UDS_TP == UDS_TP_CUSTOM
#else
static UDSTpStatus_t tp_poll(UDSTpHandle_t *hdl) {
assert(hdl);
UDSTpStatus_t status = 0;
#if UDS_TP == UDS_TP_ISOTP_C
UDSTpIsoTpC_t *impl = hdl->impl;
isotp_poll(&impl->phys_link);
isotp_poll(&impl->func_link);
if (impl->phys_link.send_status == ISOTP_SEND_STATUS_INPROGRESS) {
status |= TP_SEND_INPROGRESS;
}
#elif UDS_TP == UDS_TP_LINUX_SOCKET
#endif
return status;
}
#endif
#if UDS_TP == UDS_TP_CUSTOM
#else
static ssize_t tp_recv(struct UDSTpHandle *hdl, void *buf, size_t count, UDSTpAddr_t *ta_type) {
assert(hdl);
assert(ta_type);
assert(buf);
#if UDS_TP == UDS_TP_ISOTP_C
uint16_t size = 0;
int ret = 0;
UDSTpIsoTpC_t *impl = hdl->impl;
struct {
IsoTpLink *link;
UDSTpAddr_t ta_type;
} arr[] = {{&impl->phys_link, kTpAddrTypePhysical}, {&impl->func_link, kTpAddrTypeFunctional}};
for (size_t i = 0; i < sizeof(arr) / sizeof(arr[0]); i++) {
ret = isotp_receive(arr[i].link, buf, count, &size);
switch (ret) {
case ISOTP_RET_OK:
*ta_type = arr[i].ta_type;
return size;
case ISOTP_RET_NO_DATA:
continue;
case ISOTP_RET_ERROR:
return ISOTP_RET_ERROR;
default:
return -2;
}
}
return 0;
#elif UDS_TP == UDS_TP_LINUX_SOCKET
UDSTpLinuxIsoTp_t *impl = (UDSTpLinuxIsoTp_t *)hdl->impl;
int size = 0;
struct {
int fd;
UDSTpAddr_t ta_type;
} arr[] = {{impl->phys_fd, kTpAddrTypePhysical}, {impl->func_fd, kTpAddrTypeFunctional}};
for (size_t i = 0; i < sizeof(arr) / sizeof(arr[0]); i++) {
size = read(arr[i].fd, buf, count);
if (size < 0) {
if (EAGAIN == errno || EWOULDBLOCK == errno) {
continue;
}
printf("read. fd: %d, %s\n", arr[i].fd, strerror(errno));
} else {
*ta_type = arr[i].ta_type;
return size;
}
}
return 0;
#endif
}
#endif
#if UDS_TP == UDS_TP_CUSTOM
#else
static ssize_t tp_send(struct UDSTpHandle *hdl, const void *buf, size_t count,
UDSTpAddr_t ta_type) {
assert(hdl);
#if UDS_TP == UDS_TP_ISOTP_C
UDSTpIsoTpC_t *impl = hdl->impl;
IsoTpLink *link = NULL;
switch (ta_type) {
case kTpAddrTypePhysical:
link = &impl->phys_link;
break;
case kTpAddrTypeFunctional:
link = &impl->func_link;
break;
default:
return -4;
}
int send_status = isotp_send(link, buf, count);
switch (send_status) {
case ISOTP_RET_OK:
return count;
case ISOTP_RET_INPROGRESS:
case ISOTP_RET_OVERFLOW:
default:
return send_status;
}
#elif UDS_TP == UDS_TP_LINUX_SOCKET
UDSTpLinuxIsoTp_t *impl = (UDSTpLinuxIsoTp_t *)hdl->impl;
int fd;
switch (ta_type) {
case kTpAddrTypePhysical:
fd = impl->phys_fd;
break;
case kTpAddrTypeFunctional:
fd = impl->func_fd;
break;
default:
return -4;
}
int result = write(fd, buf, count);
if (result < 0) {
printf("write. fd: %d, errno: %d\n", fd, errno);
perror("");
}
return result;
#endif
}
#endif
#if UDS_TP == UDS_TP_LINUX_SOCKET
static int LinuxSockBind(const char *if_name, uint32_t rxid, uint32_t txid) {
int fd = 0;
if ((fd = socket(AF_CAN, SOCK_DGRAM | SOCK_NONBLOCK, CAN_ISOTP)) < 0) {
perror("Socket");
return -1;
}
struct can_isotp_fc_options fcopts = {
.bs = 0x10,
.stmin = 3,
.wftmax = 0,
};
if (setsockopt(fd, SOL_CAN_ISOTP, CAN_ISOTP_RECV_FC, &fcopts, sizeof(fcopts)) < 0) {
perror("setsockopt");
return -1;
}
struct ifreq ifr;
strcpy(ifr.ifr_name, if_name);
ioctl(fd, SIOCGIFINDEX, &ifr);
struct sockaddr_can addr;
memset(&addr, 0, sizeof(addr));
addr.can_family = AF_CAN;
addr.can_addr.tp.rx_id = rxid;
addr.can_addr.tp.tx_id = txid;
addr.can_ifindex = ifr.ifr_ifindex;
if (bind(fd, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
printf("Bind: %s %s\n", strerror(errno), if_name);
return -1;
}
printf("opened ISO-TP link fd: %d, rxid: %03x, txid: %03x\n", fd, rxid, txid);
return fd;
}
static int LinuxSockTpOpen(UDSTpHandle_t *hdl, const char *if_name, uint32_t phys_rxid,
uint32_t phys_txid, uint32_t func_rxid, uint32_t func_txid) {
assert(if_name);
UDSTpLinuxIsoTp_t *impl = (UDSTpLinuxIsoTp_t *)hdl->impl;
hdl->recv = tp_recv;
hdl->send = tp_send;
hdl->poll = tp_poll;
impl->phys_fd = LinuxSockBind(if_name, phys_rxid, phys_txid);
impl->func_fd = LinuxSockBind(if_name, func_rxid, func_txid);
if (impl->phys_fd < 0 || impl->func_fd < 0) {
return -1;
}
return 0;
}
void LinuxSockTpClose(UDSTpHandle_t *hdl) {
if (hdl) {
UDSTpLinuxIsoTp_t *impl = (UDSTpLinuxIsoTp_t *)hdl->impl;
if (impl) {
if (close(impl->phys_fd) < 0) {
perror("failed to close socket");
}
if (close(impl->func_fd) < 0) {
perror("failed to close socket");
}
}
}
}
#endif // #if UDS_TP == UDS_TP_LINUX_SOCKET
// ========================================================================
// Common
// ========================================================================
#if UDS_CUSTOM_MILLIS
#else
uint32_t UDSMillis() {
#if UDS_ARCH == UDS_ARCH_UNIX
struct timeval te;
gettimeofday(&te, NULL); // get current time
long long milliseconds = te.tv_sec * 1000LL + te.tv_usec / 1000; // calculate milliseconds
return milliseconds;
#endif
}
#endif
static bool UDSSecurityAccessLevelIsReserved(uint8_t securityLevel) {
securityLevel &= 0x3f;
return (0 == securityLevel || (0x43 <= securityLevel && securityLevel >= 0x5E) ||
0x7F == securityLevel);
}
// ========================================================================
// Server
// ========================================================================
typedef uint8_t (*UDSService)(UDSServer_t *self);
static inline uint8_t NegativeResponse(UDSServer_t *self, uint8_t response_code) {
self->send_buf[0] = 0x7F;
self->send_buf[1] = self->recv_buf[0];
self->send_buf[2] = response_code;
self->send_size = UDS_NEG_RESP_LEN;
return response_code;
}
static inline void NoResponse(UDSServer_t *self) { self->send_size = 0; }
static uint8_t _0x10_DiagnosticSessionControl(UDSServer_t *self) {
if (self->recv_size < UDS_0X10_REQ_LEN) {
return NegativeResponse(self, kIncorrectMessageLengthOrInvalidFormat);
}
enum UDSDiagnosticSessionType sessType = self->recv_buf[1] & 0x4F;
if (NULL == self->fn) {
return NegativeResponse(self, kServiceNotSupported);
}
UDSDiagSessCtrlArgs_t args = {
.type = sessType,
.p2_ms = self->p2_ms,
.p2_star_ms = self->p2_star_ms,
};
uint8_t err = self->fn(self, UDS_SRV_EVT_DiagSessCtrl, &args);
if (kPositiveResponse != err) {
return NegativeResponse(self, err);
}
self->sessionType = sessType;
self->p2_ms = args.p2_ms;
self->p2_star_ms = args.p2_star_ms;
switch (sessType) {
case kDefaultSession:
break;
case kProgrammingSession:
case kExtendedDiagnostic:
default:
self->s3_session_timeout_timer = UDSMillis() + self->s3_ms;
break;
}
self->send_buf[0] = UDS_RESPONSE_SID_OF(kSID_DIAGNOSTIC_SESSION_CONTROL);
self->send_buf[1] = sessType;
// UDS-1-2013: Table 29
// resolution: 1ms
self->send_buf[2] = self->p2_ms >> 8;
self->send_buf[3] = self->p2_ms;
// resolution: 10ms
self->send_buf[4] = (self->p2_star_ms / 10) >> 8;
self->send_buf[5] = self->p2_star_ms / 10;
self->send_size = UDS_0X10_RESP_LEN;
return kPositiveResponse;
}
static uint8_t _0x11_ECUReset(UDSServer_t *self) {
uint8_t resetType = self->recv_buf[1] & 0x3F;
if (self->recv_size < UDS_0X11_REQ_MIN_LEN) {
return NegativeResponse(self, kIncorrectMessageLengthOrInvalidFormat);
}
if (NULL == self->fn) {
return NegativeResponse(self, kServiceNotSupported);
}
UDSECUResetArgs_t args = {
.type = resetType,
.powerDownTime = 0,
};
uint8_t err = self->fn(self, UDS_SRV_EVT_EcuReset, &args);
if (kPositiveResponse == err) {
self->notReadyToReceive = true;
self->ecuResetScheduled = true;
} else {
return NegativeResponse(self, err);
}
self->send_buf[0] = UDS_RESPONSE_SID_OF(kSID_ECU_RESET);
self->send_buf[1] = resetType;
if (kEnableRapidPowerShutDown == resetType) {
self->send_buf[2] = args.powerDownTime;
self->send_size = UDS_0X11_RESP_BASE_LEN + 1;
} else {
self->send_size = UDS_0X11_RESP_BASE_LEN;
}
return kPositiveResponse;
}
static uint8_t safe_copy(UDSServer_t *srv, const void *src, uint16_t count) {
if (count <= srv->send_buf_size - srv->send_size) {
memmove(srv->send_buf + srv->send_size, src, count);
srv->send_size += count;
return kPositiveResponse;
}
return kResponseTooLong;
}
static uint8_t _0x22_ReadDataByIdentifier(UDSServer_t *self) {
uint8_t numDIDs;
uint16_t dataId = 0;
uint8_t ret = kPositiveResponse;
self->send_buf[0] = UDS_RESPONSE_SID_OF(kSID_READ_DATA_BY_IDENTIFIER);
self->send_size = 1;
if (NULL == self->fn) {
return NegativeResponse(self, kServiceNotSupported);
}
if (0 != (self->recv_size - 1) % sizeof(uint16_t)) {
return NegativeResponse(self, kIncorrectMessageLengthOrInvalidFormat);
}
numDIDs = self->recv_size / sizeof(uint16_t);
if (0 == numDIDs) {
return NegativeResponse(self, kIncorrectMessageLengthOrInvalidFormat);
}
for (int did = 0; did < numDIDs; did++) {
uint16_t idx = 1 + did * 2;
dataId = (self->recv_buf[idx] << 8) + self->recv_buf[idx + 1];
if (self->send_size + 3 > self->send_buf_size) {
return NegativeResponse(self, kResponseTooLong);
}
uint8_t *copylocation = self->send_buf + self->send_size;
copylocation[0] = dataId >> 8;
copylocation[1] = dataId;
self->send_size += 2;
UDSRDBIArgs_t args = {
.dataId = dataId,
.copy = safe_copy,
};
ret = self->fn(self, UDS_SRV_EVT_ReadDataByIdent, &args);
if (kPositiveResponse != ret) {
return NegativeResponse(self, ret);
}
}
return kPositiveResponse;
}
static uint8_t _0x27_SecurityAccess(UDSServer_t *self) {
uint8_t subFunction = self->recv_buf[1];
uint8_t response = kPositiveResponse;
if (UDSSecurityAccessLevelIsReserved(subFunction)) {
return NegativeResponse(self, kIncorrectMessageLengthOrInvalidFormat);
}
if (NULL == self->fn) {
return NegativeResponse(self, kServiceNotSupported);
}
self->send_buf[0] = UDS_RESPONSE_SID_OF(kSID_SECURITY_ACCESS);
self->send_buf[1] = subFunction;
self->send_size = UDS_0X27_RESP_BASE_LEN;
// Even: sendKey
if (0 == subFunction % 2) {
uint8_t requestedLevel = subFunction - 1;
UDSSecAccessValidateKeyArgs_t args = {
.level = requestedLevel,
.key = &self->recv_buf[UDS_0X27_REQ_BASE_LEN],
.len = self->recv_size - UDS_0X27_REQ_BASE_LEN,
};
response = self->fn(self, UDS_SRV_EVT_SecAccessValidateKey, &args);
if (kPositiveResponse != response) {
return NegativeResponse(self, response);
}
// "requestSeed = 0x01" identifies a fixed relationship between
// "requestSeed = 0x01" and "sendKey = 0x02"
// "requestSeed = 0x03" identifies a fixed relationship between
// "requestSeed = 0x03" and "sendKey = 0x04"
self->securityLevel = requestedLevel;
self->send_size = UDS_0X27_RESP_BASE_LEN;
return kPositiveResponse;
}
// Odd: requestSeed
else {
/* If a server supports security, but the requested security level is already unlocked when
a SecurityAccess ‘requestSeed’ message is received, that server shall respond with a
SecurityAccess ‘requestSeed’ positive response message service with a seed value equal to
zero (0). The server shall never send an all zero seed for a given security level that is
currently locked. The client shall use this method to determine if a server is locked for a
particular security level by checking for a non-zero seed.
*/
if (subFunction == self->securityLevel) {
// Table 52 sends a response of length 2. Use a preprocessor define if this needs
// customizing by the user.
const uint8_t already_unlocked[] = {0x00, 0x00};
return safe_copy(self, already_unlocked, sizeof(already_unlocked));
} else {
UDSSecAccessRequestSeedArgs_t args = {
.level = subFunction,
.dataRecord = &self->recv_buf[UDS_0X27_REQ_BASE_LEN],
.len = self->recv_size - UDS_0X27_REQ_BASE_LEN,
.copySeed = safe_copy,
};
response = self->fn(self, UDS_SRV_EVT_SecAccessRequestSeed, &args);
if (kPositiveResponse != response) {
return NegativeResponse(self, response);
}
if (self->send_size <= UDS_0X27_RESP_BASE_LEN) { // no data was copied
return NegativeResponse(self, kGeneralProgrammingFailure);
}
return kPositiveResponse;
}
}
return NegativeResponse(self, kGeneralProgrammingFailure);
}
static uint8_t _0x28_CommunicationControl(UDSServer_t *self) {
uint8_t controlType = self->recv_buf[1] & 0x7F;
uint8_t communicationType = self->recv_buf[2];
if (self->recv_size < UDS_0X28_REQ_BASE_LEN) {
return NegativeResponse(self, kIncorrectMessageLengthOrInvalidFormat);
}
UDSCommCtrlArgs_t args = {
.ctrlType = controlType,
.commType = communicationType,
};
uint8_t err = self->fn(self, UDS_SRV_EVT_CommCtrl, &args);
if (kPositiveResponse != err) {
return NegativeResponse(self, err);
}
self->send_buf[0] = UDS_RESPONSE_SID_OF(kSID_COMMUNICATION_CONTROL);
self->send_buf[1] = controlType;
self->send_size = UDS_0X28_RESP_LEN;
return kPositiveResponse;
}
static uint8_t _0x2E_WriteDataByIdentifier(UDSServer_t *self) {
uint16_t dataLen = 0;
uint16_t dataId = 0;
uint8_t err = kPositiveResponse;
/* UDS-1 2013 Figure 21 Key 1 */
if (self->recv_size < UDS_0X2E_REQ_MIN_LEN) {
return NegativeResponse(self, kIncorrectMessageLengthOrInvalidFormat);
}
dataId = (self->recv_buf[1] << 8) + self->recv_buf[2];
dataLen = self->recv_size - UDS_0X2E_REQ_BASE_LEN;
UDSWDBIArgs_t args = {
.dataId = dataId,
.data = &self->recv_buf[UDS_0X2E_REQ_BASE_LEN],
.len = dataLen,
};
err = self->fn(self, UDS_SRV_EVT_WriteDataByIdent, &args);
if (kPositiveResponse != err) {
return NegativeResponse(self, err);
}
self->send_buf[0] = UDS_RESPONSE_SID_OF(kSID_WRITE_DATA_BY_IDENTIFIER);
self->send_buf[1] = dataId >> 8;
self->send_buf[2] = dataId;
self->send_size = UDS_0X2E_RESP_LEN;
return kPositiveResponse;
}
static uint8_t _0x31_RoutineControl(UDSServer_t *self) {
uint8_t err = kPositiveResponse;
if (self->recv_size < UDS_0X31_REQ_MIN_LEN) {
return NegativeResponse(self, kIncorrectMessageLengthOrInvalidFormat);
}
uint8_t routineControlType = self->recv_buf[1] & 0x7F;
uint16_t routineIdentifier = (self->recv_buf[2] << 8) + self->recv_buf[3];
UDSRoutineCtrlArgs_t args = {
.ctrlType = routineControlType,
.id = routineIdentifier,
.optionRecord = &self->recv_buf[UDS_0X31_REQ_MIN_LEN],
.len = self->recv_size - UDS_0X31_REQ_MIN_LEN,
.copyStatusRecord = safe_copy,
};
self->send_buf[0] = UDS_RESPONSE_SID_OF(kSID_ROUTINE_CONTROL);
self->send_buf[1] = routineControlType;
self->send_buf[2] = routineIdentifier >> 8;
self->send_buf[3] = routineIdentifier;
self->send_size = UDS_0X31_RESP_MIN_LEN;
switch (routineControlType) {
case kStartRoutine:
case kStopRoutine:
case kRequestRoutineResults:
err = self->fn(self, UDS_SRV_EVT_RoutineCtrl, &args);
if (kPositiveResponse != err) {
return NegativeResponse(self, err);
}
break;
default:
return NegativeResponse(self, kRequestOutOfRange);
}
return kPositiveResponse;
}
static void ResetTransfer(UDSServer_t *srv) {
assert(srv);
srv->xferBlockSequenceCounter = 1;
srv->xferByteCounter = 0;
srv->xferTotalBytes = 0;
srv->xferIsActive = false;
}
static uint8_t _0x34_RequestDownload(UDSServer_t *self) {
uint8_t err;
size_t memoryAddress = 0;
size_t memorySize = 0;
if (self->xferIsActive) {
return NegativeResponse(self, kConditionsNotCorrect);
}
if (self->recv_size < UDS_0X34_REQ_BASE_LEN) {
return NegativeResponse(self, kIncorrectMessageLengthOrInvalidFormat);
}
uint8_t dataFormatIdentifier = self->recv_buf[1];
uint8_t memorySizeLength = (self->recv_buf[2] & 0xF0) >> 4;
uint8_t memoryAddressLength = self->recv_buf[2] & 0x0F;
if (memorySizeLength == 0 || memorySizeLength > sizeof(memorySize)) {
return NegativeResponse(self, kRequestOutOfRange);
}
if (memoryAddressLength == 0 || memoryAddressLength > sizeof(memoryAddress)) {
return NegativeResponse(self, kRequestOutOfRange);
}
if (self->recv_size < UDS_0X34_REQ_BASE_LEN + memorySizeLength + memoryAddressLength) {
return NegativeResponse(self, kIncorrectMessageLengthOrInvalidFormat);
}
for (int byteIdx = 0; byteIdx < memoryAddressLength; byteIdx++) {
uint8_t byte = self->recv_buf[UDS_0X34_REQ_BASE_LEN + byteIdx];
uint8_t shiftBytes = memoryAddressLength - 1 - byteIdx;
memoryAddress |= byte << (8 * shiftBytes);
}
for (int byteIdx = 0; byteIdx < memorySizeLength; byteIdx++) {
uint8_t byte = self->recv_buf[UDS_0X34_REQ_BASE_LEN + memoryAddressLength + byteIdx];
uint8_t shiftBytes = memorySizeLength - 1 - byteIdx;
memorySize |= byte << (8 * shiftBytes);
}
UDSRequestDownloadArgs_t args = {
.addr = (void *)memoryAddress,
.size = memorySize,
.dataFormatIdentifier = dataFormatIdentifier,
.maxNumberOfBlockLength = UDS_SERVER_DEFAULT_XFER_DATA_MAX_BLOCKLENGTH,
};
err = self->fn(self, UDS_SRV_EVT_RequestDownload, &args);
if (args.maxNumberOfBlockLength < 3) {
UDS_DBG_PRINT("ERROR: maxNumberOfBlockLength too short");
return NegativeResponse(self, kGeneralProgrammingFailure);
}
if (kPositiveResponse != err) {
return NegativeResponse(self, err);
}
ResetTransfer(self);
self->xferIsActive = true;
self->xferTotalBytes = memorySize;
// ISO-14229-1:2013 Table 401:
uint8_t lengthFormatIdentifier = sizeof(args.maxNumberOfBlockLength) << 4;
/* ISO-14229-1:2013 Table 396: maxNumberOfBlockLength
This parameter is used by the requestDownload positive response message to
inform the client how many data bytes (maxNumberOfBlockLength) to include in
each TransferData request message from the client. This length reflects the
complete message length, including the service identifier and the
data-parameters present in the TransferData request message.
*/
if (args.maxNumberOfBlockLength > UDS_TP_MTU) {
args.maxNumberOfBlockLength = UDS_TP_MTU;
}
self->send_buf[0] = UDS_RESPONSE_SID_OF(kSID_REQUEST_DOWNLOAD);
self->send_buf[1] = lengthFormatIdentifier;
for (uint8_t idx = 0; idx < sizeof(args.maxNumberOfBlockLength); idx++) {
uint8_t shiftBytes = sizeof(args.maxNumberOfBlockLength) - 1 - idx;
uint8_t byte = args.maxNumberOfBlockLength >> (shiftBytes * 8);
self->send_buf[UDS_0X34_RESP_BASE_LEN + idx] = byte;
}
self->send_size = UDS_0X34_RESP_BASE_LEN + sizeof(args.maxNumberOfBlockLength);
return kPositiveResponse;
}
static uint8_t _0x36_TransferData(UDSServer_t *self) {
uint8_t err = kPositiveResponse;
uint16_t request_data_len = self->recv_size - UDS_0X36_REQ_BASE_LEN;
if (self->recv_size < UDS_0X36_REQ_BASE_LEN) {
err = kIncorrectMessageLengthOrInvalidFormat;
goto fail;
}
uint8_t blockSequenceCounter = self->recv_buf[1];
if (!self->xferIsActive) {
return NegativeResponse(self, kUploadDownloadNotAccepted);
}
if (!self->RCRRP) {
if (blockSequenceCounter != self->xferBlockSequenceCounter) {
err = kRequestSequenceError;
goto fail;
} else {
self->xferBlockSequenceCounter++;
}
}
if (self->xferByteCounter + request_data_len > self->xferTotalBytes) {
err = kTransferDataSuspended;
goto fail;
}
UDSTransferDataArgs_t args = {
.data = &self->recv_buf[UDS_0X36_REQ_BASE_LEN],
.len = self->recv_size - UDS_0X36_REQ_BASE_LEN,
.copyResponse = safe_copy,
};
self->send_buf[0] = UDS_RESPONSE_SID_OF(kSID_TRANSFER_DATA);
self->send_buf[1] = blockSequenceCounter;
self->send_size = UDS_0X36_RESP_BASE_LEN;
err = self->fn(self, UDS_SRV_EVT_TransferData, &args);
switch (err) {
case kPositiveResponse:
self->xferByteCounter += request_data_len;
return kPositiveResponse;
case kRequestCorrectlyReceived_ResponsePending:
return NegativeResponse(self, kRequestCorrectlyReceived_ResponsePending);
default:
err = kGeneralProgrammingFailure;
goto fail;
}
fail:
ResetTransfer(self);
return NegativeResponse(self, err);
}
static uint8_t _0x37_RequestTransferExit(UDSServer_t *self) {
uint8_t err = kPositiveResponse;
if (!self->xferIsActive) {
return NegativeResponse(self, kUploadDownloadNotAccepted);
}
self->send_buf[0] = UDS_RESPONSE_SID_OF(kSID_REQUEST_TRANSFER_EXIT);
self->send_size = UDS_0X37_RESP_BASE_LEN;
UDSRequestTransferExitArgs_t args = {
.data = &self->recv_buf[UDS_0X37_REQ_BASE_LEN],
.len = self->recv_size - UDS_0X37_REQ_BASE_LEN,
.copyResponse = safe_copy,
};
err = self->fn(self, UDS_SRV_EVT_RequestTransferExit, &args);
switch (err) {
case kPositiveResponse:
ResetTransfer(self);
return kPositiveResponse;
case kRequestCorrectlyReceived_ResponsePending:
return NegativeResponse(self, kRequestCorrectlyReceived_ResponsePending);
default:
ResetTransfer(self);
return NegativeResponse(self, err);
}
}
static uint8_t _0x3E_TesterPresent(UDSServer_t *self) {
if (self->recv_size < UDS_0X3E_REQ_MIN_LEN) {
return NegativeResponse(self, kIncorrectMessageLengthOrInvalidFormat);
}
self->s3_session_timeout_timer = UDSMillis() + self->s3_ms;
uint8_t zeroSubFunction = self->recv_buf[1];
self->send_buf[0] = UDS_RESPONSE_SID_OF(kSID_TESTER_PRESENT);
self->send_buf[1] = zeroSubFunction & 0x3F;
self->send_size = UDS_0X3E_RESP_LEN;
return kPositiveResponse;
}
static uint8_t _0x85_ControlDTCSetting(UDSServer_t *self) {
(void)self;
if (self->recv_size < UDS_0X85_REQ_BASE_LEN) {
return NegativeResponse(self, kIncorrectMessageLengthOrInvalidFormat);
}
uint8_t dtcSettingType = self->recv_buf[1] & 0x3F;
self->send_buf[0] = UDS_RESPONSE_SID_OF(kSID_CONTROL_DTC_SETTING);
self->send_buf[1] = dtcSettingType;
self->send_size = UDS_0X85_RESP_LEN;
return kPositiveResponse;
}
/**
* @brief Get the internal service handler matching the given SID.
* @param sid
* @return pointer to UDSService or NULL if no match
*/
static UDSService getServiceForSID(uint8_t sid) {
switch (sid) {
case kSID_DIAGNOSTIC_SESSION_CONTROL:
return _0x10_DiagnosticSessionControl;
case kSID_ECU_RESET:
return _0x11_ECUReset;
case kSID_CLEAR_DIAGNOSTIC_INFORMATION:
return NULL;
case kSID_READ_DTC_INFORMATION:
return NULL;
case kSID_READ_DATA_BY_IDENTIFIER:
return _0x22_ReadDataByIdentifier;
case kSID_READ_MEMORY_BY_ADDRESS:
return NULL;
case kSID_READ_SCALING_DATA_BY_IDENTIFIER:
return NULL;
case kSID_SECURITY_ACCESS:
return _0x27_SecurityAccess;
case kSID_COMMUNICATION_CONTROL:
return _0x28_CommunicationControl;
case kSID_READ_PERIODIC_DATA_BY_IDENTIFIER:
return NULL;
case kSID_DYNAMICALLY_DEFINE_DATA_IDENTIFIER:
return NULL;
case kSID_WRITE_DATA_BY_IDENTIFIER:
return _0x2E_WriteDataByIdentifier;
case kSID_INPUT_CONTROL_BY_IDENTIFIER:
return NULL;
case kSID_ROUTINE_CONTROL:
return _0x31_RoutineControl;
case kSID_REQUEST_DOWNLOAD:
return _0x34_RequestDownload;
case kSID_REQUEST_UPLOAD:
return NULL;
case kSID_TRANSFER_DATA:
return _0x36_TransferData;
case kSID_REQUEST_TRANSFER_EXIT:
return _0x37_RequestTransferExit;
case kSID_REQUEST_FILE_TRANSFER:
return NULL;
case kSID_WRITE_MEMORY_BY_ADDRESS:
return NULL;
case kSID_TESTER_PRESENT:
return _0x3E_TesterPresent;
case kSID_ACCESS_TIMING_PARAMETER:
return NULL;
case kSID_SECURED_DATA_TRANSMISSION:
return NULL;
case kSID_CONTROL_DTC_SETTING:
return _0x85_ControlDTCSetting;
case kSID_RESPONSE_ON_EVENT:
return NULL;
default:
UDS_DBG_PRINT("no handler for request SID %x.\n", sid);
return NULL;
}
}
/**
* @brief Call the service if it exists, modifying the response if the spec calls for it.
* @note see UDS-1 2013 7.5.5 Pseudo code example of server response behavior
*
* @param self
* @param addressingScheme
*/
static uint8_t evaluateServiceResponse(UDSServer_t *self, const uint8_t addressingScheme) {
uint8_t response = kPositiveResponse;
bool suppressResponse = false;
uint8_t sid = self->recv_buf[0];
UDSService service = getServiceForSID(sid);
if (NULL == service || NULL == self->fn) {
return NegativeResponse(self, kServiceNotSupported);
}
switch (sid) {
/* CASE Service_with_sub-function */
/* test if service with sub-function is supported */
case kSID_DIAGNOSTIC_SESSION_CONTROL:
case kSID_ECU_RESET:
case kSID_READ_DTC_INFORMATION:
case kSID_SECURITY_ACCESS:
case kSID_COMMUNICATION_CONTROL:
case kSID_ROUTINE_CONTROL:
case kSID_TESTER_PRESENT:
case kSID_ACCESS_TIMING_PARAMETER:
case kSID_SECURED_DATA_TRANSMISSION:
case kSID_CONTROL_DTC_SETTING:
case kSID_RESPONSE_ON_EVENT: {
/* check minimum length of message with sub-function */
if (self->recv_size >= 2) {
/* get sub-function parameter value without bit 7 */
// switch (ctx->req.as.raw[0] & 0x7F) {
// }
// Let the service callback determine whether or not the sub-function parameter value is
// supported
response = service(self);
} else {
/* NRC 0x13: incorrectMessageLengthOrInvalidFormat */
response = kIncorrectMessageLengthOrInvalidFormat;
}
bool suppressPosRspMsgIndicationBit = self->recv_buf[1] & 0x80;
/* test if positive response is required and if responseCode is positive 0x00 */
if ((suppressPosRspMsgIndicationBit) && (response == kPositiveResponse) &&
(
// TODO: *not yet a NRC 0x78 response sent*
true)) {
suppressResponse = true;
} else {
suppressResponse = false;
}
break;
}
/* CASE Service_without_sub-function */
/* test if service without sub-function is supported */
case kSID_READ_DATA_BY_IDENTIFIER:
case kSID_READ_MEMORY_BY_ADDRESS:
case kSID_READ_SCALING_DATA_BY_IDENTIFIER:
case kSID_READ_PERIODIC_DATA_BY_IDENTIFIER:
case kSID_DYNAMICALLY_DEFINE_DATA_IDENTIFIER:
case kSID_WRITE_DATA_BY_IDENTIFIER:
case kSID_REQUEST_DOWNLOAD:
case kSID_REQUEST_UPLOAD:
case kSID_TRANSFER_DATA:
case kSID_REQUEST_TRANSFER_EXIT:
case kSID_REQUEST_FILE_TRANSFER:
case kSID_WRITE_MEMORY_BY_ADDRESS:
case kSID_CLEAR_DIAGNOSTIC_INFORMATION:
case kSID_INPUT_CONTROL_BY_IDENTIFIER: {
response = service(self);
break;
}
default: {
response = kServiceNotSupported;
break;
}
}
if ((kTpAddrTypeFunctional == addressingScheme) &&
((kServiceNotSupported == response) || (kSubFunctionNotSupported == response) ||
(kServiceNotSupportedInActiveSession == response) ||
(kSubFunctionNotSupportedInActiveSession == response) ||
(kRequestOutOfRange == response)) &&
(
// TODO: *not yet a NRC 0x78 response sent*
true)) {
suppressResponse = true; /* Suppress negative response message */
NoResponse(self);
} else {
if (suppressResponse) { /* Suppress positive response message */
NoResponse(self);
} else { /* send negative or positive response */
;
}
}
return response;
}
/**
* @brief Process the data on this link
*
* @param self
* @param link transport handle
* @param addressingScheme
*/