File: device_server.py

package info (click to toggle)
pytango 10.1.4-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 8,304 kB
  • sloc: python: 27,795; cpp: 16,150; sql: 252; sh: 152; makefile: 43
file content (1732 lines) | stat: -rw-r--r-- 57,621 bytes parent folder | download
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
# SPDX-FileCopyrightText: All Contributors to the PyTango project
# SPDX-License-Identifier: LGPL-3.0-or-later

"""
This is an internal PyTango module.
"""

from dataclasses import dataclass

import copy
import functools
import inspect
import os
import types
import numbers

from tango._tango import (
    AttrQuality,
    AttributeConfig,
    AttributeConfig_2,
    AttributeConfig_3,
    DeviceImpl,
    Device_2Impl,
    Device_3Impl,
    Device_6Impl,
    DevFailed,
    Attribute,
    AttrWriteType,
    Attr,
    Logger,
    AttrDataFormat,
    DispLevel,
    UserDefaultAttrProp,
    StdStringVector,
    EventType,
    constants,
    CmdArgType,
    EncodedAttribute,
)
from tango.pyutil import Util
from tango.release import Release
from tango.utils import (
    get_latest_device_class,
    set_complex_value,
    is_pure_str,
    parse_type_hint,
    get_attribute_type_format,
    _force_tracing,
    _forcefully_traced_method,
    _get_non_tango_source_location,
    _exception_converter,
    _InterfaceDefinedByIDL,
)
from tango.green import get_executor
from tango.attr_data import AttrData

from tango.log4tango import TangoStream

__docformat__ = "restructuredtext"

__all__ = (
    "MultiAttrProp",
    "device_server_init",
)

# Worker access

_WORKER = get_executor()


def set_worker(worker):
    global _WORKER
    _WORKER = worker


def get_worker():
    return _WORKER


# patcher for methods
def run_in_executor(fn):
    if not hasattr(fn, "wrapped_with_executor"):

        @functools.wraps(fn)
        def wrapper(*args, **kwargs):
            return get_worker().execute(fn, *args, **kwargs)

        # to avoid double wrapping we add an empty field, and then use it to check, whether function is already wrapped
        wrapper.wrapped_with_executor = True
        return wrapper
    else:
        return fn


def get_source_location(source=None):
    """Helper function that provides source location for logging functions.
    :param source:
        (optional) Method or function, which will be unwrapped of decorated wrappers
        and inspected for location. If not provided - current stack will be used to deduce the location.
    :type source: Callable

    :return:
        Tuple (filename, lineno)
    :rtype :tuple:
    """
    location = _get_non_tango_source_location(source)
    filename = os.path.basename(location.filepath)
    return filename, location.lineno


# Note: the inheritance below doesn't call get_latest_device_class(),
#       because such dynamic inheritance breaks auto-completion in IDEs.
#       Instead, we manually provide the correct class here, and verify
#       that the inheritance is correct via a unit test, in test_server.py.
class LatestDeviceImpl(Device_6Impl):
    __doc__ = f"""\
    Latest implementation of the TANGO device base class (alias for {get_latest_device_class().__name__}).

    It inherits from CORBA classes where all the network layer is implemented.
    """

    def __init__(self, *args):
        super().__init__(*args)
        # Set up python related versions for DevInfo
        self.add_version_info("PyTango", Release.version_long)
        self.add_version_info("Build.PyTango.Python", constants.Compile.PY_VERSION)
        self.add_version_info("Build.PyTango.cppTango", constants.Compile.TANGO_VERSION)
        self.add_version_info("Build.PyTango.NumPy", constants.Compile.NUMPY_VERSION)
        self.add_version_info(
            "Build.PyTango.Pybind11", constants.Compile.PYBIND11_VERSION
        )
        self.add_version_info("Python", constants.Runtime.PY_VERSION)
        self.add_version_info("NumPy", constants.Runtime.NUMPY_VERSION)


@dataclass
class MultiAttrProp(_InterfaceDefinedByIDL):
    """This class represents the python interface for the Tango IDL object
    MultiAttrProp."""

    label: str = ""
    description: str = ""
    unit: str = ""
    standard_unit: str = ""
    display_unit: str = ""
    format: str = ""
    min_value: str = ""
    max_value: str = ""
    min_alarm: str = ""
    max_alarm: str = ""
    min_warning: str = ""
    max_warning: str = ""
    delta_t: str = ""
    delta_val: str = ""
    event_period: str = ""
    archive_period: str = ""
    rel_change: str = ""
    abs_change: str = ""
    archive_rel_change: str = ""
    archive_abs_change: str = ""

    def __post_init__(self):
        self._initialized = True


def __Attribute__get_properties(self, attr_cfg=None):
    """
    get_properties(self: Attribute, attr_cfg: AttributeConfig = None) -> AttributeConfig

        Get attribute properties.

        :param conf: the config object to be filled with
                     the attribute configuration. Default is None meaning the
                     method will create internally a new :obj:`tango.AttributeConfig_5`
                     and return it.
                     Can be :obj:`tango.AttributeConfig`, :obj:`tango.AttributeConfig_2`,
                     :obj:`tango.AttributeConfig_3`, :obj:`tango.AttributeConfig_5` or
                     :obj:`tango.MultiAttrProp`

        :returns: the config object filled with attribute configuration information
        :rtype: :obj:`tango.AttributeConfig`

        New in PyTango 7.1.4
    """

    if attr_cfg is None:
        attr_cfg = MultiAttrProp()
    if not isinstance(attr_cfg, MultiAttrProp):
        raise TypeError("attr_cfg must be an instance of MultiAttrProp")
    return self._get_properties_multi_attr_prop(attr_cfg)


def __Attribute__set_properties(self, attr_cfg, dev=None):
    """
    set_properties(self: Attribute, attr_cfg: AttributeConfig, dev: DeviceImpl = None)

        Set attribute properties.

        This method sets the attribute properties value with the content
        of the fields in the :obj:`tango.AttributeConfig`/ :obj:`tango.AttributeConfig_3` object

        :param conf: the config object.
        :type conf: :obj:`tango.AttributeConfig` or :obj:`tango.AttributeConfig_3`
        :param dev: the device (not used, maintained
                    for backward compatibility)
        :type dev: :obj:`tango.DeviceImpl`

        New in PyTango 7.1.4
    """

    if not isinstance(attr_cfg, MultiAttrProp):
        raise TypeError("attr_cfg must be an instance of MultiAttrProp")
    return self._set_properties_multi_attr_prop(attr_cfg)


def __Attribute__str(self):
    return f"{self.__class__.__name__}({self.get_name()})"


