├── tests ├── __init__.py └── test_version.py ├── fluke5440b_async ├── _version.py ├── __init__.py ├── errors.py ├── flags.py ├── enums.py └── fluke_5440b.py ├── doc ├── source │ ├── readme.rst │ ├── _static │ │ └── css │ │ │ └── custom.css │ ├── index.rst │ ├── modules.rst │ ├── examples.rst │ └── conf.py └── Makefile ├── setup.py ├── .github ├── dependabot.yml └── workflows │ ├── pre-commit.yml │ ├── pylint.yml │ ├── publish-test-pypi.yml │ ├── documentation.yml │ └── publish-pypi.yml ├── .pre-commit-config.yaml ├── .gitignore ├── examples ├── simple.py ├── set_output.py ├── run_acal.py └── test_functions.py ├── pyproject.toml ├── README.md └── LICENSE /tests/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /fluke5440b_async/_version.py: -------------------------------------------------------------------------------- 1 | # pylint: disable=missing-module-docstring 2 | __version__ = "1.0.3" 3 | -------------------------------------------------------------------------------- /doc/source/readme.rst: -------------------------------------------------------------------------------- 1 | Readme 2 | ====================== 3 | 4 | .. include:: ../../README.md 5 | :parser: myst_parser.docutils_ 6 | -------------------------------------------------------------------------------- /doc/source/_static/css/custom.css: -------------------------------------------------------------------------------- 1 | div.sphinxsidebar { 2 | width: 500px; 3 | } 4 | 5 | div.bodywrapper { 6 | margin: 0 0 0 500px; 7 | } 8 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # pylint: disable=missing-module-docstring 3 | import setuptools 4 | 5 | if __name__ == "__main__": 6 | setuptools.setup() 7 | -------------------------------------------------------------------------------- /tests/test_version.py: -------------------------------------------------------------------------------- 1 | """Test to catch invalid versions when releasing a new git tag""" 2 | 3 | import os 4 | 5 | from fluke5440b_async._version import __version__ 6 | 7 | 8 | def test_version(): 9 | """ 10 | Test the Git tag when using CI against the package version 11 | """ 12 | if os.getenv("GIT_TAG"): 13 | assert os.getenv("GIT_TAG") == __version__ 14 | else: 15 | assert True 16 | -------------------------------------------------------------------------------- /doc/source/index.rst: -------------------------------------------------------------------------------- 1 | .. hp3478a_async documentation master file, created by 2 | sphinx-quickstart on Sat Jul 9 21:02:07 2022. 3 | You can adapt this file completely to your liking, but it should at least 4 | contain the root `toctree` directive. 5 | 6 | Home 7 | =================================== 8 | 9 | .. toctree:: 10 | :maxdepth: 2 11 | :caption: Contents: 12 | 13 | readme 14 | modules 15 | examples 16 | 17 | 18 | Indices and tables 19 | ================== 20 | 21 | * :ref:`genindex` 22 | * :ref:`modindex` 23 | * :ref:`search` 24 | -------------------------------------------------------------------------------- /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | version: 2 2 | updates: 3 | - package-ecosystem: "github-actions" 4 | # Workflow files stored in the 5 | # default location of `.github/workflows` 6 | directory: "/" 7 | schedule: 8 | interval: "daily" 9 | commit-message: 10 | # Prefix all commit messages with "[gha] " 11 | prefix: "[gha] " 12 | 13 | - package-ecosystem: "pip" 14 | directory: "/" 15 | schedule: 16 | interval: "daily" 17 | commit-message: 18 | # Prefix all commit messages with "[pip] " 19 | prefix: "[pip] " 20 | -------------------------------------------------------------------------------- /fluke5440b_async/__init__.py: -------------------------------------------------------------------------------- 1 | """ 2 | This is an asyncIO library for the Fluke 5440B calibrator. It manages all functions of the calibrator and takes care 3 | of the internal state. 4 | """ 5 | 6 | from ._version import __version__ 7 | from .enums import DeviceState, ErrorCode, ModeType, SeparatorType, TerminatorType 8 | from .flags import SerialPollFlags, SrqMask, StatusFlags 9 | from .fluke_5440b import CalibrationConstants, Fluke_5440B 10 | 11 | __all__ = [ 12 | "Fluke_5440B", 13 | "CalibrationConstants", 14 | "ErrorCode", 15 | "ModeType", 16 | "SeparatorType", 17 | "DeviceState", 18 | "TerminatorType", 19 | "SerialPollFlags", 20 | "SrqMask", 21 | "StatusFlags", 22 | ] 23 | -------------------------------------------------------------------------------- /doc/Makefile: -------------------------------------------------------------------------------- 1 | # Minimal makefile for Sphinx documentation 2 | # 3 | 4 | # You can set these variables from the command line, and also 5 | # from the environment for the first two. 6 | SPHINXOPTS ?= 7 | SPHINXBUILD ?= sphinx-build 8 | SOURCEDIR = source 9 | BUILDDIR = build 10 | 11 | # Put it first so that "make" without argument is like "make help". 12 | help: 13 | @$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) 14 | 15 | .PHONY: help Makefile 16 | 17 | # Catch-all target: route all unknown targets to Sphinx using the new 18 | # "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS). 19 | %: Makefile 20 | @$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) 21 | -------------------------------------------------------------------------------- /.github/workflows/pre-commit.yml: -------------------------------------------------------------------------------- 1 | name: pre-commit 2 | 3 | on: 4 | pull_request: 5 | 6 | jobs: 7 | pre-commit: 8 | runs-on: ubuntu-latest 9 | 10 | strategy: 11 | matrix: 12 | python-version: [ "3.12" ] 13 | 14 | steps: 15 | - name: Checkout source repository 16 | uses: actions/checkout@v6 17 | - name: Set up python ${{ matrix.python-version }} 18 | uses: actions/setup-python@v6 19 | with: 20 | python-version: ${{ matrix.python-version }} 21 | - name: Install dependencies for testing 22 | run: | 23 | python3 -m pip install --upgrade pip 24 | python3 -m pip install .[test] 25 | - name: Run pre-commit 26 | uses: pre-commit/action@v3.0.1 27 | -------------------------------------------------------------------------------- /doc/source/modules.rst: -------------------------------------------------------------------------------- 1 | Module Documentation 2 | ===================== 3 | 4 | .. toctree:: 5 | :maxdepth: 4 6 | 7 | fluke5440b\_async 8 | -------------- 9 | 10 | .. automodule:: fluke5440b_async 11 | :no-members: 12 | :undoc-members: 13 | :show-inheritance: 14 | 15 | .. autoclass:: Fluke_5440B 16 | :members: 17 | :undoc-members: 18 | :special-members: __init__ 19 | 20 | Dataclasses 21 | ----------- 22 | 23 | .. autoclass:: fluke5440b_async.CalibrationConstants 24 | :members: 25 | :undoc-members: 26 | 27 | Enums and Flags 28 | --------------- 29 | 30 | .. automodule:: fluke5440b_async.flags 31 | :members: 32 | :undoc-members: 33 | 34 | .. automodule:: fluke5440b_async.enums 35 | :members: 36 | :undoc-members: 37 | 38 | Errors 39 | ------ 40 | .. automodule:: fluke5440b_async.errors 41 | :members: 42 | :undoc-members: 43 | -------------------------------------------------------------------------------- /fluke5440b_async/errors.py: -------------------------------------------------------------------------------- 1 | """Custom errors raised by the Fluke 5440B.""" 2 | 3 | from .enums import ErrorCode, SelfTestErrorCode 4 | 5 | 6 | class Fluke5440bError(Exception): 7 | """The base class for all Fluke 5540B exceptions""" 8 | 9 | 10 | class DeviceError(Fluke5440bError): 11 | """The device returned an error during operation.""" 12 | 13 | def __init__(self, message: str, error_code: ErrorCode): 14 | super().__init__(message) 15 | 16 | self.code = error_code 17 | 18 | 19 | class SelftestError(Fluke5440bError): 20 | """The device returned an error during self-test. See page 4-8 of the service manual for details.""" 21 | 22 | def __init__(self, selftest: str, error_code: SelfTestErrorCode): 23 | super().__init__( 24 | f"{selftest} self-test failed with error: {error_code}." 25 | f" Check the service manual on page 4-8 for a solution." 26 | ) 27 | 28 | self.code = error_code 29 | -------------------------------------------------------------------------------- /.github/workflows/pylint.yml: -------------------------------------------------------------------------------- 1 | name: pylint 2 | 3 | on: 4 | push: 5 | branches: [ "master" ] 6 | pull_request: 7 | branches: [ "master" ] 8 | 9 | permissions: 10 | contents: read 11 | 12 | jobs: 13 | build: 14 | name: Run Pylint 15 | runs-on: ubuntu-latest 16 | 17 | strategy: 18 | matrix: 19 | python-version: [ "3.10", "3.11", "3.12" ] 20 | 21 | steps: 22 | - name: Checkout source repository 23 | uses: actions/checkout@v6 24 | - name: Set up python ${{ matrix.python-version }} 25 | uses: actions/setup-python@v6 26 | with: 27 | python-version: ${{ matrix.python-version }} 28 | - name: Install dependencies for testing 29 | run: | 30 | python3 -m pip install --upgrade pip 31 | python3 -m pip install .[test] 32 | - name: Run Pylint 33 | run: | 34 | # stop the build if there are Python syntax errors or undefined names 35 | pylint --reports n fluke5440b_async 36 | -------------------------------------------------------------------------------- /doc/source/examples.rst: -------------------------------------------------------------------------------- 1 | Examples 2 | ======== 3 | The Fluke 5440B requires a GPIB connection and a supported driver. Currently two drivers are supported by the HP 3478A 4 | driver: `Linux Gpib `_ or 5 | `Prologix Ethernet adapter `_. Linux GPIB supports 6 | `several `_ 7 | different hardware solutions. 8 | 9 | The Python asyncio drivers for the GPIB backends can be found here: 10 | 11 | * `Linux Gpib Wrapper `_ 12 | * `Prologix asyncio driver `_ 13 | 14 | See the basic example below for an implementation using the Prologix driver: 15 | 16 | Basic Example 17 | ------------- 18 | 19 | .. literalinclude:: ../../examples/simple.py 20 | :language: python 21 | 22 | More Examples 23 | ------------- 24 | More examples can be found in the 25 | `examples folder `_. 26 | -------------------------------------------------------------------------------- /fluke5440b_async/flags.py: -------------------------------------------------------------------------------- 1 | """Flags are used for the status registers returned by the device.""" 2 | 3 | from __future__ import annotations 4 | 5 | from enum import Flag 6 | 7 | 8 | class SerialPollFlags(Flag): 9 | """The register returned by a serial poll.""" 10 | 11 | NONE = 0b0 12 | DOING_STATE_CHANGE = 1 << 2 13 | MSG_RDY = 1 << 3 14 | OUTPUT_SETTLED = 1 << 4 15 | ERROR_CONDITION = 1 << 5 16 | SRQ = 1 << 6 17 | 18 | 19 | class SrqMask(Flag): 20 | """The register to control the service request interrupts.""" 21 | 22 | NONE = 0b0 23 | DOING_STATE_CHANGE = 1 << 2 24 | MSG_RDY = 1 << 3 25 | OUTPUT_SETTLED = 1 << 4 26 | ERROR_CONDITION = 1 << 5 27 | 28 | 29 | class StatusFlags(Flag): 30 | """The internal status register that holds the device configuration.""" 31 | 32 | VOLTAGE_MODE = 1 << 0 33 | CURRENT_BOOST_MODE = 1 << 1 34 | VOLTAGE_BOOST_MODE = 1 << 2 35 | DIVIDER_ENABLED = 1 << 3 36 | INTERNAL_SENSE_ENABLED = 1 << 4 37 | OUTPUT_ENABLED = 1 << 5 38 | INTERNAL_GUARD_ENABLED = 1 << 6 39 | REAR_OUTPUT_ENABLED = 1 << 7 40 | -------------------------------------------------------------------------------- /.github/workflows/publish-test-pypi.yml: -------------------------------------------------------------------------------- 1 | name: Upload to test.pypi.org 2 | 3 | on: 4 | # Triggers the workflow on push to the master branch 5 | push: 6 | branches: [ "master" ] 7 | 8 | workflow_dispatch: 9 | 10 | permissions: 11 | contents: read 12 | 13 | jobs: 14 | build: 15 | runs-on: ubuntu-latest 16 | 17 | strategy: 18 | matrix: 19 | python-version: [ "3.12" ] 20 | 21 | steps: 22 | - name: Checkout source repository 23 | uses: actions/checkout@v6 24 | - name: Set up python ${{ matrix.python-version }} 25 | uses: actions/setup-python@v6 26 | with: 27 | python-version: ${{ matrix.python-version }} 28 | - name: Install and update pip and the build dependencies 29 | run: | 30 | python3 -m pip install --upgrade pip 31 | python3 -m pip install .[dev] 32 | - name: Build and upload to PyPI 33 | continue-on-error: true 34 | run: | 35 | python3 -m build 36 | python3 -m twine upload dist/* 37 | env: 38 | TWINE_USERNAME: __token__ 39 | TWINE_PASSWORD: ${{ secrets.TWINE_TEST_TOKEN }} 40 | TWINE_REPOSITORY: testpypi 41 | -------------------------------------------------------------------------------- /.pre-commit-config.yaml: -------------------------------------------------------------------------------- 1 | # See https://pre-commit.com for more information 2 | # See https://pre-commit.com/hooks.html for more hooks 3 | repos: 4 | - repo: https://github.com/pre-commit/pre-commit-hooks 5 | rev: v4.5.0 6 | hooks: 7 | - id: check-executables-have-shebangs 8 | # Check for invalid files 9 | - id: check-toml 10 | # Check Python files 11 | - id: end-of-file-fixer 12 | - id: fix-encoding-pragma 13 | args: [--remove] 14 | - id: mixed-line-ending 15 | args: [ --fix=lf ] 16 | - id: check-executables-have-shebangs 17 | - id: requirements-txt-fixer 18 | - id: trailing-whitespace 19 | args: [ --markdown-linebreak-ext=md ] 20 | - repo: https://github.com/psf/black 21 | rev: 24.4.2 22 | hooks: 23 | - id: black 24 | - repo: https://github.com/asottile/blacken-docs 25 | rev: 1.16.0 26 | hooks: 27 | - id: blacken-docs 28 | args: [ --line-length=120 ] 29 | - repo: https://github.com/PyCQA/isort 30 | rev: 5.13.2 31 | hooks: 32 | - id: isort 33 | - repo: local 34 | hooks: 35 | - id: pylint 36 | name: pylint 37 | entry: pylint 38 | language: system 39 | types: [ python ] 40 | require_serial: true 41 | - repo: https://github.com/pre-commit/mirrors-mypy 42 | rev: 'v1.10.0' 43 | hooks: 44 | - id: mypy 45 | additional_dependencies: [types-simplejson] 46 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | env/ 12 | build/ 13 | develop-eggs/ 14 | dist/ 15 | downloads/ 16 | eggs/ 17 | .eggs/ 18 | lib/ 19 | lib64/ 20 | parts/ 21 | sdist/ 22 | var/ 23 | wheels/ 24 | *.egg-info/ 25 | .installed.cfg 26 | *.egg 27 | 28 | # PyInstaller 29 | # Usually these files are written by a python script from a template 30 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 31 | *.manifest 32 | *.spec 33 | 34 | # Installer logs 35 | pip-log.txt 36 | pip-delete-this-directory.txt 37 | 38 | # Unit test / coverage reports 39 | htmlcov/ 40 | .tox/ 41 | .coverage 42 | .coverage.* 43 | .cache 44 | nosetests.xml 45 | coverage.xml 46 | *.cover 47 | .hypothesis/ 48 | 49 | # Translations 50 | *.mo 51 | *.pot 52 | 53 | # Django stuff: 54 | *.log 55 | local_settings.py 56 | 57 | # Flask stuff: 58 | instance/ 59 | .webassets-cache 60 | 61 | # Scrapy stuff: 62 | .scrapy 63 | 64 | # Sphinx documentation 65 | docs/_build/ 66 | 67 | # PyBuilder 68 | target/ 69 | 70 | # Jupyter Notebook 71 | .ipynb_checkpoints 72 | 73 | # pyenv 74 | .python-version 75 | 76 | # celery beat schedule file 77 | celerybeat-schedule 78 | 79 | # SageMath parsed files 80 | *.sage.py 81 | 82 | # dotenv 83 | .env 84 | 85 | # virtualenv 86 | .venv 87 | venv/ 88 | ENV/ 89 | 90 | # Spyder project settings 91 | .spyderproject 92 | .spyproject 93 | 94 | # Rope project settings 95 | .ropeproject 96 | 97 | # mkdocs documentation 98 | /site 99 | 100 | # mypy 101 | .mypy_cache/ 102 | -------------------------------------------------------------------------------- /examples/simple.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # pylint: disable=duplicate-code 3 | # ##### BEGIN GPL LICENSE BLOCK ##### 4 | # 5 | # Copyright (C) 2023 Patrick Baus 6 | # This program is free software: you can redistribute it and/or modify 7 | # it under the terms of the GNU General Public License as published by 8 | # the Free Software Foundation, either version 3 of the License, or 9 | # (at your option) any later version. 10 | # 11 | # This program is distributed in the hope that it will be useful, 12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | # GNU General Public License for more details. 15 | 16 | # You should have received a copy of the GNU General Public License 17 | # along with this program. If not, see . 18 | # 19 | # ##### END GPL LICENSE BLOCK ##### 20 | """This is a simple example that uses the Prologix Ethernet adapter to set the output voltage of the calibrator.""" 21 | 22 | import asyncio 23 | 24 | from prologix_gpib_async import AsyncPrologixGpibEthernetController 25 | 26 | from fluke5440b_async import Fluke_5440B 27 | 28 | IP_ADDRESS = "127.0.0.1" 29 | 30 | 31 | async def main(): 32 | """Set the output voltage and enable the outputs.""" 33 | # No need to explicitly bring up the GPIB connection. This will be done by the instrument. 34 | async with Fluke_5440B( 35 | connection=AsyncPrologixGpibEthernetController(IP_ADDRESS, pad=7, timeout=300, wait_delay=0.25) 36 | ) as fluke5440b: 37 | await fluke5440b.set_output(10.0) 38 | # Enable the output binding posts 39 | # await fluke5440b.set_output_enabled(True) # Use with caution at high voltages. Check cabling first. 40 | 41 | 42 | asyncio.run(main(), debug=False) 43 | -------------------------------------------------------------------------------- /.github/workflows/documentation.yml: -------------------------------------------------------------------------------- 1 | name: Build Documentation and push to gh-pages 2 | 3 | on: 4 | push: 5 | branches: [ "master" ] 6 | 7 | permissions: 8 | contents: write 9 | 10 | jobs: 11 | build-documentation: 12 | runs-on: ubuntu-latest 13 | 14 | strategy: 15 | matrix: 16 | python-version: ["3.12"] 17 | 18 | steps: 19 | - name: Checkout source repository 20 | uses: actions/checkout@v6 21 | with: 22 | path: master 23 | - name: Checkout gh-pages repository 24 | uses: actions/checkout@v6 25 | with: 26 | ref: gh-pages 27 | path: gh-pages 28 | - name: Set up python ${{ matrix.python-version }} 29 | uses: actions/setup-python@v6 30 | with: 31 | python-version: ${{ matrix.python-version }} 32 | - name: Install dependencies for testing 33 | working-directory: master 34 | run: | 35 | python3 -m pip install --upgrade pip 36 | python3 -m pip install .[doc] 37 | - name: Build documentation 38 | working-directory: master/doc 39 | run: | 40 | make html 41 | - name: Commit documentation changes 42 | run: | 43 | cp -r master/doc/build/html/* gh-pages/ 44 | cd gh-pages 45 | # We need to disable Jekyll, because gh-pages does not copy files/folders with underscores: 46 | # https://github.blog/2009-12-29-bypassing-jekyll-on-github-pages/ 47 | touch .nojekyll 48 | git config user.name github-actions 49 | git config user.email github-actions@github.com 50 | git add . 51 | # git commit returns an error if there are no updates, but this is ok 52 | git commit -m "Update documentation" -a || true 53 | - name: Push documentation changes 54 | working-directory: gh-pages 55 | run: | 56 | git push 57 | -------------------------------------------------------------------------------- /.github/workflows/publish-pypi.yml: -------------------------------------------------------------------------------- 1 | name: Upload to pypi.org 2 | 3 | on: 4 | # Triggers the workflow when a release is created 5 | release: 6 | types: [created] 7 | 8 | workflow_dispatch: 9 | 10 | jobs: 11 | tests: 12 | name: Run Python tests 13 | runs-on: ubuntu-latest 14 | 15 | strategy: 16 | matrix: 17 | python-version: [ "3.12", ] 18 | 19 | steps: 20 | - name: Checkout source repository 21 | uses: actions/checkout@v6 22 | 23 | - name: Set up python ${{ matrix.python-version }} 24 | uses: actions/setup-python@v6 25 | with: 26 | cache: 'pip' # caching pip dependencies 27 | python-version: ${{ matrix.python-version }} 28 | 29 | - name: Install dependencies for testing 30 | run: | 31 | python3 -m pip install --upgrade pip 32 | python3 -m pip install .[test] 33 | 34 | - name: Test with pytest 35 | env: 36 | GIT_TAG: ${{ github.ref_type == 'tag' && github.ref_name || '' }} 37 | run: | 38 | pytest --exitfirst --verbose --failed-first 39 | 40 | upload: 41 | needs: 42 | - tests 43 | runs-on: ubuntu-latest 44 | 45 | strategy: 46 | matrix: 47 | python-version: [ "3.12" ] 48 | 49 | steps: 50 | - name: Checkout source repository 51 | uses: actions/checkout@v6 52 | - name: Set up python ${{ matrix.python-version }} 53 | uses: actions/setup-python@v6 54 | with: 55 | python-version: ${{ matrix.python-version }} 56 | - name: Install and update pip and the build dependencies 57 | run: | 58 | python3 -m pip install --upgrade pip 59 | python3 -m pip install .[dev] 60 | - name: Build and Upload to PyPI 61 | run: | 62 | python3 -m build 63 | python3 -m twine upload dist/* 64 | env: 65 | TWINE_USERNAME: __token__ 66 | TWINE_PASSWORD: ${{ secrets.TWINE_TOKEN }} 67 | -------------------------------------------------------------------------------- /pyproject.toml: -------------------------------------------------------------------------------- 1 | [project] 2 | name = "fluke5440b-async" 3 | authors = [ 4 | { name="Patrick Baus", email="patrick.baus@physik.tu-darmstadt.de" }, 5 | ] 6 | description = "A Python asyncio library for the Fluke 5440B voltage calibrator." 7 | readme = "README.md" 8 | license = { text="GNU General Public License v3 (GPLv3)" } 9 | requires-python = ">=3.7" 10 | classifiers = [ 11 | "Programming Language :: Python :: 3", 12 | "Programming Language :: Python :: 3.8", 13 | "Programming Language :: Python :: 3.9", 14 | "Programming Language :: Python :: 3.10", 15 | "Programming Language :: Python :: 3.11", 16 | "Programming Language :: Python :: 3.12", 17 | "Development Status :: 5 - Production/Stable", 18 | "License :: OSI Approved :: GNU General Public License v3 (GPLv3)", 19 | "Operating System :: OS Independent", 20 | "Intended Audience :: Developers", 21 | "Intended Audience :: Science/Research", 22 | "Natural Language :: English", 23 | "Topic :: Home Automation", 24 | "Topic :: Scientific/Engineering", 25 | ] 26 | keywords = ["Fluke 5440B", "GPIB", "API"] 27 | dynamic = ["version"] 28 | dependencies = [ 29 | "typing-extensions; python_version <'3.11'", 30 | ] 31 | 32 | [project.urls] 33 | "Homepage" = "https://github.com/PatrickBaus/pyAsyncFluke5440B" 34 | "Bug Tracker" = "https://github.com/PatrickBaus/pyAsyncFluke5440B/issues" 35 | "Download" = "https://github.com/PatrickBaus/pyAsyncFluke5440B/releases" 36 | 37 | [project.optional-dependencies] 38 | linux-gpib = ["async-gpib", "gpib-ctypes"] 39 | 40 | prologix-gpib = ["prologix-gpib-async"] 41 | 42 | dev = [ 43 | "async-gpib", "black", "build", "gpib-ctypes", "isort", "mypy", "pre-commit", "prologix-gpib-async", "pylint", 44 | "twine", 45 | ] 46 | 47 | doc = [ 48 | "myst-parser", "sphinx", 49 | ] 50 | 51 | test = [ 52 | "mypy", "pylint", "gpib-ctypes", "prologix-gpib-async", "setuptools", 53 | ] 54 | 55 | [tool.pylint.'MESSAGES CONTROL'] 56 | max-line-length = 120 57 | notes = ["FIXME", "XXX",] 58 | 59 | [tool.isort] 60 | line_length = 120 61 | profile = "black" 62 | 63 | [tool.black] 64 | line-length = 120 65 | 66 | [build-system] 67 | requires = [ 68 | "setuptools>=61.0", 69 | "typing-extensions; python_version <'3.11'", 70 | ] 71 | build-backend = "setuptools.build_meta" 72 | 73 | [tool.setuptools.dynamic] 74 | version = {attr = "fluke5440b_async.__version__"} 75 | -------------------------------------------------------------------------------- /doc/source/conf.py: -------------------------------------------------------------------------------- 1 | # Configuration file for the Sphinx documentation builder. 2 | # 3 | # This file only contains a selection of the most common options. For a full 4 | # list see the documentation: 5 | # https://www.sphinx-doc.org/en/master/usage/configuration.html 6 | 7 | # -- Path setup -------------------------------------------------------------- 8 | 9 | # If extensions (or modules to document with autodoc) are in another directory, 10 | # add these directories to sys.path here. If the directory is relative to the 11 | # documentation root, use os.path.abspath to make it absolute, like shown here. 12 | # 13 | # pylint: skip-file 14 | # import os 15 | # import sys 16 | # sys.path.insert(0, os.path.abspath('.')) 17 | 18 | # -- Project information ----------------------------------------------------- 19 | import fluke5440b_async 20 | 21 | project = "fluke5440b_async" 22 | copyright = "2023, Patrick Baus" 23 | author = "Patrick Baus" 24 | version = release = fluke5440b_async.__version__ 25 | 26 | 27 | # -- General configuration --------------------------------------------------- 28 | 29 | # Add any Sphinx extension module names here, as strings. They can be 30 | # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom 31 | # ones. 32 | extensions = [ 33 | "myst_parser", 34 | "sphinx.ext.autodoc", 35 | "sphinx.ext.napoleon", 36 | "sphinx.ext.viewcode", 37 | "sphinx.ext.mathjax", 38 | ] 39 | 40 | # Napoleon settings 41 | napoleon_include_init_with_doc = True 42 | 43 | # Add any paths that contain templates here, relative to this directory. 44 | templates_path = ["_templates"] 45 | 46 | # List of patterns, relative to source directory, that match files and 47 | # directories to ignore when looking for source files. 48 | # This pattern also affects html_static_path and html_extra_path. 49 | exclude_patterns: list[str] = [] 50 | 51 | 52 | # -- Options for HTML output ------------------------------------------------- 53 | 54 | # The theme to use for HTML and HTML Help pages. See the documentation for 55 | # a list of builtin themes. 56 | # 57 | html_theme = "nature" 58 | 59 | # Add any paths that contain custom static files (such as style sheets) here, 60 | # relative to this directory. They are copied after the builtin static files, 61 | # so a file named "default.css" will overwrite the builtin "default.css". 62 | html_static_path = ["_static"] 63 | 64 | # These paths are either relative to html_static_path 65 | # or fully qualified paths (eg. https://...) 66 | html_css_files = [ 67 | "css/custom.css", 68 | ] 69 | 70 | html_title = project + " v" + version + " documentation" 71 | -------------------------------------------------------------------------------- /examples/set_output.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # pylint: disable=duplicate-code 3 | # ##### BEGIN GPL LICENSE BLOCK ##### 4 | # 5 | # Copyright (C) 2023 Patrick Baus 6 | # This program is free software: you can redistribute it and/or modify 7 | # it under the terms of the GNU General Public License as published by 8 | # the Free Software Foundation, either version 3 of the License, or 9 | # (at your option) any later version. 10 | # 11 | # This program is distributed in the hope that it will be useful, 12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | # GNU General Public License for more details. 15 | 16 | # You should have received a copy of the GNU General Public License 17 | # along with this program. If not, see . 18 | # 19 | # ##### END GPL LICENSE BLOCK ##### 20 | """This example shows setting the output voltage of the calibrator""" 21 | 22 | import asyncio 23 | import logging 24 | import sys 25 | import typing 26 | import warnings 27 | 28 | # Devices 29 | from fluke5440b_async import Fluke_5440B 30 | 31 | if typing.TYPE_CHECKING: 32 | from async_gpib import AsyncGpib 33 | from prologix_gpib_async import AsyncPrologixGpibEthernetController 34 | else: 35 | # Uncomment if using a Prologix GPIB Ethernet adapter 36 | from prologix_gpib_async import AsyncPrologixGpibEthernetController 37 | 38 | # Uncomment if using linux-gpib 39 | # from async_gpib import AsyncGpib 40 | 41 | if "prologix_gpib_async" in sys.modules: 42 | IP_ADDRESS = "127.0.0.1" 43 | # Set the timeout to 300 seconds, State.SELF_TEST_LOW_VOLTAGE takes a little more than 3 minutes. 44 | # pylint: disable=used-before-assignment # false positive 45 | gpib_device = AsyncPrologixGpibEthernetController( 46 | IP_ADDRESS, pad=7, timeout=300, wait_delay=0.25 47 | ) # Prologix GPIB Adapter 48 | elif "async_gpib" in sys.modules: 49 | # Set the timeout to 300 seconds, State.SELF_TEST_LOW_VOLTAGE takes a little more than 3 minutes. 50 | gpib_device = AsyncGpib(name=0, pad=7, timeout=300) # NI GPIB adapter, pylint: disable=used-before-assignment 51 | from gpib_ctypes.Gpib import Gpib 52 | 53 | gpib_board = Gpib(name=0) 54 | gpib_board.config(0x7, True) # enable wait for SRQs to speed up waiting for state changes 55 | gpib_board.close() 56 | else: 57 | raise ModuleNotFoundError("No GPIB library loaded.") 58 | 59 | 60 | async def main(): 61 | """Set the output voltage and enable the outputs.""" 62 | # No need to explicitly bring up the GPIB connection. This will be done by the instrument. 63 | async with Fluke_5440B(connection=gpib_device, log_level=logging.DEBUG) as fluke5440b: 64 | await fluke5440b.set_output(10.0) 65 | # Enable the output binding posts 66 | # await fluke5440b.set_output_enabled(True) # Use with caution at high voltages. Check cabling first. 67 | 68 | 69 | # Report all mistakes managing asynchronous resources. 70 | warnings.simplefilter("always", ResourceWarning) 71 | logging.basicConfig( 72 | format="%(asctime)s.%(msecs)03d %(levelname)-8s %(message)s", 73 | level=logging.INFO, # Enable logs from the ip connection. Set to debug for even more info 74 | datefmt="%Y-%m-%d %H:%M:%S", 75 | ) 76 | 77 | asyncio.run(main(), debug=False) 78 | -------------------------------------------------------------------------------- /examples/run_acal.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # pylint: disable=duplicate-code 3 | # ##### BEGIN GPL LICENSE BLOCK ##### 4 | # 5 | # Copyright (C) 2023 Patrick Baus 6 | # This program is free software: you can redistribute it and/or modify 7 | # it under the terms of the GNU General Public License as published by 8 | # the Free Software Foundation, either version 3 of the License, or 9 | # (at your option) any later version. 10 | # 11 | # This program is distributed in the hope that it will be useful, 12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | # GNU General Public License for more details. 15 | 16 | # You should have received a copy of the GNU General Public License 17 | # along with this program. If not, see . 18 | # 19 | # ##### END GPL LICENSE BLOCK ##### 20 | """This example will run the internal ACAL routine to calibrate the instrument. It will show the calibration constants 21 | before and after the calibration.""" 22 | 23 | import asyncio 24 | import logging 25 | import sys 26 | import typing 27 | import warnings 28 | 29 | # Devices 30 | from fluke5440b_async import Fluke_5440B 31 | 32 | if typing.TYPE_CHECKING: 33 | from async_gpib import AsyncGpib 34 | from prologix_gpib_async import AsyncPrologixGpibEthernetController 35 | else: 36 | # Uncomment if using a Prologix GPIB Ethernet adapter 37 | from prologix_gpib_async import AsyncPrologixGpibEthernetController 38 | 39 | # Uncomment if using linux-gpib 40 | # from async_gpib import AsyncGpib 41 | 42 | if "prologix_gpib_async" in sys.modules: 43 | IP_ADDRESS = "127.0.0.1" 44 | # Set the timeout to 190 seconds, State.SELF_TEST_LOW_VOLTAGE takes a little more than 3 minutes. 45 | # pylint: disable=used-before-assignment # false positive 46 | gpib_device = AsyncPrologixGpibEthernetController( 47 | IP_ADDRESS, pad=7, timeout=300, wait_delay=0.25 48 | ) # Prologix GPIB Adapter 49 | elif "async_gpib" in sys.modules: 50 | # Set the timeout to 190 seconds State.SELF_TEST_LOW_VOLTAGE takes a little more than 3 minutes. 51 | gpib_device = AsyncGpib(name=0, pad=7, timeout=190) # NI GPIB adapter, pylint: disable=used-before-assignment 52 | from gpib_ctypes.Gpib import Gpib 53 | 54 | gpib_board = Gpib(name=0) 55 | gpib_board.config(0x7, True) # enable wait for SRQs to speed up waiting for state changes 56 | gpib_board.close() 57 | else: 58 | raise ModuleNotFoundError("No GPIB library loaded.") 59 | 60 | 61 | async def main(): 62 | """Print the calibration constants, then run ACAL, then print the new constants.""" 63 | # No need to explicitly bring up the GPIB connection. This will be done by the instrument. 64 | async with Fluke_5440B(connection=gpib_device, log_level=logging.DEBUG) as fluke5440b: 65 | # First run the self-test 66 | print("Running self-test, then autocalibration.") 67 | await fluke5440b.selftest_all() 68 | print("Self-test done.") 69 | cal_constants = await fluke5440b.get_calibration_constants() 70 | print(f"Calibration constants before running autocalibration:\n{cal_constants}") 71 | await fluke5440b.acal() 72 | cal_constants = await fluke5440b.get_calibration_constants() 73 | print(f"Calibration constants after running autocalibration:\n{cal_constants}") 74 | 75 | 76 | # Report all mistakes managing asynchronous resources. 77 | warnings.simplefilter("always", ResourceWarning) 78 | logging.basicConfig( 79 | format="%(asctime)s.%(msecs)03d %(levelname)-8s %(message)s", 80 | level=logging.INFO, # Enable logs from the ip connection. Set to debug for even more info 81 | datefmt="%Y-%m-%d %H:%M:%S", 82 | ) 83 | 84 | try: 85 | asyncio.run(main(), debug=False) 86 | except KeyboardInterrupt: 87 | # The loop will be canceled on a KeyboardInterrupt by the run() method, we just want to suppress the exception 88 | pass 89 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [![pylint](../../actions/workflows/pylint.yml/badge.svg)](../../actions/workflows/pylint.yml) 2 | [![PyPI](https://img.shields.io/pypi/v/fluke5440b_async)](https://pypi.org/project/fluke5440b_async/) 3 | ![PyPI - Python Version](https://img.shields.io/pypi/pyversions/fluke5440b_async) 4 | ![PyPI - Status](https://img.shields.io/pypi/status/fluke5440b_async) 5 | [![License: GPL v3](https://img.shields.io/badge/License-GPL%20v3-blue.svg)](LICENSE) 6 | [![code style](https://img.shields.io/badge/code%20style-black-000000.svg)](https://github.com/psf/black) 7 | # fluke5440b-async 8 | Python3 asyncio Fluke 5440B driver. This library requires Python [asyncio](https://docs.python.org/3/library/asyncio.html) and asyncio library for the GPIB adapter. 9 | 10 | The library is fully type-hinted. 11 | 12 | > :warning: The following features are not supported (yet): 13 | > - External calibration: I do not have the means to test this. If you want to help, open a ticket and we can get this done 14 | > - Setting and retrieving DUUT tolerances and errors. I believe this is best done in software on the host computer and not done internally in the calibrator. If you really need that featuer open a ticket. 15 | 16 | ## Supported GPIB Hardware 17 | | Device |Supported|Tested|Comments| 18 | |-------------------------------------------------------------------------------------|--|--|--| 19 | | [asyncio Prologix GPIB library](https://github.com/PatrickBaus/pyAsyncPrologixGpib) |:heavy_check_mark:|:heavy_check_mark:| | 20 | | [asyncio linux-gpib wrapper](https://github.com/PatrickBaus/pyAsyncGpib) |:heavy_check_mark:|:heavy_check_mark:| | 21 | 22 | Tested using Linux, but should work on Mac OSX, Windows or any OS with Python support. 23 | 24 | ## Documentation 25 | The full documentation can be found on GitHub Pages: 26 | [https://patrickbaus.github.io/pyAsyncFluke5440B/](https://patrickbaus.github.io/pyAsyncFluke5440B/). I use the 27 | [Numpydoc](https://numpydoc.readthedocs.io/en/latest/format.html) style for documentation and 28 | [Sphinx](https://www.sphinx-doc.org/en/master/index.html) for compiling it. 29 | 30 | # Setup 31 | To install the library in a virtual environment (always use venvs with every project): 32 | ```bash 33 | python3 -m venv env # virtual environment, optional 34 | source env/bin/activate # only if the virtual environment is used 35 | pip install fluke5440b-async 36 | ``` 37 | 38 | All examples assume that a GPIB library is installed as well. Either run 39 | ```bash 40 | pip install prologix-gpib-async # or alternatively 41 | # pip install async-gpib 42 | ``` 43 | 44 | # Usage 45 | > :warning: The calibrator does not like excessive serial polling. So, when using the Prologix adapter, one might see warnings like this: 46 | > *Got error during waiting: ErrorCode.GPIB_HANDSHAKE_ERROR. If you are using a Prologix adapter, this can be safely ignored at this point.* 47 | > These are harmless and can be ignored. 48 | 49 | The library uses an asynchronous context manager to make cleanup easier. You can use either the 50 | context manager syntax or invoke the calls manually: 51 | 52 | ```python 53 | async with Fluke_5440B(connection=gpib_device) as fluke5440b: 54 | # Add your code here 55 | ... 56 | ``` 57 | 58 | ```python 59 | try: 60 | fluke5440b = Fluke_5440B(connection=gpib_device) 61 | await fluke5440b.connect() 62 | # your code 63 | finally: 64 | await fluke5440b.disconnect() 65 | ``` 66 | 67 | 68 | A simple example for setting the output voltage. 69 | ```python 70 | from pyAsyncFluke5440B.Fluke_5440B import Fluke_5440B 71 | 72 | from pyAsyncGpib.pyAsyncGpib.AsyncGpib import AsyncGpib 73 | 74 | 75 | # This example will print voltage data to the console 76 | async def main(): 77 | # The default GPIB address is 7. 78 | async with Fluke_5440B(connection=AsyncGpib(name=0, pad=7)) as fluke5440b: 79 | # No need to explicitely bring up the GPIB connection. This will be done by the instrument. 80 | await fluke5440b.set_output(10.0) 81 | await fluke5440b.set_output_enabled(True) 82 | 83 | 84 | try: 85 | asyncio.run(main(), debug=True) 86 | except KeyboardInterrupt: 87 | # The loop will be canceled on a KeyboardInterrupt by the run() method, we just want to suppress the exception 88 | pass 89 | ``` 90 | 91 | See [examples/](examples/) for more working examples. 92 | 93 | ## Versioning 94 | 95 | I use [SemVer](http://semver.org/) for versioning. For the versions available, see the [tags on this repository](../../tags). 96 | 97 | ## Authors 98 | 99 | * **Patrick Baus** - *Initial work* - [PatrickBaus](https://github.com/PatrickBaus) 100 | 101 | ## License 102 | 103 | 104 | This project is licensed under the GPL v3 license - see the [LICENSE](LICENSE) file for details 105 | -------------------------------------------------------------------------------- /examples/test_functions.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # pylint: disable=duplicate-code 3 | # ##### BEGIN GPL LICENSE BLOCK ##### 4 | # 5 | # Copyright (C) 2023 Patrick Baus 6 | # This program is free software: you can redistribute it and/or modify 7 | # it under the terms of the GNU General Public License as published by 8 | # the Free Software Foundation, either version 3 of the License, or 9 | # (at your option) any later version. 10 | # 11 | # This program is distributed in the hope that it will be useful, 12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | # GNU General Public License for more details. 15 | 16 | # You should have received a copy of the GNU General Public License 17 | # along with this program. If not, see . 18 | # 19 | # ##### END GPL LICENSE BLOCK ##### 20 | """This example is used to test the majority of instrument functions""" 21 | 22 | import asyncio 23 | import logging 24 | import sys 25 | import warnings 26 | from decimal import Decimal 27 | from math import isclose 28 | from typing import TYPE_CHECKING, cast 29 | 30 | # Devices 31 | from fluke5440b_async import Fluke_5440B 32 | 33 | if TYPE_CHECKING: 34 | from async_gpib import AsyncGpib 35 | from prologix_gpib_async import AsyncPrologixGpibEthernetController 36 | else: 37 | # Uncomment if using a Prologix GPIB Ethernet adapter 38 | from prologix_gpib_async import AsyncPrologixGpibEthernetController 39 | 40 | # Uncomment if using linux-gpib 41 | # from async_gpib import AsyncGpib 42 | 43 | if "prologix_gpib_async" in sys.modules: 44 | IP_ADDRESS = "127.0.0.1" 45 | # Set the timeout to 300 seconds, State.SELF_TEST_LOW_VOLTAGE takes a little more than 3 minutes. 46 | # pylint: disable=used-before-assignment # false positive 47 | gpib_device = AsyncPrologixGpibEthernetController( 48 | IP_ADDRESS, pad=7, timeout=300, wait_delay=0.25 49 | ) # Prologix GPIB Adapter 50 | elif "async_gpib" in sys.modules: 51 | # Set the timeout to 300 seconds, State.SELF_TEST_LOW_VOLTAGE takes a little more than 3 minutes. 52 | gpib_device = AsyncGpib(name=0, pad=7, timeout=300) # NI GPIB adapter, pylint: disable=used-before-assignment 53 | from gpib_ctypes.Gpib import Gpib 54 | 55 | gpib_board = Gpib(name=0) 56 | gpib_board.config(0x7, True) # enable wait for SRQs to speed up waiting for state changes 57 | gpib_board.close() 58 | else: 59 | raise ModuleNotFoundError("No GPIB library loaded.") 60 | 61 | 62 | async def test_getters(device: Fluke_5440B): 63 | """ 64 | Test the instrument getter functions. 65 | Parameters 66 | ---------- 67 | device: Fluke_5440B 68 | A connected instrument. 69 | 70 | Raises 71 | ------ 72 | DeviceError 73 | If test_error is set to True and there was an error processing the command. 74 | """ 75 | print("ID :", await device.get_id()) 76 | print("Terminator :", await device.get_terminator()) 77 | print("Separator :", await device.get_separator()) 78 | print("Output :", await device.get_output()) 79 | print("Voltage limit :", await device.get_voltage_limit()) 80 | print("Current limit :", await device.get_current_limit()) 81 | print("RS232 baud rate:", await device.get_rs232_baud_rate()) 82 | print("SRQ mask :", await device.get_srq_mask()) 83 | print("Calibration constants:", await device.get_calibration_constants()) # needs a lock, when running 84 | 85 | 86 | async def test_setters(device: Fluke_5440B): 87 | """ 88 | Test the instrument setter functions. 89 | Parameters 90 | ---------- 91 | device: Fluke_5440B 92 | A connected instrument. 93 | 94 | Raises 95 | ------ 96 | DeviceError 97 | If test_error is set to True and there was an error processing the command. 98 | ValueError 99 | Raised if the limits are out of bounds. 100 | """ 101 | # voltage limit 102 | output_limit = (-10.0, 10.0) 103 | await device.set_voltage_limit(*output_limit) 104 | assert output_limit == await device.get_voltage_limit() 105 | output_limit = (-1100.0, 1100.0) 106 | await device.set_voltage_limit(*output_limit) 107 | assert output_limit == await device.get_voltage_limit() 108 | 109 | # current limit 110 | current_limit = 35 / 1000 111 | await device.set_current_limit(current_limit) 112 | assert isclose(abs(current_limit), cast(Decimal, await device.get_current_limit())) 113 | current_limit = 65 / 1000 114 | await device.set_current_limit(current_limit) 115 | assert isclose(abs(current_limit), cast(Decimal, await device.get_current_limit())) 116 | 117 | # baud rate 118 | baud_rate = 4800 119 | await device.set_rs232_baud_rate(baud_rate) 120 | assert baud_rate == await device.get_rs232_baud_rate() 121 | baud_rate = 9600 122 | await device.set_rs232_baud_rate(baud_rate) 123 | assert baud_rate == await device.get_rs232_baud_rate() 124 | 125 | 126 | async def main(): 127 | """Run the example and test all getters first, then test the setters.""" 128 | # No need to explicitly bring up the GPIB connection. This will be done by the instrument. 129 | async with Fluke_5440B(connection=gpib_device, log_level=logging.DEBUG) as fluke5440b: 130 | await test_getters(fluke5440b) 131 | await test_setters(fluke5440b) 132 | 133 | 134 | # Report all mistakes managing asynchronous resources. 135 | warnings.simplefilter("always", ResourceWarning) 136 | logging.basicConfig( 137 | format="%(asctime)s.%(msecs)03d %(levelname)-8s %(message)s", 138 | level=logging.INFO, # Enable logs from the ip connection. Set to debug for even more info 139 | datefmt="%Y-%m-%d %H:%M:%S", 140 | ) 141 | 142 | try: 143 | asyncio.run(main(), debug=True) 144 | except KeyboardInterrupt: 145 | # The loop will be canceled on a KeyboardInterrupt by the run() method, we just want to suppress the exception 146 | pass 147 | -------------------------------------------------------------------------------- /fluke5440b_async/enums.py: -------------------------------------------------------------------------------- 1 | """Enums are used to represent the device functions and settings.""" 2 | 3 | from __future__ import annotations 4 | 5 | from enum import Enum 6 | 7 | 8 | class ErrorCode(Enum): 9 | """The error codes used by the Fluke 5440B.""" 10 | 11 | NONE = 0 12 | BOOST_INTERFACE_CONNECTION_ERROR = 144 13 | BOOST_INTERFACE_MISSING = 145 14 | BOOST_INTERFACE_VOLTAGE_TRIP = 146 15 | BOOST_INTERFACE_CURRENT_TRIP = 147 16 | GPIB_HANDSHAKE_ERROR = 152 17 | TERMINATOR_ERROR = 153 18 | SEPARATOR_ERROR = 154 19 | UNKNOWN_COMMAND = 155 20 | INVALID_PARAMETER = 156 21 | BUFFER_OVERFLOW = 157 22 | INVALID_CHARACTER = 158 23 | RS232_ERROR = 160 24 | PARAMETER_OUT_OF_RANGE = 168 25 | OUTPUT_OUTSIDE_LIMITS = 169 26 | LIMIT_OUT_OF_RANGE = 170 27 | DIVIDER_OUT_OF_RANGE = 171 28 | INVALID_SENSE_MODE = 172 29 | INVALID_GUARD_MODE = 173 30 | INVALID_COMMAND = 175 31 | 32 | 33 | class SelfTestErrorCode(Enum): 34 | """The error codes thrown by the self-test routine. See page 4-8 of the service manual for details.""" 35 | 36 | NONE = 0 37 | POWER_SUPPLY_FAULT_TEST_UNGUARDED_POWER = 8 38 | POWER_SUPPLY_FAULT_CHECK_GUARDED_POWER = 9 39 | MAIN_CONTROL_FAULT_CHECK_MAIN_CONTROLLER = 16 40 | MAIN_CONTROL_FAULT_CHECK_MAIN_MEMORY = 17 41 | MAIN_CONTROL_FAULT_CHECK_MAIN_NV_MEMORY = 18 42 | MAIN_INTERRUPT_FAULT_CHECK_SERIAL_OUTPUT_TIMER = 24 43 | MAIN_INTERRUPT_FAULT_CHECK_NVMEMORY_TIMER = 25 44 | MAIN_INTERRUPT_FAULT_CHECK_SERIAL_INPUT = 26 45 | MAIN_INTERRUPT_FAULT_CHECK_INPUT_FR_FRONT = 27 46 | MAIN_INTERRUPT_FAULT_CHECK_MAIN_CLOCK = 28 47 | MAIN_INTERRUPT_FAULT_CHECK_REMOTE_INPUT = 29 48 | MAIN_INTERRUPT_FAULT_CHECK_INPUT_FR_GUARD = 30 49 | FRONT_DIGITAL_FAULT_MEMORY = 32 50 | FRONT_DIGITAL_FAULT_PROCESSOR = 33 51 | INSIDE_GUARD_FAULT_CHECK_GUARD_MEMORY = 40 52 | INSIDE_GUARD_FAULT_CHECK_DATA_BUS = 41 53 | INSIDE_GUARD_FAULT_CHECK_ADDRESS_BUS = 42 54 | INSIDE_GUARD_FAULT_CHECK_GUARD_CONTROL_BUS = 43 55 | BOARD_ACK_FAULT_CHECK_DAC_BOARD = 48 56 | BOARD_ACK_FAULT_CHECK_PREAMP_BOARD = 49 57 | BOARD_ACK_FAULT_CHECK_SAMPLE_BOARD = 50 58 | BOARD_ACK_FAULT_CHECK_OUTPUT_BOARD = 51 59 | GUARD_COMMUNICATION_FAULT_CHECK_GARBLED_DATA = 56 60 | GUARD_COMMUNICATION_FAULT_GUARD_NOT_ANSWERING = 57 61 | FRONT_COMMUNICATION_FAULT = 64 62 | ANALOG_MEASURE_FAULT_CHECK_ANALOG_BUSS = 72 63 | ANALOG_MEASURE_FAULT_CHECK_ZERO_AMP = 73 64 | ANALOG_MEASURE_FAULT_UNABLE_TO_ZERO_RANGE = 74 65 | ANALOG_MEASURE_FAULT_GAIN_SHIFT_TOO_LARGE = 75 66 | DAC_DIGITAL_FAULT_CHECK_A_TO_D = 80 67 | DAC_DIGITAL_FAULT_CHECK_FIRST_SWITCH = 81 68 | DAC_DIGITAL_FAULT_SECOND_SWITCH = 82 69 | DAC_DIGITAL_FAULT_BIAS_SIGNAL = 83 70 | DAC_ANALOG_FAULT_CHECK_0V_OUTPUT = 87 71 | DAC_ANALOG_FAULT_CHECK_REFERENCE = 88 72 | DAC_ANALOG_FAULT_CHECK_NEG_5V_REGULATOR = 89 73 | DAC_ANALOG_FAULT_CHECK_10V_OUTPUT = 90 74 | DAC_ANALOG_FAULT_CHECK_NEG_10V_OUTPUT = 91 75 | DAC_ANALOG_FAULT_CHECK_DAC_FILTER = 92 76 | DAC_ANALOG_FAULT_CHECK_5V_DAC_CKT = 93 77 | DAC_ANALOG_FAULT_CHECK_SECOND_SPEED = 94 78 | DAC_ANALOG_FAULT_CHECK_DAC_OVEN = 95 79 | DAC_ANALOG_FAULT_CHECK_5V_DAC_REC = 96 80 | GRD_PWR_SUPPLY_FAULT_CHECK_20V_OVEN = 97 81 | PREAMP_ANALOG_FAULT_CHECK_INTCAL_CONFIG = 104 82 | PREAMP_OUT_BRDS_FAULT_CHECK_STANDBY_CONFIG = 109 83 | PREAMP_ANALOG_FAULT_CHECK_PREAMP_OVEN = 110 84 | OUTPUT_BOARDS_FAULT_CHECK_ZERO_AMP = 112 85 | OUTPUT_BOARDS_FAULT_CHECK_2V_RANGE = 113 86 | OUTPUT_BOARDS_FAULT_CHECK_CURR_LIM_CKT = 114 87 | OUTPUT_BOARDS_FAULT_CHECK_02V_RANGE = 115 88 | PREAMP_OUT_BRDS_FAULT_CHECK_250V_RANGE = 116 89 | SAMPLE_STRING_FAULT_CHECK_10V_INTCAL = 120 90 | SAMPLE_STRING_FAULT_CHECK_20V_INTCAL = 121 91 | SAMPLE_STRING_FAULT_CHECK_1KV_RANGE = 122 92 | PREAMP_SAMPLE_STRING_FAULT_CHECK_HIGH_V_INTCAL = 123 93 | FIL_BOUT_BRDS_FAULT_CHECK_NEG_275V_RANGE = 128 94 | FIL_BOUT_BRDS_FAULT_CHECK_275V_RANGE = 129 95 | FIL_BOUT_BRDS_FAULT_CHECK_550V_RANGE = 130 96 | FIL_BOUT_BRDS_FAULT_CHECK_875V_RANGE = 131 97 | FIL_BOUT_BRDS_FAULT_CHECK_1100V_RANGE = 132 98 | OUTPUT_LIMIT_FAULT = 136 99 | OUTPUT_LIMIT_FAULT_OUTPUT_OVER_VOLTAGE = 137 100 | OUTPUT_LIMIT_FAULT_OUTPUT_UNDER_VOLTAGE = 138 101 | BOOST_INTERFACE_ERROR_CHECK_REAR_CONNECTOR = 144 102 | BOOST_INTERFACE_ERROR_CHECK_MISSING_REAR_CABLE = 145 103 | BOOST_INTERFACE_ERROR_VOLTAGE_TRIP = 146 104 | BOOST_INTERFACE_ERROR_CURRENT_TRIP = 147 105 | IEEE488_REMOTE_ERROR_SOURCE_HANDSHAKE = 152 106 | IEEE488_REMOTE_ERROR_EXPECTING_TERMINATOR = 153 107 | IEEE488_REMOTE_ERROR_EXPECTING_SEPARATOR = 154 108 | IEEE488_REMOTE_ERROR_EXPECTING_HEADER = 155 109 | IEEE488_REMOTE_ERROR_EXPECTING_NUMBER = 156 110 | IEEE488_REMOTE_ERROR_EXPECTING_BUFFER_OVERFLOW = 157 111 | IEEE488_REMOTE_ERROR_EXPECTING_BAD_CHARACTER = 158 112 | RS232C_SERIAL_ERROR = 160 113 | USER_ENTRY_ERROR_NUMBER_OUT_OF_RANGE = 168 114 | USER_ENTRY_ERROR_OUTPUT_OUT_OF_RANGE = 169 115 | USER_ENTRY_ERROR_LIMITS_OUT_OF_RANGE = 170 116 | USER_ENTRY_ERROR_DIVIDER_OUT_OF_RANGE = 171 117 | USER_ENTRY_ERROR_IN_OUTPUT_TERMINAL_SENSE = 172 118 | USER_ENTRY_ERROR_IN_OUTPUT_TERMINAL_GUARD = 173 119 | CAL_SWITCH_LOCKED = 174 120 | USER_ENTRY_ERROR_INSTRUMENT_IS_BUSY = 175 121 | 122 | 123 | class ModeType(Enum): 124 | """The output modes. Voltage boost means a connected Fluke 5205A power amplifier and current boost means a connected 125 | Fluke 5220A transconductance amplifier.""" 126 | 127 | NORMAL = "BSTO" 128 | VOLTAGE_BOOST = "BSTV" 129 | CURRENT_BOOST = "BSTC" 130 | 131 | 132 | class SeparatorType(Enum): 133 | """The separator used to distinguish multiple return values.""" 134 | 135 | COMMA = 0 136 | COLON = 1 137 | 138 | 139 | class DeviceState(Enum): 140 | """The internal device state.""" 141 | 142 | IDLE = 0 143 | CALIBRATING_ADC = 16 144 | ZEROING_10V_POS = 32 145 | ZEROING_10V_NEG = 33 146 | ZEROING_20V_POS = 34 147 | ZEROING_20V_NEG = 35 148 | ZEROING_250V_POS = 36 149 | ZEROING_250V_NEG = 37 150 | ZEROING_1000V_POS = 38 151 | ZEROING_1000V_NEG = 39 152 | CALIBRATING_GAIN_10V_POS = 48 153 | CALIBRATING_GAIN_20V_POS = 49 154 | CALIBRATING_GAIN_HV_POS = 50 155 | CALIBRATING_GAIN_HV_NEG = 51 156 | CALIBRATING_GAIN_20V_NEG = 52 157 | CALIBRATING_GAIN_10V_NEG = 53 158 | EXT_CAL_10V = 64 159 | EXT_CAL_20V = 65 160 | EXT_CAL_250V = 66 161 | EXT_CAL_1000V = 67 162 | EXT_CAL_2V = 68 163 | EXT_CAL_02V = 69 164 | EXT_CAL_10V_NULL = 80 165 | EXT_CAL_20V_NULL = 81 166 | EXT_CAL_250V_NULL = 82 167 | EXT_CAL_1000V_NULL = 83 168 | EXT_CAL_2V_NULL = 84 169 | EXT_CAL_02V_NULL = 85 170 | CAL_N1_N2_RATIO = 96 171 | SELF_TEST_MAIN_CPU = 112 172 | SELF_TEST_FRONTPANEL_CPU = 113 173 | SELF_TEST_GUARD_CPU = 114 174 | SELF_TEST_LOW_VOLTAGE = 128 175 | SELF_TEST_HIGH_VOLTAGE = 129 176 | SELF_TEST_OVEN = 130 177 | PRINTING = 208 178 | WRITING_TO_NVRAM = 224 179 | RESETTING = 240 180 | 181 | 182 | class TerminatorType(Enum): 183 | """The line terminator used by the instrument.""" 184 | 185 | EOI = 0 186 | CR_LF_EOI = 1 187 | LF_EOI = 2 188 | CR_LF = 3 189 | LF = 4 190 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /fluke5440b_async/fluke_5440b.py: -------------------------------------------------------------------------------- 1 | # ##### BEGIN GPL LICENSE BLOCK ##### 2 | # 3 | # Copyright (C) 2023 Patrick Baus 4 | # This file is free software: you can redistribute it and/or modify 5 | # it under the terms of the GNU General Public License as published by 6 | # the Free Software Foundation, either version 3 of the License, or 7 | # (at your option) any later version. 8 | # 9 | # This file is distributed in the hope that it will be useful, 10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | # GNU General Public License for more details. 13 | # 14 | # You should have received a copy of the GNU General Public License 15 | # along with this file. If not, see . 16 | # 17 | # ##### END GPL LICENSE BLOCK ##### 18 | """ 19 | This is an asyncIO driver for the Fluke 5440B voltage calibrator to abstract away the GPIB interface. 20 | """ 21 | from __future__ import annotations 22 | 23 | import asyncio 24 | import logging 25 | from dataclasses import dataclass 26 | from decimal import Decimal 27 | from types import TracebackType 28 | from typing import TYPE_CHECKING, Type, cast 29 | 30 | from fluke5440b_async.enums import DeviceState, ErrorCode, ModeType, SelfTestErrorCode, SeparatorType, TerminatorType 31 | from fluke5440b_async.errors import DeviceError, SelftestError 32 | from fluke5440b_async.flags import SerialPollFlags, SrqMask, StatusFlags 33 | 34 | try: 35 | from typing import Self # type: ignore # Python 3.11 36 | except ImportError: 37 | from typing_extensions import Self 38 | 39 | if TYPE_CHECKING: 40 | from async_gpib import AsyncGpib 41 | from prologix_gpib_async import AsyncPrologixGpibController 42 | 43 | BAUD_RATES_AVAILABLE = (50, 75, 110, 134.5, 150, 200, 300, 600, 1200, 1800, 2400, 4800, 9600) 44 | 45 | 46 | @dataclass 47 | class CalibrationConstants: # pylint: disable=too-many-instance-attributes 48 | """The calibration constants of the Fluke 5440B.""" 49 | 50 | # capital V due to SI pylint: disable=invalid-name 51 | gain_02V: Decimal 52 | gain_2V: Decimal 53 | gain_10V: Decimal 54 | gain_20V: Decimal 55 | gain_250V: Decimal 56 | gain_1000V: Decimal 57 | offset_10V_pos: Decimal 58 | offset_20V_pos: Decimal 59 | offset_250V_pos: Decimal 60 | offset_1000V_pos: Decimal 61 | offset_10V_neg: Decimal 62 | offset_20V_neg: Decimal 63 | offset_250V_neg: Decimal 64 | offset_1000V_neg: Decimal 65 | gain_shift_10V: Decimal 66 | gain_shift_20V: Decimal 67 | gain_shift_250V: Decimal 68 | gain_shift_1000V: Decimal 69 | resolution_ratio: Decimal 70 | adc_gain: Decimal 71 | 72 | def __str__(self) -> str: 73 | """Pretty-print the calibration constants.""" 74 | return ( 75 | f"Gain 0.2 V : {self.gain_02V*10**3:.8f} mV\n" 76 | f"Gain 2 V : {self.gain_2V*10**3:.8f} mV\n" 77 | f"Gain 10 V : {self.gain_10V*10**3:.8f} mV\n" 78 | f"Gain 20 V : {self.gain_20V*10**3:.8f} mV\n" 79 | f"Gain 250 V : {self.gain_250V*10**3:.8f} mV\n" 80 | f"Gain 1000 V : {self.gain_1000V*10**3:.8f} mV\n" 81 | f"Offset +10 V : {self.offset_10V_pos*10**3:.8f} mV\n" 82 | f"Offset +20 V : {self.offset_20V_pos*10**3:.8f} mV\n" 83 | f"Offset +250 V : {self.offset_250V_pos*10**3:.8f} mV\n" 84 | f"Offset +1000 V : {self.offset_1000V_pos*10**3:.8f} mV\n" 85 | f"Offset -10 V : {self.offset_10V_neg*10**3:.8f} mV\n" 86 | f"Offset -20 V : {self.offset_20V_neg*10**3:.8f} mV\n" 87 | f"Offset -250 V : {self.offset_250V_neg*10**3:.8f} mV\n" 88 | f"Offset -1000 V : {self.offset_1000V_neg*10**3:.8f} mV\n" 89 | f"Gain shift 10 V : {self.gain_shift_10V} µV/V\n" 90 | f"Gain shift 20 V : {self.gain_shift_20V} µV/V\n" 91 | f"Gain shift 250 V : {self.gain_shift_250V} µV/V\n" 92 | f"Gain shift 1000 V: {self.gain_shift_1000V} µV/V\n" 93 | f"Resolution ratio : {self.resolution_ratio}\n" 94 | f"ADC gain : {self.adc_gain*10**3:.8f} mV" 95 | ) 96 | 97 | 98 | class Fluke_5440B: # noqa pylint: disable=too-many-public-methods,invalid-name,too-many-lines 99 | """ 100 | The driver for the Fluke 5440B voltage calibrator. It supports both linux-gpib and the Prologix GPIB adapters. 101 | """ 102 | 103 | @property 104 | def connection(self) -> AsyncGpib | AsyncPrologixGpibController: 105 | """ 106 | The GPIB connection. 107 | """ 108 | return self.__conn 109 | 110 | def __init__(self, connection: AsyncGpib | AsyncPrologixGpibController, log_level: int = logging.WARNING): 111 | """ 112 | Create Fluke 5440B device with the GPIB connection given. 113 | 114 | Parameters 115 | ---------- 116 | connection: AsyncGpib or AsyncPrologixGpibController 117 | The GPIB connection. 118 | log_level: int, default=logging.WARNING 119 | The level of logging output. By default, only warnings or higher are output. 120 | """ 121 | self.__conn = connection 122 | self.__lock: asyncio.Lock | None = None 123 | 124 | self.__logger = logging.getLogger(__name__) 125 | self.__logger.setLevel(log_level) # Only log really important messages by default 126 | 127 | def __str__(self) -> str: 128 | return f"Fluke 5440B at {str(self.connection)}" 129 | 130 | async def __aenter__(self) -> Self: 131 | await self.connect() 132 | return self 133 | 134 | async def __aexit__( 135 | self, exc_type: Type[BaseException] | None, exc: BaseException | None, traceback: TracebackType | None 136 | ) -> None: 137 | await self.disconnect() 138 | 139 | async def get_id(self) -> tuple[str, str, str, str]: 140 | """ 141 | Returns the instrument name and the software version string. To emulate the `*IDN?` SCPI command, the result 142 | is a tuple containing the Manufacturer, Device, Serial (0) and FW version. 143 | Returns 144 | ------- 145 | tuple of str 146 | A tuple containing the manufacturer id, device id, a zero, and the software version. 147 | """ 148 | version = (await self._get_software_version()).strip() 149 | return "Fluke", "5440B", "0", version 150 | 151 | def set_log_level(self, loglevel: int = logging.WARNING): 152 | """ 153 | Set the log level of the library. By default, the level is set to warning. 154 | Parameters 155 | ---------- 156 | loglevel: int, default=logging.WARNING 157 | The log level of the library 158 | """ 159 | self.__logger.setLevel(loglevel) 160 | 161 | async def connect(self) -> None: 162 | """ 163 | Connect the GPIB connection and configure the GPIB device for the DMM. This function must be called from the 164 | AsyncIO loop and takes care of connecting the GPIB adapter. 165 | """ 166 | self.__lock = asyncio.Lock() 167 | 168 | await self.__conn.connect() 169 | if hasattr(self.__conn, "set_eot"): 170 | # Used by the Prologix adapters 171 | await self.__conn.set_eot(False) 172 | 173 | async with self.__lock: 174 | status = await self.serial_poll() # clears the SRQ bit 175 | while status & SerialPollFlags.MSG_RDY: # clear message buffer 176 | msg = await self.read() 177 | self.__logger.debug("Calibrator message at boot: %s.", msg) 178 | status = await self.serial_poll() 179 | 180 | if status & SerialPollFlags.ERROR_CONDITION: 181 | err = await self.get_error() # clear error flags not produced by us 182 | error: ErrorCode | SelfTestErrorCode 183 | try: 184 | error = ErrorCode(err) 185 | except ValueError: 186 | error = SelfTestErrorCode(err) 187 | self.__logger.debug("Calibrator errors at boot: %s.", error) 188 | state = await self.get_state() 189 | self.__logger.debug("Calibrator state at boot: %s.", state) 190 | if state != DeviceState.IDLE: 191 | await self.set_srq_mask(SrqMask.DOING_STATE_CHANGE) 192 | await self.__wait_for_idle() 193 | 194 | await self.__set_terminator(TerminatorType.LF_EOI) # terminate lines with \n 195 | await self.__set_separator(SeparatorType.COMMA) # use a comma as the separator 196 | await self.set_srq_mask(SrqMask.NONE) # Disable interrupts 197 | 198 | async def disconnect(self) -> None: 199 | """ 200 | Disconnect from the instrument and clean up. This call will also automatically remove the local lockout if set. 201 | """ 202 | try: 203 | # Return access to the device 204 | await self.local() 205 | except ConnectionError: 206 | pass 207 | finally: 208 | await self.__conn.disconnect() 209 | 210 | async def write(self, cmd: str | bytes, test_error: bool = False): 211 | """ 212 | Write a string or bytestring to the instrument. 213 | Parameters 214 | ---------- 215 | cmd: str or bytes 216 | The command written to the device 217 | test_error: bool, default=False 218 | Check for errors by serial polling after sending the command. 219 | 220 | Raises 221 | ------ 222 | DeviceError 223 | If test_error is set to True and there was an error processing the command. 224 | """ 225 | assert isinstance(cmd, (str, bytes)) 226 | try: 227 | cmd = cmd.encode("ascii") # type: ignore[union-attr] 228 | except AttributeError: 229 | pass # cmd is already a bytestring 230 | assert isinstance(cmd, bytes) 231 | # The calibrator can only buffer 127 byte 232 | if len(cmd) > 127: 233 | raise ValueError("Command size must be 127 byte or less.") 234 | 235 | await self.__conn.write(cmd) 236 | if test_error: 237 | await asyncio.sleep(0.2) # The instrument is slow in parsing commands 238 | spoll = await self.serial_poll() 239 | if spoll & SerialPollFlags.ERROR_CONDITION: 240 | self.__logger.debug("Received error while writing command %s. Serial poll register: %s.", cmd, spoll) 241 | msg = None 242 | if spoll & SerialPollFlags.MSG_RDY: 243 | # The command did return some msg, so we need to read that first (and drop it) 244 | msg = await self.read() 245 | 246 | err = ErrorCode(await self.get_error()) 247 | if msg is None: 248 | raise DeviceError(f"Device error on command: {cmd.decode('utf-8')}, code: {err}", err) 249 | raise DeviceError( 250 | f"Device error on command: {cmd.decode('utf-8')}, code: {err}, Message returned: {msg}", err 251 | ) 252 | 253 | async def read(self) -> str | list[str]: 254 | """ 255 | Read from the device. 256 | Returns 257 | ------- 258 | str or list of str: 259 | Returns either a simple string, or if multiple results are returned, a list of strings. 260 | """ 261 | result = (await self.__conn.read()).rstrip().decode("utf-8").split(",") # strip \n and split at the separator 262 | return result[0] if len(result) == 1 else result 263 | 264 | async def query(self, cmd: str | bytes, test_error: bool = False) -> str | list[str]: 265 | """ 266 | Write a string or bytestring to the instrument, then immediately read back the result. This is a combined call 267 | to :func:`write` and :func:`read`. 268 | Parameters 269 | ---------- 270 | cmd: str or bytes 271 | The command written to the device 272 | test_error: bool, default=False 273 | Check for errors by serial polling after sending the command. 274 | 275 | Returns 276 | ------- 277 | str or list of str: 278 | Returns either a simple string, or if multiple results are returned, a list of strings. 279 | 280 | Raises 281 | ------ 282 | DeviceError 283 | If test_error is set to True and there was an error processing the command. 284 | """ 285 | await self.write(cmd, test_error) 286 | return await self.read() 287 | 288 | async def __wait_for_state_change(self) -> None: 289 | while (await self.serial_poll()) & SerialPollFlags.DOING_STATE_CHANGE: 290 | await asyncio.sleep(0.5) 291 | 292 | async def reset(self) -> None: 293 | """ 294 | Place the instrument in standby, enable voltage mode, set the output voltage to 0.0, disable the divider output, 295 | the external guard mode and external sense mode. 296 | Raises 297 | ------ 298 | DeviceError 299 | Raised if there was an error processing the command. 300 | """ 301 | assert self.__lock is not None 302 | async with self.__lock: 303 | # We do not send "RESET", because a DCL will do the same and additionally circumvents the input buffer 304 | await self.__conn.clear() 305 | # We cannot use interrupts, because the device is resetting all settings and will not accept commands 306 | # until it has reset. So we will poll the status register first, and when this is done, we will poll 307 | # the device itself until it is ready 308 | await self.__wait_for_state_change() 309 | while (await self.get_state()) != DeviceState.IDLE: 310 | await asyncio.sleep(0.5) 311 | 312 | await self.__set_terminator(TerminatorType.LF_EOI) # terminate lines with \n 313 | await self.__set_separator(SeparatorType.COMMA) # use a comma as the separator 314 | await self.set_srq_mask(SrqMask.NONE) # Disable interrupts 315 | 316 | async def local(self) -> None: 317 | """ 318 | Enable the front panel buttons, if the instrument is in local lock out. 319 | """ 320 | await self.__conn.ibloc() 321 | 322 | async def get_terminator(self) -> TerminatorType: 323 | """ 324 | Returns the line terminator sent by the instrument. 325 | Returns 326 | ------- 327 | TerminatorType 328 | The line terminator used by the device. 329 | """ 330 | assert self.__lock is not None 331 | async with self.__lock: 332 | result = await self.query("GTRM", test_error=True) 333 | try: 334 | assert isinstance(result, str) 335 | term = int(result) 336 | except TypeError: 337 | raise TypeError(f"Invalid reply received. Expected an integer, but received: {result}") from None 338 | return TerminatorType(term) 339 | 340 | async def __set_terminator(self, value: TerminatorType) -> None: 341 | """ 342 | Set the line terminator used by the instrument. The choice of line terminators are EOI, , 343 | , and only. Engage the lock, before calling. 344 | Parameters 345 | ---------- 346 | value: TerminatorType 347 | 348 | Raises 349 | ------ 350 | DeviceError 351 | Raised if there was an error processing the command. 352 | """ 353 | assert isinstance(value, TerminatorType) 354 | await self.write(f"STRM {value.value:d}", test_error=True) 355 | await self.__wait_for_state_change() 356 | 357 | async def get_separator(self) -> SeparatorType: 358 | """ 359 | Returns the separator used by the instrument to separate multiple queries. 360 | Returns 361 | ------- 362 | SeparatorType 363 | The separator used by the device. 364 | 365 | Raises 366 | ------ 367 | DeviceError 368 | Raised if there was an error processing the command. 369 | """ 370 | result = await self.query("GSEP", test_error=True) 371 | try: 372 | assert isinstance(result, str) 373 | sep = int(result) 374 | except TypeError: 375 | raise TypeError(f"Invalid reply received. Expected an integer, but received: {result}") from None 376 | return SeparatorType(sep) 377 | 378 | async def __set_separator(self, value: SeparatorType) -> None: 379 | """ 380 | Set the query separator used by the instrument. The choice of separators are "," (colon) and ";" (semicolon). 381 | Engage the lock, before calling. 382 | Parameters 383 | ---------- 384 | value: SeparatorType 385 | The separator used by the device. 386 | 387 | Raises 388 | ------ 389 | DeviceError 390 | Raised if there was an error processing the command. 391 | """ 392 | assert isinstance(value, SeparatorType) 393 | await self.write(f"SSEP {value.value:d}", test_error=True) 394 | await self.__wait_for_state_change() 395 | 396 | async def set_mode(self, value: ModeType) -> None: 397 | """ 398 | Enabled either voltage or current boost mode using an external Fluke 5205A power amplifier or a Fluke 5220A 399 | transconductance amplifier. 400 | Parameters 401 | ---------- 402 | value: ModeType 403 | Either normal mode, current or voltage boost. 404 | 405 | Raises 406 | ------ 407 | DeviceError 408 | Raised if there was an error processing the command. 409 | """ 410 | assert isinstance(value, ModeType) 411 | await self.write(f"{value.value}", test_error=True) 412 | 413 | async def set_output_enabled(self, enabled: bool) -> None: 414 | """ 415 | Set the output to either STANDBY or OPR. 416 | Parameters 417 | ---------- 418 | enabled: bool 419 | Set to OPR if true 420 | 421 | Raises 422 | ------ 423 | DeviceError 424 | Raised if there was an error processing the command. 425 | """ 426 | await self.write("OPER" if enabled else "STBY", test_error=True) 427 | 428 | async def get_output(self) -> Decimal: 429 | """ 430 | Returns the output voltage currently set. 431 | Returns 432 | ------- 433 | Decimal 434 | The output voltage set. 435 | 436 | Raises 437 | ------ 438 | DeviceError 439 | Raised if there was an error processing the command. 440 | """ 441 | result = await self.query("GOUT", test_error=True) 442 | assert isinstance(result, str) 443 | return Decimal(result) 444 | 445 | @staticmethod 446 | def __limit_numeric(value: int | float | Decimal) -> str: 447 | """ 448 | According to page 4-5 of the operator manual, the value needs to meet the following criteria: 449 | - Maximum of 8 significant digits 450 | - Exponent must have less than two digits 451 | - Integers must be less than 256 452 | - 10e-12 < abs(value) < 10e8 453 | Limit to to 10*-8 resolution (10 nV is the minimum) 454 | 455 | Parameters 456 | ---------- 457 | value: int or float or Decimal 458 | The input to format 459 | 460 | Returns 461 | ------- 462 | str 463 | A formatted string of the number. 464 | """ 465 | result = f"{value:.8f}" 466 | if abs(value) >= 1: # type: ignore[operator] 467 | # There are significant digits before the decimal point, so we need to limit the length of the string 468 | # to 9 characters (decimal point + 8 significant digits) 469 | result = f"{result:.9s}" 470 | return result 471 | 472 | async def set_output(self, value: int | float | Decimal, test_error: bool = True) -> None: 473 | """ 474 | Set the output of the calibrator. If an output greater than ±22 V is set, the calibrator will automatically go 475 | to STBY for safety reasons. Call `set_output_enabled(True)` to re-enable the output. 476 | Parameters 477 | ---------- 478 | value: int or float or Decimal 479 | The value to be set 480 | test_error: bool, Default=True 481 | Raise an exception if there was an error 482 | 483 | Raises 484 | ------ 485 | DeviceError 486 | Raised if there was an error processing the command and test_error was set to True. 487 | """ 488 | if -1500 > value > 1500: 489 | raise ValueError("Value out of range") 490 | try: 491 | await self.write(f"SOUT {self.__limit_numeric(value)}", test_error) 492 | except DeviceError as e: 493 | if e.code == ErrorCode.OUTPUT_OUTSIDE_LIMITS: 494 | raise ValueError("Value out of range") from None 495 | raise 496 | 497 | async def set_internal_sense(self, enabled: bool) -> None: 498 | """ 499 | If the load resistance is greater than 1 MΩ, 2-wire calibration can be used. Otherwise, the cable resistance 500 | will reduce the accuracy. Use internal sense for 2-wire calibrations. See page 2-13 of the operator manual for 501 | details. 502 | 503 | Parameters 504 | ---------- 505 | enabled: bool 506 | Set to True for 2-wire sense. 507 | 508 | Raises 509 | ------ 510 | DeviceError 511 | Raised if there was an error processing the command. 512 | """ 513 | try: 514 | await self.write("ISNS" if enabled else "ESNS", test_error=True) 515 | except DeviceError as e: 516 | if e.code == ErrorCode.INVALID_SENSE_MODE: 517 | raise TypeError("Sense mode not allowed.") from None 518 | raise 519 | 520 | async def set_internal_guard(self, enabled: bool) -> None: 521 | """ 522 | If set, the guard is internally connected to the output LO terminal. Use this, if the device being calibrated 523 | has floating inputs. If calibrating devices with grounded inputs, connect the guard terminal to the input LO of 524 | the device and disable the internal guard. See page 2-14 of the operator manual for details. 525 | Parameters 526 | ---------- 527 | enabled: bool 528 | Set to True for floating devices. 529 | 530 | Raises 531 | ------ 532 | DeviceError 533 | Raised if there was an error processing the command. 534 | """ 535 | try: 536 | await self.write("IGRD" if enabled else "EGRD", test_error=True) 537 | except DeviceError as e: 538 | if e.code == ErrorCode.INVALID_GUARD_MODE: 539 | raise TypeError("Guard mode not allowed.") from None 540 | raise 541 | 542 | async def set_divider(self, enabled: bool) -> None: 543 | """ 544 | Enable the internal 1:10 and 1:100 divider to reduce the output noise and increase the resolution of voltages 545 | in the range -2.2 V to 2.2 V. Do not enable the external sense connection via :func:`set_internal_sense(False)`, 546 | as this will decrease the accuracy. The divider has an output impedance of 450 Ω. The load should ideally be 547 | greater than 1 GΩ to keep the loading error below 1 ppm. See page 3-10 of the operator manual for details. 548 | 549 | Parameters 550 | ---------- 551 | enabled: bool 552 | Set to True to enable the divider. 553 | 554 | Raises 555 | ------ 556 | DeviceError 557 | Raised if there was an error processing the command. 558 | """ 559 | await self.write("DIVY" if enabled else "DIVN", test_error=True) 560 | 561 | async def get_voltage_limit(self) -> tuple[Decimal, Decimal]: 562 | """ 563 | Get the voltage limit set on the instrument. It will raise an error, when in current boost mode. 564 | Returns 565 | ------- 566 | tuple of Decimal 567 | The positive and negative limit 568 | 569 | Raises 570 | ------ 571 | DeviceError 572 | Raised if there was an error processing the command. 573 | """ 574 | # TODO: Needs testing for error when in current boost mode 575 | result = await self.query("GVLM", test_error=True) 576 | return Decimal(result[1]), Decimal(result[0]) 577 | 578 | async def set_voltage_limit( 579 | self, value: int | float | Decimal, value2: int | float | Decimal | None = None 580 | ) -> None: 581 | """ 582 | Set the positive and negative voltage limit. 583 | Parameters 584 | ---------- 585 | value: int or float or Decimal 586 | Either a positive or negative number to set the positive or negative limit. 587 | value2: int or float or Decimal, optional 588 | Either a positive or negative number to set the positive or negative limit. If omitted, only one limit will 589 | be set. 590 | 591 | Raises 592 | ------ 593 | DeviceError 594 | Raised if there was an error processing the command. 595 | ValueError 596 | Raised if the limits are out of bounds. 597 | """ 598 | value = Decimal(value) 599 | if -1500 > value > 1500: 600 | raise ValueError("Value out of range.") 601 | if value2 is not None: 602 | value2 = Decimal(value2) 603 | if not -1500 <= value2 <= 1500: 604 | raise ValueError("Value out of range.") 605 | if not value * value2 <= 0: 606 | # Make sure, that one value is positive and one value negative or zero. 607 | raise ValueError("Invalid voltage limit.") 608 | 609 | try: 610 | if value2 is not None: 611 | await self.write(f"SVLM {self.__limit_numeric(value2)}", test_error=True) 612 | await self.write(f"SVLM {self.__limit_numeric(value)}", test_error=True) 613 | except DeviceError as e: 614 | if e.code == ErrorCode.LIMIT_OUT_OF_RANGE: 615 | raise ValueError("Invalid voltage limit.") from None 616 | raise 617 | 618 | async def get_current_limit(self) -> Decimal | tuple[Decimal, Decimal]: 619 | """ 620 | Get the current limit set on the instrument. It will raise an error, when in voltage boost mode. 621 | Returns 622 | ------- 623 | tuple of Decimal 624 | The positive and negative limit 625 | 626 | Raises 627 | ------ 628 | DeviceError 629 | Raised if there was an error processing the command. 630 | """ 631 | # TODO: Needs testing for error when in voltage boost mode 632 | result = await self.query("GCLM", test_error=True) 633 | if isinstance(result, list): 634 | return Decimal(result[1]), Decimal(result[0]) 635 | return Decimal(result) 636 | 637 | async def set_current_limit( 638 | self, value: int | float | Decimal, value2: int | float | Decimal | None = None 639 | ) -> None: 640 | """ 641 | Set the positive and negative current limit. 642 | Parameters 643 | ---------- 644 | value: int or float or Decimal 645 | Either a positive or negative number to set the positive or negative limit. 646 | value2: int or float or Decimal, optional 647 | Either a positive or negative number to set the positive or negative limit. If omitted, only one limit will 648 | be set. 649 | 650 | Raises 651 | ------ 652 | DeviceError 653 | Raised if there was an error processing the command. 654 | ValueError 655 | Raised if the limits are out of bounds. 656 | """ 657 | value = Decimal(value) 658 | if -20 > value > 20: 659 | raise ValueError("Value out of range.") 660 | if value2 is not None: 661 | value2 = Decimal(value2) 662 | if not -20 <= value2 <= 20: 663 | raise ValueError("Value out of range.") 664 | if not value * value2 <= 0: 665 | raise ValueError("Invalid current limit.") 666 | 667 | try: 668 | if value2 is not None: 669 | await self.write(f"SCLM {self.__limit_numeric(value2)}", test_error=True) 670 | await self.write(f"SCLM {self.__limit_numeric(value)}", test_error=True) 671 | except DeviceError as e: 672 | if e.code == ErrorCode.LIMIT_OUT_OF_RANGE: 673 | raise ValueError("Invalid current limit.") from None 674 | raise 675 | 676 | async def _get_software_version(self) -> str: 677 | """ 678 | Query the version number of the device software. It will return a string formatted as dd.dd. 679 | Returns 680 | ------- 681 | str 682 | The software version number of the instrument. 683 | 684 | Raises 685 | ------ 686 | DeviceError 687 | Raised if there was an error processing the command. 688 | """ 689 | result = await self.query("GVRS", test_error=True) 690 | assert isinstance(result, str) 691 | return result 692 | 693 | async def get_status(self) -> StatusFlags: 694 | """ 695 | Get the status of the instrument. The status flags contain the mode the instrument is running in, like boost 696 | mode, or the state of the external sense connection, etc. 697 | Returns 698 | ------- 699 | StatusFlags 700 | The status flags of the different settings 701 | 702 | Raises 703 | ------ 704 | DeviceError 705 | Raised if there was an error processing the command. 706 | """ 707 | result = await self.query("GSTS", test_error=True) 708 | try: 709 | assert isinstance(result, str) 710 | status = int(result) 711 | except TypeError: 712 | raise TypeError(f"Invalid reply received. Expected an integer, but received: {result}") from None 713 | 714 | return StatusFlags(status) 715 | 716 | async def get_error(self) -> int: 717 | """ 718 | Get the last error thrown by the instrument if any. It is recommended to check for errors after using the 719 | :func:`write` function, if the `test_error` parameter is not set. 720 | Returns 721 | ------- 722 | int 723 | The last error thrown. It might be an ErrorCode or a SelfTestErrorCode. This is ambiguous and depends on the 724 | last command. 725 | """ 726 | # Do not test for errors, because this is an infinite loop. 727 | result = await self.query("GERR", test_error=False) 728 | try: 729 | assert isinstance(result, str) 730 | error_code = int(result) 731 | except TypeError: 732 | raise TypeError(f"Invalid reply received. Expected an integer, but received: {result}") from None 733 | 734 | return error_code 735 | 736 | async def get_state(self) -> DeviceState: 737 | """ 738 | While the instrument is running long jobs, it signals its current state. Use this to poll the state. 739 | Returns 740 | ------- 741 | DeviceState 742 | The current device state. 743 | 744 | Raises 745 | ------ 746 | DeviceError 747 | Raised if there was an error processing the command. 748 | """ 749 | result = await self.query("GDNG", test_error=True) 750 | try: 751 | assert isinstance(result, str) 752 | dev_state = int(result) 753 | except TypeError: 754 | raise TypeError(f"Invalid reply received. Expected an integer, but received: {result}") from None 755 | 756 | return DeviceState(dev_state) 757 | 758 | async def __wait_for_rqs(self, raise_error: bool = True) -> SerialPollFlags: 759 | """Wait until the device requests service (RQS)""" 760 | try: 761 | await self.__conn.wait((1 << 11) | (1 << 14)) # Wait for RQS or TIMO 762 | except asyncio.TimeoutError: 763 | self.__logger.warning( 764 | "Timeout during wait. Is the IbaAUTOPOLL(0x7) bit set for the board? Or the timeout set too low?" 765 | ) 766 | 767 | spoll = await self.serial_poll() # Clear the SRQ bit 768 | if spoll & SerialPollFlags.ERROR_CONDITION and raise_error: 769 | self.__logger.debug( 770 | "Received error while waiting for device to request service. Serial poll register: %s.", spoll 771 | ) 772 | # If there was an error during waiting, raise it. 773 | # I have seen GPIB_HANDSHAKE_ERRORs with a prologix adapter, which does a lot of polling during wait. 774 | # Ignore that error for now. 775 | err = ErrorCode(await self.get_error()) 776 | if err is ErrorCode.GPIB_HANDSHAKE_ERROR: 777 | self.__logger.info( 778 | "Got error during waiting: %s. " 779 | "If you are using a Prologix adapter, this can be safely ignored at this point.", 780 | err, 781 | ) 782 | else: 783 | raise DeviceError(f"Device error, code: {err}", err) 784 | return spoll 785 | 786 | async def __wait_for_idle(self) -> None: 787 | """ 788 | Make sure, that SrqMask.DOING_STATE_CHANGE is set. 789 | """ 790 | state = await self.get_state() 791 | while state != DeviceState.IDLE: 792 | self.__logger.info("Calibrator busy: %s.", state) 793 | await self.__wait_for_rqs() 794 | state = await self.get_state() 795 | 796 | async def selftest_digital(self) -> None: 797 | """ 798 | Test the main CPU, the front panel CPU and the guard CPU. It will take about 5 seconds during which the 799 | instrument hardware is blocked. See page 3-19 of the operator manual for details. 800 | 801 | Raises 802 | ------ 803 | DeviceError 804 | Raised if there was an error processing the command. 805 | """ 806 | assert self.__lock is not None 807 | async with self.__lock: 808 | await self.set_srq_mask(SrqMask.DOING_STATE_CHANGE) # Enable SRQs to wait for each test step 809 | try: 810 | self.__logger.info("Running digital self-test. This takes about 5 seconds.") 811 | await self.__wait_for_idle() 812 | 813 | await self.write("TSTD", test_error=True) 814 | while "testing": 815 | status = await self.__wait_for_rqs(raise_error=False) 816 | if status & SerialPollFlags.ERROR_CONDITION: 817 | error_code = await self.get_error() 818 | raise SelftestError("Digital", SelfTestErrorCode(error_code)) 819 | if status & SerialPollFlags.DOING_STATE_CHANGE: 820 | state = await self.get_state() 821 | if state not in ( 822 | DeviceState.IDLE, 823 | DeviceState.SELF_TEST_MAIN_CPU, 824 | DeviceState.SELF_TEST_FRONTPANEL_CPU, 825 | DeviceState.SELF_TEST_GUARD_CPU, 826 | ): 827 | self.__logger.warning("Digital self-test failed. Invalid state: %s.", state) 828 | 829 | if state == DeviceState.IDLE: 830 | break 831 | self.__logger.info("Self-test status: %s.", state) 832 | self.__logger.info("Digital self-test passed.") 833 | finally: 834 | await self.set_srq_mask(SrqMask.NONE) # Disable SRQs 835 | 836 | async def selftest_analog(self) -> None: 837 | """ 838 | Test the ADC, the low voltage part and the oven. It will take about 4 minutes during which the instrument 839 | hardware is blocked. See page 3-19 of the operator manual for details. 840 | 841 | Raises 842 | ------ 843 | DeviceError 844 | Raised if there was an error processing the command. 845 | """ 846 | assert self.__lock is not None 847 | async with self.__lock: 848 | await self.set_srq_mask(SrqMask.DOING_STATE_CHANGE) # Enable SRQs to wait for each test step 849 | try: 850 | self.__logger.info("Running analog self-test. This takes about 4 minutes.") 851 | await self.__wait_for_idle() 852 | 853 | await self.write("TSTA", test_error=True) 854 | while "testing": 855 | status = await self.__wait_for_rqs(raise_error=False) 856 | if status & SerialPollFlags.ERROR_CONDITION: 857 | error_code = await self.get_error() 858 | raise SelftestError("Analog", SelfTestErrorCode(error_code)) 859 | if status & SerialPollFlags.DOING_STATE_CHANGE: 860 | state = await self.get_state() 861 | if state not in ( 862 | DeviceState.IDLE, 863 | DeviceState.CALIBRATING_ADC, 864 | DeviceState.SELF_TEST_LOW_VOLTAGE, 865 | DeviceState.SELF_TEST_OVEN, 866 | ): 867 | self.__logger.warning("Analog self-test failed. Invalid state: %s.", state) 868 | 869 | if state == DeviceState.IDLE: 870 | break 871 | self.__logger.info("Self-test status: %s.", state) 872 | self.__logger.info("Analog self-test passed.") 873 | finally: 874 | await self.set_srq_mask(SrqMask.NONE) # Disable SRQs 875 | 876 | async def selftest_hv(self) -> None: 877 | """ 878 | Test the ADC and the high voltage part. It will take about 1 minute during which the instrument hardware is 879 | blocked. See page 3-20 of the operator manual for details. 880 | 881 | Raises 882 | ------ 883 | DeviceError 884 | Raised if there was an error processing the command. 885 | """ 886 | assert self.__lock is not None 887 | async with self.__lock: 888 | await self.set_srq_mask(SrqMask.DOING_STATE_CHANGE) # Enable SRQs to wait for each test step 889 | try: 890 | self.__logger.info("Running high voltage self-test. This takes about 1 minute.") 891 | await self.__wait_for_idle() 892 | 893 | await self.write("TSTH", test_error=True) 894 | while "testing": 895 | status = await self.__wait_for_rqs(raise_error=False) 896 | if status & SerialPollFlags.ERROR_CONDITION: 897 | error_code = await self.get_error() 898 | raise SelftestError("High voltage", SelfTestErrorCode(error_code)) 899 | if status & SerialPollFlags.DOING_STATE_CHANGE: 900 | state = await self.get_state() 901 | if state not in ( 902 | DeviceState.IDLE, 903 | DeviceState.CALIBRATING_ADC, 904 | DeviceState.SELF_TEST_HIGH_VOLTAGE, 905 | ): 906 | self.__logger.warning("High voltage self-test failed. Invalid state: %s.", state) 907 | 908 | if state == DeviceState.IDLE: 909 | break 910 | self.__logger.info("Self-test status: %s.", state) 911 | self.__logger.info("High voltage self-test passed.") 912 | finally: 913 | await self.set_srq_mask(SrqMask.NONE) # Disable SRQs 914 | 915 | async def selftest_all(self) -> None: 916 | """ 917 | Run all three self-tests. This function is a combination of :func:`selftest_digital`, :func:`selftest_analog` 918 | and :func:`selftest_hv`. 919 | 920 | Raises 921 | ------ 922 | DeviceError 923 | Raised if there was an error processing the command. 924 | """ 925 | await self.selftest_digital() 926 | await self.selftest_analog() 927 | await self.selftest_hv() 928 | 929 | async def acal(self) -> None: 930 | """ 931 | Run the internal calibration routine. It will take about 6.5 minutes during which the instrument hardware is 932 | blocked. See page 3-2 of the operator manual for details. 933 | """ 934 | assert self.__lock is not None 935 | async with self.__lock: 936 | await self.set_srq_mask(SrqMask.DOING_STATE_CHANGE) # Enable SRQs to wait for each calibration step 937 | try: 938 | self.__logger.info("Running internal calibration. This will take about 6.5 minutes.") 939 | await self.__wait_for_idle() 940 | 941 | await self.write("CALI", test_error=True) 942 | while "calibrating": 943 | await self.__wait_for_rqs() 944 | state = await self.get_state() 945 | if state not in ( 946 | DeviceState.IDLE, 947 | DeviceState.CALIBRATING_ADC, 948 | DeviceState.ZEROING_10V_POS, 949 | DeviceState.CAL_N1_N2_RATIO, 950 | DeviceState.ZEROING_10V_NEG, 951 | DeviceState.ZEROING_20V_POS, 952 | DeviceState.ZEROING_20V_NEG, 953 | DeviceState.ZEROING_250V_POS, 954 | DeviceState.ZEROING_250V_NEG, 955 | DeviceState.ZEROING_1000V_POS, 956 | DeviceState.ZEROING_1000V_NEG, 957 | DeviceState.CALIBRATING_GAIN_10V_POS, 958 | DeviceState.CALIBRATING_GAIN_20V_POS, 959 | DeviceState.CALIBRATING_GAIN_HV_POS, 960 | DeviceState.CALIBRATING_GAIN_HV_NEG, 961 | DeviceState.CALIBRATING_GAIN_20V_NEG, 962 | DeviceState.CALIBRATING_GAIN_10V_NEG, 963 | DeviceState.WRITING_TO_NVRAM, 964 | ): 965 | self.__logger.warning("Internal calibration failed. Invalid state: %s.", state) 966 | 967 | if state == DeviceState.IDLE: 968 | break 969 | self.__logger.info("Calibration status: %s", state) 970 | self.__logger.info("Internal calibration done.") 971 | finally: 972 | await self.set_srq_mask(SrqMask.NONE) # Disable SRQs 973 | 974 | async def get_calibration_constants(self) -> CalibrationConstants: 975 | """ 976 | Query the calibration constants and gain shifts with respect to the previous internal calibration. See page 3-18 977 | of the operator manual for details. 978 | Returns 979 | ------- 980 | CalibrationConstants: 981 | A dataclass containing the constants as Decimals 982 | """ 983 | assert self.__lock is not None 984 | async with self.__lock: 985 | # We need to split the query in two parts, because the input buffer of the 5440B is only 127 byte 986 | values = cast(list[str], await self.query(",".join(["GCAL " + str(i) for i in range(10)]), test_error=True)) 987 | values += cast( 988 | list[str], await self.query(",".join(["GCAL " + str(i) for i in range(10, 20)]), test_error=True) 989 | ) 990 | return CalibrationConstants( 991 | gain_02V=Decimal(values[5]), 992 | gain_2V=Decimal(values[4]), 993 | gain_10V=Decimal(values[0]), 994 | gain_20V=Decimal(values[1]), 995 | gain_250V=Decimal(values[2]), 996 | gain_1000V=Decimal(values[3]), 997 | offset_10V_pos=Decimal(values[6]), 998 | offset_20V_pos=Decimal(values[7]), 999 | offset_250V_pos=Decimal(values[8]), 1000 | offset_1000V_pos=Decimal(values[9]), 1001 | offset_10V_neg=Decimal(values[10]), 1002 | offset_20V_neg=Decimal(values[11]), 1003 | offset_250V_neg=Decimal(values[12]), 1004 | offset_1000V_neg=Decimal(values[13]), 1005 | gain_shift_10V=Decimal(values[14]), 1006 | gain_shift_20V=Decimal(values[15]), 1007 | gain_shift_250V=Decimal(values[16]), 1008 | gain_shift_1000V=Decimal(values[17]), 1009 | resolution_ratio=Decimal(values[18]), 1010 | adc_gain=Decimal(values[19]), 1011 | ) 1012 | 1013 | async def get_rs232_baud_rate(self) -> int | float: 1014 | """ 1015 | Return the RS-232 the baud rate in bit/s. 1016 | Returns 1017 | ------- 1018 | float 1019 | The baud rate in bit/s 1020 | 1021 | Raises 1022 | ------ 1023 | DeviceError 1024 | If test_error is set to True and there was an error processing the command. 1025 | """ 1026 | result = await self.query("GBDR", test_error=True) 1027 | try: 1028 | assert isinstance(result, str) 1029 | baud_rate = int(result) 1030 | except TypeError: 1031 | raise TypeError(f"Invalid reply received. Expected an integer, but received: {result}") from None 1032 | return BAUD_RATES_AVAILABLE[baud_rate] 1033 | 1034 | async def set_rs232_baud_rate(self, value: int | float) -> None: 1035 | """ 1036 | Set the baud rate of the RS-232 interface. 1037 | Parameters 1038 | ---------- 1039 | value: {50, 75, 110, 134.5, 150, 200, 300, 600, 1200, 1800, 2400, 4800, 9600} 1040 | The baud rate. 1041 | 1042 | Raises 1043 | ------ 1044 | DeviceError 1045 | If test_error is set to True and there was an error processing the command. 1046 | """ 1047 | if value not in BAUD_RATES_AVAILABLE: 1048 | raise ValueError(f"Invalid baud rate. It must be one of: {','.join(map(str, BAUD_RATES_AVAILABLE))}.") 1049 | assert self.__lock is not None 1050 | async with self.__lock: 1051 | self.__logger.info("Setting baud rate to %d and writing to NVRAM. This takes about 1.5 minutes.", value) 1052 | try: 1053 | await self.write(f"SBDR {BAUD_RATES_AVAILABLE.index(value):d}", test_error=True) 1054 | await self.set_srq_mask(SrqMask.DOING_STATE_CHANGE) # Enable SRQs to wait until written to NVRAM 1055 | await asyncio.sleep(0.5) 1056 | await self.__wait_for_idle() 1057 | finally: 1058 | await self.set_srq_mask(SrqMask.NONE) # Disable SRQs 1059 | 1060 | async def set_enable_rs232(self, enabled: bool) -> None: 1061 | """ 1062 | Enable the RS-232 printer port. 1063 | Parameters 1064 | ---------- 1065 | enabled: bool 1066 | True to enable the RS-232 port. 1067 | 1068 | Raises 1069 | ------ 1070 | DeviceError 1071 | If test_error is set to True and there was an error processing the command. 1072 | """ 1073 | await self.write("MONY" if enabled else "MONN", test_error=True) 1074 | 1075 | async def serial_poll(self) -> SerialPollFlags: 1076 | """ 1077 | Poll the serial output buffer of the device. This can be used to query for the SRQ bit when device requests 1078 | service, has encountered an error or is busy. 1079 | Returns 1080 | ------- 1081 | SerialPollFlags 1082 | The content of the serial output buffer 1083 | """ 1084 | return SerialPollFlags(int(await self.__conn.serial_poll())) 1085 | 1086 | async def get_srq_mask(self) -> SrqMask: 1087 | """ 1088 | Get the SRQ mask. This mask is used to determine, when the device will signal the SRQ line. 1089 | Returns 1090 | ------- 1091 | SrqMask 1092 | The bitmask to determine the bits to signal. 1093 | 1094 | Raises 1095 | ------ 1096 | DeviceError 1097 | If test_error is set to True and there was an error processing the command. 1098 | """ 1099 | result = await self.query("GSRQ", test_error=True) 1100 | try: 1101 | assert isinstance(result, str) 1102 | mask = int(result) 1103 | except TypeError: 1104 | raise TypeError(f"Invalid reply received. Expected an integer, but received: {result}") from None 1105 | return SrqMask(mask) 1106 | 1107 | async def set_srq_mask(self, value: SrqMask) -> None: 1108 | """ 1109 | Set the service request mask register. Each bit set, will signal the SRQ line, when a service request of the 1110 | device is triggered. 1111 | Parameters 1112 | ---------- 1113 | value: SrqMask 1114 | The bitmask to set. 1115 | 1116 | Raises 1117 | ------ 1118 | DeviceError 1119 | If test_error is set to True and there was an error processing the command. 1120 | """ 1121 | assert isinstance(value, SrqMask) 1122 | await self.write(f"SSRQ {value.value:d}", test_error=True) 1123 | --------------------------------------------------------------------------------