PyVISA-1.4/0000775000175000017500000000000011754013232012013 5ustar floflo00000000000000PyVISA-1.4/visa.py0000644000175000017500000000003211734647057013340 0ustar floflo00000000000000from pyvisa.visa import * PyVISA-1.4/setup.py0000644000175000017500000001245111754012670013533 0ustar floflo00000000000000#!/usr/bin/env python # -*- coding: utf-8 -*- # # setup.py - Distutils setup script for PyVISA # # Copyright © 2005, 2006, 2007, 2008 # Torsten Bronger , # Gregor Thalhammer . # # This file is part of PyVISA. # # PyVISA is free software; you can redistribute it and/or modify it under # the terms of the MIT licence: # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the "Software"), # to deal in the Software without restriction, including without limitation # the rights to use, copy, modify, merge, publish, distribute, sublicense, # and/or sell copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER # DEALINGS IN THE SOFTWARE. # from distribute_setup import use_setuptools use_setuptools("0.6.24") from setuptools import setup import distutils.dir_util import shutil, os.path, atexit import sys try: distutils.dir_util.remove_tree("build") except: pass # POSIX-specific code related to RPM package configuration; other users are free to # bypass this section altogether. if os.name == 'posix': # The following code may be very specific to my own home configuration, # although I hope that it's useful to other who try to create PyVISA packages, # too. # # The goal is to override an existing local RPM configuration. Distutils only # works together with a widely untouched configuration, so I have to disable # any extisting one represented by the file ~/.rpmmacros. I look for this file # and move it to ~/.rpmmacros.original. After setup.py is terminated, this # renaming is reverted. # # Additionally, if a file ~/.rpmmacros.distutis exists, it is used for # ~/.rpmmacros while setup.py is running. So you can still make use of things # like "%vendor" or "%packager". home_dir = os.environ['HOME'] real_rpmmacros_name = os.path.join(home_dir, '.rpmmacros') distutils_rpmmacros_name = os.path.join(home_dir, '.rpmmacros.distutils') temp_rpmmacros_name = os.path.join(home_dir, '.rpmmacros.original') def restore_rpmmacros(): shutil.move(temp_rpmmacros_name, real_rpmmacros_name) # I check whether temp_rpmmacros_name exists for two reasons: First, I don't # want to overwrite it, and secondly, I don't want this renaming to take place # twice. This would happen otherwise, because setup.py is called more than # once per building session. if os.path.isfile(real_rpmmacros_name) and \ not os.path.isfile(temp_rpmmacros_name): shutil.move(real_rpmmacros_name, temp_rpmmacros_name) if os.path.isfile(distutils_rpmmacros_name): shutil.copy(distutils_rpmmacros_name, real_rpmmacros_name) atexit.register(restore_rpmmacros) # FixMe: Maybe this should be done in Python itself (using distutils.dep_util), # eventually. os.system("make --directory=doc/") os.system("ln -s ../doc src/") extra = {} if sys.version_info >= (3,): extra['use_2to3'] = True # The release name must be changed here and in doc/pyvisa.tex setup(name = 'PyVISA', description = 'Python VISA bindings for GPIB, RS232, and USB instruments', version = '1.4', long_description = \ """A Python package for support of the Virtual Instrument Software Architecture (VISA), in order to control measurement devices and test equipment via GPIB, RS232, or USB. Homepage: http://pyvisa.sourceforge.net""", author = 'Torsten Bronger, Gregor Thalhammer', author_email = 'bronger@physik.rwth-aachen.de', maintainer_email = 'pyvisa-devel@lists.sourceforge.net', url = 'http://pyvisa.sourceforge.net', download_url = 'http://sourceforge.net/projects/pyvisa/', keywords = 'VISA GPIB USB serial RS232 measurement acquisition', license = 'MIT License', classifiers = [ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'Intended Audience :: Science/Research', 'License :: OSI Approved :: MIT License', 'Operating System :: Microsoft :: Windows', 'Operating System :: POSIX :: Linux', 'Programming Language :: Python', 'Topic :: Scientific/Engineering :: Interface Engine/Protocol Translator', 'Topic :: Software Development :: Libraries :: Python Modules', ], package_dir = {'pyvisa': 'src'}, package_data = {'pyvisa': ['doc/pyvisa.pdf', 'doc/vpp43.txt']}, packages = ['pyvisa'], platforms = "Linux, Windows", py_modules = ['visa'], setup_requires = ["sphinx>=1.0", "Mock"], **extra) PyVISA-1.4/ChangeLog0000644000175000017500000006716311734647057013620 0ustar floflo000000000000002008-03-26 Torsten Bronger * doc/pyvisa.tex, doc/vpp43.txt, src/__init__.py, src/visa.py, src/visa_attributes.py, src/visa_exceptions.py, src/visa_messages.py, src/visa_study.py, src/vpp43.py, src/vpp43_attributes.py, src/vpp43_constants.py, src/vpp43_types.py, test/test_itc4.py, test/test_keithley2000.py, COPYING, PyVISA.egg-info/PKG-INFO, doc/LICENSE, doc/homepage.txt, setup.py: Updated to v1.3. Changed licence to MIT. 2008-02-08 Torsten Bronger * src/visa.py: Made determination of ressource class even more careful. 2007-09-19 Torsten Bronger * src/visa.py: Tiny improvement. * doc/pyvisa.tex, setup.py: Promoted to version 1.2 * doc/homepage.txt: Minor correction. 2007-05-03 Torsten Bronger * src/vpp43.py: Changed some __getattr__ to getattr in order to have working exceptions again (e.g. timeouts). * src/visa.py: Softened the test for "INSTR" even further. Introduced the "stb" property for GPIB instruments. 2007-01-13 Torsten Bronger * src/visa.py: Changed "is not an INSTR" error to a warning. 2006-12-09 Torsten Bronger * setup.cfg: Added correct prefix for RPM. 2006-11-24 Torsten Bronger * doc/homepage.txt: Deleted "purchase" thing. 2006-11-21 Torsten Bronger * doc/pyvisa.tex: Small corrections. * PyVISA.egg-info/PKG-INFO, PyVISA.egg-info/SOURCES.txt: Ordinary update. * setup.py: Changed version number to 1.1. * doc/homepage.txt: Updated date. * doc/Makefile: An neue mkhowto-Version angepaßt. 2006-11-02 Torsten Bronger * doc/pyvisa.tex: Improved description of values_format. * doc/pyvisa.tex: Typo fixed. Promoted version to 1.1. 2006-08-13 Torsten Bronger * src/visa.py: Typo fixed. 2006-08-11 Torsten Bronger * src/vpp43.py: Added missing self. * src/vpp43.py: Now almost all VISA function may be missing (in case of very old libraries). * doc/vpp43.txt: Mentioned possible AttributeError with viParseRsrcEx. * src/vpp43.py, src/visa.py: Made secure against missing viParseRsrcEx. * src/visa.py: Removed superfluous calls to parse_resource_extended. 2006-07-28 Torsten Bronger * src/vpp43.py: Typo fixed (thanks to Steve MULLER). 2006-02-18 Torsten Bronger * doc/homepage.txt: Typo fixed. 2006-01-26 Torsten Bronger * doc/homepage.txt: Typo corrected. * doc/homepage.txt: Made introduction more positive. 2006-01-24 Torsten Bronger * PyVISA.egg-info/SOURCES.txt: New file. * PyVISA.egg-info/PKG-INFO: Ordinary update. * doc/pyvisa.tex: Minor improvements. * setup.py: Script can now handle installation with or without setuptools. * setup.py: Switched to new distutils version. 2006-01-23 Torsten Bronger * setup.py: General update. * misc/ctypes/vpp43_types.py, test/test_itc4.py, test/test_keithley2000.py, src/visa_exceptions.py, src/visa_messages.py, src/vpp43.py, src/vpp43_attributes.py, src/vpp43_constants.py, src/vpp43_types.py, src/__init__.py, src/visa.py, doc/vpp43.txt: Copyright updated. * doc/pyvisa.tex: Copyright updated. Version number changed. * doc/vpp43.txt, doc/homepage.txt: Copyright year updated. 2005-09-24 Torsten Bronger * doc/pyvisa.tex: Minor improvements. * PyVISA.egg-info/PKG-INFO: Ordinary update. * doc/homepage.txt: Mentioned that you may have to purchase the VISA library. 2005-09-23 Torsten Bronger * src/visa.py: Fixed two bugs. 2005-09-22 Torsten Bronger * doc/pyvisa.tex: New properties of SerialInstrument explained. * src/visa.py: Added many further properties to SerialInstrument. 2005-09-21 Torsten Bronger * doc/.cvsignore, PyVISA.egg-info/PKG-INFO: Ordinary update. * doc/pyvisa.tex, setup.py: Changed version number to 0.9.7. * doc/vpp43.txt: Renamed timeout parameter in open() to open_timeout. * doc/homepage.txt: Link zu pyvLab hinzugefügt. * src/vpp43.py: Renamed Timeout parameter in open() to open_timeout. * doc/pyvisa.tex: Added section about SerialInstrument. Minor improvements. * src/visa.py: Added class SerialInstrument. Made termination characters even more robust. Minor improvements. * doc/pyvisa.tex: {read,ask_for}_floats --> {read,ask_for}_values. 2005-09-18 Torsten Bronger * src/visa.py: Minor improvements. 2005-09-07 Torsten Bronger * doc/pyvisa.tex: Added index entries. 2005-09-02 Torsten Bronger * doc/pyvisa.tex: Changed document structure a lot (to allow for an index). 2005-08-31 Torsten Bronger * setup.py, doc/pyvisa.tex: Changed version number to 0.9.6. * src/vpp43.py: Renamed TypeError to VisaTypeError. * src/visa_exceptions.py: Added InvalidBinaryFormat. Renamed TypeError to VisaTypeError. * src/visa.py: Added a lot of docstrings. Fixed bug with ValueError exception raising. * src/visa.py: Eliminated string exceptions. A little bit of code clean-up. 2005-08-27 Torsten Bronger * setup.py: Added old distutils inclusion for RPM that cause trouble with my setuptools installation. * src/visa.py: Set default for term_chars to None and implemented it in write() method. * doc/pyvisa.tex: Described new default for term_chars. * src/visa.py: Added instrument(). Fixed bugs in __repr()__. 2005-08-26 Torsten Bronger * doc/pyvisa.tex: Changed section order a little bit. Added section about VISA resource names. Added description of instrument(). 2005-08-13 Torsten Bronger * doc/homepage.txt: Changed title and inverted first enumeration. * doc/Makefile: Added a "keywords" meta tag to index.html. 2005-08-12 Torsten Bronger * src/visa_attributes.py: 0xFFFFFFFF -> 0xFFFFFFFFL * doc/homepage.txt: Minor improvement. * .cvsignore: Removed Python Eggs directory. * doc/pyvisa.tex: Changed version number to 0.9.5. * setup.py: Switched from distutils to setuptools. * PyVISA.egg-info/depends.txt, PyVISA.egg-info/top_level.txt, PyVISA.egg-info/PKG-INFO: New file. 2005-08-11 Torsten Bronger * setup.py: Changed package name to "PyVISA". Changed version number to 0.9.5. * .cvsignore: Added PyVISA.egg-info. * doc/homepage.txt: Made it more friendly. * doc/pyvisa.tex: Included positive user reports. 2005-08-09 Torsten Bronger * test/test_itc4.py, test/test_keithley2000.py, src/__init__.py, src/visa.py, src/visa_exceptions.py, src/visa_messages.py, src/vpp43.py, src/vpp43_types.py, setup.py: Removed tabs from indentation. 2005-08-08 Torsten Bronger * doc/pyvisa.tex: Added note about escaping in Windows-style paths. 2005-08-02 Torsten Bronger * doc/pyvisa.tex: Mentioned too old ctypes in Enthought Python. * doc/pyvisa.tex: Added explanation about how to set the VISA libaray within the Python program. * setup.py: Changed version number to 0.9.4. 2005-07-28 Torsten Bronger * doc/pyvisa.tex: Minor corrections. * doc/pyvisa.tex: Explained INI file for Windows. Explained selecting the DLL's filename under Windows. * src/vpp43.py: Added filename selection for VISA DLL with Windows. 2005-07-22 Torsten Bronger * doc/pyvisa.tex: Various improvements. * doc/pyvisa.tex: Changed version number to 0.9.4. Changed order of properties/keyword arguments. Modified more complex example to SCPI code. 2005-07-21 Torsten Bronger * src/visa.py: Added code to skip over header before binary data. * doc/pyvisa.tex: Added explanation of endianness. * src/visa.py: Cleaned up whitespace. * src/visa.py: Added support for endianess in case of binary transfers. * src/visa.py: Improved binary reading; now it also accepts things like "#267...". 2005-07-20 Torsten Bronger * doc/vpp43.txt: Deleted document version number. * setup.py: Changed version number to 0.9.3. * doc/pyvisa.tex: Changed version number to 0.9.3. Added description of read_raw(). Updated description of termination characters. * src/visa.py: Added read_raw(). * src/visa.py: Changed default termination characters to "" for GPIB instruments. LF and CR are completely stripped from the end of read string, no matter how the termination characters are set. * doc/homepage.txt: Moved PyVISA section to the beginning. 2005-07-19 Torsten Bronger * doc/pyvisa.tex: Added optional "format" arguments. Fixed typo. * doc/pyvisa.tex: Explained missing properties of Instrument. Added explanation of values_format. Added descriptions for ask() and ask_for_values(). * src/visa.py: Added remaining keyword arguments for Instrument constructor. Added CR and LF. Added working support for reading binary data. 2005-07-18 Torsten Bronger * src/visa.py: Added ask() and ask_for_values(). * src/visa.py: Implemented binary reading. Not working yet. * doc/pyvisa.tex: Explained new keyword arguments. * src/visa.py: Split the old term_chars in term_chars, delay, and send_end. 2005-07-17 Torsten Bronger * src/visa.py: Implemented warning system for invalid keyword arguments. Added test for valid float values in read_floats(). Added full term_char string in __get_term_char(). 2005-07-13 Torsten Bronger * doc/pyvisa.tex: Standard timeout increased from 2 to 5 seconds. read_floats() returns *always* a list. Moved trigger() method to Instrument class. * src/visa.py: Standard timeout increased from 2 to 5 seconds. read_floats() returns *always* a list. Moved trigger() method to Instrument class. Fixed bug in regular expression for termination characters. Fixed bug with ignored term_char attribute for GPIB instruments. 2005-07-09 Torsten Bronger * setup.py, doc/pyvisa.tex: Changed to new release number. * src/__init__.py: minor improvement. * src/visa.py: Increased chunk_size's default value and added it to the keyword arguments of the constructor. * doc/pyvisa.tex: Added explanation of chunk_size. 2005-07-03 Torsten Bronger * doc/pyvisa.tex: Spell-checked. * doc/pyvisa.tex: Added RS232 example. * doc/pyvisa.tex, setup.py: Changed version number to 0.9.1. * README: Corrected package name. * misc/ctypes/vpp43_types.py, setup.py, src/__init__.py, src/visa_exceptions.py, src/visa_messages.py, src/visa_study.py, src/vpp43.py, src/vpp43_attributes.py, src/vpp43_constants.py, src/vpp43_types.py, test/test_keithley2000.py: Corrected package name in copyright notice. * doc/homepage.txt: Added "GPIB" to the homepage's title. * test/test_itc4.py: New file. * doc/pyvisa.tex: Adjusted to the fact that PyVISA is now also tested with RS232. Changed date. * src/visa.py: Fixed minor bug with obsolete variable name. * src/visa.py: Added properties resource_name and resource_class to ResourceTemplate. Used both to simplify code. 2005-07-01 Torsten Bronger * setup.py: Made description even shorter. * doc/homepage.txt: Made the string "GPIB" more obvious on the homepage. 2005-06-30 Torsten Bronger * README: Undated to current situation. * setup.py: Changed description. 2005-06-29 Torsten Bronger * setup.py, doc/pyvisa.tex: Changed to version 0.9. * doc/vpp43.txt: Minor fix. * test/test_keithley2000.py: Fixed bug with variable "voltages". 2005-06-28 Torsten Bronger * doc/vpp43.txt: Added explanation of ".pyvisarc". * doc/homepage.txt, doc/pyvisa.tex, doc/vpp43.txt: Minor improvements * doc/pyvisa.tex, doc/vpp43.txt: Fixed little errors. 2005-06-27 Torsten Bronger * doc/pyvisa.tex: Mentioned needed Python version. * src/__init__.py: Fixed bug with missing $HOME on Windows. * setup.py: Added single module visa.py. Ignored exceptions from remove_tree() call. * doc/pyvisa.tex: Added explanation of .pyvisarc. Adjusted to new import strategy. * doc/.cvsignore: Added LaTeX intermediate outputs and logfiles. * src/.cvsignore: New file. * src/__init__.py: Added site-wide configuration file. * src/__init__.py: First usable version. * visa.py: New file. * setup.py: Substituted a native distutils routine for prune_path. * doc/Makefile: Moved creation of pyvisa.tex-related doc to /tmp/. * MANIFEST.in: Added ChnageLog and doc/Makefile. * setup.cfg: Added doc_files. * setup.py: Added symbolic link from src/doc/ to doc/. Added doc inclusion into the binary dumb distri. Untested, because supported since Python 2.4. * setup.py: Renamed package to "pyvisa". Added "make" call for making documentation. 2005-06-26 Torsten Bronger * doc/upload_homepage.sh: File deleted. * doc/Makefile: New file. * src/visa.py, src/visa_study.py: Adjusted header info. * src/pyvisa.py, src/visa.py: Renamed pyvisa.py to this file. * src/visa_study.py: Renamed visa.py to this file. * setup.py: Added code for disabling an existing local RPM configuation. Added "license" keyword parameter. * setup.cfg: New file. * doc/vpp43.txt: Added warning concerning load_library(). * doc/vpp43.txt: Added section about re-loading the VISA library. 2005-06-25 Torsten Bronger * setup.py: Improved description strings. * doc/pyvisa.tex, src/pyvisa.py: Changed default timeout for wait_for_srq() to 25 seconds. * test/test_keithley2000.py: New file. * src/vpp43.py: Removed TODO list. * .cvsignore: Added MANIFEST. * MANIFEST.in: Adjusted to current configuration. * README, readme.txt: File renamed. * misc/ctypes/Makefile, misc/ctypes/ctypes-test.c, misc/ctypes/ctypes-test.py, misc/ctypes/minimal.py, misc/ctypes/vpp43_types.py: New file. * setup.py: Added missing import. * setup.py: Adjusted to new directory structure. * src/__init__.py: New file. * src/pyvisa.py: Added copyright notice. * pyvisa.py, src/pyvisa.py, src/visa.py, src/visa_attributes.py, src/visa_exceptions.py, src/visa_messages.py, src/vpp43.py, src/vpp43_attributes.py, src/vpp43_constants.py, src/vpp43_types.py, visa.py, visa_attributes.py, visa_exceptions.py, visa_messages.py, vpp43.py, vpp43_attributes.py, vpp43_constants.py, vpp43_types.py: Moved file to src/ * ChangeLog: New file. 2005-06-23 Torsten Bronger * setup.py: Fixed too bugs. * setup.py: Brought up-to-date. 2005-06-23 Torsten Bronger * setup.py: Fixed two bugs. * setup.py: Brought up-to-date. 2005-06-22 Torsten Bronger * doc/.cvsignore: Added manual output file. * doc/upload_homepage.sh: Added PDF version. * doc/homepage.txt, doc/pyvisa.tex: First usable version. * doc/upload_homepage.sh, doc/homepage.txt: New file. * doc/vpp43.txt: Deleted the too general stuff (and moved it to homepage.txt). 2005-06-21 Torsten Bronger * doc/pyvisa.tex: Adjusted version number. Added copyright notice. * pyvisa.py: Added read_floats(). Changed test code to a more sophisticated example. * doc/pyvisa.tex: Many additions and improvements. 2005-06-20 Torsten Bronger * doc/pyvisa.tex: Many improvements and additions. * pyvisa.py: Fixed non-working wait_for_srq(). * pyvisa.py: Fixed bug in wait_for_srq(). * pyvisa.py: Added close() method. * pyvisa.py: Remove debug code. * pyvisa.py: The resource_manager is now cleanly deconstructed when the program is terminated. * pyvisa.py: Made calles in __del__ secure. * pyvisa.py: Deleted remains of SRQ handler. * pyvisa.py: Removed SRQ callback handler. * pyvisa.py: Renamed some variables. Added call to mother class in one __del__ routine. 2005-06-19 Torsten Bronger * doc/pyvisa.tex: Minor markup improvements. * doc/pyvisa.tex: Added license. Minor improvements. * doc/LICENSE: New file. * doc/pyvisa.tex: Added a lot of contents. * doc/pyvisa.tex: Added timeout options. 2005-06-18 Torsten Bronger * doc/pyvisa.tex: New file. * pyvisa.py: Deleted MAID test routines. As a constructor keyword argument, "timeout" may be None. * pyvisa.py: Removed superfluous supressions of warnings. Made "\r\n" the default term_chars for GPIB instruments. 2005-06-17 Torsten Bronger * vpp43.py: Removed doubled warnings. * vpp43.py: Removed some warnings that weren't significant enough. * pyvisa.py: Improved example. * pyvisa.py: Added timeout property. Added wait_for_srq(). * vpp43.py: Removed ViSession from return values (replaced by integers) because it's not hashable. * doc/vpp43.txt: Changed all "ViSession" to "integer". 2005-06-16 Torsten Bronger * pyvisa.py: Added use of VI_ATTR_SUPPRESS_END_EN. * vpp43.py: Fixed read_asynchronously(). * doc/vpp43.txt: Explained fixed read_asynchronously(). 2005-06-15 Torsten Bronger * pyvisa.py: Simplified SRQ handling greatly; still untested. * pyvisa.py: Very first and untested implementation of service request callbacks. * pyvisa.py: Cosmetic improvement. * pyvisa.py: Made module runnable. * pyvisa.py: Consequent tabify. Added _resources. 2005-06-14 Torsten Bronger * pyvisa.py: Added docstrings. Removed spurious "\". Improved test for GPIB instrument. * pyvisa.py: Added GpibInstrument with trigger method. Made the class Instrument more general. 2005-06-05 Torsten Bronger * pyvisa.py: Added many docstrings and comments. 2005-06-04 Torsten Bronger * pyvisa.py: Added code to wait for device to be present after having opened it. * vpp43.py: Removed "generate_warnings" 2005-06-02 Torsten Bronger * doc/vpp43.txt: Minor improvements. * vpp43.py: Fixed bug in parse_resource_extended(). * pyvisa.py: Renamed termination_characters to term_chars. Realised term_chars and timeout as keyword arguments. * pyvisa.py: Added get_instruments_list(). Added heuristics for aliases in resource names. * pyvisa.py: Moved some functionality to ResourceTemplate. * vpp43.py: Added __init__ to Singleton. * vpp43.py: Fixed wrong constructor call in singleton class. 2005-06-01 Torsten Bronger * pyvisa.py: Added Gpib class. Added a doc string. * pyvisa.py: Changed to new-style classes and inheritance structure. 2005-05-31 Torsten Bronger * pyvisa.py: Added rudimentary class "Interface". * pyvisa.py: Improved regular expression. 2005-05-30 Torsten Bronger * vpp43.py: Added generate_warnings. * pyvisa.py: New file. * vpp43.py: Minor omission in docstring fixed. 2005-05-29 Torsten Bronger * doc/vpp43.txt: Re-titled document. Added VisaIOWarning. * setup.py: Order now reflects module hierarchy. * visa_exceptions.py: Added VisaIOWarning. * vpp43.py: Deleted double message. * visa_exceptions.py: Tiny code layout improvement. * vpp43.py: Added warnings. 2005-05-29 Torsten Bronger * doc/vpp43.txt: Re-titled document. Added VisaIOWarning. * setup.py: Order now reflects module hierarchy. * visa_exceptions.py: Added VisaIOWarning. * vpp43.py: Deleted double message. * visa_exceptions.py: Tiny code layout improvement. * vpp43.py: Added warnings. 2005-05-28 Torsten Bronger * setup.py: Ordinary update. * vpp43.py: Fixed a bug and a weakness in scanf, sscanf, and queryf. 2005-05-27 Torsten Bronger * doc/vpp43.txt: Added explanations to new exception. * vpp43.py: Implemented new non-string exceptions. * visa_exceptions.py: Added UnknownHandler. Renamed VisaTypeError to TypeError. * doc/vpp43.txt: Explained the user_handle in an event handler correctly. * vpp43.py: Final implementation of install_handler. 2005-05-25 Torsten Bronger * doc/.cvsignore: Added "*.out". * doc/vpp43.txt: Explaind current version of install_handler. 2005-05-25 Torsten Bronger * doc/.cvsignore: Added "*.out". * doc/vpp43.txt: Explaind current version of install_handler. 2005-05-24 Torsten Bronger * doc/.cvsignore, vpp43_attributes.py: New file. * vpp43_types.py: ViHndlr uses the "standard" calling convention on Windows. * vpp43.py: New versions of install_handler and uninstall_handler. * doc/vpp43.txt: Described new handler installer/uninstaller. 2005-05-22 Torsten Bronger * vpp43_constants.py: Restored _to_int(), because I found a way to fix it. * vpp43_constants.py: Removed _to_int(). 2005-05-20 Torsten Bronger * doc/vpp43.txt: Added reference to NI user reference manual. Updated description of get_attribute. * vpp43.py: First usable version of get_attribute(). Deleted spurious calls to ensure_string_stype(). * vpp43.py: Fixed various bugs. First try with the get_attribute function. 2005-05-19 Torsten Bronger * doc/vpp43.txt: Moved "Diagnostics" section. Mentioned ctypes and Enthought-Python. * doc/vpp43.txt: Fixed minor errors. * doc/vpp43.txt: Added description of exceptions. * vpp43.py: Fixed a couple of issues in printf, scanf etc. parameters conversion. A couple of minor bugfixes, after code review due to writing documentation. * vpp43_types.py: Made ViBuf equal to ViString. * visa_exceptions.py: Fixed unbound name. Added VisaTypeError. 2005-05-18 Torsten Bronger * doc/vpp43.txt: Added general documentation. * doc/vpp43.txt: Spell-checked. * doc/vpp43.txt: First usable version. * doc/vpp43.txt: Added further functions. * vpp43.py: Added convert_to_byref. Minor bugfix. 2005-05-17 Torsten Bronger * doc/vpp43.txt: Implemented further routines. Added copyright notice. * vpp43.py: Fixed many bugs. Added some default values for parameters. * doc/vpp43.txt: Further work on the function descriptions. * doc/default.css: New file. * doc/vpp43.txt: Prepared a couple of function descriptions. * doc/vpp43.txt: Raw version of the function descriptions inserted. (Full of errors.) 2005-05-16 Torsten Bronger * doc/vpp43.txt: New file. * vpp43.py: Sorted all functions by alphabet. * vpp43.py: Fixed a couple of bugs. Deleted "ensure_string_argument()". 2005-05-15 Torsten Bronger * visa.py: Reverted to last version. * vpp43.py: Deleded explicit ctypes casts. * visa_exceptions.py: Bug fixed. * vpp43.py: Many serious fixes. * vpp43.py: Added ctypes argtypes (function signatures). 2005-05-14 Torsten Bronger * visa.py: Added deprecated type definitions. * vpp43.py: Improved formatting. * vpp43.py: Deleted all VPP types where not necessary (i.e., string and byte array types). 2005-05-12 Torsten Bronger * vpp43.py: ViSession(vi) --> vi. Added many comments. 2005-05-11 Torsten Bronger * vpp43.py: Minor fixes. Added local TODO list. 2005-05-09 Torsten Bronger * vpp43.py: Added correct list for check_status(). Minor corrections. * vpp43.py: All functions implemented. * vpp43.py: More functions added. 2005-05-08 Torsten Bronger * vpp43.py: Added further functions. Many corrections. Added support for cdecl in viPrintf etc with Windows. 2005-03-29 gth * visa.py: added code for event handling with callback functions, needs more work * visa_attributes.py: added class AttrBitSet, added attributes for event IO_COMPLETION * vpp43_types.py: fixed bug in definition of ViHndlr, return type was missing * setup.py: added visa_messages.py to list of files 2005-03-23 Torsten Bronger * vpp43.py: Added more functions. * vpp43.py: Added further routines. 2005-03-22 gth * visa.py, visa_attributes.py: added setattr (viSetAttribute), with string or numeric arguments 2005-03-20 Torsten Bronger * visa_messages.py: Minor changes. * visa_exceptions.py: Renamed base exception class to "Error". * vpp43.py: Added further routines. 2005-03-19 Torsten Bronger * visa_messages.py, vpp43_constants.py, vpp43_types.py: Improved code documentation. * vpp43.py: Added first wrapper routines. Changed export strategy: Instead of underscores, I now use __all__. * vpp43.py: Added some documentation. * vpp43.py: Moved excaptions to visa_exceptions.py. Added loading of VISA library. * visa_exceptions.py: New file. 2005-03-18 Torsten Bronger * vpp43.py: Added exception class and loading of library. Code is not working yet! 2005-03-18 gth * visa.py, visa_attributes.py: started adding attribute handling (viGetAttribute), incomplete * vpp43_types.py: resolved conflict (ViString) 2005-03-17 Torsten Bronger * vpp43_types.py: Added missing qualifier. * visa_messages.py: Fixed import error. 2005-03-17 gth * MANIFEST.in, readme.txt: New file. * .cvsignore: added build, dist (Python setup directories) * visa_messages.py: definition of __all__ leads to strange import error, commented out * vpp43_types.py: Changed definition of ViString, ViPString * setup.py, visa.py: New file 2005-03-17 Torsten Bronger * vpp43.py: Added some metadata and imports. 2005-03-16 Torsten Bronger * visa_messages.py: Added docstring. * vpp43_constants.py: Moves "completion_and_error_messages" to its own file. * vpp43_types.py: Added some meta data. Made ctypes import in a way that it's not re-exported again. * visa_messages.py: New file. 2005-03-15 Torsten Bronger * vpp43_constants.py: Added some comments. 2005-03-14 Torsten Bronger * vpp43_constants.py: Added attributes, events, and miscellaneous values. 2005-03-13 Torsten Bronger * vpp43_constants.py: New file. * vpp43_types.py: Added encoding declaration. * .cvsignore: New file. * vpp43.py: Moved type definitions to vpp43_types.py. Added copyright notice. Added encoding declaration. * vpp43-types.py, vpp43_types.py: File renamed. * vpp43-types.py: New file. 2005-03-12 Torsten Bronger * vpp43.py: Changed a lot to avoid exec statements. * vpp43.py, COPYING: New file. PyVISA-1.4/PKG-INFO0000664000175000017500000000220611754013232013110 0ustar floflo00000000000000Metadata-Version: 1.0 Name: PyVISA Version: 1.4 Summary: Python VISA bindings for GPIB, RS232, and USB instruments Home-page: http://pyvisa.sourceforge.net Author: Torsten Bronger, Gregor Thalhammer Author-email: pyvisa-devel@lists.sourceforge.net License: MIT License Download-URL: http://sourceforge.net/projects/pyvisa/ Description: A Python package for support of the Virtual Instrument Software Architecture (VISA), in order to control measurement devices and test equipment via GPIB, RS232, or USB. Homepage: http://pyvisa.sourceforge.net Keywords: VISA GPIB USB serial RS232 measurement acquisition Platform: Linux Platform: Windows Classifier: Development Status :: 5 - Production/Stable Classifier: Intended Audience :: Developers Classifier: Intended Audience :: Science/Research Classifier: License :: OSI Approved :: MIT License Classifier: Operating System :: Microsoft :: Windows Classifier: Operating System :: POSIX :: Linux Classifier: Programming Language :: Python Classifier: Topic :: Scientific/Engineering :: Interface Engine/Protocol Translator Classifier: Topic :: Software Development :: Libraries :: Python Modules PyVISA-1.4/COPYING0000644000175000017500000000230611734647057013065 0ustar floflo00000000000000The MIT License Copyright (c) 2005, 2006, 2007, 2008 Torsten Bronger , Gregor Thalhammer . Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. PyVISA-1.4/doc/0000775000175000017500000000000011754013232012560 5ustar floflo00000000000000PyVISA-1.4/doc/LICENSE0000644000175000017500000000230611734647056013603 0ustar floflo00000000000000The MIT License Copyright (c) 2005, 2006, 2007, 2008 Torsten Bronger , Gregor Thalhammer . Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. PyVISA-1.4/doc/pyvisa.tex0000644000175000017500000010667611734647056014652 0ustar floflo00000000000000% -*- mode: LaTeX; coding: utf-8; ispell-local-dictionary: "british"; -*- % % pyvisa.tex - Manual for high-level OO instrument access on top of VISA % % Copyright © 2005, 2006, 2007, 2008 % Torsten Bronger , % Gregor Thalhammer . % % This file is part of PyVISA. % % PyVISA is free software; you can redistribute it and/or modify it under the % terms of the MIT licence: % % Permission is hereby granted, free of charge, to any person obtaining a % copy of this software and associated documentation files (the "Software"), % to deal in the Software without restriction, including without limitation % the rights to use, copy, modify, merge, publish, distribute, sublicense, % and/or sell copies of the Software, and to permit persons to whom the % Software is furnished to do so, subject to the following conditions: % % The above copyright notice and this permission notice shall be included in % all copies or substantial portions of the Software. % % THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR % IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, % FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE % AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER % LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING % FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER % DEALINGS IN THE SOFTWARE. % \documentclass{howto} \title{PyVISA} \release{1.3} \author{Torsten Bronger} \authoraddress{ Aachen, Germany\\ \email{bronger@physik.rwth-aachen.de} } \date{26 March 2008} % \ifpdf{% % \usepackage{hyperref} % \hypersetup{% % pdfauthor={Torsten Bronger},% % pdftitle={PyVISA},% % pdfsubject={The PyVISA manual},% % pdfkeywords={Python,VISA,PyVISA,GPIB,USB,data acquisition,measurements} % } % }% \makeindex \begin{document} \maketitle \ifhtml \chapter*{Front Matter\label{front}} \fi Copyright \copyright{} 2005 Torsten Bronger.\\ Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version~1.2 or any later version published by the Free Software Foundation; with no Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts. A copy of the license is included as a separate file \file{LICENSE} in the PyVISA distribution. \begin{abstract} \noindent PyVISA enables you to control your measurement and test equipment -- digital multimeters, motors, sensors and the like. This document covers the easy-to-use \module{visa} module of the PyVISA package. It implements control of measurement devices in a straightforward and convenient way. The design goal is to combine HT\,Basic's simplicity with Python's modern syntax and powerful set of libraries. PyVISA doesn't implement VISA itself. Instead, PyVISA provides bindings to the VISA library (a DLL or ``shared object'' file). This library is usually shipped with your GPIB interface or software like LabVIEW\@. Alternatively, you can download it from your favourite equipment vendor (National Instruments, Agilent, etc). PyVISA is free software under the terms of the GPL\@. It can be downloaded at \ulink{PyVISA's project page}{http://sourceforge.net/projects/pyvisa}. You can report bugs there, too. Additionally, I'm happy about feedback from people who've given it a try. So far, we have positive reports of various National Instruments GPIB adapters (connected through PCI, USB, and RS\,232), the Agilent~82357\,A, and SRS lock-in amplifiers, for both Windows and Linux. However, I'd be really surprised about negative reports anyway, due to the high abstraction level of PyVISA\@. As far as USB instruments are concerned, you must make sure that they act as ordinary USB devices and not as so-called HDI devices (like keyboard and mouse). \end{abstract} \begin{samepage} \tableofcontents \end{samepage} \section{An example} Let's go \emph{in medias res} and have a look at a simple example: \begin{verbatim} from visa import * my_instrument = instrument("GPIB::14") my_instrument.write("*IDN?") print my_instrument.read() \end{verbatim} This example already shows the two main design goals of PyVISA: preferring simplicity over generality, and doing it the object-oriented way. Every instrument is represented in the source by an object instance. In this case, I have a GPIB instrument with instrument number~14, so I create the instance (i.\,e.\ variable) called \var{my_instrument} accordingly: \begin{verbatim} my_instrument = instrument("GPIB::14") \end{verbatim} \ttindex{instrument()} \code{"GPIB::14"} is the instrument's \emph{resource name}. See section~\ref{sec:VISA-resource-names} for a short explanation of that. Then, I send the message ``*IDN?''\ to the device, which is the standard GPIB message for ``what are you?''\ or -- in some cases -- ``what's on your display at the moment?'': \begin{verbatim} my_instrument.write("*IDN?") \end{verbatim} Finally, I print the instrument's answer on the screen: \begin{verbatim} print my_instrument.read() \end{verbatim} \subsection{Example for serial (RS232) device} \index{RS232@RS\,232} \index{COM2@``COM\,2''} \index{serial device} The only RS\,232 device in my lab is an old Oxford ITC\,4 temperature controller, which is connected through COM\,2 with my computer. The following code prints its self-identification on the screen: \begin{verbatim} from visa import * itc4 = instrument("COM2") itc4.write("V") print itc4.read() \end{verbatim} \ttindex{instrument()} Instead of separate write and read operations, you can do both with one \code{ask()} call. Thus, the above source code is equivalent to \begin{verbatim} from visa import * itc4 = instrument("COM2") print itc4.ask("V") \end{verbatim} It couldn't be simpler. See section~\ref{sec:serial-devices} for further information about serial devices. \subsection{A more complex example} \label{sec:more-complex-example} The following example shows how to use SCPI commands with a Keithley 2000 multimeter in order to measure 10~voltages. After having read them, the program calculates the average voltage and prints it on the screen. \index{SCPI} \index{Keithley 2000} I'll explain the program step-by-step. First, we have to initialise the instrument: \begin{verbatim} from visa import instrument keithley = instrument("GPIB::12") keithley.write("*rst; status:preset; *cls") \end{verbatim} \ttindex{instrument()} Here, we create the instrument variable \var{keithley}, which is used for all further operations on the instrument. Immediately after it, we send the initialisation and reset message to the instrument. The next step is to write all the measurement parameters, in particular the interval time (500\,ms) and the number of readings~(10) to the instrument. I won't explain it in detail. Have a look at an SCPI and/or Keithley~2000 manual. \begin{verbatim} interval_in_ms = 500 number_of_readings = 10 keithley.write("status:measurement:enable 512; *sre 1") keithley.write("sample:count %d" % number_of_readings) keithley.write("trigger:source bus") keithley.write("trigger:delay %f" % (interval_in_ms / 1000.0)) keithley.write("trace:points %d" % number_of_readings) keithley.write("trace:feed sense1; feed:control next") \end{verbatim} Okay, now the instrument is prepared to do the measurement. The next three lines make the instrument waiting for a trigger pulse, trigger it, and wait until it sends a ``service request'': \index{trigger} \index{service request} \begin{verbatim} keithley.write("initiate") keithley.trigger() keithley.wait_for_srq() \end{verbatim} With sending the service request, the instrument tells us that the measurement has been finished and that the results are ready for transmission. We could read them with \samp{keithley.ask("trace:data?")}\ however, then we'd get \begin{verbatim} NDCV-000.0004E+0,NDCV-000.0005E+0,NDCV-000.0004E+0,NDCV-000.0007E+0, NDCV-000.0000E+0,NDCV-000.0007E+0,NDCV-000.0008E+0,NDCV-000.0004E+0, NDCV-000.0002E+0,NDCV-000.0005E+0 \end{verbatim} which we would have to convert to a Python list of numbers. Fortunately, the \code{ask_for_values()} method does this work for us: \begin{verbatim} voltages = keithley.ask_for_values("trace:data?") print "Average voltage: ", sum(voltages) / len(voltages) \end{verbatim} Finally, we should reset the instrument's data buffer and SRQ status register, so that it's ready for a new run. Again, this is explained in detail in the instrument's manual: \begin{verbatim} keithley.ask("status:measurement?") keithley.write("trace:clear; feed:control next") \end{verbatim} That's it. 18 lines of lucid code. (Well, SCPI is awkward, but that's another story.) \subsection{VISA resource names} \label{sec:VISA-resource-names} \index{resource name} \index{VISA resource name} If you use the function \function{instrument()}, you must tell this function the \emph{VISA resource name} of the instrument you want to connect to. Generally, it starts with the bus type, followed by a double colon~\samp{::}, followed by the number within the bus. For example, \begin{verbatim} GPIB::10 \end{verbatim} denotes the GPIB instrument with the number~10. If you have two GPIB boards and the instrument is connected to board number~1, you must write \begin{verbatim} GPIB1::10 \end{verbatim} As for the bus, things like ``\code{GPIB}'', ``\code{USB}'', ``\code{ASRL}'' (for serial/parallel interface) are possible. So for connecting to an instrument at COM2, the resource name is \begin{verbatim} ASRL2 \end{verbatim} (Since only one instrument can be connected with one serial interface, there is no double colon parameter.) However, most VISA systems allow aliases such as \samp{COM2} or \samp{LPT1}. You may also add your own aliases. The resource name is case-insensitive. It doesn't matter whether you say \samp{ASRL2} or \samp{asrl2}. \begin{raggedright} For further information, I have to refer you to a comprehensive VISA description like \url{http://www.ni.com/pdf/manuals/370423a.pdf}. \end{raggedright} \section{\module{visa} --- module contents} \declaremodule{}{visa} \platform{Linux,Windows} \modulesynopsis{Controlling measurement and test equipment using VISA.} \moduleauthor{Torsten Bronger}{bronger@physik.rwth-aachen.de} \moduleauthor{Gregor Thalhammer}{gth@users.sourceforge.net} \sectionauthor{Torsten Bronger}{bronger@physik.rwth-aachen.de} This section is a reference to the functions and classes of the \module{visa} module, which is the main module of the PyVISA package. \subsection{Module functions} \begin{funcdesc}{get_instruments_list}{\optional{use_aliases}} returns a list with all instruments that are known to the local VISA system. If you're lucky, these are all instruments connected with the computer. The boolean \var{use_aliases} is \code{True} by default, which means that the more human-friendly aliases like ``\code{COM1}'' instead of ``\code{ASRL1}'' are returned. With some VISA systems\footnote{such as the ``Measurement and Automation Center'' by National Instruments} you can define your own aliases for each device, e.\,g.\ ``\code{keithley617}'' for ``\code{GPIB0::15::INSTR}''. If \var{use_aliases} is \code{False}, only standard resource names are returned. \index{alias} \index{Measurement and Automation Center} \end{funcdesc} \begin{funcdesc}{instrument}{resource_name\optional{, **keyw}} returns an instrument variable for the instrument given by \var{resource_name}. It saves you from calling one of the instrument classes directly by choosing the right one according to the type of the instrument. So you have \emph{one} function to open \emph{all} of your instruments. \index{factory function} The parameter \var{resource_name} may be any valid VISA instrument resource name, see section~\ref{sec:VISA-resource-names}. In particular, you can use a name returned by \function{get_instruments_list()} above. All further keyword arguments given to this function are passed to the class constructor of the respective instrument class. See section~\ref{sec:general-devices} for a table with all allowed keyword arguments and their meanings. \end{funcdesc} \subsection{Module classes} \subsubsection{General devices} \label{sec:general-devices} \begin{classdesc}{Instrument}{resource_name\optional{, **keyw}} represents an instrument, e.\,g.\ a measurement device. It is independent of a particular bus system, i.\,e.\ it may be a GPIB, serial, USB, or whatever instrument. However, it is not possible to perform bus-specific operations on instruments created by this class. For this, have a look at the specialised classes like \class{GpibInstrument} (section~\ref{sec:gpib-devices}). The parameter \var{resource_name} takes the same syntax as resource specifiers in VISA\@. Thus, it begins with the bus system followed by ``\verb|::|'', continues with the location of the device within the bus system, and ends with an optional ``\verb|::INSTR|''. Possible keyword arguments are: \begin{tableii}{ll}{var}{Keyword}{Description} \lineii{timeout}{timeout in seconds for all device operations, see section~\ref{sec:timeouts}. Default:~5} \lineii{chunk_size}{Length of read data chunks in bytes, see section~\ref{sec:chunk-length}. Default: 20\,kB} \lineii{values_format}{Data format for lists of read values, see section~\ref{sec:reading-binary-data}. Default: \code{ascii}} \lineii{term_char}{termination characters, see section~\ref{sec:termchars}. Default: \code{None}} \lineii{send_end}{whether to assert END after each write operation, see section~\ref{sec:termchars}. Default: \code{True}} \lineii{delay}{delay in seconds after each write operation, see section~\ref{sec:termchars}. Default:~0} \lineii{lock}{whether you want to have exclusive access to the device. Default: \code{VI_NO_LOCK}} \end{tableii} \index{keyword arguments, common} \ttindex{timeout} \ttindex{chunk_size} \ttindex{values_format} \ttindex{term_char} \ttindex{send_end} \ttindex{delay} \ttindex{lock} \vspace{1ex} For further information about the locking mechanism, see~\citetitle[http://pyvisa.sourceforge.net/vpp43.html]{The VISA library implementation}. \end{classdesc} The class \class{Instrument} defines the following methods and attributes: \begin{methoddesc}{write}{message} writes the string \var{message} to the instrument. \end{methoddesc} \begin{methoddesc}{read}{} returns a string sent from the instrument to the computer. \end{methoddesc} \begin{methoddesc}{read_values}{\optional{format}} returns a list of decimal values (floats) sent from the instrument to the computer. See section~\ref{sec:more-complex-example} above. The list may contain only one element or may be empty. The optional \var{format} argument overrides the setting of \var{values_format}. For information about that, see section~\ref{sec:reading-binary-data}. \end{methoddesc} \begin{methoddesc}{ask}{message} sends the string \var{message} to the instrument and returns the answer string from the instrument. \end{methoddesc} \begin{methoddesc}{ask_for_values}{message\optional{, format}} sends the string \var{message} to the instrument and reads the answer as a list of values, just as \code{read_values()} does. The optional \var{format} argument overrides the setting of \var{values_format}. For information about that, see section~\ref{sec:reading-binary-data}. \end{methoddesc} \begin{methoddesc}{clear}{} resets the device. This operation is highly bus-dependent. I refer you to the original VISA documentation, which explains how this is achieved for VXI, GPIB, serial, etc. \end{methoddesc} \begin{methoddesc}{trigger}{} sends a trigger signal to the instrument. \end{methoddesc} \begin{methoddesc}{read_raw}{} returns a string sent from the instrument to the computer. In contrast to \code{read()}, no termination characters are checked or stripped. You get the pristine message. \end{methoddesc} \begin{memberdesc}{timeout} The timeout in seconds for each I/O operation. See section~\ref{sec:timeouts} for further information. \end{memberdesc} \begin{memberdesc}{term_chars} The termination characters for each read and write operation. See section~\ref{sec:termchars} for further information. \end{memberdesc} \begin{memberdesc}{send_end} Whether or not to assert EOI (or something equivalent, depending on the interface type) after each write operation. See section~\ref{sec:termchars} for further information. \end{memberdesc} \begin{memberdesc}{delay} Time in seconds to wait after each write operation. See section~\ref{sec:termchars} for further information. \end{memberdesc} \begin{memberdesc}{values_format} The format for multi-value data sent from the instrument to the computer. See section~\ref{sec:reading-binary-data} for further information. \end{memberdesc} \subsubsection{GPIB devices} \label{sec:gpib-devices} \begin{classdesc}{GpibInstrument}{gpib_identifier\optional{, board_number\optional{, **keyw}}} represents a GPIB instrument. If \var{gpib_identifier} is a string, it is interpreted as a VISA resource name (section~\ref{sec:VISA-resource-names}). If it is a number, it denotes the device number at the GPIB bus. The optional \var{board_number} defaults to zero. If you have more that one GPIB bus system attached to the computer, you can select the bus with this parameter. The keyword arguments are interpreted the same as with the class \class{Instrument}. \end{classdesc} \begin{notice} Since this class is derived from the class \class{Instrument}, please refer to section~\ref{sec:general-devices} for the basic operations. \class{GpibInstrument} can do everything that \class{Instrument} can do, so it simply extends the original class with GPIB-specific operations. \end{notice} The class \class{GpibInstrument} defines the following methods: \begin{methoddesc}{wait_for_srq}{\optional{timeout}} waits for a serial request (SRQ) coming from the instrument. Note that this method is not ended when \emph{another} instrument signals an SRQ, only \emph{this} instrument. The \var{timeout} argument, given in seconds, denotes the maximal waiting time. The default value is 25~(seconds). If you pass \code{None} for the timeout, this method waits forever if no SRQ arrives. \end{methoddesc} \bigskip \begin{classdesc}{Gpib}{\optional{board_number}} represents a GPIB board. Although most setups have at most one GPIB interface card or USB-GPIB device (with board number~0), theoretically you may have more. Be that as it may, for board-level operations, i.\,e.\ operations that affect the whole bus with all connected devices, you must create an instance of this class. The optional GPIB board number \var{board_number} defaults to~0. \end{classdesc} The class \class{Gpib} defines the following method: \begin{methoddesc}{send_ifc}{} pulses the interface clear line (IFC) for at least 0.1~seconds. \end{methoddesc} \begin{notice} You needn't store the board instance in a variable. Instead, you may send an IFC signal just by saying \samp{Gpib().send_ifc()}. \end{notice} \subsubsection{Serial devices} \label{sec:serial-devices} Please note that ``serial instrument'' means only RS232 and parallel port instruments, i.\,e.\ everything attached to COM and LPT\@. In particular, it does not include USB instruments. For USB you have to use \class{Instrument} instead. \begin{classdesc}{SerialInstrument}{resource_name\optional{, **keyw}} represents a serial instrument. \var{resource_name} is the VISA resource name, see section~\ref{sec:VISA-resource-names}. The general keyword arguments are interpreted the same as with the class \class{Instrument}. The only difference is the default value for \var{term_chars}: For serial instruments, \code{CR} (carriage return) is used to terminate readings and writings. \end{classdesc} \begin{notice} Since this class is derived from the class \class{Instrument}, please refer to section~\ref{sec:general-devices} for all operations. \class{SerialInstrument} can do everything that \class{Instrument} can do. \end{notice} The class \class{SerialInstrument} defines the following additional properties. Note that all properties can also be given as keyword arguments when calling the class constructor or \function{instrument()}. \begin{memberdesc}{baud_rate} The communication speed in baud. The default value is 9600. \end{memberdesc} \begin{memberdesc}{data_bits} Number of data bits contained in each frame. Its value must be from 5 to~8. The default is~8. \end{memberdesc} \begin{memberdesc}{stop_bits} Number of stop bits contained in each frame. Possible values are 1, 1.5, and~2. The default is~1. \end{memberdesc} \begin{memberdesc}{parity} The parity used with every frame transmitted and received. Possible values are: \begin{tableii}{ll}{var}{Value}{Description} \lineii{no_parity}{no parity bit is used} \lineii{odd_parity}{the parity bit causes odd parity} \lineii{even_parity}{the parity bit causes even parity} \lineii{mark_parity}{the parity bit exists but it's always~1} \lineii{space_parity}{the parity bit exists but it's always~0} \end{tableii} The default value is \var{no_parity}. \end{memberdesc} \begin{memberdesc}{end_input} This determines the method used to terminate read operations. Possible values are: \begin{tableii}{ll}{var}{Value}{Description} % \lineii{no_end_input}{read will not terminate until all or the requested % data is received. This} % \lineii{}{\quad way is not supported by PyVISA at the moment.} \lineii{last_bit_end_input}{read will terminate as soon as a character arrives with its last data bit set} \lineii{term_chars_end_input}{read will terminate as soon as the last character of \var{term_chars} is received} \end{tableii} The default value is \var{term_chars_end_input}. \end{memberdesc} \section{Common properties of instrument variables} \subsection{Timeouts} \label{sec:timeouts} \ttindex{timeout} Very most VISA I/O operations may be performed with a timeout. If a timeout is set, every operation that takes longer than the timeout is aborted and an exception is raised. Timeouts are given per instrument. For all PyVISA objects, a timeout is set with \begin{verbatim} my_device.timeout = 25 \end{verbatim} Here, \var{my_device} may be a device, an interface or whatever, and its timeout is set to 25~seconds. Floating-point values are allowed. If you set it to zero, all operations must succeed instantaneously. You must not set it to \code{None}. Instead, if you want to remove the timeout, just say \begin{verbatim} del my_device.timeout \end{verbatim} Now every operation of the resource takes as long as it takes, even indefinitely if necessary. The default timeout is 5~seconds, but you can change it when creating the device object: \begin{verbatim} my_instrument = instrument("ASRL1", timeout = 8) \end{verbatim} This creates the object variable \var{my_instrument} and sets its timeout to 8~seconds. In this context, a timeout value of \code{None} is allowed, which removes the timeout for this device. Note that your local VISA library may round up this value heavily. I experienced this effect with my National Instruments VISA implementation, which rounds off to 0, 1, 3 and 10~seconds. \subsection{Chunk length} \label{sec:chunk-length} \ttindex{chunk_length} If you read data from a device, you must store it somewhere. Unfortunately, PyVISA must make space for the data \emph{before} it starts reading, which means that it must know how much data the device will send. However, it doesn't know a~priori. Therefore, PyVISA reads from the device in \emph{chunks}. Each chunk is 20~kilobytes long by default. If there's still data to be read, PyVISA repeats the procedure and eventually concatenates the results and returns it to you. Those 20~kilobytes are large enough so that mostly one read cycle is sufficient. The whole thing happens automatically, as you can see. Normally you needn't worry about it. However, some devices don't like to send data in chunks. So if you have trouble with a certain device and expect data lengths larger than the default chunk length, you should increase its value by saying e.\,g. \begin{verbatim} my_instrument.chunk_size = 102400 \end{verbatim} This example sets it to 100~kilobytes. \subsection{Reading binary data} \label{sec:reading-binary-data} \ttindex{values_format} \index{binary data} Some instruments allow for sending the measured data in binary form. This has the advantage that the data transfer is much smaller and takes less time. PyVISA currently supports three forms of transfers: \begin{description} \item[ascii] This is the default mode. It assumes a normal string with comma- or whitespace-separated values. \item[single] The values are expected as a binary sequence of IEEE floating point values with single precision (i.\,e.\ four bytes each).\footnote{All flavours of binary data streams defined in IEEE\,488.2 are supported, i.\,e.\ those beginning with ``\textit{$\langle$header$\rangle$}~\texttt{\#}\textit{$\langle$digit$\rangle$}'', where \textit{$\langle$header$\rangle$} is optional, and \textit{$\langle$digit$\rangle$} may also be~``0''.} \item[double] The same as \textbf{single}, but with values of double precision (eight bytes each). \end{description} You can set the form of transfer with the property \code{values_format}, either with the generation of the object, \begin{verbatim} my_instrument = instrument("GPIB::12", values_format = single) \end{verbatim} or later by setting the property directly: \begin{verbatim} my_instrument.values_format = single \end{verbatim} Setting this option affects the methods \code{read_values()} and \code{ask_for_values()}. In particular, you must assure separately that the device actually sends in this format. In some cases it may be necessary to set the \emph{byte order}, also known as \emph{endianness}. PyVISA assumes little-endian as default. Some instruments call this ``swapped'' byte order. However, there is also big-endian byte order. In this case you have to append \samp{| big_endian} to your values format: \begin{verbatim} my_instrument = instrument("GPIB::12", values_format = single | big_endian) \end{verbatim} \subsubsection{Example} \label{sec:binary-example} In order to demonstrate how easy reading binary data can be, remember our example from section~\ref{sec:more-complex-example}. You just have to append the lines \begin{verbatim} keithley.write("format:data sreal") keithley.values_format = single \end{verbatim} to the initialisation commands, and all measurement data will be transmitted as binary. You will only notice the increased speed, as PyVISA converts it into the same list of values as before. \subsection{Termination characters} \label{sec:termchars} \index{termination characters} \index{ending sequence} \ttindex{term_chars} Somehow the computer must detect when the device is finished with sending a message. It does so by using different methods, depending on the bus system. In most cases you don't need to worry about termination characters because the defaults are very good. However, if you have trouble, you may influence termination characters with PyVISA\@. Termination characters may be one character or a sequence of characters. Whenever this character or sequence occurs in the input stream, the read operation is terminated and the read message is given to the calling application. The next read operation continues with the input stream immediately after the last termination sequence. In PyVISA, the termination characters are stripped off the message before it is given to you. You may set termination characters for each instrument, e.\,g. \begin{verbatim} my_instrument.term_chars = CR \end{verbatim} Alternatively you can give it when creating your instrument object: \begin{verbatim} my_instrument = instrument("GPIB::10", term_chars = CR) \end{verbatim} The default value depends on the bus system. Generally, the sequence is empty, in particular for GPIB\@. For RS232 it's~\code{CR}\@. Well, the real default is not \code{""} (the empty string) but \code{None}. There is a subtle difference: \code{""} really means the termination characters are not used at all, neither for read nor for write operations. In contrast, \code{None} means that every write operation is implicitly terminated with \code{CR+LF}\@. This works well with most instruments. All CRs and LFs are stripped from the end of a read string, no matter how \var{term_chars} is set. The termination characters sequence is an ordinary string. \code{CR} and \code{LF} are just string constants that allow readable access to \verb|"\r"| and~\verb|"\n"|. Therefore, instead of \code{CR+LF}, you can also write \verb|"\r\n"|, whichever you like more. \subsubsection{``delay'' and ``send\_end''} \ttindex{delay} \ttindex{send\_end} There are two further options related to message termination, namely \code{send_end} and \code{delay}. \code{send_end} is a boolean. If it's \code{True} (the default), the EOI line is asserted after each write operation, signalling the end of the operation. EOI is GPIB-specific but similar action is taken for other interfaces. The argument \code{delay} is the time in seconds to wait after each write operation. So you could write: \begin{verbatim} my_instrument = instrument("GPIB::10", send_end = False, delay = 1.2) \end{verbatim} This will set the delay to 1.2~seconds, and the EOI line is omitted. By the way, omitting EOI is \emph{not} recommended, so if you omit it nevertheless, you should know what you're doing. \index{EOI line} \section{Mixing with direct VISA commands} \index{VISA commands, mixing with} You can mix the high-level object-oriented approach described in this document with middle-level VISA function calls in module \module{vpp43} as described in \citetitle[http://pyvisa.sourceforge.net/vpp43.html]{The VISA library implementation} which is also part of the PyVISA package. By doing so, you have full control of your devices. I recommend to import the VISA functions with \begin{verbatim} from pyvisa import vpp43 \end{verbatim} \refmodindex{vpp43} Then you can use them with \samp{vpp43.\emph{function_name}(...)}. The VISA functions need to know what session you are referring to. PyVISA opens exactly one session for each instrument or interface and stores its session handle in the instance attribute~\member{vi}. For example, these two lines are equivalent: \begin{verbatim} my_instrument.clear() vpp43.clear(my_instrument.vi) \end{verbatim} In case you need the session handle for the default resource manager, it's stored in \member{resource_manager.session}: \begin{verbatim} from visa import * from pyvisa import vpp43 my_instrument_handle = vpp43.open(resource_manager.session, "GPIB::14", VI_EXCLUSIVE_LOCK) \end{verbatim} \section{Installation} \index{installation} \subsection{Prerequisites} \index{prerequisites} PyVISA needs Python version~2.3 or newer. The PyVISA package doesn't include a low-level VISA implementation itself. You have to get it from one of the VISA vendors, e.\,g.\ from the \ulink{National Instruments VISA pages}{http://ni.com/visa/}. NI sells its VISA kit for approx.~\$\,400. However, it's bundled with most of NI's hardware and software. Besides, the download itself is free, and one user reported that he had successfully installed VISA support without buying anything. I can't really tell about other vendors but well-equipped labs probably have VISA already (even if they don't know). Please install VISA properly before you proceed. Additionally, your Python installation needs a fresh version of \ulink{ctypes}{http://starship.python.net/crew/theller/ctypes/}. By the way, if you use Windows, I recommend to install \ulink{Enthought Python}{http://www.enthought.com/python/}. It is a special Python version with all-included philosophy for scientific and engineering applications.\footnote{Of course, it's highly advisable not to have installed another version of Python on your system before you install Enthought Python.} \refmodindex{ctypes} \subsection{Setting up the module} \index{configuration} \index{setting up PyVISA} \subsubsection{Windows} PyVISA expects a file called \file{visa32.dll} in the \envvar{PATH}\@. For example, on my system you find this file in \file{C:\e WINNT\e system32\e}. Either copy it there or expand your \envvar{PATH}. Alternatively, you can create an INI file. You must do this anyway if the file is not called \file{visa32.dll} on your system. \index{visa32.dll} \index{PATH} \subsubsection{Linux} For Linux, the VISA library is by default at \file{/usr/local/vxipnp/linux/bin/libvisa.so.7}. If this is not the case on your installation, you have to create an INI file. \subsubsection{INI file for customisation} \index{INI file} If the VISA library file is not at the default place, or doesn't have the default name for your operating system (see above), you can tell PyVISA by creating a file called \file{.pyvisarc} (mind the leading dot). \index{pyvisarc@.pyvisarc} Another motivation for setting up an INI file is that you have more than one VISA library, e.\,g.\ because two GPIB interfaces of two different vendors are connected with the computer. However, in this case I'd try to use both interfaces with one library because sometimes you're lucky and it works. Note that PyVISA is currently not able to switch between DLLs while the program is running. For Windows, place it in your ``Documents and Settings'' folder,\footnote{its name depends on the language of your Windows version} e.\,g.\ \begin{verbatim} C:\Documents and Settings\smith\.pyvisarc \end{verbatim} if ``smith'' is the name of your login account. For Linux, put it in your home directory. This file has the format of an INI~file. For example, if the library is at \file{/usr/lib/libvisa.so.7}, the file \file{.pyvisarc} must contain the following: \begin{verbatim} [Paths] VISA library: /usr/lib/libvisa.so.7 \end{verbatim} Please note that ``\code{[Paths]}'' is treated case-sensitively. You can define a site-wide configuration file at \file{/usr/share/pyvisa/.pyvisarc}. (It may also be \file{/usr/local/\ldots}\ depending on the location of your Python.) Under Windows, this file is usually placed at \file{c:\e Python24\e share\e pyvisa\e .pyvisarc}. \subsubsection{Setting the VISA library in the program} You can also set the path to your VISA library at the beginning of your program. Just start the program with \begin{verbatim} from pyvisa.vpp43 import visa_library visa_library.load_library("/usr/lib/libvisa.so.7") from visa import * ... \end{verbatim} Keep in mind that the backslashes of Windows paths must be properly escaped, or the path must be preceeded by~\samp{r}: \begin{verbatim} from pyvisa.vpp43 import visa_library visa_library.load_library(r"c:\WINNT\system32\agvisa32.dll") from visa import * ... \end{verbatim} \section{About PyVISA} \index{authors} PyVISA was originally programmed by Torsten Bronger, Aachen/\hskip0pt Germany and Gregor Thalhammer, Innsbruck/\hskip0pt Austria. It bases on earlier experiences by Thalhammer. Its homepage is \url{http://sourceforge.net/projects/pyvisa/}. Please report bugs there. \textbf{I'm also very keen to know whether PyVISA works for you or not. Thank you!} \input{\jobname.ind} \end{document} % LocalWords: ascii british PyVISA pyvisa keyw GpibInstrument var NOEND EOI % LocalWords: rNOEND noend ASRL keithley gpib Center vpp ctypes dll WINNT IDN % LocalWords: ifc SCPI srq utf tex pyvisarc INI ITC DLLs asrl CRs LFs NI's % LocalWords: SerialInstrument PyVISA-1.4/doc/default.css0000644000175000017500000001145311734647056014737 0ustar floflo00000000000000/* :Author: David Goodger :Contact: goodger@users.sourceforge.net :Date: $Date: 2005-05-17 19:45:31 +0200 (Di, 17. Mai 2005) $ :Version: $Revision: 62 $ :Copyright: This stylesheet has been placed in the public domain. Default cascading style sheet for the HTML output of Docutils. */ /* "! important" is used here to override other ``margin-top`` and ``margin-bottom`` styles that are later in the stylesheet or more specific. See http://www.w3.org/TR/CSS1#the-cascade */ .first { margin-top: 0 ! important } .last { margin-bottom: 0 ! important } .hidden { display: none } a.toc-backref { text-decoration: none ; color: black } blockquote.epigraph { margin: 2em 5em ; } dl.docutils dd { margin-bottom: 0.5em } /* Uncomment (and remove this text!) to get bold-faced definition list terms dl.docutils dt { font-weight: bold } */ div.abstract { margin: 2em 5em } div.abstract p.topic-title { font-weight: bold ; text-align: center } div.admonition, div.attention, div.caution, div.danger, div.error, div.hint, div.important, div.note, div.tip, div.warning { margin: 2em ; border: medium outset ; padding: 1em } div.admonition p.admonition-title, div.hint p.admonition-title, div.important p.admonition-title, div.note p.admonition-title, div.tip p.admonition-title { font-weight: bold ; font-family: sans-serif } div.attention p.admonition-title, div.caution p.admonition-title, div.danger p.admonition-title, div.error p.admonition-title, div.warning p.admonition-title { color: red ; font-weight: bold ; font-family: sans-serif } /* Uncomment (and remove this text!) to get reduced vertical space in compound paragraphs. div.compound .compound-first, div.compound .compound-middle { margin-bottom: 0.5em } div.compound .compound-last, div.compound .compound-middle { margin-top: 0.5em } */ div.dedication { margin: 2em 5em ; text-align: center ; font-style: italic } div.dedication p.topic-title { font-weight: bold ; font-style: normal } div.figure { margin-left: 2em } div.footer, div.header { font-size: smaller } div.line-block { display: block ; margin-top: 1em ; margin-bottom: 1em } div.line-block div.line-block { margin-top: 0 ; margin-bottom: 0 ; margin-left: 1.5em } div.sidebar { margin-left: 1em ; border: medium outset ; padding: 1em ; background-color: #ffffee ; width: 40% ; float: right ; clear: right } div.sidebar p.rubric { font-family: sans-serif ; font-size: medium } div.system-messages { margin: 5em } div.system-messages h1 { color: red } div.system-message { border: medium outset ; padding: 1em } div.system-message p.system-message-title { color: red ; font-weight: bold } div.topic { margin: 2em } h1.title { text-align: center } h2.subtitle { text-align: center } hr.docutils { width: 75% } ol.simple, ul.simple { margin-bottom: 1em } ol.arabic { list-style: decimal } ol.loweralpha { list-style: lower-alpha } ol.upperalpha { list-style: upper-alpha } ol.lowerroman { list-style: lower-roman } ol.upperroman { list-style: upper-roman } p.attribution { text-align: right ; margin-left: 50% } p.caption { font-style: italic } p.credits { font-style: italic ; font-size: smaller } p.label { white-space: nowrap } p.rubric { font-weight: bold ; font-size: larger ; color: maroon ; text-align: center } p.sidebar-title { font-family: sans-serif ; font-weight: bold ; font-size: larger } p.sidebar-subtitle { font-family: sans-serif ; font-weight: bold } p.topic-title { font-weight: bold } pre.address { margin-bottom: 0 ; margin-top: 0 ; font-family: serif ; font-size: 100% } pre.line-block { font-family: serif ; font-size: 100% } pre.literal-block, pre.doctest-block { margin-left: 2em ; margin-right: 2em ; background-color: #eeeeee } span.classifier { font-family: sans-serif ; font-style: oblique } span.classifier-delimiter { font-family: sans-serif ; font-weight: bold } span.interpreted { font-family: sans-serif } span.option { white-space: nowrap } span.pre { white-space: pre } span.problematic { color: red } table.citation { border-left: solid thin gray } table.docinfo { margin: 2em 4em } table.docutils { margin-top: 0.5em ; margin-bottom: 0.5em } table.footnote { border-left: solid thin black } table.docutils td, table.docutils th, table.docinfo td, table.docinfo th { padding-left: 0.5em ; padding-right: 0.5em ; vertical-align: top } table.docutils th.field-name, table.docinfo th.docinfo-name { font-weight: bold ; text-align: left ; white-space: nowrap ; padding-left: 0 } h1 tt.docutils, h2 tt.docutils, h3 tt.docutils, h4 tt.docutils, h5 tt.docutils, h6 tt.docutils { font-size: 100% } tt.docutils { background-color: #eeeeee } ul.auto-toc { list-style-type: none } PyVISA-1.4/doc/pyvisa.txt0000644000175000017500000010727211753674730014662 0ustar floflo00000000000000.. -*- mode: rst; coding: utf-8; ispell-local-dictionary: "british"; -*- pyvisa.txt - Manual for high-level OO instrument access on top of VISA Converted from the original pyvisa.tex to restructured text. Copyright © 2012 Florian Bauer Copyright © 2011 Kevin Saff Copyright © 2005, 2006, 2007, 2008-2012 Torsten Bronger , Gregor Thalhammer . This file is part of PyVISA. PyVISA is free software; you can redistribute it and/or modify it under the terms of the MIT licence: Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ======== PyVISA ======== .. |release| replace:: 1.4 :Date: |today| :Author: Torsten Bronger :Maintainer: Florian Bauer .. _front: ================ Front Matter ================ Copyright © 2005 Torsten Bronger. Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.2 or any later version published by the Free Software Foundation; with no Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts. A copy of the license is included as a separate file :file:`LICENSE` in the PyVISA distribution. .. topic:: Abstract PyVISA enables you to control your measurement and test equipment -- digital multimeters, motors, sensors and the like. This document covers the easy-to- use :mod:`visa` module of the PyVISA package. It implements control of measurement devices in a straightforward and convenient way. The design goal is to combine HTBasic's simplicity with Python's modern syntax and powerful set of libraries. PyVISA doesn't implement VISA itself. Instead, PyVISA provides bindings to the VISA library (a DLL or "shared object" file). This library is usually shipped with your GPIB interface or software like LabVIEW . Alternatively, you can download it from your favourite equipment vendor (National Instruments, Agilent, etc). PyVISA is free software under the terms of the GPL . It can be downloaded at `PyVISA's project page `_. You can report bugs there, too. Additionally, I'm happy about feedback from people who've given it a try. So far, we have positive reports of various National Instruments GPIB adapters (connected through PCI, USB, and RS232), the Agilent 82357A, and SRS lock-in amplifiers, for both Windows and Linux. However, I'd be really surprised about negative reports anyway, due to the high abstraction level of PyVISA . As far as USB instruments are concerned, you must make sure that they act as ordinary USB devices and not as so-called HDI devices (like keyboard and mouse). .. contents:: An example ========== Let's go *in medias res* and have a look at a simple example:: from visa import * my_instrument = instrument("GPIB::14") my_instrument.write("*IDN?") print my_instrument.read() This example already shows the two main design goals of PyVISA: preferring simplicity over generality, and doing it the object-oriented way. Every instrument is represented in the source by an object instance. In this case, I have a GPIB instrument with instrument number 14, so I create the instance (i.e. variable) called *my_instrument* accordingly:: my_instrument = instrument("GPIB::14") .. index:: single: instrument() `"GPIB::14"` is the instrument's *resource name*. See section :ref:`sec:visa-resource-names` for a short explanation of that. Then, I send the message "*IDN?" to the device, which is the standard GPIB message for "what are you?" or -- in some cases -- "what's on your display at the moment?":: my_instrument.write("*IDN?") Finally, I print the instrument's answer on the screen: :: print my_instrument.read() Example for serial (RS232) device --------------------------------- .. index:: single: RS232 single: COM2 single: serial device The only RS232 device in my lab is an old Oxford ITC4 temperature controller, which is connected through COM2 with my computer. The following code prints its self-identification on the screen:: from visa import * itc4 = instrument("COM2") itc4.write("V") print itc4.read() .. index:: single: instrument() Instead of separate write and read operations, you can do both with one `ask()` call. Thus, the above source code is equivalent to:: from visa import * itc4 = instrument("COM2") print itc4.ask("V") It couldn't be simpler. See section :ref:`sec:serial-devices` for further information about serial devices. .. _sec:more-complex-example: A more complex example ---------------------- .. index:: single: SCPI single: Keithley 2000 The following example shows how to use SCPI commands with a Keithley 2000 multimeter in order to measure 10 voltages. After having read them, the program calculates the average voltage and prints it on the screen. I'll explain the program step-by-step. First, we have to initialise the instrument:: from visa import instrument keithley = instrument("GPIB::12") keithley.write("*rst; status:preset; *cls") .. index:: single: instrument() Here, we create the instrument variable *keithley*, which is used for all further operations on the instrument. Immediately after it, we send the initialisation and reset message to the instrument. The next step is to write all the measurement parameters, in particular the interval time (500ms) and the number of readings (10) to the instrument. I won't explain it in detail. Have a look at an SCPI and/or Keithley 2000 manual. .. code-block:: python interval_in_ms = 500 number_of_readings = 10 keithley.write("status:measurement:enable 512; *sre 1") keithley.write("sample:count %d" % number_of_readings) keithley.write("trigger:source bus") keithley.write("trigger:delay %f" % (interval_in_ms / 1000.0)) keithley.write("trace:points %d" % number_of_readings) keithley.write("trace:feed sense1; feed:control next") .. index:: single: trigger single: service request Okay, now the instrument is prepared to do the measurement. The next three lines make the instrument waiting for a trigger pulse, trigger it, and wait until it sends a "service request":: keithley.write("initiate") keithley.trigger() keithley.wait_for_srq() With sending the service request, the instrument tells us that the measurement has been finished and that the results are ready for transmission. We could read them with `keithley.ask("trace:data?")` however, then we'd get .. code-block:: none NDCV-000.0004E+0,NDCV-000.0005E+0,NDCV-000.0004E+0,NDCV-000.0007E+0, NDCV-000.0000E+0,NDCV-000.0007E+0,NDCV-000.0008E+0,NDCV-000.0004E+0, NDCV-000.0002E+0,NDCV-000.0005E+0 which we would have to convert to a Python list of numbers. Fortunately, the `ask_for_values()` method does this work for us:: voltages = keithley.ask_for_values("trace:data?") print "Average voltage: ", sum(voltages) / len(voltages) Finally, we should reset the instrument's data buffer and SRQ status register, so that it's ready for a new run. Again, this is explained in detail in the instrument's manual:: keithley.ask("status:measurement?") keithley.write("trace:clear; feed:control next") That's it. 18 lines of lucid code. (Well, SCPI is awkward, but that's another story.) .. _sec:visa-resource-names: VISA resource names ------------------- .. index:: single: resource name single: VISA resource name If you use the function :func:`instrument`, you must tell this function the *VISA resource name* of the instrument you want to connect to. Generally, it starts with the bus type, followed by a double colon `"::"`, followed by the number within the bus. For example, .. code-block:: none GPIB::10 denotes the GPIB instrument with the number 10. If you have two GPIB boards and the instrument is connected to board number 1, you must write .. code-block:: none GPIB1::10 As for the bus, things like `"GPIB"`, `"USB"`, `"ASRL"` (for serial/parallel interface) are possible. So for connecting to an instrument at COM2, the resource name is .. code-block:: none ASRL2 (Since only one instrument can be connected with one serial interface, there is no double colon parameter.) However, most VISA systems allow aliases such as `"COM2"` or `"LPT1"`. You may also add your own aliases. The resource name is case-insensitive. It doesn't matter whether you say `"ASRL2"` or `"asrl2"`. For further information, I have to refer you to a comprehensive VISA description like ``_. :mod:`visa` --- module contents =============================== .. module:: visa :platform: Linux,Windows :synopsis: Controlling measurement and test equipment using VISA. .. moduleauthor:: Torsten Bronger .. moduleauthor:: Gregor Thalhammer .. sectionauthor:: Torsten Bronger This section is a reference to the functions and classes of the :mod:`visa` module, which is the main module of the PyVISA package. Module functions ---------------- .. function:: get_instruments_list([use_aliases]) .. index:: single: alias single: Measurement and Automation Center returns a list with all instruments that are known to the local VISA system. If you're lucky, these are all instruments connected with the computer. The boolean *use_aliases* is `True` by default, which means that the more human- friendly aliases like `"COM1"` instead of `"ASRL1"` are returned. With some VISA systems [#]_ you can define your own aliases for each device, e.g. `"keithley617"` for `"GPIB0::15::INSTR"`. If *use_aliases* is `False`, only standard resource names are returned. .. function:: instrument(resource_name[, **keyw]) .. index:: single: factory function returns an instrument variable for the instrument given by *resource_name*. It saves you from calling one of the instrument classes directly by choosing the right one according to the type of the instrument. So you have *one* function to open *all* of your instruments. The parameter *resource_name* may be any valid VISA instrument resource name, see section :ref:`sec:visa-resource-names`. In particular, you can use a name returned by :func:`get_instruments_list` above. All further keyword arguments given to this function are passed to the class constructor of the respective instrument class. See section :ref:`sec:general-devices` for a table with all allowed keyword arguments and their meanings. Module classes -------------- .. _sec:general-devices: General devices ^^^^^^^^^^^^^^^ .. class:: Instrument(resource_name[, **keyw]) represents an instrument, e.g. a measurement device. It is independent of a particular bus system, i.e. it may be a GPIB, serial, USB, or whatever instrument. However, it is not possible to perform bus-specific operations on instruments created by this class. For this, have a look at the specialised classes like :class:`GpibInstrument` (section :ref:`sec:gpib-devices`). The parameter *resource_name* takes the same syntax as resource specifiers in VISA. Thus, it begins with the bus system followed by `"::"`, continues with the location of the device within the bus system, and ends with an optional `"::INSTR"`. Possible keyword arguments are: +-----------------+-------------------------------------------+ | Keyword | Description | +=================+===========================================+ | *timeout* | timeout in seconds for all device | | | operations, see section | | | :ref:`sec:timeouts`. Default: 5 | +-----------------+-------------------------------------------+ | *chunk_size* | Length of read data chunks in bytes, see | | | section :ref:`sec:chunk-length`. Default: | | | 20kB | +-----------------+-------------------------------------------+ | *values_format* | Data format for lists of read values, see | | | section :ref:`sec:reading-binary-data`. | | | Default: `ascii` | +-----------------+-------------------------------------------+ | *term_char* | termination characters, see section | | | :ref:`sec:termchars`. Default: `None` | +-----------------+-------------------------------------------+ | *send_end* | whether to assert END after each write | | | operation, see section | | | :ref:`sec:termchars`. Default: `True` | +-----------------+-------------------------------------------+ | *delay* | delay in seconds after each write | | | operation, see section | | | :ref:`sec:termchars`. Default: 0 | +-----------------+-------------------------------------------+ | *lock* | whether you want to have exclusive access | | | to the device. Default: `VI_NO_LOCK` | +-----------------+-------------------------------------------+ .. index:: single: keyword arguments, common single: timeout single: chunk_size single: values_format single: term_char single: send_end single: delay single: lock For further information about the locking mechanism, see `The VISA library implementation `_. The class :class:`Instrument` defines the following methods and attributes: .. method:: Instrument.write(message) writes the string *message* to the instrument. .. method:: Instrument.read() returns a string sent from the instrument to the computer. .. method:: Instrument.read_values([format]) returns a list of decimal values (floats) sent from the instrument to the computer. See section :ref:`sec:more-complex-example` above. The list may contain only one element or may be empty. The optional *format* argument overrides the setting of *values_format*. For information about that, see section :ref:`sec:reading-binary-data`. .. method:: Instrument.ask(message) sends the string *message* to the instrument and returns the answer string from the instrument. .. method:: Instrument.ask_for_values(message[, format]) sends the string *message* to the instrument and reads the answer as a list of values, just as `read_values()` does. The optional *format* argument overrides the setting of *values_format*. For information about that, see section :ref:`sec:reading-binary-data`. .. method:: Instrument.clear() resets the device. This operation is highly bus-dependent. I refer you to the original VISA documentation, which explains how this is achieved for VXI, GPIB, serial, etc. .. method:: Instrument.trigger() sends a trigger signal to the instrument. .. method:: Instrument.read_raw() returns a string sent from the instrument to the computer. In contrast to `read()`, no termination characters are checked or stripped. You get the pristine message. .. attribute:: Instrument.timeout The timeout in seconds for each I/O operation. See section :ref:`sec:timeouts` for further information. .. attribute:: Instrument.term_chars The termination characters for each read and write operation. See section :ref:`sec:termchars` for further information. .. attribute:: Instrument.send_end Whether or not to assert EOI (or something equivalent, depending on the interface type) after each write operation. See section :ref:`sec:termchars` for further information. .. attribute:: Instrument.delay Time in seconds to wait after each write operation. See section :ref:`sec:termchars` for further information. .. attribute:: Instrument.values_format The format for multi-value data sent from the instrument to the computer. See section :ref:`sec:reading-binary-data` for further information. .. _sec:gpib-devices: GPIB devices ^^^^^^^^^^^^ .. class:: GpibInstrument(gpib_identifier[, board_number[, **keyw]]) represents a GPIB instrument. If *gpib_identifier* is a string, it is interpreted as a VISA resource name (section :ref:`sec:visa-resource-names`). If it is a number, it denotes the device number at the GPIB bus. The optional *board_number* defaults to zero. If you have more that one GPIB bus system attached to the computer, you can select the bus with this parameter. The keyword arguments are interpreted the same as with the class :class:`Instrument`. .. note:: Since this class is derived from the class :class:`Instrument`, please refer to section :ref:`sec:general-devices` for the basic operations. :class:`GpibInstrument` can do everything that :class:`Instrument` can do, so it simply extends the original class with GPIB-specific operations. The class :class:`GpibInstrument` defines the following methods: .. method:: GpibInstrument.wait_for_srq([timeout]) waits for a serial request (SRQ) coming from the instrument. Note that this method is not ended when *another* instrument signals an SRQ, only *this* instrument. The *timeout* argument, given in seconds, denotes the maximal waiting time. The default value is 25 (seconds). If you pass `None` for the timeout, this method waits forever if no SRQ arrives. .. class:: Gpib([board_number]) represents a GPIB board. Although most setups have at most one GPIB interface card or USB-GPIB device (with board number 0), theoretically you may have more. Be that as it may, for board-level operations, i.e. operations that affect the whole bus with all connected devices, you must create an instance of this class. The optional GPIB board number *board_number* defaults to 0. The class :class:`Gpib` defines the following method: .. method:: Gpib.send_ifc() pulses the interface clear line (IFC) for at least 0.1 seconds. .. note:: You needn't store the board instance in a variable. Instead, you may send an IFC signal just by saying `Gpib().send_ifc()`. .. _sec:serial-devices: Serial devices ^^^^^^^^^^^^^^ Please note that "serial instrument" means only RS232 and parallel port instruments, i.e. everything attached to COM and LPT. In particular, it does not include USB instruments. For USB you have to use :class:`Instrument` instead. .. class:: SerialInstrument(resource_name[, **keyw]) represents a serial instrument. `resource_name` is the VISA resource name, see section :ref:`sec:visa-resource-names`. The general keyword arguments are interpreted the same as with the class :class:`Instrument`. The only difference is the default value for *term_chars*: For serial instruments, `CR` (carriage return) is used to terminate readings and writings. .. note:: Since this class is derived from the class :class:`Instrument`, please refer to section :ref:`sec:general-devices` for all operations. :class:`SerialInstrument` can do everything that :class:`Instrument` can do. The class :class:`SerialInstrument` defines the following additional properties. Note that all properties can also be given as keyword arguments when calling the class constructor or :func:`instrument`. .. attribute:: SerialInstrument.baud_rate The communication speed in baud. The default value is 9600. .. attribute:: SerialInstrument.data_bits Number of data bits contained in each frame. Its value must be from 5 to 8. The default is 8. .. attribute:: SerialInstrument.stop_bits Number of stop bits contained in each frame. Possible values are 1, 1.5, and 2. The default is 1. .. attribute:: SerialInstrument.parity The parity used with every frame transmitted and received. Possible values are: +----------------+-----------------------------------------+ | Value | Description | +================+=========================================+ | *no_parity* | no parity bit is used | +----------------+-----------------------------------------+ | *odd_parity* | the parity bit causes odd parity | +----------------+-----------------------------------------+ | *even_parity* | the parity bit causes even parity | +----------------+-----------------------------------------+ | *mark_parity* | the parity bit exists but it's always 1 | +----------------+-----------------------------------------+ | *space_parity* | the parity bit exists but it's always 0 | +----------------+-----------------------------------------+ The default value is *no_parity*. .. attribute:: SerialInstrument.end_input This determines the method used to terminate read operations. Possible values are: +------------------------+--------------------------------------------+ | Value | Description | +========================+============================================+ | *last_bit_end_input* | read will terminate as soon as a character | | | arrives with its last data bit set | +------------------------+--------------------------------------------+ | *term_chars_end_input* | read will terminate as soon as the last | | | character of *term_chars* is received | +------------------------+--------------------------------------------+ The default value is *term_chars_end_input*. Common properties of instrument variables ========================================= .. _sec:timeouts: Timeouts -------- .. index:: single: timeout Very most VISA I/O operations may be performed with a timeout. If a timeout is set, every operation that takes longer than the timeout is aborted and an exception is raised. Timeouts are given per instrument. For all PyVISA objects, a timeout is set with .. code-block:: python my_device.timeout = 25 Here, `my_device` may be a device, an interface or whatever, and its timeout is set to 25 seconds. Floating-point values are allowed. If you set it to zero, all operations must succeed instantaneously. You must not set it to `None`. Instead, if you want to remove the timeout, just say .. code-block:: python del my_device.timeout Now every operation of the resource takes as long as it takes, even indefinitely if necessary. The default timeout is 5 seconds, but you can change it when creating the device object: :: my_instrument = instrument("ASRL1", timeout = 8) This creates the object variable `my_instrument` and sets its timeout to 8 seconds. In this context, a timeout value of `None` is allowed, which removes the timeout for this device. Note that your local VISA library may round up this value heavily. I experienced this effect with my National Instruments VISA implementation, which rounds off to 0, 1, 3 and 10 seconds. .. _sec:chunk-length: Chunk length ------------ .. index:: single: chunk_length If you read data from a device, you must store it somewhere. Unfortunately, PyVISA must make space for the data *before* it starts reading, which means that it must know how much data the device will send. However, it doesn't know a priori. Therefore, PyVISA reads from the device in *chunks*. Each chunk is 20 kilobytes long by default. If there's still data to be read, PyVISA repeats the procedure and eventually concatenates the results and returns it to you. Those 20 kilobytes are large enough so that mostly one read cycle is sufficient. The whole thing happens automatically, as you can see. Normally you needn't worry about it. However, some devices don't like to send data in chunks. So if you have trouble with a certain device and expect data lengths larger than the default chunk length, you should increase its value by saying e.g. :: my_instrument.chunk_size = 102400 This example sets it to 100 kilobytes. .. _sec:reading-binary-data: Reading binary data ------------------- .. index:: single: values_format single: binary data Some instruments allow for sending the measured data in binary form. This has the advantage that the data transfer is much smaller and takes less time. PyVISA currently supports three forms of transfers: ascii This is the default mode. It assumes a normal string with comma- or whitespace-separated values. single The values are expected as a binary sequence of IEEE floating point values with single precision (i.e. four bytes each). [#]_ double The same as **single**, but with values of double precision (eight bytes each). You can set the form of transfer with the property `values_format`, either with the generation of the object, .. code-block:: python my_instrument = instrument("GPIB::12", values_format = single) or later by setting the property directly:: my_instrument.values_format = single Setting this option affects the methods `read_values()` and `ask_for_values()`. In particular, you must assure separately that the device actually sends in this format. In some cases it may be necessary to set the *byte order*, also known as *endianness*. PyVISA assumes little-endian as default. Some instruments call this "swapped" byte order. However, there is also big-endian byte order. In this case you have to append `| big_endian` to your values format:: my_instrument = instrument("GPIB::12", values_format = single | big_endian) .. _sec:binary-example: Example ^^^^^^^ In order to demonstrate how easy reading binary data can be, remember our example from section :ref:`sec:more-complex-example`. You just have to append the lines .. code-block:: python keithley.write("format:data sreal") keithley.values_format = single to the initialisation commands, and all measurement data will be transmitted as binary. You will only notice the increased speed, as PyVISA converts it into the same list of values as before. .. _sec:termchars: Termination characters ---------------------- .. index:: single: termination characters single: ending sequence single: term_chars Somehow the computer must detect when the device is finished with sending a message. It does so by using different methods, depending on the bus system. In most cases you don't need to worry about termination characters because the defaults are very good. However, if you have trouble, you may influence termination characters with PyVISA. Termination characters may be one character or a sequence of characters. Whenever this character or sequence occurs in the input stream, the read operation is terminated and the read message is given to the calling application. The next read operation continues with the input stream immediately after the last termination sequence. In PyVISA, the termination characters are stripped off the message before it is given to you. You may set termination characters for each instrument, e.g. .. code-block:: python my_instrument.term_chars = CR Alternatively you can give it when creating your instrument object:: my_instrument = instrument("GPIB::10", term_chars = CR) The default value depends on the bus system. Generally, the sequence is empty, in particular for GPIB . For RS232 it's `CR` . Well, the real default is not `""` (the empty string) but `None`. There is a subtle difference: `""` really means the termination characters are not used at all, neither for read nor for write operations. In contrast, `None` means that every write operation is implicitly terminated with `CR+LF` . This works well with most instruments. All CRs and LFs are stripped from the end of a read string, no matter how `term_chars` is set. The termination characters sequence is an ordinary string. `CR` and `LF` are just string constants that allow readable access to `"\\r"` and `"\\n"`. Therefore, instead of `CR+LF`, you can also write `"\\r\\n"`, whichever you like more. `delay` and `send_end` ^^^^^^^^^^^^^^^^^^^^^^ .. index:: single: delay single: send_end There are two further options related to message termination, namely `send_end` and `delay`. `send_end` is a boolean. If it's `True` (the default), the EOI line is asserted after each write operation, signalling the end of the operation. EOI is GPIB-specific but similar action is taken for other interfaces. The argument `delay` is the time in seconds to wait after each write operation. So you could write:: my_instrument = instrument("GPIB::10", send_end = False, delay = 1.2) .. index:: single: EOI line This will set the delay to 1.2 seconds, and the EOI line is omitted. By the way, omitting EOI is *not* recommended, so if you omit it nevertheless, you should know what you're doing. Mixing with direct VISA commands ================================ .. index:: single: VISA commands, mixing with You can mix the high-level object-oriented approach described in this document with middle-level VISA function calls in module :mod:`vpp43` as described in `The VISA library implementation `_ which is also part of the PyVISA package. By doing so, you have full control of your devices. I recommend to import the VISA functions with:: from pyvisa import vpp43 .. index:: module: vpp43 Then you can use them with `vpp43.function_name(...)`. The VISA functions need to know what session you are referring to. PyVISA opens exactly one session for each instrument or interface and stores its session handle in the instance attribute :attr:`vi`. For example, these two lines are equivalent:: my_instrument.clear() vpp43.clear(my_instrument.vi) In case you need the session handle for the default resource manager, it's stored in :attr:`resource_manager.session`:: from visa import * from pyvisa import vpp43 my_instrument_handle = vpp43.open(resource_manager.session, "GPIB::14", VI_EXCLUSIVE_LOCK) Installation ============ .. index:: single: installation Prerequisites ------------- .. index:: single: prerequisites module: ctypes PyVISA needs Python version 2.3 or newer. The PyVISA package doesn't include a low-level VISA implementation itself. You have to get it from one of the VISA vendors, e.g. from the `National Instruments VISA pages `_. NI sells its VISA kit for approx. $400. However, it's bundled with most of NI's hardware and software. Besides, the download itself is free, and one user reported that he had successfully installed VISA support without buying anything. I can't really tell about other vendors but well-equipped labs probably have VISA already (even if they don't know). Please install VISA properly before you proceed. Additionally, your Python installation needs a fresh version of `ctypes `_. By the way, if you use Windows, I recommend to install `Enthought Python `_. It is a special Python version with all- included philosophy for scientific and engineering applications. [#]_ Setting up the module --------------------- .. index:: single: configuration single: setting up PyVISA Windows ^^^^^^^ .. index:: single: visa32.dll single: PATH PyVISA expects a file called :file:`visa32.dll` in the :envvar:`PATH` . For example, on my system you find this file in :file:`C:\WINNT\system32\`. Either copy it there or expand your :envvar:`PATH`. Alternatively, you can create an INI file. You must do this anyway if the file is not called :file:`visa32.dll` on your system. Linux ^^^^^ For Linux, the VISA library is by default at :file:`/usr/local/vxipnp/linux/bin/libvisa.so.7`. If this is not the case on your installation, you have to create an INI file. INI file for customisation ^^^^^^^^^^^^^^^^^^^^^^^^^^ .. index:: single: INI file single: pyvisarc@.pyvisarc If the VISA library file is not at the default place, or doesn't have the default name for your operating system (see above), you can tell PyVISA by creating a file called :file:`.pyvisarc` (mind the leading dot). Another motivation for setting up an INI file is that you have more than one VISA library, e.g. because two GPIB interfaces of two different vendors are connected with the computer. However, in this case I'd try to use both interfaces with one library because sometimes you're lucky and it works. Note that PyVISA is currently not able to switch between DLLs while the program is running. For Windows, place it in your "Documents and Settings" folder, [#]_ e.g. .. code-block:: none C:\Documents and Settings\smith\.pyvisarc if "smith" is the name of your login account. For Linux, put it in your home directory. This file has the format of an INI file. For example, if the library is at :file:`/usr/lib/libvisa.so.7`, the file :file:`.pyvisarc` must contain the following:: [Paths] VISA library: /usr/lib/libvisa.so.7 Please note that `[Paths]` is treated case-sensitively. You can define a site-wide configuration file at :file:`/usr/share/pyvisa/.pyvisarc`. (It may also be :file:`/usr/local/...` depending on the location of your Python.) Under Windows, this file is usually placed at :file:`c:\Python24\share\pyvisa\.pyvisarc`. Setting the VISA library in the program ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ You can also set the path to your VISA library at the beginning of your program. Just start the program with :: from pyvisa.vpp43 import visa_library visa_library.load_library("/usr/lib/libvisa.so.7") from visa import * ... Keep in mind that the backslashes of Windows paths must be properly escaped, or the path must be preceeded by `r`:: from pyvisa.vpp43 import visa_library visa_library.load_library(r"c:\WINNT\system32\agvisa32.dll") from visa import * ... About PyVISA ============ .. index:: single: authors PyVISA was originally programmed by Torsten Bronger, Aachen Germany and Gregor Thalhammer, Innsbruck Austria. It bases on earlier experiences by Thalhammer. Its homepage is ``_. Please report bugs there. **I'm also very keen to know whether PyVISA works for you or not. Thank you!** .. rubric:: Footnotes .. [#] such as the "Measurement and Automation Center" by National Instruments .. [#] All flavours of binary data streams defined in IEEE488.2 are supported, i.e. those beginning with *
#*, where *
* is optional, and ** may also be "0". .. [#] Of course, it's highly advisable not to have installed another version of Python on your system before you install Enthought Python. .. [#] its name depends on the language of your Windows version PyVISA-1.4/doc/conf.py0000644000175000017500000001463211734647056014102 0ustar floflo00000000000000# -*- coding: utf-8 -*- # # PyVISA documentation build configuration file # # This file is execfile()d with the current directory set to its containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. import sys, os # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. #sys.path.append(os.path.abspath('.')) # -- General configuration ----------------------------------------------------- # Add any Sphinx extension module names here, as strings. They can be extensions # coming with Sphinx (named 'sphinx.ext.*') or your custom ones. extensions = ['sphinx.ext.autodoc', 'sphinx.ext.doctest'] autoclass_content = 'both' # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix of source filenames. source_suffix = '.txt' # The encoding of source files. #source_encoding = 'utf-8' # The master toctree document. master_doc = 'pyvisa' # General information about the project. project = u'PyVISA' copyright = u"2012 Florian Bauer, 2011 Kevin Saff, 2005-2011 Torsten Bronger, Gregor Thalhammer" # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. version = '1.4' # The full version, including alpha/beta/rc tags. release = '1.4.dev' # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. #language = None # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: #today = '' # Else, today_fmt is used as the format for a strftime call. #today_fmt = '%B %d, %Y' # List of documents that shouldn't be included in the build. #unused_docs = [] # List of directories, relative to source directory, that shouldn't be searched # for source files. exclude_trees = ['_build'] # The reST default role (used for this markup: `text`) to use for all documents. #default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. #add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). #add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. #show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # A list of ignored prefixes for module index sorting. #modindex_common_prefix = [] # -- Options for HTML output --------------------------------------------------- # The theme to use for HTML and HTML Help pages. Major themes that come with # Sphinx are currently 'default' and 'sphinxdoc'. html_theme = 'sphinxdoc' # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. #html_theme_options = {} # Add any paths that contain custom themes here, relative to this directory. #html_theme_path = [] # The name for this set of Sphinx documents. If None, it defaults to # " v documentation". #html_title = None # A shorter title for the navigation bar. Default is the same as html_title. #html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. #html_logo = None # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. #html_favicon = None # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['_static'] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. #html_use_smartypants = True # Custom sidebar templates, maps document names to template names. #html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. #html_additional_pages = {} # If false, no module index is generated. #html_use_modindex = True # If false, no index is generated. #html_use_index = True # If true, the index is split into individual pages for each letter. #html_split_index = False # If true, links to the reST sources are added to the pages. #html_show_sourcelink = True # If true, an OpenSearch description file will be output, and all pages will # contain a tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. #html_use_opensearch = '' # If nonempty, this is the file name suffix for HTML files (e.g. ".xhtml"). #html_file_suffix = '' # Output file base name for HTML help builder. htmlhelp_basename = 'pyvisadoc' # -- Options for LaTeX output -------------------------------------------------- # The paper size ('letter' or 'a4'). #latex_paper_size = 'letter' # The font size ('10pt', '11pt' or '12pt'). #latex_font_size = '10pt' # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, author, documentclass [howto/manual]). latex_documents = [ ('index', 'pyvisa.tex', u'PyVISA Documentation', u'Florian Bauer', 'manual'), ] # The name of an image file (relative to this directory) to place at the top of # the title page. #latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. #latex_use_parts = False # Additional stuff for the LaTeX preamble. #latex_preamble = '' # Documents to append as an appendix to all manuals. #latex_appendices = [] # If false, no module index is generated. #latex_use_modindex = True PyVISA-1.4/doc/Makefile0000644000175000017500000001025011734647056014233 0ustar floflo00000000000000# Makefile for Sphinx documentation # # You can set these variables from the command line. SPHINXOPTS = SPHINXBUILD = sphinx-build PAPER = BUILDDIR = _build # Internal variables. PAPEROPT_a4 = -D latex_paper_size=a4 PAPEROPT_letter = -D latex_paper_size=letter ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . .PHONY: help clean html dirhtml pickle json htmlhelp qthelp latex changes linkcheck doctest help: @echo "Please use \`make ' where is one of" @echo " html to make standalone HTML files" @echo " dirhtml to make HTML files named index.html in directories" @echo " pickle to make pickle files" @echo " json to make JSON files" @echo " htmlhelp to make HTML files and a HTML help project" @echo " qthelp to make HTML files and a qthelp project" @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" @echo " changes to make an overview of all changed/added/deprecated items" @echo " linkcheck to check all external links for integrity" @echo " doctest to run all doctests embedded in the documentation (if enabled)" clean: -rm -rf $(BUILDDIR)/* html: $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html @echo @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." dirhtml: $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml @echo @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." pickle: $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle @echo @echo "Build finished; now you can process the pickle files." json: $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json @echo @echo "Build finished; now you can process the JSON files." htmlhelp: $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp @echo @echo "Build finished; now you can run HTML Help Workshop with the" \ ".hhp project file in $(BUILDDIR)/htmlhelp." qthelp: $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp @echo @echo "Build finished; now you can run "qcollectiongenerator" with the" \ ".qhcp project file in $(BUILDDIR)/qthelp, like this:" @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/usbio.qhcp" @echo "To view the help file:" @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/usbio.qhc" latex: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." @echo "Run \`make all-pdf' or \`make all-ps' in that directory to" \ "run these through (pdf)latex." changes: $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes @echo @echo "The overview file is in $(BUILDDIR)/changes." linkcheck: $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck @echo @echo "Link check complete; look for any errors in the above output " \ "or in $(BUILDDIR)/linkcheck/output.txt." doctest: $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest @echo "Testing of doctests in the sources finished, look at the " \ "results in $(BUILDDIR)/doctest/output.txt." ## Contents of the old makefile: ## ## .PHONY: all upload ## ## all: vpp43.html index.html pyvisa.pdf pyvisa ## ## vpp43.html: vpp43.txt ## rst2html.py vpp43.txt > vpp43.html ## ## index.html: homepage.txt ## rst2html.py homepage.txt | \ ## sed -e "s%%\\0\n%" \ ## > index.html ## ## # I have to do the following in /tmp because latex2html doesn't want to work in ## # a path that contains a dot. Unfortunately, the BUILD directory that ## # Distutils creates contains one. ## ## pyvisa.pdf: pyvisa.tex ## rm -Rf pyvisa /tmp/pyvisa ## cp pyvisa.tex /tmp/ ## cd /tmp ; /usr/lib/python2.5/doc/tools/mkhowto --pdf --html \ ## --up-link http://pyvisa.sourceforge.net \ ## --up-title "PyVISA homepage" --numeric --image-type=png \ ## --iconserver=. pyvisa.tex ## mv /tmp/pyvisa.pdf /tmp/pyvisa . ## ## upload: all ## scp vpp43.html index.html default.css pyvisa.pdf \ ## shell.sf.net:/home/groups/p/py/pyvisa/htdocs/ PyVISA-1.4/doc/vpp43.txt0000644000175000017500000015030711753675004014313 0ustar floflo00000000000000.. -*- mode: rst; coding: iso-8859-1; ispell-local-dictionary: "british"; -*- .. .. vpp43.txt - VISA VPP-4.3.2 functions documentation .. .. Copyright © 2005, 2006, 2007, 2008 .. Torsten Bronger , .. Gregor Thalhammer . .. .. This file is part of PyVISA. .. .. PyVISA is free software; you can redistribute it and/or modify it under .. the terms of the MIT licence: .. .. Permission is hereby granted, free of charge, to any person obtaining a .. copy of this software and associated documentation files (the "Software"), .. to deal in the Software without restriction, including without limitation .. the rights to use, copy, modify, merge, publish, distribute, sublicense, .. and/or sell copies of the Software, and to permit persons to whom the .. Software is furnished to do so, subject to the following conditions: .. .. The above copyright notice and this permission notice shall be included in .. all copies or substantial portions of the Software. .. .. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR .. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, .. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL .. THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER .. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING .. FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER .. DEALINGS IN THE SOFTWARE. .. ====================================== The VISA library implementation ====================================== --------------------------------- Part of the PyVISA package --------------------------------- :Date: |today| :Author: Torsten Bronger :Maintainer: Florian Bauer :Abstract: This document covers the ``vpp43.py`` module, which is part of the PyVISA_ package. This module implements thin wrappers around all functions defined in the `VISA specification`_. Thus it enables the programmer to communicate with measurement and test devices via GPIB, RS232, USB etc. .. _PyVISA: http://pyvisa.sourceforge.net/ .. _`VISA specification`: http://www.ivifoundation.org/Downloads/Class%20Specifications/vpp43.doc .. contents:: About the vpp43 module ====================== This module ``vpp43`` is a cautious yet thorough adaption of the VISA specification for Python. The "textual languages" VISA specification can't be implemented as is because Python is rather different from C and Visual Basic, most notably because of lacking call-by-reference. The second important difference are strings: In C they are null-terminated whereas Python doesn't have this constraint. The slightly odd name ``vpp43`` for this module derives from the necessity to make (name)space for the ``visa`` module that is supposed to realise the actual high-level VISA access in Python. The `VXIplug&play Systems Alliance`_ used to maintain the VISA specifications, and, although today the `IVI foundation`_ is responsible for this task, the files are still called ``vpp43.doc`` etc. So I thought ``vpp43`` was an appropriate name. .. _`VXIplug&play Systems Alliance`: http://www.vxipnp.org/ .. _`IVI foundation`: http://ivifoundation.org You may wonder why I did choose new names for all routines. I did so because Python has its own naming guidelines, and because it shows that the routines had to be adapted. However, I didn't change them really: Every routine is a 1:1 counterpart. By calling them from C, you could even create a C-based VISA implementation with the original function signatures and semantics. Moreover, the new names are mere expansions of the original ones. Connecting to the VISA shared object ==================================== ``vpp43`` tries to find the VISA library for itself. On Windows, this is not a big problem. ``visa32.dll`` must be in your ``PATH``. If it isn't, move it there or expand your ``PATH``. However, on Linux you may need to give the explicit path to the shared object file. You do so by saying for example:: import pyvisa.vpp43 as vpp43 vpp43.visa_library.load_library("/path/to/my/libvisa.so.7") By default, ``vpp43`` looks for the library in ``/usr/local/vxipnp/linux/bin/libvisa.so.7``. Please pay attention to the fact that the library must have been successfully loaded *before* any VISA call is made. Alternatively, you can tell PyVISA so by creating a file ``~/.pyvisarc``. This has the format of an INI file. For example, if the library is at ``/usr/lib/libvisa.so.7``, the file ``.pyvisarc`` must contain the following:: [Paths] VISA library: /usr/lib/libvisa.so.7 Please note that ``[Paths]`` is treated case-sensitively. You can define a site-wide configuration file at ``/usr/share/pyvisa/.pyvisarc``. (It may also be ``/usr/local/...`` depending on the location of your Python.) Diagnostics =========== This module can raise a couple of ``vpp43``-specific exceptions. :Name: VisaIOError :Description: This is an error of the underlying VISA library, as described in table 3.3.1 in the `VISA specification for textual languages`_. The exception member ``error_code`` contains the (always negative) VISA error number, as listed in that table. :Name: VisaIOWarning :Description: This is a warning of the underlying VISA library, as described in table 3.3.1 in the `VISA specification for textual languages`_. The exception member ``completion_code`` contains the (always positive) VISA completion number, as listed in that table. Normally you don't see these warnings. You can turn them into exceptions with:: import warnings warnings.filterwarnings("error") Consult the description of the ``warnings`` package for further information. .. _`VISA specification for textual languages`: http://www.ivifoundation.org/Downloads/Class%20Specifications/vpp432.doc :Name: TypeError :Description: The current implementation of `printf`_, `scanf`_, `sprintf`_, `sscanf`_, and `queryf`_ have the limitation that only integers, floats, and strings are allowed as types for the arbitrary arguments. Additionally, only format string directives for C longs, C doubles, and C strings are allowed to use, albeit not checked. However, if you pass a list or a unicode string, you get this exception. The same exception is raised if an unsupported type is passed as user handle to `install_handler`_. See there for a list of supported types. :Name: UnknownHandler :Description: Raised if an unknown `handler`/`user_handle` pair is passed to `uninstall_handler`_. In particular, you must save the user handle returned by `install_handler`_ in order to pass it to uninstall_handler. Moreover, this module may pass exceptions generated by ctypes. This may be because you've passed a wrong type to a function, or that the VISA library file was not found, but it may also mean a bug in ``vpp43`` itself. So if you don't see why the exception was raised, contact the current maintainers of PyVISA. The PyVISA function reference ============================= Please note that all descriptions given in this reference serve mostly as reminders. For real descriptions consult a `VISA specification`_ or `NI-VISA Programmer Reference Manual`_. However, whenever there are PyVISA-specific semantics, they are listed here, too. .. _`VISA specification`: http://www.ivifoundation.org/Downloads/Class%20Specifications/vpp43.doc .. _`NI-VISA Programmer Reference Manual`: http://digital.ni.com/manuals.nsf/websearch/87E52268CF9ACCEE86256D0F006E860D assert_interrupt_signal ....................... Asserts the specified device interrupt or signal. :Call: assert_interrupt_signal(vi, mode, status_id) :VISA name: viAssertIntrSignal :Parameters: `vi` : integer Unique logical identifier to a session. `mode` : integer This specifies how to assert the interrupt. `status_id` : integer This is the status value to be presented during an interrupt acknowledge cycle. :Return values: None. assert_trigger .............. Assert software or hardware trigger. :Call: assert_trigger(vi, protocol) :VISA name: viAssertTrigger :Parameters: `vi` : integer Unique logical identifier to a session. `protocol` : integer Trigger protocol to use during assertion. Valid values are: ``VI_TRIG_PROT_DEFAULT``, ``VI_TRIG_PROT_ON``, ``VI_TRIG_PROT_OFF``, and ``VI_TRIG_PROT_SYNC``. :Return values: None. assert_utility_signal ..................... Asserts the specified utility bus signal. :Call: assert_utility_signal(vi, line) :VISA name: viAssertUtilSignal :Parameters: `vi` : integer Unique logical identifier to a session. `line` : integer Specifies the utility bus signal to assert. :Return values: None. buffer_read ........... Similar to `read`_, except that the operation uses the formatted I/O read buffer for holding data read from the device. :Call: buffer = buffer_read(vi, count) :VISA name: viBufRead :Parameters: `vi` : integer Unique logical identifier to a session. `count` : integer Maximal number of bytes to be read. :Return values: `buffer` : string The buffer with the received data from device. buffer_write ............ Similar to `write`_, except the data is written to the formatted I/O write buffer rather than directly to the device. :Call: return_count = buffer_write(vi, buffer) :VISA name: viBufWrite :Parameters: `vi` : integer Unique logical identifier to a session. `buffer` : string The data block to be sent to device. :Return values: `return_count` : integer The number of bytes actually transferred. clear ..... Clear a device. :Call: clear(vi) :VISA name: viClear :Parameters: `vi` : integer Unique logical identifier to a session. :Return values: None. close ..... Close the specified session, event, or find list. :Call: close(vi) :VISA name: viClose :Parameters: `vi` : integer, ViEvent, or ViFindList Unique logical identifier to a session, event, or find list. :Return values: None. disable_event ............. Disable notification of an event type by the specified mechanisms. :Call: disable_event(vi, event_type, mechanism) :VISA name: viDisableEvent :Parameters: `vi` : integer Unique logical identifier to a session. `event_type` : integer Logical event identifier. `mechanism` : integer Specifies event handling mechanisms to be disabled. The queuing mechanism is disabled by specifying ``VI_QUEUE``, and the callback mechanism is disabled by specifying ``VI_HNDLR`` or ``VI_SUSPEND_HNDLR``. It is possible to disable both mechanisms simultaneously by specifying ``VI_ALL_MECH``. :Return values: None. discard_events .............. Discard event occurrences for specified event types and mechanisms in a session. :Call: discard_events(vi, event_type, mechanism) :VISA name: viDiscardEvents :Parameters: `vi` : integer Unique logical identifier to a session. `event_type` : integer Logical event identifier. `mechanism` : integer Specifies the mechanisms for which the events are to be discarded. The ``VI_QUEUE`` value is specified for the queuing mechanism and the ``VI_SUSPEND_HNDLR`` value is specified for the pending events in the callback mechanism. It is possible to specify both mechanisms simultaneously by specifying ``VI_ALL_MECH``. :Return values: None. enable_event ............ Enable notification of a specified event. :Call: enable_event(vi, event_type, mechanism, context) :VISA name: viEnableEvent :Parameters: `vi` : integer Unique logical identifier to a session. `event_type` : integer Logical event identifier. `mechanism` : integer Specifies event handling mechanisms to be enabled. The queuing mechanism is enabled by specifying ``VI_QUEUE``, and the callback mechanism is enabled by specifying ``VI_HNDLR`` or ``VI_SUSPEND_HNDLR``. It is possible to enable both mechanisms simultaneously by specifying bit-wise "or" of ``VI_QUEUE`` and one of the two mode values for the callback mechanism. `context` : integer : optional According to the VISA specification, this must be ``Vi_NULL`` always. (This is also the default value, of course.) :Return values: None. find_next ......... :Call: instrument_description = find_next(find_list) :VISA name: viFindNext :Parameters: `find_list` : ViFindList Describes a find list. This parameter must be created by `find_resources`_. :Return values: `instrument_description` : string Returns a string identifying the location of a device. Strings can then be passed to `open`_ to establish a session to the given device. find_resources .............. :Call: find_list, return_counter, instrument_description = find_resources(session, regular_expression) :VISA name: viFindRsrc :Parameters: `session` : integer Resource Manager session (should always be the Default Resource Manager for VISA returned from `open_default_resource_manager`_). `regular_expression` : integer This is a regular expression followed by an optional logical expression. :Return values: `find_list` : ViFindList Returns a handle identifying this search session. This handle will be used as an input in `find_next`_. `return_counter` : integer Number of matches. `instrument_description` : string Returns a string identifying the location of a device. Strings can then be passed to `open`_ to establish a session to the given device. flush ..... Manually flush the specified buffers associated with formatted I/O operations and/or serial communication. :Call: flush(vi, mask) :VISA name: viFlush :Parameters: `vi` : integer Unique logical identifier to a session. `mask` : integer Specifies the action to be taken with flushing the buffer. :Return values: None. get_attribute ............. Retrieve the state of an attribute. :Call: attribute_state = get_attribute(vi, attribute) :VISA name: viGetAttribute :Parameters: `vi` : integer, ViEvent, or ViFindList Unique logical identifier to a session. `attribute` : integer Session, event, or find list attribute for which the state query is made. :Return values: `attribute_state` : integer, string, or list of integers The state of the queried attribute for a specified resource. gpib_command ............ Write GPIB command bytes on the bus. :Call: return_count = gpib_command(vi, buffer) :VISA name: viGpibCommand :Parameters: `vi` : integer Unique logical identifier to a session. `buffer` : string Buffer containing valid GPIB commands. :Return values: `return_count` : integer Number of bytes actually transferred. gpib_control_atn ................ Controls the state of the GPIB ATN interface line, and optionally the active controller state of the local interface board. :Call: gpib_control_atn(vi, mode) :VISA name: viGpibControlATN :Parameters: `vi` : integer Unique logical identifier to a session. `mode` : integer Specifies the state of the ATN line and optionally the local active controller state. See the Description section for actual values. :Return values: None. gpib_control_ren ................ Controls the state of the GPIB REN interface line, and optionally the remote/local state of the device. :Call: gpib_control_ren(vi, mode) :VISA name: viGpibControlREN :Parameters: `vi` : integer Unique logical identifier to a session. `mode` : integer Specifies the state of the REN line and optionally the device remote/local state. See the Description section for actual values. :Return values: None. gpib_pass_control ................. Tell the GPIB device at the specified address to become controller in charge (CIC). :Call: gpib_pass_control(vi, primary_address, secondary_address) :VISA name: viGpibPassControl :Parameters: `vi` : integer Unique logical identifier to a session. `primary_address` : integer Primary address of the GPIB device to which you want to pass control. `secondary_address` : integer Secondary address of the targeted GPIB device. If the targeted device does not have a secondary address, this parameter should contain the value ``VI_NO_SEC_ADDR``. :Return values: None. gpib_send_ifc ............. Pulse the interface clear line (IFC) for at least 100 microseconds. :Call: gpib_send_ifc(vi) :VISA name: viGpibSendIFC :Parameters: `vi` : integer Unique logical identifier to a session. :Return values: None. in_8, in_16, in_32 .................. Read in an 8-bit, 16-bit, or 32-bit value from the specified memory space and offset. :Call: | value_8 = in_8(vi, space, offset) | value_16 = in_16(vi, space, offset) | value_32 = in_32(vi, space, offset) :VISA name: viIn8, viIn16, viIn32 :Parameters: `vi` : integer Unique logical identifier to a session. `space` : integer Specifies the address space. `offset` : integer Offset in bytes of the address or register from which to read. :Return values: `value_8`, `value_16`, `value_32` : integer Data read from bus (8 bits for `in_8`, 16 bits for `in_16`, and 32 bits for `in_32`). install_handler ............... Install handlers for event callbacks. A handler must have the following signature:: def event_handler(vi, event_type, context, user_handle): ... Its parameters mean the following: `vi` : integer Unique logical identifier to a session. `event_type` : ViEvent Logical event identifier. With ``event_type.value`` you get its value as an integer. `context` : ViEvent A handle specifying the unique occurrence of an event. `user_handle` : ctypes pointer type A *pointer* to the user handle in ctypes form. See below at "Return values" for how to use it, however, you have to substitute ``user_handle.contents`` for ``converted_user_handle`` in the explanation. :Call: converted_user_handle = install_handler(vi, event_type, handler, user_handle) :VISA name: viInstallHandler :Parameters: `vi` : integer Unique logical identifier to a session. `event_type` : integer Logical event identifier. `handler` : callable Interpreted as a valid reference to a handler to be installed by a client application. `user_handle` : ``None``, float, integer, string, or list of floats or integers : optional A value specified by an application that can be used for identifying handlers uniquely for an event type. It defaults to ``None``. :Return values: `converted_user_handle` : ctypes type An object representing the user_handle. Use it to communicate with your handler. If your user_handle was a list, you get its elements as usual with ``converted_user_handle[index]``. You can even convert it to a list with ``list(converted_user_handle)`` (however, this yields a copy). For strings, use ``converted_user_handle.value`` if it's supposed to be interpreted as a null-terminated string, or ``converted_user_handle.raw`` if you want to see *all* bytes. You can also write to both expressions, however, slicing is only possible for reading. For simple types, you can say ``converted_user_handle.value`` (read and write). **Attention:** You must assure that you never write values to converted_user_data which are longer (in bytes) than the initial values. So be careful not to write a string longer than the original one, nor a longer list. You'd be alerted by exceptions, though. lock .... Establish an access mode to the specified resource. :Call: access_key = lock(vi, lock_type, timeout, requested_key) :VISA name: viLock :Parameters: `vi` : integer Unique logical identifier to a session. `lock_type` : integer Specifies the type of lock requested, which can be either ``VI_EXCLUSIVE_LOCK`` or ``VI_SHARED_LOCK``. `timeout` : integer Absolute time period in milliseconds that a resource waits to get unlocked by the locking session before returning this operation with an error. `requested_key` : ctypes string : optional This parameter is not used if `lock_type` is ``VI_EXCLUSIVE_LOCK`` (exclusive locks). When trying to lock the resource as ``VI_SHARED_LOCK`` (shared), you can either omit it so that VISA generates an `access_key` for the session, or you can suggest an `access_key` to use for the shared lock. :Return values: `access_key` : ctypes string : optional This value is ``None`` if `lock_type` is ``VI_EXCLUSIVE_LOCK`` (exclusive locks). When trying to lock the resource as ``VI_SHARED_LOCK`` (shared), the function returns a unique access key for the lock if the operation succeeds. This `access_key` can then be passed to other sessions to share the lock. map_address ........... Map the specified memory space into the process's address space. :Call: address = map_address(vi, map_space, map_base, map_size, access, suggested) :VISA name: viMapAddress :Parameters: `vi` : integer Unique logical identifier to a session. `map_space` : integer Specifies the address space to map. `map_base` : ViBusAddress Offset in bytes of the memory to be mapped. `map_size` : integer Amount of memory to map in bytes. `access` : integer : optional Must be ``VI_FALSE``. `suggested` : integer : optional If not ``VI_NULL`` (the default), 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 values: `address` : ViAddr Address in your process space where the memory was mapped. map_trigger ........... Map the specified trigger source line to the specified destination line. :Call: map_trigger(vi, trigger_source, trigger_destination, mode) :VISA name: viMapTrigger :Parameters: `vi` : integer Unique logical identifier to a session. `trigger_source` : integer Source line from which to map. `trigger_destination` : integer Destination line to which to map. `mode` : integer Specifies the trigger mapping mode. This should always be VI_NULL. :Return values: None. memory_allocation ................. Allocate memory from a device's memory region. :Call: memory_allocation(vi, size) :VISA name: viMemAlloc :Parameters: `vi` : integer Unique logical identifier to a session. `size` : integer Specifies the size of the allocation. :Return values: offset : ViBusAddress Returns the offset of the allocated device memory. memory_free ........... Free memory previously allocated using `memory_allocation`_. :Call: memory_free(vi, offset) :VISA name: viMemFree :Parameters: `vi` : integer Unique logical identifier to a session. `offset` : ViBusAddress Specifies the memory previously allocated with `memory_allocation`_. :Return values: None. move .... Move a block of data. :Call: move(vi, source_space, source_offset, source_width, destination_space, destination_offset, destination_width, length) :VISA name: viMove :Parameters: `vi` : integer Unique logical identifier to a session. `source_space` : integer Specifies the address space of the source. `source_offset` : integer Offset in bytes of the starting address or register from which to read. `source_width` : integer Specifies the data width of the source. `destination_space` : integer Specifies the address space of the destination. `destination_offset` : integer Offset in bytes of the starting address or register to which to write. `destination_width` : integer Specifies the data width of the destination. `length` : integer Number of elements to transfer, where the data width of the elements to transfer is identical to source data width. :Return values: None. move_asynchronously ................... Move a block of data asynchronously. :Call: job_id = move_asynchronously(vi, source_space, source_offset, source_width, destination_space, destination_offset, destination_width, length) :VISA name: viMoveAsync :Parameters: `vi` : integer Unique logical identifier to a session. `source_space` : integer Specifies the address space of the source. `source_offset` : integer Offset in bytes of the starting address or register from which to read. `source_width` : integer Specifies the data width of the source. `destination_space` : integer Specifies the address space of the destination. `destination_offset` : integer Offset in bytes of the starting address or register to which to write. `destination_width` : integer Specifies the data width of the destination. `length` : integer Number of elements to transfer, where the data width of the elements to transfer is identical to source data width. :Return values: `job_id` : ViJobId The job identifier of this asynchronous move operation. Each time an asynchronous move operation is called, it is assigned a unique job identifier. move_in_8, move_in_16, move_in_32 ................................. Move a block of data from the specified address space and offset to local memory in increments of 8, 16, or 32 bits. :Call: | buffer_8 = move_in_8(vi, space, offset, length) | buffer_16 = move_in_16(vi, space, offset, length) | buffer_32 = move_in_32(vi, space, offset, length) :VISA name: viMoveIn8, viMoveIn16, viMoveIn32 :Parameters: `vi` : integer Unique logical identifier to a session. `space` : integer Specifies the address space. `offset` : ViBusAddress Offset in bytes of the starting address or register from which to read. `length` : integer Number of elements to transfer, where the data width of the elements to transfer is identical to data width (8, 16, or 32 bits). :Return values: `buffer_8`, `buffer_16`, `buffer_32` : list of integers Data read from bus as a Python list of values. move_out_8, move_out_16, move_out_32 .................................... Move a block of data from local memory to the specified address space and offset in increments of 8, 16, or 32 bits. :Call: | move_out_8(vi, space, offset, length, buffer_8) | move_out_16(vi, space, offset, length, buffer_16) | move_out_32(vi, space, offset, length, buffer_32) :VISA name: viMoveOut8, viMoveOut16, viMoveOut32 :Parameters: `vi` : integer Unique logical identifier to a session. `space` : integer Specifies the address space. `offset` : ViBusAddress Offset in bytes of the starting address or register from which to write. `length` : integer Number of elements to transfer, where the data width of the elements to transfer is identical to data width (8, 16, or 32 bits). `buffer_8`, `buffer_16`, `buffer_32` : sequence of integers Data to write to bus. This may be a list or a tuple, however in any case in must contain integers. :Return values: None. open .... Open a session to the specified device. :Call: vi = open(session, resource_name, access_mode, open_timeout) :VISA name: viOpen :Parameters: `session` : integer Resource Manager session (should always be the Default Resource Manager for VISA returned from `open_default_resource_manager`_). `resource_name` : string Unique symbolic name of a resource. `access_mode` : integer : optional Defaults to ``VI_NO_LOCK``. Specifies the modes by which the resource is to be accessed. The value ``VI_EXCLUSIVE_LOCK`` is used to acquire an exclusive lock immediately upon opening a session; if a lock cannot be acquired, the session is closed and an error is returned. The value ``VI_LOAD_CONFIG`` is used to configure attributes to values specified by some external configuration utility; if this value is not used, the session uses the default values provided by this specification. Multiple access modes can be used simultaneously by specifying a "bitwise OR" of the above values. `open_timeout` : integer : optional If the `access_mode` parameter requests a lock, then this parameter specifies the absolute time period in milliseconds that the resource waits to get unlocked before this operation returns an error; otherwise, this parameter is ignored. Defaults to ``VI_TMO_IMMEDIATE``. :Return values: `vi` : integer Unique logical identifier reference to a session. open_default_resource_manager ............................. Return a session to the Default Resource Manager resource. :Call: session = open_default_resource_manager() :VISA name: viOpenDefaultRM :Parameters: None. :Return values: `session` : integer Unique logical identifier to a Default Resource Manager session. get_default_resource_manager ............................ This is a deprecated alias for `open_default_resource_manager`_. out_8, out_16, out_32 ..................... :Call: | out_8(vi, space, offset, value_8) | out_16(vi, space, offset, value_16) | out_32(vi, space, offset, value_32) :VISA name: viOut8, viOut16, viOut32 :Parameters: `vi` : integer Unique logical identifier to a session. `space` : integer Specifies the address space. `offset` : integer Offset in bytes of the address or register to which to write. `value_8`, `value_16`, `value_32`: integer Data to write to bus (8 bits for out_8, 16 bits for out_16, and 32 bits for out_32). :Return values: None. parse_resource .............. Parse a resource string to get the interface information. :Call: interface_type, interface_board_number = parse_resource(session, resource_name) :VISA name: viParseRsrc :Parameters: `session` : integer Resource Manager session (should always be the Default Resource Manager for VISA returned from `open_default_resource_manager`_). `resource_name` : string Unique symbolic name of a resource. :Return values: `interface_type` : integer Interface type of the given resource string. `interface_board_number` : integer Board number of the interface of the given resource string. parse_resource_extended ....................... Parse a resource string to get extended interface information. **Attention:** Calling this function may raise an ``AttributeError`` because some older VISA implementation don't have the function ``viParseRsrcEx``. :Call: interface_type, interface_board_number, resource_class, unaliased_expanded_resource_name, alias_if_exists = parse_resource_extended(session, resource_name) :VISA name: viParseRsrcEx :Parameters: `session` : integer Resource Manager session (should always be the Default Resource Manager for VISA returned from `open_default_resource_manager`_). `resource_name` : string Unique symbolic name of a resource. :Return values: `interface_type` : integer Interface type of the given resource string. `interface_board_number` : integer Board number of the interface of the given resource string. `resource_class` : string Specifies the resource class (for example "INSTR") of the given resource string. `unaliased_expanded_resource_name` : string This is the expanded version of the given resource string. The format should be similar to the VISA-defined canonical resource name. `alias_if_exists` : string Specifies the user-defined alias for the given resource string, if a VISA implementation allows aliases and an alias exists for the given resource string. If not, this is ``None``. peek_8, peek_16, peek_32 ........................ Read an 8-bit, 16-bit, or 32-bit value from the specified address. :Call: | value_8 = peek_8(vi, address) | value_16 = peek_16(vi, address) | value_32 = peek_32(vi, address) :VISA name: viPeek8, viPeek16, viPeek32 :Parameters: `vi` : integer Unique logical identifier to a session. `address` : ViAddr Specifies the source address to read the value. :Return values: `value_8`, `value_16`, `value_32` : integer Data read from bus (8 bits for peek_8, 16 bits for peek_16, and 32 bits for peek_32). poke_8, poke_16, poke_32 ........................ Write an 8-bit, 16-bit, or 32-bit value to the specified address. :Call: | poke_8(vi, address, value_8) | poke_16(vi, address, value_16) | poke_32(vi, address, value_32) :VISA name: vipoke_8 :Parameters: `vi` : integer Unique logical identifier to a session. `address` : integer Specifies the destination address to store the value. `value_8`, `value_16`, `value_32` : integer Data to write to bus (8 bits for poke_8, 16 bits for poke_16, and 32 bits for poke_32). :Return values: None. printf ...... Convert, format, and send the parameters ``...`` to the device as specified by the format string. .. Warning:: The current implementation only supports the following C data types: ``long``, ``double`` and ``char*`` (strings). Thus, you can only use these three data types in format strings for printf, scanf and the like. :Call: printf(vi, write_format, ...) :VISA name: viPrintf :Parameters: `vi` : integer Unique logical identifier to a session. `write_format` : string String describing the format for arguments. `...` : integers, floats, or strings Arguments sent to the device according to `write_format`. :Return values: None. queryf ...... Perform a formatted write and read through a single operation invocation. .. Warning:: The current implementation only supports the following C data types: ``long``, ``double`` and ``char*`` (strings). Thus, you can only use these three data types in format strings for printf, scanf and the like. :Call: value1, value2, ... = queryf(vi, write_format, read_format, (...), ..., maximal_string_length = 1024) :VISA name: viQueryf :Parameters: `vi` : integer Unique logical identifier to a session. `write_format` : string String describing the format for arguments. `read_format` : string String describing the format for arguments. `(...)` : tuple of integers, floats, or strings Arguments sent to the device according to `write_format`. May be ``None``. `...` : integers, floats, or strings Arguments to be read from the device according to `read_format`. It's totally insignificant which values they have, they serve just as a cheap way to determine what types are to be expected. So actually this argument list shouldn't be necessary, but with the current implementation, it is, sorry. These arguments may be (however needn't be) the same names used for storing the result values. Alternatively, you can give literals. `maximal_string_length` : integer : keyword argument The maximal length assumed for string result arguments. Note that string results must *never* exceed this length. It defaults to 1024. :Return values: `value1`, `value2`, ... : integers, floats, or strings Arguments read from the device according to `read_format`. Of course, this must be the same sequence (as far as data types are concerned) as the given argument list `...` above. read .... Read data from device synchronously. :Call: buffer = read(vi, count) :VISA name: viRead :Parameters: `vi` : integer Unique logical identifier to a session. `count` : integer Maximal number of bytes to be read. :Return values: `buffer` : string Represents the buffer with the received data from device. read_asynchronously ................... Read data from device asynchronously. :Call: buffer, job_id = read_asynchronously(vi, count) :VISA name: viReadAsync :Parameters: `vi` : integer Unique logical identifier to a session. `count` : integer Maximal number of bytes to be read. :Return values: `buffer` : ctypes string buffer Represents the buffer with the data received from device. It's not a native Python data type because it's filled in the background (i.e. asynchronously). After you assured that the reading is finished, you get its value with:: buffer.raw[:return_count] You get ``return_count`` via the attribute ``VI_ATTR_RET_COUNT``. See the `VISA reference`_ for further information. `job_id` : ViJobId Represents the location of a variable that will be set to the job identifier of this asynchronous read operation. .. _`VISA reference`: http://digital.ni.com/manuals.nsf/websearch/87E52268CF9ACCEE86256D0F006E860D read_stb ........ Read a status byte of the service request. :Call: status = read_stb(vi) :VISA name: viReadSTB :Parameters: `vi` : integer Unique logical identifier to a session. :Return values: `status` : integer Service request status byte. read_to_file ............ Read data synchronously, and store the transferred data in a file. :Call: return_count = read_to_file(vi, filename, count) :VISA name: viReadToFile :Parameters: `vi` : integer Unique logical identifier to a session. `file_name` : string Name of file to which data will be written. `count` : integer Maximal number of bytes to be read. :Return values: `return_count` : integer Number of bytes actually transferred. scanf ..... Read, convert, and format data using the format specifier. Store the formatted data in the given optional parameters. .. Warning:: The current implementation only supports the following C data types: ``long``, ``double`` and ``char*`` (strings). Thus, you can only use these three data types in format strings for printf, scanf and the like. :Call: value1, value2, ... = scanf(vi, read_format, ..., maximal_string_length = 1024) :VISA name: viScanf :Parameters: `vi` : integer Unique logical identifier to a session. `read_format` : string String describing the format for arguments. `...` : integers, floats, or strings Arguments to be read from the device according to `read_format`. It's totally insignificant which values they have, they serve just as a cheap way to determine what types are to be expected. So actually this argument list shouldn't be necessary, but with the current implementation, it is, sorry. These arguments may be (however needn't be) the same names used for storing the result values. Alternatively, you can give literals. `maximal_string_length` : integer : keyword argument The maximal length assumed for string result arguments. Note that string results must *never* exceed this length. It defaults to 1024. :Return values: `value1`, `value2`, ... : integers, floats, or strings Arguments read from the device according to `read_format`. Of course, this must be the same sequence (as far as data types are concerned) as the given argument list `...` above. set_attribute ............. Set the state of an attribute. :Call: set_attribute(vi, attribute, attribute_state) :VISA name: viSetAttribute :Parameters: `vi` : integer, ViEvent, or ViFindList Unique logical identifier to a session. `attribute` : integer Session, event, or find list attribute for which the state is modified. `attribute_state` : integer The state of the attribute to be set for the specified resource. The interpretation of the individual attribute value is defined by the resource. :Return values: None. set_buffer .......... Set the size for the formatted I/O and/or serial communication buffer(s). :Call: set_buffer(vi, mask, size) :VISA name: viSetBuf :Parameters: `vi` : integer Unique logical identifier to a session. `mask` : integer Specifies the type of buffer. `size` : integer The size to be set for the specified buffer(s). :Return values: None. sprintf ....... Same as `printf`_, except the data is written to a user-specified buffer rather than the device. .. Warning:: The current implementation only supports the following C data types: ``long``, ``double`` and ``char*`` (strings). Thus, you can only use these three data types in format strings for printf, scanf and the like. :Call: buffer = sprintf(vi, write_format, ..., buffer_length = 1024) :VISA name: viSPrintf :Parameters: `vi` : integer Unique logical identifier to a session. `write_format` : string String describing the format for arguments. `...` : integers, floats, or strings Arguments sent to the buffer according to `write_format`. `buffer_length` : integer : keyword argument Length of the user-specified buffer in bytes. Defaults to 1024. :Return values: `buffer` : string Buffer where the formatted data was written to. sscanf ...... Same as `scanf`_, except that the data is read from a user-specified buffer instead of a device. .. Warning:: The current implementation only supports the following C data types: ``long``, ``double`` and ``char*`` (strings). Thus, you can only use these three data types in format strings for printf, scanf and the like. :Call: value1, value2, ... = sscanf(vi, buffer, read_format, ..., maximal_string_length = 1024) :VISA name: viSScanf :Parameters: `vi` : integer Unique logical identifier to a session. `buffer` : string Buffer from which data is read and formatted. `read_format` : string String describing the format for arguments. `...` : integers, floats, or strings Arguments to be read from the device according to `read_format`. It's totally insignificant which values they have, they serve just as a cheap way to determine what types are to be expected. So actually this argument list shouldn't be necessary, but with the current implementation, it is, sorry. These arguments may be (however needn't be) the same names used for storing the result values. Alternatively, you can give literals. `maximal_string_length` : integer : keyword argument The maximal length assumed for string result arguments. Note that string results must *never* exceed this length. It defaults to 1024. :Return values: `value1`, `value2`, ... : integers, floats, or strings Arguments read from the device according to `read_format`. Of course, this must be the same sequence (as far as data types are concerned) as the given argument list `...` above. status_description .................. Return a user-readable description of the status code passed to the operation. :Call: description = status_description(vi, status) :VISA name: viStatusDesc :Parameters: `vi` : integer, ViEvent, or ViFindList Unique logical identifier to a session. `status` : integer Status code to interpret. :Return values: `description` : string The user-readable string interpretation of the status code passed to the operation. terminate ......... Request a VISA session to terminate normal execution of an operation. :Call: terminate(vi, degree, job_id) :VISA name: viTerminate :Parameters: `vi` : integer Unique logical identifier to a session. `degree` : integer ``VI_NULL`` `job_id` : ViJobId Specifies an operation identifier. :Return values: None. uninstall_handler ................. Uninstall handlers for events. :Call: uninstall_handler(vi, event_type, handler, user_handle) :VISA name: viUninstallHandler :Parameters: `vi` : integer Unique logical identifier to a session. `event_type` : integer Logical event identifier. `handler` : callable Interpreted as a valid reference to a handler to be uninstalled by a client application. `user_handle` : ctypes type : optional A value specified by an application that can be used for identifying handlers uniquely in a session for an event. It *must* be the object returned by `install_handler`_. Consequently, it defaults to ``None``. :Return values: None. unlock ...... Relinquish a lock for the specified resource. :Call: unlock(vi) :VISA name: viUnlock :Parameters: `vi` : integer Unique logical identifier to a session. :Return values: None. unmap_address ............. Unmap memory space previously mapped by `map_address`_. :Call: unmap_address(vi) :VISA name: viUnmapAddress :Parameters: `vi` : integer Unique logical identifier to a session. :Return values: None. unmap_trigger ............. Undo a previous map from the specified trigger source line to the specified destination line. :Call: unmap_trigger(vi, trigger_source, trigger_destination) :VISA name: viUnmapTrigger :Parameters: `vi` : integer Unique logical identifier to a session. `trigger_source` : integer Source line used in previous map. `trigger_destination` : integer Destination line used in previous map. :Return values: None. usb_control_in .............. Request arbitrary data from the USB device on the control port. :Call: buffer = usb_control_in(vi, request_type_bitmap_field, request_id, request_value, index, length) :VISA name: viUsbControlIn :Parameters: `vi` : integer Unique logical identifier to a session. `request_type_bitmap_field` : integer Bitmap field for defining the USB control port request. The bitmap fields are as defined by the USB specification. The direction bit must be device-to-host. `request_id` : integer Request ID for this transfer. The meaning of this value depends on `request_type_bitmap_field`. `request_value` : integer Request value for this transfer. `index` : integer Specifies the interface or endpoint index number, depending on `request_type_bitmap_field`. `length` : integer : optional Number of data in bytes to request from the device during the Data stage. If this value is not given or 0, an empty string is returned. :Return values: `buffer` : string Actual data received from the device during the Data stage. If `length` is not given or 0, an empty string is returned. usb_control_out ............... Send arbitrary data to the USB device on the control port. :Call: usb_control_out(vi, request_type_bitmap_field, request_id, request_value, index, buffer) :VISA name: viUsbControlOut :Parameters: `vi` : integer Unique logical identifier to a session. `request_type_bitmap_field` : integer Bitmap field for defining the USB control port request. The bitmap fields are as defined by the USB specification. The direction bit must be host-to-device. `request_id` : integer Request ID for this transfer. The meaning of this value depends on `request_type_bitmap_field`. `request_value` : integer Request value for this transfer. `index` : integer Specifies the interface or endpoint index number, depending on `request_type_bitmap_field`. `buffer` : string : optional Actual data to send to the device during the Data stage. If not given, nothing is sent. :Return values: None. vprintf, vqueryf, vscanf, vsprintf, vsscanf ........................................... These variants make no sense in Python, so I realised them as mere aliases (just drop the "v"). vxi_command_query ................. Send the device a miscellaneous command or query and/or retrieve the response to a previous query. :Call: vxi_command_query(vi, mode, command) :VISA name: viVxiCommandQuery :Parameters: `vi` : integer Unique logical identifier to a session. `mode` : integer Specifies whether to issue a command and/or retrieve a response. `command` : integer The miscellaneous command to send. :Return values: `response` : integer The response retrieved from the device. If the mode specifies just sending a command, this parameter may be ``VI_NULL``. wait_on_event ............. Wait for an occurrence of the specified event for a given session. :Call: out_event_type, out_context = wait_on_event(vi, in_event_type, timeout) :VISA name: viWaitOnEvent :Parameters: `vi` : integer Unique logical identifier to a session. `in_event_type` : integer Logical identifier of the event(s) to wait for. `timeout` : integer Absolute time period in milliseconds that the resource shall wait for a specified event to occur before returning the time elapsed error. :Return values: `out_event_type` : integer Logical identifier of the event actually received. `out_context` : ViEvent A handle specifying the unique occurrence of an event. write ..... Write data to device synchronously. :Call: return_count = write(vi, buffer) :VISA name: viWrite :Parameters: `vi` : integer Unique logical identifier to a session. `buffer` : string Contains the data block to be sent to the device. :Return values: `return_count` : integer The number of bytes actually transferred. write_asynchronously .................... Write data to device asynchronously. :Call: job_id = write_asynchronously(vi, buffer) :VISA name: viWriteAsync :Parameters: `vi` : integer Unique logical identifier to a session. `buffer` : string Contains the data block to be sent to the device. :Return values: `job_id` : ViJobId The job identifier of this asynchronous write operation. write_from_file ............... Take data from a file and write it out synchronously. :Call: return_count = write_from_file(vi, filename, count) :VISA name: viWriteFromFile :Parameters: `vi` : integer Unique logical identifier to a session. `filename` : string Name of file from which data will be read. `count` : integer Maximal number of bytes to be written. :Return values: `return_count` : integer Number of bytes actually transferred. .. LocalWords: rst british vpp PyVISA ies dll Gregor Thalhammer ViSession atn .. LocalWords: viAssertIntrSignal viAssertTrigger PROT viAssertUtilSignal ren .. LocalWords: viBufRead viBufWrite viClear viClose ViEvent ViFindList HNDLR .. LocalWords: viDisableEvent viDiscardEvents viEnableEvent viFindNext gpib .. LocalWords: viFindRsrc viFlush viGetAttribute viGpibCommand ADDR ifc viIn .. LocalWords: viGpibControlATN viGpibControlREN viGpibPassControl ViHndlr .. LocalWords: viGpibSendIFC viInstallHandler viLock viMapAddress ViAddr TMO .. LocalWords: ViBusAddress viMapTrigger viMemAlloc viMemFree viMove ViJobId .. LocalWords: viMoveAsync viMoveIn viMoveOut viOpen viOpenDefaultRM viOut .. LocalWords: viParseRsrc unaliased viParseRsrcEx INSTR viPeek vipoke printf .. LocalWords: scanf viPrintf queryf viQueryf viRead viReadAsync stb viScanf .. LocalWords: viReadSTB viReadToFile viSetAttribute viSetBuf sprintf sscanf .. LocalWords: viSPrintf viSScanf viStatusDesc viTerminate viUninstallHandler .. LocalWords: viUnlock viUnmapAddress viUnmapTrigger usb viUsbControlIn vxi .. LocalWords: viUsbControlOut vprintf vqueryf vscanf vsprintf vsscanf IVI .. LocalWords: viVxiCommandQuery viWaitOnEvent viWrite viWriteAsync WINNT def .. LocalWords: viWriteFromFile FixMe VisaIOError TypeError ctypes Enthought .. LocalWords: VisaIOWarning UnknownHandler pyvisa PyVISA-1.4/doc/index.txt0000664000175000017500000001531711753674666014466 0ustar floflo00000000000000.. -*- mode: rst; coding: iso-8859-1; ispell-local-dictionary: "british"; -*- .. .. index.txt - The reST source code of PyVISA's homepage .. .. Copyright © 2005, 2006, 2007, 2008 .. Torsten Bronger , .. Gregor Thalhammer . .. .. This file is part of PyVISA. .. .. PyVISA is free software; you can redistribute it and/or modify it under .. the terms of the MIT licence: .. .. Permission is hereby granted, free of charge, to any person obtaining a .. copy of this software and associated documentation files (the "Software"), .. to deal in the Software without restriction, including without limitation .. the rights to use, copy, modify, merge, publish, distribute, sublicense, .. and/or sell copies of the Software, and to permit persons to whom the .. Software is furnished to do so, subject to the following conditions: .. .. The above copyright notice and this permission notice shall be included in .. all copies or substantial portions of the Software. .. .. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR .. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, .. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL .. THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER .. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING .. FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER .. DEALINGS IN THE SOFTWARE. .. ============================================== Python GPIB etc. support with PyVISA ============================================== ------------------------------------------------------- Controlling GPIB, RS232, and USB instruments ------------------------------------------------------- :Date: |today| :Author: Torsten Bronger :Maintainer: Florian Bauer PyVISA ======= The PyVISA package enables you to control all kinds of measurement equipment through various busses (GPIB, RS232, USB) with Python programs. As an example, reading self-identification from a Keithley Multimeter with GPIB number 12 is as easy as three lines of Python code:: import visa keithley = visa.instrument("GPIB::12") print keithley.ask("*IDN?") (That's the whole program; really!) It is tailored to work on both Windows and Linux, and with arbitrary adapters (e.g. National Instruments, Agilent, Tektronics, Stanford Research Systems). In order to achieve this, PyVISA relies on an external library file which is bundled with hardware and software of those vendors. (So only in rare cases you have to purchase it separately.) PyVISA implements convenient and Pythonic programming in two layers: 1. An object-oriented Python module has been created simply called ``visa``. It is the recommended way to use PyVISA. See the `PyVISA manual`_ for more information. 2. Additionally, there is the lower level module ``vpp43``, which directly calls the VISA functions from Python. See the `PyVISA low-level implementation`_ for more information. This is only for people who need full control or the official VISA functions for some reason. PyVISA is free open-source software. The `PyVISA project page`_ contains the bug tracker and the download area. Projects using PyVISA so far: * `pyvLab`_ -- program to control VISA-talking instruments .. _`pyvLab`: http://pyvlab.sourceforge.net/ General overview ================ The programming of measurement instruments can be real pain. There are many different protocols, sent over many different interfaces and bus systems (GPIB, RS232, USB). For every programming language you want to use, you have to find libraries that support both your device and its bus system. In order to ease this unfortunate situation, the VISA [#]_ specification was defined in the middle of the 90ies. Today VISA is implemented on all significant operating systems. A couple of vendors offer VISA libraries, partly with free download. These libraries work together with arbitrary peripherical devices, although they may be limited to certain interface devices, such as the vendor's GPIB card. .. [#] Virtual Instrument Software Architecture The VISA specification has explicit bindings to Visual Basic, C, and G (LabVIEW's graphical language). However, you can use VISA with any language capable of calling functions in a DLL. Python is such a language. VISA and Python =============== Python has a couple of features that make it very interesting for measurement controlling: * Python is an easy-to-learn scripting language with short development cycles. * It represents a high abstraction level [#]_, which perfectly blends with the abstraction level of measurement programs. * It has a very rich set of native libraries, including numerical and plotting modules for data analysis and visualisation. * A large set of books (in many languages) and on-line publications is available. * You can download it for free at http://www.python.org. .. [#] For example, you don't need to care about the underlying operating system with all its peculiarities. Links ===== * PyVISA itself: - the `PyVISA project page`_ with download area and bug tracker - the `PyVISA manual`_ - the `PyVISA low-level implementation`_ called ``vpp43`` * The original VISA docs: - `VISA specification`_ (scroll down to the end) - `VISA library specification`_ - `VISA specification for textual languages`_ * The very good VISA manuals from `National Instruments's VISA pages`_: - `NI-VISA User Manual`_ - `NI-VISA Programmer Reference Manual`_ - `NI-VISA help file`_ in HTML .. _`PyVISA manual`: http://pyvisa.sourceforge.net/pyvisa.html .. _`as PDF`: http://pyvisa.sourceforge.net/pyvisa.pdf .. _`PyVISA project page`: http://sourceforge.net/projects/pyvisa/ .. _`PyVISA low-level implementation`: http://pyvisa.sourceforge.net/vpp43.html .. _`VISA specification`: http://www.ivifoundation.org/Downloads/Specifications.htm .. _`VISA library specification`: http://www.ivifoundation.org/Downloads/Class%20Specifications/vpp43.doc .. _`VISA specification for textual languages`: http://www.ivifoundation.org/Downloads/Class%20Specifications/vpp432.doc .. _`National Instruments's VISA pages`: http://ni.com/visa/ .. _`NI-VISA Programmer Reference Manual`: http://digital.ni.com/manuals.nsf/websearch/87E52268CF9ACCEE86256D0F006E860D .. _`NI-VISA help file`: http://digital.ni.com/manuals.nsf/websearch/21992F3750B967ED86256F47007B00B3 .. _`NI-VISA User Manual`: http://digital.ni.com/manuals.nsf/websearch/266526277DFF74F786256ADC0065C50C .. LocalWords: rst british reST ies vpp pyvisa docs pyvLab PyVISA-1.4/doc/.cvsignore0000644000175000017500000000020211734647056014567 0ustar floflo00000000000000*.aux *.log *.out *.dvi *.idx *.pla *.syn *.toc *.ilg *.ind vpp43.html vpp43.pdf vpp43.tex index.html pyvisa pyvisa.pdf pyvisa.ps PyVISA-1.4/doc/make.bat0000644000175000017500000000615611734647056014212 0ustar floflo00000000000000@ECHO OFF REM Command file for Sphinx documentation set SPHINXBUILD=sphinx-build set BUILDDIR=_build set ALLSPHINXOPTS=-d %BUILDDIR%/doctrees %SPHINXOPTS% . if NOT "%PAPER%" == "" ( set ALLSPHINXOPTS=-D latex_paper_size=%PAPER% %ALLSPHINXOPTS% ) if "%1" == "" goto help if "%1" == "help" ( :help echo.Please use `make ^` where ^ is one of echo. html to make standalone HTML files echo. dirhtml to make HTML files named index.html in directories echo. pickle to make pickle files echo. json to make JSON files echo. htmlhelp to make HTML files and a HTML help project echo. qthelp to make HTML files and a qthelp project echo. latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter echo. changes to make an overview over all changed/added/deprecated items echo. linkcheck to check all external links for integrity echo. doctest to run all doctests embedded in the documentation if enabled goto end ) if "%1" == "clean" ( for /d %%i in (%BUILDDIR%\*) do rmdir /q /s %%i del /q /s %BUILDDIR%\* goto end ) if "%1" == "html" ( %SPHINXBUILD% -b html %ALLSPHINXOPTS% %BUILDDIR%/html echo. echo.Build finished. The HTML pages are in %BUILDDIR%/html. goto end ) if "%1" == "dirhtml" ( %SPHINXBUILD% -b dirhtml %ALLSPHINXOPTS% %BUILDDIR%/dirhtml echo. echo.Build finished. The HTML pages are in %BUILDDIR%/dirhtml. goto end ) if "%1" == "pickle" ( %SPHINXBUILD% -b pickle %ALLSPHINXOPTS% %BUILDDIR%/pickle echo. echo.Build finished; now you can process the pickle files. goto end ) if "%1" == "json" ( %SPHINXBUILD% -b json %ALLSPHINXOPTS% %BUILDDIR%/json echo. echo.Build finished; now you can process the JSON files. goto end ) if "%1" == "htmlhelp" ( %SPHINXBUILD% -b htmlhelp %ALLSPHINXOPTS% %BUILDDIR%/htmlhelp echo. echo.Build finished; now you can run HTML Help Workshop with the ^ .hhp project file in %BUILDDIR%/htmlhelp. goto end ) if "%1" == "qthelp" ( %SPHINXBUILD% -b qthelp %ALLSPHINXOPTS% %BUILDDIR%/qthelp echo. echo.Build finished; now you can run "qcollectiongenerator" with the ^ .qhcp project file in %BUILDDIR%/qthelp, like this: echo.^> qcollectiongenerator %BUILDDIR%\qthelp\usbio.qhcp echo.To view the help file: echo.^> assistant -collectionFile %BUILDDIR%\qthelp\usbio.ghc goto end ) if "%1" == "latex" ( %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex echo. echo.Build finished; the LaTeX files are in %BUILDDIR%/latex. goto end ) if "%1" == "changes" ( %SPHINXBUILD% -b changes %ALLSPHINXOPTS% %BUILDDIR%/changes echo. echo.The overview file is in %BUILDDIR%/changes. goto end ) if "%1" == "linkcheck" ( %SPHINXBUILD% -b linkcheck %ALLSPHINXOPTS% %BUILDDIR%/linkcheck echo. echo.Link check complete; look for any errors in the above output ^ or in %BUILDDIR%/linkcheck/output.txt. goto end ) if "%1" == "doctest" ( %SPHINXBUILD% -b doctest %ALLSPHINXOPTS% %BUILDDIR%/doctest echo. echo.Testing of doctests in the sources finished, look at the ^ results in %BUILDDIR%/doctest/output.txt. goto end ) :end PyVISA-1.4/test/0000775000175000017500000000000011754013232012772 5ustar floflo00000000000000PyVISA-1.4/test/test_visa_attributes.py0000664000175000017500000000042211753475165017631 0ustar floflo00000000000000from __future__ import print_function from pyvisa import visa_attributes def test_attributes(): for value, info in visa_attributes.attributes.items(): assert value == info.attribute_value assert info.attribute_name != '' assert repr(info) != '' PyVISA-1.4/test/test_keithley2000.py0000644000175000017500000000372211753410506016531 0ustar floflo00000000000000#!/usr/bin/env python # -*- coding: utf-8 -*- # # test_keithley2000.py - PyVISA test code for Keithley 2000 multimeter # # Copyright © 2005, 2006, 2007, 2008 # Torsten Bronger , # Gregor Thalhammer . # # This file is part of PyVISA. # # PyVISA is free software; you can redistribute it and/or modify it under # the terms of the MIT licence: # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the "Software"), # to deal in the Software without restriction, including without limitation # the rights to use, copy, modify, merge, publish, distribute, sublicense, # and/or sell copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER # DEALINGS IN THE SOFTWARE. # from __future__ import print_function from visa import * def test_keithley2000(): print("Test start") keithley = GpibInstrument(12) milliseconds = 500 number_of_values = 10 keithley.write("F0B2M2G0T2Q%dI%dX" % (milliseconds, number_of_values)) keithley.trigger() keithley.wait_for_srq() voltages = keithley.read_floats() print("Average: ", sum(voltages) / len(voltages)) print("Test end") PyVISA-1.4/test/conftest.py0000664000175000017500000000016411753471102015175 0ustar floflo00000000000000import os from mock import Mock import ctypes ctypes.cdll = Mock() if os.name == 'nt': ctypes.windll = Mock() PyVISA-1.4/test/test_itc4.py0000644000175000017500000000341111753474440015256 0ustar floflo00000000000000#!/usr/bin/env python # -*- coding: utf-8 -*- # # test_itc4.py - PyVISA test code for Oxfort ITC4 temperature controller # # Copyright © 2005, 2006, 2007, 2008 # Torsten Bronger , # Gregor Thalhammer . # # This file is part of PyVISA. # # PyVISA is free software; you can redistribute it and/or modify it under # the terms of the MIT licence: # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the "Software"), # to deal in the Software without restriction, including without limitation # the rights to use, copy, modify, merge, publish, distribute, sublicense, # and/or sell copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER # DEALINGS IN THE SOFTWARE. # from __future__ import print_function from visa import * def test_itc4(): print("Test start") itc4 = Instrument("COM2", term_chars = b"\r", timeout = 5) itc4.write("V") print(itc4.read()) print("Test end") PyVISA-1.4/setup.cfg0000644000175000017500000000046611754013232013640 0ustar floflo00000000000000[bdist_rpm] release = 1 provides = pyvisa requires = python doc_files = README ChangeLog doc/pyvisa.pdf doc/pyvisa/ doc/vpp43.html doc/index.html doc/default.css [install] [egg_info] tag_build = tag_date = 0 tag_svn_revision = 0 [build_sphinx] source-dir = doc/ build-dir = doc/_build all_files = 1 PyVISA-1.4/src/0000775000175000017500000000000011754013232012602 5ustar floflo00000000000000PyVISA-1.4/src/visa.py0000664000175000017500000007767611753473050014154 0ustar floflo00000000000000#!/usr/bin/env python # -*- coding: utf-8 -*- # # visa.py - High-level object-oriented VISA implementation # # Copyright © 2005, 2006, 2007, 2008 # Torsten Bronger , # Gregor Thalhammer . # # This file is part of PyVISA. # # PyVISA is free software; you can redistribute it and/or modify it under # the terms of the MIT licence: # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the "Software"), # to deal in the Software without restriction, including without limitation # the rights to use, copy, modify, merge, publish, distribute, sublicense, # and/or sell copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER # DEALINGS IN THE SOFTWARE. # """Top-level module of PyVISA with object-oriented layer on top of the original VISA functions (in vpp43.py). See http://pyvisa.sourceforge.net/pyvisa/ for details. Exported functions: get_instruments_list() -- return a list with all found instruments instrument() -- factory function for creating instrument instances Exported classes: ResourceTemplate -- abstract base class of the VISA implementation ResourceManager -- singleton class for the default resource manager Instrument -- generic class for all kinds of Instruments GpibInstrument -- class for GPIB instruments SerialInstrument -- class for serial (COM, LPT) instruments Interface -- base class for GPIB interfaces (rather than instruments) Gpib -- class for GPIB interfaces (rather than instruments) Exported variables: resource_manager -- the single instance of ResourceManager. """ __version__ = "$Revision: 344 $" # $Source$ import vpp43 from vpp43_constants import * from visa_exceptions import * import re, time, warnings, atexit, struct def _removefilter(action, message="", category=Warning, module="", lineno=0, append=0): """Remove all entries from the list of warnings filters that match the given filter. It is the opposite to warnings.filterwarnings() and has the same parameters as it.""" import re item = (action, re.compile(message, re.I), category, re.compile(module), lineno) new_filters = [] for filter in warnings.filters: equal = 1 for j in xrange(len(item)): if item[j] != filter[j]: equal = 0 break if not equal: new_filters.append(filter) if len(warnings.filters) == len(new_filters): warnings.warn("Warning filter not found", stacklevel=2) warnings.filters = new_filters def _warn_for_invalid_keyword_arguments(keyw, allowed_keys): for key in keyw.iterkeys(): if key not in allowed_keys: warnings.warn("Keyword argument \"%s\" unknown" % key, stacklevel = 3) def _filter_keyword_arguments(keyw, selected_keys): result = {} for key, value in keyw.iteritems(): if key in selected_keys: result[key] = value return result class ResourceTemplate(object): """The abstract base class of the VISA implementation. It covers life-cycle services: opening and closing of vi's. Don't instantiate it! """ import vpp43 as _vpp43 # Needed for finishing the object safely. vi = None """VISA handle of the resource""" def __init__(self, resource_name=None, **keyw): """ResourceTemplate class constructor. It opens a session to the resource. Parameters: resource_name -- (optional) the VISA name for the resource, e.g. "GPIB::10". If "None", it's assumed that the resource manager is to be constructed. keyw -- keyword argument for the class constructor of the device instance to be generated. Allowed arguments: lock, timeout. See Instrument class for a detailed description. """ _warn_for_invalid_keyword_arguments(keyw, ("lock", "timeout")) if self.__class__ is ResourceTemplate: raise TypeError, "trying to instantiate an abstract class" if resource_name is not None: # is none for the resource manager warnings.filterwarnings("ignore", "VI_SUCCESS_DEV_NPRESENT") self.vi = vpp43.open(resource_manager.session, resource_name, keyw.get("lock", VI_NO_LOCK)) if vpp43.get_status() == VI_SUCCESS_DEV_NPRESENT: # okay, the device was not ready when we opened the session. # Now it gets five seconds more to become ready. Every 0.1 # seconds we probe it with viClear. passed_time = 0 # in seconds while passed_time < 5.0: time.sleep(0.1) passed_time += 0.1 try: vpp43.clear(self.vi) except VisaIOError, error: if error.error_code == VI_ERROR_NLISTENERS: continue else: raise break else: # Very last chance, this time without exception handling time.sleep(0.1) passed_time += 0.1 vpp43.clear(self.vi) _removefilter("ignore", "VI_SUCCESS_DEV_NPRESENT") timeout = keyw.get("timeout", 5) if timeout is None: vpp43.set_attribute(self.vi, VI_ATTR_TMO_VALUE, VI_TMO_INFINITE) else: self.timeout = timeout def __del__(self): self.close() def __set_timeout(self, timeout): if not(0 <= timeout <= 4294967): raise ValueError, "timeout value is invalid" vpp43.set_attribute(self.vi, VI_ATTR_TMO_VALUE, int(timeout * 1000)) def __get_timeout(self): timeout = vpp43.get_attribute(self.vi, VI_ATTR_TMO_VALUE) if timeout == VI_TMO_INFINITE: raise NameError, "no timeout is specified" return timeout / 1000.0 def __del_timeout(self): timeout = self.__get_timeout() # just to test whether it's defined vpp43.set_attribute(self.vi, VI_ATTR_TMO_VALUE, VI_TMO_INFINITE) timeout = property(__get_timeout, __set_timeout, __del_timeout, """The timeout in seconds for all resource I/O operations. Note that the VISA library may round up this value heavily. I experienced that my NI VISA implementation had only the values 0, 1, 3 and 10 seconds. """) def __get_resource_class(self): try: resource_class = \ vpp43.get_attribute(self.vi, VI_ATTR_RSRC_CLASS).upper() except VisaIOError, error: if error.error_code == VI_ERROR_NSUP_ATTR: return None else: raise return resource_class resource_class = property(__get_resource_class, None, None, """The resource class of the resource as a string.""") def __get_resource_name(self): return vpp43.get_attribute(self.vi, VI_ATTR_RSRC_NAME) resource_name = property(__get_resource_name, None, None, """The VISA resource name of the resource as a string.""") def __get_interface_type(self): interface_type, _ = \ vpp43.parse_resource(resource_manager.session, self.resource_name) return interface_type interface_type = property(__get_interface_type, None, None, """The interface type of the resource as a number.""") def close(self): """Closes the VISA session and marks the handle as invalid. This method can be called to ensure that all resources are freed. Finishing the object by __del__ seems to work safely enough though. """ if self.vi is not None: self._vpp43.close(self.vi) self.vi = None class ResourceManager(vpp43.Singleton, ResourceTemplate): """Singleton class for the default resource manager.""" def init(self): """Singleton class constructor. See vpp43.Singleton for details. """ ResourceTemplate.__init__(self) # I have "session" as an alias because the specification calls the "vi" # handle "session" for the resource manager. self.session = self.vi = vpp43.open_default_resource_manager() def __repr__(self): return "ResourceManager()" resource_manager = ResourceManager() """The global resource manager instance. Exactly one is needed.""" def _destroy_resource_manager(): # delete self-reference for clean finishing del ResourceManager.__it__ atexit.register(_destroy_resource_manager) def get_instruments_list(use_aliases=True): """Get a list of all connected devices. Parameters: use_aliases -- if True, return an alias name for the device if it has one. Otherwise, always return the standard resource name like "GPIB::10". Return value: A list of strings with the names of all connected devices, ready for being used to open each of them. """ # Phase I: Get all standard resource names (no aliases here) resource_names = [] find_list, return_counter, instrument_description = \ vpp43.find_resources(resource_manager.session, "?*::INSTR") resource_names.append(instrument_description) for i in xrange(return_counter - 1): resource_names.append(vpp43.find_next(find_list)) # Phase two: If available and use_aliases is True, substitute the alias. # Otherwise, truncate the "::INSTR". result = [] for resource_name in resource_names: try: _, _, _, _, alias_if_exists = \ vpp43.parse_resource_extended(resource_manager.session, resource_name) except AttributeError: alias_if_exists = None if alias_if_exists and use_aliases: result.append(alias_if_exists) else: result.append(resource_name[:-7]) return result def instrument(resource_name, **keyw): """Factory function for instrument instances. Parameters: resource_name -- the VISA resource name of the device. It may be an alias. keyw -- keyword argument for the class constructor of the device instance to be generated. See the class Instrument for further information. Return value: The generated instrument instance. """ interface_type, _ = \ vpp43.parse_resource(resource_manager.session, resource_name) if interface_type == VI_INTF_GPIB: return GpibInstrument(resource_name, **keyw) elif interface_type == VI_INTF_ASRL: return SerialInstrument(resource_name, **keyw) else: return Instrument(resource_name, **keyw) # The bits in the bitfield mean the following: # # bit number if set / if not set # 0 binary/ascii # 1 double/single (IEEE floating point) # 2 big-endian/little-endian # # This leads to the following constants: ascii = 0 single = 1 double = 3 big_endian = 4 CR = b"\r" LF = b"\n" class Instrument(ResourceTemplate): """Class for all kinds of Instruments. It can be instantiated, however, if you want to use special features of a certain interface system (GPIB, USB, RS232, etc), you must instantiate one of its child classes. """ chunk_size = 20*1024 """How many bytes are read per low-level call""" __term_chars = None """Termination character sequence. See below.""" delay = 0.0 """Seconds to wait after each high-level write""" values_format = ascii """floating point data value format""" def __init__(self, resource_name, **keyw): """Constructor method. Parameters: resource_name -- the instrument's resource name or an alias, may be taken from the list from get_instruments_list(). Keyword arguments: timeout -- the VISA timeout for each low-level operation in milliseconds. term_chars -- the termination characters for this device, see description of class property "term_chars". chunk_size -- size of data packets in bytes that are read from the device. lock -- whether you want to have exclusive access to the device. Default: VI_NO_LOCK delay -- waiting time in seconds after each write command. Default: 0 send_end -- whether to assert end line after each write command. Default: True values_format -- floating point data value format. Default: ascii (0) """ _warn_for_invalid_keyword_arguments(keyw, ("timeout", "term_chars", "chunk_size", "lock", "delay", "send_end", "values_format")) ResourceTemplate.__init__(self, resource_name, **_filter_keyword_arguments(keyw, ("timeout", "lock"))) self.term_chars = keyw.get("term_chars") self.chunk_size = keyw.get("chunk_size", self.chunk_size) self.delay = keyw.get("delay", 0.0) self.send_end = keyw.get("send_end", True) self.values_format = keyw.get("values_format", self.values_format) # I validate the resource class by requesting it from the instrument if not self.resource_class: warnings.warn("resource class of instrument could not be determined", stacklevel=2) # FixMe: RAW and SOCKET should be moved in own classes eventually elif self.resource_class not in ("INSTR", "RAW", "SOCKET"): warnings.warn("given resource was not an INSTR but %s" % self.resource_class, stacklevel=2) def __repr__(self): return "Instrument(\"%s\")" % self.resource_name def write(self, message): """Write a string message to the device. Parameters: message -- the string message to be sent. The term_chars are appended to it, unless they are already. """ if self.__term_chars and not message.endswith(self.__term_chars): message += self.__term_chars elif self.__term_chars is None and not message.endswith(CR+LF): message += CR+LF vpp43.write(self.vi, message) if self.delay > 0.0: time.sleep(self.delay) def _strip_term_chars(self, buffer): if self.__term_chars: if buffer.endswith(self.__term_chars): buffer = buffer[:-len(self.__term_chars)] else: warnings.warn("read string doesn't end with " "termination characters", stacklevel=2) return buffer.rstrip(CR+LF) def read_raw(self): """Read the unmodified string sent from the instrument to the computer. In contrast to read(), no termination characters are checked or stripped. You get the pristine message. """ warnings.filterwarnings("ignore", "VI_SUCCESS_MAX_CNT") try: buffer = b"" chunk = vpp43.read(self.vi, self.chunk_size) buffer += chunk while vpp43.get_status() == VI_SUCCESS_MAX_CNT: chunk = vpp43.read(self.vi, self.chunk_size) buffer += chunk finally: _removefilter("ignore", "VI_SUCCESS_MAX_CNT") return buffer def read(self): """Read a string from the device. Reading stops when the device stops sending (e.g. by setting appropriate bus lines), or the termination characters sequence was detected. Attention: Only the last character of the termination characters is really used to stop reading, however, the whole sequence is compared to the ending of the read string message. If they don't match, a warning is issued. All line-ending characters are stripped from the end of the string. Parameters: None Return value: The string read from the device. """ return self._strip_term_chars(self.read_raw()) def read_values(self, format=None): """Read a list of floating point values from the device. Parameters: format -- (optional) the format of the values. If given, it overrides the class attribute "values_format". Possible values are bitwise disjunctions of the above constants ascii, single, double, and big_endian. Default is ascii. Return value: The list with the read values. """ if not format: format = self.values_format if format & 0x01 == ascii: float_regex = re.compile(r"[-+]?(?:\d+(?:\.\d*)?|\d*\.\d+)" "(?:[eE][-+]?\d+)?") return [float(raw_value) for raw_value in float_regex.findall(self.read())] # Okay, we need to read binary data original_term_chars = self.term_chars self.term_chars = b"" try: data = self.read_raw() finally: self.term_chars = original_term_chars hash_sign_position = data.find("#") if hash_sign_position == -1 or len(data) - hash_sign_position < 2: raise InvalidBinaryFormat if hash_sign_position > 0: data = data[hash_sign_position:] if data[1].isdigit() and int(data[1]) > 0: number_of_digits = int(data[1]) # I store data and data_length in two separate variables in case # that data is too short. FixMe: Maybe I should raise an error if # it's too long and the trailing part is not just CR/LF. data_length = int(data[2:2+number_of_digits]) data = data[2+number_of_digits:2+number_of_digits + data_length] elif data[1] == "0" and data[-1] == "\n": data = data[2:-1] data_length = len(data) else: raise InvalidBinaryFormat if format & 0x04 == big_endian: endianess = ">" else: endianess = "<" try: if format & 0x03 == single: result = list(struct.unpack(endianess + str(data_length/4) + "f", data)) elif format & 0x03 == double: result = list(struct.unpack(endianess + str(data_length/8) + "d", data)) else: raise ValueError, "unknown data values format requested" except struct.error: raise InvalidBinaryFormat, "binary data itself was malformed" return result def read_floats(self): """This method is deprecated. Use read_values() instead.""" warnings.warn("read_floats() is deprecated. Use read_values()", stacklevel=2) return self.read_values(format=ascii) def ask(self, message): """A combination of write(message) and read()""" self.write(message) return self.read() def ask_for_values(self, message, format=None): """A combination of write(message) and read_values()""" self.write(message) return self.read_values(format) def clear(self): """Resets the device. This operation is highly bus-dependent.""" vpp43.clear(self.vi) def trigger(self): """Sends a software trigger to the device.""" vpp43.set_attribute(self.vi, VI_ATTR_TRIG_ID, VI_TRIG_SW) vpp43.assert_trigger(self.vi, VI_TRIG_PROT_DEFAULT) def __set_term_chars(self, term_chars): """Set a new termination character sequence. See below the property "term_char".""" # First, reset termination characters, in case something bad happens. self.__term_chars = b"" vpp43.set_attribute(self.vi, VI_ATTR_TERMCHAR_EN, VI_FALSE) if term_chars == b"" or term_chars == None: self.__term_chars = term_chars return # Only the last character in term_chars is the real low-level # termination character, the rest is just used for verification after # each read operation. last_char = term_chars[-1] # Consequently, it's illogical to have the real termination character # twice in the sequence (otherwise reading would stop prematurely). if term_chars[:-1].find(last_char) != -1: raise ValueError, "ambiguous ending in termination characters" vpp43.set_attribute(self.vi, VI_ATTR_TERMCHAR, ord(last_char)) vpp43.set_attribute(self.vi, VI_ATTR_TERMCHAR_EN, VI_TRUE) self.__term_chars = term_chars def __get_term_chars(self): """Return the current termination characters for the device.""" return self.__term_chars def __del_term_chars(self): self.term_chars = None term_chars = property(__get_term_chars, __set_term_chars, __del_term_chars, r"""Set or read a new termination character sequence (property). Normally, you just give the new termination sequence, which is appended to each write operation (unless it's already there), and expected as the ending mark during each read operation. A typical example is CR+LF or just CR. If you assign "" to this property, the termination sequence is deleted. The default is None, which means that CR is appended to each write operation but not expected after each read operation (but stripped if present). """) def __set_send_end(self, send): if send: vpp43.set_attribute(self.vi, VI_ATTR_SEND_END_EN, VI_TRUE) else: vpp43.set_attribute(self.vi, VI_ATTR_SEND_END_EN, VI_FALSE) def __get_send_end(self): return vpp43.get_attribute(self.vi, VI_ATTR_SEND_END_EN) == VI_TRUE send_end = property(__get_send_end, __set_send_end, None, """Whether or not to assert EOI (or something equivalent after each write operation. """) class GpibInstrument(Instrument): """Class for GPIB instruments. This class extents the Instrument class with special operations and properties of GPIB instruments. """ def __init__(self, gpib_identifier, board_number=0, **keyw): """Class constructor. parameters: gpib_identifier -- if it's a string, it is interpreted as the instrument's VISA resource name. If it's a number, it's the instrument's GPIB number. board_number -- (default: 0) the number of the GPIB bus. Further keyword arguments are passed to the constructor of class Instrument. """ _warn_for_invalid_keyword_arguments(keyw, ("timeout", "term_chars", "chunk_size", "lock", "delay", "send_end", "values_format")) if isinstance(gpib_identifier, int): resource_name = "GPIB%d::%d" % (board_number, gpib_identifier) else: resource_name = gpib_identifier Instrument.__init__(self, resource_name, **keyw) # Now check whether the instrument is really valid if self.interface_type != VI_INTF_GPIB: raise ValueError, "device is not a GPIB instrument" vpp43.enable_event(self.vi, VI_EVENT_SERVICE_REQ, VI_QUEUE) def __del__(self): if self.vi is not None: self.__switch_events_off() Instrument.__del__(self) def __repr__(self): return "GpibInstrument(\"%s\")" % self.resource_name def __switch_events_off(self): self._vpp43.disable_event(self.vi, VI_ALL_ENABLED_EVENTS, VI_ALL_MECH) self._vpp43.discard_events(self.vi, VI_ALL_ENABLED_EVENTS, VI_ALL_MECH) def wait_for_srq(self, timeout=25): """Wait for a serial request (SRQ) coming from the instrument. Note that this method is not ended when *another* instrument signals an SRQ, only *this* instrument. Parameters: timeout -- (optional) the maximal waiting time in seconds. The default value is 25 (seconds). "None" means waiting forever if necessary. """ vpp43.enable_event(self.vi, VI_EVENT_SERVICE_REQ, VI_QUEUE) if timeout and not(0 <= timeout <= 4294967): raise ValueError, "timeout value is invalid" starting_time = time.clock() while True: if timeout is None: adjusted_timeout = VI_TMO_INFINITE else: adjusted_timeout = int((starting_time + timeout - time.clock()) * 1000) if adjusted_timeout < 0: adjusted_timeout = 0 event_type, context = \ vpp43.wait_on_event(self.vi, VI_EVENT_SERVICE_REQ, adjusted_timeout) vpp43.close(context) if self.stb & 0x40: break vpp43.discard_events(self.vi, VI_EVENT_SERVICE_REQ, VI_QUEUE) def __get_stb(self): return vpp43.read_stb(self.vi) stb = property(__get_stb, None, None, """Service request status register.""") # The following aliases are used for the "end_input" property no_end_input = VI_ASRL_END_NONE last_bit_end_input = VI_ASRL_END_LAST_BIT term_chars_end_input = VI_ASRL_END_TERMCHAR # The following aliases are used for the "parity" property no_parity = VI_ASRL_PAR_NONE odd_parity = VI_ASRL_PAR_ODD even_parity = VI_ASRL_PAR_EVEN mark_parity = VI_ASRL_PAR_MARK space_parity = VI_ASRL_PAR_SPACE class SerialInstrument(Instrument): """Class for serial (RS232 or parallel port) instruments. Not USB! This class extents the Instrument class with special operations and properties of serial instruments. """ def __init__(self, resource_name, **keyw): """Class constructor. parameters: resource_name -- the instrument's resource name or an alias, may be taken from the list from get_instruments_list(). Further keyword arguments are passed to the constructor of class Instrument. """ _warn_for_invalid_keyword_arguments(keyw, ("timeout", "term_chars", "chunk_size", "lock", "delay", "send_end", "values_format", "baud_rate", "data_bits", "end_input", "parity", "stop_bits")) keyw.setdefault("term_chars", CR) Instrument.__init__(self, resource_name, **_filter_keyword_arguments(keyw, ("timeout", "term_chars", "chunk_size", "lock", "delay", "send_end", "values_format"))) # Now check whether the instrument is really valid if self.interface_type != VI_INTF_ASRL: raise ValueError, "device is not a serial instrument" self.baud_rate = keyw.get("baud_rate", 9600) self.data_bits = keyw.get("data_bits", 8) self.stop_bits = keyw.get("stop_bits", 1) self.parity = keyw.get("parity", no_parity) self.end_input = keyw.get("end_input", term_chars_end_input) def __get_baud_rate(self): return vpp43.get_attribute(self.vi, VI_ATTR_ASRL_BAUD) def __set_baud_rate(self, rate): vpp43.set_attribute(self.vi, VI_ATTR_ASRL_BAUD, rate) baud_rate = property(__get_baud_rate, __set_baud_rate, None, """Baud rate of the serial instrument""") def __get_data_bits(self): return vpp43.get_attribute(self.vi, VI_ATTR_ASRL_DATA_BITS) def __set_data_bits(self, bits): if not 5 <= bits <= 8: raise ValueError, "number of data bits must be from 5 to 8" vpp43.set_attribute(self.vi, VI_ATTR_ASRL_DATA_BITS, bits) data_bits = property(__get_data_bits, __set_data_bits, None, """Number of data bits contained in each frame """ """(from 5 to 8)""") def __get_stop_bits(self): deci_bits = vpp43.get_attribute(self.vi, VI_ATTR_ASRL_STOP_BITS) if deci_bits == 10: return 1 elif deci_bits == 15: return 1.5 elif deci_bits == 20: return 2 def __set_stop_bits(self, bits): deci_bits = 10 * bits if 9 < deci_bits < 11: deci_bits = 10 elif 14 < deci_bits < 16: deci_bits = 15 elif 19 < deci_bits < 21: deci_bits = 20 else: raise ValueError, "invalid number of stop bits" vpp43.set_attribute(self.vi, VI_ATTR_ASRL_STOP_BITS, deci_bits) stop_bits = property(__get_stop_bits, __set_stop_bits, None, """Number of stop bits contained in each frame """ """(1, 1.5, or 2)""") def __get_parity(self): return vpp43.get_attribute(self.vi, VI_ATTR_ASRL_PARITY) def __set_parity(self, parity): vpp43.set_attribute(self.vi, VI_ATTR_ASRL_PARITY, parity) parity = property(__get_parity, __set_parity, None, """The parity used with every frame transmitted """ """and received""") def __get_end_input(self): return vpp43.get_attribute(self.vi, VI_ATTR_ASRL_END_IN) def __set_end_input(self, termination): vpp43.set_attribute(self.vi, VI_ATTR_ASRL_END_IN, termination) end_input = property(__get_end_input, __set_end_input, None, """indicates the method used to terminate read operations""") class Interface(ResourceTemplate): """Base class for GPIB interfaces. You may wonder why this exists since the only child class is Gpib(). I don't know either, but the VISA specification says that there are attributes that only "interfaces that support GPIB" have and other that "all" have. FixMe: However, maybe it's better to merge both classes. In any case you should not instantiate this class.""" def __init__(self, interface_name): """Class constructor. Parameters: interface_name -- VISA resource name of the interface. May be "GPIB0" or "GPIB1::INTFC". """ ResourceTemplate.__init__(self, interface_name) # I validate the resource class by requesting it from the interface if self.resource_class != "INTFC": warnings.warn("resource is not an INTFC but %s" % self.resource_class, stacklevel=2) def __repr__(self): return "Interface(\"%s\")" % self.resource_name class Gpib(Interface): """Class for GPIB interfaces (rather than instruments).""" def __init__(self, board_number=0): """Class constructor. Parameters: board_number -- integer denoting the number of the GPIB board, defaults to 0. """ Interface.__init__(self, "GPIB" + str(board_number)) self.board_number = board_number def __repr__(self): return "Gpib(%d)" % self.board_number def send_ifc(self): """Send "interface clear" signal to the GPIB.""" vpp43.gpib_send_ifc(self.vi) def _test_pyvisa(): print "Test start" keithley = GpibInstrument(12) milliseconds = 500 number_of_values = 10 keithley.write("F0B2M2G0T2Q%dI%dX" % (milliseconds, number_of_values)) keithley.trigger() keithley.wait_for_srq() voltages = keithley.read_values() print "Average: ", sum(voltages) / len(voltages) print "Test end" if __name__ == '__main__': _test_pyvisa() PyVISA-1.4/src/vpp43_constants.py0000644000175000017500000004456511734647057016260 0ustar floflo00000000000000#!/usr/bin/env python # -*- coding: utf-8 -*- # # vpp43_constants.py - VISA VPP-4.3 constants (VPP-4.3.2 spec, section 3) # # Copyright © 2005, 2006, 2007, 2008 # Torsten Bronger , # Gregor Thalhammer . # # This file is part of PyVISA. # # PyVISA is free software; you can redistribute it and/or modify it under # the terms of the MIT licence: # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the "Software"), # to deal in the Software without restriction, including without limitation # the rights to use, copy, modify, merge, publish, distribute, sublicense, # and/or sell copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER # DEALINGS IN THE SOFTWARE. # """Makes all "completion and error codes", "attribute values", "event type values", and "values and ranges" defined in the VISA specification VPP-4.3.2, section 3, available as variable values. The module exports the values under the original, all-uppercase names. """ __version__ = "$Revision: 334 $" # $Source$ # _to_int() is necessary because the VISA specification is flawed: It defines # the VISA codes, which have a value less than zero, in their internal 32-bit # signed integer representation. However, this is positive. ctypes doesn't # care about that and (correctly) returns the negative value, which is left as # such by Python. # def _to_int(x): """Converts a completion and error code as it is listed in 32-bit notation in the VPP-4.3.2 specification to the actual integer value. """ if x > 0x7FFFFFFFL: return int(x - 0x100000000L) else: return int(x) VI_SUCCESS = _to_int(0x00000000L) VI_SUCCESS_EVENT_EN = _to_int(0x3FFF0002L) VI_SUCCESS_EVENT_DIS = _to_int(0x3FFF0003L) VI_SUCCESS_QUEUE_EMPTY = _to_int(0x3FFF0004L) VI_SUCCESS_TERM_CHAR = _to_int(0x3FFF0005L) VI_SUCCESS_MAX_CNT = _to_int(0x3FFF0006L) VI_SUCCESS_DEV_NPRESENT = _to_int(0x3FFF007DL) VI_SUCCESS_TRIG_MAPPED = _to_int(0x3FFF007EL) VI_SUCCESS_QUEUE_NEMPTY = _to_int(0x3FFF0080L) VI_SUCCESS_NCHAIN = _to_int(0x3FFF0098L) VI_SUCCESS_NESTED_SHARED = _to_int(0x3FFF0099L) VI_SUCCESS_NESTED_EXCLUSIVE = _to_int(0x3FFF009AL) VI_SUCCESS_SYNC = _to_int(0x3FFF009BL) VI_WARN_QUEUE_OVERFLOW = _to_int(0x3FFF000CL) VI_WARN_CONFIG_NLOADED = _to_int(0x3FFF0077L) VI_WARN_NULL_OBJECT = _to_int(0x3FFF0082L) VI_WARN_NSUP_ATTR_STATE = _to_int(0x3FFF0084L) VI_WARN_UNKNOWN_STATUS = _to_int(0x3FFF0085L) VI_WARN_NSUP_BUF = _to_int(0x3FFF0088L) # The following one is a non-standard NI extension VI_WARN_EXT_FUNC_NIMPL = _to_int(0x3FFF00A9L) VI_ERROR_SYSTEM_ERROR = _to_int(0xBFFF0000L) VI_ERROR_INV_OBJECT = _to_int(0xBFFF000EL) VI_ERROR_RSRC_LOCKED = _to_int(0xBFFF000FL) VI_ERROR_INV_EXPR = _to_int(0xBFFF0010L) VI_ERROR_RSRC_NFOUND = _to_int(0xBFFF0011L) VI_ERROR_INV_RSRC_NAME = _to_int(0xBFFF0012L) VI_ERROR_INV_ACC_MODE = _to_int(0xBFFF0013L) VI_ERROR_TMO = _to_int(0xBFFF0015L) VI_ERROR_CLOSING_FAILED = _to_int(0xBFFF0016L) VI_ERROR_INV_DEGREE = _to_int(0xBFFF001BL) VI_ERROR_INV_JOB_ID = _to_int(0xBFFF001CL) VI_ERROR_NSUP_ATTR = _to_int(0xBFFF001DL) VI_ERROR_NSUP_ATTR_STATE = _to_int(0xBFFF001EL) VI_ERROR_ATTR_READONLY = _to_int(0xBFFF001FL) VI_ERROR_INV_LOCK_TYPE = _to_int(0xBFFF0020L) VI_ERROR_INV_ACCESS_KEY = _to_int(0xBFFF0021L) VI_ERROR_INV_EVENT = _to_int(0xBFFF0026L) VI_ERROR_INV_MECH = _to_int(0xBFFF0027L) VI_ERROR_HNDLR_NINSTALLED = _to_int(0xBFFF0028L) VI_ERROR_INV_HNDLR_REF = _to_int(0xBFFF0029L) VI_ERROR_INV_CONTEXT = _to_int(0xBFFF002AL) VI_ERROR_QUEUE_OVERFLOW = _to_int(0xBFFF002DL) VI_ERROR_NENABLED = _to_int(0xBFFF002FL) VI_ERROR_ABORT = _to_int(0xBFFF0030L) VI_ERROR_RAW_WR_PROT_VIOL = _to_int(0xBFFF0034L) VI_ERROR_RAW_RD_PROT_VIOL = _to_int(0xBFFF0035L) VI_ERROR_OUTP_PROT_VIOL = _to_int(0xBFFF0036L) VI_ERROR_INP_PROT_VIOL = _to_int(0xBFFF0037L) VI_ERROR_BERR = _to_int(0xBFFF0038L) VI_ERROR_IN_PROGRESS = _to_int(0xBFFF0039L) VI_ERROR_INV_SETUP = _to_int(0xBFFF003AL) VI_ERROR_QUEUE_ERROR = _to_int(0xBFFF003BL) VI_ERROR_ALLOC = _to_int(0xBFFF003CL) VI_ERROR_INV_MASK = _to_int(0xBFFF003DL) VI_ERROR_IO = _to_int(0xBFFF003EL) VI_ERROR_INV_FMT = _to_int(0xBFFF003FL) VI_ERROR_NSUP_FMT = _to_int(0xBFFF0041L) VI_ERROR_LINE_IN_USE = _to_int(0xBFFF0042L) VI_ERROR_NSUP_MODE = _to_int(0xBFFF0046L) VI_ERROR_SRQ_NOCCURRED = _to_int(0xBFFF004AL) VI_ERROR_INV_SPACE = _to_int(0xBFFF004EL) VI_ERROR_INV_OFFSET = _to_int(0xBFFF0051L) VI_ERROR_INV_WIDTH = _to_int(0xBFFF0052L) VI_ERROR_NSUP_OFFSET = _to_int(0xBFFF0054L) VI_ERROR_NSUP_VAR_WIDTH = _to_int(0xBFFF0055L) VI_ERROR_WINDOW_NMAPPED = _to_int(0xBFFF0057L) VI_ERROR_RESP_PENDING = _to_int(0xBFFF0059L) VI_ERROR_NLISTENERS = _to_int(0xBFFF005FL) VI_ERROR_NCIC = _to_int(0xBFFF0060L) VI_ERROR_NSYS_CNTLR = _to_int(0xBFFF0061L) VI_ERROR_NSUP_OPER = _to_int(0xBFFF0067L) VI_ERROR_INTR_PENDING = _to_int(0xBFFF0068L) VI_ERROR_ASRL_PARITY = _to_int(0xBFFF006AL) VI_ERROR_ASRL_FRAMING = _to_int(0xBFFF006BL) VI_ERROR_ASRL_OVERRUN = _to_int(0xBFFF006CL) VI_ERROR_TRIG_NMAPPED = _to_int(0xBFFF006EL) VI_ERROR_NSUP_ALIGN_OFFSET = _to_int(0xBFFF0070L) VI_ERROR_USER_BUF = _to_int(0xBFFF0071L) VI_ERROR_RSRC_BUSY = _to_int(0xBFFF0072L) VI_ERROR_NSUP_WIDTH = _to_int(0xBFFF0076L) VI_ERROR_INV_PARAMETER = _to_int(0xBFFF0078L) VI_ERROR_INV_PROT = _to_int(0xBFFF0079L) VI_ERROR_INV_SIZE = _to_int(0xBFFF007BL) VI_ERROR_WINDOW_MAPPED = _to_int(0xBFFF0080L) VI_ERROR_NIMPL_OPER = _to_int(0xBFFF0081L) VI_ERROR_INV_LENGTH = _to_int(0xBFFF0083L) VI_ERROR_INV_MODE = _to_int(0xBFFF0091L) VI_ERROR_SESN_NLOCKED = _to_int(0xBFFF009CL) VI_ERROR_MEM_NSHARED = _to_int(0xBFFF009DL) VI_ERROR_LIBRARY_NFOUND = _to_int(0xBFFF009EL) VI_ERROR_NSUP_INTR = _to_int(0xBFFF009FL) VI_ERROR_INV_LINE = _to_int(0xBFFF00A0L) VI_ERROR_FILE_ACCESS = _to_int(0xBFFF00A1L) VI_ERROR_FILE_IO = _to_int(0xBFFF00A2L) VI_ERROR_NSUP_LINE = _to_int(0xBFFF00A3L) VI_ERROR_NSUP_MECH = _to_int(0xBFFF00A4L) VI_ERROR_INTF_NUM_NCONFIG = _to_int(0xBFFF00A5L) VI_ERROR_CONN_LOST = _to_int(0xBFFF00A6L) # The following two are a non-standard NI extensions VI_ERROR_MACHINE_NAVAIL = _to_int(0xBFFF00A7L) VI_ERROR_NPERMISSION = _to_int(0xBFFF00A8L) # # Attribute constants # # All attribute codes are unsigned long, so no _to_int() is necessary. # VI_ATTR_RSRC_CLASS = 0xBFFF0001L VI_ATTR_RSRC_NAME = 0xBFFF0002L VI_ATTR_RSRC_IMPL_VERSION = 0x3FFF0003L VI_ATTR_RSRC_LOCK_STATE = 0x3FFF0004L VI_ATTR_MAX_QUEUE_LENGTH = 0x3FFF0005L VI_ATTR_USER_DATA = 0x3FFF0007L VI_ATTR_FDC_CHNL = 0x3FFF000DL VI_ATTR_FDC_MODE = 0x3FFF000FL VI_ATTR_FDC_GEN_SIGNAL_EN = 0x3FFF0011L VI_ATTR_FDC_USE_PAIR = 0x3FFF0013L VI_ATTR_SEND_END_EN = 0x3FFF0016L VI_ATTR_TERMCHAR = 0x3FFF0018L VI_ATTR_TMO_VALUE = 0x3FFF001AL VI_ATTR_GPIB_READDR_EN = 0x3FFF001BL VI_ATTR_IO_PROT = 0x3FFF001CL VI_ATTR_DMA_ALLOW_EN = 0x3FFF001EL VI_ATTR_ASRL_BAUD = 0x3FFF0021L VI_ATTR_ASRL_DATA_BITS = 0x3FFF0022L VI_ATTR_ASRL_PARITY = 0x3FFF0023L VI_ATTR_ASRL_STOP_BITS = 0x3FFF0024L VI_ATTR_ASRL_FLOW_CNTRL = 0x3FFF0025L VI_ATTR_RD_BUF_OPER_MODE = 0x3FFF002AL VI_ATTR_RD_BUF_SIZE = 0x3FFF002BL VI_ATTR_WR_BUF_OPER_MODE = 0x3FFF002DL VI_ATTR_WR_BUF_SIZE = 0x3FFF002EL VI_ATTR_SUPPRESS_END_EN = 0x3FFF0036L VI_ATTR_TERMCHAR_EN = 0x3FFF0038L VI_ATTR_DEST_ACCESS_PRIV = 0x3FFF0039L VI_ATTR_DEST_BYTE_ORDER = 0x3FFF003AL VI_ATTR_SRC_ACCESS_PRIV = 0x3FFF003CL VI_ATTR_SRC_BYTE_ORDER = 0x3FFF003DL VI_ATTR_SRC_INCREMENT = 0x3FFF0040L VI_ATTR_DEST_INCREMENT = 0x3FFF0041L VI_ATTR_WIN_ACCESS_PRIV = 0x3FFF0045L VI_ATTR_WIN_BYTE_ORDER = 0x3FFF0047L VI_ATTR_GPIB_ATN_STATE = 0x3FFF0057L VI_ATTR_GPIB_ADDR_STATE = 0x3FFF005CL VI_ATTR_GPIB_CIC_STATE = 0x3FFF005EL VI_ATTR_GPIB_NDAC_STATE = 0x3FFF0062L VI_ATTR_GPIB_SRQ_STATE = 0x3FFF0067L VI_ATTR_GPIB_SYS_CNTRL_STATE = 0x3FFF0068L VI_ATTR_GPIB_HS488_CBL_LEN = 0x3FFF0069L VI_ATTR_CMDR_LA = 0x3FFF006BL VI_ATTR_VXI_DEV_CLASS = 0x3FFF006CL VI_ATTR_MAINFRAME_LA = 0x3FFF0070L VI_ATTR_MANF_NAME = 0xBFFF0072L VI_ATTR_MODEL_NAME = 0xBFFF0077L VI_ATTR_VXI_VME_INTR_STATUS = 0x3FFF008BL VI_ATTR_VXI_TRIG_STATUS = 0x3FFF008DL VI_ATTR_VXI_VME_SYSFAIL_STATE = 0x3FFF0094L VI_ATTR_WIN_BASE_ADDR = 0x3FFF0098L VI_ATTR_WIN_SIZE = 0x3FFF009AL VI_ATTR_ASRL_AVAIL_NUM = 0x3FFF00ACL VI_ATTR_MEM_BASE = 0x3FFF00ADL VI_ATTR_ASRL_CTS_STATE = 0x3FFF00AEL VI_ATTR_ASRL_DCD_STATE = 0x3FFF00AFL VI_ATTR_ASRL_DSR_STATE = 0x3FFF00B1L VI_ATTR_ASRL_DTR_STATE = 0x3FFF00B2L VI_ATTR_ASRL_END_IN = 0x3FFF00B3L VI_ATTR_ASRL_END_OUT = 0x3FFF00B4L VI_ATTR_ASRL_REPLACE_CHAR = 0x3FFF00BEL VI_ATTR_ASRL_RI_STATE = 0x3FFF00BFL VI_ATTR_ASRL_RTS_STATE = 0x3FFF00C0L VI_ATTR_ASRL_XON_CHAR = 0x3FFF00C1L VI_ATTR_ASRL_XOFF_CHAR = 0x3FFF00C2L VI_ATTR_WIN_ACCESS = 0x3FFF00C3L VI_ATTR_RM_SESSION = 0x3FFF00C4L VI_ATTR_VXI_LA = 0x3FFF00D5L VI_ATTR_MANF_ID = 0x3FFF00D9L VI_ATTR_MEM_SIZE = 0x3FFF00DDL VI_ATTR_MEM_SPACE = 0x3FFF00DEL VI_ATTR_MODEL_CODE = 0x3FFF00DFL VI_ATTR_SLOT = 0x3FFF00E8L VI_ATTR_INTF_INST_NAME = 0xBFFF00E9L VI_ATTR_IMMEDIATE_SERV = 0x3FFF0100L VI_ATTR_INTF_PARENT_NUM = 0x3FFF0101L VI_ATTR_RSRC_SPEC_VERSION = 0x3FFF0170L VI_ATTR_INTF_TYPE = 0x3FFF0171L VI_ATTR_GPIB_PRIMARY_ADDR = 0x3FFF0172L VI_ATTR_GPIB_SECONDARY_ADDR = 0x3FFF0173L VI_ATTR_RSRC_MANF_NAME = 0xBFFF0174L VI_ATTR_RSRC_MANF_ID = 0x3FFF0175L VI_ATTR_INTF_NUM = 0x3FFF0176L VI_ATTR_TRIG_ID = 0x3FFF0177L VI_ATTR_GPIB_REN_STATE = 0x3FFF0181L VI_ATTR_GPIB_UNADDR_EN = 0x3FFF0184L VI_ATTR_DEV_STATUS_BYTE = 0x3FFF0189L VI_ATTR_FILE_APPEND_EN = 0x3FFF0192L VI_ATTR_VXI_TRIG_SUPPORT = 0x3FFF0194L VI_ATTR_TCPIP_ADDR = 0xBFFF0195L VI_ATTR_TCPIP_HOSTNAME = 0xBFFF0196L VI_ATTR_TCPIP_PORT = 0x3FFF0197L VI_ATTR_TCPIP_DEVICE_NAME = 0xBFFF0199L VI_ATTR_TCPIP_NODELAY = 0x3FFF019AL VI_ATTR_TCPIP_KEEPALIVE = 0x3FFF019BL VI_ATTR_4882_COMPLIANT = 0x3FFF019FL VI_ATTR_USB_SERIAL_NUM = 0xBFFF01A0L VI_ATTR_USB_INTFC_NUM = 0x3FFF01A1L VI_ATTR_USB_PROTOCOL = 0x3FFF01A7L VI_ATTR_USB_MAX_INTR_SIZE = 0x3FFF01AFL VI_ATTR_JOB_ID = 0x3FFF4006L VI_ATTR_EVENT_TYPE = 0x3FFF4010L VI_ATTR_SIGP_STATUS_ID = 0x3FFF4011L VI_ATTR_RECV_TRIG_ID = 0x3FFF4012L VI_ATTR_INTR_STATUS_ID = 0x3FFF4023L VI_ATTR_STATUS = 0x3FFF4025L VI_ATTR_RET_COUNT = 0x3FFF4026L VI_ATTR_BUFFER = 0x3FFF4027L VI_ATTR_RECV_INTR_LEVEL = 0x3FFF4041L VI_ATTR_OPER_NAME = 0xBFFF4042L VI_ATTR_GPIB_RECV_CIC_STATE = 0x3FFF4193L VI_ATTR_RECV_TCPIP_ADDR = 0xBFFF4198L VI_ATTR_USB_RECV_INTR_SIZE = 0x3FFF41B0L VI_ATTR_USB_RECV_INTR_DATA = 0xBFFF41B1L # # Event Types # # All event codes are unsigned long, so no _to_int() is necessary. # VI_EVENT_IO_COMPLETION = 0x3FFF2009L VI_EVENT_TRIG = 0xBFFF200AL VI_EVENT_SERVICE_REQ = 0x3FFF200BL VI_EVENT_CLEAR = 0x3FFF200DL VI_EVENT_EXCEPTION = 0xBFFF200EL VI_EVENT_GPIB_CIC = 0x3FFF2012L VI_EVENT_GPIB_TALK = 0x3FFF2013L VI_EVENT_GPIB_LISTEN = 0x3FFF2014L VI_EVENT_VXI_VME_SYSFAIL = 0x3FFF201DL VI_EVENT_VXI_VME_SYSRESET = 0x3FFF201EL VI_EVENT_VXI_SIGP = 0x3FFF2020L VI_EVENT_VXI_VME_INTR = 0xBFFF2021L VI_EVENT_TCPIP_CONNECT = 0x3FFF2036L VI_EVENT_USB_INTR = 0x3FFF2037L VI_ALL_ENABLED_EVENTS = 0x3FFF7FFFL # # Values and Ranges # VI_FIND_BUFLEN = 256 VI_NULL = 0 VI_TRUE = 1 VI_FALSE = 0 VI_INTF_GPIB = 1 VI_INTF_VXI = 2 VI_INTF_GPIB_VXI = 3 VI_INTF_ASRL = 4 VI_INTF_TCPIP = 6 VI_INTF_USB = 7 VI_PROT_NORMAL = 1 VI_PROT_FDC = 2 VI_PROT_HS488 = 3 VI_PROT_4882_STRS = 4 VI_PROT_USBTMC_VENDOR = 5 VI_FDC_NORMAL = 1 VI_FDC_STREAM = 2 VI_LOCAL_SPACE = 0 VI_A16_SPACE = 1 VI_A24_SPACE = 2 VI_A32_SPACE = 3 VI_OPAQUE_SPACE = 0xFFFF VI_UNKNOWN_LA = -1 VI_UNKNOWN_SLOT = -1 VI_UNKNOWN_LEVEL = -1 VI_QUEUE = 1 VI_HNDLR = 2 VI_SUSPEND_HNDLR = 4 VI_ALL_MECH = 0xFFFF VI_ANY_HNDLR = 0 VI_TRIG_ALL = -2 VI_TRIG_SW = -1 VI_TRIG_TTL0 = 0 VI_TRIG_TTL1 = 1 VI_TRIG_TTL2 = 2 VI_TRIG_TTL3 = 3 VI_TRIG_TTL4 = 4 VI_TRIG_TTL5 = 5 VI_TRIG_TTL6 = 6 VI_TRIG_TTL7 = 7 VI_TRIG_ECL0 = 8 VI_TRIG_ECL1 = 9 VI_TRIG_PANEL_IN = 27 VI_TRIG_PANEL_OUT = 28 VI_TRIG_PROT_DEFAULT = 0 VI_TRIG_PROT_ON = 1 VI_TRIG_PROT_OFF = 2 VI_TRIG_PROT_SYNC = 5 VI_READ_BUF = 1 VI_WRITE_BUF = 2 VI_READ_BUF_DISCARD = 4 VI_WRITE_BUF_DISCARD = 8 VI_IO_IN_BUF = 16 VI_IO_OUT_BUF = 32 VI_IO_IN_BUF_DISCARD = 64 VI_IO_OUT_BUF_DISCARD = 128 VI_FLUSH_ON_ACCESS = 1 VI_FLUSH_WHEN_FULL = 2 VI_FLUSH_DISABLE = 3 VI_NMAPPED = 1 VI_USE_OPERS = 2 VI_DEREF_ADDR = 3 VI_TMO_IMMEDIATE = 0 # Attention! The following is *really* positive! (unsigned long) VI_TMO_INFINITE = 0xFFFFFFFFL VI_NO_LOCK = 0 VI_EXCLUSIVE_LOCK = 1 VI_SHARED_LOCK = 2 VI_LOAD_CONFIG = 4 VI_NO_SEC_ADDR = 0xFFFF VI_ASRL_PAR_NONE = 0 VI_ASRL_PAR_ODD = 1 VI_ASRL_PAR_EVEN = 2 VI_ASRL_PAR_MARK = 3 VI_ASRL_PAR_SPACE = 4 VI_ASRL_STOP_ONE = 10 VI_ASRL_STOP_ONE5 = 15 VI_ASRL_STOP_TWO = 20 VI_ASRL_FLOW_NONE = 0 VI_ASRL_FLOW_XON_XOFF = 1 VI_ASRL_FLOW_RTS_CTS = 2 VI_ASRL_FLOW_DTR_DSR = 4 VI_ASRL_END_NONE = 0 VI_ASRL_END_LAST_BIT = 1 VI_ASRL_END_TERMCHAR = 2 VI_ASRL_END_BREAK = 3 VI_STATE_ASSERTED = 1 VI_STATE_UNASSERTED = 0 VI_STATE_UNKNOWN = -1 VI_BIG_ENDIAN = 0 VI_LITTLE_ENDIAN = 1 VI_DATA_PRIV = 0 VI_DATA_NPRIV = 1 VI_PROG_PRIV = 2 VI_PROG_NPRIV = 3 VI_BLCK_PRIV = 4 VI_BLCK_NPRIV = 5 VI_D64_PRIV = 6 VI_D64_NPRIV = 7 VI_WIDTH_8 = 1 VI_WIDTH_16 = 2 VI_WIDTH_32 = 4 VI_GPIB_REN_DEASSERT = 0 VI_GPIB_REN_ASSERT = 1 VI_GPIB_REN_DEASSERT_GTL = 2 VI_GPIB_REN_ASSERT_ADDRESS = 3 VI_GPIB_REN_ASSERT_LLO = 4 VI_GPIB_REN_ASSERT_ADDRESS_LLO = 5 VI_GPIB_REN_ADDRESS_GTL = 6 VI_GPIB_ATN_DEASSERT = 0 VI_GPIB_ATN_ASSERT = 1 VI_GPIB_ATN_DEASSERT_HANDSHAKE = 2 VI_GPIB_ATN_ASSERT_IMMEDIATE = 3 VI_GPIB_HS488_DISABLED = 0 VI_GPIB_HS488_NIMPL = -1 VI_GPIB_UNADDRESSED = 0 VI_GPIB_TALKER = 1 VI_GPIB_LISTENER = 2 VI_VXI_CMD16 = 0x0200 VI_VXI_CMD16_RESP16 = 0x0202 VI_VXI_RESP16 = 0x0002 VI_VXI_CMD32 = 0x0400 VI_VXI_CMD32_RESP16 = 0x0402 VI_VXI_CMD32_RESP32 = 0x0404 VI_VXI_RESP32 = 0x0004 VI_ASSERT_SIGNAL = -1 VI_ASSERT_USE_ASSIGNED = 0 VI_ASSERT_IRQ1 = 1 VI_ASSERT_IRQ2 = 2 VI_ASSERT_IRQ3 = 3 VI_ASSERT_IRQ4 = 4 VI_ASSERT_IRQ5 = 5 VI_ASSERT_IRQ6 = 6 VI_ASSERT_IRQ7 = 7 VI_UTIL_ASSERT_SYSRESET = 1 VI_UTIL_ASSERT_SYSFAIL = 2 VI_UTIL_DEASSERT_SYSFAIL = 3 VI_VXI_CLASS_MEMORY = 0 VI_VXI_CLASS_EXTENDED = 1 VI_VXI_CLASS_MESSAGE = 2 VI_VXI_CLASS_REGISTER = 3 VI_VXI_CLASS_OTHER = 4 # "Backwards compatibility" according to NI VI_NORMAL = VI_PROT_NORMAL VI_FDC = VI_PROT_FDC VI_HS488 = VI_PROT_HS488 VI_ASRL488 = VI_PROT_4882_STRS VI_ASRL_IN_BUF = VI_IO_IN_BUF VI_ASRL_OUT_BUF = VI_IO_OUT_BUF VI_ASRL_IN_BUF_DISCARD = VI_IO_IN_BUF_DISCARD VI_ASRL_OUT_BUF_DISCARD = VI_IO_OUT_BUF_DISCARD PyVISA-1.4/src/visa_study.py0000644000175000017500000003617411734647057015377 0ustar floflo00000000000000#!/usr/bin/env python # -*- coding: utf-8 -*- # # visa_study.py - Alternative high-level VISA implementation # # Copyright © 2005, 2006, 2007, 2008 # Torsten Bronger , # Gregor Thalhammer . # # This file is part of PyVISA. # # PyVISA is free software; you can redistribute it and/or modify it under # the terms of the MIT licence: # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the "Software"), # to deal in the Software without restriction, including without limitation # the rights to use, copy, modify, merge, publish, distribute, sublicense, # and/or sell copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER # DEALINGS IN THE SOFTWARE. # """visa_study.py defines an Python interface to the VISA library """ __version__ = "$Revision: 334 $" # $Source$ from ctypes import * from visa_messages import * from vpp43_types import * from vpp43_constants import * from visa_attributes import attributes_s, attributes import os import types import sys import logging log = logging.getLogger('visa') #load Visa library if os.name == 'nt': visa = windll.visa32 elif os.name == 'posix': visa = cdll.LoadLibrary('libvisa.so') else: raise "No implementation for your platform available." class VisaError(IOError): """Base class for VISA errors""" def __init__(self, value): self.value = value def __str__(self): if self.value: (shortdesc, longdesc) = completion_and_error_messages[self.value] hexvalue = self.value #convert errorcodes (negative) to long if hexvalue < 0: hexvalue = hexvalue + 0x100000000L return shortdesc + " (%X): "%hexvalue + longdesc #Checks return values for errors def CheckStatus(status): #status = ViStatus(status).value if status < 0: raise VisaError(status) else: return status #implement low level VISA functions #VISA Resource Management visa.viOpenDefaultRM.restype = CheckStatus visa.viOpen.restype = CheckStatus visa.viFindRsrc.restype = CheckStatus visa.viFindNext.restype = CheckStatus visa.viParseRsrc.restype = CheckStatus visa.viParseRsrcEx.restype = CheckStatus visa.viClose.restype = CheckStatus visa.viGetAttribute.restype = CheckStatus visa.viSetAttribute.restype = CheckStatus def OpenDefaultRM(): """Return a session to the Default Resource Manager resource.""" sesn = ViSession() result = visa.viOpenDefaultRM(byref(sesn)) return (result, sesn.value) def Open(sesn, rsrcName, accessMode, openTimeout): """Open a session to the specified device.""" sesn = ViSession(sesn) rsrcName = ViRsrc(rsrcName) accessMode = ViAccessMode(accessMode) openTimout = ViUInt32(openTimeout) vi = ViSession() result = visa.viOpen(sesn, rsrcName, accessMode, openTimeout, byref(vi)) return (result, vi.value) def FindRsrc(session, expr): """Query a VISA system to locate the resources associated with a specified interface. This operation matches the value specified in the expr parameter with the resources available for a particular interface. In comparison to the original VISA function, this returns the complete list of found resources.""" sesn = ViSession(session) expr = ViString(expr) findList = ViFindList() retcnt = ViUInt32() instrDesc = c_buffer('\000', 256) resource_list = [] result = visa.viFindRsrc(sesn, expr, byref(findList), byref(retcnt), instrDesc) if result>=0: resource_list.append(instrDesc.value) for i in range(1, retcnt.value): visa.viFindNext(findList, instrDesc) resource_list.append(instrDesc.value) visa.viClose(findList) return resource_list def ParseRsrc(sesn, rsrcName): """Parse a resource string to get the interface information.""" intfType = ViUInt16() intfNum = ViUInt16() result = visa.viParseRsrc( ViSession(sesn), ViRsrc(rsrcName), byref(intfType), byref(intfNum)) return (result, intfType.value, intfNum.value) def ParseRsrcEx(sesn, rsrcName): """Parse a resource string to get extended interface information.""" intfType = ViUInt16() intfNum = ViUInt16() rsrcClass = c_buffer(256) unaliasedExpandedRsrcName = c_buffer(256) aliasIfExists = c_buffer(256) result = visa.viParseRsrcEx(sesn, rsrcName, byref(intfType), byref(intfNum), rsrcClass, unaliasedExpandedRsrcName, aliasIfExists) return (result, intfType.value, intfNum.value, rsrcClass.value, unaliasedExpandedRsrcName.value, aliasIfExists.value) #VISA Resource Template def Close(object): """Close the specified session, event, or find list. This operation closes a session, event, or a find list. In this process all the data structures that had been allocated for the specified vi are freed.""" result = visa.viClose(ViObject(object)) return result def GetAttribute(vi, attribute): """Retrieve the state of an attribute. Argument can be numeric or string argument""" #convert argument to numeric (attr_value) if isinstance(attribute, types.StringTypes): attr_name, attr_info = attribute, attributes_s[attribute] attr_value = attr_info.attribute_value else: attr_value, attr_info = attribute, attributes[attribute] attr_name = attr_info.attribute_name #call viGetAttribute, convert output to proper data type attr_type = attr_info.datatype if attr_type is ViString: attr_val = c_buffer(256) result = visa.viGetAttribute(vi, attr_value, attr_val) elif attr_type is ViBuf: attr_val = c_void_p() result = visa.viGetAttribute(vi, attr_value, byref(attr_val)) else: attr_val = attr_type(attr_value) result = visa.viGetAttribute(vi, attr_value, byref(attr_val)) val = attr_val.value #convert result to string if attr_info.values: value_ext = attr_info.values.tostring(val) else: if isinstance(val, (types.IntType, types.LongType)): value_ext = str(val) + " (%s)"%hex(val) else: value_ext = str(val) return (attr_name, val, value_ext) def SetAttribute(vi, attribute, value): """Set attribute""" #convert attribute to numeric ('attr_value') if isinstance(attribute, types.StringTypes): attr_name, attr_info = attribute, attributes_s[attribute] attr_value = attr_info.attribute_value else: attr_value, attr_info = attribute, attributes[attribute] attr_name = attr_info.attribute_name #convert value to numeric ('val'), when appropriate if isinstance(value, types.StringTypes): if attr_info.values: val = attr_info.values.fromstring(value) else: #fallback, FIXME val = str(value) print 'conversion from string argument not possible' else: val = value cval = attr_info.datatype(val) result = visa.viSetAttribute(vi, attr_value, cval) return result #Basic I/O visa.viWrite.restype = CheckStatus def Write(vi, buf): vi = ViSession(vi) buf = c_buffer(buf, len(buf)) count = ViUInt32(len(buf)) retCount = ViUInt32() log.debug("Write: %s", buf) result = visa.viWrite(vi, buf, count, byref(retCount)) return retCount.value visa.viRead.restype = CheckStatus def Read(vi, count): vi = ViSession(vi) buf = create_string_buffer(count) count = ViUInt32(count) retCount = ViUInt32() result = visa.viRead(vi, buf, count, byref(retCount)) log.debug("Read: buffer length %d at %s", sizeof(buf), hex(addressof(buf))) return (result, buf.raw[0:retCount.value]) visa.viWriteAsync.restype = CheckStatus def WriteAsync(vi, buf): vi = ViSession(vi) buf = c_buffer(buf, len(buf)) count = ViUInt32(len(buf)) jobId = ViJobId() result = visa.viWriteAsync(vi, buf, count, byref(jobId)) return jobId.value visa.viReadAsync.restype = CheckStatus def ReadAsync(vi, count): buf = create_string_buffer(count) #FIXME: buffer needs to survive garbage collection! jobId = ViJobId() log.debug("ReadAsync: buffer length %d at %s", sizeof(buf), hex(addressof(buf))) visa.viReadAsync(ViSession(vi), buf, ViUInt32(count), byref(jobId)) return jobId.value # visa.viGpibControlREN.restype = CheckStatus def GpibControlREN(vi, mode): vi = ViSession(vi) mode = ViUInt16(mode) result = visa.viGpibControlREN(vi, mode) #Event management visa.viEnableEvent.restype = CheckStatus def EnableEvent(vi, eventType, mechanism): visa.viEnableEvent(vi, eventType, mechanism, 0) visa.viInstallHandler.restype = CheckStatus visa.viInstallHandler.argtypes = [ViSession, ViEventType, ViHndlr, ViAddr] #FIXME: dangerous ViAddr def InstallHandler(vi, eventType, handler, userHandle): userHandle = ViAddr(userHandle) visa.viInstallHandler(vi, eventType, handler, userHandle) #higher level classes and metho)ds class ResourceManager: def __init__(self): result, self.session = OpenDefaultRM() def __del__(self): Close(self.session) def find_resource(self, expression): resource_list = FindRsrc(self.session, expression) return resource_list def parse_resource(self, resource_name): """give information about resource""" result, interface_type, interface_number, \ rsrcClass, unaliasedExpandedRsrcName, \ aliasIfExists = ParseRsrcEx(self.session, resource_name) return interface_type, interface_number, \ rsrcClass, unaliasedExpandedRsrcName, \ aliasIfExists def open(self, resourceName, exclusiveLock = None, loadConfig = None, openTimeout = 1000): accessMode = 0 if exclusiveLock: accessMode = accessMode | VI_EXCLUSIVE_LOCK if loadConfig: accessMode = accessMode | VI_LOAD_CONFIG result, vi = Open(self.session, resourceName, accessMode, openTimeout) return Resource(vi) class Resource: def __init__(self, vi): self.session = vi #def __del__(self): #shit happens # self.close() def write(self, buf): return Write(self.session, buf) def read(self, maxcount = None): if maxcount: result, buf = Read(self.session, maxcount) return buf else: accumbuf = '' while 1: result, buf = Read(self.session, 1024) accumbuf = accumbuf + buf if result in (VI_SUCCESS, VI_SUCCESS_TERM_CHAR): return accumbuf def getattr(self, attribute): attrvalue = GetAttribute(self.session, attribute) return attrvalue def setattr(self, attribute, value): SetAttribute(self.session, attribute, value) def setlocal(self): #VI_GPIB_REN_DEASSERT = 0 #VI_GPIB_REN_ASSERT = 1 #VI_GPIB_REN_DEASSERT_GTL = 2 #VI_GPIB_REN_ASSERT_ADDRESS = 3 #VI_GPIB_REN_ASSERT_LLO = 4 #VI_GPIB_REN_ASSERT_ADDRESS_LLO = 5 #VI_GPIB_REN_ADDRESS_GTL = 6 mode = 6 #Test Marconi 2019: 0 local, 1 remote, 2 local, 4 local lockout, 5 local, 6 local GpibControlREN(self.session, mode) def close(self): Close(self.session) def install_handler(self, eventType, handler, user_handle): return InstallHandler(self.session, eventType, handler, user_handle) def enable_event(self, eventType, mechanism): return EnableEvent(self.session, eventType, mechanism) #_RM = ResourceManager() #liefert Exception in __del__ beim Beenden #open = _RM.Open #find_resource = _RM.FindResource #for faster testing def testvisa(): logging.basicConfig(level = logging.DEBUG) #log.setLevel(logging.DEBUG) #FIXME #open ResourceManager RM = ResourceManager() #find resources resourcelist = RM.find_resource('ASRL?::INSTR') print resourcelist #get some information without opening result = RM.parse_resource('ASRL1::INSTR') print result #open device = RM.open('ASRL1::INSTR') #high level write device.write('*IDN?') #high level read #print device.read() #don't wan't to wait for timeout... #try getting all attributes for key in attributes_s.keys(): try: print device.getattr(key) except IOError, value: print "Error retrieving Attribute ", key #set some attributes, try different combinations of numeric/string arguments device.setattr('VI_ATTR_ASRL_DATA_BITS', 7) print device.getattr(VI_ATTR_ASRL_DATA_BITS) #attribute value, string argument device.setattr(VI_ATTR_ASRL_STOP_BITS, 'VI_ASRL_STOP_TWO') print device.getattr('VI_ATTR_ASRL_STOP_BITS') print #bitfields device.setattr('VI_ATTR_ASRL_FLOW_CNTRL', VI_ASRL_FLOW_XON_XOFF | VI_ASRL_FLOW_RTS_CTS) print device.getattr('VI_ATTR_ASRL_FLOW_CNTRL') #bitfield with string argument device.setattr(VI_ATTR_ASRL_FLOW_CNTRL, 'VI_ASRL_FLOW_NONE') print device.getattr('VI_ATTR_ASRL_FLOW_CNTRL') #callback functions def event_handler(vi, event_type, context, userhandle): #def event_handler(vi, event_type, context): #FIX: should accept four arguments sys.stdout.flush() print 'in event handler' print 'vi: ', vi print 'event_type: ', event_type print 'context: ', context print GetAttribute(context, VI_ATTR_EVENT_TYPE) print GetAttribute(context, VI_ATTR_STATUS) print GetAttribute(context, VI_ATTR_JOB_ID) print GetAttribute(context, VI_ATTR_BUFFER) print GetAttribute(context, VI_ATTR_RET_COUNT) print GetAttribute(context, VI_ATTR_OPER_NAME) print 'userhandle: ', userhandle print 'leaving event handler' return VI_SUCCESS device.install_handler(VI_EVENT_IO_COMPLETION, ViHndlr(event_handler), 13) device.enable_event(VI_EVENT_IO_COMPLETION, VI_HNDLR) print 'session', device.session jobId = WriteAsync(device.session, 'going to nowhere city') print "jobId: ", jobId jobId = ReadAsync(device.session, 10) print "jobId: ", jobId device.close() if __name__ == '__main__': testvisa() PyVISA-1.4/src/vpp43_types.py0000644000175000017500000001304011734647057015370 0ustar floflo00000000000000#!/usr/bin/env python # -*- coding: utf-8 -*- # # vpp43_types.py - VISA VPP-4.3 data types (VPP-4.3.2 spec, section 3) # # Copyright © 2005, 2006, 2007, 2008 # Torsten Bronger , # Gregor Thalhammer . # # This file is part of PyVISA. # # PyVISA is free software; you can redistribute it and/or modify it under # the terms of the MIT licence: # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the "Software"), # to deal in the Software without restriction, including without limitation # the rights to use, copy, modify, merge, publish, distribute, sublicense, # and/or sell copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER # DEALINGS IN THE SOFTWARE. # """All data types that are defined by VPP-4.3.2. The module exports all data types including the pointer and array types. This means "ViUInt32" and such. """ __version__ = "$Revision: 334 $" # $Source$ # ctypes and os shouldn't be re-exported. import ctypes as _ctypes import os as _os # Part One: Type Assignments for VISA and Instrument Drivers, see spec table # 3.1.1. # # Remark: The pointer and probably also the array variants are of no # significance in Python because there is no native call-by-reference. # However, as long as I'm not fully sure about this, they won't hurt. def _type_dublet(ctypes_type): return (ctypes_type, _ctypes.POINTER(ctypes_type)) def _type_triplet(ctypes_type): return _type_dublet(ctypes_type) + (_ctypes.POINTER(ctypes_type),) ViUInt32, ViPUInt32, ViAUInt32 = _type_triplet(_ctypes.c_ulong) ViInt32, ViPInt32, ViAInt32 = _type_triplet(_ctypes.c_long) ViUInt16, ViPUInt16, ViAUInt16 = _type_triplet(_ctypes.c_ushort) ViInt16, ViPInt16, ViAInt16 = _type_triplet(_ctypes.c_short) ViUInt8, ViPUInt8, ViAUInt8 = _type_triplet(_ctypes.c_ubyte) ViInt8, ViPInt8, ViAInt8 = _type_triplet(_ctypes.c_byte) ViAddr, ViPAddr, ViAAddr = _type_triplet(_ctypes.c_void_p) ViChar, ViPChar, ViAChar = _type_triplet(_ctypes.c_char) ViByte, ViPByte, ViAByte = _type_triplet(_ctypes.c_ubyte) ViBoolean, ViPBoolean, ViABoolean = _type_triplet(ViUInt16) ViReal32, ViPReal32, ViAReal32 = _type_triplet(_ctypes.c_float) ViReal64, ViPReal64, ViAReal64 = _type_triplet(_ctypes.c_double) # The following three type triplets are defined rather pathologically, both in # the spec and the reference .h file. Therefore, I can't use _type_triplet. ViBuf = ViPByte ViPBuf = ViBuf ViABuf = _ctypes.POINTER(ViBuf) ViString = _ctypes.c_char_p # ViPChar in the spec ViPString = _ctypes.c_char_p # ViPChar in the spec ViAString = _ctypes.POINTER(ViString) # It is impractical to have ViBuf defined as an array of unsigned chars, # because ctypes forces me then to cast the string buffer to an array type. # The only semantic difference is that ViString is null terminated while ViBuf # is not (as I understand it). However, in Python there is no difference. # Since the memory representation is the same -- which is guaranteed by the C # language specification -- the following ViBuf re-definitions are sensible: ViBuf = ViPBuf = ViString ViABuf = _ctypes.POINTER(ViBuf) ViRsrc = ViString ViPRsrc = ViString ViARsrc = _ctypes.POINTER(ViRsrc) ViStatus, ViPStatus, ViAStatus = _type_triplet(ViInt32) ViVersion, ViPVersion, ViAVersion = _type_triplet(ViUInt32) ViObject, ViPObject, ViAObject = _type_triplet(ViUInt32) ViSession, ViPSession, ViASession = _type_triplet(ViObject) ViAttr = ViUInt32 ViConstString = _ctypes.POINTER(ViChar) # Part Two: Type Assignments for VISA only, see spec table 3.1.2. The # difference to the above is of no significance in Python, so I use it here # only for easier synchronisation with the spec. ViAccessMode, ViPAccessMode = _type_dublet(ViUInt32) ViBusAddress, ViPBusAddress = _type_dublet(ViUInt32) ViBusSize = ViUInt32 ViAttrState, ViPAttrState = _type_dublet(ViUInt32) # The following is weird, taken from news:zn2ek2w2.fsf@python.net ViVAList = _ctypes.POINTER(_ctypes.c_char) ViEventType, ViPEventType, ViAEventType = _type_triplet(ViUInt32) ViPAttr = _ctypes.POINTER(ViAttr) ViAAttr = ViPAttr ViEventFilter = ViUInt32 ViFindList, ViPFindList = _type_dublet(ViObject) ViEvent, ViPEvent = _type_dublet(ViObject) ViKeyId, ViPKeyId = _type_dublet(ViString) ViJobId, ViPJobId = _type_dublet(ViUInt32) # Class of callback functions for event handling, first type is result type if _os.name == 'nt': ViHndlr = _ctypes.WINFUNCTYPE(ViStatus, ViSession, ViEventType, ViEvent, ViAddr) else: ViHndlr = _ctypes.CFUNCTYPE(ViStatus, ViSession, ViEventType, ViEvent, ViAddr) PyVISA-1.4/src/visa_attributes.py0000644000175000017500000002664511753734655016421 0ustar floflo00000000000000#!/usr/bin/env python # -*- coding: utf-8 -*- # # __init__.py - PyVISA's package initialisation. # # Copyright © 2005, 2006, 2007, 2008 # Torsten Bronger , # Gregor Thalhammer . # # This file is part of PyVISA. # # PyVISA is free software; you can redistribute it and/or modify it under # the terms of the MIT licence: # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the "Software"), # to deal in the Software without restriction, including without limitation # the rights to use, copy, modify, merge, publish, distribute, sublicense, # and/or sell copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER # DEALINGS IN THE SOFTWARE. # import vpp43_constants as _constants from vpp43_types import * from visa_messages import completion_and_error_messages import string viRO = 'readonly' viRW = 'readwrite' viGlobal = 'Global' viLocal = 'Local' class _AttrRange: def __init__(self, minimum, maximum): self.minimum = minimum self.maximum = maximum def __contains__(self, item): if item >= self.minimum and item<=self.maximum: return True else: return False def tostring(self, val): if val in self: return str(val) else: raise IndexError def fromstring(self, strval): val = int(strval) #FIXME: always int? (long, double) return val class _AttrSet: """encapsulates named attributes values, for conversion between name and value""" def __init__(self, *args): self.NameSet = args self.namedict = {} self.valuedict = {} for name in args: value = _constants.__dict__[name] self.namedict[value] = name self.valuedict[name] = value def __repr__(self): return repr(self.valuedict) def __contains__(self, item): return item in self.NameSet #def __getitem__(self, key): # return self.tostring(key) def tostring(self, value): return self.namedict.get(value, None) def fromstring(self, name): return self.valuedict.get(name, None) class _AttrBitSet(_AttrSet): """class for set of attribute values that can be ORed together""" def __contains__(self, bitfield): #Fixme: more strict test for validity, test for zero """True if at least on of allowed bits is set""" for bit in self.namedict: if bit & item: return True else: return False def tostring(self, bitfield): s = '' for bit in self.namedict.keys(): if bit & bitfield: if not s: s = self.namedict[bit] else: s = s + ' | ' + self.namedict[bit] if self.namedict.has_key(0) and bitfield == 0: #no bit set: special name s = self.namedict[0] return s def fromstring(self, expr): bitfield = 0 for s in map(string.strip, string.split(expr, '|')): #split at | and remove whitespace bitfield = bitfield | self.valuedict[s] return bitfield class viAttrInfo: """container for information about attribute (attribute name, value, access restriction, scope (local for session or global for device), ctypes data type, range of possible values, short and long description""" def __init__(self, access, scope, datatype, values, shortdesc, description, attribute = None, name = None): self.access = access self.scope = scope self.datatype = datatype self.values = values self.description = description self.attribute_name = name self.attribute_value = attribute def __repr__(self): #s = repr(self.typecode) + repr(self.values) #return s return repr(self.__dict__) #VISA Template Attributes #Table 3.2.1 attributes_s = { 'VI_ATTR_RSRC_IMPL_VERSION': \ viAttrInfo( viRO, viGlobal, ViVersion, _AttrRange(0, 0xFFFFFFFFL), 'implementation version', "Resource version that uniquely identifies each of the different "\ "revisions or implementations of a resource." ), 'VI_ATTR_RSRC_LOCK_STATE': \ viAttrInfo( viRO, viGlobal, ViAccessMode, _AttrSet('VI_NO_LOCK', 'VI_EXCLUSIVE_LOCK', 'VI_SHARED_LOCK'), 'lock state', "The current locking state of the resource. The resource can be "\ "unlocked, locked with an exclusive lock, or locked with a shared "\ "lock." ), 'VI_ATTR_RSRC_MANF_ID': \ viAttrInfo( viRO, viGlobal, ViUInt16, _AttrRange(0, 0x3FFF), 'resource manufacturer ID', "A value that corresponds to the VXI manufacturer ID of the "\ "manufacturer that created the implementation." ), 'VI_ATTR_RSRC_MANF_NAME': \ viAttrInfo( viRO, viGlobal, ViString, None, 'resource manufacturer name', "A string that corresponds to the VXI manufacturer name of the "\ "manufacturer that created the implementation." ), 'VI_ATTR_RSRC_NAME': \ viAttrInfo( viRO, viGlobal, ViRsrc, None, 'resource name', "The unique identifier for a resource compliant with the address "\ "structure presented in Section 4.4.1, Address String." ), 'VI_ATTR_RSRC_SPEC_VERSION': \ viAttrInfo( viRO, viGlobal, ViVersion, None, 'resource specification version', "Resource version that uniquely identifies the version of the VISA "\ "specification to which the implementation is compliant." ), 'VI_ATTR_RSRC_CLASS': \ viAttrInfo( viRO, viGlobal, ViString, None, 'resource class', "Specifies the resource class (for example, INSTR)." ), #Generic INSTR Resource Attributes 'VI_ATTR_INTF_NUM': \ viAttrInfo( viRO, viGlobal, ViUInt16, _AttrRange(0, 0xFFFF), 'interface number', "Board number for the given interface." ), 'VI_ATTR_INTF_TYPE': \ viAttrInfo( viRO, viGlobal, ViUInt16, _AttrSet('VI_INTF_VXI', 'VI_INTF_GPIB', 'VI_INTF_GPIB_VXI', 'VI_INTF_ASRL', 'VI_INTF_TCPIP', 'VI_INTF_USB'), 'interface type', "Interface type of the given session." ), 'VI_ATTR_INTF_INST_NAME': \ viAttrInfo( viRO, viGlobal, ViString, None, 'interface name', "Human-readable text describing the given interface." ), #ASRL Specific INSTR Resource Attributes 'VI_ATTR_ASRL_AVAIL_NUM': \ viAttrInfo( viRO, viGlobal, ViUInt32, None, #0 to 0xFFFFFFFFL 'number of bytes available at serial port', "" ), 'VI_ATTR_ASRL_BAUD': \ viAttrInfo( viRW, viGlobal, ViUInt32, None, #0 to 0xFFFFFFFFL 'serial baud rate', "" ), 'VI_ATTR_ASRL_DATA_BITS': \ viAttrInfo( viRW, viGlobal, ViUInt16, _AttrRange(5, 8), '', "" ), 'VI_ATTR_ASRL_PARITY': \ viAttrInfo( viRW, viGlobal, ViUInt16, _AttrSet('VI_ASRL_PAR_NONE', 'VI_ASRL_PAR_ODD', 'VI_ASRL_PAR_EVEN', 'VI_ASRL_PAR_MARK', 'VI_ASRL_PAR_SPACE'), '', "" ), 'VI_ATTR_ASRL_STOP_BITS': \ viAttrInfo( viRW, viGlobal, ViUInt16, _AttrSet('VI_ASRL_STOP_ONE', 'VI_ASRL_STOP_ONE5', 'VI_ASRL_STOP_TWO'), '', "" ), 'VI_ATTR_ASRL_FLOW_CNTRL': \ viAttrInfo( viRW, viGlobal, ViUInt16, _AttrBitSet('VI_ASRL_FLOW_NONE', 'VI_ASRL_FLOW_XON_XOFF', 'VI_ASRL_FLOW_RTS_CTS', 'VI_ASRL_FLOW_DTR_DSR'), '', "" ), 'VI_ATTR_ASRL_END_IN': \ viAttrInfo( viRW, viLocal, ViUInt16, _AttrSet('VI_ASRL_END_NONE', 'VI_ASRL_END_LAST_BIT', 'VI_ASRL_END_TERMCHAR'), '', "" ), 'VI_ATTR_ASRL_END_OUT': \ viAttrInfo( viRW, viLocal, ViUInt16, _AttrSet('VI_ASRL_END_NONE', 'VI_ASRL_END_LAST_BIT', 'VI_ASRL_END_TERMCHAR', 'VI_ASRL_END_BREAK'), '', "" ), 'VI_ATTR_ASRL_CTS_STATE': \ viAttrInfo( viRO, viGlobal, ViInt16, _AttrSet('VI_STATE_ASSERTED', 'VI_STATE_UNASSERTED', 'VI_STATE_UNKNOWN'), '', "" ), 'VI_ATTR_ASRL_DCD_STATE': \ viAttrInfo( viRO, viGlobal, ViInt16, _AttrSet('VI_STATE_ASSERTED', 'VI_STATE_UNASSERTED', 'VI_STATE_UNKNOWN'), '', "" ), 'VI_ATTR_ASRL_DSR_STATE': \ viAttrInfo( viRO, viGlobal, ViInt16, _AttrSet('VI_STATE_ASSERTED', 'VI_STATE_UNASSERTED', 'VI_STATE_UNKNOWN'), '', "" ), 'VI_ATTR_ASRL_DTR_STATE': \ viAttrInfo( viRW, viGlobal, ViInt16, _AttrSet('VI_STATE_ASSERTED', 'VI_STATE_UNASSERTED', 'VI_STATE_UNKNOWN'), '', "" ), 'VI_ATTR_ASRL_RI_STATE': \ viAttrInfo( viRO, viGlobal, ViInt16, _AttrSet('VI_STATE_ASSERTED', 'VI_STATE_UNASSERTED', 'VI_STATE_UNKNOWN'), '', "" ), 'VI_ATTR_ASRL_RTS_STATE': \ viAttrInfo( viRW, viGlobal, ViInt16, _AttrSet('VI_STATE_ASSERTED', 'VI_STATE_UNASSERTED', 'VI_STATE_UNKNOWN'), '', "" ), 'VI_ATTR_ASRL_REPLACE_CHAR': \ viAttrInfo( viRW, viLocal, ViUInt8, None, #0 to FFh, '', "" ), 'VI_ATTR_ASRL_XON_CHAR': \ viAttrInfo( viRW, viLocal, ViUInt8, None, #0 to FFh '', "" ), 'VI_ATTR_ASRL_XOFF_CHAR': \ viAttrInfo( viRW, viLocal, ViUInt8, None, #0 to FFh '', "" ), #Event Attributes: VI_EVENT_IO_COMPLETION 'VI_ATTR_EVENT_TYPE': \ viAttrInfo( viRO, None, ViEventType, _AttrSet('VI_EVENT_IO_COMPLETION'), #FIXME: add other Events 'event type', "Unique logical identifier of the event type." ), 'VI_ATTR_STATUS': \ viAttrInfo( viRO, None, ViStatus, _AttrSet(*map(lambda x:x[0], completion_and_error_messages.values())), #list of status codes, FIXME 'return code of asynchronous operation that has completed', "" ), 'VI_ATTR_JOB_ID': \ viAttrInfo( viRO, None, ViJobId, None, 'job ID', "" ), 'VI_ATTR_BUFFER': \ viAttrInfo( viRO, None, ViBuf, None, 'buffer address', "Address of a buffer that was used in an asynchronous operation." ), 'VI_ATTR_RET_COUNT': \ viAttrInfo( viRO, None, ViUInt32, None, #0 to ffffffffh 'return count', "actual number of elements that were asynchronously transferred" ), 'VI_ATTR_OPER_NAME': \ viAttrInfo( viRO, None, ViString, None, 'operation name', "The name of the operation generating the event." ) } """List of VISA Attributes, as dictionary with string keys""" attributes = {} #dict with attribute value (not name) as key for name, info in attributes_s.iteritems(): value = _constants.__dict__[name] #convert attribute name to value info.attribute_name = name info.attribute_value = value attributes[value] = info #print attr PyVISA-1.4/src/vpp43.py0000644000175000017500000012421411734647057014152 0ustar floflo00000000000000#!/usr/bin/env python # -*- coding: utf-8 -*- # # vpp43.py - VISA VPP-4.3.2 functions implementation # # Copyright © 2005, 2006, 2007, 2008 # Torsten Bronger , # Gregor Thalhammer . # # This file is part of PyVISA. # # PyVISA is free software; you can redistribute it and/or modify it under # the terms of the MIT licence: # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the "Software"), # to deal in the Software without restriction, including without limitation # the rights to use, copy, modify, merge, publish, distribute, sublicense, # and/or sell copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER # DEALINGS IN THE SOFTWARE. # """Main module of the implementation of the original VISA routines. See VPP-4.3.2. """ __version__ = "$Revision: 334 $" # \$Source${}$\$ VI_SPEC_VERSION = 0x00300000 from visa_exceptions import * from vpp43_constants import * from vpp43_types import * from vpp43_attributes import attributes import os from ctypes import byref, cdll, c_void_p, c_double, c_long, \ create_string_buffer, POINTER if os.name == 'nt': from ctypes import windll, WINFUNCTYPE as FUNCTYPE else: from ctypes import CFUNCTYPE as FUNCTYPE import warnings from visa_messages import completion_and_error_messages visa_functions = [ "assert_interrupt_signal", "assert_trigger", "assert_utility_signal", "buffer_read", "buffer_write", "clear", "close", "disable_event", "discard_events", "enable_event", "find_next", "find_resources", "flush", "get_attribute", "get_default_resource_manager", "gpib_command", "gpib_control_atn", "gpib_control_ren", "gpib_pass_control", "gpib_send_ifc", "in_16", "in_32", "in_8", "install_handler", "lock", "map_address", "map_trigger", "memory_allocation", "memory_free", "move", "move_asynchronously", "move_in_16", "move_in_32", "move_in_8", "move_out_16", "move_out_32", "move_out_8", "open", "open_default_resource_manager", "out_16", "out_32", "out_8", "parse_resource", "parse_resource_extended", "peek_16", "peek_32", "peek_8", "poke_16", "poke_32", "poke_8", "printf", "queryf", "read", "read_asynchronously", "read_to_file", "read_stb", "scanf", "set_attribute", "set_buffer", "sprintf", "sscanf", "status_description", "terminate", "uninstall_handler", "unlock", "unmap_address", "unmap_trigger", "usb_control_in", "usb_control_out", "vprintf", "vqueryf", "vscanf", "vsprintf", "vsscanf", "vxi_command_query", "wait_on_event", "write", "write_asynchronously", "write_from_file"] __all__ = ["visa_library", "get_status"] + visa_functions # Add all symbols from #visa_exceptions# and #vpp43_constants# to the list of # exported symbols import visa_exceptions, vpp43_constants __all__.extend([name for name in vpp43_constants.__dict__.keys() + visa_exceptions.__dict__.keys() if name[0] != '_']) # load VISA library class Singleton(object): """Base class for singleton classes. Taken from . I added the definition of __init__. """ def __new__(cls, *args, **kwds): it = cls.__dict__.get("__it__") if it is not None: return it cls.__it__ = it = object.__new__(cls) it.init(*args, **kwds) return it def init(self, *args, **kwds): pass def __init__(self, *args, **kwds): pass class VisaLibrary(Singleton): """Singleton class for VISA ctypes library handle. This class has only one instance called "visa_library". The purpose of its instance is to provide access to the ctypes object that contains the VISA library. Public methods: load_library -- (re-)loads the VISA library __call__ -- returns the ctypes object holding the VISA library """ def init(self): self.__lib = self.__cdecl_lib = None def load_library(self, path = None): """(Re-)loads the VISA library. The optional parameter "path" holds the full path to the VISA library. It is called implicitly by __call__ if not called successfully before. It may raise an OSNotSupported exception, or an OSError if the library file was not found. """ if os.name == 'nt': if path: self.__lib = windll.LoadLibrary(path) self.__cdecl_lib = cdll.LoadLibrary(path) else: self.__lib = windll.visa32 self.__cdecl_lib = cdll.visa32 elif os.name == 'posix': if not path: path = "/usr/local/vxipnp/linux/bin/libvisa.so.7" self.__lib = self.__cdecl_lib = cdll.LoadLibrary(path) else: self.__lib = self.__cdecl_lib = None raise visa_exceptions.OSNotSupported, os.name self.__initialize_library_functions() def set_user_handle_type(self, user_handle): # Actually, it's not necessary to change ViHndlr *globally*. However, # I don't want to break symmetry too much with all the other VPP43 # routines. global ViHndlr if user_handle is None: user_handle_p = c_void_p else: user_handle_p = POINTER(type(user_handle)) ViHndlr = FUNCTYPE(ViStatus, ViSession, ViEventType, ViEvent, user_handle_p) self.__lib.viInstallHandler.argtypes = [ViSession, ViEventType, ViHndlr, user_handle_p] self.__lib.viUninstallHandler.argtypes = [ViSession, ViEventType, ViHndlr, user_handle_p] def __call__(self, force_cdecl = False): """Returns the ctypes object to the VISA library. If "force_cdecl" is True, use the cdecl calling convention even under Windows, where the stdcall convension is the default. For Linux, this has no effect. """ if self.__lib is None or self.__cdecl_lib is None: self.load_library() if force_cdecl: return self.__cdecl_lib return self.__lib def __initialize_library_functions(self): # Consistency remark: here all VPP-4.3.2 routines must be listed (unless, of # course, they don't return a status value, like "peek" and "poke"). for visa_function in ["viAssertIntrSignal", "viAssertTrigger", "viAssertUtilSignal", "viBufRead", "viBufWrite", "viClear", "viClose", "viDisableEvent", "viDiscardEvents", "viEnableEvent", "viFindNext", "viFindRsrc", "viFlush", "viGetAttribute", "viGpibCommand", "viGpibControlATN", "viGpibControlREN", "viGpibPassControl", "viGpibSendIFC", "viIn16", "viIn32", "viIn8", "viInstallHandler", "viLock", "viMapAddress", "viMapTrigger", "viMemAlloc", "viMemFree", "viMove", "viMoveAsync", "viMoveIn16", "viMoveIn32", "viMoveIn8", "viMoveOut16", "viMoveOut32", "viMoveOut8", "viOpen", "viOpenDefaultRM", "viOut16", "viOut32", "viOut8", "viParseRsrc", "viParseRsrcEx", "viRead", "viReadAsync", "viReadSTB", "viReadToFile", "viSetAttribute", "viSetBuf", "viStatusDesc", "viTerminate", "viUninstallHandler", "viUnlock", "viUnmapAddress", "viUnmapTrigger", "viUsbControlIn", "viUsbControlOut", "viVPrintf", "viVQueryf", "viVSPrintf", "viVSScanf", "viVScanf", "viVxiCommandQuery", "viWaitOnEvent", "viWrite", "viWriteAsync", "viWriteFromFile"]: try: getattr(self.__lib, visa_function).restype = check_status except AttributeError: # Mostly, viParseRsrcEx was not found pass for visa_function in ["viPrintf", "viScanf", "viSPrintf", "viSScanf", "viQueryf"]: try: getattr(self.__cdecl_lib, visa_function).restype = check_status except AttributeError: pass for visa_function in ["viPeek8", "viPeek16", "viPeek32", "viPoke8", "viPoke16", "viPoke32"]: try: getattr(self.__lib, visa_function).restype = None except AttributeError: pass # Here too, we silently ignore missing functions. If the user accesses # it nevertheless, an AttributeError is raised which is clear enough self.__set_argument_types("viAssertIntrSignal", [ViSession, ViInt16, ViUInt32]) self.__set_argument_types("viAssertTrigger", [ViSession, ViUInt16]) self.__set_argument_types("viAssertUtilSignal", [ViSession, ViUInt16]) self.__set_argument_types("viBufRead", [ViSession, ViPBuf, ViUInt32, ViPUInt32]) self.__set_argument_types("viBufWrite", [ViSession, ViBuf, ViUInt32, ViPUInt32]) self.__set_argument_types("viClear", [ViSession]) self.__set_argument_types("viClose", [ViObject]) self.__set_argument_types("viDisableEvent", [ViSession, ViEventType, ViUInt16]) self.__set_argument_types("viDiscardEvents", [ViSession, ViEventType, ViUInt16]) self.__set_argument_types("viEnableEvent", [ViSession, ViEventType, ViUInt16, ViEventFilter]) self.__set_argument_types("viFindNext", [ViSession, ViAChar]) self.__set_argument_types("viFindRsrc", [ViSession, ViString, ViPFindList, ViPUInt32, ViAChar]) self.__set_argument_types("viFlush", [ViSession, ViUInt16]) self.__set_argument_types("viGetAttribute", [ViObject, ViAttr, c_void_p]) self.__set_argument_types("viGpibCommand", [ViSession, ViBuf, ViUInt32, ViPUInt32]) self.__set_argument_types("viGpibControlATN", [ViSession, ViUInt16]) self.__set_argument_types("viGpibControlREN", [ViSession, ViUInt16]) self.__set_argument_types("viGpibPassControl", [ViSession, ViUInt16, ViUInt16]) self.__set_argument_types("viGpibSendIFC", [ViSession]) self.__set_argument_types("viIn8", [ViSession, ViUInt16, ViBusAddress, ViPUInt8]) self.__set_argument_types("viIn16", [ViSession, ViUInt16, ViBusAddress, ViPUInt16]) self.__set_argument_types("viIn32", [ViSession, ViUInt16, ViBusAddress, ViPUInt32]) self.__set_argument_types("viInstallHandler", [ViSession, ViEventType, ViHndlr, ViAddr]) self.__set_argument_types("viLock", [ViSession, ViAccessMode, ViUInt32, ViKeyId, ViAChar]) self.__set_argument_types("viMapAddress", [ViSession, ViUInt16, ViBusAddress, ViBusSize, ViBoolean, ViAddr, ViPAddr]) self.__set_argument_types("viMapTrigger", [ViSession, ViInt16, ViInt16, ViUInt16]) self.__set_argument_types("viMemAlloc", [ViSession, ViBusSize, ViPBusAddress]) self.__set_argument_types("viMemFree", [ViSession, ViBusAddress]) self.__set_argument_types("viMove", [ViSession, ViUInt16, ViBusAddress, ViUInt16, ViUInt16, ViBusAddress, ViUInt16, ViBusSize]) self.__set_argument_types("viMoveAsync", [ViSession, ViUInt16, ViBusAddress, ViUInt16, ViUInt16, ViBusAddress, ViUInt16, ViBusSize, ViPJobId]) self.__set_argument_types("viMoveIn8", [ViSession, ViUInt16, ViBusAddress, ViBusSize, ViAUInt8]) self.__set_argument_types("viMoveIn16", [ViSession, ViUInt16, ViBusAddress, ViBusSize, ViAUInt16]) self.__set_argument_types("viMoveIn32", [ViSession, ViUInt16, ViBusAddress, ViBusSize, ViAUInt32]) self.__set_argument_types("viMoveOut8", [ViSession, ViUInt16, ViBusAddress, ViBusSize, ViAUInt8]) self.__set_argument_types("viMoveOut16", [ViSession, ViUInt16, ViBusAddress, ViBusSize, ViAUInt16]) self.__set_argument_types("viMoveOut32", [ViSession, ViUInt16, ViBusAddress, ViBusSize, ViAUInt32]) # The following function *must* be available in order to assure that we # have a VISA library at all (rather than something completely # different). I hope that viOpen is old enough in the VISA # specification. self.__set_argument_types("viOpen", [ViSession, ViRsrc, ViAccessMode, ViUInt32, ViPSession], may_be_missing=False) self.__set_argument_types("viOpenDefaultRM", [ViPSession]) self.__set_argument_types("viOut8", [ViSession, ViUInt16, ViBusAddress, ViUInt8]) self.__set_argument_types("viOut16", [ViSession, ViUInt16, ViBusAddress, ViUInt16]) self.__set_argument_types("viOut32", [ViSession, ViUInt16, ViBusAddress, ViUInt32]) self.__set_argument_types("viParseRsrc", [ViSession, ViRsrc, ViPUInt16, ViPUInt16]) self.__set_argument_types("viParseRsrcEx", [ViSession, ViRsrc, ViPUInt16, ViPUInt16, ViAChar, ViAChar, ViAChar]) self.__set_argument_types("viPeek8", [ViSession, ViAddr, ViPUInt8]) self.__set_argument_types("viPeek16", [ViSession, ViAddr, ViPUInt16]) self.__set_argument_types("viPeek32", [ViSession, ViAddr, ViPUInt32]) self.__set_argument_types("viPoke8", [ViSession, ViAddr, ViUInt8]) self.__set_argument_types("viPoke16", [ViSession, ViAddr, ViUInt16]) self.__set_argument_types("viPoke32", [ViSession, ViAddr, ViUInt32]) self.__set_argument_types("viPrintf", [ViSession, ViString], force_cdecl=True) self.__set_argument_types("viQueryf", [ViSession, ViString, ViString], force_cdecl=True) self.__set_argument_types("viRead", [ViSession, ViPBuf, ViUInt32, ViPUInt32]) self.__set_argument_types("viReadAsync", [ViSession, ViPBuf, ViUInt32, ViPJobId]) self.__set_argument_types("viReadSTB", [ViSession, ViPUInt16]) self.__set_argument_types("viReadToFile", [ViSession, ViString, ViUInt32, ViPUInt32]) self.__set_argument_types("viScanf", [ViSession, ViString], force_cdecl=True) self.__set_argument_types("viSetAttribute", [ViObject, ViAttr, ViAttrState]) self.__set_argument_types("viSetBuf", [ViSession, ViUInt16, ViUInt32]) self.__set_argument_types("viSPrintf", [ViSession, ViPBuf, ViString], force_cdecl=True) self.__set_argument_types("viSScanf", [ViSession, ViBuf, ViString], force_cdecl=True) self.__set_argument_types("viStatusDesc", [ViObject, ViStatus, ViAChar]) self.__set_argument_types("viTerminate", [ViSession, ViUInt16, ViJobId]) self.__set_argument_types("viUninstallHandler", [ViSession, ViEventType, ViHndlr, ViAddr]) self.__set_argument_types("viUnlock", [ViSession]) self.__set_argument_types("viUnmapAddress", [ViSession]) self.__set_argument_types("viUnmapTrigger", [ViSession, ViInt16, ViInt16]) self.__set_argument_types("viUsbControlIn", [ViSession, ViInt16, ViInt16, ViUInt16, ViUInt16, ViUInt16, ViPBuf, ViPUInt16]) self.__set_argument_types("viUsbControlOut", [ViSession, ViInt16, ViInt16, ViUInt16, ViUInt16, ViUInt16, ViPBuf]) # The following "V" routines are *not* implemented in PyVISA, and will # never be: viVPrintf, viVQueryf, viVScanf, viVSPrintf, viVSScanf self.__set_argument_types("viVxiCommandQuery", [ViSession, ViUInt16, ViUInt32, ViPUInt32]) self.__set_argument_types("viWaitOnEvent", [ViSession, ViEventType, ViUInt32, ViPEventType, ViPEvent]) self.__set_argument_types("viWrite", [ViSession, ViBuf, ViUInt32, ViPUInt32]) self.__set_argument_types("viWriteAsync", [ViSession, ViBuf, ViUInt32, ViPJobId]) self.__set_argument_types("viWriteFromFile", [ViSession, ViString, ViUInt32, ViPUInt32]) def __set_argument_types(self, visa_function, types, force_cdecl=False, may_be_missing=True): if not force_cdecl: library = self.__lib else: library = self.__cdecl_lib try: getattr(library, visa_function).argtypes = types except AttributeError: if not may_be_missing: raise visa_library = VisaLibrary() visa_status = 0 dodgy_completion_codes = \ [VI_SUCCESS_MAX_CNT, VI_SUCCESS_DEV_NPRESENT, VI_SUCCESS_SYNC, VI_WARN_QUEUE_OVERFLOW, VI_WARN_CONFIG_NLOADED, VI_WARN_NULL_OBJECT, VI_WARN_NSUP_ATTR_STATE, VI_WARN_UNKNOWN_STATUS, VI_WARN_NSUP_BUF, VI_WARN_EXT_FUNC_NIMPL] """For these completion codes, warnings are issued.""" def check_status(status): """Check return values for errors and warnings.""" global visa_status visa_status = status if status < 0: raise visa_exceptions.VisaIOError, status if status in dodgy_completion_codes: abbreviation, description = completion_and_error_messages[status] warnings.warn("%s: %s" % (abbreviation, description), visa_exceptions.VisaIOWarning, stacklevel = 2) return status def get_status(): return visa_status # convert_argument_list is used for VISA routines with variable argument list, # which means that also the types are unknown. Therefore I convert the Python # types to well-defined ctypes types. # # Attention: This means that only C doubles, C long ints, and strings can be # used in format strings! No "float"s, no "long doubles", no "int"s etc. # Further, only floats, integers and strings can be passed to printf and scanf, # but neither unicode strings nor sequence types. # # All of these restrictions may be removed in the future. def convert_argument_list(original_arguments): """Converts a Python arguments list to the equivalent ctypes list. Arguments: original_arguments -- a sequence type with the arguments that should be used with ctypes. Return value: a tuple with the ctypes version of the argument list. """ converted_arguments = [] for argument in original_arguments: if isinstance(argument, float): converted_arguments.append(c_double(argument)) elif isinstance(argument, int): converted_arguments.append(c_long(argument)) elif isinstance(argument, str): converted_arguments.append(argument) else: raise visa_exceptions.VisaTypeError, \ "Invalid type in scanf/printf: %s" % type(argument) return tuple(converted_arguments) def convert_to_byref(byvalue_arguments, buffer_length): """Converts a list of ctypes objects to a tuple with ctypes references (pointers) to them, for use in scanf-like functions. Arguments: byvalue_arguments -- a list (sic!) with the original arguments. They must be simple ctypes objects or Python strings. If there are Python strings, they are converted in place to ctypes buffers of the same length and same contents. buffer_length -- minimal length of ctypes buffers generated from Python strings. Return value: a tuple with the by-references arguments. """ converted_arguments = [] for i in range(len(byvalue_arguments)): if isinstance(byvalue_arguments[i], str): byvalue_arguments[i] = \ create_string_buffer(byvalue_arguments[i], max(len(byvalue_arguments[i]) + 1, buffer_length)) converted_arguments.append(byvalue_arguments[i]) elif isinstance(byvalue_arguments[i], (c_long, c_double)): converted_arguments.append(byref(byvalue_arguments[i])) else: raise visa_exceptions.VisaTypeError, \ "Invalid type in scanf: %s" % type(argument) return tuple(converted_arguments) def construct_return_tuple(original_ctypes_sequence): """Generate a return value for queryf(), scanf(), and sscanf() out of the list of ctypes objects. Arguments: original_ctypes_sequence -- a sequence of ctypes objects, i.e. c_long, c_double, and ctypes strings. Return value: The pythonic variants of the ctypes objects, in a form suitable to be returned by a function: None if empty, single value, or tuple of all values. """ length = len(original_ctypes_sequence) if length == 0: return None elif length == 1: return original_ctypes_sequence[0].value else: return tuple([argument.value for argument in original_ctypes_sequence]) # The VPP-4.3.2 routines # Usually, there is more than one way to pass parameters to ctypes calls. The # ctypes policy used in this code goes as follows: # # * Null pointers are passed as "None" rather than "0". This is a little bit # unfortunate, since the VPP specification calls this "VI_NULL", but I can't # use "VI_NULL" since it's an integer and may not be compatible with a # pointer type (don't know whether this is really dangerous). # # * Strings must have been created with "create_string_buffer" and are passed # without any further conversion; they stand in the parameter list as is. # The same applies to pseudo-string types as ViRsrc or VuBuf. Their Pythonic # counterpats are strings as well. # # * All other types are explicitly cast using the types defined by ctypes' # "restype". # # Further notes: # # * The following Python routines take and give handles as ctypes objects. # Since the user shouldn't be interested in handle values anyway, I see no # point in converting them to Python strings or integers. # # * All other parameters are natural Python types, i.e. strings (may contain # binary data) and integers. The same is true for return values. # # * The original VPP function signatures cannot be realised in Python, at least # not in a sensible way, because a) Python has no real call-by-reference, and # b) Python allows for more elegant solutions, e.g. using len(buffer) instead # of a separate "count" parameter, or using tuples as return values. # # Therefore, all function signatures have been carefully adjusted. I think # this is okay, since the original standard must be adopted to at least C and # Visual Basic anyway, with slight modifications. I also made the function # names and parameters more legible, but in a way that it's perfectly clear # which original function is meant. # # The important thing is that the semantics of functions and parameters are # totally intact, and the inner order of parameters, too. There is a 1:1 # mapping. def assert_interrupt_signal(vi, mode, status_id): visa_library().viAssertIntrSignal(vi, mode, status_id) def assert_trigger(vi, protocol): visa_library().viAssertTrigger(vi, protocol) def assert_utility_signal(vi, line): visa_library().viAssertUtilSignal(vi, line) def buffer_read(vi, count): buffer = create_string_buffer(count) return_count = ViUInt32() visa_library().viBufRead(vi, buffer, count, byref(return_count)) return buffer.raw[:return_count.value] def buffer_write(vi, buffer): return_count = ViUInt32() visa_library().viBufWrite(vi, buffer, len(buffer), byref(return_count)) return return_count.value def clear(vi): visa_library().viClear(vi) def close(vi): visa_library().viClose(vi) def disable_event(vi, event_type, mechanism): visa_library().viDisableEvent(vi, event_type, mechanism) def discard_events(vi, event_type, mechanism): visa_library().viDiscardEvents(vi, event_type, mechanism) def enable_event(vi, event_type, mechanism, context = VI_NULL): context = VI_NULL # according to spec VPP-4.3, section 3.7.3.1 visa_library().viEnableEvent(vi, event_type, mechanism, context) def find_next(find_list): instrument_description = create_string_buffer(VI_FIND_BUFLEN) visa_library().viFindNext(find_list, instrument_description) return instrument_description.value def find_resources(session, regular_expression): find_list = ViFindList() return_counter = ViUInt32() instrument_description = create_string_buffer(VI_FIND_BUFLEN) visa_library().viFindRsrc(session, regular_expression, byref(find_list), byref(return_counter), instrument_description) return (find_list, return_counter.value, instrument_description.value) def flush(vi, mask): visa_library().viFlush(vi, mask) def get_attribute(vi, attribute): # FixMe: How to deal with ViBuf? datatype = attributes[attribute] if datatype == ViString: attribute_state = create_string_buffer(256) visa_library().viGetAttribute(vi, attribute, attribute_state) elif datatype == ViAUInt8: length = get_attribute(vi, VI_ATTR_USB_RECV_INTR_SIZE) attribute_state = (ViUInt8 * length)() visa_library().viGetAttribute(vi, attribute, byref(attribute_state)) return list(attribute_state) else: attribute_state = datatype() visa_library().viGetAttribute(vi, attribute, byref(attribute_state)) return attribute_state.value def gpib_command(vi, buffer): return_count = ViUInt32() visa_library().viGpibCommand(vi, buffer, len(buffer), byref(return_count)) return return_count.value def gpib_control_atn(vi, mode): visa_library().viGpibControlATN(vi, mode) def gpib_control_ren(vi, mode): visa_library().viGpibControlREN(vi, mode) def gpib_pass_control(vi, primary_address, secondary_address): visa_library().viGpibPassControl(vi, primary_address, secondary_address) def gpib_send_ifc(vi): visa_library().viGpibSendIFC(vi) def in_8(vi, space, offset): value_8 = ViUInt8() visa_library().viIn8(vi, space, offset, byref(value_8)) return value_8.value def in_16(vi, space, offset): value_16 = ViUInt16() visa_library().viIn16(vi, space, offset, byref(value_16)) return value_16.value def in_32(vi, space, offset): value_32 = ViUInt32() visa_library().viIn32(vi, space, offset, byref(value_32)) return value_32.value handlers = [] """Contains all installed event handlers. Its elements are tuples with three elements: The handler itself (a Python callable), the user handle (as a ctypes object) and the handler again, this time as a ctypes object created with CFUNCTYPE. """ def install_handler(vi, event_type, handler, user_handle = None): if user_handle is None: converted_user_handle = None else: if isinstance(user_handle, int): converted_user_handle = c_long(user_handle) elif isinstance(user_handle, float): converted_user_handle = c_double(user_handle) elif isinstance(user_handle, str): converted_user_handle = c_create_string_buffer(user_handle) elif isinstance(user_handle, list): for element in user_handle: if not isinstance(element, int): converted_user_handle = \ (c_double * len(user_handle))(tuple(user_handle)) break else: converted_user_handle = \ (c_long * len(user_handle))(*tuple(user_handle)) else: raise visa_exceptions.VisaTypeError, \ "Type not allowed as user handle: %s" % type(user_handle) visa_library.set_user_handle_type(converted_user_handle) converted_handler = ViHndlr(handler) if user_handle is None: visa_library().viInstallHandler(vi, event_type, converted_handler, None) else: visa_library().viInstallHandler(vi, event_type, converted_handler, byref(converted_user_handle)) handlers.append((handler, converted_user_handle, converted_handler)) return converted_user_handle def lock(vi, lock_type, timeout, requested_key = None): if lock_type == VI_EXCLUSIVE_LOCK: requested_key = None access_key = None else: access_key = create_string_buffer(256) visa_library().viLock(vi, lock_type, timeout, requested_key, access_key) return access_key def map_address(vi, map_space, map_base, map_size, access = VI_FALSE, suggested = VI_NULL): access = VI_FALSE address = ViAddr() visa_library().viMapAddress(vi, map_space, map_base, map_size, access, suggested, byref(address)) return address def map_trigger(vi, trigger_source, trigger_destination, mode): visa_library().viMapTrigger(vi, trigger_source, trigger_destination, mode) def memory_allocation(vi, size): offset = ViBusAddress() visa_library().viMemAlloc(vi, size, byref(offset)) return offset def memory_free(vi, offset): visa_library().viMemFree(vi, offset) def move(vi, source_space, source_offset, source_width, destination_space, destination_offset, destination_width, length): visa_library().viMove(vi, source_space, source_offset, source_width, destination_space, destination_offset, destination_width, length) def move_asynchronously(vi, source_space, source_offset, source_width, destination_space, destination_offset, destination_width, length): job_id = ViJobId() visa_library().viMoveAsync(vi, source_space, source_offset, source_width, destination_space, destination_offset, destination_width, length, byref(job_id)) return job_id def move_in_8(vi, space, offset, length): buffer_8 = (ViUInt8 * length)(); visa_library().viMoveIn8(vi, space, offset, length, buffer_8) return list(buffer_8) def move_in_16(vi, space, offset, length): buffer_16 = (ViUInt16 * length)(); visa_library().viMoveIn16(vi, space, offset, length, buffer_16) return list(buffer_16) def move_in_32(vi, space, offset, length): buffer_32 = (ViUInt32 * length)(); visa_library().viMoveIn32(vi, space, offset, length, buffer_32) return list(buffer_32) def move_out_8(vi, space, offset, length, buffer_8): converted_buffer = (ViUInt8 * length)(*tuple(buffer_8)) visa_library().viMoveOut8(vi, space, offset, length, converted_buffer) def move_out_16(vi, space, offset, length, buffer_16): converted_buffer = (ViUInt16 * length)(*tuple(buffer_16)) visa_library().viMoveOut16(vi, space, offset, length, converted_buffer) def move_out_32(vi, space, offset, length, buffer_16): converted_buffer = (ViUInt32 * length)(*tuple(buffer_32)) visa_library().viMoveOut32(vi, space, offset, length, converted_buffer) def open(session, resource_name, access_mode = VI_NO_LOCK, open_timeout = VI_TMO_IMMEDIATE): vi = ViSession() visa_library().viOpen(session, resource_name, access_mode, open_timeout, byref(vi)) return vi.value def open_default_resource_manager(): session = ViSession() visa_library().viOpenDefaultRM(byref(session)) return session.value get_default_resource_manager = open_default_resource_manager """A deprecated alias. See VPP-4.3, rule 4.3.5 and observation 4.3.2.""" def out_8(vi, space, offset, value_8): visa_library().viOut8(vi, space, offset, value_8) def out_16(vi, space, offset, value_16): visa_library().viOut16(vi, space, offset, value_16) def out_32(vi, space, offset, value_32): visa_library().viOut32(vi, space, offset, value_32) def parse_resource(session, resource_name): interface_type = ViUInt16() interface_board_number = ViUInt16() visa_library().viParseRsrc(session, resource_name, byref(interface_type), byref(interface_board_number)) return (interface_type.value, interface_board_number.value) def parse_resource_extended(session, resource_name): interface_type = ViUInt16() interface_board_number = ViUInt16() resource_class = create_string_buffer(VI_FIND_BUFLEN) unaliased_expanded_resource_name = create_string_buffer(VI_FIND_BUFLEN) alias_if_exists = create_string_buffer(VI_FIND_BUFLEN) visa_library().viParseRsrcEx(session, resource_name, byref(interface_type), byref(interface_board_number), resource_class, unaliased_expanded_resource_name, alias_if_exists) if alias_if_exists.value == "": alias_if_exists = None else: alias_if_exists = alias_if_exists.value return (interface_type.value, interface_board_number.value, resource_class.value, unaliased_expanded_resource_name.value, alias_if_exists) def peek_8(vi, address): value_8 = ViUInt8() visa_library().viPeek8(vi, address, byref(value_8)) return value_8.value def peek_16(vi, address): value_16 = ViUInt16() visa_library().viPeek16(vi, address, byref(value_16)) return value_16.value def peek_32(vi, address): value_32 = ViUInt32() visa_library().viPeek32(vi, address, byref(value_32)) return value_32.value def poke_8(vi, address, value_8): visa_library().viPoke8(vi, address, value_8) def poke_16(vi, address, value_16): visa_library().viPoke16(vi, address, value_16) def poke_32(vi, address, value_32): visa_library().viPoke32(vi, address, value_32) def printf(vi, write_format, *args): visa_library(force_cdecl=True).viPrintf(vi, write_format, *convert_argument_list(args)) def queryf(vi, write_format, read_format, write_args, *read_args, **keyw): maximal_string_length = keyw.get("maxmial_string_length", 1024) argument_list = list(convert_argument_list(read_args)) if write_args is None: write_args = () visa_library(force_cdecl=True) \ .viQueryf(vi, write_format, read_format, *(convert_argument_list(write_args) + convert_to_byref(argument_list, maximal_string_length))) return construct_return_tuple(argument_list) def read(vi, count): buffer = create_string_buffer(count) return_count = ViUInt32() visa_library().viRead(vi, buffer, count, byref(return_count)) return buffer.raw[:return_count.value] def read_asynchronously(vi, count): buffer = create_string_buffer(count) job_id = ViJobId() visa_library().viReadAsync(vi, buffer, count, byref(job_id)) return (buffer, job_id) def read_stb(vi): status = ViUInt16() visa_library().viReadSTB(vi, byref(status)) return status.value def read_to_file(vi, filename, count): return_count = ViUInt32() visa_library().viReadToFile(vi, filename, count, return_count) return return_count # FixMe: I have to test whether the results are really written to # "argument_list" rather than only to a local copy within "viScanf". def scanf(vi, read_format, *args, **keyw): maximal_string_length = keyw.get("maxmial_string_length", 1024) argument_list = list(convert_argument_list(args)) visa_library(force_cdecl=True) \ .viScanf(vi, read_format, *convert_to_byref(argument_list, maximal_string_length)) return construct_return_tuple(argument_list) def set_attribute(vi, attribute, attribute_state): visa_library().viSetAttribute(vi, attribute, attribute_state) def set_buffer(vi, mask, size): visa_library().viSetBuf(vi, mask, size) def sprintf(vi, write_format, *args, **keyw): buffer = create_string_buffer(keyw.get("buffer_length", 1024)) visa_library(force_cdecl=True).viSPrintf(vi, buffer, write_format, *convert_argument_list(args)) return buffer.raw def sscanf(vi, buffer, read_format, *args, **keyw): maximal_string_length = keyw.get("maxmial_string_length", 1024) argument_list = list(convert_argument_list(args)) visa_library(force_cdecl=True) \ .viSScanf(vi, buffer, read_format, *convert_to_byref(argument_list, maximal_string_length)) return construct_return_tuple(argument_list) def status_description(vi, status): description = create_string_buffer(256) visa_library().viStatusDesc(vi, status, description) return description.value def terminate(vi, degree, job_id): visa_library().viTerminate(vi, degree, job_id) def uninstall_handler(vi, event_type, handler, user_handle = None): for i in xrange(len(handlers)): element = handlers[i] if element[0] is handler and element[1] is user_handle: del handlers[i] break else: raise visa_exceptions.UnknownHandler visa_library().viUninstallHandler(vi, event_type, element[2], byref(element[1])) def unlock(vi): visa_library().viUnlock(vi) def unmap_address(vi): visa_library().viUnmapAddress(vi) def unmap_trigger(vi, trigger_source, trigger_destination): visa_library().viUnmapTrigger(vi, trigger_source, trigger_destination) def usb_control_in(vi, request_type_bitmap_field, request_id, request_value, index, length = 0): buffer = create_string_buffer(length) return_count = ViUInt16() visa_library().viUsbControlIn(vi, request_type_bitmap_field, request_id, request_value, index, length, buffer, byref(return_count)) return buffer.raw[:return_count.value] def usb_control_out(vi, request_type_bitmap_field, request_id, request_value, index, buffer = ""): length = len(buffer) visa_library().viUsbControlOut(vi, request_type_bitmap_field, request_id, request_value, index, length, buffer) # The following variants make no sense in Python, so I realise them as mere # aliases. vprintf = printf vqueryf = queryf vscanf = scanf vsprintf = sprintf vsscanf = sscanf def vxi_command_query(vi, mode, command): response = ViUInt32() visa_library().viVxiCommandQuery(vi, mode, command, byref(response)) return response.value def wait_on_event(vi, in_event_type, timeout): out_event_type = ViEventType() out_context = ViEvent() visa_library().viWaitOnEvent(vi, in_event_type, timeout, byref(out_event_type), byref(out_context)) return (out_event_type.value, out_context) def write(vi, buffer): return_count = ViUInt32() visa_library().viWrite(vi, buffer, len(buffer), byref(return_count)) return return_count.value def write_asynchronously(vi, buffer): job_id = ViJobId() visa_library().viWriteAsync(vi, buffer, len(buffer), byref(job_id)) return job_id def write_from_file(vi, filename, count): return_count = ViUInt32() visa_library().viWriteFromFile(vi, filename, count, return_count) return return_count PyVISA-1.4/src/vpp43_attributes.py0000644000175000017500000001602311734647057016416 0ustar floflo00000000000000#!/usr/bin/env python # -*- coding: utf-8 -*- # # vpp43_attributes.py - VISA VPP-4.3.2 attributes data # # Copyright © 2005, 2006, 2007, 2008 # Torsten Bronger , # Gregor Thalhammer . # # This file is part of PyVISA. # # PyVISA is free software; you can redistribute it and/or modify it under # the terms of the MIT licence: # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the "Software"), # to deal in the Software without restriction, including without limitation # the rights to use, copy, modify, merge, publish, distribute, sublicense, # and/or sell copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER # DEALINGS IN THE SOFTWARE. # __version__ = "$Revision: 334 $" # \$Source${}$\$ from vpp43_constants import * from vpp43_types import * attributes = { VI_ATTR_4882_COMPLIANT : ViBoolean, # VI_ATTR_ASRL_ALLOW_TRANSMIT VI_ATTR_ASRL_AVAIL_NUM : ViUInt32, VI_ATTR_ASRL_BAUD : ViUInt32, # VI_ATTR_ASRL_BREAK_LEN # VI_ATTR_ASRL_BREAK_STATE VI_ATTR_ASRL_CTS_STATE : ViInt16, VI_ATTR_ASRL_DATA_BITS : ViUInt16, VI_ATTR_ASRL_DCD_STATE : ViInt16, # VI_ATTR_ASRL_DISCARD_NULL VI_ATTR_ASRL_DSR_STATE : ViInt16, VI_ATTR_ASRL_DTR_STATE : ViInt16, VI_ATTR_ASRL_END_IN : ViUInt16, VI_ATTR_ASRL_END_OUT : ViUInt16, VI_ATTR_ASRL_FLOW_CNTRL : ViUInt16, VI_ATTR_ASRL_PARITY : ViUInt16, VI_ATTR_ASRL_REPLACE_CHAR : ViUInt8, VI_ATTR_ASRL_RI_STATE : ViInt16, VI_ATTR_ASRL_RTS_STATE : ViInt16, VI_ATTR_ASRL_STOP_BITS : ViUInt16, # VI_ATTR_ASRL_WIRE_MODE VI_ATTR_ASRL_XOFF_CHAR : ViUInt8, VI_ATTR_ASRL_XON_CHAR : ViUInt8, VI_ATTR_BUFFER : ViBuf, VI_ATTR_CMDR_LA : ViInt16, VI_ATTR_DEST_ACCESS_PRIV : ViUInt16, VI_ATTR_DEST_BYTE_ORDER : ViUInt16, VI_ATTR_DEST_INCREMENT : ViInt32, VI_ATTR_DEV_STATUS_BYTE : ViUInt8, VI_ATTR_DMA_ALLOW_EN : ViBoolean, VI_ATTR_EVENT_TYPE : ViEventType, VI_ATTR_FDC_CHNL : ViUInt16, VI_ATTR_FDC_GEN_SIGNAL_EN : None, VI_ATTR_FDC_MODE : ViUInt16, VI_ATTR_FDC_USE_PAIR : ViBoolean, VI_ATTR_FILE_APPEND_EN : ViBoolean, VI_ATTR_GPIB_ADDR_STATE : ViInt16, VI_ATTR_GPIB_ATN_STATE : ViInt16, VI_ATTR_GPIB_CIC_STATE : ViBoolean, VI_ATTR_GPIB_HS488_CBL_LEN : ViInt16, VI_ATTR_GPIB_NDAC_STATE : ViInt16, VI_ATTR_GPIB_PRIMARY_ADDR : ViUInt16, VI_ATTR_GPIB_READDR_EN : ViBoolean, VI_ATTR_GPIB_RECV_CIC_STATE : ViBoolean, VI_ATTR_GPIB_REN_STATE : ViInt16, VI_ATTR_GPIB_SECONDARY_ADDR : ViUInt16, VI_ATTR_GPIB_SRQ_STATE : ViInt16, VI_ATTR_GPIB_SYS_CNTRL_STATE : ViBoolean, VI_ATTR_GPIB_UNADDR_EN : ViBoolean, VI_ATTR_IMMEDIATE_SERV : ViBoolean, VI_ATTR_INTF_INST_NAME : ViString, VI_ATTR_INTF_NUM : ViUInt16, VI_ATTR_INTF_PARENT_NUM : ViUInt16, VI_ATTR_INTF_TYPE : ViUInt16, VI_ATTR_INTR_STATUS_ID : ViUInt32, VI_ATTR_IO_PROT : ViUInt16, VI_ATTR_JOB_ID : ViJobId, VI_ATTR_MAINFRAME_LA : ViInt16, VI_ATTR_MANF_ID : ViUInt16, VI_ATTR_MANF_NAME : ViString, VI_ATTR_MAX_QUEUE_LENGTH : ViUInt32, VI_ATTR_MEM_BASE : ViBusAddress, VI_ATTR_MEM_SIZE : ViBusSize, VI_ATTR_MEM_SPACE : ViUInt16, VI_ATTR_MODEL_CODE : ViUInt16, VI_ATTR_MODEL_NAME : ViString, VI_ATTR_OPER_NAME : ViString, # Many "PXI" attributes VI_ATTR_RD_BUF_OPER_MODE : ViUInt16, VI_ATTR_RD_BUF_SIZE : ViUInt32, VI_ATTR_RECV_INTR_LEVEL : ViInt16, VI_ATTR_RECV_TCPIP_ADDR : None, VI_ATTR_RECV_TRIG_ID : ViInt16, VI_ATTR_RET_COUNT : ViUInt32, VI_ATTR_RM_SESSION : ViSession, VI_ATTR_RSRC_CLASS : ViString, VI_ATTR_RSRC_IMPL_VERSION : ViVersion, VI_ATTR_RSRC_LOCK_STATE : ViAccessMode, VI_ATTR_RSRC_MANF_ID : ViUInt16, VI_ATTR_RSRC_MANF_NAME : ViString, VI_ATTR_RSRC_NAME : ViRsrc, VI_ATTR_RSRC_SPEC_VERSION : ViVersion, VI_ATTR_SEND_END_EN : ViBoolean, VI_ATTR_SIGP_STATUS_ID : ViUInt16, VI_ATTR_SLOT : ViInt16, VI_ATTR_SRC_ACCESS_PRIV : ViUInt16, VI_ATTR_SRC_BYTE_ORDER : ViUInt16, VI_ATTR_SRC_INCREMENT : ViInt32, VI_ATTR_STATUS : ViStatus, VI_ATTR_SUPPRESS_END_EN : ViBoolean, VI_ATTR_TCPIP_ADDR : ViString, VI_ATTR_TCPIP_DEVICE_NAME : ViString, VI_ATTR_TCPIP_HOSTNAME : ViString, VI_ATTR_TCPIP_KEEPALIVE : ViBoolean, VI_ATTR_TCPIP_NODELAY : ViBoolean, VI_ATTR_TCPIP_PORT : ViUInt16, VI_ATTR_TERMCHAR : ViUInt8, VI_ATTR_TERMCHAR_EN : ViBoolean, VI_ATTR_TMO_VALUE : ViUInt32, VI_ATTR_TRIG_ID : ViInt16, # VI_ATTR_USB_ALT_SETTING # VI_ATTR_USB_BULK_IN_PIPE # VI_ATTR_USB_BULK_IN_STATUS # VI_ATTR_USB_BULK_OUT_PIPE # VI_ATTR_USB_BULK_OUT_STATUS # VI_ATTR_USB_CLASS VI_ATTR_USB_INTFC_NUM : ViInt16, # VI_ATTR_USB_INTR_IN_PIPE # VI_ATTR_USB_INTR_IN_STATUS VI_ATTR_USB_MAX_INTR_SIZE : ViUInt16, # VI_ATTR_USB_NUM_INTFCS # VI_ATTR_USB_NUM_PIPES VI_ATTR_USB_PROTOCOL : ViInt16, VI_ATTR_USB_RECV_INTR_DATA : ViAUInt8, VI_ATTR_USB_RECV_INTR_SIZE : ViUInt16, VI_ATTR_USB_SERIAL_NUM : ViString, # VI_ATTR_USB_SUBCLASS VI_ATTR_USER_DATA : ViAddr, VI_ATTR_VXI_DEV_CLASS : ViUInt16, VI_ATTR_VXI_LA : ViInt16, VI_ATTR_VXI_TRIG_STATUS : ViUInt32, VI_ATTR_VXI_TRIG_SUPPORT : ViUInt32, VI_ATTR_VXI_VME_INTR_STATUS : ViUInt16, VI_ATTR_VXI_VME_SYSFAIL_STATE : ViInt16, VI_ATTR_WIN_ACCESS : ViUInt16, VI_ATTR_WIN_ACCESS_PRIV : ViUInt16, VI_ATTR_WIN_BASE_ADDR : ViBusAddress, VI_ATTR_WIN_BYTE_ORDER : ViUInt16, VI_ATTR_WIN_SIZE : ViBusSize, VI_ATTR_WR_BUF_OPER_MODE : ViUInt16, VI_ATTR_WR_BUF_SIZE : ViUInt32 } PyVISA-1.4/src/visa_exceptions.py0000644000175000017500000000745711734647057016412 0ustar floflo00000000000000#!/usr/bin/env python # -*- coding: utf-8 -*- # # visa_exceptions.py - Exceptions for the whole VISA package # # Copyright © 2005, 2006, 2007, 2008 # Torsten Bronger , # Gregor Thalhammer . # # This file is part of PyVISA. # # PyVISA is free software; you can redistribute it and/or modify it under # the terms of the MIT licence: # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the "Software"), # to deal in the Software without restriction, including without limitation # the rights to use, copy, modify, merge, publish, distribute, sublicense, # and/or sell copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER # DEALINGS IN THE SOFTWARE. # __version__ = "$Revision: 334 $" # $Source$ from visa_messages import completion_and_error_messages \ as _completion_and_error_messages class Error(Exception): """Abstract basic exception class for this module.""" def __init__(self, description): Exception.__init__(self, description) class VisaIOError(Error): """Exception class for VISA I/O errors. Please note that all values for "error_code" are negative according to the specification (VPP-4.3.2, observation 3.3.2) and the NI implementation. """ def __init__(self, error_code): abbreviation, description = _completion_and_error_messages[error_code] Error.__init__(self, abbreviation + ": " + description) self.error_code = error_code class VisaIOWarning(Warning): """Exception class for VISA I/O warnings. According to the specification VPP-4.3.2 and the NI implementation. """ def __init__(self, description): Warning.__init__(self, description) class VisaTypeError(Error): """Exception class for wrong types in VISA function argument lists. Raised if unsupported types are given to scanf, sscanf, printf, sprintf, and queryf. Because the current implementation doesn't analyse the format strings, it can only deal with integers, floats, and strings. Additionally, this exception is raised by install_handler if un unsupported type is used for the user handle. """ def __init__(self, description): Error.__init__(self, description) class UnknownHandler(Error): """Exception class for invalid handler data given to uninstall_handler(). uninstall_handler() checks whether the handler and user_data parameters point to a known handler previously installed with install_handler(). If it can't find it, this exception is raised. """ def __init__(self): Error.__init__(self, "Handler with this handler function and user data" " not found") class OSNotSupported(Error): def __init__(self, os): Error.__init__(self, os + " is not yet supported by PyVISA") class InvalidBinaryFormat(Error): def __init__(self, description = ""): if description: description = ": " + description Error.__init__(self, "unrecognized binary data format" + description) PyVISA-1.4/src/__init__.py0000644000175000017500000000363511734647057014740 0ustar floflo00000000000000#!/usr/bin/env python # -*- coding: utf-8 -*- # # __init__.py - PyVISA's package initialisation. # # Copyright © 2005, 2006, 2007, 2008 # Torsten Bronger , # Gregor Thalhammer . # # This file is part of PyVISA. # # PyVISA is free software; you can redistribute it and/or modify it under # the terms of the MIT licence: # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the "Software"), # to deal in the Software without restriction, including without limitation # the rights to use, copy, modify, merge, publish, distribute, sublicense, # and/or sell copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER # DEALINGS IN THE SOFTWARE. # import ConfigParser, os, sys import vpp43 _config_parser = ConfigParser.SafeConfigParser() _config_parser.read([os.path.join(sys.prefix, "share", "pyvisa", ".pyvisarc"), os.path.join(os.path.expanduser("~"), ".pyvisarc")]) try: _visa_library_path = _config_parser.get("Paths", "visa library") except ConfigParser.Error: pass else: vpp43.visa_library.load_library(_visa_library_path) PyVISA-1.4/src/visa_messages.py0000644000175000017500000005523311734647057016033 0ustar floflo00000000000000#!/usr/bin/env python # -*- coding: utf-8 -*- # # visa_messages.py - VISA completion and error messages # # Copyright © 2005, 2006, 2007, 2008 # Torsten Bronger , # Gregor Thalhammer . # # This file is part of PyVISA. # # PyVISA is free software; you can redistribute it and/or modify it under # the terms of the MIT licence: # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the "Software"), # to deal in the Software without restriction, including without limitation # the rights to use, copy, modify, merge, publish, distribute, sublicense, # and/or sell copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER # DEALINGS IN THE SOFTWARE. # """Textual explanations of VISA completion and error codes. The only export is "completion_and_error_messages", which is a dictionary that binds every completion and error value to its name and a short textual description (both in a two-elements tuple). """ __version__ = "$Revision: 334 $" # $Source$ from vpp43_constants import * # Don't export the VPP-4.3 constants, but only the messages. __all__ = ("completion_and_error_messages",) completion_and_error_messages = { VI_SUCCESS : ("VI_SUCCESS", "Operation completed successfully."), VI_SUCCESS_EVENT_EN : ("VI_SUCCESS_EVENT_EN", "Specified event is already enabled for at "\ "least one of the specified mechanisms."), VI_SUCCESS_EVENT_DIS : ("VI_SUCCESS_EVENT_DIS", "Specified event is already disabled for "\ "at least one of the specified mechanisms."), VI_SUCCESS_QUEUE_EMPTY : ("VI_SUCCESS_QUEUE_EMPTY", "Operation completed successfully, but "\ "queue was already empty."), VI_SUCCESS_TERM_CHAR : ("VI_SUCCESS_TERM_CHAR", "The specified termination character was "\ "read."), VI_SUCCESS_MAX_CNT : ("VI_SUCCESS_MAX_CNT", "The number of bytes transferred is equal "\ "to the requested input count. More data "\ "may be available."), VI_SUCCESS_DEV_NPRESENT : ("VI_SUCCESS_DEV_NPRESENT", "Session opened successfully, but the "\ "device at the specified address is not "\ "responding."), VI_SUCCESS_TRIG_MAPPED : ("VI_SUCCESS_TRIG_MAPPED", "The path from trigSrc to trigDest is "\ "already mapped."), VI_SUCCESS_QUEUE_NEMPTY : ("VI_SUCCESS_QUEUE_NEMPTY", "Wait terminated successfully on receipt "\ "of an event notification. There is at "\ "least one more event object of the "\ "requested type(s) available for this "\ "session."), VI_SUCCESS_NCHAIN : ("VI_SUCCESS_NCHAIN", "Event handled successfully. Do not invoke "\ "any other handlers on this session for "\ "this event."), VI_SUCCESS_NESTED_SHARED : ("VI_SUCCESS_NESTED_SHARED", "Operation completed successfully, and "\ "this session has nested shared locks."), VI_SUCCESS_NESTED_EXCLUSIVE: ("VI_SUCCESS_NESTED_EXCLUSIVE", "Operation completed successfully, and "\ "this session has nested exclusive locks."), VI_SUCCESS_SYNC : ("VI_SUCCESS_SYNC", "Operation completed successfully, but the "\ "operation was actually synchronous rather "\ "than asynchronous."), VI_WARN_QUEUE_OVERFLOW : ("VI_WARN_QUEUE_OVERFLOW", "VISA received more event information of "\ "the specified type than the configured "\ "queue size could hold."), VI_WARN_CONFIG_NLOADED : ("VI_WARN_CONFIG_NLOADED", "The specified configuration either does "\ "not exist or could not be loaded. "\ "VISA-specified defaults will be used."), VI_WARN_NULL_OBJECT : ("VI_WARN_NULL_OBJECT", "The specified object reference is "\ "uninitialized."), VI_WARN_NSUP_ATTR_STATE : ("VI_WARN_NSUP_ATTR_STATE", "Although the specified state of the "\ "attribute is valid, it is not supported "\ "by this implementation."), VI_WARN_UNKNOWN_STATUS : ("VI_WARN_UNKNOWN_STATUS", "The status code passed to the operation "\ "could not be interpreted."), VI_WARN_NSUP_BUF : ("VI_WARN_NSUP_BUF", "The specified I/O buffer type is not "\ "supported."), VI_WARN_EXT_FUNC_NIMPL : ("VI_WARN_EXT_FUNC_NIMPL", "The operation succeeded, but a lower "\ "level driver did not implement the "\ "extended functionality."), VI_ERROR_SYSTEM_ERROR : ("VI_ERROR_SYSTEM_ERROR", "Unknown system error (miscellaneous "\ "error)."), VI_ERROR_INV_OBJECT : ("VI_ERROR_INV_OBJECT", "The given session or object reference is "\ "invalid."), VI_ERROR_RSRC_LOCKED : ("VI_ERROR_RSRC_LOCKED", "Specified type of lock cannot be "\ "obtained, or specified operation cannot "\ "be performed, because the resource is "\ "locked."), VI_ERROR_INV_EXPR : ("VI_ERROR_INV_EXPR", "Invalid expression specified for search."), VI_ERROR_RSRC_NFOUND : ("VI_ERROR_RSRC_NFOUND", "Insufficient location information or the "\ "requested device or resource is not "\ "present in the system."), VI_ERROR_INV_RSRC_NAME : ("VI_ERROR_INV_RSRC_NAME", "Invalid resource reference specified. "\ "Parsing error."), VI_ERROR_INV_ACC_MODE : ("VI_ERROR_INV_ACC_MODE", "Invalid access mode."), VI_ERROR_TMO : ("VI_ERROR_TMO", "Timeout expired before operation "\ "completed."), VI_ERROR_CLOSING_FAILED : ("VI_ERROR_CLOSING_FAILED", "The VISA driver failed to properly close "\ "the session or object reference. This "\ "might be due to an error freeing internal "\ "or OS resources, a failed network "\ "connection, or a lower-level driver or OS "\ "error."), VI_ERROR_INV_DEGREE : ("VI_ERROR_INV_DEGREE", "Specified degree is invalid."), VI_ERROR_INV_JOB_ID : ("VI_ERROR_INV_JOB_ID", "Specified job identifier is invalid."), VI_ERROR_NSUP_ATTR : ("VI_ERROR_NSUP_ATTR", "The specified attribute is not defined or "\ "supported by the referenced object."), VI_ERROR_NSUP_ATTR_STATE : ("VI_ERROR_NSUP_ATTR_STATE", "The specified state of the attribute is "\ "not valid, or is not supported as defined "\ "by the object."), VI_ERROR_ATTR_READONLY : ("VI_ERROR_ATTR_READONLY", "The specified attribute is read-only."), VI_ERROR_INV_LOCK_TYPE : ("VI_ERROR_INV_LOCK_TYPE", "The specified type of lock is not "\ "supported by this resource."), VI_ERROR_INV_ACCESS_KEY : ("VI_ERROR_INV_ACCESS_KEY", "The access key to the resource associated "\ "with the specified session is invalid."), VI_ERROR_INV_EVENT : ("VI_ERROR_INV_EVENT", "Specified event type is not supported by "\ "the resource."), VI_ERROR_INV_MECH : ("VI_ERROR_INV_MECH", "Invalid mechanism specified."), VI_ERROR_HNDLR_NINSTALLED : ("VI_ERROR_HNDLR_NINSTALLED", "A handler was not installed."), VI_ERROR_INV_HNDLR_REF : ("VI_ERROR_INV_HNDLR_REF", "The given handler reference is either "\ "invalid or was not installed."), VI_ERROR_INV_CONTEXT : ("VI_ERROR_INV_CONTEXT", "Specified event context is invalid."), VI_ERROR_QUEUE_OVERFLOW : ("VI_ERROR_QUEUE_OVERFLOW", "The event queue for the specified type "\ "has overflowed (usually due to previous "\ "events not having been closed)."), VI_ERROR_NENABLED : ("VI_ERROR_NENABLED", "You must be enabled for events of the "\ "specified type in order to receive them."), VI_ERROR_ABORT : ("VI_ERROR_ABORT", "User abort occurred during transfer."), VI_ERROR_RAW_WR_PROT_VIOL : ("VI_ERROR_RAW_WR_PROT_VIOL", "Violation of raw write protocol occurred "\ "during transfer."), VI_ERROR_RAW_RD_PROT_VIOL : ("VI_ERROR_RAW_RD_PROT_VIOL", "Violation of raw read protocol occurred "\ "during transfer."), VI_ERROR_OUTP_PROT_VIOL : ("VI_ERROR_OUTP_PROT_VIOL", "Device reported an output protocol error "\ "during transfer."), VI_ERROR_INP_PROT_VIOL : ("VI_ERROR_INP_PROT_VIOL", "Device reported an input protocol error "\ "during transfer."), VI_ERROR_BERR : ("VI_ERROR_BERR", "Bus error occurred during transfer."), VI_ERROR_IN_PROGRESS : ("VI_ERROR_IN_PROGRESS", "Unable to queue the asynchronous "\ "operation because there is already an "\ "operation in progress."), VI_ERROR_INV_SETUP : ("VI_ERROR_INV_SETUP", "Unable to start operation because setup "\ "is invalid (usually due to attributes "\ "being set to an inconsistent state)."), VI_ERROR_QUEUE_ERROR : ("VI_ERROR_QUEUE_ERROR", "Unable to queue the asynchronous "\ "operation (usually due to the I/O "\ "completion event not being enabled or "\ "insufficient space in the session's "\ "queue)."), VI_ERROR_ALLOC : ("VI_ERROR_ALLOC", "Insufficient system resources to perform "\ "necessary memory allocation."), VI_ERROR_INV_MASK : ("VI_ERROR_INV_MASK", "Invalid buffer mask specified."), VI_ERROR_IO : ("VI_ERROR_IO", "Could not perform operation because of "\ "I/O error."), VI_ERROR_INV_FMT : ("VI_ERROR_INV_FMT", "A format specifier in the format string "\ "is invalid."), VI_ERROR_NSUP_FMT : ("VI_ERROR_NSUP_FMT", "A format specifier in the format string "\ "is not supported."), VI_ERROR_LINE_IN_USE : ("VI_ERROR_LINE_IN_USE", "The specified trigger line is currently "\ "in use."), VI_ERROR_NSUP_MODE : ("VI_ERROR_NSUP_MODE", "The specified mode is not supported by "\ "this VISA implementation."), VI_ERROR_SRQ_NOCCURRED : ("VI_ERROR_SRQ_NOCCURRED", "Service request has not been received for "\ "the session."), VI_ERROR_INV_SPACE : ("VI_ERROR_INV_SPACE", "Invalid address space specified."), VI_ERROR_INV_OFFSET : ("VI_ERROR_INV_OFFSET", "Invalid offset specified."), VI_ERROR_INV_WIDTH : ("VI_ERROR_INV_WIDTH", "Invalid access width specified."), VI_ERROR_NSUP_OFFSET : ("VI_ERROR_NSUP_OFFSET", "Specified offset is not accessible from "\ "this hardware."), VI_ERROR_NSUP_VAR_WIDTH : ("VI_ERROR_NSUP_VAR_WIDTH", "Cannot support source and destination "\ "widths that are different."), VI_ERROR_WINDOW_NMAPPED : ("VI_ERROR_WINDOW_NMAPPED", "The specified session is not currently "\ "mapped."), VI_ERROR_RESP_PENDING : ("VI_ERROR_RESP_PENDING", "A previous response is still pending, "\ "causing a multiple query error."), VI_ERROR_NLISTENERS : ("VI_ERROR_NLISTENERS", "No listeners condition is detected (both "\ "NRFD and NDAC are deasserted)."), VI_ERROR_NCIC : ("VI_ERROR_NCIC", "The interface associated with this "\ "session is not currently the controller "\ "in charge."), VI_ERROR_NSYS_CNTLR : ("VI_ERROR_NSYS_CNTLR", "The interface associated with this "\ "session is not the system controller."), VI_ERROR_NSUP_OPER : ("VI_ERROR_NSUP_OPER", "The given session or object reference "\ "does not support this operation."), VI_ERROR_INTR_PENDING : ("VI_ERROR_INTR_PENDING", "An interrupt is still pending from a "\ "previous call."), VI_ERROR_ASRL_PARITY : ("VI_ERROR_ASRL_PARITY", "A parity error occurred during transfer."), VI_ERROR_ASRL_FRAMING : ("VI_ERROR_ASRL_FRAMING", "A framing error occurred during transfer."), VI_ERROR_ASRL_OVERRUN : ("VI_ERROR_ASRL_OVERRUN", "An overrun error occurred during "\ "transfer. A character was not read from "\ "the hardware before the next character "\ "arrived."), VI_ERROR_TRIG_NMAPPED : ("VI_ERROR_TRIG_NMAPPED", "The path from trigSrc to trigDest is not "\ "currently mapped."), VI_ERROR_NSUP_ALIGN_OFFSET : ("VI_ERROR_NSUP_ALIGN_OFFSET", "The specified offset is not properly "\ "aligned for the access width of the "\ "operation."), VI_ERROR_USER_BUF : ("VI_ERROR_USER_BUF", "A specified user buffer is not valid or "\ "cannot be accessed for the required size."), VI_ERROR_RSRC_BUSY : ("VI_ERROR_RSRC_BUSY", "The resource is valid, but VISA cannot "\ "currently access it."), VI_ERROR_NSUP_WIDTH : ("VI_ERROR_NSUP_WIDTH", "Specified width is not supported by this "\ "hardware."), VI_ERROR_INV_PARAMETER : ("VI_ERROR_INV_PARAMETER", "The value of some parameter (which "\ "parameter is not known) is invalid."), VI_ERROR_INV_PROT : ("VI_ERROR_INV_PROT", "The protocol specified is invalid."), VI_ERROR_INV_SIZE : ("VI_ERROR_INV_SIZE", "Invalid size of window specified."), VI_ERROR_WINDOW_MAPPED : ("VI_ERROR_WINDOW_MAPPED", "The specified session currently contains "\ "a mapped window."), VI_ERROR_NIMPL_OPER : ("VI_ERROR_NIMPL_OPER", "The given operation is not implemented."), VI_ERROR_INV_LENGTH : ("VI_ERROR_INV_LENGTH", "Invalid length specified."), VI_ERROR_INV_MODE : ("VI_ERROR_INV_MODE", "Invalid mode specified."), VI_ERROR_SESN_NLOCKED : ("VI_ERROR_SESN_NLOCKED", "The current session did not have a lock "\ "on the resource."), VI_ERROR_MEM_NSHARED : ("VI_ERROR_MEM_NSHARED", "The device does not export any memory."), VI_ERROR_LIBRARY_NFOUND : ("VI_ERROR_LIBRARY_NFOUND", "A code library required by VISA could not "\ "be located or loaded."), VI_ERROR_NSUP_INTR : ("VI_ERROR_NSUP_INTR", "The interface cannot generate an "\ "interrupt on the requested level or with "\ "the requested statusID value."), VI_ERROR_INV_LINE : ("VI_ERROR_INV_LINE", "The value specified by the line parameter "\ "is invalid."), VI_ERROR_FILE_ACCESS : ("VI_ERROR_FILE_ACCESS", "An error occurred while trying to open "\ "the specified file. Possible reasons "\ "include an invalid path or lack of access "\ "rights."), VI_ERROR_FILE_IO : ("VI_ERROR_FILE_IO", "An error occurred while performing I/O on "\ "the specified file."), VI_ERROR_NSUP_LINE : ("VI_ERROR_NSUP_LINE", "One of the specified lines (trigSrc or "\ "trigDest) is not supported by this VISA "\ "implementation, or the combination of "\ "lines is not a valid mapping."), VI_ERROR_NSUP_MECH : ("VI_ERROR_NSUP_MECH", "The specified mechanism is not supported "\ "for the given event type."), VI_ERROR_INTF_NUM_NCONFIG : ("VI_ERROR_INTF_NUM_NCONFIG", "The interface type is valid but the "\ "specified interface number is not "\ "configured."), VI_ERROR_CONN_LOST : ("VI_ERROR_CONN_LOST", "The connection for the given session has "\ "been lost."), VI_ERROR_MACHINE_NAVAIL : ("VI_ERROR_MACHINE_NAVAIL", "The remote machine does not exist or is "\ "not accepting any connections. If the "\ "NI-VISA server is installed and running "\ "on the remote machine, it may have an "\ "incompatible version or may be listening "\ "on a different port."), VI_ERROR_NPERMISSION : ("VI_ERROR_NPERMISSION", "Access to the resource or remote machine "\ "is denied. This is due to lack of "\ "sufficient privileges for the current "\ "user or machine") } """A dictionary that holds the name and a short description of all completion and error codes in the VISA specification. The name and the description are strings in a tupel. """ PyVISA-1.4/src/.cvsignore0000644000175000017500000000000611734647057014614 0ustar floflo00000000000000*.pyc PyVISA-1.4/MANIFEST.in0000644000175000017500000000016311734647057013567 0ustar floflo00000000000000include ChangeLog COPYING MANIFEST MANIFEST.in include doc/*.css doc/*.txt doc/LICENSE doc/pyvisa.tex doc/Makefile PyVISA-1.4/PyVISA.egg-info/0000775000175000017500000000000011754013232014560 5ustar floflo00000000000000PyVISA-1.4/PyVISA.egg-info/PKG-INFO0000644000175000017500000000220611754013231015652 0ustar floflo00000000000000Metadata-Version: 1.0 Name: PyVISA Version: 1.4 Summary: Python VISA bindings for GPIB, RS232, and USB instruments Home-page: http://pyvisa.sourceforge.net Author: Torsten Bronger, Gregor Thalhammer Author-email: pyvisa-devel@lists.sourceforge.net License: MIT License Download-URL: http://sourceforge.net/projects/pyvisa/ Description: A Python package for support of the Virtual Instrument Software Architecture (VISA), in order to control measurement devices and test equipment via GPIB, RS232, or USB. Homepage: http://pyvisa.sourceforge.net Keywords: VISA GPIB USB serial RS232 measurement acquisition Platform: Linux Platform: Windows Classifier: Development Status :: 5 - Production/Stable Classifier: Intended Audience :: Developers Classifier: Intended Audience :: Science/Research Classifier: License :: OSI Approved :: MIT License Classifier: Operating System :: Microsoft :: Windows Classifier: Operating System :: POSIX :: Linux Classifier: Programming Language :: Python Classifier: Topic :: Scientific/Engineering :: Interface Engine/Protocol Translator Classifier: Topic :: Software Development :: Libraries :: Python Modules PyVISA-1.4/PyVISA.egg-info/top_level.txt0000644000175000017500000000001411754013231017302 0ustar floflo00000000000000visa pyvisa PyVISA-1.4/PyVISA.egg-info/dependency_links.txt0000644000175000017500000000000111754013231020623 0ustar floflo00000000000000 PyVISA-1.4/PyVISA.egg-info/SOURCES.txt0000644000175000017500000000123411754013232016442 0ustar floflo00000000000000.coverage .cvsignore COPYING ChangeLog MANIFEST.in README distribute_setup.py setup.cfg setup.py tox.ini visa.py PyVISA.egg-info/PKG-INFO PyVISA.egg-info/SOURCES.txt PyVISA.egg-info/dependency_links.txt PyVISA.egg-info/top_level.txt doc/.cvsignore doc/LICENSE doc/Makefile doc/conf.py doc/default.css doc/index.txt doc/make.bat doc/pyvisa.tex doc/pyvisa.txt doc/vpp43.txt src/.cvsignore src/__init__.py src/visa.py src/visa_attributes.py src/visa_exceptions.py src/visa_messages.py src/visa_study.py src/vpp43.py src/vpp43_attributes.py src/vpp43_constants.py src/vpp43_types.py test/conftest.py test/test_itc4.py test/test_keithley2000.py test/test_visa_attributes.pyPyVISA-1.4/tox.ini0000664000175000017500000000022111754012547013331 0ustar floflo00000000000000[tox] envlist = py26,py27,py32 [testenv] deps= pytest sphinx mock commands= {envpython} distribute_setup.py py.test PyVISA-1.4/README0000644000175000017500000000114611734647057012713 0ustar floflo00000000000000Python package 'PyVISA' A Python package for support of the "Virtual Instrument Software Architecture" (VISA), in order to control measurement devices and test equipment via GPIB, RS232, Ethernet or USB. * Prerequisites: - VISA (tested with NI-VISA 3.2, WinXP, from www.ni.com/visa) - ctypes (tested with 0.9.2, 0.9.5) - Python (tested with 2.3, 2.4) * Installation: unzip source distribution file > python setup.py install * Description See examples in directory test/ and documentation in doc/. A detailed specification of VISA can be found at http://www.ivifoundation.org/Downloads/Specifications.htm PyVISA-1.4/.coverage0000664000175000017500000000006211754013036013607 0ustar floflo00000000000000€}q(U collectorqUcoverage v3.5.2qUlinesq}u.PyVISA-1.4/distribute_setup.py0000664000175000017500000003737211753735276016021 0ustar floflo00000000000000#!python """Bootstrap distribute installation If you want to use setuptools in your package's setup.py, just include this file in the same directory with it, and add this to the top of your setup.py:: from distribute_setup import use_setuptools use_setuptools() If you want to require a specific version of setuptools, set a download mirror, or use an alternate download directory, you can do so by supplying the appropriate options to ``use_setuptools()``. This file can also be run as a script to install or upgrade setuptools. """ import os import sys import time import fnmatch import tempfile import tarfile from distutils import log try: from site import USER_SITE except ImportError: USER_SITE = None try: import subprocess def _python_cmd(*args): args = (sys.executable,) + args return subprocess.call(args) == 0 except ImportError: # will be used for python 2.3 def _python_cmd(*args): args = (sys.executable,) + args # quoting arguments if windows if sys.platform == 'win32': def quote(arg): if ' ' in arg: return '"%s"' % arg return arg args = [quote(arg) for arg in args] return os.spawnl(os.P_WAIT, sys.executable, *args) == 0 DEFAULT_VERSION = "0.6.26" DEFAULT_URL = "http://pypi.python.org/packages/source/d/distribute/" SETUPTOOLS_FAKED_VERSION = "0.6c11" SETUPTOOLS_PKG_INFO = """\ Metadata-Version: 1.0 Name: setuptools Version: %s Summary: xxxx Home-page: xxx Author: xxx Author-email: xxx License: xxx Description: xxx """ % SETUPTOOLS_FAKED_VERSION def _install(tarball, install_args=()): # extracting the tarball tmpdir = tempfile.mkdtemp() log.warn('Extracting in %s', tmpdir) old_wd = os.getcwd() try: os.chdir(tmpdir) tar = tarfile.open(tarball) _extractall(tar) tar.close() # going in the directory subdir = os.path.join(tmpdir, os.listdir(tmpdir)[0]) os.chdir(subdir) log.warn('Now working in %s', subdir) # installing log.warn('Installing Distribute') if not _python_cmd('setup.py', 'install', *install_args): log.warn('Something went wrong during the installation.') log.warn('See the error message above.') finally: os.chdir(old_wd) def _build_egg(egg, tarball, to_dir): # extracting the tarball tmpdir = tempfile.mkdtemp() log.warn('Extracting in %s', tmpdir) old_wd = os.getcwd() try: os.chdir(tmpdir) tar = tarfile.open(tarball) _extractall(tar) tar.close() # going in the directory subdir = os.path.join(tmpdir, os.listdir(tmpdir)[0]) os.chdir(subdir) log.warn('Now working in %s', subdir) # building an egg log.warn('Building a Distribute egg in %s', to_dir) _python_cmd('setup.py', '-q', 'bdist_egg', '--dist-dir', to_dir) finally: os.chdir(old_wd) # returning the result log.warn(egg) if not os.path.exists(egg): raise IOError('Could not build the egg.') def _do_download(version, download_base, to_dir, download_delay): egg = os.path.join(to_dir, 'distribute-%s-py%d.%d.egg' % (version, sys.version_info[0], sys.version_info[1])) if not os.path.exists(egg): tarball = download_setuptools(version, download_base, to_dir, download_delay) _build_egg(egg, tarball, to_dir) sys.path.insert(0, egg) import setuptools setuptools.bootstrap_install_from = egg def use_setuptools(version=DEFAULT_VERSION, download_base=DEFAULT_URL, to_dir=os.curdir, download_delay=15, no_fake=True): # making sure we use the absolute path to_dir = os.path.abspath(to_dir) was_imported = 'pkg_resources' in sys.modules or \ 'setuptools' in sys.modules try: try: import pkg_resources if not hasattr(pkg_resources, '_distribute'): if not no_fake: _fake_setuptools() raise ImportError except ImportError: return _do_download(version, download_base, to_dir, download_delay) try: pkg_resources.require("distribute>="+version) return except pkg_resources.VersionConflict: e = sys.exc_info()[1] if was_imported: sys.stderr.write( "The required version of distribute (>=%s) is not available,\n" "and can't be installed while this script is running. Please\n" "install a more recent version first, using\n" "'easy_install -U distribute'." "\n\n(Currently using %r)\n" % (version, e.args[0])) sys.exit(2) else: del pkg_resources, sys.modules['pkg_resources'] # reload ok return _do_download(version, download_base, to_dir, download_delay) except pkg_resources.DistributionNotFound: return _do_download(version, download_base, to_dir, download_delay) finally: if not no_fake: _create_fake_setuptools_pkg_info(to_dir) def download_setuptools(version=DEFAULT_VERSION, download_base=DEFAULT_URL, to_dir=os.curdir, delay=15): """Download distribute from a specified location and return its filename `version` should be a valid distribute version number that is available as an egg for download under the `download_base` URL (which should end with a '/'). `to_dir` is the directory where the egg will be downloaded. `delay` is the number of seconds to pause before an actual download attempt. """ # making sure we use the absolute path to_dir = os.path.abspath(to_dir) try: from urllib.request import urlopen except ImportError: from urllib2 import urlopen tgz_name = "distribute-%s.tar.gz" % version url = download_base + tgz_name saveto = os.path.join(to_dir, tgz_name) src = dst = None if not os.path.exists(saveto): # Avoid repeated downloads try: log.warn("Downloading %s", url) src = urlopen(url) # Read/write all in one block, so we don't create a corrupt file # if the download is interrupted. data = src.read() dst = open(saveto, "wb") dst.write(data) finally: if src: src.close() if dst: dst.close() return os.path.realpath(saveto) def _no_sandbox(function): def __no_sandbox(*args, **kw): try: from setuptools.sandbox import DirectorySandbox if not hasattr(DirectorySandbox, '_old'): def violation(*args): pass DirectorySandbox._old = DirectorySandbox._violation DirectorySandbox._violation = violation patched = True else: patched = False except ImportError: patched = False try: return function(*args, **kw) finally: if patched: DirectorySandbox._violation = DirectorySandbox._old del DirectorySandbox._old return __no_sandbox def _patch_file(path, content): """Will backup the file then patch it""" existing_content = open(path).read() if existing_content == content: # already patched log.warn('Already patched.') return False log.warn('Patching...') _rename_path(path) f = open(path, 'w') try: f.write(content) finally: f.close() return True _patch_file = _no_sandbox(_patch_file) def _same_content(path, content): return open(path).read() == content def _rename_path(path): new_name = path + '.OLD.%s' % time.time() log.warn('Renaming %s into %s', path, new_name) os.rename(path, new_name) return new_name def _remove_flat_installation(placeholder): if not os.path.isdir(placeholder): log.warn('Unkown installation at %s', placeholder) return False found = False for file in os.listdir(placeholder): if fnmatch.fnmatch(file, 'setuptools*.egg-info'): found = True break if not found: log.warn('Could not locate setuptools*.egg-info') return log.warn('Removing elements out of the way...') pkg_info = os.path.join(placeholder, file) if os.path.isdir(pkg_info): patched = _patch_egg_dir(pkg_info) else: patched = _patch_file(pkg_info, SETUPTOOLS_PKG_INFO) if not patched: log.warn('%s already patched.', pkg_info) return False # now let's move the files out of the way for element in ('setuptools', 'pkg_resources.py', 'site.py'): element = os.path.join(placeholder, element) if os.path.exists(element): _rename_path(element) else: log.warn('Could not find the %s element of the ' 'Setuptools distribution', element) return True _remove_flat_installation = _no_sandbox(_remove_flat_installation) def _after_install(dist): log.warn('After install bootstrap.') placeholder = dist.get_command_obj('install').install_purelib _create_fake_setuptools_pkg_info(placeholder) def _create_fake_setuptools_pkg_info(placeholder): if not placeholder or not os.path.exists(placeholder): log.warn('Could not find the install location') return pyver = '%s.%s' % (sys.version_info[0], sys.version_info[1]) setuptools_file = 'setuptools-%s-py%s.egg-info' % \ (SETUPTOOLS_FAKED_VERSION, pyver) pkg_info = os.path.join(placeholder, setuptools_file) if os.path.exists(pkg_info): log.warn('%s already exists', pkg_info) return log.warn('Creating %s', pkg_info) f = open(pkg_info, 'w') try: f.write(SETUPTOOLS_PKG_INFO) finally: f.close() pth_file = os.path.join(placeholder, 'setuptools.pth') log.warn('Creating %s', pth_file) f = open(pth_file, 'w') try: f.write(os.path.join(os.curdir, setuptools_file)) finally: f.close() _create_fake_setuptools_pkg_info = _no_sandbox(_create_fake_setuptools_pkg_info) def _patch_egg_dir(path): # let's check if it's already patched pkg_info = os.path.join(path, 'EGG-INFO', 'PKG-INFO') if os.path.exists(pkg_info): if _same_content(pkg_info, SETUPTOOLS_PKG_INFO): log.warn('%s already patched.', pkg_info) return False _rename_path(path) os.mkdir(path) os.mkdir(os.path.join(path, 'EGG-INFO')) pkg_info = os.path.join(path, 'EGG-INFO', 'PKG-INFO') f = open(pkg_info, 'w') try: f.write(SETUPTOOLS_PKG_INFO) finally: f.close() return True _patch_egg_dir = _no_sandbox(_patch_egg_dir) def _before_install(): log.warn('Before install bootstrap.') _fake_setuptools() def _under_prefix(location): if 'install' not in sys.argv: return True args = sys.argv[sys.argv.index('install')+1:] for index, arg in enumerate(args): for option in ('--root', '--prefix'): if arg.startswith('%s=' % option): top_dir = arg.split('root=')[-1] return location.startswith(top_dir) elif arg == option: if len(args) > index: top_dir = args[index+1] return location.startswith(top_dir) if arg == '--user' and USER_SITE is not None: return location.startswith(USER_SITE) return True def _fake_setuptools(): log.warn('Scanning installed packages') try: import pkg_resources except ImportError: # we're cool log.warn('Setuptools or Distribute does not seem to be installed.') return ws = pkg_resources.working_set try: setuptools_dist = ws.find(pkg_resources.Requirement.parse('setuptools', replacement=False)) except TypeError: # old distribute API setuptools_dist = ws.find(pkg_resources.Requirement.parse('setuptools')) if setuptools_dist is None: log.warn('No setuptools distribution found') return # detecting if it was already faked setuptools_location = setuptools_dist.location log.warn('Setuptools installation detected at %s', setuptools_location) # if --root or --preix was provided, and if # setuptools is not located in them, we don't patch it if not _under_prefix(setuptools_location): log.warn('Not patching, --root or --prefix is installing Distribute' ' in another location') return # let's see if its an egg if not setuptools_location.endswith('.egg'): log.warn('Non-egg installation') res = _remove_flat_installation(setuptools_location) if not res: return else: log.warn('Egg installation') pkg_info = os.path.join(setuptools_location, 'EGG-INFO', 'PKG-INFO') if (os.path.exists(pkg_info) and _same_content(pkg_info, SETUPTOOLS_PKG_INFO)): log.warn('Already patched.') return log.warn('Patching...') # let's create a fake egg replacing setuptools one res = _patch_egg_dir(setuptools_location) if not res: return log.warn('Patched done.') _relaunch() def _relaunch(): log.warn('Relaunching...') # we have to relaunch the process # pip marker to avoid a relaunch bug if sys.argv[:3] == ['-c', 'install', '--single-version-externally-managed']: sys.argv[0] = 'setup.py' args = [sys.executable] + sys.argv sys.exit(subprocess.call(args)) def _extractall(self, path=".", members=None): """Extract all members from the archive to the current working directory and set owner, modification time and permissions on directories afterwards. `path' specifies a different directory to extract to. `members' is optional and must be a subset of the list returned by getmembers(). """ import copy import operator from tarfile import ExtractError directories = [] if members is None: members = self for tarinfo in members: if tarinfo.isdir(): # Extract directories with a safe mode. directories.append(tarinfo) tarinfo = copy.copy(tarinfo) tarinfo.mode = 448 # decimal for oct 0700 self.extract(tarinfo, path) # Reverse sort directories. if sys.version_info < (2, 4): def sorter(dir1, dir2): return cmp(dir1.name, dir2.name) directories.sort(sorter) directories.reverse() else: directories.sort(key=operator.attrgetter('name'), reverse=True) # Set correct owner, mtime and filemode on directories. for tarinfo in directories: dirpath = os.path.join(path, tarinfo.name) try: self.chown(tarinfo, dirpath) self.utime(tarinfo, dirpath) self.chmod(tarinfo, dirpath) except ExtractError: e = sys.exc_info()[1] if self.errorlevel > 1: raise else: self._dbg(1, "tarfile: %s" % e) def _build_install_args(argv): install_args = [] user_install = '--user' in argv if user_install and sys.version_info < (2,6): log.warn("--user requires Python 2.6 or later") raise SystemExit(1) if user_install: install_args.append('--user') return install_args def main(argv, version=DEFAULT_VERSION): """Install or upgrade setuptools and EasyInstall""" tarball = download_setuptools() _install(tarball, _build_install_args(argv)) if __name__ == '__main__': main(sys.argv[1:]) PyVISA-1.4/.cvsignore0000644000175000017500000000003211734647057014024 0ustar floflo00000000000000*.pyc build dist MANIFEST