def __Attribute__set_value(self, *args):
    """
    .. function:: set_value(self, data)
                  set_value(self, str_data, data)
        :noindex:

    Set internal attribute value.

    This method stores the attribute read value inside the object.
    This method also stores the date when it is called and initializes the
    attribute quality factor.

    :param data: the data to be set. Data must be compatible with the attribute type and format.
                 E.g., sequence for SPECTRUM and a SEQUENCE of equal-length SEQUENCES
                 for IMAGE attributes.
                 The recommended sequence is a C continuous and aligned numpy
                 array, as it can be optimized.
    :param str_data: special variation for DevEncoded data type. In this case 'data' must
                     be a str or an object with the buffer interface.
    :type str_data: str

    .. versionchanged:: 10.1.0
        The dim_x and dim_y parameters were removed.
    """

    if not len(args):
        raise TypeError("set_value method must be called with at least one argument!")

    for arg in args:
        if arg is None:
            raise TypeError("set_value method cannot be called with None!")

    if self.get_data_type() == CmdArgType.DevEncoded and not isinstance(
        args[0], EncodedAttribute
    ):
        if len(args) > 2:
            raise TypeError(
                "Too many arguments. "
                "Note, that dim_x and dim_y arguments are no longer supported."
            )
    else:
        if len(args) > 1:
            raise TypeError(
                "Too many arguments. "
                "Note, that dim_x and dim_y arguments are no longer supported."
            )

    self._set_value(*args)


def __Attribute__set_value_date_quality(self, *args):
    """
    .. function::   set_value_date_quality(self, data, time_stamp, quality)
                    set_value_date_quality(self, str_data, data, time_stamp, quality)
        :noindex:

    Set internal attribute value, date and quality factor.

    This method stores the attribute read value, the date and the attribute quality
    factor inside the object.

    :param data: the data to be set. Data must be compatible with the attribute type and format.
                 E.g., sequence for SPECTRUM and a SEQUENCE of equal-length SEQUENCES
                 for IMAGE attributes.
                 The recommended sequence is a C continuous and aligned numpy
                 array, as it can be optimized.
    :param str_data: special variation for DevEncoded data type. In this case 'data' must
                     be a str or an object with the buffer interface.
    :type str_data: str
    :param time_stamp: the time stamp
    :type time_stamp: double
    :param quality: the attribute quality factor
    :type quality: AttrQuality

    .. versionchanged:: 10.1.0
        The dim_x and dim_y parameters were removed.
    """

    if len(args) < 3:
        raise TypeError(
            "set_value_date_quality method must be called with at least three arguments!"
        )

    for arg in args:
        if arg is None:
            raise TypeError("set_value_date_quality method cannot be called with None!")

    if self.get_data_type() == CmdArgType.DevEncoded and not isinstance(
        args[0], EncodedAttribute
    ):
        if len(args) > 4:
            raise TypeError(
                "Too many arguments. "
                "Note, that dim_x and dim_y arguments are no longer supported."
            )
        elif (
            len(args) == 4
            and not isinstance(args[-1], AttrQuality)
            and isinstance(args[-1], numbers.Number)
        ):
            raise TypeError(
                f"Last argument, {args[3]}, has the incorrect type: {type(args[3])}. "
                "It must be AttrQuality. "
                "Note, that dim_x and dim_y arguments are no longer supported."
            )
    else:
        if len(args) > 3:
            raise TypeError(
                "Too many arguments. "
                "Note, that dim_x and dim_y arguments are no longer supported."
            )
        elif (
            len(args) == 3
            and not isinstance(args[-1], AttrQuality)
            and isinstance(args[-1], numbers.Number)
        ):
            raise TypeError(
                f"Last argument, {args[2]}, has the incorrect type: {type(args[2])}. "
                "It must be AttrQuality. "
                "Note, that dim_x and dim_y arguments are no longer supported."
            )

    self._set_value_date_quality(*args)


def __init_Attribute():
    Attribute.__str__ = __Attribute__str
    Attribute.__repr__ = __Attribute__str
    Attribute.get_properties = __Attribute__get_properties
    Attribute.set_properties = __Attribute__set_properties

    Attribute.set_value = __Attribute__set_value
    Attribute.set_value_date_quality = __Attribute__set_value_date_quality


def __DeviceImpl__get_device_class(self):
    """
    get_device_class(self)

        Get device class singleton.

        :returns: the device class singleton (device_class field)
        :rtype: DeviceClass

    """
    try:
        return self._device_class_instance
    except AttributeError:
        return None


def __DeviceImpl__get_device_properties(self, ds_class=None):
    """
    get_device_properties(self, ds_class = None)

        Utility method that fetches all the device properties from the database
        and converts them into members of this DeviceImpl.

        :param ds_class: the DeviceClass object. Optional. Default value is
                         None meaning that the corresponding DeviceClass object for this
                         DeviceImpl will be used
        :type ds_class: DeviceClass

        :raises DevFailed:
    """
    if ds_class is None:
        try:
            # Call this method in a try/except in case this is called during the DS shutdown sequence
            ds_class = self.get_device_class()
        except Exception:
            return
    try:
        pu = self.prop_util = ds_class.prop_util
        self.device_property_list = copy.deepcopy(ds_class.device_property_list)
        class_prop = ds_class.class_property_list
        pu.get_device_properties(self, class_prop, self.device_property_list)
        for prop_name in class_prop:
            setattr(self, prop_name, pu.get_property_values(prop_name, class_prop))
        for prop_name in self.device_property_list:
            setattr(
                self,
                prop_name,
                self.prop_util.get_property_values(
                    prop_name, self.device_property_list
                ),
            )
    except DevFailed as df:
        print(80 * "-")
        print(df)
        raise df


def __DeviceImpl__add_attribute(
    self, attr, r_meth=None, w_meth=None, is_allo_meth=None
):
    """
    add_attribute(self, attr, r_meth=None, w_meth=None, is_allo_meth=None) -> Attr

        Add a new attribute to the device attribute list.

        Please, note that if you add
        an attribute to a device at device creation time, this attribute will be added
        to the device class attribute list. Therefore, all devices belonging to the
        same class created after this attribute addition will also have this attribute.

        If you pass a reference to unbound method for read, write or is_allowed method
        (e.g. DeviceClass.read_function or self.__class__.read_function),
        during execution the corresponding bound method (self.read_function) will be used.

        Note: Calling the synchronous add_attribute method from a coroutine function in
        an asyncio server may cause a deadlock.
        Use ``await`` :meth:`async_add_attribute` instead.
        However, if overriding the synchronous method ``initialize_dynamic_attributes``,
        then the synchronous add_attribute method must be used, even in asyncio servers.

        :param attr: the new attribute to be added to the list.
        :type attr: server.attribute or Attr or AttrData
        :param r_meth: the read method to be called on a read request
                       (if attr is of type server.attribute, then use the
                       fget field in the attr object instead)
        :type r_meth: callable
        :param w_meth: the write method to be called on a write request
                       (if attr is writable)
                       (if attr is of type server.attribute, then use the
                       fset field in the attr object instead)
        :type w_meth: callable
        :param is_allo_meth: the method that is called to check if it
                             is possible to access the attribute or not
                             (if attr is of type server.attribute, then use the
                             fisallowed field in the attr object instead)
        :type is_allo_meth: callable

        :returns: the newly created attribute.
        :rtype: Attr

        :raises DevFailed:
    """

    return __DeviceImpl__add_attribute_realization(
        self, attr, r_meth, w_meth, is_allo_meth
    )


