From b52383713968f25ec502fda58ab0b4477367bead Mon Sep 17 00:00:00 2001 From: Rob van der Most Date: Sun, 12 Jan 2020 12:09:06 +0100 Subject: [PATCH] Version 0.1.0 - Basic AVR support --- .editorconfig | 21 +++ .github/ISSUE_TEMPLATE.md | 15 ++ .github/workflows/pythonpackage.yml | 38 ++++ .github/workflows/pythonpublish.yml | 26 +++ .gitignore | 112 ++++++++++++ .readthedocs.yml | 17 ++ AUTHORS.rst | 13 ++ CONTRIBUTING.rst | 127 +++++++++++++ HISTORY.rst | 20 +++ LICENSE | 22 +++ MANIFEST.in | 11 ++ Makefile | 91 ++++++++++ README.md | 1 - README.rst | 44 +++++ aio_marantz_avr/__init__.py | 17 ++ aio_marantz_avr/avr.py | 268 ++++++++++++++++++++++++++++ aio_marantz_avr/cli.py | 91 ++++++++++ aio_marantz_avr/enums.py | 91 ++++++++++ docs/Makefile | 20 +++ docs/authors.rst | 1 + docs/conf.py | 162 +++++++++++++++++ docs/contributing.rst | 1 + docs/history.rst | 1 + docs/index.rst | 20 +++ docs/installation.rst | 51 ++++++ docs/make.bat | 36 ++++ docs/readme.rst | 1 + docs/usage.rst | 7 + pyproject.toml | 2 + requirements_dev.txt | 16 ++ setup.cfg | 29 +++ setup.py | 53 ++++++ tests/__init__.py | 1 + tests/test_avr.py | 260 +++++++++++++++++++++++++++ tox.ini | 27 +++ 35 files changed, 1712 insertions(+), 1 deletion(-) create mode 100644 .editorconfig create mode 100644 .github/ISSUE_TEMPLATE.md create mode 100644 .github/workflows/pythonpackage.yml create mode 100644 .github/workflows/pythonpublish.yml create mode 100644 .gitignore create mode 100644 .readthedocs.yml create mode 100644 AUTHORS.rst create mode 100644 CONTRIBUTING.rst create mode 100644 HISTORY.rst create mode 100644 LICENSE create mode 100644 MANIFEST.in create mode 100644 Makefile delete mode 100644 README.md create mode 100644 README.rst create mode 100644 aio_marantz_avr/__init__.py create mode 100644 aio_marantz_avr/avr.py create mode 100644 aio_marantz_avr/cli.py create mode 100644 aio_marantz_avr/enums.py create mode 100644 docs/Makefile create mode 100644 docs/authors.rst create mode 100755 docs/conf.py create mode 100644 docs/contributing.rst create mode 100644 docs/history.rst create mode 100644 docs/index.rst create mode 100644 docs/installation.rst create mode 100644 docs/make.bat create mode 100644 docs/readme.rst create mode 100644 docs/usage.rst create mode 100644 pyproject.toml create mode 100644 requirements_dev.txt create mode 100644 setup.cfg create mode 100644 setup.py create mode 100644 tests/__init__.py create mode 100644 tests/test_avr.py create mode 100644 tox.ini diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000..d4a2c44 --- /dev/null +++ b/.editorconfig @@ -0,0 +1,21 @@ +# http://editorconfig.org + +root = true + +[*] +indent_style = space +indent_size = 4 +trim_trailing_whitespace = true +insert_final_newline = true +charset = utf-8 +end_of_line = lf + +[*.bat] +indent_style = tab +end_of_line = crlf + +[LICENSE] +insert_final_newline = false + +[Makefile] +indent_style = tab diff --git a/.github/ISSUE_TEMPLATE.md b/.github/ISSUE_TEMPLATE.md new file mode 100644 index 0000000..d42576d --- /dev/null +++ b/.github/ISSUE_TEMPLATE.md @@ -0,0 +1,15 @@ +* AsyncIO Marantz AVR version: +* Python version: +* Operating System: + +### Description + +Describe what you were trying to get done. +Tell us what happened, what went wrong, and what you expected to happen. + +### What I Did + +``` +Paste the command(s) you ran and the output. +If there was a crash, please include the traceback here. +``` diff --git a/.github/workflows/pythonpackage.yml b/.github/workflows/pythonpackage.yml new file mode 100644 index 0000000..b3582b2 --- /dev/null +++ b/.github/workflows/pythonpackage.yml @@ -0,0 +1,38 @@ +name: Python package + +on: [push] + +jobs: + build: + + runs-on: ubuntu-latest + strategy: + max-parallel: 4 + matrix: + python-version: [3.6, 3.7, 3.8] + + steps: + - uses: actions/checkout@v1 + - name: Set up Python ${{ matrix.python-version }} + uses: actions/setup-python@v1 + with: + python-version: ${{ matrix.python-version }} + - name: Install dependencies + run: | + python -m pip install --upgrade pip + python setup.py develop + - name: Lint with flake8 + run: | + pip install flake8 + # stop the build if there are Python syntax errors or undefined names + flake8 . --count --select=E9,F63,F7,F82 --show-source --statistics + # exit-zero treats all errors as warnings. The GitHub editor is 127 chars wide + flake8 . --count --exit-zero --max-complexity=10 --max-line-length=127 --statistics + - name: Check types + run: | + pip install mypy + mypy aio_marantz_avr + - name: Test with pytest + run: | + pip install pytest pytest-asyncio + pytest diff --git a/.github/workflows/pythonpublish.yml b/.github/workflows/pythonpublish.yml new file mode 100644 index 0000000..21f2f01 --- /dev/null +++ b/.github/workflows/pythonpublish.yml @@ -0,0 +1,26 @@ +name: Upload Python Package + +on: + release: + types: [created] + +jobs: + deploy: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v1 + - name: Set up Python + uses: actions/setup-python@v1 + with: + python-version: '3.x' + - name: Install dependencies + run: | + python -m pip install --upgrade pip + pip install setuptools wheel twine + - name: Build and publish + env: + TWINE_USERNAME: ${{ secrets.PYPI_USERNAME }} + TWINE_PASSWORD: ${{ secrets.PYPI_PASSWORD }} + run: | + python setup.py sdist bdist_wheel + twine upload dist/* diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..b62d0ba --- /dev/null +++ b/.gitignore @@ -0,0 +1,112 @@ +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class + +# C extensions +*.so + +# Distribution / packaging +.Python +env/ +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +wheels/ +*.egg-info/ +.installed.cfg +*.egg + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*.cover +.hypothesis/ +.pytest_cache/ + +# Translations +*.mo +*.pot + +# Django stuff: +*.log +local_settings.py + +# Flask stuff: +instance/ +.webassets-cache + +# Scrapy stuff: +.scrapy + +# Sphinx documentation +docs/_build/ + +# PyBuilder +target/ + +# Jupyter Notebook +.ipynb_checkpoints + +# pyenv +.python-version + +# celery beat schedule file +celerybeat-schedule + +# SageMath parsed files +*.sage.py + +# dotenv +.env + +# virtualenv +.venv +venv/ +ENV/ + +# Spyder project settings +.spyderproject +.spyproject + +# Rope project settings +.ropeproject + +# mkdocs documentation +/site + +# mypy +.mypy_cache/ + +# IDE settings +.vscode/ + + +.venv + +# Generated documentation +docs/aio_marantz_avr.rst +docs/modules.rst diff --git a/.readthedocs.yml b/.readthedocs.yml new file mode 100644 index 0000000..a40249a --- /dev/null +++ b/.readthedocs.yml @@ -0,0 +1,17 @@ +# Read the Docs configuration file +# See https://docs.readthedocs.io/en/stable/config-file/v2.html for details + +version: 2 + +sphinx: + configuration: docs/conf.py + +formats: all + +# Optionally set the version of Python and requirements required to build your docs +python: + version: 3.7 + install: + - method: setuptools + path: . + - requirements: requirements_dev.txt diff --git a/AUTHORS.rst b/AUTHORS.rst new file mode 100644 index 0000000..24b86cb --- /dev/null +++ b/AUTHORS.rst @@ -0,0 +1,13 @@ +======= +Credits +======= + +Development Lead +---------------- + +* Rob van der Most + +Contributors +------------ + +None yet. Why not be the first? diff --git a/CONTRIBUTING.rst b/CONTRIBUTING.rst new file mode 100644 index 0000000..9f9377f --- /dev/null +++ b/CONTRIBUTING.rst @@ -0,0 +1,127 @@ +.. highlight:: shell + +============ +Contributing +============ + +Contributions are welcome, and they are greatly appreciated! Every little bit +helps, and credit will always be given. + +You can contribute in many ways: + +Types of Contributions +---------------------- + +Report Bugs +~~~~~~~~~~~ + +Report bugs at https://github.com/silvester747/aio_marantz_avr/issues. + +If you are reporting a bug, please include: + +* Your operating system name and version. +* Any details about your local setup that might be helpful in troubleshooting. +* Detailed steps to reproduce the bug. + +Fix Bugs +~~~~~~~~ + +Look through the GitHub issues for bugs. Anything tagged with "bug" and "help +wanted" is open to whoever wants to implement it. + +Implement Features +~~~~~~~~~~~~~~~~~~ + +Look through the GitHub issues for features. Anything tagged with "enhancement" +and "help wanted" is open to whoever wants to implement it. + +Write Documentation +~~~~~~~~~~~~~~~~~~~ + +AsyncIO Marantz AVR could always use more documentation, whether as part of the +official AsyncIO Marantz AVR docs, in docstrings, or even on the web in blog posts, +articles, and such. + +Submit Feedback +~~~~~~~~~~~~~~~ + +The best way to send feedback is to file an issue at https://github.com/silvester747/aio_marantz_avr/issues. + +If you are proposing a feature: + +* Explain in detail how it would work. +* Keep the scope as narrow as possible, to make it easier to implement. +* Remember that this is a volunteer-driven project, and that contributions + are welcome :) + +Get Started! +------------ + +Ready to contribute? Here's how to set up `aio_marantz_avr` for local development. + +1. Fork the `aio_marantz_avr` repo on GitHub. +2. Clone your fork locally:: + + $ git clone git@github.com:your_name_here/aio_marantz_avr.git + +3. Install your local copy into a virtualenv. Assuming you have virtualenvwrapper installed, this is how you set up your fork for local development:: + + $ mkvirtualenv aio_marantz_avr + $ cd aio_marantz_avr/ + $ python setup.py develop + +4. Create a branch for local development:: + + $ git checkout -b name-of-your-bugfix-or-feature + + Now you can make your changes locally. + +5. When you're done making changes, check that your changes pass flake8 and the + tests, including testing other Python versions with tox:: + + $ flake8 aio_marantz_avr tests + $ python setup.py test or pytest + $ tox + + To get flake8 and tox, just pip install them into your virtualenv. + +6. Commit your changes and push your branch to GitHub:: + + $ git add . + $ git commit -m "Your detailed description of your changes." + $ git push origin name-of-your-bugfix-or-feature + +7. Submit a pull request through the GitHub website. + +Pull Request Guidelines +----------------------- + +Before you submit a pull request, check that it meets these guidelines: + +1. The pull request should include tests. +2. If the pull request adds functionality, the docs should be updated. Put + your new functionality into a function with a docstring, and add the + feature to the list in README.rst. +3. The pull request should work for Python 3.6, 3.7 and 3.8, and for PyPy. Check + the GitHub Actions for your pull request are passing. + +Tips +---- + +To run a subset of tests:: + +$ pytest tests.test_aio_marantz_avr + + +Deploying +--------- + +A reminder for the maintainers on how to deploy. +Make sure all your changes are committed (including an entry in HISTORY.rst). +Then run:: + +$ bump2version patch # possible: major / minor / patch +$ git push +$ git push --tags + +GitHub Actions will then deploy to PyPI if tests pass. diff --git a/HISTORY.rst b/HISTORY.rst new file mode 100644 index 0000000..1d27612 --- /dev/null +++ b/HISTORY.rst @@ -0,0 +1,20 @@ +======= +History +======= + +All notable changes to this project will be documented in this file. + +The format is based on `Keep a Changelog`_, and this project adheres to `Semantic Versioning`_. + +.. _`Keep a Changelog`: https://keepachangelog.com/en/1.0.0/ +.. _`Semantic Versioning`: https://semver.org/spec/v2.0.0.html + +0.1.0 (2020-01-07) +------------------ + +First release on PyPI. + +Added +~~~~~ + +* Basic control of limited Marantz AVR models. diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..b87814a --- /dev/null +++ b/LICENSE @@ -0,0 +1,22 @@ +MIT License + +Copyright (c) 2020, Rob van der Most + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + diff --git a/MANIFEST.in b/MANIFEST.in new file mode 100644 index 0000000..965b2dd --- /dev/null +++ b/MANIFEST.in @@ -0,0 +1,11 @@ +include AUTHORS.rst +include CONTRIBUTING.rst +include HISTORY.rst +include LICENSE +include README.rst + +recursive-include tests * +recursive-exclude * __pycache__ +recursive-exclude * *.py[co] + +recursive-include docs *.rst conf.py Makefile make.bat *.jpg *.png *.gif diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..a87ebea --- /dev/null +++ b/Makefile @@ -0,0 +1,91 @@ +.PHONY: clean clean-test clean-pyc clean-build docs help +.DEFAULT_GOAL := help + +define BROWSER_PYSCRIPT +import os, webbrowser, sys + +from urllib.request import pathname2url + +webbrowser.open("file://" + pathname2url(os.path.abspath(sys.argv[1]))) +endef +export BROWSER_PYSCRIPT + +define PRINT_HELP_PYSCRIPT +import re, sys + +for line in sys.stdin: + match = re.match(r'^([a-zA-Z_-]+):.*?## (.*)$$', line) + if match: + target, help = match.groups() + print("%-20s %s" % (target, help)) +endef +export PRINT_HELP_PYSCRIPT + +BROWSER := python -c "$$BROWSER_PYSCRIPT" + +help: + @python -c "$$PRINT_HELP_PYSCRIPT" < $(MAKEFILE_LIST) + +clean: clean-build clean-pyc clean-test ## remove all build, test, coverage and Python artifacts + +clean-build: ## remove build artifacts + rm -fr build/ + rm -fr dist/ + rm -fr .eggs/ + find . -name '*.egg-info' -exec rm -fr {} + + find . -name '*.egg' -exec rm -f {} + + +clean-pyc: ## remove Python file artifacts + find . -name '*.pyc' -exec rm -f {} + + find . -name '*.pyo' -exec rm -f {} + + find . -name '*~' -exec rm -f {} + + find . -name '__pycache__' -exec rm -fr {} + + +clean-test: ## remove test and coverage artifacts + rm -fr .tox/ + rm -f .coverage + rm -fr htmlcov/ + rm -fr .pytest_cache + +lint: ## check style with flake8 + flake8 aio_marantz_avr tests + +test: ## run tests quickly with the default Python + pytest + +test-all: ## run tests on every Python version with tox + tox + +coverage: ## check code coverage quickly with the default Python + coverage run --source aio_marantz_avr -m pytest + coverage report -m + coverage html + $(BROWSER) htmlcov/index.html + +docs: ## generate Sphinx HTML documentation, including API docs + rm -f docs/aio_marantz_avr.rst + rm -f docs/modules.rst + sphinx-apidoc -o docs/ aio_marantz_avr + $(MAKE) -C docs clean + $(MAKE) -C docs html + $(BROWSER) docs/_build/html/index.html + +servedocs: docs ## compile the docs watching for changes + watchmedo shell-command -p '*.rst' -c '$(MAKE) -C docs html' -R -D . + +release: dist ## package and upload a release + twine upload dist/* + +dist: clean ## builds source and wheel package + python setup.py sdist + python setup.py bdist_wheel + ls -l dist + +install: clean ## install the package to the active Python's site-packages + python setup.py install + +format: ## apply code formatting + black aio_marantz_avr + +mypy: ## check type hints with mypy + mypy aio_marantz_avr diff --git a/README.md b/README.md deleted file mode 100644 index a02b62f..0000000 --- a/README.md +++ /dev/null @@ -1 +0,0 @@ -aio_marantz_avr diff --git a/README.rst b/README.rst new file mode 100644 index 0000000..709e398 --- /dev/null +++ b/README.rst @@ -0,0 +1,44 @@ +=================== +AsyncIO Marantz AVR +=================== + + +.. image:: https://img.shields.io/pypi/v/aio_marantz_avr.svg + :target: https://pypi.python.org/pypi/aio_marantz_avr + +.. image:: https://readthedocs.org/projects/aio-marantz-avr/badge/?version=latest + :target: https://aio-marantz-avr.readthedocs.io/en/latest/?badge=latest + :alt: Documentation Status + +.. image:: https://github.com/silvester747/aio_marantz_avr/workflows/Python%20package/badge.svg + :target: https://github.com/silvester747/aio_marantz_avr/actions + :alt: Build Status + +AsyncIO access to Marantz AVRs. + + +* Free software: MIT license +* Documentation: https://aio-marantz-avr.readthedocs.io. + + +Features +-------- + +* Control and read status of a Marantz AVR over Telnet using python AsyncIO. +* Command line tool. + +Supported models: + +* SR7011 (tested) +* AV7703 +* SR6011 +* SR5011 +* NR1607 + +Credits +------- + +This package was created with Cookiecutter_ and the `audreyr/cookiecutter-pypackage`_ project template. + +.. _Cookiecutter: https://github.com/audreyr/cookiecutter +.. _`audreyr/cookiecutter-pypackage`: https://github.com/audreyr/cookiecutter-pypackage diff --git a/aio_marantz_avr/__init__.py b/aio_marantz_avr/__init__.py new file mode 100644 index 0000000..18ce6bf --- /dev/null +++ b/aio_marantz_avr/__init__.py @@ -0,0 +1,17 @@ +"""Top-level package for AsyncIO Marantz AVR.""" + +__author__ = """Rob van der Most""" +__email__ = "silvester747@gmail.com" +__version__ = "0.1.0" + +from .avr import AvrTimeoutError, connect, DisconnectedError, MarantzAVR +from .enums import InputSource, Power, SurroundMode + +__all__ = [ + "connect", + "DisconnectedError", + "MarantzAVR", + "InputSource", + "Power", + "SurroundMode", +] diff --git a/aio_marantz_avr/avr.py b/aio_marantz_avr/avr.py new file mode 100644 index 0000000..1c28793 --- /dev/null +++ b/aio_marantz_avr/avr.py @@ -0,0 +1,268 @@ +"""Control of an AVR over Telnet.""" + +import asyncio +import telnetlib3 + +from typing import Any, List, MutableMapping, Optional, Type + +from .enums import InputSource, Power, SurroundMode + + +class AvrError(Exception): + """Base class for all errors returned from an AVR.""" + + pass + + +class DisconnectedError(AvrError): + """The connection to the AVR has been lost, or has never been established.""" + + pass + + +class AvrTimeoutError(AvrError): + """A request to the AVR has timed out.""" + + pass + + +async def connect(host: str, port: int = 23, timeout: float = 1.0) -> "MarantzAVR": + """Connect to an AVR.""" + reader, writer = await telnetlib3.open_connection(host, port=port, encoding="ascii") + return MarantzAVR(reader, writer, timeout) + + +def _on_off_from_bool(value: bool) -> str: + if value: + return "ON" + else: + return "OFF" + + +def _on_off_to_bool(value: str) -> bool: + return value == "ON" + + +class _DataDefinition: + query: str + data_names: List[str] + + def __init__(self, query: str, data_names: List[str]): + self.query = query + self.data_names = data_names + + +class MarantzAVR: + """Connection to a Marantz AVR over Telnet. + + Uses `connect` to create a connection to the AVR. + """ + + DATA_DEFS: List[_DataDefinition] = [ + _DataDefinition("PW?", ["PW"]), + _DataDefinition("MU?", ["MU"]), + _DataDefinition("MV?", ["MV", "MVMAX"]), + _DataDefinition("SI?", ["SI"]), + _DataDefinition("MS?", ["MS"]), + ] + + _reader: telnetlib3.TelnetReader + _writer: telnetlib3.TelnetWriter + _timeout: float + + _data: MutableMapping[str, Optional[str]] + _reading: bool + + def __init__( + self, reader: telnetlib3.TelnetReader, writer: telnetlib3.TelnetWriter, timeout: float, + ): + self._reader = reader + self._writer = writer + self._timeout = timeout + self._prepare_data() + self._reading = False + + def _prepare_data(self) -> None: + self._data = {} + for data_def in self.DATA_DEFS: + for name in data_def.data_names: + self._data[name] = None + + @property + def power(self) -> Optional[Power]: + """Power state of the AVR.""" + return self._get_enum_data("PW", Power) + + @property + def is_volume_muted(self) -> Optional[bool]: + """Boolean if volume is currently muted.""" + return self._get_boolean_data("MU") + + @property + def volume_level(self) -> Optional[float]: + """Volume level of the AVR zone (00..max_volume_level).""" + return self._get_volume_level("MV") + + @property + def max_volume_level(self) -> Optional[float]: + """Maximum volume level of the AVR zone.""" + return self._get_volume_level("MVMAX") + + @property + def source(self) -> Optional[InputSource]: + """Name of the current input source.""" + return self._get_enum_data("SI", InputSource) + + @property + def source_list(self) -> List[InputSource]: + """List of available input sources.""" + return list(InputSource) + + @property + def sound_mode(self) -> Optional[SurroundMode]: + """Name of the current sound mode.""" + return self._get_enum_data("MS", SurroundMode) + + @property + def sound_mode_list(self) -> List[SurroundMode]: + """List of available sound modes.""" + return list(SurroundMode) + + async def refresh(self) -> None: + """Refresh all properties from the AVR.""" + if self._reading: + return + + for data_def in self.DATA_DEFS: + await self._send_command(data_def.query) + await self._wait_for_response_with_timeout(*data_def.data_names) + + async def turn_on(self) -> None: + """Turn the AVR on.""" + await self._send_command("PW", "ON") + await self._wait_for_response_with_timeout("PW") + + async def turn_off(self) -> None: + """Turn the AVR off.""" + await self._send_command("PW", "STANDBY") + await self._wait_for_response_with_timeout("PW") + + async def mute_volume(self, mute: bool) -> None: + """Mute or unmute the volume. + + Arguments: + mute -- True to mute, False to unmute. + """ + await self._send_command("MU", _on_off_from_bool(mute)) + await self._wait_for_response_with_timeout("MU") + + async def set_volume_level(self, level: int) -> None: + """Set the volume level. + + Arguments: + level -- An integer value between 0 and `max_volume_level`. + """ + await self._send_command(f"MV{level:02}") + await self._wait_for_response_with_timeout("MV") + + async def volume_level_up(self) -> None: + """Turn the volume level up one notch.""" + await self._send_command("MVUP") + await self._wait_for_response_with_timeout("MV") + + async def volume_level_down(self) -> None: + """Turn the volume level down one notch.""" + await self._send_command("MVDOWN") + await self._wait_for_response_with_timeout("MV") + + async def select_source(self, source: InputSource) -> None: + """Select the input source.""" + await self._send_command("SI", source.value) + await self._wait_for_response_with_timeout("SI") + + async def select_sound_mode(self, mode: SurroundMode) -> None: + """Select the sound mode.""" + await self._send_command("MS", mode.value) + await self._wait_for_response_with_timeout("MS") + + async def _send_command(self, *parts: str) -> None: + if self._reader.at_eof(): + raise DisconnectedError() + + self._writer.write("".join(parts)) + self._writer.write("\r") + await self._writer.drain() + + async def _with_timeout(self, coro) -> Optional[Any]: + try: + return await asyncio.wait_for(coro, self._timeout) + except asyncio.TimeoutError: + raise AvrTimeoutError + + async def _wait_for_response_with_timeout(self, *names: str) -> None: + await self._with_timeout(self._wait_for_response(*names)) + + async def _wait_for_response(self, *names: str) -> None: + if self._reading: + return + + self._reading = True + try: + pending_names = list(names) + while True: + line = await self._reader.readline() + if not line and self._reader.at_eof(): + raise DisconnectedError + + match = self._process_response(line) + if match in pending_names: + pending_names.remove(match) + if len(pending_names) == 0: + return + except ConnectionError: + raise DisconnectedError + finally: + self._reading = False + + def _process_response(self, response: str) -> Optional[str]: + matches = [name for name in self._data.keys() if response.startswith(name)] + + if not matches: + return None + + if len(matches) > 1: + matches.sort(key=len, reverse=True) + match = matches[0] + + self._data[match] = response.strip()[len(match) :] + return match + + def _get_boolean_data(self, name: str) -> Optional[bool]: + value = self._data[name] + if value is not None: + return _on_off_to_bool(value) + return None + + def _get_int_data(self, name: str) -> Optional[int]: + value = self._data[name] + if value is not None: + return int(value) + return None + + def _get_enum_data(self, name: str, enum_type: Type) -> Optional[Any]: + value = self._data[name] + if value is not None: + return enum_type(value) + return None + + def _get_volume_level(self, name: str) -> Optional[float]: + value = self._data[name] + if value is None: + return None + + # Volume levels are either 2 or 3 characters. The floating point is between 2 and 3. + value = value.strip() + level = float(value) + if len(value) == 3: + level /= 10.0 + return level diff --git a/aio_marantz_avr/cli.py b/aio_marantz_avr/cli.py new file mode 100644 index 0000000..d357169 --- /dev/null +++ b/aio_marantz_avr/cli.py @@ -0,0 +1,91 @@ +"""Console script for aio_marantz_avr.""" +import argparse +import asyncio +import sys + +from .avr import connect, DisconnectedError +from .enums import InputSource, SurroundMode + + +async def run(args): + avr = await connect(host=args.host) + + if args.show: + await avr.refresh() + print(f"Power: {avr.power}") + print(f"Is volume muted: {avr.is_volume_muted}") + print(f"Volume level: {avr.volume_level}") + print(f"Max volume level: {avr.max_volume_level}") + print(f"Source: {avr.source}") + print(f"Sound mode: {avr.sound_mode}") + + if args.turn_on: + await avr.turn_on() + print(f"NEW Power: {avr.power}") + + if args.turn_off: + await avr.turn_off() + print(f"NEW Power: {avr.power}") + + if args.mute_volume_on: + await avr.mute_volume(True) + print(f"NEW Is volume muted: {avr.is_volume_muted}") + + if args.mute_volume_off: + await avr.mute_volume(False) + print(f"NEW Is volume muted: {avr.is_volume_muted}") + + if args.select_source: + await avr.select_source(InputSource[args.select_source]) + print(f"NEW Source: {avr.source}") + + if args.select_sound_mode: + await avr.select_sound_mode(SurroundMode[args.select_sound_mode]) + print(f"NEW Sound mode: {avr.sound_mode}") + + if args.set_volume_level: + await avr.set_volume_level(args.set_volume_level) + print(f"NEW Volume level: {avr.volume_level}") + + if args.volume_level_up: + await avr.volume_level_up() + print(f"NEW Volume level: {avr.volume_level}") + + if args.volume_level_down: + await avr.volume_level_down() + print(f"NEW Volume level: {avr.volume_level}") + + +def main(): + """Console script for aio_marantz_avr.""" + parser = argparse.ArgumentParser() + parser.add_argument("--host", required=True, help="Host name or IP of the AVR.") + parser.add_argument("--show", action="store_true", help="Show all properties.") + parser.add_argument("--turn-on", action="store_true", help="Turn the AVR on.") + parser.add_argument("--turn-off", action="store_true", help="Turn the AVR off.") + parser.add_argument("--mute-volume-on", action="store_true", help="Turn volume mute on.") + parser.add_argument("--mute-volume-off", action="store_true", help="Turn volume mute off.") + parser.add_argument( + "--select-source", choices=InputSource.__members__.keys(), help="Select input source.", + ) + parser.add_argument( + "--select-sound-mode", choices=SurroundMode.__members__.keys(), help="Select sound mode.", + ) + parser.add_argument("--set-volume-level", type=int, help="Set the volume level.") + parser.add_argument("--volume-level-up", action="store_true", help="Turn the volume level up.") + parser.add_argument( + "--volume-level-down", action="store_true", help="Turn the volume level down." + ) + args = parser.parse_args() + + try: + asyncio.run(run(args)) + except DisconnectedError: + print("Connection lost.", file=sys.stderr) + return 1 + + return 0 + + +if __name__ == "__main__": + sys.exit(main()) # pragma: no cover diff --git a/aio_marantz_avr/enums.py b/aio_marantz_avr/enums.py new file mode 100644 index 0000000..087551b --- /dev/null +++ b/aio_marantz_avr/enums.py @@ -0,0 +1,91 @@ +"""Enums used by the AVR.""" + +from enum import Enum + + +class Power(Enum): + Off = "OFF" + On = "ON" + Standby = "STANDBY" + + +class InputSource(Enum): + Phono = "PHONO" + CD = "CD" + DVD = "DVD" + Bluray = "BD" + TV = "TV" + CblSat = "SAT/CBL" + MediaPlayer = "MPLAY" + Game = "GAME" + Tuner = "TUNER" + HDRadio = "HDRADIO" + SiriusXM = "SIRIUSXM" + Pandora = "PANDORA" + InternetRadio = "IRADIO" + Server = "SERVER" + Favorites = "FAVORITES" + Aux1 = "AUX1" + Aux2 = "AUX2" + Aux3 = "AUX3" + Aux4 = "AUX4" + Aux5 = "AUX5" + Aux6 = "AUX6" + Aux7 = "AUX7" + OnlineMusic = "NET" + Bluetooth = "BT" + + +class SurroundMode(Enum): + # Settable values + Movie = "MOVIE" + Music = "MUSIC" + Game = "GAME" + Direct = "DIRECT" + PureDirect = "PURE DIRECT" + Stereo = "STEREO" + Auto = "AUTO" + DolbyDigital = "DOLBY DIGITAL" + DtsSurround = "DTS SURROUND" + Auro3D = "AURO3D" + Auro2DSurround = "AURO2DSURR" + MultiChannelStereo = "MCH STEREO" + Virtual = "VIRTUAL" + + # Rotate between options + Left = "LEFT" + Right = "RIGHT" + + # Return only + # TODO: Split combined modes + DolbySurround = "DOLBY SURROUND" + DolbyAtmos = "DOLBY ATMOS" + DolbyDigitalDS = "DOLBY D+DS" + DolbyDigitalNeuralX = "DOLBY D+NEURAL:X" + DolbyDigitalPlus = "DOLBY D+" + DolbyDigitalPlusDS = "DOLBY D+ +DS" + DolbyDigitalPlusNeuralX = "DOLBY D+ +NEURAL:X" + DolbyHD = "DOLBY HD" + DolbyHDDS = "DOLBY HD+DS" + DolbyHDNeuralX = "DOLBY HD+NEURAL:X" + NeuralX = "NEURAL:X" + DtsEsDscrt6_1 = "DTS ES DSCRT6.1" + DtsEsMtrx6_1 = "DTS ES MTRX6.1" + DtsDS = "DTS+DS" + DtsNeuralX = "DTS+NEURAL:X" + DtsEsMtrxNeuralX = "DTS ES MTRX+NEURAL:X" + DtsEsDscrtNeuralX = "DTS ES DSCRT+NEURAL:X" + Dts96_24 = "DTS96/24" + Dts96EsMtrx = "DTS96 ES MTRX" + DtsHD = "DTS HD" + DtsHDMstr = "DTS HD MSTR" + DtsHDDS = "MSDTS HD+DS" + DtsHDNeuralX = "DTS HD+NEURAL:X" + DtsX = "DTS:X" + DtsXMstr = "DTS:X MSTR" + DtsExpress = "DTS EXPRESS" + DtsES8ChDscrt = "DTS ES 8CH DSCRT" + MultiChIn = "MULTI CH IN" + MultiChInDS = "M CH IN+DS" + MultiChInNeuralX = "M CH IN+NEURAL:X" + MultiChIn7_1 = "MULTI CH IN 7.1" diff --git a/docs/Makefile b/docs/Makefile new file mode 100644 index 0000000..368fcec --- /dev/null +++ b/docs/Makefile @@ -0,0 +1,20 @@ +# Minimal makefile for Sphinx documentation +# + +# You can set these variables from the command line. +SPHINXOPTS = +SPHINXBUILD = python -msphinx +SPHINXPROJ = aio_marantz_avr +SOURCEDIR = . +BUILDDIR = _build + +# Put it first so that "make" without argument is like "make help". +help: + @$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) + +.PHONY: help Makefile + +# Catch-all target: route all unknown targets to Sphinx using the new +# "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS). +%: Makefile + @$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) diff --git a/docs/authors.rst b/docs/authors.rst new file mode 100644 index 0000000..e122f91 --- /dev/null +++ b/docs/authors.rst @@ -0,0 +1 @@ +.. include:: ../AUTHORS.rst diff --git a/docs/conf.py b/docs/conf.py new file mode 100755 index 0000000..cfb08f4 --- /dev/null +++ b/docs/conf.py @@ -0,0 +1,162 @@ +#!/usr/bin/env python +# +# aio_marantz_avr documentation build configuration file, created by +# sphinx-quickstart on Fri Jun 9 13:47:02 2017. +# +# This file is execfile()d with the current directory set to its +# containing dir. +# +# Note that not all possible configuration values are present in this +# autogenerated file. +# +# All configuration values have a default; values that are commented out +# serve to show the default. + +# If extensions (or modules to document with autodoc) are in another +# directory, add these directories to sys.path here. If the directory is +# relative to the documentation root, use os.path.abspath to make it +# absolute, like shown here. +# +import os +import sys +sys.path.insert(0, os.path.abspath('..')) + +import aio_marantz_avr + +# -- General configuration --------------------------------------------- + +# If your documentation needs a minimal Sphinx version, state it here. +# +# needs_sphinx = '1.0' + +# Add any Sphinx extension module names here, as strings. They can be +# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom ones. +extensions = ['sphinx.ext.autodoc', 'sphinx.ext.viewcode'] + +# Add any paths that contain templates here, relative to this directory. +templates_path = ['_templates'] + +# The suffix(es) of source filenames. +# You can specify multiple suffix as a list of string: +# +# source_suffix = ['.rst', '.md'] +source_suffix = '.rst' + +# The master toctree document. +master_doc = 'index' + +# General information about the project. +project = 'AsyncIO Marantz AVR' +copyright = "2020, Rob van der Most" +author = "Rob van der Most" + +# The version info for the project you're documenting, acts as replacement +# for |version| and |release|, also used in various other places throughout +# the built documents. +# +# The short X.Y version. +version = aio_marantz_avr.__version__ +# The full version, including alpha/beta/rc tags. +release = aio_marantz_avr.__version__ + +# The language for content autogenerated by Sphinx. Refer to documentation +# for a list of supported languages. +# +# This is also used if you do content translation via gettext catalogs. +# Usually you set "language" from the command line for these cases. +language = None + +# List of patterns, relative to source directory, that match files and +# directories to ignore when looking for source files. +# This patterns also effect to html_static_path and html_extra_path +exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store'] + +# The name of the Pygments (syntax highlighting) style to use. +pygments_style = 'sphinx' + +# If true, `todo` and `todoList` produce output, else they produce nothing. +todo_include_todos = False + + +# -- Options for HTML output ------------------------------------------- + +# The theme to use for HTML and HTML Help pages. See the documentation for +# a list of builtin themes. +# +html_theme = 'alabaster' + +# Theme options are theme-specific and customize the look and feel of a +# theme further. For a list of options available for each theme, see the +# documentation. +# +# html_theme_options = {} + +# Add any paths that contain custom static files (such as style sheets) here, +# relative to this directory. They are copied after the builtin static files, +# so a file named "default.css" will overwrite the builtin "default.css". +html_static_path = ['_static'] + + +# -- Options for HTMLHelp output --------------------------------------- + +# Output file base name for HTML help builder. +htmlhelp_basename = 'aio_marantz_avrdoc' + + +# -- Options for LaTeX output ------------------------------------------ + +latex_elements = { + # The paper size ('letterpaper' or 'a4paper'). + # + # 'papersize': 'letterpaper', + + # The font size ('10pt', '11pt' or '12pt'). + # + # 'pointsize': '10pt', + + # Additional stuff for the LaTeX preamble. + # + # 'preamble': '', + + # Latex figure (float) alignment + # + # 'figure_align': 'htbp', +} + +# Grouping the document tree into LaTeX files. List of tuples +# (source start file, target name, title, author, documentclass +# [howto, manual, or own class]). +latex_documents = [ + (master_doc, 'aio_marantz_avr.tex', + 'AsyncIO Marantz AVR Documentation', + 'Rob van der Most', 'manual'), +] + + +# -- Options for manual page output ------------------------------------ + +# One entry per manual page. List of tuples +# (source start file, name, description, authors, manual section). +man_pages = [ + (master_doc, 'aio_marantz_avr', + 'AsyncIO Marantz AVR Documentation', + [author], 1) +] + + +# -- Options for Texinfo output ---------------------------------------- + +# Grouping the document tree into Texinfo files. List of tuples +# (source start file, target name, title, author, +# dir menu entry, description, category) +texinfo_documents = [ + (master_doc, 'aio_marantz_avr', + 'AsyncIO Marantz AVR Documentation', + author, + 'aio_marantz_avr', + 'One line description of project.', + 'Miscellaneous'), +] + + + diff --git a/docs/contributing.rst b/docs/contributing.rst new file mode 100644 index 0000000..e582053 --- /dev/null +++ b/docs/contributing.rst @@ -0,0 +1 @@ +.. include:: ../CONTRIBUTING.rst diff --git a/docs/history.rst b/docs/history.rst new file mode 100644 index 0000000..2506499 --- /dev/null +++ b/docs/history.rst @@ -0,0 +1 @@ +.. include:: ../HISTORY.rst diff --git a/docs/index.rst b/docs/index.rst new file mode 100644 index 0000000..050cf42 --- /dev/null +++ b/docs/index.rst @@ -0,0 +1,20 @@ +Welcome to AsyncIO Marantz AVR's documentation! +====================================== + +.. toctree:: + :maxdepth: 2 + :caption: Contents: + + readme + installation + usage + modules + contributing + authors + history + +Indices and tables +================== +* :ref:`genindex` +* :ref:`modindex` +* :ref:`search` diff --git a/docs/installation.rst b/docs/installation.rst new file mode 100644 index 0000000..b9c48a0 --- /dev/null +++ b/docs/installation.rst @@ -0,0 +1,51 @@ +.. highlight:: shell + +============ +Installation +============ + + +Stable release +-------------- + +To install AsyncIO Marantz AVR, run this command in your terminal: + +.. code-block:: console + + $ pip install aio_marantz_avr + +This is the preferred method to install AsyncIO Marantz AVR, as it will always install the most recent stable release. + +If you don't have `pip`_ installed, this `Python installation guide`_ can guide +you through the process. + +.. _pip: https://pip.pypa.io +.. _Python installation guide: http://docs.python-guide.org/en/latest/starting/installation/ + + +From sources +------------ + +The sources for AsyncIO Marantz AVR can be downloaded from the `Github repo`_. + +You can either clone the public repository: + +.. code-block:: console + + $ git clone git://github.com/silvester747/aio_marantz_avr + +Or download the `tarball`_: + +.. code-block:: console + + $ curl -OJL https://github.com/silvester747/aio_marantz_avr/tarball/master + +Once you have a copy of the source, you can install it with: + +.. code-block:: console + + $ python setup.py install + + +.. _Github repo: https://github.com/silvester747/aio_marantz_avr +.. _tarball: https://github.com/silvester747/aio_marantz_avr/tarball/master diff --git a/docs/make.bat b/docs/make.bat new file mode 100644 index 0000000..ed1c6b8 --- /dev/null +++ b/docs/make.bat @@ -0,0 +1,36 @@ +@ECHO OFF + +pushd %~dp0 + +REM Command file for Sphinx documentation + +if "%SPHINXBUILD%" == "" ( + set SPHINXBUILD=python -msphinx +) +set SOURCEDIR=. +set BUILDDIR=_build +set SPHINXPROJ=aio_marantz_avr + +if "%1" == "" goto help + +%SPHINXBUILD% >NUL 2>NUL +if errorlevel 9009 ( + echo. + echo.The Sphinx module was not found. Make sure you have Sphinx installed, + echo.then set the SPHINXBUILD environment variable to point to the full + echo.path of the 'sphinx-build' executable. Alternatively you may add the + echo.Sphinx directory to PATH. + echo. + echo.If you don't have Sphinx installed, grab it from + echo.http://sphinx-doc.org/ + exit /b 1 +) + +%SPHINXBUILD% -M %1 %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% +goto end + +:help +%SPHINXBUILD% -M help %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% + +:end +popd diff --git a/docs/readme.rst b/docs/readme.rst new file mode 100644 index 0000000..72a3355 --- /dev/null +++ b/docs/readme.rst @@ -0,0 +1 @@ +.. include:: ../README.rst diff --git a/docs/usage.rst b/docs/usage.rst new file mode 100644 index 0000000..30d19fd --- /dev/null +++ b/docs/usage.rst @@ -0,0 +1,7 @@ +===== +Usage +===== + +To use AsyncIO Marantz AVR in a project:: + + import aio_marantz_avr diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 0000000..aa4949a --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,2 @@ +[tool.black] +line-length = 100 diff --git a/requirements_dev.txt b/requirements_dev.txt new file mode 100644 index 0000000..5e2b74c --- /dev/null +++ b/requirements_dev.txt @@ -0,0 +1,16 @@ +pip==19.2.3 +bump2version==0.5.11 +wheel==0.33.6 +watchdog==0.9.0 +flake8==3.7.8 +tox==3.14.0 +coverage==4.5.4 +Sphinx==1.8.5 +twine==1.14.0 +mypy==0.761 +black==19.10b0 + +pytest==4.6.5 +pytest-runner==5.1 +pytest-asyncio==0.10.0 +pytest-sugar==0.9.2 diff --git a/setup.cfg b/setup.cfg new file mode 100644 index 0000000..ad9a579 --- /dev/null +++ b/setup.cfg @@ -0,0 +1,29 @@ +[bumpversion] +current_version = 0.1.0 +commit = True +tag = True + +[bumpversion:file:setup.py] +search = version='{current_version}' +replace = version='{new_version}' + +[bumpversion:file:aio_marantz_avr/__init__.py] +search = __version__ = '{current_version}' +replace = __version__ = '{new_version}' + +[bdist_wheel] +universal = 1 + +[flake8] +exclude = docs +max_line_length = 100 + +[aliases] +# Define setup.py command aliases here +test = pytest + +[tool:pytest] +collect_ignore = ['setup.py'] + +[mypy-telnetlib3] +ignore_missing_imports = True diff --git a/setup.py b/setup.py new file mode 100644 index 0000000..0dea2f6 --- /dev/null +++ b/setup.py @@ -0,0 +1,53 @@ +#!/usr/bin/env python + +"""The setup script.""" + +from setuptools import setup, find_packages + +with open('README.rst') as readme_file: + readme = readme_file.read() + +with open('HISTORY.rst') as history_file: + history = history_file.read() + +requirements = ["telnetlib3==1.0.2", ] + +setup_requirements = ['pytest-runner', ] + +test_requirements = ['pytest>=3', "pytest-asyncio>=0.10", ] + +setup( + author="Rob van der Most", + author_email='silvester747@gmail.com', + python_requires='>=3.5', + classifiers=[ + 'Development Status :: 2 - Pre-Alpha', + 'Intended Audience :: Developers', + 'License :: OSI Approved :: MIT License', + 'Natural Language :: English', + 'Programming Language :: Python :: 3', + 'Programming Language :: Python :: 3.5', + 'Programming Language :: Python :: 3.6', + 'Programming Language :: Python :: 3.7', + 'Programming Language :: Python :: 3.8', + ], + description="AsyncIO access to Marantz AVRs.", + entry_points={ + 'console_scripts': [ + 'aio_marantz_avr=aio_marantz_avr.cli:main', + ], + }, + install_requires=requirements, + license="MIT license", + long_description=readme + '\n\n' + history, + include_package_data=True, + keywords='aio_marantz_avr', + name='aio_marantz_avr', + packages=find_packages(include=['aio_marantz_avr', 'aio_marantz_avr.*']), + setup_requires=setup_requirements, + test_suite='tests', + tests_require=test_requirements, + url='https://github.com/silvester747/aio_marantz_avr', + version='0.1.0', + zip_safe=False, +) diff --git a/tests/__init__.py b/tests/__init__.py new file mode 100644 index 0000000..73ab4bf --- /dev/null +++ b/tests/__init__.py @@ -0,0 +1 @@ +"""Unit test package for aio_marantz_avr.""" diff --git a/tests/test_avr.py b/tests/test_avr.py new file mode 100644 index 0000000..1e0b26f --- /dev/null +++ b/tests/test_avr.py @@ -0,0 +1,260 @@ +#!/usr/bin/env python + +"""Tests for `avr` package.""" + +import asyncio +import pytest +import telnetlib3 + +from typing import Awaitable, List, Mapping + +from aio_marantz_avr import (connect, DisconnectedError, InputSource, Power, SurroundMode, + AvrTimeoutError) + + +class TestShell: + reader = None + writer = None + + @property + def connected(self): + return self.reader is not None and self.writer is not None + + def shell(self, reader, writer): + self.reader = reader + self.writer = writer + + async def run_and_respond(self, aw: Awaitable, + response_mapping: Mapping[str, List[str]]) -> None: + await asyncio.wait_for(asyncio.gather(aw, self.expect_and_respond(response_mapping)), + timeout=5) + + async def expect_and_respond(self, response_mapping: Mapping[str, List[str]]) -> None: + while True: + command = await self.reader.readline() + + if command in response_mapping: + responses = response_mapping[command] + del response_mapping[command] + for response in responses: + self.writer.write(response) + await self.writer.drain() + if not response_mapping: + return + + +@pytest.fixture +def test_shell(): + return TestShell() + + +def create_task(coro): + # asyncio.create_task does not exist yet in python 3.6, but ensure_future does the same + return asyncio.ensure_future(coro) + + +@pytest.fixture +async def test_server(test_shell, unused_tcp_port): + server = await telnetlib3.create_server(shell=test_shell.shell, port=unused_tcp_port, + encoding="ascii") + server_task = create_task(server.wait_closed()) + yield server + test_shell.writer.close() + server.close() + await server_task + + +@pytest.mark.asyncio +async def test_connect(test_server, test_shell, unused_tcp_port): + avr = await connect("localhost", port=unused_tcp_port) + assert avr is not None + assert test_shell.connected + + +@pytest.fixture +async def avr(test_server, unused_tcp_port): + return await connect("localhost", port=unused_tcp_port) + + +@pytest.mark.asyncio +async def test_mute_on(avr, test_shell): + await test_shell.run_and_respond( + avr.mute_volume(True), + {"MUON\r": ["MUON\r"]} + ) + assert avr.is_volume_muted is True + + +@pytest.mark.asyncio +async def test_mute_off(avr, test_shell): + await test_shell.run_and_respond( + avr.mute_volume(False), + {"MUOFF\r": ["MUOFF\r"]} + ) + assert avr.is_volume_muted is False + + +@pytest.mark.asyncio +async def test_turn_on(avr, test_shell): + await test_shell.run_and_respond( + avr.turn_on(), + {"PWON\r": ["PWON\r"]} + ) + assert avr.power == Power.On + + +@pytest.mark.asyncio +async def test_turn_off(avr, test_shell): + await test_shell.run_and_respond( + avr.turn_off(), + {"PWSTANDBY\r": ["PWSTANDBY\r"]} + ) + assert avr.power == Power.Standby + + +@pytest.mark.asyncio +async def test_select_source(avr, test_shell): + await test_shell.run_and_respond( + avr.select_source(InputSource.DVD), + {"SIDVD\r": ["SIDVD\r"]} + ) + assert avr.source == InputSource.DVD + + +@pytest.mark.asyncio +async def test_select_sound_mode(avr, test_shell): + await test_shell.run_and_respond( + avr.select_sound_mode(SurroundMode.Movie), + {"MSMOVIE\r": ["MSMOVIE\r"]} + ) + assert avr.sound_mode == SurroundMode.Movie + + +@pytest.mark.asyncio +async def test_set_volume_level(avr, test_shell): + await test_shell.run_and_respond( + avr.set_volume_level(30), + {"MV30\r": ["MV30\r"]} + ) + assert avr.volume_level == 30. + + +@pytest.mark.asyncio +async def test_set_volume_level_single_digit(avr, test_shell): + await test_shell.run_and_respond( + avr.set_volume_level(3), + {"MV03\r": ["MV03\r"]} + ) + assert avr.volume_level == 3. + + +@pytest.mark.asyncio +async def test_volume_level_up(avr, test_shell): + await test_shell.run_and_respond( + avr.volume_level_up(), + {"MVUP\r": ["MV30\r"]} + ) + assert avr.volume_level == 30. + + +@pytest.mark.asyncio +async def test_volume_level_down(avr, test_shell): + await test_shell.run_and_respond( + avr.volume_level_down(), + {"MVDOWN\r": ["MV30\r"]} + ) + assert avr.volume_level == 30. + + +@pytest.mark.asyncio +async def test_volume_level_decimal(avr, test_shell): + await test_shell.run_and_respond( + avr.volume_level_down(), + {"MVDOWN\r": ["MV305\r"]} + ) + assert avr.volume_level == 30.5 + + +@pytest.mark.asyncio +async def test_refresh(avr, test_shell): + await test_shell.run_and_respond( + avr.refresh(), + {"MU?\r": ["MUOFF\r"], "PW?\r": ["PWON\r"], "MV?\r": ["MV400\r", "MVMAX980\r"], + "SI?\r": ["SISAT/CBL\r"], "MS?\r": ["MSDOLBY DIGITAL\r"], } + ) + assert avr.power == Power.On + assert avr.is_volume_muted is False + assert avr.volume_level == 40. + assert avr.max_volume_level == 98. + assert avr.source == InputSource.CblSat + assert avr.sound_mode == SurroundMode.DolbyDigital + + +@pytest.mark.asyncio +async def test_timeout_during_refresh(avr, test_shell): + task = create_task(test_shell.expect_and_respond({"MU?\r": ["MUOFF\r"], })) + + with pytest.raises(AvrTimeoutError): + await avr.refresh() + + task.cancel() + + +def test_initial_state(avr): + """Initial states are unknown, so None""" + assert avr.power is None + assert avr.is_volume_muted is None + assert avr.volume_level is None + assert avr.max_volume_level is None + assert avr.source is None + assert avr.sound_mode is None + + +@pytest.mark.asyncio +async def test_refresh_while_running_command(avr, test_shell): + turn_on_task = create_task(avr.turn_on()) + command = await test_shell.reader.readline() + assert command == "PWON\r" + + await avr.refresh() + + test_shell.writer.write("PWON\r") + await test_shell.writer.drain() + await turn_on_task + + +@pytest.mark.asyncio +async def test_run_command_while_refreshing(avr, test_shell): + refresh_task = create_task(avr.refresh()) + command = await test_shell.reader.readline() + assert command + + await avr.turn_on() + command2 = await test_shell.reader.readline() + assert command2 == "PWON\r" + + refresh_task.cancel() + + +@pytest.mark.asyncio +async def test_refresh_after_disconnect(avr, test_shell, test_server): + test_shell.writer.close() + test_server.close() + + with pytest.raises(DisconnectedError): + await avr.refresh() + + +@pytest.mark.asyncio +async def test_send_command_after_disconnect(avr, test_shell, test_server): + test_shell.writer.close() + test_server.close() + + with pytest.raises(DisconnectedError): + await avr.turn_on() + + +@pytest.mark.asyncio +async def test_timeout_in_command(avr): + with pytest.raises(AvrTimeoutError): + await avr.turn_on() diff --git a/tox.ini b/tox.ini new file mode 100644 index 0000000..7fcf423 --- /dev/null +++ b/tox.ini @@ -0,0 +1,27 @@ +[tox] +envlist = py35, py36, py37, py38, flake8 + +[travis] +python = + 3.8: py38 + 3.7: py37 + 3.6: py36 + 3.5: py35 + +[testenv:flake8] +basepython = python +deps = flake8 +commands = flake8 aio_marantz_avr + +[testenv] +setenv = + PYTHONPATH = {toxinidir} +deps = + -r{toxinidir}/requirements_dev.txt +; If you want to make tox run the tests with the same versions, create a +; requirements.txt with the pinned versions and uncomment the following line: +; -r{toxinidir}/requirements.txt +commands = + pip install -U pip + pytest --basetemp={envtmpdir} +