summaryrefslogtreecommitdiff
path: root/pyvisa/highlevel.py
blob: b6f610b256f1e1d67015df20be0eaf28df8285a3 (plain)
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
# -*- coding: utf-8 -*-
"""
    pyvisa.highlevel
    ~~~~~~~~~~~~~~~~

    High level Visa library wrapper.

    This file is part of PyVISA.

    :copyright: 2014 by PyVISA Authors, see AUTHORS for more details.
    :license: MIT, see LICENSE for more details.
"""

from __future__ import division, unicode_literals, print_function, absolute_import

import contextlib
import collections
import pkgutil
import os
from collections import defaultdict

from . import logger
from . import constants
from . import errors
from . import rname

#: Resource extended information
#:
#: Named tuple with information about a resource. Returned by some :class:`ResourceManager` methods.
#:
#: :interface_type: Interface type of the given resource string. :class:`pyvisa.constants.InterfaceType`
#: :interface_board_number: Board number of the interface of the given resource string.
#: :resource_class: Specifies the resource class (for example, "INSTR") of the given resource string.
#: :resource_name: This is the expanded version of the given resource string.
#:                       The format should be similar to the VISA-defined canonical resource name.
#: :alias: Specifies the user-defined alias for the given resource string.
ResourceInfo = collections.namedtuple('ResourceInfo',
                                      'interface_type interface_board_number '
                                      'resource_class resource_name alias')