async def __DeviceImpl__async_add_attribute(
    self, attr, r_meth=None, w_meth=None, is_allo_meth=None
):
    """
    async_add_attribute(self, attr, r_meth=None, w_meth=None, is_allo_meth=None) -> Attr

        Add a new attribute to the device attribute list.

        Please, note that if you add
        an attribute to a device at device creation time, this attribute will be added
        to the device class attribute list. Therefore, all devices belonging to the
        same class created after this attribute addition will also have this attribute.

        If you pass a reference to unbound method for read, write or is_allowed method
        (e.g. DeviceClass.read_function or self.__class__.read_function),
        during execution the corresponding bound method (self.read_function) will be used.

        :param attr: the new attribute to be added to the list.
        :type attr: server.attribute or Attr or AttrData
        :param r_meth: the read method to be called on a read request
                       (if attr is of type server.attribute, then use the
                       fget field in the attr object instead)
        :type r_meth: callable
        :param w_meth: the write method to be called on a write request
                       (if attr is writable)
                       (if attr is of type server.attribute, then use the
                       fset field in the attr object instead)
        :type w_meth: callable
        :param is_allo_meth: the method that is called to check if it
                             is possible to access the attribute or not
                             (if attr is of type server.attribute, then use the
                             fisallowed field in the attr object instead)
        :type is_allo_meth: callable

        :returns: the newly created attribute.
        :rtype: Attr

        :raises DevFailed:

        .. versionadded:: 10.0.0
    """

    return await get_worker().delegate(
        __DeviceImpl__add_attribute_realization,
        self,
        attr,
        r_meth,
        w_meth,
        is_allo_meth,
    )


def __DeviceImpl__add_attribute_realization(self, attr, r_meth, w_meth, is_allo_meth):
    attr_data = None
    type_hint = None

    if isinstance(attr, AttrData):
        attr_data = attr
        attr = attr.to_attr()

    att_name = attr.get_name()

    # get read method and its name
    r_name = f"read_{att_name}"
    if r_meth is None:
        if attr_data is not None:
            r_name = attr_data.read_method_name
        if hasattr(attr_data, "fget"):
            r_meth = attr_data.fget
        elif hasattr(self, r_name):
            r_meth = getattr(self, r_name)
    else:
        r_name = r_meth.__name__

    # patch it if attribute is readable
    if attr.get_writable() in (
        AttrWriteType.READ,
        AttrWriteType.READ_WRITE,
        AttrWriteType.READ_WITH_WRITE,
    ):
        type_hint = dict(r_meth.__annotations__).get("return", None)
        r_name = f"__wrapped_read_{att_name}_{r_name}__"
        r_meth_green_mode = getattr(attr_data, "read_green_mode", True)
        __patch_device_with_dynamic_attribute_read_method(
            self, r_name, r_meth, r_meth_green_mode
        )

    # get write method and its name
    w_name = f"write_{att_name}"
    if w_meth is None:
        if attr_data is not None:
            w_name = attr_data.write_method_name
        if hasattr(attr_data, "fset"):
            w_meth = attr_data.fset
        elif hasattr(self, w_name):
            w_meth = getattr(self, w_name)
    else:
        w_name = w_meth.__name__

    # patch it if attribute is writable
    if attr.get_writable() in (
        AttrWriteType.WRITE,
        AttrWriteType.READ_WRITE,
        AttrWriteType.READ_WITH_WRITE,
    ):
        type_hints = dict(w_meth.__annotations__)
        if type_hint is None and type_hints:
            type_hint = list(type_hints.values())[-1]

        w_name = f"__wrapped_write_{att_name}_{w_name}__"
        w_meth_green_mode = getattr(attr_data, "write_green_mode", True)
        __patch_device_with_dynamic_attribute_write_method(
            self, w_name, w_meth, w_meth_green_mode
        )

    # get is allowed method and its name
    ia_name = f"is_{att_name}_allowed"
    if is_allo_meth is None:
        if attr_data is not None:
            ia_name = attr_data.is_allowed_name
        if hasattr(attr_data, "fisallowed"):
            is_allo_meth = attr_data.fisallowed
        elif hasattr(self, ia_name):
            is_allo_meth = getattr(self, ia_name)
    else:
        ia_name = is_allo_meth.__name__

    # patch it if exists
    if is_allo_meth is not None:
        ia_name = f"__wrapped_is_allowed_{att_name}_{ia_name}__"
        ia_meth_green_mode = getattr(attr_data, "isallowed_green_mode", True)
        __patch_device_with_dynamic_attribute_is_allowed_method(
            self, ia_name, is_allo_meth, ia_meth_green_mode
        )

    if attr_data and type_hint:
        if not attr_data.has_dtype_kword:
            dtype, dformat, max_x, max_y = parse_type_hint(
                type_hint, caller="attribute"
            )
            if dformat is None:
                if attr_data.attr_format not in [
                    AttrDataFormat.IMAGE,
                    AttrDataFormat.SPECTRUM,
                ]:
                    raise RuntimeError(
                        "For numpy.ndarrays AttrDataFormat has to be specified"
                    )
                dformat = attr_data.attr_format

            dtype, dformat, enum_labels = get_attribute_type_format(
                dtype, dformat, None
            )
            attr_data.attr_type = dtype
            attr_data.attr_format = dformat
            if enum_labels:
                attr_data.set_enum_labels_to_attr_prop(enum_labels)
            if not attr_data.has_size_kword:
                if max_x:
                    attr_data.dim_x = max_x
                if max_y:
                    attr_data.dim_y = max_y

            attr = attr_data.to_attr()

    self._add_attribute(attr, r_name, w_name, ia_name)
    return attr


