-
-
Notifications
You must be signed in to change notification settings - Fork 82
/
Copy pathprotocol.py
executable file
·1821 lines (1480 loc) · 83.2 KB
/
protocol.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
__all__ = [
'PDU',
'RateLimiter',
'TransportLayerLogic',
'TransportLayer',
'CanStack',
'NotifierBasedCanStack'
]
from isotp.can_message import CanMessage
from isotp.tools import Timer, FiniteByteGenerator
import isotp.address
import isotp.errors
import queue
import logging
from copy import copy
import binascii
import time
import math
import enum
from dataclasses import dataclass
import threading
import inspect
import functools
from collections.abc import Iterable
from typing import Optional, Any, List, Callable, Dict, Tuple, Union, Generator, cast
try:
import can
_can_available = True
except ImportError:
_can_available = False
def is_documented_by(original: Callable[[Any], Any]) -> Callable[[Any], Any]:
def wrapper(target: Callable[[Any], Any]) -> Callable[[Any], Any]:
target.__doc__ = original.__doc__
return target
return wrapper
class PDU:
"""
Converts a CAN Message into a meaningful PDU such as SingleFrame, FirstFrame, ConsecutiveFrame, FlowControl
:param msg: The CAN message
:type msg: `isotp.protocol.CanMessage`
"""
__slots__ = 'type', 'length', 'data', 'blocksize', 'stmin', 'stmin_sec', 'seqnum', 'flow_status', 'rx_dl', 'escape_sequence', 'can_dl'
class Type:
SINGLE_FRAME = 0
FIRST_FRAME = 1
CONSECUTIVE_FRAME = 2
FLOW_CONTROL = 3
class FlowStatus:
ContinueToSend = 0
Wait = 1
Overflow = 2
type: int
length: Optional[int]
data: bytes
blocksize: Optional[int]
stmin: Optional[int]
stmin_sec: Optional[float]
seqnum: Optional[int]
flow_status: Optional[int]
rx_dl: int
escape_sequence: bool
can_dl: int
def __init__(self, msg: CanMessage, start_of_data: int = 0) -> None:
self.data = bytes()
self.length = None
self.blocksize = None
self.stmin = None
self.stmin_sec = None
self.seqnum = None
self.flow_status = None
self.escape_sequence = False
if len(msg.data) < start_of_data:
raise ValueError("Received message is missing data according to prefix size")
self.can_dl = len(msg.data)
self.rx_dl = max(8, self.can_dl)
msg_data = msg.data[start_of_data:]
datalen = len(msg_data)
# Guarantee at least presence of byte #1
if datalen > 0:
hnb = (msg_data[0] >> 4) & 0xF
if hnb > 3:
raise ValueError('Received message with unknown frame type %d' % hnb)
self.type = int(hnb)
else:
raise ValueError('Empty CAN frame')
if self.type == self.Type.SINGLE_FRAME:
length_placeholder = int(msg_data[0]) & 0xF
if length_placeholder != 0:
self.length = length_placeholder
if self.length > datalen - 1:
raise ValueError("Received Single Frame with length of %d while there is room for %d bytes of data with this configuration" % (
self.length, datalen - 1))
self.data = msg_data[1:][:self.length]
else: # Escape sequence
if datalen < 2:
raise ValueError('Single frame with escape sequence must be at least %d bytes long with this configuration' % (2 + start_of_data))
self.escape_sequence = True
self.length = int(msg_data[1])
if self.length == 0:
raise ValueError("Received Single Frame with length of 0 bytes")
if self.length > datalen - 2:
raise ValueError("Received Single Frame with length of %d while there is room for %d bytes of data with this configuration" % (
self.length, datalen - 2))
self.data = msg_data[2:][:self.length]
elif self.type == self.Type.FIRST_FRAME:
if datalen < 2:
raise ValueError('First frame without escape sequence must be at least %d bytes long with this configuration' % (2 + start_of_data))
length_placeholder = ((int(msg_data[0]) & 0xF) << 8) | int(msg_data[1])
if length_placeholder != 0: # Frame is maximum 4095 bytes
self.length = length_placeholder
self.data = msg_data[2:][:min(self.length, datalen - 2)]
else: # Frame is larger than 4095 bytes
if datalen < 6:
raise ValueError('First frame with escape sequence must be at least %d bytes long with this configuration' % (6 + start_of_data))
self.escape_sequence = True
self.length = (msg_data[2] << 24) | (msg_data[3] << 16) | (msg_data[4] << 8) | (msg_data[5] << 0)
self.data = msg_data[6:][:min(self.length, datalen - 6)]
elif self.type == self.Type.CONSECUTIVE_FRAME:
self.seqnum = int(msg_data[0]) & 0xF
self.data = msg_data[1:] # No need to check size as this will return empty data if overflow.
elif self.type == self.Type.FLOW_CONTROL:
if datalen < 3:
raise ValueError('Flow Control frame must be at least %d bytes with the actual configuration' % (3 + start_of_data))
self.flow_status = int(msg_data[0]) & 0xF
if self.flow_status >= 3:
raise ValueError('Unknown flow status')
self.blocksize = int(msg_data[1])
stmin_temp = int(msg_data[2])
if stmin_temp >= 0 and stmin_temp <= 0x7F:
self.stmin_sec = stmin_temp / 1000
elif stmin_temp >= 0xf1 and stmin_temp <= 0xF9:
self.stmin_sec = (stmin_temp - 0xF0) / 10000
if self.stmin_sec is None:
raise ValueError('Invalid StMin received in Flow Control')
else:
self.stmin = stmin_temp
else:
raise ValueError("Unsupported PDU type: %s" % self.type)
@classmethod
def craft_flow_control_data(cls, flow_status: int, blocksize: int, stmin: int) -> bytes:
return bytes([(0x30 | (flow_status) & 0xF), blocksize & 0xFF, stmin & 0xFF])
def name(self) -> str:
if self.type is None:
return "[None]"
if self.type == self.Type.SINGLE_FRAME:
return "SINGLE_FRAME"
elif self.type == self.Type.FIRST_FRAME:
return "FIRST_FRAME"
elif self.type == self.Type.CONSECUTIVE_FRAME:
return "CONSECUTIVE_FRAME"
elif self.type == self.Type.FLOW_CONTROL:
return "FLOW_CONTROL"
else:
return "Reserved"
class RateLimiter:
TIME_SLOT_LENGTH = 0.005
enabled: bool
mean_bitrate: float
window_size_sec: float
error_reason: str
burst_bitcount: List[int]
burst_time: List[float]
bit_total: int
window_bit_max: float
def __init__(self, mean_bitrate: float = 10000000, window_size_sec: float = 0.1) -> None:
self.enabled = False
self.mean_bitrate = mean_bitrate
self.window_size_sec = window_size_sec
self.error_reason = ''
self.reset()
if self.can_be_enabled():
self.enable()
def can_be_enabled(self) -> bool:
try:
float(self.mean_bitrate)
except:
self.error_reason = 'mean_bitrate is not numerical'
return False
if float(self.mean_bitrate) <= 0:
self.error_reason = 'mean_bitrate must be greater than 0'
return False
try:
float(self.window_size_sec)
except:
self.error_reason = 'window_size_sec is not numerical'
return False
if float(self.window_size_sec) <= 0:
self.error_reason = 'window_size_sec must be greater than 0'
return False
return True
def set_bitrate(self, mean_bitrate: float) -> None:
self.mean_bitrate = mean_bitrate
def enable(self) -> None:
if self.can_be_enabled():
self.mean_bitrate = float(self.mean_bitrate)
self.window_size_sec = float(self.window_size_sec)
self.enabled = True
self.reset()
else:
raise ValueError('Cannot enable Rate Limiter. \n %s' % self.error_reason)
def disable(self) -> None:
self.enabled = False
def reset(self) -> None:
self.burst_bitcount = []
self.burst_time = []
self.bit_total = 0
self.window_bit_max = self.mean_bitrate * self.window_size_sec
def update(self) -> None:
if not self.enabled:
self.reset()
return
t = time.perf_counter()
while len(self.burst_time) > 0:
t2 = self.burst_time[0]
if t - t2 > self.window_size_sec:
self.burst_time.pop(0)
n_to_remove = self.burst_bitcount.pop(0)
self.bit_total -= n_to_remove
else:
break
def allowed_bytes(self) -> int:
no_limit = 0xFFFFFFFF
if not self.enabled:
return no_limit
allowed_bits = max(self.window_bit_max - self.bit_total, 0)
return math.floor(allowed_bits / 8)
def inform_byte_sent(self, datalen: int) -> None:
if self.enabled:
bytelen = datalen * 8
t = time.perf_counter()
self.bit_total += bytelen
if len(self.burst_time) == 0:
self.burst_time.append(t)
self.burst_bitcount.append(bytelen)
else:
last_time = self.burst_time[-1]
if t - last_time > self.TIME_SLOT_LENGTH:
self.burst_time.append(t)
self.burst_bitcount.append(bytelen)
else:
self.burst_bitcount[-1] += bytelen
class TransportLayerLogic:
LOGGER_NAME = 'isotp'
@dataclass(init=False)
class Params:
__slots__ = (
'stmin',
'blocksize',
'override_receiver_stmin',
'rx_flowcontrol_timeout',
'rx_consecutive_frame_timeout',
'tx_padding',
'wftmax',
'tx_data_length',
'tx_data_min_length',
'max_frame_size',
'can_fd',
'bitrate_switch',
'default_target_address_type',
'rate_limit_max_bitrate',
'rate_limit_window_size',
'rate_limit_enable',
'listen_mode',
'blocking_send',
'logger_name',
'wait_func'
)
stmin: int
blocksize: int
override_receiver_stmin: Optional[float]
rx_flowcontrol_timeout: float
rx_consecutive_frame_timeout: float
tx_padding: Optional[int]
wftmax: int
tx_data_length: int
tx_data_min_length: Optional[int]
max_frame_size: int
can_fd: bool
bitrate_switch: bool
default_target_address_type: isotp.TargetAddressType
rate_limit_max_bitrate: int
rate_limit_window_size: float
rate_limit_enable: bool
listen_mode: bool
blocking_send: bool
logger_name: str
wait_func: Callable[[float], None]
def __init__(self) -> None:
self.stmin = 0
self.blocksize = 8
self.override_receiver_stmin = None
self.rx_flowcontrol_timeout = 1000
self.rx_consecutive_frame_timeout = 1000
self.tx_padding = None
self.wftmax = 0
self.tx_data_length = 8
self.tx_data_min_length = None
self.max_frame_size = 4095
self.can_fd = False
self.bitrate_switch = False
self.default_target_address_type = isotp.address.TargetAddressType.Physical
self.rate_limit_max_bitrate = 100000000
self.rate_limit_window_size = 0.2
self.rate_limit_enable = False
self.listen_mode = False
self.blocking_send = False
self.logger_name = TransportLayer.LOGGER_NAME
self.wait_func = time.sleep
def set(self, key: str, val: Any, validate: bool = True) -> None:
param_alias: Dict[str, str] = {
}
if key in param_alias:
key = param_alias[key]
setattr(self, key, val)
if validate:
self.validate()
def validate(self) -> None:
if not isinstance(self.rx_flowcontrol_timeout, int):
raise ValueError('rx_flowcontrol_timeout must be an integer')
if self.rx_flowcontrol_timeout < 0:
raise ValueError('rx_flowcontrol_timeout must be positive integer')
if not isinstance(self.rx_consecutive_frame_timeout, int):
raise ValueError('rx_consecutive_frame_timeout must be an integer')
if self.rx_consecutive_frame_timeout < 0:
raise ValueError('rx_consecutive_frame_timeout must be positive integer')
if self.tx_padding is not None:
if not isinstance(self.tx_padding, int):
raise ValueError('tx_padding must be an integer')
if self.tx_padding < 0 or self.tx_padding > 0xFF:
raise ValueError('tx_padding must be an integer between 0x00 and 0xFF')
if not isinstance(self.stmin, int):
raise ValueError('stmin must be an integer')
if self.stmin < 0 or self.stmin > 0xFF:
raise ValueError('stmin must be positive integer between 0x00 and 0xFF')
if not isinstance(self.blocksize, int):
raise ValueError('blocksize must be an integer')
if self.blocksize < 0 or self.blocksize > 0xFF:
raise ValueError('blocksize must be and integer between 0x00 and 0xFF')
if self.override_receiver_stmin is not None:
if not isinstance(self.override_receiver_stmin, (int, float)) or isinstance(self.override_receiver_stmin, bool):
raise ValueError('override_receiver_stmin must be a float')
self.override_receiver_stmin = float(self.override_receiver_stmin)
if self.override_receiver_stmin < 0 or not math.isfinite(self.override_receiver_stmin):
raise ValueError('Invalid override_receiver_stmin')
if not isinstance(self.wftmax, int):
raise ValueError('wftmax must be an integer')
if self.wftmax < 0:
raise ValueError('wftmax must be and integer equal or greater than 0')
if not isinstance(self.tx_data_length, int):
raise ValueError('tx_data_length must be an integer')
if self.tx_data_length not in [8, 12, 16, 20, 24, 32, 48, 64]:
raise ValueError('tx_data_length must be one of these value : 8, 12, 16, 20, 24, 32, 48, 64 ')
if self.tx_data_min_length is not None:
if not isinstance(self.tx_data_min_length, int):
raise ValueError('tx_data_min_length must be an integer')
if self.tx_data_min_length not in [1, 2, 3, 4, 5, 6, 7, 8, 12, 16, 20, 24, 32, 48, 64]:
raise ValueError('tx_data_min_length must be one of these value : 1, 2, 3, 4, 5, 6, 7, 8, 12, 16, 20, 24, 32, 48, 64 ')
if self.tx_data_min_length > self.tx_data_length:
raise ValueError('tx_data_min_length cannot be greater than tx_data_length')
if not isinstance(self.max_frame_size, int):
raise ValueError('max_frame_size must be an integer')
if self.max_frame_size < 0:
raise ValueError('max_frame_size must be a positive integer')
if not isinstance(self.can_fd, bool):
raise ValueError('can_fd must be a boolean value')
if not isinstance(self.bitrate_switch, bool):
raise ValueError('bitrate_switch must be a boolean value')
if isinstance(self.default_target_address_type, int):
self.default_target_address_type = isotp.TargetAddressType(self.default_target_address_type)
if not isinstance(self.default_target_address_type, isotp.TargetAddressType):
raise ValueError('default_target_address_type must be an integer or a TargetAddressType instance')
if self.default_target_address_type not in [isotp.address.TargetAddressType.Physical, isotp.address.TargetAddressType.Functional]:
raise ValueError('default_target_address_type must be either be Physical (%d) or Functional (%d)' %
(isotp.address.TargetAddressType.Physical.value, isotp.address.TargetAddressType.Functional.value))
if not isinstance(self.rate_limit_max_bitrate, int):
raise ValueError('rate_limit_max_bitrate must be an integer')
if self.rate_limit_max_bitrate <= 0:
raise ValueError('rate_limit_max_bitrate must be greater than 0')
if not (isinstance(self.rate_limit_window_size, float) or isinstance(self.rate_limit_window_size, int)):
raise ValueError('rate_limit_window_size must be a float ')
if self.rate_limit_window_size <= 0:
raise ValueError('rate_limit_window_size must be greater than 0')
if not isinstance(self.rate_limit_enable, bool):
raise ValueError('rate_limit_enable must be a boolean value')
if self.rate_limit_max_bitrate * self.rate_limit_window_size < self.tx_data_length * 8:
raise ValueError(
'Rate limiter is so restrictive that a SingleFrame cannot be sent. Please, allow a higher bitrate or increase the window size. (tx_data_length = %d)' % self.tx_data_length)
if not isinstance(self.listen_mode, bool):
raise ValueError('listen_mode must be a boolean value')
if not isinstance(self.blocking_send, bool):
raise ValueError('blocking_send must be a boolean value')
if not isinstance(self.logger_name, str):
raise ValueError('logger_name must be a string')
if not callable(self.wait_func):
raise ValueError('wait_func should be a callable')
try:
self.wait_func(0.001)
except Exception as e:
raise ValueError("Given wait_func raised an exception %s" % e)
class RxState(enum.Enum):
IDLE = 0
WAIT_CF = 1
class TxState(enum.Enum):
IDLE = 0
WAIT_FC = 1
TRANSMIT_CF = 2
TRANSMIT_SF_STANDBY = 3
TRANSMIT_FF_STANDBY = 4
SendGenerator = Tuple[Generator[int, None, None], int]
@dataclass
class SendRequest:
"""An object representing a call to `TransportLayer.send() by the user. Wraps the given parameter and associate with a completion event and a success flag`"""
generator: FiniteByteGenerator
target_address_type: isotp.address.TargetAddressType
complete_event: threading.Event
success: bool
def __init__(self,
data: Union[bytearray, bytes, "TransportLayerLogic.SendGenerator"],
target_address_type: isotp.address.TargetAddressType
):
if isinstance(data, tuple):
if len(data) != 2:
raise ValueError("Given tuple must have 2 items. A generator and a length")
gen, size = data
self.generator = FiniteByteGenerator(gen, size)
elif isinstance(data, Iterable):
data = cast(Union[bytes, bytearray], data) # type:ignore
self.generator = FiniteByteGenerator((x for x in data), len(data))
else:
raise ValueError("data must be an iterable element (bytes or bytearray) or a tuple of generator,size")
self.consumed_size = 0
self.target_address_type = target_address_type
self.complete_event = threading.Event()
self.success = False
def complete(self, success: bool) -> None:
self.success = success
self.complete_event.set()
@dataclass(frozen=True)
class ProcessStats:
"""Some statistics produced by every ``process`` called indicating how much has been accomplish during that iteration."""
__slots__ = ('received', 'received_processed', 'sent', 'frame_received')
received: int
received_processed: int
sent: int
frame_received: int
def __repr__(self) -> str:
return f'<{self.__class__.__name__} received:{self.received} (processed: {self.received_processed}, sent: {self.sent})>'
@dataclass(frozen=True)
class ProcessRxReport:
immediate_tx_required: bool
frame_received: bool
__slots__ = ('immediate_tx_required', 'frame_received')
@dataclass(frozen=True)
class ProcessTxReport:
msg: Optional[CanMessage]
immediate_rx_required: bool
__slots__ = 'msg', 'immediate_rx_required'
RxFn = Callable[[float], Optional[CanMessage]]
TxFn = Callable[[CanMessage], None]
PostSendCallback = Callable[[SendRequest], None]
ErrorHandler = Callable[[Exception], None]
params: Params
logger: logging.Logger
remote_blocksize: Optional[int]
rxfn: RxFn
txfn: TxFn
tx_queue: "queue.Queue[SendRequest]"
rx_queue: "queue.Queue[bytearray]"
tx_standby_msg: Optional[CanMessage]
rx_state: RxState
tx_state: TxState
rx_block_counter: int
last_seqnum: int
rx_frame_length: int
tx_frame_length: int
last_flow_control_frame: Optional[PDU]
tx_block_counter: int
tx_seqnum: int
wft_counter: int
pending_flow_control_tx: bool
timer_tx_stmin: Timer
error_handler: Optional[ErrorHandler]
actual_rxdl: Optional[int]
timings: Dict[Tuple[RxState, TxState], float]
active_send_request: Optional[SendRequest]
rx_buffer: bytearray
address: isotp.address.AbstractAddress
timer_rx_fc: Timer
timer_rx_cf: Timer
rate_limiter: RateLimiter
blocking_rxfn: bool
post_send_callback: Optional[PostSendCallback]
def __init__(self,
rxfn: RxFn,
txfn: TxFn,
address: isotp.Address,
error_handler: Optional[ErrorHandler] = None,
params: Optional[Dict[str, Any]] = None,
post_send_callback: Optional[PostSendCallback] = None
):
self.post_send_callback = post_send_callback
self.params = self.Params()
self.logger = logging.getLogger(self.LOGGER_NAME)
if params is not None:
for k in params:
self.params.set(k, params[k], validate=False)
self.params.validate()
self.logger = logging.getLogger(self.params.logger_name)
self.remote_blocksize = None # Block size received in Flow Control message
# Backward compatibility. Handle rxfn with no params as non-blocking
if len(inspect.signature(rxfn).parameters) < 1:
self.rxfn = lambda x: rxfn() # type: ignore
self.blocking_rxfn = False
self.logger.debug("Given rxfn is considered non-blocking")
else:
self.rxfn = rxfn # Function to call to receive a CAN message
self.blocking_rxfn = True
self.logger.debug("Given rxfn is considered blocking")
self.txfn = txfn # Function to call to receive a CAN message
self.set_address(address)
self.tx_queue = queue.Queue() # Layer Input queue for IsoTP frame
self.rx_queue = queue.Queue() # Layer Output queue for IsoTP frame
self.tx_standby_msg = None # Pending message when throttling is active
self.active_send_request = None # The user request for sending. Contains a synchronizing event for blocking send
self.rx_state = self.RxState.IDLE # State of the reception FSM
self.tx_state = self.TxState.IDLE # State of the transmission FSM
self.last_rx_state = self.rx_state # Used to log changes in states
self.last_tx_state = self.tx_state # Used to log changes in states
self.rx_block_counter = 0 # Keeps track of how many block we've received. Used to determine when to send a flow control message
self.last_seqnum = 0 # Consecutive frame Sequence number of previous message
self.rx_frame_length = 0 # Length of IsoTP frame being received at the moment
self.tx_frame_length = 0 # Length of the data that we are sending
self.last_flow_control_frame = None # When a FlowControl is received. Put here
self.tx_block_counter = 0 # Keeps track of how many block we've sent. USed to determine when to wait for a flow control message
self.tx_seqnum = 0 # Keeps track of the actual sequence number while sending
self.wft_counter = 0 # Keeps track of how many wait frame we've received
self.pending_flow_control_tx = False # Flag indicating that we need to transmit a flow control message. Set by Rx Process, Cleared by Tx Process
self._empty_rx_buffer()
self.timer_tx_stmin = Timer(timeout=0)
self.error_handler = error_handler
self.actual_rxdl = None # Length of the CAN messages during a reception. Set by the first frame. All consecutive frames must be identical
# Legacy (v1.x) timing recommendation
self.timings = {
(self.RxState.IDLE, self.TxState.IDLE): 0.02,
(self.RxState.IDLE, self.TxState.WAIT_FC): 0.005,
}
self.load_params()
def load_params(self) -> None:
self.params.validate()
self.timer_rx_fc = Timer(timeout=float(self.params.rx_flowcontrol_timeout) / 1000)
self.timer_rx_cf = Timer(timeout=float(self.params.rx_consecutive_frame_timeout) / 1000)
self.rate_limiter = RateLimiter(mean_bitrate=self.params.rate_limit_max_bitrate, window_size_sec=self.params.rate_limit_window_size)
if self.params.rate_limit_enable:
self.rate_limiter.enable()
def send(self,
data: Union[bytes, bytearray, SendGenerator],
target_address_type: Optional[Union[isotp.address.TargetAddressType, int]] = None,
send_timeout: Optional[float] = None
) -> None:
"""
Enqueue an IsoTP frame to be sent over CAN network.
When performing a blocking send, this method returns only when the transmission is complete or raise an exception when a failure or a timeout occurs.
See :ref:`blocking_send<param_blocking_send>`
:param data: The data to be sent. Can either be a bytearray or a tuple containing a generator and a size. The generator should return integer
:type data: bytearray | (Generator, int)
:param target_address_type: Optional parameter that can be Physical (0) for 1-to-1 communication or Functional (1) for 1-to-n.
See :class:`isotp.TargetAddressType<isotp.TargetAddressType>`.
If not provided, parameter :ref:`default_target_address_type<param_default_target_address_type>` will be used (default to ``Physical``)
:type target_address_type: int
:param send_timeout: Timeout value for blocking send. Unused if :ref:`blocking_send<param_blocking_send>` is ``False``
:type send_timeout: float or None
:raises ValueError: Given data is not a bytearray, a tuple (generator,size) or the size is too big
:raises RuntimeError: Transmit queue is full or tried to transmit while the stack is configured in :ref:`listen mode<param_listen_mode>`
:raises BlockingSendTimeout: When :ref:`blocking_send<param_blocking_send>` is set to ``True`` and the send operation does not complete in the given timeout.
:raises BlockingSendFailure: When :ref:`blocking_send<param_blocking_send>` is set to ``True`` and the transmission failed for any reason (e.g. unexpected frame or bad timings), including a timeout. Note that
:class:`BlockingSendTimeout<BlockingSendTimeout>` inherits :class:`BlockingSendFailure<BlockingSendFailure>`.
"""
if self.params.listen_mode:
raise RuntimeError("Cannot transmit when listen_mode=True")
if target_address_type is None:
target_address_type = self.params.default_target_address_type
else:
target_address_type = isotp.address.TargetAddressType(target_address_type)
send_request = self.SendRequest(data=data, target_address_type=target_address_type)
if self.tx_queue.full():
raise RuntimeError('Transmit queue is full')
if target_address_type == isotp.address.TargetAddressType.Functional:
length_bytes = 1 if self.params.tx_data_length == 8 else 2
maxlen = self.params.tx_data_length - length_bytes - len(self.address.get_tx_payload_prefix())
if send_request.generator.total_length() > maxlen:
raise ValueError('Cannot send multi packet frame with Functional TargetAddressType')
if self.params.blocking_send:
send_request.complete_event.clear()
self.logger.debug("Enqueuing a SendRequest for %d bytes and TAT=%s" % (send_request.generator.total_length(), target_address_type.name))
self.tx_queue.put(send_request)
if self.post_send_callback is not None:
self.post_send_callback(send_request)
if self.params.blocking_send:
send_request.complete_event.wait(send_timeout)
if not send_request.complete_event.is_set():
raise isotp.errors.BlockingSendTimeout("Failed to send IsoTP frame in time")
else:
if not send_request.success:
raise isotp.errors.BlockingSendFailure("Error while sending IsoTP frame")
# Receive an IsoTP frame. Output of the layer
def recv(self, block: bool = False, timeout: Optional[float] = None) -> Optional[bytearray]:
"""
Dequeue an IsoTP frame from the reception queue if available.
:param block: Tells if the read should be blocking or not
:type block: bool
:param timeout: Timeout value used for blocking read only
:type timeout: float
:return: The next available IsoTP frame
:rtype: bytearray or None
"""
try:
return self.rx_queue.get(block=block, timeout=timeout)
except queue.Empty:
return None
def available(self) -> bool:
"""
Returns ``True`` if an IsoTP frame is awaiting in the reception queue. ``False`` otherwise
"""
return not self.rx_queue.empty()
def transmitting(self) -> bool:
"""
Returns ``True`` if an IsoTP frame is being transmitted. ``False`` otherwise
"""
return not self.tx_queue.empty() or self.tx_state != self.TxState.IDLE
def process(self, rx_timeout: float = 0.0, do_rx: bool = True, do_tx: bool = True) -> ProcessStats:
"""
Function to be called periodically, as fast as possible.
This function is expected to block only if the given rxfn performs a blocking read.
:param rx_timeout: Timeout for any read operation
:type rx_timeout: float
:param do_rx: Process reception when ``True``
:type do_rx: bool
:param do_tx: Process transmission when ``True``
:type do_tx: bool
:return: Statistics about what have been accomplished during the call
:rtype: :class:`ProcessStats<isotp.ProcessStats>`
"""
run_process = True
msg_received = 0
msg_received_processed = 0
msg_sent = 0
nb_frame_received = 0
# Run as long as RxStateMachine or Tx StateMachine request the other state machine to immediatly do a pass.
# Prevent useless latency in FSM processing
while run_process:
msg: Optional[CanMessage] = None
run_process = False
# if we have data to send and nothing else in process. start by sending that data. Avoid blocking in rxfn for nothing.
start_with_tx = do_tx \
and not self.tx_queue.empty() \
and self.rx_state == self.RxState.IDLE \
and self.tx_state == self.TxState.IDLE
if start_with_tx:
run_process = True
if do_rx and not start_with_tx:
first_loop = True
while msg is not None or first_loop:
first_loop = False
msg = self.rxfn(rx_timeout)
self._check_timeouts_rx() # Check for every message because rxfn may be blocking since v2.x. Always execute, even if msg=None (issue #41)
if msg is not None:
msg_received += 1
for_me = self.address.is_for_me(msg)
if self.logger.isEnabledFor(logging.DEBUG):
addr = "%08X" % msg.arbitration_id if msg.is_extended_id else "%03X" % msg.arbitration_id
processed = 'p' if for_me else 'i' # processed/ignored
self.logger.debug("Rx: <%s> (%02d) [%s]\t %s" % (addr,
len(msg.data), processed, binascii.hexlify(msg.data).decode('ascii')))
if for_me:
msg_received_processed += 1
rx_result = self._process_rx(msg)
if rx_result.frame_received:
nb_frame_received += 1
if rx_result.immediate_tx_required:
break
start_with_tx = False # it's a one-time event
self.rate_limiter.update() # Only applies to transmission. Update after rxfn because it can be blocking.
if do_tx:
first_loop = True
msg = None
while msg is not None or first_loop:
first_loop = False
tx_result = self._process_tx()
msg = tx_result.msg
if msg is not None:
msg_sent += 1
if self.logger.isEnabledFor(logging.DEBUG):
self.logger.debug("Tx: <%03X> (%02d) [ ]\t %s" % (msg.arbitration_id,
len(msg.data), binascii.hexlify(msg.data).decode('ascii')))
self.txfn(msg)
if tx_result.immediate_rx_required:
run_process = True
break
if self.logger.isEnabledFor(logging.DEBUG):
if self.last_rx_state != self.rx_state or self.last_tx_state != self.tx_state:
self.logger.debug(f"TxState={self.tx_state.name} - RxState={self.rx_state.name}")
self.last_tx_state = self.tx_state
self.last_rx_state = self.rx_state
return self.ProcessStats(
received=msg_received,
received_processed=msg_received_processed,
sent=msg_sent,
frame_received=nb_frame_received
)
def _set_rxfn(self, rxfn: "TransportLayerLogic.RxFn") -> None:
"""
Allow post init change of rxfn. This is a trick to implement the threaded Transport Layer
and keeping the ability to run the TransportLayerLogic without threads for backward compatibility
with v1.x
"""
self.rxfn = rxfn
def _check_timeouts_rx(self) -> None:
if self.timer_rx_cf.is_timed_out():
self._trigger_error(isotp.errors.ConsecutiveFrameTimeoutError("Reception of CONSECUTIVE_FRAME timed out."))
self._stop_receiving()
def _process_rx(self, msg: CanMessage) -> ProcessRxReport:
"""Process the reception of a CAN message. Moves the reception state machine accordingly and optionally"""
# Decoding of message into PDU
try:
pdu = PDU(msg, start_of_data=self.address.get_rx_prefix_size())
except Exception as e:
self._trigger_error(isotp.errors.InvalidCanDataError("Received invalid CAN frame. %s" % (str(e))))
self._stop_receiving()
return self.ProcessRxReport(immediate_tx_required=False, frame_received=False)
# Process Flow Control message
if pdu.type == PDU.Type.FLOW_CONTROL:
self.last_flow_control_frame = pdu # Given to _process_tx method. Queue of 1 message depth
# Nothing else to be done with FlowControl. Return and run _process_tx right away
return self.ProcessRxReport(immediate_tx_required=True, frame_received=False)
frame_complete = False
if pdu.type == PDU.Type.SINGLE_FRAME:
if pdu.can_dl > 8 and pdu.escape_sequence == False:
self._trigger_error(isotp.errors.MissingEscapeSequenceError(
'For SingleFrames conveyed on a CAN message with data length (CAN_DL) > 8, length should be encoded on byte #1 and byte #0 should be 0x00'))
return self.ProcessRxReport(immediate_tx_required=False, frame_received=False)
immediate_tx_msg_required = False
# Process the state machine
if self.rx_state == self.RxState.IDLE:
self.rx_frame_length = 0
self.timer_rx_cf.stop()
if pdu.type == PDU.Type.SINGLE_FRAME:
if pdu.data is not None:
frame_complete = True
self.rx_queue.put(bytearray(pdu.data))
elif pdu.type == PDU.Type.FIRST_FRAME:
started = self._start_reception_after_first_frame_if_valid(pdu)
immediate_tx_msg_required = immediate_tx_msg_required or started
elif pdu.type == PDU.Type.CONSECUTIVE_FRAME:
self._trigger_error(isotp.errors.UnexpectedConsecutiveFrameError('Received a ConsecutiveFrame while reception was idle. Ignoring'))
elif self.rx_state == self.RxState.WAIT_CF:
if pdu.type == PDU.Type.SINGLE_FRAME:
if pdu.data is not None:
frame_complete = True
self.rx_queue.put(bytearray(pdu.data))
self.rx_state = self.RxState.IDLE
self._trigger_error(isotp.errors.ReceptionInterruptedWithSingleFrameError(
'Reception of IsoTP frame interrupted with a new SingleFrame'))
elif pdu.type == PDU.Type.FIRST_FRAME:
started = self._start_reception_after_first_frame_if_valid(pdu)
immediate_tx_msg_required = immediate_tx_msg_required or started
self._trigger_error(isotp.errors.ReceptionInterruptedWithFirstFrameError(
'Reception of IsoTP frame interrupted with a new FirstFrame'))
elif pdu.type == PDU.Type.CONSECUTIVE_FRAME:
expected_seqnum = (self.last_seqnum + 1) & 0xF
if pdu.seqnum == expected_seqnum:
bytes_to_receive = (self.rx_frame_length - len(self.rx_buffer))
if pdu.rx_dl != self.actual_rxdl and pdu.rx_dl < bytes_to_receive:
self._trigger_error(isotp.errors.ChangingInvalidRXDLError(
"Received a ConsecutiveFrame with RX_DL=%s while expected RX_DL=%s. Ignoring frame" % (pdu.rx_dl, self.actual_rxdl)))
return self.ProcessRxReport(immediate_tx_required=False, frame_received=False)
self._start_rx_cf_timer() # Received a CF message. Restart counter. Timeout handled above.
self.last_seqnum = pdu.seqnum
self._append_rx_data(pdu.data[:bytes_to_receive]) # Python handle overflow
if len(self.rx_buffer) >= self.rx_frame_length:
frame_complete = True
self.rx_queue.put(copy(self.rx_buffer)) # Data complete
self._stop_receiving() # Go back to IDLE. Reset all variables and timers.
else:
self.rx_block_counter += 1
if self.params.blocksize > 0 and (self.rx_block_counter % self.params.blocksize) == 0:
self._request_tx_flowcontrol(PDU.FlowStatus.ContinueToSend) # Sets a flag to 1. _process_tx will send it for use.
# We stop the timer until the flow control message is gone. This timer is reactivated in the _process_tx().
self.timer_rx_cf.stop()
immediate_tx_msg_required = True
else:
self._stop_receiving()
received = str(None)
if pdu.seqnum is not None:
received = "0x%02X" % pdu.seqnum
self._trigger_error(isotp.errors.WrongSequenceNumberError(
'Received a ConsecutiveFrame with wrong SequenceNumber. Expecting 0x%02X, Received %s' % (expected_seqnum, received)))
if self.pending_flow_control_tx:
immediate_tx_msg_required = True
return self.ProcessRxReport(immediate_tx_required=immediate_tx_msg_required, frame_received=frame_complete)
def _process_tx(self) -> ProcessTxReport:
"""Process the transmit state machine"""
output_msg = None # Value outputted. If None, no subsequent call to _process_tx will be done.
allowed_bytes = self.rate_limiter.allowed_bytes()
# Sends flow control if _process_rx requested it
if self.pending_flow_control_tx:
self.pending_flow_control_tx = False
if self.pending_flowcontrol_status == PDU.FlowStatus.ContinueToSend:
self._start_rx_cf_timer() # We tell the sending party that it can continue to send data, so we start checking the timeout again
if not self.params.listen_mode: # Inhibit Flow Control in listen mode.
flow_control_msg = self._make_flow_control(flow_status=self.pending_flowcontrol_status)