class VisaLibraryBase(object):
    """Base for VISA library classes.

    A class derived from `VisaLibraryBase` library provides the low-level communication
    to the underlying devices providing Pythonic wrappers to VISA functions. But not all
    derived class must/will implement all methods.

    The default VisaLibrary class is :class:`pyvisa.ctwrapper.highlevel.NIVisaLibrary`,
    which implements a ctypes wrapper around the NI-VISA library.

    In general, you should not instantiate it directly. The object exposed to the user
    is the :class:`pyvisa.highlevel.ResourceManager`. If needed, you can access the
    VISA library from it::

        >>> import visa
        >>> rm = visa.ResourceManager("/path/to/my/libvisa.so.7")
        >>> lib = rm.visalib
    """

    #: Default ResourceManager instance for this library.
    resource_manager = None

    #: Maps library path to VisaLibrary object
    _registry = dict()

    #: Last return value of the library.
    _last_status = 0

    #: Maps session handle to last status. dict()
    _last_status_in_session = None

    #: Maps session handle to warnings to ignore. defaultdict(set)
    _ignore_warning_in_session = None

    #: Contains all installed event handlers.
    #: Its elements are tuples with three elements: The handler itself (a Python
    #: callable), the user handle (as a ct object) and the handler again, this
    #: time as a ct object created with CFUNCTYPE.
    handlers = None

    #: Set error codes on which to issue a warning. set
    issue_warning_on = None

    def __new__(cls, library_path=''):
        if library_path == '':
            errs = []
            for path in cls.get_library_paths():
                try:
                    return cls(path)
                except OSError as e:
                    logger.debug('Could not open VISA library %s: %s', path, str(e))
                    errs.append(str(e))
                except Exception as e:
                    errs.append(str(e))
            else:
                raise OSError('Could not open VISA library:\n' + '\n'.join(errs))

        if (cls, library_path) in cls._registry:
            return cls._registry[(cls, library_path)]

        obj = super(VisaLibraryBase, cls).__new__(cls)

        obj.library_path = library_path

        obj._logging_extra = {'library_path': obj.library_path}

        obj._init()

        # Create instance specific registries.
        #: Error codes on which to issue a warning.
        obj.issue_warning_on = set(errors.default_warnings)
        obj._last_status_in_session = dict()
        obj._ignore_warning_in_session = defaultdict(set)
        obj.handlers = defaultdict(list)

        logger.debug('Created library wrapper for %s', library_path)

        cls._registry[(cls, library_path)] = obj

        return obj

    @staticmethod
    def get_library_paths():
        """Override this method to return an iterable of possible library_paths
        to try in case that no argument is given.
        """
        return 'unset',

    @staticmethod
    def get_debug_info():
        """Override this method to return an iterable of lines with the backend debug details.
        """
        return ['Does not provide debug info']

    def _init(self):
        """Override this method to customize VisaLibrary initialization.
        """
        pass

    def __str__(self):
        return 'Visa Library at %s' % self.library_path

    def __repr__(self):
        return '<VisaLibrary(%r)>' % self.library_path

    @property
    def last_status(self):
        """Last return value of the library.
        """
        return self._last_status

    def get_last_status_in_session(self, session):
        """Last status in session.

        Helper function to be called by resources properties.
        """
        try:
            return self._last_status_in_session[session]
        except KeyError:
            raise errors.Error('The session %r does not seem to be valid as it does not have any last status' % session)

    @contextlib.contextmanager
    def ignore_warning(self, session, *warnings_constants):
        """A session dependent context for ignoring warnings

        :param session: Unique logical identifier to a session.
        :param warnings_constants: constants identifying the warnings to ignore.
        """
        self._ignore_warning_in_session[session].update(warnings_constants)
        yield
        self._ignore_warning_in_session[session].difference_update(warnings_constants)

    def install_visa_handler(self, session, event_type, handler, user_handle=None):
        """Installs handlers for event callbacks.

        :param session: Unique logical identifier to a session.
        :param event_type: Logical event identifier.
        :param handler: Interpreted as a valid reference to a handler to be installed by a client application.
        :param user_handle: A value specified by an application that can be used for identifying handlers
                            uniquely for an event type.
        :returns: user handle (a ctypes object)
        """
        try:
            new_handler = self.install_handler(session, event_type, handler, user_handle)
        except TypeError as e:
            raise errors.VisaTypeError(str(e))

        self.handlers[session].append(new_handler + (event_type,))
        return new_handler[1]

    def uninstall_visa_handler(self, session, event_type, handler, user_handle=None):
        """Uninstalls handlers for events.

        :param session: Unique logical identifier to a session.
        :param event_type: Logical event identifier.
        :param handler: Interpreted as a valid reference to a handler to be uninstalled by a client application.
        :param user_handle: The user handle (ctypes object or None) returned by install_visa_handler.
        """
        for ndx, element in enumerate(self.handlers[session]):
            if element[0] is handler and element[1] is user_handle and element[4] == event_type:
                del self.handlers[session][ndx]
                break
        else:
            raise errors.UnknownHandler(event_type, handler, user_handle)
        self.uninstall_handler(session, event_type,  element[2], user_handle)

    def __uninstall_all_handlers_helper(self, session):
        for element in self.handlers[session]:
            self.uninstall_handler(session, element[4],  element[2], element[1])
        del self.handlers[session]

    def uninstall_all_visa_handlers(self, session):
        """Uninstalls all previously installed handlers for a particular session.

        :param session: Unique logical identifier to a session. If None, operates on all sessions.
        """

        if session is not None:
            self.__uninstall_all_handlers_helper(session)
        else:
            for session in list(self.handlers):
                self.__uninstall_all_handlers_helper(session)

    def read_memory(self, session, space, offset, width, extended=False):
        """Reads in an 8-bit, 16-bit, 32-bit, or 64-bit value from the specified memory space and offset.

        Corresponds to viIn* functions of the VISA library.

        :param session: Unique logical identifier to a session.
        :param space: Specifies the address space. (Constants.*SPACE*)
        :param offset: Offset (in bytes) of the address or register from which to read.
        :param width: Number of bits to read.
        :param extended: Use 64 bits offset independent of the platform.
        :return: Data read from memory, return value of the library call.
        :rtype: int, :class:`pyvisa.constants.StatusCode`
        """
        if width == 8:
            return self.in_8(session, space, offset, extended)
        elif width == 16:
            return self.in_16(session, space, offset, extended)
        elif width == 32:
            return self.in_32(session, space, offset, extended)
        elif width == 64:
            return self.in_64(session, space, offset, extended)

        raise ValueError('%s is not a valid size. Valid values are 8, 16, 32 or 64' % width)

    def write_memory(self, session, space, offset, data, width, extended=False):
        """Write in an 8-bit, 16-bit, 32-bit, 64-bit value to the specified memory space and offset.

        Corresponds to viOut* functions of the VISA library.

        :param session: Unique logical identifier to a session.
        :param space: Specifies the address space. (Constants.*SPACE*)
        :param offset: Offset (in bytes) of the address or register from which to read.
        :param data: Data to write to bus.
        :param width: Number of bits to read.
        :param extended: Use 64 bits offset independent of the platform.
        :return: return value of the library call.
        :rtype: :class:`pyvisa.constants.StatusCode`
        """
        if width == 8:
            return self.out_8(session, space, offset, data, extended)
        elif width == 16:
            return self.out_16(session, space, offset, data, extended)
        elif width == 32:
            return self.out_32(session, space, offset, data, extended)
        elif width == 64:
            return self.out_64(session, space, offset, data, extended)

        raise ValueError('%s is not a valid size. Valid values are 8, 16, 32, or 64' % width)

    def move_in(self, session, space, offset, length, width, extended=False):
        """Moves a block of data to local memory from the specified address space and offset.

        Corresponds to viMoveIn* functions of the VISA library.

        :param session: Unique logical identifier to a session.
        :param space: Specifies the address space. (Constants.*SPACE*)
        :param offset: Offset (in bytes) of the address or register from which to read.
        :param length: Number of elements to transfer, where the data width of the elements to transfer
                       is identical to the source data width.
        :param width: Number of bits to read per element.
        :param extended: Use 64 bits offset independent of the platform.
        :return: Data read from the bus, return value of the library call.
        :rtype: list, :class:`pyvisa.constants.StatusCode`
        """
        if width == 8:
            return self.move_in_8(session, space, offset, length, extended)
        elif width == 16:
            return self.move_in_16(session, space, offset, length, extended)
        elif width == 32:
            return self.move_in_32(session, space, offset, length, extended)
        elif width == 64:
            return self.move_in_64(session, space, offset, length, extended)

        raise ValueError('%s is not a valid size. Valid values are 8, 16, 32 or 64' % width)

    def move_out(self, session, space, offset, length, data, width, extended=False):
        """Moves a block of data from local memory to the specified address space and offset.

        Corresponds to viMoveOut* functions of the VISA library.

        :param session: Unique logical identifier to a session.
        :param space: Specifies the address space. (Constants.*SPACE*)
        :param offset: Offset (in bytes) of the address or register from which to read.
        :param length: Number of elements to transfer, where the data width of the elements to transfer
                       is identical to the source data width.
        :param data: Data to write to bus.
        :param width: Number of bits to read per element.
        :param extended: Use 64 bits offset independent of the platform.
        :return: return value of the library call.
        :rtype: :class:`pyvisa.constants.StatusCode`
        """
        if width == 8:
            return self.move_out_8(session, space, offset, length, data, extended)
        elif width == 16:
            return self.move_out_16(session, space, offset, length, data, extended)
        elif width == 32:
            return self.move_out_32(session, space, offset, length, data, extended)
        elif width == 64:
            return self.move_out_64(session, space, offset, length, data, extended)

        raise ValueError('%s is not a valid size. Valid values are 8, 16, 32 or 64' % width)

    def peek(self, session, address, width):
        """Read an 8, 16, 32, or 64-bit value from the specified address.

        Corresponds to viPeek* functions of the VISA library.

        :param session: Unique logical identifier to a session.
        :param address: Source address to read the value.
        :param width: Number of bits to read.
        :return: Data read from bus, return value of the library call.
        :rtype: bytes, :class:`pyvisa.constants.StatusCode`
        """

        if width == 8:
            return self.peek_8(session, address)
        elif width == 16:
            return self.peek_16(session, address)
        elif width == 32:
            return self.peek_32(session, address)
        elif width == 64:
            return self.peek_64(session, address)

        raise ValueError('%s is not a valid size. Valid values are 8, 16, 32 or 64' % width)

    def poke(self, session, address, width, data):
        """Writes an 8, 16, 32, or 64-bit value from the specified address.

        Corresponds to viPoke* functions of the VISA library.

        :param session: Unique logical identifier to a session.
        :param address: Source address to read the value.
        :param width: Number of bits to read.
        :param data: Data to be written to the bus.
        :return: return value of the library call.
        :rtype: :class:`pyvisa.constants.StatusCode`
        """

        if width == 8:
            return self.poke_8(session, address, data)
        elif width == 16:
            return self.poke_16(session, address, data)
        elif width == 32:
            return self.poke_32(session, address, data)
        elif width == 64:
            return self.poke_64(session, address, data)

        raise ValueError('%s is not a valid size. Valid values are 8, 16, 32, or 64' % width)

    # Methods that VISA Library implementations must implement

    def assert_interrupt_signal(self, session, mode, status_id):
        """Asserts the specified interrupt or signal.

        Corresponds to viAssertIntrSignal function of the VISA library.

        :param session: Unique logical identifier to a session.
        :param mode: How to assert the interrupt. (Constants.ASSERT*)
        :param status_id: This is the status value to be presented during an interrupt acknowledge cycle.
        :return: return value of the library call.
        :rtype: :class:`pyvisa.constants.StatusCode`
        """
        raise NotImplementedError

    def assert_trigger(self, session, protocol):
        """Asserts software or hardware trigger.

        Corresponds to viAssertTrigger function of the VISA library.

        :param session: Unique logical identifier to a session.
        :param protocol: Trigger protocol to use during assertion. (Constants.PROT*)
        :return: return value of the library call.
        :rtype: :class:`pyvisa.constants.StatusCode`
        """
        raise NotImplementedError

    def assert_utility_signal(self, session, line):
        """Asserts or deasserts the specified utility bus signal.

        Corresponds to viAssertUtilSignal function of the VISA library.

        :param session: Unique logical identifier to a session.
        :param line: specifies the utility bus signal to assert. (Constants.VI_UTIL_ASSERT*)
        :return: return value of the library call.
        :rtype: :class:`pyvisa.constants.StatusCode`
        """
        raise NotImplementedError

    def buffer_read(self, session, count):
        """Reads data from device or interface through the use of a formatted I/O read buffer.

        Corresponds to viBufRead function of the VISA library.

        :param session: Unique logical identifier to a session.
        :param count: Number of bytes to be read.
        :return: data read, return value of the library call.
        :rtype: bytes, :class:`pyvisa.constants.StatusCode`
        """
        raise NotImplementedError

    def buffer_write(self, session, data):
        """Writes data to a formatted I/O write buffer synchronously.

        Corresponds to viBufWrite function of the VISA library.

        :param session: Unique logical identifier to a session.
        :param data: data to be written.
        :type data: bytes
        :return: number of written bytes, return value of the library call.
        :rtype: int, :class:`pyvisa.constants.StatusCode`
        """
        raise NotImplementedError

    def clear(self, session):
        """Clears a device.

        Corresponds to viClear function of the VISA library.

        :param session: Unique logical identifier to a session.
        :return: return value of the library call.
        :rtype: :class:`pyvisa.constants.StatusCode`
        """
        raise NotImplementedError

    def close(self, session):
        """Closes the specified session, event, or find list.

        Corresponds to viClose function of the VISA library.

        :param session: Unique logical identifier to a session, event, or find list.
        :return: return value of the library call.
        :rtype: :class:`pyvisa.constants.StatusCode`
        """
        raise NotImplementedError

    def disable_event(self, session, event_type, mechanism):
        """Disables notification of the specified event type(s) via the specified mechanism(s).

        Corresponds to viDisableEvent function of the VISA library.

        :param session: Unique logical identifier to a session.
        :param event_type: Logical event identifier.
        :param mechanism: Specifies event handling mechanisms to be disabled.
                          (Constants.VI_QUEUE, .VI_HNDLR, .VI_SUSPEND_HNDLR, .VI_ALL_MECH)
        :return: return value of the library call.
        :rtype: :class:`pyvisa.constants.StatusCode`
        """
        raise NotImplementedError

    def discard_events(self, session, event_type, mechanism):
        """Discards event occurrences for specified event types and mechanisms in a session.

        Corresponds to viDiscardEvents function of the VISA library.

        :param session: Unique logical identifier to a session.
        :param event_type: Logical event identifier.
        :param mechanism: Specifies event handling mechanisms to be discarded.
                          (Constants.VI_QUEUE, .VI_HNDLR, .VI_SUSPEND_HNDLR, .VI_ALL_MECH)
        :return: return value of the library call.
        :rtype: :class:`pyvisa.constants.StatusCode`
        """
        raise NotImplementedError

    def enable_event(self, session, event_type, mechanism, context=None):
        """Enable event occurrences for specified event types and mechanisms in a session.

        Corresponds to viEnableEvent function of the VISA library.

        :param session: Unique logical identifier to a session.
        :param event_type: Logical event identifier.
        :param mechanism: Specifies event handling mechanisms to be enabled.
                          (Constants.VI_QUEUE, .VI_HNDLR, .VI_SUSPEND_HNDLR)
        :param context:
        :return: return value of the library call.
        :rtype: :class:`pyvisa.constants.StatusCode`
        """
        raise NotImplementedError

    def flush(self, session, mask):
        """Manually flushes the specified buffers associated with formatted I/O operations and/or serial communication.

        Corresponds to viFlush function of the VISA library.

        :param session: Unique logical identifier to a session.
        :param mask: Specifies the action to be taken with flushing the buffer.
                     (Constants.READ*, .WRITE*, .IO*)
        :return: return value of the library call.
        :rtype: :class:`pyvisa.constants.StatusCode`
        """
        raise NotImplementedError

    def get_attribute(self, session, attribute):
        """Retrieves the state of an attribute.

        Corresponds to viGetAttribute function of the VISA library.

        :param session: Unique logical identifier to a session, event, or find list.
        :param attribute: Resource attribute for which the state query is made (see Attributes.*)
        :return: The state of the queried attribute for a specified resource, return value of the library call.
        :rtype: unicode (Py2) or str (Py3), list or other type, :class:`pyvisa.constants.StatusCode`
        """
        raise NotImplementedError

    def gpib_command(self, session, data):
        """Write GPIB command bytes on the bus.

        Corresponds to viGpibCommand function of the VISA library.

        :param session: Unique logical identifier to a session.
        :param data: data tor write.
        :type data: bytes
        :return: Number of written bytes, return value of the library call.
        :rtype: int, :class:`pyvisa.constants.StatusCode`
        """
        raise NotImplementedError

    def gpib_control_atn(self, session, mode):
        """Specifies the state of the ATN line and the local active controller state.

        Corresponds to viGpibControlATN function of the VISA library.

        :param session: Unique logical identifier to a session.
        :param mode: Specifies the state of the ATN line and optionally the local active controller state.
                     (Constants.VI_GPIB_ATN*)
        :return: return value of the library call.
        :rtype: :class:`pyvisa.constants.StatusCode`
        """
        raise NotImplementedError

    def gpib_control_ren(self, session, mode):
        """Controls the state of the GPIB Remote Enable (REN) interface line, and optionally the remote/local
        state of the device.

        Corresponds to viGpibControlREN function of the VISA library.

        :param session: Unique logical identifier to a session.
        :param mode: Specifies the state of the REN line and optionally the device remote/local state.
                     (Constants.VI_GPIB_REN*)
        :return: return value of the library call.
        :rtype: :class:`pyvisa.constants.StatusCode`
        """
        raise NotImplementedError

    def gpib_pass_control(self, session, primary_address, secondary_address):
        """Tell the GPIB device at the specified address to become controller in charge (CIC).

        Corresponds to viGpibPassControl function of the VISA library.

        :param session: Unique logical identifier to a session.
        :param primary_address: Primary address of the GPIB device to which you want to pass control.
        :param secondary_address: Secondary address of the targeted GPIB device.
                                  If the targeted device does not have a secondary address,
                                  this parameter should contain the value Constants.VI_NO_SEC_ADDR.
        :return: return value of the library call.
        :rtype: :class:`pyvisa.constants.StatusCode`
        """
        raise NotImplementedError

    def gpib_send_ifc(self, session):
        """Pulse the interface clear line (IFC) for at least 100 microseconds.

        Corresponds to viGpibSendIFC function of the VISA library.

        :param session: Unique logical identifier to a session.
        :return: return value of the library call.
        :rtype: :class:`pyvisa.constants.StatusCode`
        """
        raise NotImplementedError

    def in_8(self, session, space, offset, extended=False):
        """Reads in an 8-bit value from the specified memory space and offset.

        Corresponds to viIn8* function of the VISA library.

        :param session: Unique logical identifier to a session.
        :param space: Specifies the address space. (Constants.*SPACE*)
        :param offset: Offset (in bytes) of the address or register from which to read.
        :param extended: Use 64 bits offset independent of the platform.
        :return: Data read from memory, return value of the library call.
        :rtype: int, :class:`pyvisa.constants.StatusCode`
        """
        raise NotImplementedError

    def in_16(self, session, space, offset, extended=False):
        """Reads in an 16-bit value from the specified memory space and offset.

        Corresponds to viIn16* function of the VISA library.

        :param session: Unique logical identifier to a session.
        :param space: Specifies the address space. (Constants.*SPACE*)
        :param offset: Offset (in bytes) of the address or register from which to read.
        :param extended: Use 64 bits offset independent of the platform.
        :return: Data read from memory, return value of the library call.
        :rtype: int, :class:`pyvisa.constants.StatusCode`
        """
        raise NotImplementedError

    def in_32(self, session, space, offset, extended=False):
        """Reads in an 32-bit value from the specified memory space and offset.

        Corresponds to viIn32* function of the VISA library.

        :param session: Unique logical identifier to a session.
        :param space: Specifies the address space. (Constants.*SPACE*)
        :param offset: Offset (in bytes) of the address or register from which to read.
        :param extended: Use 64 bits offset independent of the platform.
        :return: Data read from memory, return value of the library call.
        :rtype: int, :class:`pyvisa.constants.StatusCode`
        """
        raise NotImplementedError

    def in_64(self, session, space, offset, extended=False):
        """Reads in an 64-bit value from the specified memory space and offset.

        Corresponds to viIn64* function of the VISA library.

        :param session: Unique logical identifier to a session.
        :param space: Specifies the address space. (Constants.*SPACE*)
        :param offset: Offset (in bytes) of the address or register from which to read.
        :param extended: Use 64 bits offset independent of the platform.
        :return: Data read from memory, return value of the library call.
        :rtype: int, :class:`pyvisa.constants.StatusCode`
        """
        raise NotImplementedError

    def install_handler(self, session, event_type, handler, user_handle):
        """Installs handlers for event callbacks.

        Corresponds to viInstallHandler function of the VISA library.

        :param session: Unique logical identifier to a session.
        :param event_type: Logical event identifier.
        :param handler: Interpreted as a valid reference to a handler to be installed by a client application.
        :param user_handle: A value specified by an application that can be used for identifying handlers
                            uniquely for an event type.
        :returns: a handler descriptor which consists of three elements:
                 - handler (a python callable)
                 - user handle (a ctypes object)
                 - ctypes handler (ctypes object wrapping handler)
                 and return value of the library call.
        :rtype: int, :class:`pyvisa.constants.StatusCode`
        """
        raise NotImplementedError

    def list_resources(self, session, query='?*::INSTR'):
        """Returns a tuple of all connected devices matching query.

        :param query: regular expression used to match devices.
        """
        raise NotImplementedError

    def lock(self, session, lock_type, timeout, requested_key=None):
        """Establishes an access mode to the specified resources.

        Corresponds to viLock function of the VISA library.

        :param session: Unique logical identifier to a session.
        :param lock_type: Specifies the type of lock requested, either Constants.EXCLUSIVE_LOCK or Constants.SHARED_LOCK.
        :param timeout: Absolute time period (in milliseconds) that a resource waits to get unlocked by the
                        locking session before returning an error.
        :param requested_key: This parameter is not used and should be set to VI_NULL when lockType is VI_EXCLUSIVE_LOCK.
        :return: access_key that can then be passed to other sessions to share the lock, return value of the library call.
        :rtype: str, :class:`pyvisa.constants.StatusCode`
        """
        raise NotImplementedError

    def map_address(self, session, map_space, map_base, map_size,
                    access=False, suggested=None):
        """Maps the specified memory space into the process's address space.

        Corresponds to viMapAddress function of the VISA library.

        :param session: Unique logical identifier to a session.
        :param map_space: Specifies the address space to map. (Constants.*SPACE*)
        :param map_base: Offset (in bytes) of the memory to be mapped.
        :param map_size: Amount of memory to map (in bytes).
        :param access:
        :param suggested: If not Constants.VI_NULL (0), the operating system attempts to map the memory to the address
                          specified in suggested. There is no guarantee, however, that the memory will be mapped to
                          that address. This operation may map the memory into an address region different from
                          suggested.

        :return: address in your process space where the memory was mapped, return value of the library call.
        :rtype: address, :class:`pyvisa.constants.StatusCode`
        """
        raise NotImplementedError

    def map_trigger(self, session, trigger_source, trigger_destination, mode):
        """Map the specified trigger source line to the specified destination line.

        Corresponds to viMapTrigger function of the VISA library.

        :param session: Unique logical identifier to a session.
        :param trigger_source: Source line from which to map. (Constants.VI_TRIG*)
        :param trigger_destination: Destination line to which to map. (Constants.VI_TRIG*)
        :param mode:
        :return: return value of the library call.
        :rtype: :class:`pyvisa.constants.StatusCode`
        """
        raise NotImplementedError

    def memory_allocation(self, session, size, extended=False):
        """Allocates memory from a resource's memory region.

        Corresponds to viMemAlloc* functions of the VISA library.

        :param session: Unique logical identifier to a session.
        :param size: Specifies the size of the allocation.
        :param extended: Use 64 bits offset independent of the platform.
        :return: offset of the allocated memory, return value of the library call.
        :rtype: offset, :class:`pyvisa.constants.StatusCode`
        """
        raise NotImplementedError

    def memory_free(self, session, offset, extended=False):
        """Frees memory previously allocated using the memory_allocation() operation.

        Corresponds to viMemFree* function of the VISA library.

        :param session: Unique logical identifier to a session.
        :param offset: Offset of the memory to free.
        :param extended: Use 64 bits offset independent of the platform.
        :return: return value of the library call.
        :rtype: :class:`pyvisa.constants.StatusCode`
        """
        raise NotImplementedError

    def move(self, session, source_space, source_offset, source_width, destination_space,
             destination_offset, destination_width, length):
        """Moves a block of data.

        Corresponds to viMove function of the VISA library.

        :param session: Unique logical identifier to a session.
        :param source_space: Specifies the address space of the source.
        :param source_offset: Offset of the starting address or register from which to read.
        :param source_width: Specifies the data width of the source.
        :param destination_space: Specifies the address space of the destination.
        :param destination_offset: Offset of the starting address or register to which to write.
        :param destination_width: Specifies the data width of the destination.
        :param length: Number of elements to transfer, where the data width of the elements to transfer
                       is identical to the source data width.
        :return: return value of the library call.
        :rtype: :class:`pyvisa.constants.StatusCode`
        """
        raise NotImplementedError

    def move_asynchronously(self, session, source_space, source_offset, source_width,
                            destination_space, destination_offset,
                            destination_width, length):
        """Moves a block of data asynchronously.

        Corresponds to viMoveAsync function of the VISA library.

        :param session: Unique logical identifier to a session.
        :param source_space: Specifies the address space of the source.
        :param source_offset: Offset of the starting address or register from which to read.
        :param source_width: Specifies the data width of the source.
        :param destination_space: Specifies the address space of the destination.
        :param destination_offset: Offset of the starting address or register to which to write.
        :param destination_width: Specifies the data width of the destination.
        :param length: Number of elements to transfer, where the data width of the elements to transfer
                       is identical to the source data width.
        :return: Job identifier of this asynchronous move operation, return value of the library call.
        :rtype: jobid, :class:`pyvisa.constants.StatusCode`
        """
        raise NotImplementedError

    def move_in_8(self, session, space, offset, length, extended=False):
        """Moves an 8-bit block of data from the specified address space and offset to local memory.

        Corresponds to viMoveIn8* functions of the VISA library.

        :param session: Unique logical identifier to a session.
        :param space: Specifies the address space. (Constants.*SPACE*)
        :param offset: Offset (in bytes) of the address or register from which to read.
        :param length: Number of elements to transfer, where the data width of the elements to transfer
                       is identical to the source data width.
        :param extended: Use 64 bits offset independent of the platform.
        :return: Data read from the bus, return value of the library call.
        :rtype: list, :class:`pyvisa.constants.StatusCode`
        """
        raise NotImplementedError

    def move_in_16(self, session, space, offset, length, extended=False):
        """Moves an 16-bit block of data from the specified address space and offset to local memory.

        Corresponds to viMoveIn16* functions of the VISA library.

        :param session: Unique logical identifier to a session.
        :param space: Specifies the address space. (Constants.*SPACE*)
        :param offset: Offset (in bytes) of the address or register from which to read.
        :param length: Number of elements to transfer, where the data width of the elements to transfer
                       is identical to the source data width.
        :param extended: Use 64 bits offset independent of the platform.
        :return: Data read from the bus, return value of the library call.
        :rtype: list, :class:`pyvisa.constants.StatusCode`
        """
        raise NotImplementedError

    def move_in_32(self, session, space, offset, length, extended=False):
        """Moves an 32-bit block of data from the specified address space and offset to local memory.

        Corresponds to viMoveIn32* functions of the VISA library.

        :param session: Unique logical identifier to a session.
        :param space: Specifies the address space. (Constants.*SPACE*)
        :param offset: Offset (in bytes) of the address or register from which to read.
        :param length: Number of elements to transfer, where the data width of the elements to transfer
                       is identical to the source data width.
        :param extended: Use 64 bits offset independent of the platform.
        :return: Data read from the bus, return value of the library call.
        :rtype: list, :class:`pyvisa.constants.StatusCode`
        """
        raise NotImplementedError

    def move_in_64(self, session, space, offset, length, extended=False):
        """Moves an 64-bit block of data from the specified address space and offset to local memory.

        Corresponds to viMoveIn64* functions of the VISA library.

        :param session: Unique logical identifier to a session.
        :param space: Specifies the address space. (Constants.*SPACE*)
        :param offset: Offset (in bytes) of the address or register from which to read.
        :param length: Number of elements to transfer, where the data width of the elements to transfer
                       is identical to the source data width.
        :param extended: Use 64 bits offset independent of the platform.
        :return: Data read from the bus, return value of the library call.
        :rtype: list, :class:`pyvisa.constants.StatusCode`
        """
        raise NotImplementedError

    def move_out_8(self, session, space, offset, length, data, extended=False):
        """Moves an 8-bit block of data from local memory to the specified address space and offset.

        Corresponds to viMoveOut8* functions of the VISA library.

        :param session: Unique logical identifier to a session.
        :param space: Specifies the address space. (Constants.*SPACE*)
        :param offset: Offset (in bytes) of the address or register from which to read.
        :param length: Number of elements to transfer, where the data width of the elements to transfer
                       is identical to the source data width.
        :param data: Data to write to bus.
        :param extended: Use 64 bits offset independent of the platform.
        :return: return value of the library call.
        :rtype: :class:`pyvisa.constants.StatusCode`

        Corresponds to viMoveOut8 function of the VISA library.
        """
        raise NotImplementedError

    def move_out_16(self, session, space, offset, length, data, extended=False):
        """Moves an 16-bit block of data from local memory to the specified address space and offset.

        Corresponds to viMoveOut16* functions of the VISA library.

        :param session: Unique logical identifier to a session.
        :param space: Specifies the address space. (Constants.*SPACE*)
        :param offset: Offset (in bytes) of the address or register from which to read.
        :param length: Number of elements to transfer, where the data width of the elements to transfer
                       is identical to the source data width.
        :param data: Data to write to bus.
        :param extended: Use 64 bits offset independent of the platform.
        :return: return value of the library call.
        :rtype: :class:`pyvisa.constants.StatusCode`
        """
        raise NotImplementedError

    def move_out_32(self, session, space, offset, length, data, extended=False):
        """Moves an 32-bit block of data from local memory to the specified address space and offset.

        Corresponds to viMoveOut32* functions of the VISA library.

        :param session: Unique logical identifier to a session.
        :param space: Specifies the address space. (Constants.*SPACE*)
        :param offset: Offset (in bytes) of the address or register from which to read.
        :param length: Number of elements to transfer, where the data width of the elements to transfer
                       is identical to the source data width.
        :param data: Data to write to bus.
        :param extended: Use 64 bits offset independent of the platform.
        :return: return value of the library call.
        :rtype: :class:`pyvisa.constants.StatusCode`
        """
        raise NotImplementedError

    def move_out_64(self, session, space, offset, length, data, extended=False):
        """Moves an 64-bit block of data from local memory to the specified address space and offset.

        Corresponds to viMoveOut64* functions of the VISA library.

        :param session: Unique logical identifier to a session.
        :param space: Specifies the address space. (Constants.*SPACE*)
        :param offset: Offset (in bytes) of the address or register from which to read.
        :param length: Number of elements to transfer, where the data width of the elements to transfer
                       is identical to the source data width.
        :param data: Data to write to bus.
        :param extended: Use 64 bits offset independent of the platform.
        :return: return value of the library call.
        :rtype: :class:`pyvisa.constants.StatusCode`
        """
        raise NotImplementedError

    def open(self, session, resource_name,
             access_mode=constants.AccessModes.no_lock, open_timeout=constants.VI_TMO_IMMEDIATE):
        """Opens a session to the specified resource.

        Corresponds to viOpen function of the VISA library.

        :param session: Resource Manager session (should always be a session returned from open_default_resource_manager()).
        :param resource_name: Unique symbolic name of a resource.
        :param access_mode: Specifies the mode by which the resource is to be accessed.
        :type access_mode: :class:`pyvisa.constants.AccessModes`
        :param open_timeout: Specifies the maximum time period (in milliseconds) that this operation waits
                             before returning an error.
        :return: Unique logical identifier reference to a session, return value of the library call.
        :rtype: session, :class:`pyvisa.constants.StatusCode`
        """
        raise NotImplementedError

    def open_default_resource_manager(self):
        """This function returns a session to the Default Resource Manager resource.

        Corresponds to viOpenDefaultRM function of the VISA library.

        :return: Unique logical identifier to a Default Resource Manager session, return value of the library call.
        :rtype: session, :class:`pyvisa.constants.StatusCode`
        """
        raise NotImplementedError

    def out_8(self, session, space, offset, data, extended=False):
        """Write in an 8-bit value from the specified memory space and offset.

        Corresponds to viOut8* functions of the VISA library.

        :param session: Unique logical identifier to a session.
        :param space: Specifies the address space. (Constants.*SPACE*)
        :param offset: Offset (in bytes) of the address or register from which to read.
        :param data: Data to write to bus.
        :param extended: Use 64 bits offset independent of the platform.
        :return: return value of the library call.
        :rtype: :class:`pyvisa.constants.StatusCode`
        """
        raise NotImplementedError

    def out_16(self, session, space, offset, data, extended=False):
        """Write in an 16-bit value from the specified memory space and offset.

        Corresponds to viOut16* functions of the VISA library.

        :param session: Unique logical identifier to a session.
        :param space: Specifies the address space. (Constants.*SPACE*)
        :param offset: Offset (in bytes) of the address or register from which to read.
        :param data: Data to write to bus.
        :param extended: Use 64 bits offset independent of the platform.
        :return: return value of the library call.
        :rtype: :class:`pyvisa.constants.StatusCode`
        """
        raise NotImplementedError

    def out_32(self, session, space, offset, data, extended=False):
        """Write in an 32-bit value from the specified memory space and offset.

        Corresponds to viOut32* functions of the VISA library.

        :param session: Unique logical identifier to a session.
        :param space: Specifies the address space. (Constants.*SPACE*)
        :param offset: Offset (in bytes) of the address or register from which to read.
        :param data: Data to write to bus.
        :param extended: Use 64 bits offset independent of the platform.
        :return: return value of the library call.
        :rtype: :class:`pyvisa.constants.StatusCode`
        """
        raise NotImplementedError

    def out_64(self, session, space, offset, data, extended=False):
        """Write in an 64-bit value from the specified memory space and offset.

        Corresponds to viOut64* functions of the VISA library.

        :param session: Unique logical identifier to a session.
        :param space: Specifies the address space. (Constants.*SPACE*)
        :param offset: Offset (in bytes) of the address or register from which to read.
        :param data: Data to write to bus.
        :param extended: Use 64 bits offset independent of the platform.
        :return: return value of the library call.
        :rtype: :class:`pyvisa.constants.StatusCode`
        """
        raise NotImplementedError

    def parse_resource(self, session, resource_name):
        """Parse a resource string to get the interface information.

        Corresponds to viParseRsrc function of the VISA library.

        :param session: Resource Manager session (should always be the Default Resource Manager for VISA
                        returned from open_default_resource_manager()).
        :param resource_name: Unique symbolic name of a resource.
        :return: Resource information with interface type and board number, return value of the library call.
        :rtype: :class:`pyvisa.highlevel.ResourceInfo`, :class:`pyvisa.constants.StatusCode`
        """
        return self.parse_resource_extended(session, resource_name)

    def parse_resource_extended(self, session, resource_name):
        """Parse a resource string to get extended interface information.

        Corresponds to viParseRsrcEx function of the VISA library.

        :param session: Resource Manager session (should always be the Default Resource Manager for VISA
                        returned from open_default_resource_manager()).
        :param resource_name: Unique symbolic name of a resource.
        :return: Resource information, return value of the library call.
        :rtype: :class:`pyvisa.highlevel.ResourceInfo`, :class:`pyvisa.constants.StatusCode`
        """
        try:
            parsed = rname.parse_resource_name(resource_name)

            return (ResourceInfo(parsed.interface_type_const,
                                 parsed.board,
                                 parsed.resource_class,
                                 str(parsed), None),
                    constants.StatusCode.success)
        except ValueError:
            return 0, constants.StatusCode.error_invalid_resource_name

    def peek_8(self, session, address):
        """Read an 8-bit value from the specified address.

        Corresponds to viPeek8 function of the VISA library.

        :param session: Unique logical identifier to a session.
        :param address: Source address to read the value.
        :return: Data read from bus, return value of the library call.
        :rtype: bytes, :class:`pyvisa.constants.StatusCode`
        """
        raise NotImplementedError

    def peek_16(self, session, address):
        """Read an 16-bit value from the specified address.

        Corresponds to viPeek16 function of the VISA library.

        :param session: Unique logical identifier to a session.
        :param address: Source address to read the value.
        :return: Data read from bus, return value of the library call.
        :rtype: bytes, :class:`pyvisa.constants.StatusCode`
        """
        raise NotImplementedError

    def peek_32(self, session, address):
        """Read an 32-bit value from the specified address.

        Corresponds to viPeek32 function of the VISA library.

        :param session: Unique logical identifier to a session.
        :param address: Source address to read the value.
        :return: Data read from bus, return value of the library call.
        :rtype: bytes, :class:`pyvisa.constants.StatusCode`
        """
        raise NotImplementedError

    def peek_64(self, session, address):
        """Read an 64-bit value from the specified address.

        Corresponds to viPeek64 function of the VISA library.

        :param session: Unique logical identifier to a session.
        :param address: Source address to read the value.
        :return: Data read from bus, return value of the library call.
        :rtype: bytes, :class:`pyvisa.constants.StatusCode`
        """
        raise NotImplementedError

    def poke_8(self, session, address, data):
        """Write an 8-bit value from the specified address.

        Corresponds to viPoke8 function of the VISA library.

        :param session: Unique logical identifier to a session.
        :param address: Source address to read the value.
        :param data: value to be written to the bus.
        :return: Data read from bus.
        :return: return value of the library call.
        :rtype: :class:`pyvisa.constants.StatusCode`
        """
        raise NotImplementedError

    def poke_16(self, session, address, data):
        """Write an 16-bit value from the specified address.

        Corresponds to viPoke16 function of the VISA library.

        :param session: Unique logical identifier to a session.
        :param address: Source address to read the value.
        :param data: value to be written to the bus.
        :return: return value of the library call.
        :rtype: :class:`pyvisa.constants.StatusCode`
        """
        raise NotImplementedError

    def poke_32(self, session, address, data):
        """Write an 32-bit value from the specified address.

        Corresponds to viPoke32 function of the VISA library.

        :param session: Unique logical identifier to a session.
        :param address: Source address to read the value.
        :param data: value to be written to the bus.
        :return: return value of the library call.
        :rtype: :class:`pyvisa.constants.StatusCode`
        """
        raise NotImplementedError

    def poke_64(self, session, address, data):
        """Write an 64-bit value from the specified address.

        Corresponds to viPoke64 function of the VISA library.

        :param session: Unique logical identifier to a session.
        :param address: Source address to read the value.
        :param data: value to be written to the bus.
        :return: return value of the library call.
        :rtype: :class:`pyvisa.constants.StatusCode`
        """
        raise NotImplementedError

    def read(self, session, count):
        """Reads data from device or interface synchronously.

        Corresponds to viRead function of the VISA library.

        :param session: Unique logical identifier to a session.
        :param count: Number of bytes to be read.
        :return: data read, return value of the library call.
        :rtype: bytes, :class:`pyvisa.constants.StatusCode`
        """
        raise NotImplementedError

    def read_asynchronously(self, session, count):
        """Reads data from device or interface asynchronously.

        Corresponds to viReadAsync function of the VISA library.

        :param session: Unique logical identifier to a session.
        :param count: Number of bytes to be read.
        :return: result, jobid, return value of the library call.
        :rtype: ctypes buffer, jobid, :class:`pyvisa.constants.StatusCode`
        """
        raise NotImplementedError

    def read_stb(self, session):
        """Reads a status byte of the service request.

        Corresponds to viReadSTB function of the VISA library.

        :param session: Unique logical identifier to a session.
        :return: Service request status byte, return value of the library call.
        :rtype: int, :class:`pyvisa.constants.StatusCode`
        """
        raise NotImplementedError

    def read_to_file(self, session, filename, count):
        """Read data synchronously, and store the transferred data in a file.

        Corresponds to viReadToFile function of the VISA library.

        :param session: Unique logical identifier to a session.
        :param filename: Name of file to which data will be written.
        :param count: Number of bytes to be read.
        :return: Number of bytes actually transferred, return value of the library call.
        :rtype: int, :class:`pyvisa.constants.StatusCode`
        """
        raise NotImplementedError

    def set_attribute(self, session, attribute, attribute_state):
        """Sets the state of an attribute.

        Corresponds to viSetAttribute function of the VISA library.

        :param session: Unique logical identifier to a session.
        :param attribute: Attribute for which the state is to be modified. (Attributes.*)
        :param attribute_state: The state of the attribute to be set for the specified object.
        :return: return value of the library call.
        :rtype: :class:`pyvisa.constants.StatusCode`
        """
        raise NotImplementedError

    def set_buffer(self, session, mask, size):
        """Sets the size for the formatted I/O and/or low-level I/O communication buffer(s).

        Corresponds to viSetBuf function of the VISA library.

        :param session: Unique logical identifier to a session.
        :param mask: Specifies the type of buffer. (Constants.VI_READ_BUF, .VI_WRITE_BUF, .VI_IO_IN_BUF, .VI_IO_OUT_BUF)
        :param size: The size to be set for the specified buffer(s).
        :return: return value of the library call.
        :rtype: :class:`pyvisa.constants.StatusCode`
        """
        raise NotImplementedError

    def status_description(self, session, status):
        """Returns a user-readable description of the status code passed to the operation.

        Corresponds to viStatusDesc function of the VISA library.

        :param session: Unique logical identifier to a session.
        :param status: Status code to interpret.
        :return: - The user-readable string interpretation of the status code passed to the operation,
                 - return value of the library call.
        :rtype: - unicode (Py2) or str (Py3)
                - :class:`pyvisa.constants.StatusCode`
        """
        raise NotImplementedError

    def terminate(self, session, degree, job_id):
        """Requests a VISA session to terminate normal execution of an operation.

        Corresponds to viTerminate function of the VISA library.

        :param session: Unique logical identifier to a session.
        :param degree: Constants.NULL
        :param job_id: Specifies an operation identifier.
        :return: return value of the library call.
        :rtype: :class:`pyvisa.constants.StatusCode`
        """
        raise NotImplementedError

    def uninstall_handler(self, session, event_type, handler, user_handle=None):
        """Uninstalls handlers for events.

        Corresponds to viUninstallHandler function of the VISA library.

        :param session: Unique logical identifier to a session.
        :param event_type: Logical event identifier.
        :param handler: Interpreted as a valid reference to a handler to be uninstalled by a client application.
        :param user_handle: A value specified by an application that can be used for identifying handlers
                            uniquely in a session for an event.
        :return: return value of the library call.
        :rtype: :class:`pyvisa.constants.StatusCode`
        """
        raise NotImplementedError

    def unlock(self, session):
        """Relinquishes a lock for the specified resource.

        Corresponds to viUnlock function of the VISA library.

        :param session: Unique logical identifier to a session.
        :return: return value of the library call.
        :rtype: :class:`pyvisa.constants.StatusCode`
        """
        raise NotImplementedError

    def unmap_address(self, session):
        """Unmaps memory space previously mapped by map_address().

        Corresponds to viUnmapAddress function of the VISA library.

        :param session: Unique logical identifier to a session.
        :return: return value of the library call.
        :rtype: :class:`pyvisa.constants.StatusCode`
        """
        raise NotImplementedError

    def unmap_trigger(self, session, trigger_source, trigger_destination):
        """Undo a previous map from the specified trigger source line to the specified destination line.

        Corresponds to viUnmapTrigger function of the VISA library.

        :param session: Unique logical identifier to a session.
        :param trigger_source: Source line used in previous map. (Constants.VI_TRIG*)
        :param trigger_destination: Destination line used in previous map. (Constants.VI_TRIG*)
        :return: return value of the library call.
        :rtype: :class:`pyvisa.constants.StatusCode`
        """
        raise NotImplementedError

    def usb_control_in(self, session, request_type_bitmap_field, request_id, request_value,
                       index, length=0):
        """Performs a USB control pipe transfer from the device.

        Corresponds to viUsbControlIn function of the VISA library.

        :param session: Unique logical identifier to a session.
        :param request_type_bitmap_field: bmRequestType parameter of the setup stage of a USB control transfer.
        :param request_id: bRequest parameter of the setup stage of a USB control transfer.
        :param request_value: wValue parameter of the setup stage of a USB control transfer.
        :param index: wIndex parameter of the setup stage of a USB control transfer.
                      This is usually the index of the interface or endpoint.
        :param length: wLength parameter of the setup stage of a USB control transfer.
                       This value also specifies the size of the data buffer to receive the data from the
                       optional data stage of the control transfer.
        :return: - The data buffer that receives the data from the optional data stage of the control transfer
                 - return value of the library call.
        :rtype: - bytes
                - :class:`pyvisa.constants.StatusCode`
        """
        raise NotImplementedError

    def usb_control_out(self, session, request_type_bitmap_field, request_id, request_value,
                        index, data=""):
        """Performs a USB control pipe transfer to the device.

        Corresponds to viUsbControlOut function of the VISA library.

        :param session: Unique logical identifier to a session.
        :param request_type_bitmap_field: bmRequestType parameter of the setup stage of a USB control transfer.
        :param request_id: bRequest parameter of the setup stage of a USB control transfer.
        :param request_value: wValue parameter of the setup stage of a USB control transfer.
        :param index: wIndex parameter of the setup stage of a USB control transfer.
                      This is usually the index of the interface or endpoint.
        :param data: The data buffer that sends the data in the optional data stage of the control transfer.
        :return: return value of the library call.
        :rtype: :class:`pyvisa.constants.StatusCode`
        """
        raise NotImplementedError

    def vxi_command_query(self, session, mode, command):
        """Sends the device a miscellaneous command or query and/or retrieves the response to a previous query.

        Corresponds to viVxiCommandQuery function of the VISA library.

        :param session: Unique logical identifier to a session.
        :param mode: Specifies whether to issue a command and/or retrieve a response. (Constants.VI_VXI_CMD*, .VI_VXI_RESP*)
        :param command: The miscellaneous command to send.
        :return: The response retrieved from the device, return value of the library call.
        :rtype: int, :class:`pyvisa.constants.StatusCode`
        """
        raise NotImplementedError

    def wait_on_event(self, session, in_event_type, timeout):
        """Waits for an occurrence of the specified event for a given session.

        Corresponds to viWaitOnEvent function of the VISA library.

        :param session: Unique logical identifier to a session.
        :param in_event_type: Logical identifier of the event(s) to wait for.
        :param timeout: Absolute time period in time units that the resource shall wait for a specified event to
                        occur before returning the time elapsed error. The time unit is in milliseconds.
        :return: - Logical identifier of the event actually received
                 - A handle specifying the unique occurrence of an event
                 - return value of the library call.
        :rtype: - eventtype
                - event
                - :class:`pyvisa.constants.StatusCode`
        """
        raise NotImplementedError

    def write(self, session, data):
        """Writes data to device or interface synchronously.

        Corresponds to viWrite function of the VISA library.

        :param session: Unique logical identifier to a session.
        :param data: data to be written.
        :type data: str
        :return: Number of bytes actually transferred, return value of the library call.
        :rtype: int, :class:`pyvisa.constants.StatusCode`
        """
        raise NotImplementedError

    def write_asynchronously(self, session, data):
        """Writes data to device or interface asynchronously.

        Corresponds to viWriteAsync function of the VISA library.

        :param session: Unique logical identifier to a session.
        :param data: data to be written.
        :return: Job ID of this asynchronous write operation, return value of the library call.
        :rtype: jobid, :class:`pyvisa.constants.StatusCode`
        """
        raise NotImplementedError

    def write_from_file(self, session, filename, count):
        """Take data from a file and write it out synchronously.

        Corresponds to viWriteFromFile function of the VISA library.

        :param session: Unique logical identifier to a session.
        :param filename: Name of file from which data will be read.
        :param count: Number of bytes to be written.
        :return: Number of bytes actually transferred, return value of the library call.
        :rtype: int, :class:`pyvisa.constants.StatusCode`
        """
        raise NotImplementedError