def __patch_device_with_dynamic_attribute_read_method(
    device, name, r_meth, r_meth_green_mode
):
    if __is_device_method(device, r_meth):
        if r_meth_green_mode:

            @functools.wraps(r_meth)
            def read_attr(device, attr):
                worker = get_worker()
                # already bound to device, so exclude device arg
                ret = worker.execute(r_meth, attr)
                if not attr.value_is_set() and ret is not None:
                    set_complex_value(attr, ret)
                return ret

        else:

            @functools.wraps(r_meth)
            def read_attr(device, attr):
                ret = r_meth(attr)
                if not attr.value_is_set() and ret is not None:
                    set_complex_value(attr, ret)
                return ret

    else:
        if r_meth_green_mode:

            @functools.wraps(r_meth)
            def read_attr(device, attr):
                worker = get_worker()
                # unbound function or not on device object, so include device arg
                ret = worker.execute(r_meth, device, attr)
                if not attr.value_is_set() and ret is not None:
                    set_complex_value(attr, ret)
                return ret

        else:

            @functools.wraps(r_meth)
            def read_attr(device, attr):
                ret = r_meth(device, attr)
                if not attr.value_is_set() and ret is not None:
                    set_complex_value(attr, ret)
                return ret

    if _force_tracing:
        read_attr = _forcefully_traced_method(read_attr)

    bound_method = types.MethodType(read_attr, device)
    setattr(device, name, bound_method)


def __patch_device_with_dynamic_attribute_write_method(
    device, name, w_meth, w_meth_green_mode
):
    if __is_device_method(device, w_meth):
        if w_meth_green_mode:

            @functools.wraps(w_meth)
            def write_attr(device, attr):
                worker = get_worker()
                # already bound to device, so exclude device arg
                return worker.execute(w_meth, attr)

        else:

            @functools.wraps(w_meth)
            def write_attr(device, attr):
                return w_meth(attr)

    else:
        if w_meth_green_mode:

            @functools.wraps(w_meth)
            def write_attr(device, attr):
                worker = get_worker()
                # unbound function or not on device object, so include device arg
                return worker.execute(w_meth, device, attr)

        else:
            write_attr = w_meth

    if _force_tracing:
        write_attr = _forcefully_traced_method(write_attr)

    bound_method = types.MethodType(write_attr, device)
    setattr(device, name, bound_method)


def __patch_device_with_dynamic_attribute_is_allowed_method(
    device, name, is_allo_meth, ia_meth_green_mode
):
    if __is_device_method(device, is_allo_meth):
        if ia_meth_green_mode:

            @functools.wraps(is_allo_meth)
            def is_allowed_attr(device, request_type):
                worker = get_worker()
                # already bound to device, so exclude device arg
                return worker.execute(is_allo_meth, request_type)

        else:

            @functools.wraps(is_allo_meth)
            def is_allowed_attr(device, request_type):
                return is_allo_meth(request_type)

    else:
        if ia_meth_green_mode:

            @functools.wraps(is_allo_meth)
            def is_allowed_attr(device, request_type):
                worker = get_worker()
                # unbound function or not on device object, so include device arg
                return worker.execute(is_allo_meth, device, request_type)

        else:
            is_allowed_attr = is_allo_meth

    if _force_tracing:
        is_allowed_attr = _forcefully_traced_method(is_allowed_attr)

    bound_method = types.MethodType(is_allowed_attr, device)
    setattr(device, name, bound_method)


def __is_device_method(device, func):
    """Return True if func is bound to device object (i.e., a method)"""
    return inspect.ismethod(func) and func.__self__ is device


def __DeviceImpl__remove_attribute(self, attr_name, free_it=False, clean_db=True):
    """
    remove_attribute(self, attr_name)

        Remove one attribute from the device attribute list.

        Note: Call of synchronous remove_attribute method from a coroutine function in
        an asyncio server may cause a deadlock.
        Use ``await`` :meth:`async_remove_attribute` instead.
        However, if overriding the synchronous method ``initialize_dynamic_attributes``,
        then the synchronous remove_attribute method must be used, even in asyncio servers.

        :param attr_name: attribute name
        :type attr_name: str

        :param free_it: free Attr object flag. Default False
        :type free_it: bool

        :param clean_db: clean attribute related info in db. Default True
        :type clean_db: bool

        :raises DevFailed:

        .. versionadded:: 9.5.0
            *free_it* parameter.
            *clean_db* parameter.

    """

    self._remove_attribute(attr_name, free_it, clean_db)


async def __DeviceImpl__async_remove_attribute(
    self, attr_name, free_it=False, clean_db=True
):
    """

    async_remove_attribute(self, attr_name, free_it=False, clean_db=True)

        Remove one attribute from the device attribute list.

        :param attr_name: attribute name
        :type attr_name: str

        :param free_it: free Attr object flag. Default False
        :type free_it: bool

        :param clean_db: clean attribute related info in db. Default True
        :type clean_db: bool

        :raises DevFailed:

        .. versionadded:: 10.0.0

    """

    await get_worker().delegate(self._remove_attribute, attr_name, free_it, clean_db)


def __DeviceImpl__add_command(self, cmd, device_level=True):
    """
    add_command(self, cmd, device_level=True) -> cmd

        Add a new command to the device command list.

        :param cmd: the new command to be added to the list
        :param device_level: Set this flag to true if the command must be added
                             for only this device

        :returns: The command to add
        :rtype: Command

        :raises DevFailed:
    """
    config = dict(cmd.__tango_command__[1][2])
    disp_level = DispLevel.OPERATOR

    cmd_name = cmd.__name__

    # default values
    fisallowed = "is_{0}_allowed".format(cmd_name)
    fisallowed_green_mode = True

    if config:
        if "Display level" in config:
            disp_level = config["Display level"]

        if "Is allowed" in config:
            fisallowed = config["Is allowed"]

        fisallowed_green_mode = config["Is allowed green_mode"]

    if is_pure_str(fisallowed):
        fisallowed = getattr(self, fisallowed, None)

    if fisallowed is not None:
        fisallowed_name = (
            f"__wrapped_{getattr(fisallowed, '__name__', f'is_{cmd_name}_allowed')}__"
        )
        __patch_device_with_dynamic_command_is_allowed_method(
            self, fisallowed_name, fisallowed, fisallowed_green_mode
        )
    else:
        fisallowed_name = ""

    setattr(self, cmd_name, cmd)

    self._add_command(
        cmd_name, cmd.__tango_command__[1], fisallowed_name, disp_level, device_level
    )
    return cmd


