-
Notifications
You must be signed in to change notification settings - Fork 181
/
Copy pathpdu.py
2118 lines (1752 loc) · 70.4 KB
/
pdu.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
"""DICOM Upper Layer Protocol Data Units (PDUs).
There are seven different PDUs:
- A_ASSOCIATE_RQ
- A_ASSOCIATE_AC
- A_ASSOCIATE_RJ
- P_DATA_TF
- A_RELEASE_RQ
- A_RELEASE_RP
- A_ABORT_RQ
::
from_primitive encode
+----------------+ ------> +------------+ -----> +-------------+
| DUL Primitive | | PDU | | Peer AE |
+----------------+ <------ +------------+ <----- +-------------+
to_primitive decode
"""
import logging
from struct import Struct
from typing import (
Iterator,
Optional,
Any,
Callable,
List,
Tuple,
TYPE_CHECKING,
Union,
cast,
)
from pydicom.uid import UID
from pynetdicom.pdu_items import (
ApplicationContextItem,
PresentationContextItemRQ,
PresentationContextItemAC,
UserInformationItem,
PresentationDataValueItem,
PDU_ITEM_TYPES,
_PDUItemType,
PDUItem,
)
from pynetdicom.utils import decode_bytes, set_ae
if TYPE_CHECKING: # pragma: no cover
from pynetdicom.pdu_primitives import (
A_ASSOCIATE,
P_DATA,
A_RELEASE,
A_ABORT,
A_P_ABORT,
)
LOGGER = logging.getLogger(__name__)
_PDVItem = List[PresentationDataValueItem]
_AbortType = Union["A_ABORT", "A_P_ABORT"]
_PDUType = Union[
"A_ASSOCIATE_RQ",
"A_ASSOCIATE_AC",
"A_ASSOCIATE_RJ",
"P_DATA_TF",
"A_RELEASE_RQ",
"A_RELEASE_RP",
"A_ABORT_RQ",
]
# Predefine some structs to make decoding and encoding faster
UCHAR = Struct("B")
UINT2 = Struct(">H")
UINT4 = Struct(">I")
UNPACK_UCHAR = UCHAR.unpack
UNPACK_UINT2 = UINT2.unpack
UNPACK_UINT4 = UINT4.unpack
PACK_UCHAR = UCHAR.pack
PACK_UINT2 = UINT2.pack
PACK_UINT4 = UINT4.pack
class PDU:
"""Base class for PDUs.
Protocol Data Units (PDUs) are the message formats exchanged between peer
entities within a layer. A PDU consists of protocol control information
and user data. PDUs are constructed by mandatory fixed fields followed by
optional variable fields that contain one or more items and/or sub-items.
References
----------
DICOM Standard, Part 8, :dcm:`Section 9.3 <part08/sect_9.3.html>`
"""
def decode(self, bytestream: bytes) -> None:
"""Decode `bytestream` and use the result to set the field values of
the PDU.
Parameters
----------
bytestream : bytes
The PDU data to be decoded.
"""
for (offset, length), attr_name, func, args in self._decoders:
# Allow us to use None as a `length`
if length:
sl = slice(offset, offset + length)
else:
sl = slice(offset, None)
setattr(self, attr_name, func(bytestream[sl], *args))
@property
def _decoders(self) -> Any:
"""Return an iterable of tuples that contain field decoders."""
raise NotImplementedError
def encode(self) -> bytes:
"""Return the encoded PDU as :class:`bytes`.
Returns
-------
bytes
The encoded PDU.
"""
bytestream = bytes()
for attr_name, func, args in self._encoders:
# If attr_name is None then the field is usually reserved
if attr_name:
bytestream += func(getattr(self, attr_name), *args)
else:
bytestream += func(*args)
return bytestream
@property
def _encoders(self) -> Any:
"""Return an iterable of tuples that contain field encoders."""
raise NotImplementedError
def __eq__(self, other: Any) -> bool:
"""Return ``True`` if `self` equals `other`."""
if other is self:
return True
# pylint: disable=protected-access
if isinstance(other, self.__class__):
self_dict = {
enc[0]: getattr(self, enc[0]) for enc in self._encoders if enc[0]
}
other_dict = {
enc[0]: getattr(other, enc[0]) for enc in other._encoders if enc[0]
}
return self_dict == other_dict
return NotImplemented
@staticmethod
def _generate_items(bytestream: bytes) -> Iterator[Tuple[int, bytes]]:
"""Yield PDU item data from `bytestream`.
Parameters
----------
bytestream : bytes
The encoded PDU variable item data.
Yields
------
int, bytes
The variable item's 'Item Type' parameter as int, and the item's
entire encoded data as bytes.
Notes
-----
Can be used with the following PDU items/sub-items:
- Application Context Item
- Presentation Context Item (RQ/AC)
- Abstract Syntax Sub-item
- Transfer Syntax Sub-item
- User Information Item
- Implementation Class UID Sub-item (RQ/AC)
- Implementation Version Name Sub-item (RQ/AC)
- Asynchronous Operations Window Sub-item (RQ/AC)
- SCP/SCU Role Selection Sub-item (RQ/AC)
- SOP Class Extended Negotiation Sub-item (RQ/AC)
- SOP Class Common Extended Negotiation Sub-item (RQ/AC)
- User Identity Sub-item (RQ/AC)
**Encoding**
When encoded, PDU item and sub-item data for the above has the
following structure, taken from various tables in (offsets shown
with Python indexing). Items are always encoded using Big Endian.
+--------+-------------+-------------+
| Offset | Length | Description |
+========+=============+=============+
| 0 | 1 | Item type |
+--------+-------------+-------------+
| 1 | 1 | Reserved |
+--------+-------------+-------------+
| 2 | 2 | Item length |
+--------+-------------+-------------+
| 4 | Item length | Item data |
+--------+-------------+-------------+
References
----------
* DICOM Standard, Part 8, :dcm:`Section 9.3 <part08/sect_9.3.html>`
* DICOM Standard, Part 8,
:dcm:`Section 9.3.1<part08/sect_9.3.html#sect_9.3.1>`
"""
offset = 0
while bytestream[offset : offset + 1]:
item_type = UNPACK_UCHAR(bytestream[offset : offset + 1])[0]
item_length = UNPACK_UINT2(bytestream[offset + 2 : offset + 4])[0]
item_data = bytestream[offset : offset + 4 + item_length]
assert len(item_data) == 4 + item_length
yield item_type, item_data
# Move `offset` to the start of the next item
offset += 4 + item_length
def __len__(self) -> int:
"""Return the total length of the encoded PDU as :class:`int`."""
return 6 + self.pdu_length
def __ne__(self, other: Any) -> bool:
"""Return ``True`` if `self` does not equal `other`."""
return not self == other
@property
def pdu_length(self) -> int:
"""Return the *PDU Length* field value as :class:`int`."""
raise NotImplementedError
@property
def pdu_type(self) -> int:
"""Return the *PDU Type* field value as :class:`int`."""
return PDU_TYPES[self.__class__]
@staticmethod
def _wrap_bytes(bytestream: bytes) -> bytes:
"""Return `bytestream` without changing it."""
return bytestream
@staticmethod
def _wrap_encode_items(items: List[PDUItem]) -> bytes:
"""Return `items` encoded as bytes.
Parameters
----------
items : list of PDU items
The items to encode.
Returns
-------
bytes
The encoded items.
"""
bytestream = bytes()
for item in items:
bytestream += item.encode()
return bytestream
@staticmethod
def _wrap_encode_str(value: str, pad: int = 0) -> bytes:
"""Return `value` as ASCII encoded :class:`bytes`.
Each component of Application Context, Abstract Syntax and Transfer
Syntax UIDs should be encoded as a ISO 646:1990-Basic G0 Set Numeric
String (characters 0-9), with each component separated by '.' (0x2e).
'ascii' is chosen because this is the `codec Python uses
<https://docs.python.org/3/library/codecs.html>`_ for ISO 646.
Parameters
----------
value : str
The ASCII string to be encoded.
pad : int, optional
The maximum amount of trailing padding to be used (default ``0``).
Returns
-------
bytes
The encoded `value`.
References
----------
* DICOM Standard, Part 8, :dcm:`Annex F <part08/chapter_F.html>`
* `Python codecs module
<https://docs.python.org/3/library/codecs.html>`_
"""
return value.ljust(pad).encode("ascii", errors="strict")
def _wrap_generate_items(self, bytestream: bytes) -> List[PDUItem]:
"""Return a list of decoded PDU items generated from `bytestream`."""
item_list = []
for item_type, item_bytes in self._generate_items(bytestream):
item = PDU_ITEM_TYPES[item_type]()
item.decode(item_bytes)
item_list.append(item)
return item_list
@staticmethod
def _wrap_pack(value: Any, packer: Callable[[Any], bytes]) -> bytes:
"""Return `value` encoded as bytes using `packer`.
Parameters
----------
value
The value to encode.
packer : callable
A callable function to use to pack the data as bytes. The
`packer` should return the packed bytes. Example:
struct.Struct('>I').pack
Returns
-------
bytes
"""
return packer(value)
@staticmethod
def _wrap_unpack(bytestream: bytes, unpacker: Callable[[bytes], Tuple[Any]]) -> Any:
"""Return the first value when `unpacker` is run on `bytestream`.
Parameters
----------
bytestream : bytes
The encoded data to unpack.
unpacker : callable
A callable function to use to unpack the data in `bytestream`. The
`unpacker` should return a tuple containing unpacked values.
Example: struct.Struct('>I').unpack.
"""
return unpacker(bytestream)[0]
class A_ASSOCIATE_RQ(PDU):
"""An A-ASSOCIATE-RQ PDU.
An A-ASSOCIATE-RQ PDU is sent by an association requestor to initiate
association negotiation with an acceptor.
Attributes
----------
pdu_type : int
The *PDU Type* field value (``0x01``).
protocol_version : int
The *Protocol Version* field value (``0x01``).
variable_items : list
A list containing the A-ASSOCIATE-RQ's *Variable Items*. Contains
one Application Context item, one or more Presentation Context items
and one User Information item. The order of the items is not
guaranteed.
Notes
-----
An A-ASSOCIATE-RQ PDU requires the following parameters:
* PDU type (1, fixed value, ``0x01``)
* PDU length (1)
* Protocol version (1, default value, ``0x01``)
* Called AE title (1)
* Calling AE title (1)
* Variable items (1)
* Application Context Item (1)
* Item type (1, fixed value, ``0x10``)
* Item length (1)
* Application Context Name (1, fixed in an application)
* Presentation Context Item(s) (1 or more)
* Item type (1, fixed value, ``0x21``)
* Item length (1)
* Context ID (1)
* Abstract/Transfer Syntax Sub-items (1)
* Abstract Syntax Sub-item (1)
* Item type (1, fixed, ``0x30``)
* Item length (1)
* Abstract syntax name (1)
* Transfer Syntax Sub-items (1 or more)
* Item type (1, fixed, ``0x40``)
* Item length (1)
* Transfer syntax name(s) (1 or more)
* User Information Item (1)
* Item type (1, fixed, ``0x50``)
* Item length (1)
* User data Sub-items (2 or more)
* Maximum Length Received Sub-item (1)
* Implementation Class UID Sub-item (1)
* Optional User Data Sub-items (0 or more)
**Encoding**
When encoded, an A-ASSOCIATE-RQ PDU has the following structure, taken
from `Table 9-11<part08/sect_9.3.2.html>` (offsets shown with Python
indexing). PDUs are always encoded using Big Endian.
+--------+-------------+------------------+
| Offset | Length | Description |
+========+=============+==================+
| 0 | 1 | PDU type |
+--------+-------------+------------------+
| 1 | 1 | Reserved |
+--------+-------------+------------------+
| 2 | 4 | PDU length |
+--------+-------------+------------------+
| 6 | 2 | Protocol version |
+--------+-------------+------------------+
| 8 | 2 | Reserved |
+--------+-------------+------------------+
| 10 | 16 | Called AE title |
+--------+-------------+------------------+
| 26 | 16 | Calling AE title |
+--------+-------------+------------------+
| 42 | 32 | Reserved |
+--------+-------------+------------------+
| 74 | Variable | Variable items |
+--------+-------------+------------------+
References
----------
* DICOM Standard, Part 8, Sections :dcm:`9.3.2<part08/sect_9.3.2.html>`
and :dcm:`9.3.1<part08/sect_9.3.html#sect_9.3.1>`
"""
def __init__(self, primitive: Optional["A_ASSOCIATE"] = None) -> None:
"""Initialise a new A-ASSOCIATE-RQ PDU.
Parameters
----------
primitive : pynetdicom.pdu_primitive.A_ASSOCIATE
The primitive to use to initialise the PDU.
"""
# We allow the user to modify the protocol version if so desired
self.protocol_version = 0x01
self._called_aet = ""
self._calling_aet = ""
# Set some default values
self.called_ae_title = "Default"
self.calling_ae_title = "Default"
# `variable_items` is a list containing the following:
# 1 ApplicationContextItem
# 1 or more PresentationContextItemRQ
# 1 UserInformationItem
# The order of the items in the list may not be as given above
self.variable_items: _PDUItemType = []
if primitive is not None:
self.from_primitive(primitive)
def from_primitive(self, primitive: "A_ASSOCIATE") -> None:
"""Setup the current PDU using an A-ASSOCIATE (request) primitive.
Parameters
----------
primitive : pdu_primitives.A_ASSOCIATE
The primitive to use to set the current PDU field values.
"""
self.calling_ae_title = primitive.calling_ae_title
self.called_ae_title = primitive.called_ae_title
# Add Application Context
application_context = ApplicationContextItem()
application_context.application_context_name = cast(
UID, primitive.application_context_name
)
self.variable_items.append(application_context)
# Add Presentation Context(s)
for contexts in primitive.presentation_context_definition_list:
presentation_context = PresentationContextItemRQ()
presentation_context.from_primitive(contexts)
self.variable_items.append(presentation_context)
# Add User Information
user_information = UserInformationItem()
user_information.from_primitive(primitive.user_information)
self.variable_items.append(user_information)
def to_primitive(self) -> "A_ASSOCIATE":
"""Return an A-ASSOCIATE (request) primitive from the current PDU.
Returns
-------
pdu_primitives.A_ASSOCIATE
The primitive representation of the current PDU.
"""
from pynetdicom.pdu_primitives import A_ASSOCIATE
primitive = A_ASSOCIATE()
primitive.calling_ae_title = self.calling_ae_title
primitive.called_ae_title = self.called_ae_title
primitive.application_context_name = self.application_context_name
for item in self.variable_items:
# Add presentation contexts
if isinstance(item, PresentationContextItemRQ):
primitive.presentation_context_definition_list.append(
item.to_primitive()
)
# Add user information
elif isinstance(item, UserInformationItem):
primitive.user_information = item.to_primitive()
return primitive
@property
def application_context_name(self) -> Optional[UID]:
"""Return the *Application Context Name*, if available.
Returns
-------
pydicom.uid.UID or None
The requestor's *Application Context Name* or None if not
available.
"""
for item in self.variable_items:
if isinstance(item, ApplicationContextItem):
return item.application_context_name
return None
@property
def called_ae_title(self) -> str:
"""Get or set the *Called AE Title* field value as :class:`str`.
Will be converted to a fixed length 16-byte value (padded with trailing
spaces ``0x20``). Leading and trailing spaces are non-significant and a
value of 16 spaces is not allowed.
Parameters
----------
value : str or bytes
The value you wish to set. A value consisting of spaces is not
allowed and values longer than 16 characters will be truncated.
"""
return self._called_aet
@called_ae_title.setter
def called_ae_title(self, value: Union[str, bytes]) -> None:
"""Set the *Called AE Title* field value"""
if isinstance(value, bytes):
# PS3.8 Table 9-11: Leading and trailing spaces are non-significant
value = decode_bytes(value).strip()
if not value:
raise ValueError(
"Invalid 'Called AE Title' value - must not consist "
"entirely of spaces"
)
self._called_aet = cast(str, set_ae(value, "Called AE Title", False, False))
@property
def calling_ae_title(self) -> str:
"""Return the *Calling AE Title* field value as :class:`str`."""
return self._calling_aet
@calling_ae_title.setter
def calling_ae_title(self, value: Union[str, bytes]) -> None:
"""Set the *Calling AE Title* field value.
Will be converted to a fixed length 16-byte value (padded with trailing
spaces ``0x20``). Leading and trailing spaces are non-significant and a
value of 16 spaces is not allowed.
Parameters
----------
value : str or bytes
The value you wish to set. A value consisting of spaces is not
allowed and values longer than 16 characters will be truncated.
"""
if isinstance(value, bytes):
# PS3.8 Table 9-11: Leading and trailing spaces are non-significant
value = decode_bytes(value).strip()
if not value:
raise ValueError(
"Invalid 'Calling AE Title' value - must not consist "
"entirely of spaces"
)
self._calling_aet = cast(str, set_ae(value, "Calling AE Title", False, False))
@property
def _decoders(self) -> Any:
"""Return an iterable of tuples that contain field decoders.
Returns
-------
list of tuple
A list of ``((offset, length), attr_name, callable, [args])``,
where:
- ``offset`` is the byte offset to start at
- ``length`` is how many bytes to slice (if None then will slice
to the end of the data),
- ``attr_name`` is the name of the attribute corresponding to the
field
- ``callable`` is a decoding function that returns the decoded
value
- ``args`` is a list of arguments to pass ``callable``
"""
return [
((6, 2), "protocol_version", self._wrap_unpack, [UNPACK_UINT2]),
((10, 16), "called_ae_title", self._wrap_bytes, []),
((26, 16), "calling_ae_title", self._wrap_bytes, []),
((74, None), "variable_items", self._wrap_generate_items, []),
]
@property
def _encoders(self) -> Any:
"""Return an iterable of tuples that contain field decoders.
Returns
-------
list of tuple
A list of ``(attr_name, callable, [args])``, where:
- ``attr_name`` is the name of the attribute corresponding to the
field
- ``callable`` is an encoding function that returns :class:`bytes`
- ``args`` is a :class:`list` of arguments to pass ``callable``.
"""
return [
("pdu_type", PACK_UCHAR, []),
(None, self._wrap_pack, [0x00, PACK_UCHAR]),
("pdu_length", PACK_UINT4, []),
("protocol_version", PACK_UINT2, []),
(None, self._wrap_pack, [0x0000, PACK_UINT2]),
("called_ae_title", self._wrap_encode_str, [16]),
("calling_ae_title", self._wrap_encode_str, [16]),
(None, self._wrap_pack, [0x00, PACK_UINT4]),
(None, self._wrap_pack, [0x00, PACK_UINT4]),
(None, self._wrap_pack, [0x00, PACK_UINT4]),
(None, self._wrap_pack, [0x00, PACK_UINT4]),
(None, self._wrap_pack, [0x00, PACK_UINT4]),
(None, self._wrap_pack, [0x00, PACK_UINT4]),
(None, self._wrap_pack, [0x00, PACK_UINT4]),
(None, self._wrap_pack, [0x00, PACK_UINT4]),
("variable_items", self._wrap_encode_items, []),
]
@property
def pdu_length(self) -> int:
"""Return the *PDU Length* field value as :class:`int`."""
length = 68
for item in self.variable_items:
length += len(item)
return length
@property
def presentation_context(self) -> List[PresentationContextItemRQ]:
"""Return a list of the Presentation Context items.
Returns
-------
list of pdu_items.PresentationContextItemRQ
The Presentation Context items.
"""
return [
item
for item in self.variable_items
if isinstance(item, PresentationContextItemRQ)
]
def __str__(self) -> str:
"""Return a string representation of the PDU."""
s = ["A-ASSOCIATE-RQ PDU"]
s.append("==================")
s.append(f" PDU type: 0x{self.pdu_type:02X}")
s.append(f" PDU length: {self.pdu_length} bytes")
s.append(f" Protocol version: {self.protocol_version}")
s.append(f" Called AET: {self.called_ae_title}")
s.append(f" Calling AET: {self.calling_ae_title}")
s.append("")
s.append(" Variable Items")
s.append(" ---------------")
s.append(" * Application Context Item")
s.append(f" - Context name: ={self.application_context_name}")
s.append(" * Presentation Context Item(s):")
for cx in self.presentation_context:
item_str_list = str(cx).split("\n")
s.append(f" - {item_str_list[0]}")
for jj in item_str_list[1:-1]:
s.append(f" {jj}")
s.append(" * User Information Item(s):")
for item in cast(UserInformationItem, self.user_information).user_data:
item_str_list = str(item).split("\n")
s.append(f" - {item_str_list[0]}")
for jj in item_str_list[1:-1]:
s.append(f" {jj}")
return "\n".join(s)
@property
def user_information(self) -> Optional[UserInformationItem]:
"""Return the User Information Item, if available.
Returns
-------
pdu_items.UserInformationItem or None
The requestor's User Information object or ``None``, if not
available.
"""
for item in self.variable_items:
if isinstance(item, UserInformationItem):
return item
return None
class A_ASSOCIATE_AC(PDU):
"""An A-ASSOCIATE-AC PDU.
An A-ASSOCIATE-AC PDU is sent by an association acceptor to indicate that
association negotiation has been successful.
Attributes
----------
pdu_type : int
The *PDU Type* field value (``0x02``).
protocol_version : int
The *Protocol Version* field value (default ``0x01``).
variable_items : list
A list containing the A-ASSOCIATE-AC's 'Variable Items'. Contains
one Application Context item, one or more Presentation Context items
and one User Information item. The order of the items is not
guaranteed.
Notes
-----
An A-ASSOCIATE-AC PDU requires the following parameters:
* PDU type (1, fixed value, ``0x02``)
* PDU length (1)
* Protocol version (1, default value, ``0x01``)
* Variable items (1)
* Application Context Item (1)
* Item type (1, fixed value, ``0x10``)
* Item length (1)
* Application Context Name (1, fixed in an application)
* Presentation Context Item(s) (1 or more)
* Item type (1, fixed value, ``0x21``)
* Item length (1)
* Context ID (1)
* Result/reason (1)
* Transfer Syntax Sub-items (1)
* Item type (1, fixed, ``0x40``)
* Item length (1)
* Transfer syntax name(s) (1)
* User Information Item (1)
* Item type (1, fixed, ``0x50``)
* Item length (1)
* User data Sub-items (2 or more)
* Maximum Length Received Sub-item (1)
* Implementation Class UID Sub-item (1)
* Optional User Data Sub-items (0 or more)
**Encoding**
When encoded, an A-ASSOCIATE-AC PDU has the following structure, taken
from Table 9-17 (offsets shown with Python indexing). PDUs are always
encoded using Big Endian.
+--------+-------------+------------------+
| Offset | Length | Description |
+========+=============+==================+
| 0 | 1 | PDU type |
+--------+-------------+------------------+
| 1 | 1 | Reserved |
+--------+-------------+------------------+
| 2 | 4 | PDU length |
+--------+-------------+------------------+
| 6 | 2 | Protocol version |
+--------+-------------+------------------+
| 8 | 2 | Reserved |
+--------+-------------+------------------+
| 10 | 16 | Reserved^ |
+--------+-------------+------------------+
| 26 | 16 | Reserved^ |
+--------+-------------+------------------+
| 42 | 32 | Reserved |
+--------+-------------+------------------+
| 74 | Variable | Variable items |
+--------+-------------+------------------+
^ The reserved fields shall be sent with a value identical to the value
received in the A-ASSOCIATE-RQ but their values shall not be tested.
References
----------
* DICOM Standard, Part 8,
:dcm:`Section 9.3.3 <part08/sect_9.3.3.html>`
* DICOM Standard, Part 8,
:dcm:`Section 9.3.1<part08/sect_9.3.html#sect_9.3.1>`
"""
def __init__(self, primitive: Optional["A_ASSOCIATE"] = None) -> None:
"""Initialise a new A-ASSOCIATE-AC PDU.
Parameters
----------
primitive : pynetdicom.pdu_primitive.A_ASSOCIATE
The primitive to use to initialise the PDU.
"""
# We allow the user to modify the protocol version if so desired
self.protocol_version = 0x01
# Called AE Title, should be present, but no guarantees
self._reserved_aet: str = ""
# Calling AE Title, should be present, but no guarantees
self._reserved_aec: str = ""
# `variable_items` is a list containing the following:
# 1 ApplicationContextItem
# 1 or more PresentationContextItemAC
# 1 UserInformationItem
# The order of the items in the list may not be as given above
self.variable_items: _PDUItemType = []
if primitive is not None:
self.from_primitive(primitive)
def from_primitive(self, primitive: "A_ASSOCIATE") -> None:
"""Setup the current PDU using an A-ASSOCIATE (accept) primitive.
Parameters
----------
primitive : pdu_primitives.A_ASSOCIATE
The primitive to use to set the current PDU field values.
"""
self.reserved_aet = primitive.called_ae_title
self.reserved_aec = primitive.calling_ae_title
# Make application context
application_context = ApplicationContextItem()
application_context.application_context_name = cast(
UID, primitive.application_context_name
)
self.variable_items.append(application_context)
# Make presentation contexts
for ii in primitive.presentation_context_definition_results_list:
presentation_context = PresentationContextItemAC()
presentation_context.from_primitive(ii)
self.variable_items.append(presentation_context)
# Make user information
user_information = UserInformationItem()
user_information.from_primitive(primitive.user_information)
self.variable_items.append(user_information)
def to_primitive(self) -> "A_ASSOCIATE":
"""Return an A-ASSOCIATE (accept) primitive from the current PDU.
Returns
-------
pdu_primitives.A_ASSOCIATE
The primitive representation of the current PDU.
"""
from pynetdicom.pdu_primitives import A_ASSOCIATE
primitive = A_ASSOCIATE()
# The two reserved parameters at byte offsets 11 and 27 shall be set
# to called and calling AET byte the value shall not be
# tested when received (PS3.8 Table 9-17)
primitive._called_ae_title = self.reserved_aet
primitive._calling_ae_title = self.reserved_aec
for item in self.variable_items:
# Add application context
if isinstance(item, ApplicationContextItem):
primitive.application_context_name = item.application_context_name
# Add presentation contexts
elif isinstance(item, PresentationContextItemAC):
primitive.presentation_context_definition_results_list.append(
item.to_primitive()
)
# Add user information
elif isinstance(item, UserInformationItem):
primitive.user_information = item.to_primitive()
# 0x00 = Accepted
primitive.result = 0x00
return primitive
@property
def application_context_name(self) -> Optional[UID]:
"""Return the *Application Context Name*, if available.
Returns
-------
pydicom.uid.UID or None
The acceptor's *Application Context Name* or None if not available.
"""
for item in self.variable_items:
if isinstance(item, ApplicationContextItem):
return item.application_context_name
return None
@property
def called_ae_title(self) -> str:
"""Return the value sent in the *Called AE Title* reserved space.
While the standard says this value should match the A-ASSOCIATE-RQ
value there is no guarantee and this should not be used as a check
value.
Returns
-------
str
The value the A-ASSOCIATE-AC sent in the *Called AE Title* reserved
space. May be an empty string if unable to decode the value.
"""
return self.reserved_aet
@property
def calling_ae_title(self) -> str:
"""Return the value sent in the *Calling AE Title* reserved space.
While the standard says this value should match the A-ASSOCIATE-RQ
value there is no guarantee and this should not be used as a check
value.
Returns
-------
bytes
The value the A-ASSOCIATE-AC sent in the *Calling AE Title*
reserved space. May be an empty string if unable to decode the
value.
"""
return self.reserved_aec
@property
def _decoders(self) -> Any:
"""Return an iterable of tuples that contain field decoders.
Returns
-------
list of tuple
A list of ((offset, length), attr_name, callable, [args]), where
- offset is the byte offset to start at
- length is how many bytes to slice (if None then will slice to the
end of the data),
- attr_name is the name of the attribute corresponding to the field
- callable is a decoding function that returns the decoded value,
- args is a list of arguments to pass callable.
"""
return [
((6, 2), "protocol_version", self._wrap_unpack, [UNPACK_UINT2]),
((10, 16), "reserved_aet", self._wrap_bytes, []), # Called AET
((26, 16), "reserved_aec", self._wrap_bytes, []), # Calling AET
((74, None), "variable_items", self._wrap_generate_items, []),
]
@property
def _encoders(self) -> Any:
"""Return an iterable of tuples that contain field decoders.
Returns
-------
list of tuple
A list of (attr_name, callable, [args]), where