def list_backends():
    """Return installed backends.

    Backends are installed python packages named pyvisa-<something> where <something>
    is the name of the backend.

    :rtype: list
    """
    return ['ni'] + [name for (loader, name, ispkg) in pkgutil.iter_modules()
                     if name.startswith('pyvisa-') and not name.endswith('-script')]


#: Maps backend name to VisaLibraryBase derived class
#: dict[str, :class:`pyvisa.highlevel.VisaLibraryBase`]
_WRAPPERS = {}


def get_wrapper_class(backend_name):
    """Return the WRAPPER_CLASS for a given backend.

    :rtype: pyvisa.highlevel.VisaLibraryBase
    """
    try:
        return _WRAPPERS[backend_name]
    except KeyError:
        if backend_name == 'ni':
            from .ctwrapper import NIVisaLibrary
            _WRAPPERS['ni'] = NIVisaLibrary
            return NIVisaLibrary

    try:
        pkg = __import__('pyvisa-' + backend_name)
        _WRAPPERS[backend_name] = cls = pkg.WRAPPER_CLASS
        return cls
    except ImportError:
        raise ValueError('Wrapper not found: No package named pyvisa-%s' % backend_name)


def open_visa_library(specification):
    """Helper function to create a VISA library wrapper.

    In general, you should not use the function directly. The VISA library
    wrapper will be created automatically when you create a ResourceManager object.
    """

    if not specification:
        try:
            specification = os.environ['PYVISA_LIBRARY']
        except KeyError:
            logger.debug('No visa libaray specified and environment variable PYVISA_LIBRARY is unset. Using NI library')

    try:
        argument, wrapper = specification.split('@')
    except ValueError:
        argument = specification
        wrapper = 'ni'

    cls = get_wrapper_class(wrapper)

    try:
        return cls(argument)
    except Exception as e:
        logger.debug('Could not open VISA wrapper %s: %s\n%s', cls, str(argument), e)
        raise