def __patch_device_with_dynamic_command_method(device, name, method):
    if __is_device_method(device, method):

        @functools.wraps(method)
        def wrapped_command_method(device, *args):
            worker = get_worker()
            # already bound to device, so exclude device arg
            return worker.execute(method, *args)

    else:

        @functools.wraps(method)
        def wrapped_command_method(device, *args):
            worker = get_worker()
            # unbound function or not on device object, so include device arg
            return worker.execute(method, device, *args)

    bound_method = types.MethodType(wrapped_command_method, device)
    setattr(device, name, bound_method)


def __patch_device_with_dynamic_command_is_allowed_method(
    device, name, is_allo_meth, green_mode
):
    if __is_device_method(device, is_allo_meth):
        if green_mode:

            @functools.wraps(is_allo_meth)
            def is_allowed_cmd(device):
                worker = get_worker()
                # already bound to device, so exclude device arg
                return worker.execute(is_allo_meth)

        else:
            is_allowed_cmd = is_allo_meth

    else:
        if green_mode:

            @functools.wraps(is_allo_meth)
            def is_allowed_cmd(device):
                worker = get_worker()
                # unbound function or not on device object, so include device arg
                return worker.execute(is_allo_meth, device)

        else:

            @functools.wraps(is_allo_meth)
            def is_allowed_cmd(device):
                # unbound function or not on device object, so include device arg
                return is_allo_meth(device)

    if _force_tracing:
        is_allowed_cmd = _forcefully_traced_method(is_allowed_cmd)

    bound_method = types.MethodType(is_allowed_cmd, device)
    setattr(device, name, bound_method)


def __DeviceImpl__remove_command(self, cmd_name, free_it=False, clean_db=True):
    """
    remove_command(self, cmd_name, free_it=False, clean_db=True)

        Remove one command from the device command list.

        :param cmd_name: command name to be removed from the list
        :type cmd_name: str
        :param free_it: set to true if the command object must be freed.
        :type free_it: bool
        :param clean_db: Clean command related information (included polling info
                         if the command is polled) from database.

        :raises DevFailed:
    """
    self._remove_command(cmd_name, free_it, clean_db)


def __DeviceImpl__debug_stream(self, msg, *args, source=None):
    """
    debug_stream(self, msg, *args, source=None)

        Sends the given message to the tango debug stream.

        Since PyTango 7.1.3, the same can be achieved with::

            print(msg, file=self.log_debug)

        :param msg: the message to be sent to the debug stream
        :type msg: str

        :param \\*args: Arguments to format a message string.

        :param source: Function that will be inspected for filename and lineno in the log message.
        :type source: Callable

        .. versionadded:: 9.4.2
            added *source* parameter
    """
    filename, line = get_source_location(source)
    if args:
        msg = msg % args
    self.__debug_stream(filename, line, msg)


def __DeviceImpl__info_stream(self, msg, *args, source=None):
    """
    info_stream(self, msg, *args, source=None)

        Sends the given message to the tango info stream.

        Since PyTango 7.1.3, the same can be achieved with::

            print(msg, file=self.log_info)

        :param msg: the message to be sent to the info stream
        :type msg: str

        :param \\*args: Arguments to format a message string.

        :param source: Function that will be inspected for filename and lineno in the log message.
        :type source: Callable

        .. versionadded:: 9.4.2
            added *source* parameter
    """
    filename, line = get_source_location(source)
    if args:
        msg = msg % args
    self.__info_stream(filename, line, msg)


def __DeviceImpl__warn_stream(self, msg, *args, source=None):
    """
    warn_stream(self, msg, *args, source=None)

        Sends the given message to the tango warn stream.

        Since PyTango 7.1.3, the same can be achieved with::

            print(msg, file=self.log_warn)

        :param msg: the message to be sent to the warn stream
        :type msg: str

        :param \\*args: Arguments to format a message string.

        :param source: Function that will be inspected for filename and lineno in the log message.
        :type source: Callable

        .. versionadded:: 9.4.2
            added *source* parameter
    """
    filename, line = get_source_location(source)
    if args:
        msg = msg % args
    self.__warn_stream(filename, line, msg)


def __DeviceImpl__error_stream(self, msg, *args, source=None):
    """
    error_stream(self, msg, *args, source=None)

        Sends the given message to the tango error stream.

        Since PyTango 7.1.3, the same can be achieved with::

            print(msg, file=self.log_error)

        :param msg: the message to be sent to the error stream
        :type msg: str

        :param \\*args: Arguments to format a message string.

        :param source: Function that will be inspected for filename and lineno in the log message.
        :type source: Callable

        .. versionadded:: 9.4.2
            added *source* parameter
    """
    filename, line = get_source_location(source)
    if args:
        msg = msg % args
    self.__error_stream(filename, line, msg)


def __DeviceImpl__fatal_stream(self, msg, *args, source=None):
    """
    fatal_stream(self, msg, *args, source=None)

        Sends the given message to the tango fatal stream.

        Since PyTango 7.1.3, the same can be achieved with::

            print(msg, file=self.log_fatal)

        :param msg: the message to be sent to the fatal stream
        :type msg: str

        :param \\*args: Arguments to format a message string.

        :param source: Function that will be inspected for filename and lineno in the log message.
        :type source: Callable

        .. versionadded:: 9.4.2
            added *source* parameter
    """
    filename, line = get_source_location(source)
    if args:
        msg = msg % args
    self.__fatal_stream(filename, line, msg)


@property
def __DeviceImpl__debug(self):
    if not hasattr(self, "_debug_s"):
        self._debug_s = TangoStream(self.debug_stream)
    return self._debug_s


@property
def __DeviceImpl__info(self):
    if not hasattr(self, "_info_s"):
        self._info_s = TangoStream(self.info_stream)
    return self._info_s


@property
def __DeviceImpl__warn(self):
    if not hasattr(self, "_warn_s"):
        self._warn_s = TangoStream(self.warn_stream)
    return self._warn_s


@property
def __DeviceImpl__error(self):
    if not hasattr(self, "_error_s"):
        self._error_s = TangoStream(self.error_stream)
    return self._error_s


@property
def __DeviceImpl__fatal(self):
    if not hasattr(self, "_fatal_s"):
        self._fatal_s = TangoStream(self.fatal_stream)
    return self._fatal_s


def __DeviceImpl__str(self):
    dev_name = "unknown"
    try:
        util = Util.instance(False)
        if not util.is_svr_starting() and not util.is_svr_shutting_down():
            dev_name = self.get_name()
    except DevFailed:
        pass  # Util singleton hasn't been initialised yet
    return f"{self.__class__.__name__}({dev_name})"


def __event_exception_converter(*args, **kwargs):
    args = list(args)
    exception = None

    if len(args) and isinstance(args[0], Exception):
        exception = args[0]
    elif "except" in kwargs:
        exception = kwargs.pop("except")

    if exception:
        args[0] = _exception_converter(exception)

    return args, kwargs


