-
-
Notifications
You must be signed in to change notification settings - Fork 214
/
Copy pathclient.py
executable file
·2590 lines (1961 loc) · 142 KB
/
client.py
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
from udsoncan import Request, Response, services
from udsoncan.common.Routine import Routine
from udsoncan.common.dtc import Dtc
from udsoncan.common.dids import DataIdentifier
from udsoncan.common.MemoryLocation import MemoryLocation
from udsoncan.common.DynamicDidDefinition import DynamicDidDefinition
from udsoncan.common.CommunicationType import CommunicationType
from udsoncan.common.DataFormatIdentifier import DataFormatIdentifier
from udsoncan.common.Baudrate import Baudrate
from udsoncan.common.IOControls import IOValues, IOMasks
from udsoncan.common.Filesize import Filesize
from udsoncan.connections import BaseConnection
from udsoncan.BaseService import BaseService
from udsoncan.exceptions import *
from udsoncan.configs import default_client_config
from udsoncan.typing import ClientConfig, TypedDict
import logging
import binascii
import functools
import time
from typing import Callable, Optional, Union, Dict, List, Any, cast, Type
class SessionTiming(TypedDict):
p2_server_max: Optional[float]
p2_star_server_max: Optional[float]
class Client:
"""
__init__(self, conn, config=default_client_config, request_timeout = None)
Object that interacts with a UDS server.
It builds a service request, sends it to the server, receives and parses its response, detects communication anomalies and logs what it is doing for further debugging.
:param conn: The underlying protocol interface.
:type conn: :ref:`Connection<Connection>`
:param config: The :ref:`client configuration<client_config>`
:type config: dict
:param request_timeout: Maximum amount of time to wait for a response. This parameter exists for backward compatibility only. For detailed timeout handling, see :ref:`Client configuration<config_timeouts>`
:type request_timeout: int
"""
class SuppressPositiveResponse:
enabled: bool
wait_nrc: bool
def __init__(self):
self.enabled = False
self.wait_nrc = False
def __call__(self, wait_nrc: bool = False):
self.wait_nrc = wait_nrc
return self
def __enter__(self):
self.enabled = True
return self
def __exit__(self, type, value, traceback):
self.enabled = False
self.wait_nrc = None
class PayloadOverrider:
modifier: Optional[Union[Callable, bytes]]
enabled: bool
def __init__(self):
self.modifier = None
self.enabled = False
def __enter__(self):
self.enabled = True
return self
def __exit__(self, type, value, traceback):
self.modifier = None
self.enabled = False
def __call__(self, modifier):
self.modifier = modifier
return self
def get_overrided_payload(self, original_payload: bytes) -> bytes:
assert self.modifier is not None
if callable(self.modifier):
return self.modifier(original_payload)
else:
return self.modifier
conn: BaseConnection
config: ClientConfig
suppress_positive_response: "Client.SuppressPositiveResponse"
payload_override: "Client.PayloadOverrider"
last_response: Optional[Response]
session_timing: SessionTiming
logger: logging.Logger
def __init__(self, conn: BaseConnection, config: ClientConfig = default_client_config, request_timeout: Optional[float] = None):
self.conn = conn
self.config = cast(ClientConfig, dict(config)) # Makes a copy of given configuration
# For backward compatibility
if request_timeout is not None:
self.config['request_timeout'] = request_timeout
self.suppress_positive_response = Client.SuppressPositiveResponse()
self.payload_override = Client.PayloadOverrider()
self.last_response = None
self.session_timing = cast(SessionTiming, dict(p2_server_max=None, p2_star_server_max=None)) # python 3.7 cast
self.refresh_config()
def __enter__(self):
self.open()
return self
def __exit__(self, type, value, traceback):
self.close()
def open(self) -> None:
if not self.conn.is_open():
self.conn.open()
def close(self) -> None:
self.conn.close()
def configure_logger(self) -> None:
logger_name = 'UdsClient'
if 'logger_name' in self.config:
logger_name = "UdsClient[%s]" % self.config['logger_name']
self.logger = logging.getLogger(logger_name)
def set_config(self, key: str, value: Any) -> None:
self.config[key] = value # type:ignore
self.refresh_config()
def set_configs(self, dic: ClientConfig) -> None:
self.config.update(dic)
self.refresh_config()
def refresh_config(self) -> None:
self.configure_logger()
for k in default_client_config:
if k not in self.config:
self.config[k] = default_client_config[k] # type:ignore
self.validate_config()
def validate_config(self) -> None:
if self.config['standard_version'] not in [2006, 2013, 2020]:
raise ConfigError('Valid standard versions are 2006, 2013, 2020. %s is not supported' % self.config['standard_version'])
# Decorator to apply on functions that the user will call.
# Each function raises exceptions. This decorator handles these exceptions, logs them,
# then suppresses them or not depending on the client configuration.
# if func1 and func2 are decorated and func2 calls func1, it should be done this way : self.func1._func_no_error_management(self, ...)
def standard_error_management(func: Callable): # type: ignore
@functools.wraps(func)
def decorated(self: "Client", *args, **kwargs):
try:
return func(self, *args, **kwargs)
except NegativeResponseException as e:
e.response.positive = False
if self.config['exception_on_negative_response']:
logline = '[%s] : %s' % (e.__class__.__name__, str(e))
self.logger.warning(logline)
raise
else:
self.logger.warning(str(e))
return e.response
except InvalidResponseException as e:
e.response.valid = False
if self.config['exception_on_invalid_response']:
self.logger.error('[%s] : %s' % (e.__class__.__name__, str(e)))
raise
else:
self.logger.error(str(e))
return e.response
except UnexpectedResponseException as e:
e.response.unexpected = True
if self.config['exception_on_unexpected_response']:
self.logger.error('[%s] : %s' % (e.__class__.__name__, str(e)))
raise
else:
self.logger.error(str(e))
return e.response
except Exception as e:
self.logger.error('[%s] : %s' % (e.__class__.__name__, str(e)))
raise
decorated._func_no_error_management = func # type:ignore
return decorated
def service_log_prefix(self, service: Type[BaseService]):
return "%s<0x%02x>" % (service.get_name(), service.request_id())
@standard_error_management
def change_session(self, newsession: int) -> Optional[services.DiagnosticSessionControl.InterpretedResponse]:
"""
Requests the server to change the diagnostic session with a :ref:`DiagnosticSessionControl<DiagnosticSessionControl>` service request
:Effective configuration: ``exception_on_<type>_response``
:param newsession: The session to try to switch. Values from :class:`DiagnosticSessionControl.Session <udsoncan.services.DiagnosticSessionControl.Session>` can be used.
:type newsession: int
:return: The server response parsed by :meth:`DiagnosticSessionControl.interpret_response<udsoncan.services.DiagnosticSessionControl.interpret_response>`
:rtype: :ref:`Response<Response>`
"""
req = services.DiagnosticSessionControl.make_request(newsession)
named_newsession = '%s (0x%02x)' % (services.DiagnosticSessionControl.Session.get_name(newsession), newsession)
self.logger.info('%s - Switching session to %s' % (self.service_log_prefix(services.DiagnosticSessionControl), named_newsession))
response = self.send_request(req)
if response is None:
return None
response = services.DiagnosticSessionControl.interpret_response(response, standard_version=self.config['standard_version'])
if newsession != response.service_data.session_echo:
raise UnexpectedResponseException(response, "Response subfunction received from server (0x%02x) does not match the requested subfunction (0x%02x)" % (
response.service_data.session_echo, newsession))
if self.config['standard_version'] > 2006:
assert response.service_data.p2_server_max is not None
assert response.service_data.p2_star_server_max is not None
if self.config['use_server_timing']:
self.logger.info('%s - Received new timing parameters. P2=%.3fs and P2*=%.3fs. Using these value from now on.' %
(self.service_log_prefix(services.DiagnosticSessionControl), response.service_data.p2_server_max, response.service_data.p2_star_server_max))
self.session_timing['p2_server_max'] = response.service_data.p2_server_max
self.session_timing['p2_star_server_max'] = response.service_data.p2_star_server_max
return response
@standard_error_management
def request_seed(self, level: int, data=bytes()) -> Optional[services.SecurityAccess.InterpretedResponse]:
"""
Requests a seed to unlock a security level with the :ref:`SecurityAccess<SecurityAccess>` service
:Effective configuration: ``exception_on_<type>_response``
:param level: The security level to unlock. If value is even, it will be converted to the corresponding odd value
:type level: int
:param data: The data to send to the server (securityAccessDataRecord)
:type data: bytes
:return: The server response parsed by :meth:`SecurityAccess.interpret_response<udsoncan.services.SecurityAccess.interpret_response>`
:rtype: :ref:`Response<Response>`
"""
req = services.SecurityAccess.make_request(level, mode=services.SecurityAccess.Mode.RequestSeed, data=data)
assert req.subfunction is not None
# level may be corrected by service.
self.logger.info('%s - Requesting seed to unlock security access level 0x%02x' %
(self.service_log_prefix(services.SecurityAccess), req.subfunction))
response = self.send_request(req)
if response is None:
return None
response = services.SecurityAccess.interpret_response(response, mode=services.SecurityAccess.Mode.RequestSeed)
assert response.service_data.seed is not None
expected_level = services.SecurityAccess.normalize_level(mode=services.SecurityAccess.Mode.RequestSeed, level=level)
received_level = response.service_data.security_level_echo
if expected_level != received_level:
raise UnexpectedResponseException(
response, "Response subfunction received from server (0x%02x) does not match the requested subfunction (0x%02x)" % (received_level, expected_level))
self.logger.debug('Received seed [%s]' % (binascii.hexlify(response.service_data.seed).decode('ascii')))
return response
# Performs a SecurityAccess service request. Send key
@standard_error_management
def send_key(self, level: int, key: bytes) -> Optional[services.SecurityAccess.InterpretedResponse]:
"""
Sends a key to unlock a security level with the :ref:`SecurityAccess<SecurityAccess>` service
:Effective configuration: ``exception_on_<type>_response``
:param level: The security level to unlock. If value is odd, it will be converted to the corresponding even value
:type level: int
:param key: The key to send to the server
:type key: bytes
:return: The server response parsed by :meth:`SecurityAccess.interpret_response<udsoncan.services.SecurityAccess.interpret_response>`
:rtype: :ref:`Response<Response>`
"""
req = services.SecurityAccess.make_request(level, mode=services.SecurityAccess.Mode.SendKey, data=key)
assert req.subfunction is not None
self.logger.info('%s - Sending key to unlock security access level 0x%02x' %
(self.service_log_prefix(services.SecurityAccess), req.subfunction))
self.logger.debug('\tKey to send [%s]' % (binascii.hexlify(key).decode('ascii')))
response = self.send_request(req)
if response is None:
return None
response = services.SecurityAccess.interpret_response(response, mode=services.SecurityAccess.Mode.SendKey)
expected_level = services.SecurityAccess.normalize_level(mode=services.SecurityAccess.Mode.SendKey, level=level)
received_level = response.service_data.security_level_echo
if expected_level != received_level:
raise UnexpectedResponseException(
response, "Response subfunction received from server (0x%02x) does not match the requested subfunction (0x%02x)" % (received_level, expected_level))
return response
@standard_error_management
def unlock_security_access(self, level, seed_params=bytes()) -> Optional[services.SecurityAccess.InterpretedResponse]:
"""
Successively calls request_seed and send_key to unlock a security level with the :ref:`SecurityAccess<SecurityAccess>` service.
The key computation is done by calling config['security_algo']
:Effective configuration: ``exception_on_<type>_response`` ``security_algo`` ``security_algo_params``
:param level: The level to unlock. Can be the odd or even variant of it.
:type level: int
:param seed_params: Optional data to attach to the RequestSeed request (securityAccessDataRecord).
:type seed_params: bytes
:return: The server response parsed by :meth:`SecurityAccess.interpret_response<udsoncan.services.SecurityAccess.interpret_response>`
:rtype: :ref:`Response<Response>`
"""
if 'security_algo' not in self.config or not callable(self.config['security_algo']):
raise NotImplementedError("Client configuration does not provide a security algorithm")
response = self.request_seed._func_no_error_management(self, level, data=seed_params)
seed = response.service_data.seed
if len(seed) > 0 and seed == b'\x00' * len(seed):
self.logger.info('%s - Security access level 0x%02x is already unlocked, no key will be sent.' %
(self.service_log_prefix(services.SecurityAccess), level))
return response
params = self.config['security_algo_params'] if 'security_algo_params' in self.config else None
# Starting from V1.12, level is now passed to the algorithm.
# We now use named parameters for backward compatibility
algo_params = {}
try:
algo_args = self.config['security_algo'].__code__.co_varnames[:self.config['security_algo'].__code__.co_argcount]
if 'seed' in algo_args:
algo_params['seed'] = seed
if 'level' in algo_args:
algo_params['level'] = level
if 'params' in algo_args:
algo_params['params'] = params
except:
algo_params = {'seed': seed, 'params': params, 'level': level}
key = self.config['security_algo'].__call__(**algo_params) # type: ignore
return self.send_key._func_no_error_management(self, level, key)
@standard_error_management
def tester_present(self) -> Optional[services.TesterPresent.InterpretedResponse]:
"""
Sends a TesterPresent request to keep the session active.
:Effective configuration: ``exception_on_<type>_response``
:return: The server response parsed by :meth:`TesterPresent.interpret_response<udsoncan.services.TesterPresent.interpret_response>`
:rtype: :ref:`Response<Response>`
"""
req = services.TesterPresent.make_request()
assert req.subfunction is not None
self.logger.info('%s - Sending TesterPresent request' % (self.service_log_prefix(services.TesterPresent)))
response = self.send_request(req)
if response is None:
return None
response = services.TesterPresent.interpret_response(response)
if req.subfunction != response.service_data.subfunction_echo:
raise UnexpectedResponseException(response, "Response subfunction received from server (0x%02x) does not match the requested subfunction (0x%02x)" % (
response.service_data.subfunction_echo, req.subfunction))
return response
@standard_error_management
def read_data_by_identifier_first(self, didlist: Union[int, List[int]]) -> Optional[Any]:
"""
Shortcut to extract a single DID.
Calls read_data_by_identifier then returns the first DID asked for.
:Effective configuration: ``exception_on_<type>_response`` ``data_identifiers`` ``tolerate_zero_padding``
:param didlist: The list of DID to be read
:type didlist: list[int]
:return: The server response parsed by :meth:`ReadDataByIdentifier.interpret_response<udsoncan.services.ReadDataByIdentifier.interpret_response>`
:rtype: :ref:`Response<Response>`
"""
didlist = services.ReadDataByIdentifier.validate_didlist_input(didlist)
response = self.read_data_by_identifier(didlist)
values = response.service_data.values
if len(values) > 0 and len(didlist) > 0:
return values[didlist[0]]
return None
@standard_error_management
def test_data_identifier(self, didlist: Union[int, List[int]]) -> Optional[Response]:
"""
Sends a request for the ReadDataByIdentifier and returns blindly the received response without parsing.
The requested DIDs do not have to be inside the client list of supported DID.
This method can be useful for testing if a DID exists on an ECU
:Effective configuration: ``exception_on_<type>_response``
:param didlist: The DIDs to peek
:type didlist: list[int]
:return: The raw server response. The response will not be parsed by any service, causing ``service_data`` to always be ``None``
:rtype: :ref:`Response<Response>`
"""
# Do the validation. No need to read return value as we enforced a single DID already
didlist = services.ReadDataByIdentifier.validate_didlist_input(didlist)
req = services.ReadDataByIdentifier.make_request(didlist=didlist, didconfig=None) # No config
return self.send_request(req)
@standard_error_management
def read_data_by_identifier(self, didlist: Union[int, List[int]]) -> Optional[services.ReadDataByIdentifier.InterpretedResponse]:
"""
Requests a value associated with a data identifier (DID) through the :ref:`ReadDataByIdentifier<ReadDataByIdentifier>` service.
:Effective configuration: ``exception_on_<type>_response`` ``data_identifiers`` ``tolerate_zero_padding``
See :ref:`an example<reading_a_did>` about how to read a DID
:param didlist: The list of DID to be read
:type didlist: list[int]
:return: The server response parsed by :meth:`ReadDataByIdentifier.interpret_response<udsoncan.services.ReadDataByIdentifier.interpret_response>`
:rtype: :ref:`Response<Response>`
"""
didlist = services.ReadDataByIdentifier.validate_didlist_input(didlist)
req = services.ReadDataByIdentifier.make_request(didlist=didlist, didconfig=self.config['data_identifiers'])
if len(didlist) == 1:
self.logger.info("%s - Reading data identifier : 0x%04x (%s)" %
(self.service_log_prefix(services.ReadDataByIdentifier), didlist[0], DataIdentifier.name_from_id(didlist[0])))
else:
self.logger.info("%s - Reading %d data identifier : %s" %
(self.service_log_prefix(services.ReadDataByIdentifier), len(didlist), list(map(hex, didlist))))
if 'data_identifiers' not in self.config or not isinstance(self.config['data_identifiers'], dict):
raise ConfigError('Configuration does not contains a valid data identifier description.')
response = self.send_request(req)
if response is None:
return None
try:
response = services.ReadDataByIdentifier.interpret_response(response,
didlist=didlist,
didconfig=self.config['data_identifiers'],
tolerate_zero_padding=self.config['tolerate_zero_padding']
)
except ConfigError as e:
if e.key in didlist:
raise
else:
raise UnexpectedResponseException(
response, "Server returned values for data identifier 0x%04x that was not requested and no Codec was defined for it. Parsing must be stopped." % (e.key))
set_request_didlist = set(didlist)
set_response_didlist = set(response.service_data.values.keys())
extra_did = set_response_didlist - set_request_didlist
missing_did = set_request_didlist - set_response_didlist
if len(extra_did) > 0:
raise UnexpectedResponseException(
response, "Server returned values for %d data identifier that were not requested. Dids are : %s" % (len(extra_did), extra_did))
if len(missing_did) > 0:
raise UnexpectedResponseException(
response, "%d data identifier values are missing from server response. Dids are : %s" % (len(missing_did), missing_did))
return response
# Performs a WriteDataByIdentifier request.
@standard_error_management
def write_data_by_identifier(self, did: int, value: Any) -> Optional[services.WriteDataByIdentifier.InterpretedResponse]:
"""
Requests to write a value associated with a data identifier (DID) through the :ref:`WriteDataByIdentifier<WriteDataByIdentifier>` service.
:Effective configuration: ``exception_on_<type>_response`` ``data_identifiers``
:param did: The DID to write its value
:type did: int
:param value: Value given to the :ref:`DidCodec <DidCodec>`.encode method. The payload returned by the codec will be sent to the server.
:type value: int
:return: The server response parsed by :meth:`WriteDataByIdentifier.interpret_response<udsoncan.services.WriteDataByIdentifier.interpret_response>`
:rtype: :ref:`Response<Response>`
"""
req = services.WriteDataByIdentifier.make_request(did, value, didconfig=self.config['data_identifiers'])
self.logger.info("%s - Writing data identifier 0x%04x (%s)" %
(self.service_log_prefix(services.WriteDataByIdentifier), did, DataIdentifier.name_from_id(did)))
response = self.send_request(req)
if response is None:
return None
response = services.WriteDataByIdentifier.interpret_response(response)
if response.service_data.did_echo != did:
raise UnexpectedResponseException(
response, "Server returned a response for data identifier 0x%04x while client requested for did 0x%04x" % (response.service_data.did_echo, did))
return response
@standard_error_management
def ecu_reset(self, reset_type: int) -> Optional[services.ECUReset.InterpretedResponse]:
"""
Requests the server to execute a reset sequence through the :ref:`ECUReset<ECUReset>` service.
:Effective configuration: ``exception_on_<type>_response``
:param reset_type: The type of reset to perform. :class:`ECUReset.ResetType<udsoncan.services.ECUReset.ResetType>`
:type reset_type: int
:return: The server response parsed by :meth:`ECUReset.interpret_response<udsoncan.services.ECUReset.interpret_response>`
:rtype: :ref:`Response<Response>`
"""
req = services.ECUReset.make_request(reset_type)
self.logger.info("%s - Requesting reset of type 0x%02x (%s)" %
(self.service_log_prefix(services.ECUReset), reset_type, services.ECUReset.ResetType.get_name(reset_type)))
response = self.send_request(req)
if response is None:
return None
response = services.ECUReset.interpret_response(response)
if response.service_data.reset_type_echo != reset_type:
raise UnexpectedResponseException(response, "Response subfunction received from server (0x%02x) does not match the requested subfunction (0x%02x)" % (
response.service_data.reset_type_echo, reset_type))
if response.service_data.reset_type_echo == services.ECUReset.ResetType.enableRapidPowerShutDown and response.service_data.powerdown_time != 0xFF:
assert response.service_data.powerdown_time is not None
self.logger.info('Server will shutdown in %d seconds.' % (response.service_data.powerdown_time))
return response
@standard_error_management
def clear_dtc(self, group: int = 0xFFFFFF, memory_selection: Optional[int] = None) -> Optional[services.ClearDiagnosticInformation.InterpretedResponse]:
"""
Requests the server to clear its active Diagnostic Trouble Codes with the :ref:`ClearDiagnosticInformation<ClearDiagnosticInformation>` service.
:Effective configuration: ``exception_on_<type>_response``. ``standard_version``
:param group: The group of DTCs to clear. It may refer to Powertrain DTCs, Chassis DTCs, etc. Values are defined by the ECU manufacturer except for two specific values
- ``0x000000`` : Emissions-related systems
- ``0xFFFFFF`` : All DTCs
:type group: int
:param memory_selection: MemorySelection byte (0-0xFF). This value is user defined and introduced in 2020 version of ISO-14229-1.
Only added to the request payload when different from None. Default : None
:type memory_selection: int
:return: The server response parsed by :meth:`ClearDiagnosticInformation.interpret_response<udsoncan.services.ClearDiagnosticInformation.interpret_response>`
:rtype: :ref:`Response<Response>`
"""
request = services.ClearDiagnosticInformation.make_request(
group, memory_selection=memory_selection, standard_version=self.config['standard_version'])
memys_str = ''
if memory_selection is not None:
memys_str = ' , MemorySelection : %d' % memory_selection
if group == 0xFFFFFF:
self.logger.info('%s - Clearing all DTCs (group mask : 0xFFFFFF%s)' %
(self.service_log_prefix(services.ClearDiagnosticInformation), memys_str))
else:
self.logger.info('%s - Clearing DTCs matching group mask : 0x%06x%s' %
(self.service_log_prefix(services.ClearDiagnosticInformation), group, memys_str))
response = self.send_request(request)
if response is None:
return None
response = services.ClearDiagnosticInformation.interpret_response(response)
return response
# Performs a RoutineControl Service request
def start_routine(self, routine_id: int, data: Optional[bytes] = None) -> Optional[services.RoutineControl.InterpretedResponse]:
"""
Requests the server to start a routine through the :ref:`RoutineControl<RoutineControl>` service (subfunction = 0x01).
:Effective configuration: ``exception_on_<type>_response``
:param routine_id: The 16-bit numerical ID of the routine to start
:type group: int
:param data: Optional additional data to give to the server
:type data: bytes
:return: The server response parsed by :meth:`RoutineControl.interpret_response<udsoncan.services.RoutineControl.interpret_response>`
:rtype: :ref:`Response<Response>`
"""
return self.routine_control(routine_id, services.RoutineControl.ControlType.startRoutine, data)
# Performs a RoutineControl Service request
def stop_routine(self, routine_id: int, data: Optional[bytes] = None) -> Optional[services.RoutineControl.InterpretedResponse]:
"""
Requests the server to stop a routine through the :ref:`RoutineControl<RoutineControl>` service (subfunction = 0x02).
:Effective configuration: ``exception_on_<type>_response``
:param routine_id: The 16-bit numerical ID of the routine to stop
:type group: int
:param data: Optional additional data to give to the server
:type data: bytes
:return: The server response parsed by :meth:`RoutineControl.interpret_response<udsoncan.services.RoutineControl.interpret_response>`
:rtype: :ref:`Response<Response>`
"""
return self.routine_control(routine_id, services.RoutineControl.ControlType.stopRoutine, data)
# Performs a RoutineControl Service request
def get_routine_result(self, routine_id: int, data: Optional[bytes] = None) -> Optional[services.RoutineControl.InterpretedResponse]:
"""
Requests the server to send back the execution result of the specified routine through the :ref:`RoutineControl<RoutineControl>` service (subfunction = 0x03).
:Effective configuration: ``exception_on_<type>_response``
:param routine_id: The 16-bit numerical ID of the routine
:type group: int
:param data: Optional additional data to give to the server
:type data: bytes
:return: The server response parsed by :meth:`RoutineControl.interpret_response<udsoncan.services.RoutineControl.interpret_response>`
:rtype: :ref:`Response<Response>`
"""
return self.routine_control(routine_id, services.RoutineControl.ControlType.requestRoutineResults, data)
# Performs a RoutineControl Service request
@standard_error_management
def routine_control(self, routine_id: int, control_type: int, data: Optional[bytes] = None) -> Optional[services.RoutineControl.InterpretedResponse]:
"""
Sends a generic request for the :ref:`RoutineControl<RoutineControl>` service with custom subfunction (control_type).
:Effective configuration: ``exception_on_<type>_response``
:param control_type: The service subfunction. See :class:`RoutineControl.ControlType<udsoncan.services.RoutineControl.ControlType>`
:type group: int
:param routine_id: The 16-bit numerical ID of the routine
:type group: int
:param data: Optional additional data to give to the server
:type data: bytes
:return: The server response parsed by :meth:`RoutineControl.interpret_response<udsoncan.services.RoutineControl.interpret_response>`
:rtype: :ref:`Response<Response>`
"""
request = services.RoutineControl.make_request(routine_id, control_type, data=data)
payload_length = 0 if data is None else len(data)
action = "ISOSAEReserved action for routine ID"
if control_type == services.RoutineControl.ControlType.startRoutine:
action = "Starting routine ID"
elif control_type == services.RoutineControl.ControlType.stopRoutine:
action = "Stoping routine ID"
elif control_type == services.RoutineControl.ControlType.requestRoutineResults:
action = "Requesting result for routine ID"
self.logger.info("%s - ControlType=0x%02x - %s 0x%04x (%s) with a payload of %d bytes" %
(self.service_log_prefix(services.RoutineControl), control_type, action, routine_id, Routine.name_from_id(routine_id), payload_length))
if data is not None:
self.logger.debug("\tPayload data : %s" % binascii.hexlify(data).decode('ascii'))
response = self.send_request(request)
if response is None:
return None
response = services.RoutineControl.interpret_response(response)
if control_type != response.service_data.control_type_echo:
raise UnexpectedResponseException(response, "Control type of response (0x%02x) does not match request control type (0x%02x)" % (
response.service_data.control_type_echo, control_type))
if routine_id != response.service_data.routine_id_echo:
raise UnexpectedResponseException(response, "Response received from server (ID = 0x%04x) does not match the requested routine ID (0x%04x)" % (
response.service_data.routine_id_echo, routine_id))
return response
def read_extended_timing_parameters(self) -> Optional[services.AccessTimingParameter.InterpretedResponse]:
"""
Reads the timing parameters from the server with :ref:`AccessTimingParameter<AccessTimingParameter>` service with subfunction ``readExtendedTimingParameterSet`` (0x01).
:Effective configuration: ``exception_on_<type>_response``
:return: The server response parsed by :meth:`AccessTimingParameter.interpret_response<udsoncan.services.AccessTimingParameter.interpret_response>`
:rtype: :ref:`Response<Response>`
"""
return self.access_timing_parameter(access_type=services.AccessTimingParameter.AccessType.readExtendedTimingParameterSet)
def reset_default_timing_parameters(self) -> Optional[services.AccessTimingParameter.InterpretedResponse]:
"""
Resets the server timing parameters to their default value with :ref:`AccessTimingParameter<AccessTimingParameter>` service with subfunction ``setTimingParametersToDefaultValues`` (0x02).
:Effective configuration: ``exception_on_<type>_response``
:return: The server response parsed by :meth:`AccessTimingParameter.interpret_response<udsoncan.services.AccessTimingParameter.interpret_response>`
:rtype: :ref:`Response<Response>`
"""
return self.access_timing_parameter(access_type=services.AccessTimingParameter.AccessType.setTimingParametersToDefaultValues)
def read_active_timing_parameters(self) -> Optional[services.AccessTimingParameter.InterpretedResponse]:
"""
Reads the currently active timing parameters from the server with :ref:`AccessTimingParameter<AccessTimingParameter>` service with subfunction ``readCurrentlyActiveTimingParameters`` (0x03).
:Effective configuration: ``exception_on_<type>_response``
:return: The server response parsed by :meth:`AccessTimingParameter.interpret_response<udsoncan.services.AccessTimingParameter.interpret_response>`
:rtype: :ref:`Response<Response>`
"""
return self.access_timing_parameter(access_type=services.AccessTimingParameter.AccessType.readCurrentlyActiveTimingParameters)
def set_timing_parameters(self, params: bytes) -> Optional[services.AccessTimingParameter.InterpretedResponse]:
"""
Sets the timing parameters into the server with :ref:`AccessTimingParameter<AccessTimingParameter>` service with subfunction ``setTimingParametersToGivenValues`` (0x04).
:Effective configuration: ``exception_on_<type>_response``
:param params: The parameters data. Specific to each ECU.
:type params: bytes
:return: The server response parsed by :meth:`AccessTimingParameter.interpret_response<udsoncan.services.AccessTimingParameter.interpret_response>`
:rtype: :ref:`Response<Response>`
"""
return self.access_timing_parameter(access_type=services.AccessTimingParameter.AccessType.setTimingParametersToGivenValues, timing_param_record=params)
@standard_error_management
def access_timing_parameter(self,
access_type: int,
timing_param_record: Optional[bytes] = None
) -> Optional[services.AccessTimingParameter.InterpretedResponse]:
"""
Sends a generic request for :ref:`AccessTimingParameter<AccessTimingParameter>` service with configurable subfunction (access_type).
:Effective configuration: ``exception_on_<type>_response``
:param access_type: The service subfunction. See :class:`AccessTimingParameter.AccessType<udsoncan.services.AccessTimingParameter.AccessType>`
:type access_type: int
:param params: The parameters data. Specific to each ECU.
:type params: bytes
:return: The server response parsed by :meth:`AccessTimingParameter.interpret_response<udsoncan.services.AccessTimingParameter.interpret_response>`
:rtype: :ref:`Response<Response>`
"""
request = services.AccessTimingParameter.make_request(access_type, timing_param_record)
payload_length = 0 if timing_param_record is None else len(timing_param_record)
self.logger.info('%s - AccessType=0x%02x (%s) - Sending request with record payload of %d bytes' % (self.service_log_prefix(
services.AccessTimingParameter), access_type, services.AccessTimingParameter.AccessType.get_name(access_type), payload_length))
if timing_param_record is not None:
self.logger.debug("Payload data : %s" % binascii.hexlify(timing_param_record).decode('ascii'))
response = self.send_request(request)
if response is None:
return None
response = services.AccessTimingParameter.interpret_response(response)
if access_type != response.service_data.access_type_echo:
raise UnexpectedResponseException(response, "Access type of response (0x%02x) does not match request access type (0x%02x)" % (
response.service_data.access_type_echo, access_type))
allowed_response_record_access_type = [
services.AccessTimingParameter.AccessType.readExtendedTimingParameterSet,
services.AccessTimingParameter.AccessType.readCurrentlyActiveTimingParameters
]
if len(response.service_data.timing_param_record) > 0 and access_type not in allowed_response_record_access_type:
self.logger.warning("Server returned data in the AccessTimingParameter response although none was asked")
return response
@standard_error_management
def communication_control(self,
control_type: int,
communication_type: Union[int, bytes, CommunicationType],
node_id: Optional[int] = None,
) -> Optional[services.CommunicationControl.InterpretedResponse]:
"""
Switches the transmission or reception of certain messages on/off with :ref:`CommunicationControl<CommunicationControl>` service.
:Effective configuration: ``exception_on_<type>_response``
:param control_type: The action to request such as enabling or disabling some messages. See :class:`CommunicationControl.ControlType<udsoncan.services.CommunicationControl.ControlType>`. This value can also be ECU manufacturer-specific
:type control_type: int
:param communication_type: Indicates what section of the network and the type of message that should be affected by the command. Refer to :ref:`CommunicationType<CommunicationType>` for more details. If an `integer` or a `bytes` is given, the value will be decoded to create the required :ref:`CommunicationType<CommunicationType>` object
:type communication_type: :ref:`CommunicationType<CommunicationType>`, bytes, int
:param node_id: DTC memory identifier (nodeIdentificationNumber). This value is user defined and introduced in 2013 version of ISO-14229-1.
Possible only when control type is ``enableRxAndDisableTxWithEnhancedAddressInformation`` or ``enableRxAndTxWithEnhancedAddressInformation``
Only added to the request payload when different from None. Default : None
:type node_id: int
:return: The server response parsed by :meth:`CommunicationControl.interpret_response<udsoncan.services.CommunicationControl.interpret_response>`
:rtype: :ref:`Response<Response>`
"""
communication_type = services.CommunicationControl.normalize_communication_type(communication_type)
request = services.CommunicationControl.make_request(
control_type, communication_type, node_id, standard_version=self.config['standard_version'])
self.logger.info('%s - ControlType=0x%02x (%s) - Sending request with a CommunicationType byte of 0x%02x (%s). nodeIdentificationNumber=%s ' % (
self.service_log_prefix(services.CommunicationControl),
control_type,
services.CommunicationControl.ControlType.get_name(control_type),
communication_type.get_byte_as_int(),
str(communication_type),
str(node_id)
)
)
response = self.send_request(request)
if response is None:
return None
response = services.CommunicationControl.interpret_response(response)
if control_type != response.service_data.control_type_echo:
raise UnexpectedResponseException(response, "Control type of response (0x%02x) does not match request control type (0x%02x)" % (
response.service_data.control_type_echo, control_type))
return response
def request_download(self,
memory_location: MemoryLocation,
dfi: Optional[DataFormatIdentifier] = None
) -> Optional[services.RequestDownload.InterpretedResponse]:
"""
Informs the server that the client wants to initiate a download from the client to the server by sending a :ref:`RequestDownload<RequestDownload>` service request.
:Effective configuration: ``exception_on_<type>_response`` ``server_address_format`` ``server_memorysize_format``
:param memory_location: The address and size of the memory block to be written.
:type memory_location: :ref:`MemoryLocation <MemoryLocation>`
:param dfi: Optional :ref:`DataFormatIdentifier <DataFormatIdentifier>` defining the compression and encryption scheme of the data.
If not specified, the default value of 00 will be used, specifying no encryption and no compression
:type dfi: :ref:`DataFormatIdentifier <DataFormatIdentifier>`
:return: The server response parsed by :meth:`RequestDownload.interpret_response<udsoncan.services.RequestDownload.interpret_response>`
:rtype: :ref:`Response<Response>`
"""
response = self.request_upload_download(services.RequestDownload, memory_location, dfi)
return cast(Optional[services.RequestDownload.InterpretedResponse], response)
def request_upload(self,
memory_location: MemoryLocation,
dfi: Optional[DataFormatIdentifier] = None
) -> Optional[services.RequestUpload.InterpretedResponse]:
"""
Informs the server that the client wants to initiate an upload from the server to the client by sending a :ref:`RequestUpload<RequestUpload>` service request.
:Effective configuration: ``exception_on_<type>_response`` ``server_address_format`` ``server_memorysize_format``
:param memory_location: The address and size of the memory block to be written.
:type memory_location: :ref:`MemoryLocation <MemoryLocation>`
:param dfi: Optional :ref:`DataFormatIdentifier <DataFormatIdentifier>` defining the compression and encryption scheme of the data.
If not specified, the default value of 00 will be used, specifying no encryption and no compression
:type dfi: :ref:`DataFormatIdentifier <DataFormatIdentifier>`
:return: The server response parsed by :meth:`RequestUpload.interpret_response<udsoncan.services.RequestUpload.interpret_response>`
:rtype: :ref:`Response<Response>`
"""
response = self.request_upload_download(services.RequestUpload, memory_location, dfi)
return cast(Optional[services.RequestUpload.InterpretedResponse], response)
# Common code for both RequestDownload and RequestUpload services
@standard_error_management
def request_upload_download(self, service_cls, memory_location, dfi=None):
dfi = service_cls.normalize_data_format_identifier(dfi)
if service_cls not in [services.RequestDownload, services.RequestUpload]:
raise ValueError('Service must either be RequestDownload or RequestUpload')
if not isinstance(memory_location, MemoryLocation):
raise ValueError('memory_location must be an instance of MemoryLocation')
# If user does not specify a byte format, we apply the one in client configuration.
if 'server_address_format' in self.config:
memory_location.set_format_if_none(address_format=self.config['server_address_format'])
if 'server_memorysize_format' in self.config:
memory_location.set_format_if_none(memorysize_format=self.config['server_memorysize_format'])
request = service_cls.make_request(memory_location=memory_location, dfi=dfi)
action = ""
if service_cls == services.RequestDownload:
action = "Requesting a download (client to server)"
elif service_cls == services.RequestUpload:
action = "Requesting an upload (server to client)"
else:
raise ValueError("Bad service")
self.logger.info('%s - %s for memory location [%s] and DataFormatIdentifier 0x%02x (%s)' %
(self.service_log_prefix(service_cls), action, str(memory_location), dfi.get_byte_as_int(), str(dfi)))
response = self.send_request(request)
if response is None:
return None
service_cls.interpret_response(response)
return response
@standard_error_management
def transfer_data(self,
sequence_number: int,
data: Optional[bytes] = None
) -> Optional[services.TransferData.InterpretedResponse]:
"""
Transfer a block of data to/from the client to/from the server by sending a :ref:`TransferData<TransferData>` service request and returning the server response.
:Effective configuration: ``exception_on_<type>_response``
:param sequence_number: Corresponds to an 8bit counter that should increment for each new block transferred.
Allowed values are from 0 to 0xFF
:type sequence_number: int
:param data: Optional additional data to send to the server
:type data: bytes
:return: The server response parsed by :meth:`TransferData.interpret_response<udsoncan.services.TransferData.interpret_response>`
:rtype: :ref:`Response<Response>`
"""
request = services.TransferData.make_request(sequence_number, data)
data_len = 0 if data is None else len(data)
self.logger.info('%s - Sending a block of data with SequenceNumber=%d that is %d bytes long .' %
(self.service_log_prefix(services.TransferData), sequence_number, data_len))
if data is not None:
self.logger.debug('Data to transfer : %s' % binascii.hexlify(data).decode('ascii'))
response = self.send_request(request)
if response is None:
return None
response = services.TransferData.interpret_response(response)
if sequence_number != response.service_data.sequence_number_echo:
raise UnexpectedResponseException(response, "Block sequence number of response (0x%02x) does not match request block sequence number (0x%02x)" % (
response.service_data.sequence_number_echo, sequence_number))
return response
@standard_error_management
def request_transfer_exit(self, data: Optional[bytes] = None) -> Optional[services.RequestTransferExit.InterpretedResponse]:
"""
Informs the server that the client wants to stop the data transfer by sending a :ref:`RequestTransferExit<RequestTransferExit>` service request.
:Effective configuration: ``exception_on_<type>_response``
:param data: Optional additional data to send to the server
:type data: bytes
:return: The server response parsed by :meth:`RequestTransferExit.interpret_response<udsoncan.services.RequestTransferExit.interpret_response>`
:rtype: :ref:`Response<Response>`
"""
request = services.RequestTransferExit.make_request(data)