class ResourceManager(object):
    """VISA Resource Manager

    :param visa_library: VisaLibrary Instance, path of the VISA library or VisaLibrary spec string.
                         (if not given, the default for the platform will be used).
    """

    #: Maps (Interface Type, Resource Class) to Python class encapsulating that resource.
    _resource_classes = dict()

    #: Session handler for the resource manager.
    _session = None

    @classmethod
    def register_resource_class(cls, interface_type, resource_class, python_class):
        if (interface_type, resource_class) in cls._resource_classes:
            logger.warning('%s is already registered in the ResourceManager. '
                           'Overwriting with %s' % ((interface_type, resource_class), python_class))
        cls._resource_classes[(interface_type, resource_class)] = python_class

    def __new__(cls, visa_library=''):
        if not isinstance(visa_library, VisaLibraryBase):
            visa_library = open_visa_library(visa_library)

        if visa_library.resource_manager is not None:
            obj = visa_library.resource_manager
            logger.debug('Reusing ResourceManager with session %s',  obj.session)
            return obj

        obj = super(ResourceManager, cls).__new__(cls)

        obj.session, err = visa_library.open_default_resource_manager()

        obj.visalib = visa_library
        obj.visalib.resource_manager = obj

        logger.debug('Created ResourceManager with session %s',  obj.session)
        return obj

    @property
    def session(self):
        """Resource Manager session handle.

        :raises: :class:`pyvisa.errors.InvalidSession` if session is closed.
        """
        if self._session is None:
            raise errors.InvalidSession()
        return self._session

    @session.setter
    def session(self, value):
        self._session = value

    def __str__(self):
        return 'Resource Manager of %s' % self.visalib

    def __repr__(self):
        return '<ResourceManager(%r)>' % self.visalib

    def __del__(self):
        self.close()

    def ignore_warning(self, *warnings_constants):
        """Ignoring warnings context manager for the current resource.

        :param warnings_constants: constants identifying the warnings to ignore.
        """
        return self.visalib.ignore_warning(self.session, *warnings_constants)

    @property
    def last_status(self):
        """Last status code returned for an operation with this Resource Manager

        :rtype: :class:`pyvisa.constants.StatusCode`
        """
        return self.visalib.get_last_status_in_session(self.session)

    def close(self):
        """Close the resource manager session.
        """
        try:
            logger.debug('Closing ResourceManager (session: %s)', self.session)
            self.visalib.close(self.session)
            self.session = None
            self.visalib.resource_manager = None
        except errors.InvalidSession:
            pass

    def list_resources(self, query='?*::INSTR'):
        """Returns a tuple of all connected devices matching query.

        :param query: regular expression used to match devices.
        """

        return self.visalib.list_resources(self.session, query)

    def list_resources_info(self, query='?*::INSTR'):
        """Returns a dictionary mapping resource names to resource extended
        information of all connected devices matching query.

        :param query: regular expression used to match devices.
        :return: Mapping of resource name to ResourceInfo
        :rtype: dict[str, :class:`pyvisa.highlevel.ResourceInfo`]
        """

        return dict((resource, self.resource_info(resource))
                    for resource in self.list_resources(query))

    def resource_info(self, resource_name, extended=True):
        """Get the (extended) information of a particular resource.

        :param resource_name: Unique symbolic name of a resource.

        :rtype: :class:`pyvisa.highlevel.ResourceInfo`
        """

        if extended:
            ret, err = self.visalib.parse_resource_extended(self.session, resource_name)
        else:
            ret, err = self.visalib.parse_resource(self.session, resource_name)

        return ret

    def open_bare_resource(self, resource_name,
                          access_mode=constants.AccessModes.no_lock,
                          open_timeout=constants.VI_TMO_IMMEDIATE):
        """Open the specified resource without wrapping into a class

        :param resource_name: name or alias of the resource to open.
        :param access_mode: access mode.
        :type access_mode: :class:`pyvisa.constants.AccessModes`
        :param open_timeout: time out to open.

        :return: Unique logical identifier reference to a session.
        """
        return self.visalib.open(self.session, resource_name, access_mode, open_timeout)

    def open_resource(self, resource_name,
                      access_mode=constants.AccessModes.no_lock,
                      open_timeout=constants.VI_TMO_IMMEDIATE,
                      resource_pyclass=None,
                      **kwargs):
        """Return an instrument for the resource name.

        :param resource_name: name or alias of the resource to open.
        :param access_mode: access mode.
        :type access_mode: :class:`pyvisa.constants.AccessModes`
        :param open_timeout: time out to open.
        :param resource_pyclass: resource python class to use to instantiate the Resource.
                                 Defaults to None: select based on the resource name.
        :param kwargs: keyword arguments to be used to change instrument attributes
                       after construction.

        :rtype: :class:`pyvisa.resources.Resource`
        """

        if resource_pyclass is None:
            info = self.resource_info(resource_name, extended=True)

            try:
                resource_pyclass = self._resource_classes[(info.interface_type, info.resource_class)]
            except KeyError:
                resource_pyclass = self._resource_classes[(constants.InterfaceType.unknown, '')]
                logger.warning('There is no class defined for %r. Using Resource', (info.interface_type, info.resource_class))

        res = resource_pyclass(self, resource_name)
        for key in kwargs.keys():
            try:
                getattr(res, key)
                present = True
            except AttributeError:
                present = False
            except errors.InvalidSession:
                present = True

            if not present:
                raise ValueError('%r is not a valid attribute for type %s' % (key, res.__class__.__name__))

        res.open(access_mode, open_timeout)

        for key, value in kwargs.items():
            setattr(res, key, value)

        return res

    #: For backwards compatibility
    get_instrument = open_resource