def __check_removed_dim_parameters(*args, **kwargs):
    if "dim_x" in kwargs or "dim_y" in kwargs:
        raise TypeError("dim_x and dim_y arguments are no longer supported")
    if len(args) < 2:
        return
    elif len(args) > 4:
        raise TypeError(
            "Too many arguments. "
            "Note, that dim_x and dim_y arguments are no longer supported."
        )
    last_arg = args[-1]
    if not isinstance(last_arg, AttrQuality) and isinstance(last_arg, numbers.Number):
        if len(args) == 2:
            msg = "For DevEncoded attribute it must one of str, bytes, bytearray. "
        else:
            msg = "It must be of type AttrQuality. "

        raise TypeError(
            f"Last argument, {last_arg}, has the incorrect type: {type(last_arg)}. "
            f"{msg}"
            "Note, that dim_x and dim_y arguments are no longer supported."
        )


def __DeviceImpl__push_change_event(self, attr_name, *args, **kwargs):
    """
    .. function:: push_change_event(self, attr_name, except)
                  push_change_event(self, attr_name, data)
                  push_change_event(self, attr_name, data, time_stamp, quality)
                  push_change_event(self, attr_name, str_data, data)
                  push_change_event(self, attr_name, str_data, data, time_stamp, quality)
        :noindex:

    Push a change event for the given attribute name.

    :param attr_name: attribute name
    :type attr_name: str
    :param data: the data to be sent as attribute event data. Data must be compatible with the
                 attribute type and format.
                 for SPECTRUM and IMAGE attributes, data can be any type of sequence of elements
                 compatible with the attribute type
    :param str_data: special variation for DevEncoded data type. In this case 'data' must
                     be a str or an object with the buffer interface.
    :type str_data: str
    :param except: Instead of data, you may want to send an exception.
    :type except: DevFailed
    :param time_stamp: the time stamp
    :type time_stamp: double
    :param quality: the attribute quality factor
    :type quality: AttrQuality

    :raises DevFailed: If the attribute data type is not coherent.

     .. versionchanged:: 10.1.0
        Removed optional 'dim_x' and 'dim_y' arguments. The dimensions are automatically
        determined from the data.
    """
    args, kwargs = __event_exception_converter(*args, **kwargs)
    __check_removed_dim_parameters(*args, **kwargs)
    self.__generic_push_event(attr_name, EventType.CHANGE_EVENT, *args, **kwargs)


def __DeviceImpl__push_alarm_event(self, attr_name, *args, **kwargs):
    """
    .. function:: push_alarm_event(self, attr_name, except)
                  push_alarm_event(self, attr_name, data)
                  push_alarm_event(self, attr_name, data, time_stamp, quality)
                  push_alarm_event(self, attr_name, str_data, data)
                  push_alarm_event(self, attr_name, str_data, data, time_stamp, quality)
        :noindex:

    Push an alarm event for the given attribute name.

    :param attr_name: attribute name
    :type attr_name: str
    :param data: the data to be sent as attribute event data. Data must be compatible with the
                 attribute type and format.
                 for SPECTRUM and IMAGE attributes, data can be any type of sequence of elements
                 compatible with the attribute type
    :param str_data: special variation for DevEncoded data type. In this case 'data' must
                     be a str or an object with the buffer interface.
    :type str_data: str
    :param except: Instead of data, you may want to send an exception.
    :type except: DevFailed
    :param time_stamp: the time stamp
    :type time_stamp: double
    :param quality: the attribute quality factor
    :type quality: AttrQuality

    :raises DevFailed: If the attribute data type is not coherent.

     .. versionchanged:: 10.1.0
        Removed optional 'dim_x' and 'dim_y' arguments. The dimensions are automatically
        determined from the data.
    """
    args, kwargs = __event_exception_converter(*args, **kwargs)
    __check_removed_dim_parameters(*args, **kwargs)
    self.__generic_push_event(attr_name, EventType.ALARM_EVENT, *args, **kwargs)


def __DeviceImpl__push_archive_event(self, attr_name, *args, **kwargs):
    """
    .. function:: push_archive_event(self, attr_name, except)
                  push_archive_event(self, attr_name, data)
                  push_archive_event(self, attr_name, data, time_stamp, quality)
                  push_archive_event(self, attr_name, str_data, data)
                  push_archive_event(self, attr_name, str_data, data, time_stamp, quality)
        :noindex:

    Push an archive event for the given attribute name.

    :param attr_name: attribute name
    :type attr_name: str
    :param data: the data to be sent as attribute event data. Data must be compatible with the
                 attribute type and format.
                 for SPECTRUM and IMAGE attributes, data can be any type of sequence of elements
                 compatible with the attribute type
    :param str_data: special variation for DevEncoded data type. In this case 'data' must
                     be a str or an object with the buffer interface.
    :type str_data: str
    :param except: Instead of data, you may want to send an exception.
    :type except: DevFailed
    :param time_stamp: the time stamp
    :type time_stamp: double
    :param quality: the attribute quality factor
    :type quality: AttrQuality

    :raises DevFailed: If the attribute data type is not coherent.

     .. versionchanged:: 10.1.0
        Removed optional 'dim_x' and 'dim_y' arguments. The dimensions are automatically
        determined from the data.
    """
    args, kwargs = __event_exception_converter(*args, **kwargs)
    __check_removed_dim_parameters(*args, **kwargs)
    self.__generic_push_event(attr_name, EventType.ARCHIVE_EVENT, *args, **kwargs)


def __DeviceImpl__push_event(self, attr_name, filt_names, filt_vals, *args, **kwargs):
    """
    .. function:: push_event(self, attr_name, filt_names, filt_vals, except)
                  push_event(self, attr_name, filt_names, filt_vals, data)
                  push_event(self, attr_name, filt_names, filt_vals, str_data, data)
                  push_event(self, attr_name, filt_names, filt_vals, data, time_stamp, quality)
                  push_event(self, attr_name, filt_names, filt_vals, str_data, data, time_stamp, quality)
        :noindex:

    Push a user event for the given attribute name.

    :param attr_name: attribute name
    :type attr_name: str
    :param filt_names: unused (kept for backwards compatibility) - pass an empty list.
    :type filt_names: Sequence[str]
    :param filt_vals: unused (kept for backwards compatibility) - pass an empty list.
    :type filt_vals: Sequence[double]
    :param data: the data to be sent as attribute event data. Data must be compatible with the
                 attribute type and format.
                 for SPECTRUM and IMAGE attributes, data can be any type of sequence of elements
                 compatible with the attribute type
    :param str_data: special variation for DevEncoded data type. In this case 'data' must
                     be a str or an object with the buffer interface.
    :type str_data: str
    :param except: Instead of data, you may want to send an exception.
    :type except: DevFailed
    :param time_stamp: the time stamp
    :type time_stamp: double
    :param quality: the attribute quality factor
    :type quality: AttrQuality

    :raises DevFailed: If the attribute data type is not coherent.

     .. versionchanged:: 10.1.0
        Removed optional 'dim_x' and 'dim_y' arguments. The dimensions are automatically
        determined from the data.
    """
    args, kwargs = __event_exception_converter(*args, **kwargs)
    __check_removed_dim_parameters(*args, **kwargs)
    self.__push_event(attr_name, filt_names, filt_vals, *args, **kwargs)


def __DeviceImpl__set_telemetry_enabled(self, enabled: bool):
    """
    set_telemetry_enabled(self, enabled) -> None

        Enable or disable the device's telemetry interface.

        This is a no-op if telemetry support isn't compiled into cppTango.

        :param enabled: True to enable telemetry tracing
        :type enabled: bool

        .. versionadded:: 10.0.0
    """
    if enabled:
        self._enable_telemetry()
    else:
        self._disable_telemetry()


def __DeviceImpl__set_kernel_tracing_enabled(self, enabled: bool):
    """
    set_kernel_tracing_enabled(self, enabled) -> None

        Enable or disable telemetry tracing of cppTango kernel methods, and
        for high-level PyTango devices, tracing of the PyTango kernel (BaseDevice)
        methods.

        This is a no-op if telemetry support isn't compiled into cppTango.

        :param enabled: True to enable kernel tracing
        :type enabled: bool

        .. versionadded:: 10.0.0
    """
    if enabled:
        self._enable_kernel_traces()
    else:
        self._disable_kernel_traces()


def __DeviceImpl__get_attribute_config(self, attr_names) -> list[AttributeConfig]:
    """
    Returns the list of :obj:`tango.AttributeConfig` for the requested names

    :param attr_names: sequence of str with attribute names, or single attribute name
    :type attr_names: list[str] | str

    :returns: :class:`tango.AttributeConfig` for each requested attribute name
    :rtype: list[:class:`tango.AttributeConfig`]

    """
    if is_pure_str(attr_names):
        attr_names = [attr_names]
    return self._get_attribute_config(attr_names)


def __DeviceImpl__fill_attr_polling_buffer(self, attribute_name, attr_history_stack):
    """
    fill_attr_polling_buffer(self, attribute_name, attr_history_stack) -> None

        Fill attribute polling buffer with your own data. E.g.:

        .. code-block:: python

            def fill_history(self):
                # note is such case quality will ATTR_VALID, and time_stamp will be time.time()
                self.fill_attr_polling_buffer(attribute_name, TimedAttrData(my_new_value))

        or:

        .. code-block:: python

            def fill_history(self):
                data = TimedAttrData(value=my_new_value,
                                     quality=AttrQuality.ATTR_WARNING,
                                     w_value=my_new_w_value,
                                     time_stamp=my_time)

                self.fill_attr_polling_buffer(attribute_name, data)

        or:

        .. code-block:: python

            def fill_history(self):
                data = [TimedAttrData(my_new_value),
                        TimedAttrData(error=RuntimeError("Cannot read value")]

                self.fill_attr_polling_buffer(attribute_name, data)

    :param attribute_name: name of the attribute to fill polling buffer
    :type attribute_name: :obj:`str`

    :param attr_history_stack: data to be inserted.
    :type attr_history_stack: :obj:`tango.TimedAttrData` or list[:obj:`tango.TimedAttrData`]

    :return: None

    :raises: :obj:`tango.DevFailed`

    .. versionadded:: 10.1.0
    """

    util = Util.instance(False)
    util.fill_attr_polling_buffer(self, attribute_name, attr_history_stack)


def __DeviceImpl__fill_cmd_polling_buffer(self, command_name, cmd_history_stack):
    """
    fill_cmd_polling_buffer(self, device, command_name, cmd_history_stack) -> None

        Fill command polling buffer with your own data. E.g.:


        .. code-block:: python

            def fill_history(self):
                # note is such case time_stamp will be set to time.time()
                self.fill_cmd_polling_buffer(command_name, TimedCmdData(my_new_value))

        or:

        .. code-block:: python

            def fill_history(self):
                data = TimedCmdData(value=my_new_value,
                                     time_stamp=my_time)

                self.fill_cmd_polling_buffer(command_name, data)

        or:

        .. code-block:: python

            def fill_history(self):
                data = [TimedCmdData(my_new_value),
                        TimedCmdData(error=RuntimeError("Cannot read value")]

                self.fill_cmd_polling_buffer(command_name, data)


    :param command_name: name of the command to fill polling buffer
    :type command_name: :obj:`str`

    :param cmd_history_stack: data to be inserted
    :type cmd_history_stack: :obj:`tango.TimedCmdData` or list[:obj:`tango.TimedCmdData`]

    :return: None

    :raises: :obj:`tango.DevFailed`

    .. versionadded:: 10.1.0
    """

    util = Util.instance(False)
    util.fill_cmd_polling_buffer(self, command_name, cmd_history_stack)


def __Device_2Impl__get_attribute_config_2(self, attr_names) -> list[AttributeConfig_2]:
    """
    Returns the list of :obj:`tango.AttributeConfig_2` for the requested names

    :param attr_names: sequence of str with attribute names, or single attribute name
    :type attr_names: list[str] | str

    :returns: :class:`tango.AttributeConfig_2` for each requested attribute name
    :rtype: list[:class:`tango.AttributeConfig_2`]
    """
    if is_pure_str(attr_names):
        attr_names = [attr_names]
    return self._get_attribute_config_2(attr_names)


def __Device_3Impl__get_attribute_config_3(self, attr_names) -> list[AttributeConfig_3]:
    """
    Returns the list of :obj:`tango.AttributeConfig_3` for the requested names

    :param attr_names: sequence of str with attribute names, or single attribute name
    :type attr_names: list[str] | str

    :returns: :class:`tango.AttributeConfig_3` for each requested attribute name
    :rtype: list[:class:`tango.AttributeConfig_3`]
    """
    if is_pure_str(attr_names):
        attr_names = [attr_names]
    return self._get_attribute_config_3(attr_names)


def __init_DeviceImpl():
    DeviceImpl._device_class_instance = None
    DeviceImpl.get_device_class = __DeviceImpl__get_device_class
    DeviceImpl.get_device_properties = __DeviceImpl__get_device_properties
    DeviceImpl.add_attribute = __DeviceImpl__add_attribute
    DeviceImpl.remove_attribute = __DeviceImpl__remove_attribute
    DeviceImpl.add_command = __DeviceImpl__add_command
    DeviceImpl.remove_command = __DeviceImpl__remove_command
    DeviceImpl.async_add_attribute = __DeviceImpl__async_add_attribute
    DeviceImpl.async_remove_attribute = __DeviceImpl__async_remove_attribute
    DeviceImpl.__str__ = __DeviceImpl__str
    DeviceImpl.__repr__ = __DeviceImpl__str
    DeviceImpl.debug_stream = __DeviceImpl__debug_stream
    DeviceImpl.info_stream = __DeviceImpl__info_stream
    DeviceImpl.warn_stream = __DeviceImpl__warn_stream
    DeviceImpl.error_stream = __DeviceImpl__error_stream
    DeviceImpl.fatal_stream = __DeviceImpl__fatal_stream
    DeviceImpl.log_debug = __DeviceImpl__debug
    DeviceImpl.log_info = __DeviceImpl__info
    DeviceImpl.log_warn = __DeviceImpl__warn
    DeviceImpl.log_error = __DeviceImpl__error
    DeviceImpl.log_fatal = __DeviceImpl__fatal
    DeviceImpl.push_change_event = __DeviceImpl__push_change_event
    DeviceImpl.push_alarm_event = __DeviceImpl__push_alarm_event
    DeviceImpl.push_archive_event = __DeviceImpl__push_archive_event
    DeviceImpl.push_event = __DeviceImpl__push_event
    DeviceImpl.set_telemetry_enabled = __DeviceImpl__set_telemetry_enabled
    DeviceImpl.set_kernel_tracing_enabled = __DeviceImpl__set_kernel_tracing_enabled
    DeviceImpl.get_attribute_config = __DeviceImpl__get_attribute_config
    DeviceImpl.fill_attr_polling_buffer = __DeviceImpl__fill_attr_polling_buffer
    DeviceImpl.fill_cmd_polling_buffer = __DeviceImpl__fill_cmd_polling_buffer


def __init_Device_2Impl():
    Device_2Impl.get_attribute_config_2 = __Device_2Impl__get_attribute_config_2


def __init_Device_3Impl():
    Device_3Impl.get_attribute_config_3 = __Device_3Impl__get_attribute_config_3


def __Logger__log(self, level, msg, *args):
    """
    log(self, level, msg, *args)

        Sends the given message to the tango the selected stream.

        :param level: Log level
        :type level: Level.LevelLevel
        :param msg: the message to be sent to the stream
        :type msg: str
        :param args: list of optional message arguments
        :type args: Sequence[str]
    """
    filename, line = get_source_location()
    if args:
        msg = msg % args
    self.__log(filename, line, level, msg)


def __Logger__log_unconditionally(self, level, msg, *args):
    """
    log_unconditionally(self, level, msg, *args)

        Sends the given message to the tango the selected stream,
        without checking the level.

        :param level: Log level
        :type level: Level.LevelLevel
        :param msg: the message to be sent to the stream
        :type msg: str
        :param args: list of optional message arguments
        :type args: Sequence[str]
    """
    filename, line = get_source_location()
    if args:
        msg = msg % args
    self.__log_unconditionally(filename, line, level, msg)


def __Logger__debug(self, msg, *args):
    """
    debug(self, msg, *args)

        Sends the given message to the tango debug stream.

        :param msg: the message to be sent to the debug stream
        :type msg: str
        :param args: list of optional message arguments
        :type args: Sequence[str]
    """
    filename, line = get_source_location()
    if args:
        msg = msg % args
    self.__debug(filename, line, msg)


def __Logger__info(self, msg, *args):
    """
    info(self, msg, *args)

        Sends the given message to the tango info stream.

        :param msg: the message to be sent to the info stream
        :type msg: str
        :param args: list of optional message arguments
        :type args: Sequence[str]
    """
    filename, line = get_source_location()
    if args:
        msg = msg % args
    self.__info(filename, line, msg)


def __Logger__warn(self, msg, *args):
    """
    warn(self, msg, *args)

        Sends the given message to the tango warn stream.

        :param msg: the message to be sent to the warn stream
        :type msg: str
        :param args: list of optional message arguments
        :type args: Sequence[str]
    """
    filename, line = get_source_location()
    if args:
        msg = msg % args
    self.__warn(filename, line, msg)


def __Logger__error(self, msg, *args):
    """
    error(self, msg, *args)

        Sends the given message to the tango error stream.

        :param msg: the message to be sent to the error stream
        :type msg: str
        :param args: list of optional message arguments
        :type args: Sequence[str]
    """
    filename, line = get_source_location()
    if args:
        msg = msg % args
    self.__error(filename, line, msg)


def __Logger__fatal(self, msg, *args):
    """
    fatal(self, msg, *args)

        Sends the given message to the tango fatal stream.

        :param msg: the message to be sent to the fatal stream
        :type msg: str
        :param args: list of optional message arguments
        :type args: Sequence[str]
    """
    filename, line = get_source_location()
    if args:
        msg = msg % args
    self.__fatal(filename, line, msg)


def __UserDefaultAttrProp_set_enum_labels(self, enum_labels):
    """
    set_enum_labels(self, enum_labels)

        Set default enumeration labels.

        :param enum_labels: list of enumeration labels
        :type enum_labels: Sequence[str]

        New in PyTango 9.2.0
    """
    elbls = StdStringVector()
    for enu in enum_labels:
        elbls.append(enu)
    return self._set_enum_labels(elbls)


def __Attr__str(self):
    return f"{self.__class__.__name__}({self.get_name()})"


def __init_Attr():
    Attr.__str__ = __Attr__str
    Attr.__repr__ = __Attr__str


def __init_UserDefaultAttrProp():
    UserDefaultAttrProp.set_enum_labels = __UserDefaultAttrProp_set_enum_labels


def __init_Logger():
    Logger.log = __Logger__log
    Logger.log_unconditionally = __Logger__log_unconditionally
    Logger.debug = __Logger__debug
    Logger.info = __Logger__info
    Logger.warning = __Logger__warn
    Logger.error = __Logger__error
    Logger.fatal = __Logger__fatal

    # kept for backward compatibility
    Logger.warn = __Logger__warn


def device_server_init(doc=True):
    __init_DeviceImpl()
    __init_Device_2Impl()
    __init_Device_3Impl()
    __init_Attribute()
    __init_Attr()
    __init_UserDefaultAttrProp()
    __init_Logger()