├── touch
├── requirements.txt
├── MANIFEST.in
├── tests
├── __init__.py
├── conftest.py
├── test_issues.py
├── test_cipher.py
├── common.py
├── test_discovery.py
├── test_network.py
└── test_device.py
├── setup.cfg
├── greeclimate
├── __init__.py
├── exceptions.py
├── taskable.py
├── deviceinfo.py
├── cipher.py
├── discovery.py
├── network.py
└── device.py
├── samples
└── GreePlus Device Capture Filtered.pcapng.gz
├── .idea
├── codeStyles
│ └── codeStyleConfig.xml
├── vcs.xml
├── .gitignore
├── inspectionProfiles
│ └── profiles_settings.xml
├── ruff.xml
├── modules.xml
├── misc.xml
├── material_theme_project_new.xml
├── greeclimate.iml
└── runConfigurations
│ └── pytest_in__.xml
├── .vscode
└── settings.json
├── setup.py
├── .releaserc
├── package.json
├── gree.py
├── .gitignore
├── .github
└── workflows
│ └── python-package.yml
├── README.md
├── emulator.py
├── CHANGELOG.md
├── network-log.txt
└── LICENSE.txt
/touch:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/requirements.txt:
--------------------------------------------------------------------------------
1 | netifaces
2 | pycryptodome~=3.10
--------------------------------------------------------------------------------
/MANIFEST.in:
--------------------------------------------------------------------------------
1 | include requirements.txt README.md LICENSE.txt
--------------------------------------------------------------------------------
/tests/__init__.py:
--------------------------------------------------------------------------------
1 | import logging
2 |
3 | _LOGGER = logging.getLogger(__name__)
4 | _LOGGER.setLevel(logging.DEBUG)
5 |
--------------------------------------------------------------------------------
/setup.cfg:
--------------------------------------------------------------------------------
1 | [metadata]
2 | version = 2.1.0
3 |
4 | [tool:pytest]
5 | asyncio_mode = auto
6 | testpaths =
7 | tests
8 |
9 |
--------------------------------------------------------------------------------
/greeclimate/__init__.py:
--------------------------------------------------------------------------------
1 | import logging
2 |
3 | logging.basicConfig(
4 | level=logging.DEBUG, format="%(name)s - %(levelname)s - %(message)s"
5 | )
6 |
--------------------------------------------------------------------------------
/samples/GreePlus Device Capture Filtered.pcapng.gz:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/cmroche/greeclimate/HEAD/samples/GreePlus Device Capture Filtered.pcapng.gz
--------------------------------------------------------------------------------
/.idea/codeStyles/codeStyleConfig.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/.idea/vcs.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/.idea/.gitignore:
--------------------------------------------------------------------------------
1 | # Default ignored files
2 | /shelf/
3 | /workspace.xml
4 | # Editor-based HTTP Client requests
5 | /httpRequests/
6 | # Datasource local storage ignored files
7 | /dataSources/
8 | /dataSources.local.xml
9 |
--------------------------------------------------------------------------------
/.idea/inspectionProfiles/profiles_settings.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/.idea/ruff.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
--------------------------------------------------------------------------------
/.idea/modules.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
--------------------------------------------------------------------------------
/.idea/misc.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
--------------------------------------------------------------------------------
/greeclimate/exceptions.py:
--------------------------------------------------------------------------------
1 | class DeviceNotBoundError(Exception):
2 | """The device being used does not have it's device key set yet. Either provide one or bind the device"""
3 |
4 | pass
5 |
6 |
7 | class DeviceTimeoutError(Exception):
8 | """The device timed out when trying to communicate"""
9 |
10 | pass
11 |
--------------------------------------------------------------------------------
/.vscode/settings.json:
--------------------------------------------------------------------------------
1 | {
2 | "python.linting.enabled": true,
3 | "python.linting.lintOnSave": true,
4 | "python.linting.flake8Enabled": true,
5 | "python.pythonPath": "/usr/local/bin/python",
6 | "python.testing.unittestArgs": [
7 | "-v",
8 | "-s",
9 | "./test",
10 | "-p",
11 | "test_*.py"
12 | ],
13 | "python.testing.pytestEnabled": true,
14 | "python.testing.nosetestsEnabled": false,
15 | "python.testing.unittestEnabled": false,
16 | "python.testing.pytestArgs": [
17 | "tests"
18 | ],
19 | }
--------------------------------------------------------------------------------
/.idea/material_theme_project_new.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
--------------------------------------------------------------------------------
/.idea/greeclimate.iml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
--------------------------------------------------------------------------------
/setup.py:
--------------------------------------------------------------------------------
1 | import setuptools
2 |
3 | with open("README.md", "r") as fh:
4 | long_description = fh.read()
5 |
6 | with open("requirements.txt") as f:
7 | requirements = f.read().splitlines()
8 |
9 | setuptools.setup(
10 | name="greeclimate",
11 | python_requires=">=3.8",
12 | install_requires=requirements,
13 | author="Clifford Roche",
14 | author_email="",
15 | description="Discover, connect and control Gree based minisplit systems",
16 | long_description=long_description,
17 | long_description_content_type="text/markdown",
18 | url="https://github.com/cmroche/greeclimate",
19 | packages=setuptools.find_packages(exclude=["tests"]),
20 | classifiers=[
21 | "Programming Language :: Python :: 3",
22 | "License :: OSI Approved :: GNU General Public License v3 (GPLv3)",
23 | "Operating System :: OS Independent",
24 | ],
25 | )
26 |
--------------------------------------------------------------------------------
/.releaserc:
--------------------------------------------------------------------------------
1 | # Global settings: branch naming conventions, run as CI, tag format, plugin dependencies
2 | tagFormat: v${version}
3 | branches:
4 | - +([0-9])?(.{+([0-9]),x}).x # maintenance branches format: N.x, N.x.x or N.N.x, where N is a number
5 | - master
6 | # below are there as examples for extra branches + prelease branches configurations
7 | - name: beta # format: vN.N.N-beta.N
8 | prerelease: true
9 | - name: alpha # format: vN.N.N-alpha.N
10 | prerelease: true
11 | ci: true
12 | dryRun: false
13 | debug: false
14 | plugins:
15 | - - "@semantic-release/commit-analyzer"
16 | - preset: angular
17 | - "@semantic-release/release-notes-generator"
18 | - "semantic-release-pypi"
19 | - "@semantic-release/github"
20 | - - "@semantic-release/changelog"
21 | - changelogFile: CHANGELOG.md
22 | - - "@semantic-release/git"
23 | - assets: ["CHANGELOG.md", "setup.py", "setup.cfg"]
24 |
--------------------------------------------------------------------------------
/.idea/runConfigurations/pytest_in__.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "greeclimate-release",
3 | "version": "1.0.0",
4 | "description": "",
5 | "main": "index.js",
6 | "directories": {
7 | "test": "tests"
8 | },
9 | "scripts": {
10 | "test": "echo \"Error: no test specified\" && exit 1"
11 | },
12 | "repository": {
13 | "type": "git",
14 | "url": "git+https://github.com/cmroche/greeclimate.git"
15 | },
16 | "author": "Clifford Roche",
17 | "license": "GPL-3.0-or-later",
18 | "bugs": {
19 | "url": "https://github.com/cmroche/greeclimate/issues"
20 | },
21 | "homepage": "https://github.com/cmroche/greeclimate#readme",
22 | "dependencies": {
23 | "@semantic-release/changelog": "^6.0.3",
24 | "@semantic-release/commit-analyzer": "^13.0.0",
25 | "@semantic-release/git": "^10.0.1",
26 | "@semantic-release/github": "^10.0.6",
27 | "@semantic-release/release-notes-generator": "^14.0.1",
28 | "semantic-release": "^24.0.0",
29 | "semantic-release-pypi": "^3.0.1"
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/greeclimate/taskable.py:
--------------------------------------------------------------------------------
1 | from __future__ import annotations
2 |
3 | import asyncio
4 | import logging
5 | from asyncio import Task
6 | from asyncio.events import AbstractEventLoop
7 | from typing import List, Coroutine
8 |
9 | _LOGGER = logging.getLogger(__name__)
10 |
11 |
12 | class Taskable:
13 | """Mixin class for objects that can be run as tasks."""
14 |
15 | def __init__(self, loop: AbstractEventLoop = None):
16 | self._loop: AbstractEventLoop = loop or asyncio.get_event_loop()
17 | self._tasks = []
18 |
19 | @property
20 | def tasks(self) -> List[Coroutine]:
21 | """Returns the outstanding tasks waiting completion."""
22 | return self._tasks
23 |
24 | def _task_done_callback(self, task):
25 | if task.exception():
26 | _LOGGER.exception("Uncaught exception", exc_info=task.exception())
27 | self._tasks.remove(task)
28 |
29 | def _create_task(self, coro) -> Task:
30 | """Create and track tasks that are being created for events."""
31 | task = self._loop.create_task(coro)
32 | self._tasks.append(task)
33 | task.add_done_callback(self._task_done_callback)
34 | return task
35 |
36 |
--------------------------------------------------------------------------------
/tests/conftest.py:
--------------------------------------------------------------------------------
1 | """Pytest module configuration."""
2 | from unittest.mock import patch
3 |
4 | import pytest
5 |
6 | from greeclimate.device import Device
7 | from tests.common import FakeCipher
8 |
9 | MOCK_INTERFACES = ["lo"]
10 | MOCK_LO_IFACE = {
11 | 2: [{"addr": "10.0.0.1", "netmask": "255.0.0.0", "peer": "10.255.255.255"}]
12 | }
13 |
14 |
15 | @pytest.fixture(name="netifaces")
16 | def netifaces_fixture():
17 | """Patch netifaces interface discover."""
18 | with patch("netifaces.interfaces", return_value=MOCK_INTERFACES), patch(
19 | "netifaces.ifaddresses", return_value=MOCK_LO_IFACE
20 | ) as ifaddr_mock:
21 | yield ifaddr_mock
22 |
23 |
24 | @pytest.fixture(name="cipher")
25 | def cipher_fixture():
26 | """Patch the cipher object."""
27 | with patch("greeclimate.device.CipherV1") as mock1, patch("greeclimate.device.CipherV2") as mock2:
28 | mock1.return_value = FakeCipher(b"1234567890123456")
29 | mock2.return_value = FakeCipher(b"1234567890123456")
30 | yield mock1, mock2
31 |
32 |
33 | @pytest.fixture(name="send")
34 | def network_fixture():
35 | """Patch the device object."""
36 | with patch.object(Device, "send") as mock:
37 | yield mock
38 |
--------------------------------------------------------------------------------
/greeclimate/deviceinfo.py:
--------------------------------------------------------------------------------
1 | class DeviceInfo:
2 | """Device information class, used to identify and connect
3 |
4 | Attributes
5 | ip: IP address (ipv4 only) of the physical device
6 | port: Usually this will always be 7000
7 | mac: mac address, in the format 'aabbcc112233'
8 | name: Name of unit, if available
9 | """
10 |
11 | def __init__(self, ip, port, mac, name, brand=None, model=None, version=None):
12 | self.ip = ip
13 | self.port = port
14 | self.mac = mac
15 | self.name = name if name else mac.replace(":", "")
16 | self.brand = brand
17 | self.model = model
18 | self.version = version
19 |
20 | def __str__(self):
21 | return f"Device: {self.name} @ {self.ip}:{self.port} (mac: {self.mac})"
22 |
23 | def __eq__(self, other):
24 | """Check equality based on Device Info properties"""
25 | if isinstance(other, DeviceInfo):
26 | return (
27 | self.mac == other.mac
28 | and self.name == other.name
29 | and self.brand == other.brand
30 | and self.model == other.model
31 | and self.version == other.version
32 | )
33 | return False
34 |
35 | def __ne__(self, other):
36 | """Check inequality based on Device Info properties"""
37 | return not self.__eq__(other)
38 |
39 |
--------------------------------------------------------------------------------
/tests/test_issues.py:
--------------------------------------------------------------------------------
1 | from unittest.mock import patch
2 |
3 | import pytest
4 |
5 | from greeclimate.device import Props, Device
6 |
7 |
8 | @pytest.mark.asyncio
9 | async def test_issue_69_TemSen_40_should_not_set_firmware_v4():
10 | from tests.test_device import generate_device_mock_async
11 |
12 | mock_v3_state = { "TemSen": 40 }
13 | device = await generate_device_mock_async()
14 |
15 | for p in Props:
16 | assert device.get_property(p) is None
17 |
18 | def fake_send(*args, **kwargs):
19 | device.handle_state_update(**mock_v3_state)
20 |
21 | with patch.object(Device, "send", wraps=fake_send()):
22 | await device.update_state()
23 | assert device.version is None
24 |
25 | """Tests for issue 72"""
26 |
27 | @pytest.mark.asyncio
28 | async def test_issue_87_quiet_should_set_2():
29 | """Check that quiet mode uses 2 instead of 1"""
30 | from tests.test_device import generate_device_mock_async
31 |
32 | mock_v3_state = { "Quiet": 2 }
33 | device = await generate_device_mock_async()
34 |
35 | assert device.get_property(Props.QUIET) is None
36 | device.quiet = True
37 |
38 | def fake_send(*args, **kwargs):
39 | device.handle_state_update(**mock_v3_state)
40 |
41 | with patch.object(Device, "send", wraps=fake_send()) as mock:
42 | await device.push_state_update()
43 | mock.assert_called_once()
44 |
45 | assert device.get_property(Props.QUIET) == 2
46 |
--------------------------------------------------------------------------------
/tests/test_cipher.py:
--------------------------------------------------------------------------------
1 | import base64
2 |
3 | import pytest
4 |
5 | from greeclimate.cipher import CipherV1, CipherV2, CipherBase
6 |
7 |
8 | @pytest.fixture
9 | def cipher_v1_key():
10 | return b'ThisIsASecretKey'
11 |
12 |
13 | @pytest.fixture
14 | def cipher_v1(cipher_v1_key):
15 | return CipherV1(cipher_v1_key)
16 |
17 |
18 | @pytest.fixture
19 | def cipher_v2_key():
20 | return b'ThisIsASecretKey'
21 |
22 |
23 | @pytest.fixture
24 | def cipher_v2(cipher_v2_key):
25 | return CipherV2(cipher_v2_key)
26 |
27 |
28 | @pytest.fixture
29 | def plain_text():
30 | return {"message": "Hello, World!"}
31 |
32 |
33 | def test_encryption_then_decryption_yields_original(cipher_v1, plain_text):
34 | encrypted, _ = cipher_v1.encrypt(plain_text)
35 | decrypted = cipher_v1.decrypt(encrypted)
36 | assert decrypted == plain_text
37 |
38 |
39 | def test_decryption_with_modified_data_raises_error(cipher_v1, plain_text):
40 | _, _ = cipher_v1.encrypt(plain_text)
41 | modified_data = base64.b64encode(b"modified data ").decode()
42 | with pytest.raises(UnicodeDecodeError):
43 | cipher_v1.decrypt(modified_data)
44 |
45 |
46 | def test_encryption_then_decryption_yields_original_with_tag(cipher_v2, plain_text):
47 | encrypted, tag = cipher_v2.encrypt(plain_text)
48 | decrypted = cipher_v2.decrypt(encrypted)
49 | assert decrypted == plain_text
50 |
51 |
52 | def test_cipher_base_not_implemented():
53 | fake_key = b'fake'
54 |
55 | with pytest.raises(NotImplementedError):
56 | CipherBase(fake_key).encrypt(None)
57 |
58 | with pytest.raises(NotImplementedError):
59 | CipherBase(fake_key).decrypt(None)
60 |
61 |
--------------------------------------------------------------------------------
/gree.py:
--------------------------------------------------------------------------------
1 | import argparse
2 | import asyncio
3 | import logging
4 |
5 | from greeclimate.device import Device, DeviceInfo
6 | from greeclimate.discovery import Discovery, Listener
7 |
8 | logging.basicConfig(
9 | level=logging.DEBUG, format="%(name)s - %(levelname)s - %(message)s"
10 | )
11 | _LOGGER = logging.getLogger(__name__)
12 |
13 |
14 | class DiscoveryListener(Listener):
15 | def __init__(self, bind):
16 | """Initialize the event handler."""
17 | super().__init__()
18 | self.bind = bind
19 |
20 | """Class to handle incoming device discovery events."""
21 |
22 | async def device_found(self, device_info: DeviceInfo) -> None:
23 | """A new device was found on the network."""
24 | if self.bind:
25 | device = Device(device_info)
26 | await device.bind()
27 | await device.request_version()
28 | _LOGGER.info(f"Device firmware: {device.hid}")
29 |
30 |
31 | async def run_discovery(bind=False):
32 | """Run the device discovery process."""
33 | _LOGGER.debug("Scanning network for Gree devices")
34 |
35 | discovery = Discovery()
36 | listener = DiscoveryListener(bind)
37 | discovery.add_listener(listener)
38 |
39 | await discovery.scan(wait_for=10)
40 |
41 | _LOGGER.info("Done discovering devices")
42 |
43 |
44 | if __name__ == "__main__":
45 | parser = argparse.ArgumentParser(description="Gree command line utility.")
46 | parser.add_argument("--discovery", default=False, action="store_true")
47 | parser.add_argument("--bind", default=False, action="store_true")
48 | args = parser.parse_args()
49 |
50 | if args.discovery:
51 | asyncio.run(run_discovery(args.bind))
52 |
--------------------------------------------------------------------------------
/.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 | build/
12 | develop-eggs/
13 | dist/
14 | downloads/
15 | eggs/
16 | .eggs/
17 | lib/
18 | lib64/
19 | parts/
20 | sdist/
21 | var/
22 | wheels/
23 | pip-wheel-metadata/
24 | share/python-wheels/
25 | *.egg-info/
26 | .installed.cfg
27 | *.egg
28 | MANIFEST
29 |
30 | # PyInstaller
31 | # Usually these files are written by a python script from a template
32 | # before PyInstaller builds the exe, so as to inject date/other infos into it.
33 | *.manifest
34 | *.spec
35 |
36 | # Installer logs
37 | pip-log.txt
38 | pip-delete-this-directory.txt
39 |
40 | # Unit test / coverage reports
41 | htmlcov/
42 | .tox/
43 | .nox/
44 | .coverage
45 | .coverage.*
46 | .cache
47 | nosetests.xml
48 | coverage.xml
49 | *.cover
50 | *.py,cover
51 | .hypothesis/
52 | .pytest_cache/
53 |
54 | # Translations
55 | *.mo
56 | *.pot
57 |
58 | # Django stuff:
59 | *.log
60 | local_settings.py
61 | db.sqlite3
62 | db.sqlite3-journal
63 |
64 | # Flask stuff:
65 | instance/
66 | .webassets-cache
67 |
68 | # Scrapy stuff:
69 | .scrapy
70 |
71 | # Sphinx documentation
72 | docs/_build/
73 |
74 | # PyBuilder
75 | target/
76 |
77 | # Jupyter Notebook
78 | .ipynb_checkpoints
79 |
80 | # IPython
81 | profile_default/
82 | ipython_config.py
83 |
84 | # pyenv
85 | .python-version
86 |
87 | # pipenv
88 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
89 | # However, in case of collaboration, if having platform-specific dependencies or dependencies
90 | # having no cross-platform support, pipenv may install dependencies that don't work, or not
91 | # install all needed dependencies.
92 | #Pipfile.lock
93 |
94 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow
95 | __pypackages__/
96 |
97 | # Celery stuff
98 | celerybeat-schedule
99 | celerybeat.pid
100 |
101 | # SageMath parsed files
102 | *.sage.py
103 |
104 | # Environments
105 | .env
106 | .venv
107 | env/
108 | venv/
109 | ENV/
110 | env.bak/
111 | venv.bak/
112 |
113 | # Spyder project settings
114 | .spyderproject
115 | .spyproject
116 |
117 | # Rope project settings
118 | .ropeproject
119 |
120 | # mkdocs documentation
121 | /site
122 |
123 | # mypy
124 | .mypy_cache/
125 | .dmypy.json
126 | dmypy.json
127 |
128 | # Pyre type checker
129 | .pyre/
130 |
131 | .DS_Store
132 |
133 | cov.xml
134 |
135 | boot.py
136 |
137 | # npm stuff
138 | node_modules
--------------------------------------------------------------------------------
/.github/workflows/python-package.yml:
--------------------------------------------------------------------------------
1 | # This workflow will install Python dependencies, run tests and lint with a variety of Python versions
2 | # For more information see: https://help.github.com/actions/language-and-framework-guides/using-python-with-github-actions
3 |
4 | name: Python package
5 |
6 | on:
7 | push:
8 | branches: [master]
9 | pull_request:
10 | branches: [master]
11 |
12 | jobs:
13 | build:
14 | runs-on: ubuntu-latest
15 | strategy:
16 | matrix:
17 | python-version: [3.8, 3.9, "3.10", "3.11", "3.12"]
18 |
19 | steps:
20 | - uses: actions/checkout@v4
21 | - name: Set up Python ${{ matrix.python-version }}
22 | uses: actions/setup-python@v5
23 | with:
24 | python-version: ${{ matrix.python-version }}
25 | - name: Install dependencies
26 | run: |
27 | python -m pip install --upgrade pip
28 | pip install flake8 pytest pytest-asyncio pytest-cov
29 | if [ -f requirements.txt ]; then pip install -r requirements.txt; fi
30 | - name: Lint with flake8
31 | run: |
32 | # stop the build if there are Python syntax errors or undefined names
33 | flake8 . --count --select=E9,F63,F7,F82 --show-source --statistics
34 | # exit-zero treats all errors as warnings. The GitHub editor is 127 chars wide
35 | flake8 . --count --exit-zero --max-complexity=10 --max-line-length=127 --statistics
36 | - name: Test with unittest
37 | run: |
38 | pytest --cov-report=xml --cov=greeclimate tests/
39 | - uses: codecov/codecov-action@v4
40 | with:
41 | file: ./coverage.xml
42 | env:
43 | CODECOV_TOKEN: ${{ secrets.CODECOV_TOKEN }}
44 | publish:
45 | needs: build
46 | name: Publish to Github & NPM or Github Package Registry
47 | runs-on: ubuntu-latest
48 | steps:
49 | - uses: actions/checkout@v4
50 | - name: Set up Python 3.9
51 | uses: actions/setup-python@v5
52 | with:
53 | python-version: 3.9
54 | - name: Install dependencies
55 | run: |
56 | python -m pip install --upgrade pip
57 | pip install setuptools wheel twine
58 | pip install importlib_metadata==7.2.1
59 | if [ -f requirements-dev.txt ]; then pip install -r requirements-dev.txt; fi
60 | - uses: actions/setup-node@v4
61 | with:
62 | node-version: 20
63 | - env:
64 | CI: true
65 | run: npm ci
66 | - if: success()
67 | env:
68 | CI: true
69 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
70 | PYPI_TOKEN: ${{ secrets.PYPI_TOKEN }}
71 | PYPI_USER: ${{ secrets.PYPI_USER }}
72 | run: npx semantic-release
73 |
--------------------------------------------------------------------------------
/greeclimate/cipher.py:
--------------------------------------------------------------------------------
1 | import base64
2 | import json
3 | import logging
4 | from typing import Union, Tuple
5 |
6 | from Crypto.Cipher import AES
7 |
8 | _logger = logging.getLogger(__name__)
9 |
10 | class CipherBase:
11 | def __init__(self, key: bytes) -> None:
12 | self._key: bytes = key
13 |
14 | @property
15 | def key(self) -> str:
16 | return self._key.decode()
17 |
18 | @key.setter
19 | def key(self, value: str) -> None:
20 | self._key = value.encode()
21 |
22 | def encrypt(self, data) -> Tuple[str, Union[str, None]]:
23 | raise NotImplementedError
24 |
25 | def decrypt(self, data) -> dict:
26 | raise NotImplementedError
27 |
28 |
29 | class CipherV1(CipherBase):
30 | def __init__(self, key: bytes = b'a3K8Bx%2r8Y7#xDh') -> None:
31 | super().__init__(key)
32 |
33 | def __create_cipher(self) -> AES:
34 | return AES.new(self._key, AES.MODE_ECB)
35 |
36 | def __pad(self, s) -> str:
37 | return s + (16 - len(s) % 16) * chr(16 - len(s) % 16)
38 |
39 | def encrypt(self, data) -> Tuple[str, Union[str, None]]:
40 | _logger.debug("Encrypting data: %s", data)
41 | cipher = self.__create_cipher()
42 | padded = self.__pad(json.dumps(data)).encode()
43 | encrypted = cipher.encrypt(padded)
44 | encoded = base64.b64encode(encrypted).decode()
45 | _logger.debug("Encrypted data: %s", encoded)
46 | return encoded, None
47 |
48 | def decrypt(self, data) -> dict:
49 | _logger.debug("Decrypting data: %s", data)
50 | cipher = self.__create_cipher()
51 | decoded = base64.b64decode(data)
52 | decrypted = cipher.decrypt(decoded).decode()
53 | t = decrypted.replace(decrypted[decrypted.rindex('}') + 1:], '')
54 | _logger.debug("Decrypted data: %s", t)
55 | return json.loads(t)
56 |
57 |
58 | class CipherV2(CipherBase):
59 | GCM_NONCE = b'\x54\x40\x78\x44\x49\x67\x5a\x51\x6c\x5e\x63\x13'
60 | GCM_AEAD = b'qualcomm-test'
61 |
62 | def __init__(self, key: bytes = b'{yxAHAY_Lm6pbC/<') -> None:
63 | super().__init__(key)
64 |
65 | def __create_cipher(self) -> AES:
66 | cipher = AES.new(self._key, AES.MODE_GCM, nonce=self.GCM_NONCE)
67 | cipher.update(self.GCM_AEAD)
68 | return cipher
69 |
70 | def encrypt(self, data) -> Tuple[str, str]:
71 | _logger.debug("Encrypting data: %s", data)
72 | cipher = self.__create_cipher()
73 | encrypted, tag = cipher.encrypt_and_digest(json.dumps(data).encode())
74 | encoded = base64.b64encode(encrypted).decode()
75 | tag = base64.b64encode(tag).decode()
76 | _logger.debug("Encrypted data: %s", encoded)
77 | _logger.debug("Cipher digest: %s", tag)
78 | return encoded, tag
79 |
80 | def decrypt(self, data) -> dict:
81 | _logger.info("Decrypting data: %s", data)
82 | cipher = self.__create_cipher()
83 | decoded = base64.b64decode(data)
84 | decrypted = cipher.decrypt(decoded).decode()
85 | t = decrypted.replace(decrypted[decrypted.rindex('}') + 1:], '')
86 | _logger.debug("Decrypted data: %s", t)
87 | return json.loads(t)
88 |
89 |
--------------------------------------------------------------------------------
/tests/common.py:
--------------------------------------------------------------------------------
1 | import socket
2 | from socket import SOCK_DGRAM
3 | from typing import Tuple, Union
4 | from unittest.mock import Mock
5 |
6 | from greeclimate.cipher import CipherV1, CipherBase
7 |
8 | DEFAULT_TIMEOUT = 1
9 | DISCOVERY_REQUEST = {"t": "scan"}
10 | DISCOVERY_RESPONSE = {
11 | "t": "pack",
12 | "i": 1,
13 | "uid": 0,
14 | "cid": "aabbcc112233",
15 | "tcid": "",
16 | "pack": {
17 | "t": "dev",
18 | "cid": "aabbcc112233",
19 | "bc": "gree",
20 | "brand": "gree",
21 | "catalog": "gree",
22 | "mac": "aabbcc112233",
23 | "mid": "10001",
24 | "model": "gree",
25 | "name": "fake unit",
26 | "series": "gree",
27 | "vender": "1",
28 | "ver": "V1.1.13",
29 | "lock": 0,
30 | },
31 | }
32 | DISCOVERY_RESPONSE_NO_CID = {
33 | "t": "pack",
34 | "i": 1,
35 | "uid": 0,
36 | "cid": "",
37 | "tcid": "",
38 | "pack": {
39 | "t": "dev",
40 | "cid": "",
41 | "bc": "gree",
42 | "brand": "gree",
43 | "catalog": "gree",
44 | "mac": "aabbcc112233",
45 | "mid": "10001",
46 | "model": "gree",
47 | "name": "fake unit",
48 | "series": "gree",
49 | "vender": "1",
50 | "ver": "V1.1.13",
51 | "lock": 0,
52 | },
53 | }
54 | DEFAULT_REQUEST = {
55 | "t": "pack",
56 | "i": 1,
57 | "uid": 0,
58 | "cid": "aabbcc112233",
59 | "tcid": "",
60 | "pack": {
61 | "t": "test"
62 | }
63 | }
64 | DEFAULT_RESPONSE = {
65 | "t": "pack",
66 | "i": 1,
67 | "uid": 0,
68 | "cid": "aabbcc112233",
69 | "tcid": "",
70 | "pack": {
71 | "t": "testresponse"
72 | }
73 | }
74 |
75 |
76 | def generate_response(data):
77 | """Generate a response from a request."""
78 | response = DEFAULT_RESPONSE.copy()
79 | response["pack"].update(data)
80 | return response
81 |
82 |
83 | def get_mock_device_info():
84 | return Mock(
85 | name="device-info",
86 | ip="127.0.0.1",
87 | port="7000",
88 | mac="aabbcc112233",
89 | brand="gree",
90 | model="gree",
91 | version="1.1.13",
92 | )
93 |
94 |
95 | def encrypt_payload(data):
96 | """Encrypt the payload of responses quickly."""
97 | d = data.copy()
98 | cipher = CipherV1()
99 | d["pack"], _ = cipher.encrypt(d["pack"])
100 | return d
101 |
102 |
103 | class FakeCipher(CipherBase):
104 | """Fake cipher object for testing."""
105 |
106 | def __init__(self, key: bytes) -> None:
107 | super().__init__(key)
108 |
109 | def encrypt(self, data) -> Tuple[str, Union[str, None]]:
110 | return data, None
111 |
112 | def decrypt(self, data) -> dict:
113 | return data
114 |
115 |
116 | class Responder:
117 | """Context manage for easy raw socket responders."""
118 |
119 | def __init__(self, family, addr, bcast=False) -> None:
120 | """Initialize the class."""
121 | self.sock = None
122 | self.family = family
123 | self.addr = addr
124 | self.bcast = bcast
125 |
126 | def __enter__(self):
127 | """Enter the context manager."""
128 | self.sock = socket.socket(self.family, SOCK_DGRAM)
129 | self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
130 | self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, self.bcast)
131 | self.sock.settimeout(DEFAULT_TIMEOUT)
132 | self.sock.bind(("", self.addr))
133 | return self.sock
134 |
135 | def __exit__(self, *args):
136 | """Exit the context manager."""
137 | self.sock.close()
138 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | 
2 |
3 | ## Gree Climate
4 |
5 | Discover, connect and control Gree based mini-split systems.
6 |
7 | **greeclimate** is a ***fully async*** Python3 based package for controlling Gree based ACs and heat pumps. Gree is a common brand for mini-split systems and is licensed and resold under many product names. This module should work for any device that also works with the Gree+ app, but has been tested on
8 |
9 | - Proklima mini-splits units
10 | - Trane mini-split heat pump (4TXK38)
11 |
12 | _If you have tested and know of others systems that work, please fork and submit a PR with the make and model_
13 |
14 | **Based on the following work**
15 |
16 | - [Gree Remote by tomikaa87](https://github.com/tomikaa87/gree-remote)
17 |
18 | ## Getting the package
19 |
20 | The easiest way to grab **greeclimate** is through PyPI
21 | `pip3 install greeclimate`
22 |
23 | ## Use Gree Climate
24 |
25 | ### Finding and binding to devices
26 |
27 | Scan the network for devices, select a device and immediately bind. See the notes below for caveats.
28 |
29 | ```python
30 | discovery = Discovery()
31 | for device_info in await discovery.scan(wait_for=5):
32 | try:
33 | device = Device(device_info)
34 | await device.bind() # Device will auto bind on update if you omit this step
35 | except CannotConnect:
36 | _LOGGER.error("Unable to bind to gree device: %s", device_info)
37 | continue
38 |
39 | _LOGGER.debug(
40 | "Adding Gree device at %s:%i (%s)",
41 | device.device_info.ip,
42 | device.device_info.port,
43 | device.device_info.name,
44 | )
45 | ```
46 |
47 | #### Caveats
48 |
49 | Devices have and use 2 encryption keys. 1 for discovery and setup which is the same on all gree devices, and a second which is negotiated during the binding process.
50 |
51 | Binding is incredibly finnicky, if you do not have the device key you must first scan and re-bind. The device will only respond to binding requests immediately proceeding a scan.
52 |
53 | ### Update device state
54 |
55 | It's possible for devices to be updated from external sources, to update the `Device` internal state with the physical device call `Device.update_state()`
56 |
57 | ### Properties
58 |
59 | There are several properties representing the state of the HVAC. Setting these properties will command the HVAC to change state.
60 |
61 | Not all properties are supported on each device, in the event a property isn't supported commands to the HVAC will simply be ignored.
62 |
63 | When setting a value it is cached but not pushed to the device until `Device.push_state_update()` is called.
64 |
65 | ```python
66 | device = Device(...)
67 | device.power = True
68 | device.mode = Mode.Auto
69 | device.target_temperature = 25
70 | device.temperature_units = TemperatureUnits.C
71 | device.fan_speed = FanSpeed.Auto
72 | device.fresh_air = True
73 | device.xfan = True
74 | device.anion = True
75 | device.sleep = True
76 | device.light = True
77 | device.horizontal_swing = HorizontalSwing.FullSwing
78 | device.vertical_swing = VerticalSwing.FullSwing
79 | device.quiet = True
80 | device.turbo = True
81 | device.steady_heat = True
82 | device.power_save = True
83 | device.target_humidity = 45
84 |
85 | # Send the state update to the HVAC
86 | await device.push_state_update()
87 | ```
88 |
89 | ## Debugging
90 |
91 | Maybe the reason you're here is that you're working with Home Assistant and your device isn't being detected.
92 |
93 | There are a few tools to help investigate the various compatibility problems that Gree based devices present.
94 |
95 | Below is a series of tests, please run them and use their output in issue reports. Additionally using [Wireshark](https://www.wireshark.org) or tcpdump to capture the network traffic can greatly assist in investigations.
96 |
97 | ### Setup
98 |
99 | This presumes you have python installed
100 |
101 | ```bash
102 | pip install -r requirements.txt
103 | ```
104 |
105 | ### Getting some basic information about your network
106 | #### Linux / OSX
107 | ```bash
108 | sudo route -n
109 | sudo ifconfig
110 | ```
111 | #### Windows command line
112 | ```
113 | route print -4
114 | ipconfig
115 | ```
116 |
117 | ### Running the discovery tests
118 |
119 | First test is to check the response of devices when trying to discovery them, writes the results to **discovery_results.txt**. Use [Wireshark](https://www.wireshark.org) here if you can.
120 |
121 | ```bash
122 | python gree.py --discovery > discovery_results.txt
123 | ```
124 |
--------------------------------------------------------------------------------
/emulator.py:
--------------------------------------------------------------------------------
1 | """
2 | Micropython device emulator, intended to run on 8266 mcus
3 | """
4 |
5 | import json
6 | import socket
7 | import time
8 |
9 | import network
10 | import ubinascii
11 | from ucryptolib import aes
12 |
13 | device_id = ubinascii.hexlify(network.WLAN().config("mac")).decode()
14 | device_name = device_id[-8:]
15 |
16 | GENERIC_KEY = "a3K8Bx%2r8Y7#xDh"
17 | DEVICE_KEY = device_id + device_id[:4]
18 |
19 | sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
20 | sock.bind(("0.0.0.0", 7000))
21 |
22 | print("listening on for device events")
23 |
24 |
25 | def send_device_data(addr, data, key):
26 | """Send a formatted request to the device."""
27 | print("\r\nS: ", json.dumps(data))
28 |
29 | if "pack" in data:
30 |
31 | def pad(s):
32 | bs = 16
33 | return s + (bs - len(s) % bs) * chr(bs - len(s) % bs)
34 |
35 | cipher = aes(key, 1)
36 | encrypted = cipher.encrypt(pad(json.dumps(data.get("pack")).encode()))
37 | data["pack"] = ubinascii.b2a_base64(encrypted).decode()
38 |
39 | data_bytes = json.dumps(data).encode()
40 | sock.sendto(data_bytes, addr)
41 |
42 |
43 | def scan_response(addr):
44 | resp = {
45 | "t": "pack",
46 | "i": 1,
47 | "uid": 0,
48 | "cid": device_id,
49 | "tcid": "",
50 | "pack": {
51 | "t": "dev",
52 | "cid": device_id,
53 | "bc": "",
54 | "brand": "gree",
55 | "catalog": "gree",
56 | "mac": device_id,
57 | "mid": "10001",
58 | "model": "gree",
59 | "name": device_name,
60 | "series": "gree",
61 | "vender": "1",
62 | "ver": "V1.2.1",
63 | "lock": 0,
64 | },
65 | }
66 | send_device_data(addr, resp, GENERIC_KEY)
67 |
68 |
69 | state_cols = [
70 | "Pow",
71 | "Mod",
72 | "SetTem",
73 | "TemUn",
74 | "TemRec",
75 | "TemSen",
76 | "WdSpd",
77 | "Air",
78 | "Blo",
79 | "Health",
80 | "SwhSlp",
81 | "Lig",
82 | "SwingLfRig",
83 | "SwUpDn",
84 | "Quiet",
85 | "Tur",
86 | "StHt",
87 | "SvSt",
88 | "HeatCoolType",
89 | "hid",
90 | ]
91 | state_dat = [1, 4, 23, 0, 0, 25, 0, 0, 0, 1, 0, 1, 0, 1, 0, 0, 0, 0, 0, "V4.0.0"]
92 |
93 |
94 | def cmd_response(addr, opt, p):
95 | for j in range(len(opt)):
96 | o = opt[j]
97 | i = state_cols.index(o)
98 | state_dat[i] = p[j]
99 |
100 | resp = {
101 | "t": "pack",
102 | "i": 0,
103 | "uid": 0,
104 | "cid": device_id,
105 | "tcid": "",
106 | "pack": {
107 | "t": "res",
108 | "mac": device_id,
109 | "r": 200,
110 | "opt": opt,
111 | "p": p,
112 | "val": p,
113 | },
114 | }
115 | send_device_data(addr, resp, DEVICE_KEY)
116 |
117 |
118 | def status_response(addr, opt):
119 | r = []
120 | for o in opt:
121 | i = state_cols.index(o)
122 | r.append(state_dat[i])
123 |
124 | resp = {
125 | "t": "pack",
126 | "i": 0,
127 | "uid": 0,
128 | "cid": device_id,
129 | "tcid": "",
130 | "pack": {
131 | "t": "dat",
132 | "mac": device_id,
133 | "r": 200,
134 | "cols": state_cols,
135 | "dat": r,
136 | },
137 | }
138 | send_device_data(addr, resp, DEVICE_KEY)
139 |
140 |
141 | def bind_response(addr):
142 | resp = {
143 | "t": "pack",
144 | "i": 1,
145 | "uid": 0,
146 | "cid": device_id,
147 | "tcid": "",
148 | "pack": {
149 | "t": "bindok",
150 | "mac": device_id,
151 | "key": DEVICE_KEY,
152 | "r": 200,
153 | },
154 | }
155 | send_device_data(addr, resp, GENERIC_KEY)
156 |
157 |
158 | while True:
159 | (d, addr) = sock.recvfrom(2048)
160 | p = json.loads(d.decode())
161 |
162 | print("\r\nR: ", d.decode())
163 | command = p.get("t")
164 | if command == "scan":
165 | scan_response(addr)
166 | elif command == "pack":
167 | # Decrypt the incoming request
168 | key = GENERIC_KEY if p.get("i") == 1 else DEVICE_KEY
169 | cipher = aes(key, 1)
170 | decoded = ubinascii.a2b_base64(p.get("pack"))
171 | decrypted = cipher.decrypt(decoded).decode()
172 | fixed = decrypted.replace(decrypted[decrypted.rindex("}") + 1 :], "")
173 | print("D: ", fixed)
174 | data = json.loads(fixed)
175 |
176 | command = data.get("t")
177 | if command == "bind":
178 | bind_response(addr)
179 | elif command == "cmd":
180 | cmd_response(addr, data.get("opt"), data.get("p"))
181 | elif command == "status":
182 | status_response(addr, data.get("cols"))
183 |
184 | time.sleep_ms(500)
185 |
--------------------------------------------------------------------------------
/CHANGELOG.md:
--------------------------------------------------------------------------------
1 | # [2.1.0](https://github.com/cmroche/greeclimate/compare/v2.0.0...v2.1.0) (2024-08-05)
2 |
3 |
4 | ### Features
5 |
6 | * Support GCM encryption for Gree devices ([#92](https://github.com/cmroche/greeclimate/issues/92)) ([7122cdd](https://github.com/cmroche/greeclimate/commit/7122cdd82597af82109a17bc32dcbfb97c78073c))
7 |
8 | # [2.0.0](https://github.com/cmroche/greeclimate/compare/v1.4.6...v2.0.0) (2024-07-02)
9 |
10 |
11 | ### Features
12 |
13 | * Full async networking ([#90](https://github.com/cmroche/greeclimate/issues/90)) ([4587984](https://github.com/cmroche/greeclimate/commit/4587984df8d01a1bc7a0b20f01590f455e361a0b))
14 |
15 |
16 | ### BREAKING CHANGES
17 |
18 | * API calls no longer block waiting for device response, use the add
19 | handler to listen for updates from the device.
20 |
21 | ## [1.4.6](https://github.com/cmroche/greeclimate/compare/v1.4.5...v1.4.6) (2024-06-27)
22 |
23 |
24 | ### Bug Fixes
25 |
26 | * Quiet mode to set value 2 not 1 ([#88](https://github.com/cmroche/greeclimate/issues/88)) ([129a190](https://github.com/cmroche/greeclimate/commit/129a1905940a0c723dce4890e6d567346967137c)), closes [#87](https://github.com/cmroche/greeclimate/issues/87)
27 |
28 | ## [1.4.5](https://github.com/cmroche/greeclimate/compare/v1.4.4...v1.4.5) (2024-06-27)
29 |
30 |
31 | ### Bug Fixes
32 |
33 | * use of Queue where Event was expected ([#85](https://github.com/cmroche/greeclimate/issues/85)) ([9dfcdbb](https://github.com/cmroche/greeclimate/commit/9dfcdbb9ae65b2c5e2f4c753e1fe7e6fa7de70a3))
34 |
35 | ## [1.4.4](https://github.com/cmroche/greeclimate/compare/v1.4.3...v1.4.4) (2024-06-27)
36 |
37 |
38 | ### Bug Fixes
39 |
40 | * twine upload error ([#84](https://github.com/cmroche/greeclimate/issues/84)) ([f097886](https://github.com/cmroche/greeclimate/commit/f097886cc39cca1beb20188cf8e762f121874cdf))
41 |
42 | ## [1.4.3](https://github.com/cmroche/greeclimate/compare/v1.4.2...v1.4.3) (2024-06-26)
43 |
44 |
45 | ### Bug Fixes
46 |
47 | * Check for v4 temperature records ([#69](https://github.com/cmroche/greeclimate/issues/69)) ([#81](https://github.com/cmroche/greeclimate/issues/81)) ([f4882c1](https://github.com/cmroche/greeclimate/commit/f4882c1e6e3bbad5b62a5c6284ec6dbc26131d3d))
48 |
49 | ## [1.4.2](https://github.com/cmroche/greeclimate/compare/v1.4.1...v1.4.2) (2024-06-26)
50 |
51 |
52 | ### Bug Fixes
53 |
54 | * Fahrenheit conversion inconsistencies ([#73](https://github.com/cmroche/greeclimate/issues/73)) ([f09f3f1](https://github.com/cmroche/greeclimate/commit/f09f3f1433968269027ea1d27259c09bc787df43))
55 |
56 | ## [1.4.1](https://github.com/cmroche/greeclimate/compare/v1.4.0...v1.4.1) (2023-02-05)
57 |
58 |
59 | ### Bug Fixes
60 |
61 | * Allow socket reuse for discovery ([#64](https://github.com/cmroche/greeclimate/issues/64)) ([db819b4](https://github.com/cmroche/greeclimate/commit/db819b496c98f89330debd5668d3f0bfff729441))
62 |
63 | # [1.4.0](https://github.com/cmroche/greeclimate/compare/v1.3.0...v1.4.0) (2022-12-03)
64 |
65 |
66 | ### Features
67 |
68 | * Add device properties for dehumidifiers ([#62](https://github.com/cmroche/greeclimate/issues/62)) ([0e2a084](https://github.com/cmroche/greeclimate/commit/0e2a0846a2dd4ed5221c5861f5e5cd857a2dca2b))
69 |
70 | # [1.3.0](https://github.com/cmroche/greeclimate/compare/v1.2.1...v1.3.0) (2022-08-06)
71 |
72 |
73 | ### Features
74 |
75 | * Support manually passing bcast addresses to device scan ([b57dbd5](https://github.com/cmroche/greeclimate/commit/b57dbd50d95d92479550592378f61372754a6fe9))
76 |
77 | ## [1.2.1](https://github.com/cmroche/greeclimate/compare/v1.2.0...v1.2.1) (2022-06-05)
78 |
79 |
80 | ### Bug Fixes
81 |
82 | * Bump semver-regex from 3.1.3 to 3.1.4 ([#54](https://github.com/cmroche/greeclimate/issues/54)) ([fdfa0f6](https://github.com/cmroche/greeclimate/commit/fdfa0f6a8eb362a2956cdc5d83eb7b61e93229e5))
83 |
84 | # [1.2.0](https://github.com/cmroche/greeclimate/compare/v1.1.1...v1.2.0) (2022-05-22)
85 |
86 |
87 | ### Features
88 |
89 | * Adding check and raise error when trying to convert out of range temp ([1bddf8b](https://github.com/cmroche/greeclimate/commit/1bddf8b7b34b7c1889812ff5c5e89128a1a365ce))
90 |
91 | ## [1.1.1](https://github.com/cmroche/greeclimate/compare/v1.1.0...v1.1.1) (2022-04-08)
92 |
93 |
94 | ### Bug Fixes
95 |
96 | * Allow min temps down to 8C or 46F ([#52](https://github.com/cmroche/greeclimate/issues/52)) ([b957e0f](https://github.com/cmroche/greeclimate/commit/b957e0f33a2578f229f5e016b42349f561bd898e))
97 | * Bump minimist from 1.2.5 to 1.2.6 ([#50](https://github.com/cmroche/greeclimate/issues/50)) ([95892e4](https://github.com/cmroche/greeclimate/commit/95892e4c8619daad72081b40f1c077149341cfbd))
98 |
99 | # [1.1.0](https://github.com/cmroche/greeclimate/compare/v1.0.3...v1.1.0) (2022-03-06)
100 |
101 |
102 | ### Features
103 |
104 | * Check firmware version from temperature report ([#49](https://github.com/cmroche/greeclimate/issues/49)) ([cd6a25f](https://github.com/cmroche/greeclimate/commit/cd6a25f9556e6fd3d4871ac86883d114fc1e9b9e))
105 |
106 | ## [1.0.3](https://github.com/cmroche/greeclimate/compare/v1.0.2...v1.0.3) (2022-02-13)
107 |
108 |
109 | ### Bug Fixes
110 |
111 | * Add version from PyPI release to setup.cfg ([#47](https://github.com/cmroche/greeclimate/issues/47)) ([61e916a](https://github.com/cmroche/greeclimate/commit/61e916a9578bea2c5f100708ea208c823356ad94))
112 |
113 | ## [1.0.2](https://github.com/cmroche/greeclimate/compare/v1.0.1...v1.0.2) (2022-01-14)
114 |
115 |
116 | ### Bug Fixes
117 |
118 | * Devices with NULL name use mac instead ([#44](https://github.com/cmroche/greeclimate/issues/44)) ([153cc32](https://github.com/cmroche/greeclimate/commit/153cc328dbfb2975f221bedc959e57754e993702))
119 | * Handle undefined bcast or peer IPs from Wireshark ([#45](https://github.com/cmroche/greeclimate/issues/45)) ([e28eb83](https://github.com/cmroche/greeclimate/commit/e28eb83a3ec5a06f3b69affda5411de485f5ded2))
120 |
121 | ## [1.0.1](https://github.com/cmroche/greeclimate/compare/v1.0.0...v1.0.1) (2021-12-30)
122 |
123 |
124 | ### Bug Fixes
125 |
126 | * Add overrides for MTK device IDs ([#41](https://github.com/cmroche/greeclimate/issues/41)) ([c036fd4](https://github.com/cmroche/greeclimate/commit/c036fd4c58703d152bee282d23caac6a81875a29))
127 |
128 | # 1.0.0 (2021-11-21)
129 |
130 |
131 | ### Bug Fixes
132 |
133 | * Support no "val" protocol variation ([f1993e1](https://github.com/cmroche/greeclimate/commit/f1993e1c6a582d701bf7b354f3b60e7e229f939a))
134 |
--------------------------------------------------------------------------------
/greeclimate/discovery.py:
--------------------------------------------------------------------------------
1 | from __future__ import annotations
2 |
3 | import asyncio
4 | import logging
5 | from asyncio import Task
6 | from asyncio.events import AbstractEventLoop
7 | from ipaddress import IPv4Address
8 |
9 | from greeclimate.cipher import CipherV1
10 | from greeclimate.device import DeviceInfo
11 | from greeclimate.network import BroadcastListenerProtocol, IPAddr
12 | from greeclimate.taskable import Taskable
13 |
14 | _LOGGER = logging.getLogger(__name__)
15 |
16 |
17 | class Listener:
18 | """Base class for device discovery events."""
19 |
20 | async def device_found(self, device_info: DeviceInfo) -> None:
21 | """Called any time a new (unique) device is found on the network."""
22 |
23 | async def device_update(self, device_info: DeviceInfo) -> None:
24 | """Called any time an up address for a device has changed on the network."""
25 |
26 |
27 | class Discovery(BroadcastListenerProtocol, Listener, Taskable):
28 | """Interact with gree devices on the network
29 |
30 | The `GreeClimate` class provides basic services for discovery and
31 | interaction with gree device on the network.
32 | """
33 |
34 | def __init__(
35 | self,
36 | timeout: int = 2,
37 | allow_loopback: bool = False,
38 | loop: AbstractEventLoop = None,
39 | ) -> None:
40 | """Initialized the discovery manager.
41 |
42 | Args:
43 | timeout (int): Wait this long for responses to the scan request
44 | allow_loopback (bool): Allow scanning the loopback interface, default `False`
45 | loop (AbstractEventLoop): Async event loop
46 | """
47 | BroadcastListenerProtocol.__init__(self, timeout)
48 | Taskable.__init__(self, loop)
49 | self.device_cipher = CipherV1()
50 | self._allow_loopback: bool = allow_loopback
51 | self._device_infos: list[DeviceInfo] = []
52 | self._listeners: list[Listener] = []
53 |
54 | # Task management
55 | @property
56 | def devices(self) -> list[DeviceInfo]:
57 | """Return the current known list of devices."""
58 | return self._device_infos
59 |
60 | # Listener management
61 | def add_listener(self, listener: Listener) -> list[Task]:
62 | """Add a listener that will receive discovery events.
63 |
64 | Adding a listener will cause all currently known device to trigger a
65 | new device added event on the listen object.
66 |
67 | Args:
68 | listener (Listener): A listener object which will receive events
69 |
70 | Returns:
71 | List[Coro]: List of tasks for device found events.
72 | """
73 | if listener not in self._listeners:
74 | self._listeners.append(listener)
75 | return [self._create_task(listener.device_found(x)) for x in self.devices]
76 |
77 | def remove_listener(self, listener: Listener) -> bool:
78 | """Remove a listener that has already been registered.
79 |
80 | Args:
81 | listener (Listener): A listener object which will receive events
82 |
83 | Returns:
84 | bool: True if listener has been remove, false if it didn't exist
85 | """
86 | if listener in self._listeners:
87 | self._listeners.remove(listener)
88 | return True
89 | return False
90 |
91 | async def device_found(self, device_info: DeviceInfo) -> None:
92 | """Device is found.
93 |
94 | Notify all listeners that a device was found. Exceptions raised by
95 | listeners are ignored.
96 |
97 | Args:
98 | device_info (DeviceInfo): Information about the newly discovered
99 | device
100 | """
101 |
102 | for index, last_info in enumerate(self._device_infos):
103 | if device_info == last_info:
104 | if device_info.ip != last_info.ip:
105 | # ip address info may have been updated, so store the new info
106 | # and trigger a `device_update` event.
107 | self._device_infos[index] = device_info
108 | tasks = [l.device_update(device_info) for l in self._listeners]
109 | await asyncio.gather(*tasks, return_exceptions=True)
110 | return
111 |
112 | self._device_infos.append(device_info)
113 |
114 | _LOGGER.info("Found gree device %s", str(device_info))
115 |
116 | tasks = [l.device_found(device_info) for l in self._listeners]
117 | await asyncio.gather(*tasks, return_exceptions=True)
118 |
119 | def packet_received(self, obj, addr: IPAddr) -> None:
120 | """Event called when a packet is received and decoded."""
121 | pack = obj.get("pack")
122 | if not pack:
123 | _LOGGER.error("Received an unexpected response during discovery")
124 | return
125 |
126 | device = (
127 | addr[0],
128 | addr[1],
129 | pack.get("mac") or pack.get("cid"),
130 | pack.get("name"),
131 | pack.get("brand"),
132 | pack.get("model"),
133 | pack.get("ver"),
134 | )
135 |
136 | self._create_task(self.device_found(DeviceInfo(*device)))
137 |
138 | # Discovery
139 | async def scan(self, wait_for: int = 0, bcast_ifaces: list[IPv4Address] | None = None) -> list[DeviceInfo]:
140 | """Sends a discovery broadcast packet on each network interface to
141 | locate Gree units on the network
142 |
143 | Args:
144 | wait_for (int): Optionally wait this many seconds for discovery
145 | and return the devices found.
146 | bcast_ifaces (list[IPv4Address]): List of broadcast addresses to scan
147 |
148 | Returns:
149 | List[DeviceInfo]: List of devices found during this scan
150 | """
151 | _LOGGER.info("Scanning for Gree devices ...")
152 |
153 | await self.search_devices(bcast_ifaces)
154 | if wait_for:
155 | await asyncio.sleep(wait_for)
156 | await asyncio.gather(*self.tasks, return_exceptions=True)
157 |
158 | return self._device_infos
159 |
160 | def _get_broadcast_addresses(self) -> list[IPv4Address]:
161 | """Return a list of broadcast addresses for each discovered interface"""
162 | import netifaces
163 |
164 | bdrAddrs = []
165 | for iface in netifaces.interfaces():
166 | for addr in netifaces.ifaddresses(iface).get(netifaces.AF_INET, []):
167 | ipaddr = addr.get("addr")
168 | bdr = addr.get("broadcast")
169 | peer = addr.get("peer")
170 | if addr:
171 | ip4addr = IPv4Address(ipaddr)
172 | if ip4addr.is_loopback and self._allow_loopback:
173 | if bdr or peer:
174 | bdrAddrs.append(IPv4Address(bdr or peer))
175 | elif not ip4addr.is_loopback:
176 | if bdr:
177 | bdrAddrs.append(IPv4Address(bdr))
178 |
179 | return bdrAddrs
180 |
181 | async def search_on_interface(self, bcast_iface: IPv4Address) -> None:
182 | """Search for devices on a specific interface."""
183 | _LOGGER.debug(
184 | "Listening for devices on %s",
185 | bcast_iface,
186 | )
187 |
188 | if self._transport is None:
189 | self._transport, _ = await self._loop.create_datagram_endpoint(
190 | lambda: self, local_addr=("0.0.0.0", 0), allow_broadcast=True
191 | )
192 |
193 | await self.send({"t": "scan"}, (str(bcast_iface), 7000))
194 |
195 | async def search_devices(self, broadcastAddrs: list[IPv4Address] | None = None) -> None:
196 | """Search for devices with specific broadcast addresses."""
197 | if not broadcastAddrs:
198 | broadcastAddrs = self._get_broadcast_addresses()
199 | await asyncio.gather(
200 | *[asyncio.create_task(self.search_on_interface(b)) for b in broadcastAddrs], return_exceptions=True
201 | )
--------------------------------------------------------------------------------
/tests/test_discovery.py:
--------------------------------------------------------------------------------
1 | import asyncio
2 | import json
3 | import socket
4 | from threading import Thread
5 | from unittest.mock import MagicMock, PropertyMock, patch
6 |
7 | import pytest
8 |
9 | from greeclimate.discovery import Discovery, Listener
10 | from .common import (
11 | DEFAULT_TIMEOUT,
12 | DISCOVERY_REQUEST,
13 | DISCOVERY_RESPONSE,
14 | Responder,
15 | get_mock_device_info, encrypt_payload,
16 | )
17 |
18 |
19 | @pytest.mark.asyncio
20 | @pytest.mark.parametrize(
21 | "addr,family", [(("127.0.0.1", 7000), socket.AF_INET)]
22 | )
23 | async def test_discover_devices(netifaces, addr, family):
24 | netifaces.return_value = {
25 | 2: [{"addr": addr[0], "netmask": "255.0.0.0", "peer": addr[0]}]
26 | }
27 |
28 | devices = [
29 | {"cid": "aabbcc001122", "mac": "aabbcc001122", "name": "MockDevice1"},
30 | {"cid": "aabbcc001123", "mac": "aabbcc001123", "name": "MockDevice2"},
31 | {"cid": "", "mac": "aabbcc001124", "name": "MockDevice3"},
32 | ]
33 |
34 | with Responder(family, addr[1]) as sock:
35 |
36 | def responder(s):
37 | (d, addr) = s.recvfrom(2048)
38 | p = json.loads(d)
39 | assert p == DISCOVERY_REQUEST
40 |
41 | for d in devices:
42 | r = DISCOVERY_RESPONSE.copy()
43 | r["pack"].update(d)
44 | p = json.dumps(encrypt_payload(r))
45 | s.sendto(p.encode(), addr)
46 |
47 | serv = Thread(target=responder, args=(sock,))
48 | serv.start()
49 |
50 | discovery = Discovery(allow_loopback=True)
51 | devices = await discovery.scan(wait_for=DEFAULT_TIMEOUT)
52 | assert devices is not None
53 | assert len(devices) == 3
54 |
55 | sock.close()
56 | serv.join(timeout=DEFAULT_TIMEOUT)
57 |
58 |
59 | @pytest.mark.asyncio
60 | async def test_discover_no_devices(netifaces):
61 | netifaces.return_value = {
62 | 2: [{"addr": "127.0.0.1", "netmask": "255.0.0.0", "peer": "127.0.0.1"}]
63 | }
64 |
65 | discovery = Discovery(allow_loopback=True)
66 | devices = await discovery.scan(wait_for=DEFAULT_TIMEOUT)
67 |
68 | assert devices is not None
69 | assert len(devices) == 0
70 |
71 |
72 | @pytest.mark.asyncio
73 | @pytest.mark.parametrize(
74 | "addr,family", [(("127.0.0.1", 7000), socket.AF_INET)]
75 | )
76 | async def test_discover_deduplicate_multiple_discoveries(
77 | netifaces, addr, family
78 | ):
79 | netifaces.return_value = {
80 | 2: [{"addr": addr[0], "netmask": "255.0.0.0", "peer": addr[0]}]
81 | }
82 |
83 | devices = [
84 | {"cid": "aabbcc001122", "mac": "aabbcc001122", "name": "MockDevice1"},
85 | {"cid": "aabbcc001123", "mac": "aabbcc001123", "name": "MockDevice2"},
86 | {"cid": "aabbcc001123", "mac": "aabbcc001123", "name": "MockDevice2"},
87 | ]
88 |
89 | with Responder(family, addr[1]) as sock:
90 |
91 | def responder(s):
92 | (d, addr) = s.recvfrom(2048)
93 | p = json.loads(d)
94 | assert p == DISCOVERY_REQUEST
95 |
96 | for d in devices:
97 | r = DISCOVERY_RESPONSE.copy()
98 | r["pack"].update(d)
99 | p = json.dumps(encrypt_payload(r))
100 | s.sendto(p.encode(), addr)
101 |
102 | serv = Thread(target=responder, args=(sock,))
103 | serv.start()
104 |
105 | discovery = Discovery(allow_loopback=True)
106 | devices = await discovery.scan(wait_for=DEFAULT_TIMEOUT)
107 | assert devices is not None
108 | assert len(devices) == 2
109 |
110 | sock.close()
111 | serv.join(timeout=DEFAULT_TIMEOUT)
112 |
113 |
114 | @pytest.mark.asyncio
115 | @pytest.mark.parametrize(
116 | "addr,family", [(("127.0.0.1", 7000), socket.AF_INET)]
117 | )
118 | async def test_discovery_events(netifaces, addr, family):
119 | netifaces.return_value = {
120 | 2: [{"addr": addr[0], "netmask": "255.0.0.0", "peer": addr[0]}]
121 | }
122 |
123 | with Responder(family, addr[1]) as sock:
124 |
125 | def responder(s):
126 | (d, addr) = s.recvfrom(2048)
127 | p = json.loads(d)
128 | assert p == DISCOVERY_REQUEST
129 |
130 | p = json.dumps(encrypt_payload(DISCOVERY_RESPONSE))
131 | s.sendto(p.encode(), addr)
132 |
133 | serv = Thread(target=responder, args=(sock,))
134 | serv.start()
135 |
136 | with patch.object(Discovery, "packet_received", return_value=None) as mock:
137 | discovery = Discovery(allow_loopback=True)
138 | await discovery.scan()
139 | await asyncio.sleep(DEFAULT_TIMEOUT)
140 |
141 | assert mock.call_count == 1
142 |
143 | sock.close()
144 | serv.join(timeout=DEFAULT_TIMEOUT)
145 |
146 |
147 | @pytest.mark.asyncio
148 | async def test_discovery_device_update_events():
149 | discovery = Discovery(allow_loopback=True)
150 | discovery.packet_received(
151 | {
152 | "pack": {
153 | "mac": "aa11bb22cc33",
154 | "cid": 1,
155 | "name": "MockDevice",
156 | "brand": "",
157 | "model": "",
158 | "ver": "1.0.0",
159 | }
160 | },
161 | ("1.1.1.1", 7000),
162 | )
163 |
164 | await asyncio.gather(*discovery.tasks, return_exceptions=True)
165 |
166 | assert len(discovery.devices) == 1
167 | assert discovery.devices[0].mac == "aa11bb22cc33"
168 | assert discovery.devices[0].ip == "1.1.1.1"
169 |
170 | discovery.packet_received(
171 | {
172 | "pack": {
173 | "mac": "aa11bb22cc33",
174 | "cid": 1,
175 | "name": "MockDevice",
176 | "brand": "",
177 | "model": "",
178 | "ver": "1.0.0",
179 | }
180 | },
181 | ("1.1.2.2", 7000),
182 | )
183 |
184 | await asyncio.gather(*discovery.tasks, return_exceptions=True)
185 |
186 | assert len(discovery.devices) == 1
187 | assert discovery.devices[0].mac == "aa11bb22cc33"
188 | assert discovery.devices[0].ip == "1.1.2.2"
189 |
190 |
191 | @pytest.mark.asyncio
192 | @pytest.mark.parametrize(
193 | "addr,family", [(("127.0.0.1", 7000), socket.AF_INET)]
194 | )
195 | async def test_discover_devices_bad_data(netifaces, addr, family):
196 | """Create a socket broadcast responder, an async broadcast listener,
197 | test discovery responses.
198 | """
199 | netifaces.return_value = {
200 | 2: [{"addr": addr[0], "netmask": "255.0.0.0", "peer": addr[0]}]
201 | }
202 |
203 | with Responder(family, addr[1]) as sock:
204 |
205 | def responder(s):
206 | (d, addr) = s.recvfrom(2048)
207 | p = json.loads(d)
208 | assert p == DISCOVERY_REQUEST
209 |
210 | s.sendto("garbage data".encode(), addr)
211 |
212 | serv = Thread(target=responder, args=(sock,))
213 | serv.start()
214 |
215 | # Run the listener portion now
216 | discovery = Discovery(allow_loopback=True)
217 | response = await discovery.scan(wait_for=DEFAULT_TIMEOUT)
218 |
219 | assert response is not None
220 | assert len(response) == 0
221 |
222 | sock.close()
223 | serv.join(timeout=DEFAULT_TIMEOUT)
224 |
225 |
226 | @pytest.mark.asyncio
227 | async def test_add_new_listener():
228 | """Register a listener, test that is registered."""
229 |
230 | listener = MagicMock(spec_set=Listener)
231 | discovery = Discovery()
232 |
233 | result = discovery.add_listener(listener)
234 | assert result is not None
235 |
236 | result = discovery.add_listener(listener)
237 | assert result is None
238 |
239 |
240 | @pytest.mark.asyncio
241 | async def test_add_new_listener_with_devices():
242 | """Register a listener, test that is registered."""
243 |
244 | with patch.object(Discovery, "devices", new_callable=PropertyMock) as mock:
245 | mock.return_value = [get_mock_device_info()]
246 | listener = MagicMock(spec_set=Listener)
247 | discovery = Discovery()
248 |
249 | result = discovery.add_listener(listener)
250 | await asyncio.gather(*discovery.tasks)
251 |
252 | assert result is not None
253 | assert len(result) == 1
254 | assert listener.device_found.call_count == 1
255 |
256 |
257 | @pytest.mark.asyncio
258 | async def test_remove_listener():
259 | """Register, remove listener, test results."""
260 |
261 | listener = MagicMock(spec_set=Listener)
262 | discovery = Discovery()
263 |
264 | result = discovery.add_listener(listener)
265 | assert result is not None
266 |
267 | result = discovery.remove_listener(listener)
268 | assert result is True
269 |
270 | result = discovery.remove_listener(listener)
271 | assert result is False
272 |
--------------------------------------------------------------------------------
/greeclimate/network.py:
--------------------------------------------------------------------------------
1 | import asyncio
2 | import json
3 | import logging
4 | import socket
5 | from dataclasses import dataclass
6 | from enum import Enum
7 | from typing import Any, Dict, Tuple, Union
8 |
9 | from greeclimate.cipher import CipherBase
10 | from greeclimate.deviceinfo import DeviceInfo
11 |
12 | NETWORK_TIMEOUT = 10
13 | _LOGGER = logging.getLogger(__name__)
14 |
15 | IPAddr = Tuple[str, int]
16 |
17 |
18 | class Commands(Enum):
19 | BIND = "bind"
20 | CMD = "cmd"
21 | PACK = "pack"
22 | SCAN = "scan"
23 | STATUS = "status"
24 |
25 |
26 | class Response(Enum):
27 | BIND_OK = "bindok"
28 | DATA = "dat"
29 | RESULT = "res"
30 |
31 |
32 | @dataclass
33 | class IPInterface:
34 | ip_address: str
35 | bcast_address: str
36 |
37 |
38 | class DeviceProtocolBase2(asyncio.DatagramProtocol):
39 | """Event driven device protocol class."""
40 |
41 | def __init__(self, timeout: int = 10, drained: asyncio.Event = None) -> None:
42 | """Initialize the device protocol object.
43 |
44 | Args:
45 | timeout (int): Packet send timeout
46 | drained (asyncio.Event): Packet send drain event signal
47 | """
48 | self._timeout: int = timeout
49 | self._drained: asyncio.Event = drained or asyncio.Event()
50 | self._drained.set()
51 |
52 | self._transport: Union[asyncio.transports.DatagramTransport, None] = None
53 | self._cipher: Union[CipherBase, None] = None
54 |
55 |
56 | # This event need to be implemented to handle incoming requests
57 | def packet_received(self, obj, addr: IPAddr) -> None:
58 | """Event called when a packet is received and decoded.
59 |
60 | Args:
61 | obj (JSON): Json object with decoded UDP data
62 | addr (IPAddr): Endpoint address of the sender
63 | """
64 | raise NotImplementedError("packet_received must be implemented in a subclass")
65 |
66 | @property
67 | def device_cipher(self) -> CipherBase:
68 | """Sets the encryption key used for device data."""
69 | return self._cipher
70 |
71 | @device_cipher.setter
72 | def device_cipher(self, value: CipherBase):
73 | """Gets the encryption key used for device data."""
74 | self._cipher = value
75 |
76 | @property
77 | def device_key(self) -> str:
78 | """Gets the encryption key used for device data."""
79 | if self._cipher is None:
80 | raise ValueError("Cipher object not set")
81 | return self._cipher.key
82 |
83 | @device_key.setter
84 | def device_key(self, value: str):
85 | """Sets the encryption key used for device data."""
86 | if self._cipher is None:
87 | raise ValueError("Cipher object not set")
88 | self._cipher.key = value
89 |
90 | def close(self) -> None:
91 | """Close the UDP transport."""
92 | try:
93 | self._transport.close()
94 | self._transport = None
95 | except RuntimeError:
96 | pass
97 |
98 | def connection_made(self, transport: asyncio.transports.DatagramTransport) -> None:
99 | """Called when the Datagram protocol handler is initialized."""
100 | self._transport = transport
101 |
102 | def connection_lost(self, exc: Exception) -> None:
103 | """Handle a closed socket."""
104 |
105 | if self._transport is not None:
106 | self._transport.close()
107 | self._transport = None
108 |
109 | # In this case the connection was closed unexpectedly
110 | if exc is not None:
111 | _LOGGER.exception("Connection was closed unexpectedly", exc_info=exc)
112 | raise exc
113 |
114 | def error_received(self, exc: Exception) -> None:
115 | """Handle error while sending/receiving datagrams."""
116 | _LOGGER.exception("Connection reported an exception", exc_info=exc)
117 |
118 | def pause_writing(self) -> None:
119 | """Stop writing additional data to the transport."""
120 | self._drained.clear()
121 | super().pause_writing()
122 |
123 | def resume_writing(self) -> None:
124 | """Resume writing data to the transport."""
125 | self._drained.set()
126 | super().resume_writing()
127 |
128 | def datagram_received(self, data: bytes, addr: IPAddr) -> None:
129 | """Handle an incoming datagram."""
130 | if len(data) == 0:
131 | return
132 |
133 | obj = json.loads(data)
134 |
135 | if obj.get("pack"):
136 | obj["pack"] = self._cipher.decrypt(obj["pack"])
137 |
138 | _LOGGER.debug("Received packet from %s:\n<- %s", addr[0], json.dumps(obj))
139 | self.packet_received(obj, addr)
140 |
141 | async def send(self, obj, addr: IPAddr = None, cipher: Union[CipherBase, None] = None) -> None:
142 | """Send encode and send JSON command to the device.
143 |
144 | Args:
145 | addr (object): (Optional) Address to send the message
146 | cipher (object): (Optional) Initial cipher to use for SCANNING and BINDING
147 | """
148 | _LOGGER.debug("Sending packet:\n-> %s", json.dumps(obj))
149 |
150 | if obj.get("pack"):
151 | if obj.get("i") == 1:
152 | if cipher is None:
153 | raise ValueError("Cipher must be supplied for SCAN or BIND messages")
154 | self._cipher = cipher
155 |
156 | obj["pack"], tag = self._cipher.encrypt(obj["pack"])
157 | if tag:
158 | obj["tag"] = tag
159 |
160 | data_bytes = json.dumps(obj).encode()
161 | self._transport.sendto(data_bytes, addr)
162 |
163 | task = asyncio.create_task(self._drained.wait())
164 | await asyncio.wait_for(task, self._timeout)
165 |
166 |
167 | class BroadcastListenerProtocol(DeviceProtocolBase2):
168 | """Special protocol handler for when broadcast is needed."""
169 |
170 | def connection_made(self, transport: asyncio.transports.DatagramTransport) -> None:
171 | """Called when the Datagram protocol handler is initialized."""
172 | super().connection_made(transport)
173 |
174 | sock = transport.get_extra_info("socket") # type: socket.socket
175 | sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
176 | sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
177 |
178 |
179 | class DeviceProtocol2(DeviceProtocolBase2):
180 | """Protocol handler for direct device communication."""
181 | _handlers = {}
182 |
183 | def __init__(self, timeout: int = 10, drained: asyncio.Event = None) -> None:
184 | """Initialize the device protocol object.
185 |
186 | Args:
187 | timeout (int): Packet send timeout
188 | drained (asyncio.Event): Packet send drain event signal
189 | """
190 | DeviceProtocolBase2.__init__(self, timeout, drained)
191 | self._ready = asyncio.Event()
192 | self._ready.clear()
193 |
194 | @property
195 | def ready(self) -> asyncio.Event:
196 | return self._ready
197 |
198 | def add_handler(self, event_name: Response, callback):
199 | """Add a callback for a specific event."""
200 | if event_name not in Response:
201 | raise ValueError(f"Invalid event name: {event_name.value}")
202 |
203 | if event_name not in self._handlers:
204 | self._handlers[event_name] = []
205 | self._handlers[event_name].append(callback)
206 |
207 | def remove_handler(self, event_name: Response, callback):
208 | """Remove a specific callback for a specific event."""
209 | if event_name not in Response:
210 | raise ValueError(f"Invalid event name: {event_name.value}")
211 |
212 | if event_name in self._handlers:
213 | self._handlers[event_name].remove(callback)
214 |
215 | def packet_received(self, obj, addr: IPAddr) -> None:
216 | """Event called when a packet is received and decoded.
217 |
218 | Args:
219 | obj (JSON): Json object with decoded UDP data
220 | addr (IPAddr): Endpoint address of the sender
221 | """
222 | params = {
223 | Response.BIND_OK.value: lambda o, a: [o["pack"]["key"]],
224 | Response.DATA.value: lambda o, a: [dict(zip(o["pack"]["cols"], o["pack"]["dat"]))],
225 | Response.RESULT.value: lambda o, a: [dict(zip(o["pack"]["opt"], o["pack"]["val"]))],
226 | }
227 | handlers = {
228 | Response.BIND_OK.value: lambda *args: self.__handle_device_bound(*args),
229 | Response.DATA.value: lambda *args: self.__handle_state_update(*args),
230 | Response.RESULT.value: lambda *args: self.__handle_state_update(*args),
231 | }
232 | try:
233 | resp = obj.get("pack", {}).get("t")
234 | handler = handlers.get(resp, self.handle_unknown_packet)
235 | param = params.get(resp, lambda o, a: (o, a))(obj, addr)
236 | handler(*param)
237 | except AttributeError as e:
238 | _LOGGER.exception("Error while handling packet", exc_info=e)
239 | except KeyError as e:
240 | _LOGGER.exception("Error while handling packet", exc_info=e)
241 | else:
242 | # Call any registered callbacks for this event
243 | if resp in handlers:
244 | for callback in self._handlers.get(Response(resp), []):
245 | callback(*param)
246 |
247 | def handle_unknown_packet(self, obj, addr: IPAddr) -> None:
248 | _LOGGER.warning("Received unknown packet from %s:\n%s", addr[0], json.dumps(obj))
249 |
250 | def __handle_device_bound(self, key: str) -> None:
251 | self._ready.set()
252 | self.handle_device_bound(key)
253 |
254 | def handle_device_bound(self, key: str) -> None:
255 | """ Implement this function to handle device bound events. """
256 | pass
257 |
258 | def __handle_state_update(self, data) -> None:
259 | self.handle_state_update(**data)
260 |
261 | def handle_state_update(self, **kwargs) -> None:
262 | """ Implement this function to handle device state updates. """
263 | pass
264 |
265 | def _generate_payload(self, command: Commands, device_info: DeviceInfo, data: Dict[str, Any]) -> Dict[str, Any]:
266 | payload = {
267 | "cid": "app",
268 | "i": 1 if command in [Commands.BIND, Commands.SCAN] else 0,
269 | "t": Commands.PACK.value if data is not None else command.value,
270 | "uid": 0,
271 | "tcid": device_info.mac
272 | }
273 | if data is not None:
274 | payload["pack"] = {
275 | "t": command.value,
276 | "mac": device_info.mac
277 | }
278 | payload["pack"].update(data)
279 | return payload
280 |
281 | def create_bind_message(self, device_info: DeviceInfo) -> Dict[str, Any]:
282 | return self._generate_payload(Commands.BIND, device_info, {"uid": 0})
283 |
284 | def create_status_message(self, device_info: DeviceInfo, *args) -> Dict[str, Any]:
285 | return self._generate_payload(Commands.STATUS, device_info, {"cols": list(args)})
286 |
287 | def create_command_message(self, device_info: DeviceInfo, **kwargs) -> Dict[str, Any]:
288 | return self._generate_payload(Commands.CMD, device_info,
289 | {"opt": list(kwargs.keys()), "p": list(kwargs.values())})
290 |
--------------------------------------------------------------------------------
/network-log.txt:
--------------------------------------------------------------------------------
1 | 2020-11-08 11:39:37 DEBUG (MainThread) [greeclimate.network] Recived packet:
2 | {"t": "pack", "i": 1, "uid": 0, "cid": "f4911e7aca59", "tcid": "", "pack": {"t": "dev", "cid": "f4911e7aca59", "bc": "", "brand": "gree", "catalog": "gree", "mac": "f4911e7aca59", "mid": "10001", "model": "gree", "name": "1e7aca59", "series": "gree", "vender": "1", "ver": "V1.2.1", "lock": 0}}
3 | 2020-11-08 11:39:37 DEBUG (MainThread) [greeclimate.network] Received response from device search
4 | {'t': 'dev', 'cid': 'f4911e7aca59', 'bc': '', 'brand': 'gree', 'catalog': 'gree', 'mac': 'f4911e7aca59', 'mid': '10001', 'model': 'gree', 'name': '1e7aca59', 'series': 'gree', 'vender': '1', 'ver': 'V1.2.1', 'lock': 0}
5 |
6 | 2020-11-08 11:39:39 DEBUG (MainThread) [greeclimate.network] Recived packet:
7 | {"t": "pack", "i": 1, "uid": 0, "cid": "f4911e7aca59", "tcid": "", "pack": {"t": "dev", "cid": "f4911e7aca59", "bc": "", "brand": "gree", "catalog": "gree", "mac": "f4911e7aca59", "mid": "10001", "model": "gree", "name": "1e7aca59", "series": "gree", "vender": "1", "ver": "V1.2.1", "lock": 0}}
8 | 2020-11-08 11:39:39 DEBUG (MainThread) [greeclimate.network] Received response from device search
9 | {'t': 'dev', 'cid': 'f4911e7aca59', 'bc': '', 'brand': 'gree', 'catalog': 'gree', 'mac': 'f4911e7aca59', 'mid': '10001', 'model': 'gree', 'name': '1e7aca59', 'series': 'gree', 'vender': '1', 'ver': 'V1.2.1', 'lock': 0}
10 |
11 | 2020-11-08 11:39:41 DEBUG (MainThread) [greeclimate.network] Sending packet:
12 | {"cid": "app", "i": "1", "t": "pack", "uid": 0, "tcid": "f4911e7aca59", "pack": {"mac": "f4911e7aca59", "t": "bind", "uid": 0}}
13 | 2020-11-08 11:39:41 DEBUG (MainThread) [greeclimate.network] Recived packet:
14 | {"t": "pack", "i": 1, "uid": 0, "cid": "f4911e7aca59", "tcid": "", "pack": {"t": "bindok", "mac": "f4911e7aca59", "key": "St8Vw1Yz4Bc7Ef0H", "r": 200}}
15 | 2020-11-08 11:40:34 DEBUG (MainThread) [greeclimate.network] Recived packet:
16 | {"t": "pack", "i": 1, "uid": 0, "cid": "f4911e7aca59", "tcid": "", "pack": {"t": "dev", "cid": "f4911e7aca59", "bc": "", "brand": "gree", "catalog": "gree", "mac": "f4911e7aca59", "mid": "10001", "model": "gree", "name": "1e7aca59", "series": "gree", "vender": "1", "ver": "V1.2.1", "lock": 0}}
17 | 2020-11-08 11:40:34 DEBUG (MainThread) [greeclimate.network] Received response from device search
18 | {'t': 'dev', 'cid': 'f4911e7aca59', 'bc': '', 'brand': 'gree', 'catalog': 'gree', 'mac': 'f4911e7aca59', 'mid': '10001', 'model': 'gree', 'name': '1e7aca59', 'series': 'gree', 'vender': '1', 'ver': 'V1.2.1', 'lock': 0}
19 | 2020-11-08 11:40:36 DEBUG (MainThread) [greeclimate.network] Recived packet:
20 | {"t": "pack", "i": 1, "uid": 0, "cid": "f4911e7aca59", "tcid": "", "pack": {"t": "dev", "cid": "f4911e7aca59", "bc": "", "brand": "gree", "catalog": "gree", "mac": "f4911e7aca59", "mid": "10001", "model": "gree", "name": "1e7aca59", "series": "gree", "vender": "1", "ver": "V1.2.1", "lock": 0}}
21 | 2020-11-08 11:40:36 DEBUG (MainThread) [greeclimate.network] Received response from device search
22 | {'t': 'dev', 'cid': 'f4911e7aca59', 'bc': '', 'brand': 'gree', 'catalog': 'gree', 'mac': 'f4911e7aca59', 'mid': '10001', 'model': 'gree', 'name': '1e7aca59', 'series': 'gree', 'vender': '1', 'ver': 'V1.2.1', 'lock': 0}
23 |
24 | 2020-11-08 11:40:38 DEBUG (MainThread) [greeclimate.network] Sending packet:
25 | {"cid": "app", "i": "1", "t": "pack", "uid": 0, "tcid": "f4911e7aca59", "pack": {"mac": "f4911e7aca59", "t": "bind", "uid": 0}}
26 | 2020-11-08 11:40:38 DEBUG (MainThread) [greeclimate.network] Recived packet:
27 | {"t": "pack", "i": 1, "uid": 0, "cid": "f4911e7aca59", "tcid": "", "pack": {"t": "bindok", "mac": "f4911e7aca59", "key": "St8Vw1Yz4Bc7Ef0H", "r": 200}}
28 | 2020-11-08 11:46:13 DEBUG (MainThread) [greeclimate.network] Recived packet:
29 | {"t": "pack", "i": 1, "uid": 0, "cid": "f4911e7aca59", "tcid": "", "pack": {"t": "dev", "cid": "f4911e7aca59", "bc": "", "brand": "gree", "catalog": "gree", "mac": "f4911e7aca59", "mid": "10001", "model": "gree", "name": "1e7aca59", "series": "gree", "vender": "1", "ver": "V1.2.1", "lock": 0}}
30 | 2020-11-08 11:46:13 DEBUG (MainThread) [greeclimate.network] Received response from device search
31 | {'t': 'dev', 'cid': 'f4911e7aca59', 'bc': '', 'brand': 'gree', 'catalog': 'gree', 'mac': 'f4911e7aca59', 'mid': '10001', 'model': 'gree', 'name': '1e7aca59', 'series': 'gree', 'vender': '1', 'ver': 'V1.2.1', 'lock': 0}
32 | 2020-11-08 11:46:15 DEBUG (MainThread) [greeclimate.network] Recived packet:
33 | {"t": "pack", "i": 1, "uid": 0, "cid": "f4911e7aca59", "tcid": "", "pack": {"t": "dev", "cid": "f4911e7aca59", "bc": "", "brand": "gree", "catalog": "gree", "mac": "f4911e7aca59", "mid": "10001", "model": "gree", "name": "1e7aca59", "series": "gree", "vender": "1", "ver": "V1.2.1", "lock": 0}}
34 | 2020-11-08 11:46:15 DEBUG (MainThread) [greeclimate.network] Received response from device search
35 | {'t': 'dev', 'cid': 'f4911e7aca59', 'bc': '', 'brand': 'gree', 'catalog': 'gree', 'mac': 'f4911e7aca59', 'mid': '10001', 'model': 'gree', 'name': '1e7aca59', 'series': 'gree', 'vender': '1', 'ver': 'V1.2.1', 'lock': 0}
36 | 2020-11-08 11:46:17 INFO (MainThread) [greeclimate.discovery] Found Device: 1e7aca59 @ 192.168.1.29:7000 (mac: f4911e7aca59)
37 |
38 | 2020-11-08 11:46:17 INFO (MainThread) [greeclimate.device] Starting device binding to Device: 1e7aca59 @ 192.168.1.29:7000 (mac: f4911e7aca59)
39 | 2020-11-08 11:46:17 DEBUG (MainThread) [greeclimate.network] Sending packet:
40 | {"cid": "app", "i": "1", "t": "pack", "uid": 0, "tcid": "f4911e7aca59", "pack": {"mac": "f4911e7aca59", "t": "bind", "uid": 0}}
41 | 2020-11-08 11:46:17 DEBUG (MainThread) [greeclimate.network] Recived packet:
42 | {"t": "pack", "i": 1, "uid": 0, "cid": "f4911e7aca59", "tcid": "", "pack": {"t": "bindok", "mac": "f4911e7aca59", "key": "St8Vw1Yz4Bc7Ef0H", "r": 200}}
43 | 2020-11-08 11:50:22 DEBUG (MainThread) [greeclimate.network] Recived packet:
44 | {"t": "pack", "i": 1, "uid": 0, "cid": "f4911e7aca59", "tcid": "", "pack": {"t": "dev", "cid": "f4911e7aca59", "bc": "", "brand": "gree", "catalog": "gree", "mac": "f4911e7aca59", "mid": "10001", "model": "gree", "name": "1e7aca59", "series": "gree", "vender": "1", "ver": "V1.2.1", "lock": 0}}
45 | 2020-11-08 11:50:22 DEBUG (MainThread) [greeclimate.network] Received response from device search
46 | {'t': 'dev', 'cid': 'f4911e7aca59', 'bc': '', 'brand': 'gree', 'catalog': 'gree', 'mac': 'f4911e7aca59', 'mid': '10001', 'model': 'gree', 'name': '1e7aca59', 'series': 'gree', 'vender': '1', 'ver': 'V1.2.1', 'lock': 0}
47 | 2020-11-08 11:50:24 DEBUG (MainThread) [greeclimate.network] Recived packet:
48 | {"t": "pack", "i": 1, "uid": 0, "cid": "f4911e7aca59", "tcid": "", "pack": {"t": "dev", "cid": "f4911e7aca59", "bc": "", "brand": "gree", "catalog": "gree", "mac": "f4911e7aca59", "mid": "10001", "model": "gree", "name": "1e7aca59", "series": "gree", "vender": "1", "ver": "V1.2.1", "lock": 0}}
49 | 2020-11-08 11:50:24 DEBUG (MainThread) [greeclimate.network] Received response from device search
50 | {'t': 'dev', 'cid': 'f4911e7aca59', 'bc': '', 'brand': 'gree', 'catalog': 'gree', 'mac': 'f4911e7aca59', 'mid': '10001', 'model': 'gree', 'name': '1e7aca59', 'series': 'gree', 'vender': '1', 'ver': 'V1.2.1', 'lock': 0}
51 |
52 | 2020-11-08 11:50:26 DEBUG (MainThread) [greeclimate.network] Sending packet:
53 | {"cid": "app", "i": "1", "t": "pack", "uid": 0, "tcid": "f4911e7aca59", "pack": {"mac": "f4911e7aca59", "t": "bind", "uid": 0}}
54 | 2020-11-08 11:50:26 DEBUG (MainThread) [greeclimate.network] Recived packet:
55 | {"t": "pack", "i": 1, "uid": 0, "cid": "f4911e7aca59", "tcid": "", "pack": {"t": "bindok", "mac": "f4911e7aca59", "key": "St8Vw1Yz4Bc7Ef0H", "r": 200}}
56 |
57 | 2020-11-08 11:50:26 DEBUG (MainThread) [greeclimate.network] Sending packet:
58 | {"cid": "app", "i": 0, "t": "pack", "uid": 0, "tcid": "f4911e7aca59", "pack": {"mac": "f4911e7aca59", "t": "status", "cols": ["Pow", "Mod", "SetTem", "TemUn", "TemRec", "WdSpd", "Air", "Blo", "Health", "SwhSlp", "Lig", "SwingLfRig", "SwUpDn", "Quiet", "Tur", "StHt", "SvSt", "HeatCoolType"]}}
59 | 2020-11-08 11:50:26 DEBUG (MainThread) [greeclimate.network] Recived packet:
60 | {"t": "pack", "i": 0, "uid": 0, "cid": "f4911e7aca59", "tcid": "", "pack": {"t": "dat", "mac": "f4911e7aca59", "r": 200, "cols": ["Pow", "Mod", "SetTem", "TemUn", "TemRec", "WdSpd", "Air", "Blo", "Health", "SwhSlp", "Lig", "SwingLfRig", "SwUpDn", "Quiet", "Tur", "StHt", "SvSt", "HeatCoolType"], "dat": [1, 4, 23, 0, 0, 0, 0, 0, 1, 0, 1, 0, 1, 0, 0, 0, 0, 0]}}
61 |
62 | 2020-11-08 11:50:44 DEBUG (MainThread) [greeclimate.device] Pushing state updates to (Device: 1e7aca59 @ 192.168.1.29:7000 (mac: f4911e7aca59))
63 | 2020-11-08 11:50:44 DEBUG (MainThread) [greeclimate.device] Sending remote state update Lig -> 0
64 | 2020-11-08 11:50:44 DEBUG (MainThread) [greeclimate.network] Sending packet:
65 | {"cid": "app", "i": 0, "t": "pack", "uid": 0, "tcid": "f4911e7aca59", "pack": {"opt": ["Lig"], "p": [0], "t": "cmd"}}
66 | 2020-11-08 11:50:44 DEBUG (MainThread) [greeclimate.network] Recived packet:
67 | {"t": "pack", "i": 0, "uid": 0, "cid": "f4911e7aca59", "tcid": "", "pack": {"t": "res", "mac": "f4911e7aca59", "r": 200, "opt": ["Lig"], "p": [0], "val": [0]}}
68 |
69 | 2020-11-08 11:51:25 DEBUG (MainThread) [greeclimate.device] Updating device properties for (Device: 1e7aca59 @ 192.168.1.29:7000 (mac: f4911e7aca59))
70 | 2020-11-08 11:51:26 DEBUG (MainThread) [greeclimate.network] Sending packet:
71 | {"cid": "app", "i": 0, "t": "pack", "uid": 0, "tcid": "f4911e7aca59", "pack": {"mac": "f4911e7aca59", "t": "status", "cols": ["Pow", "Mod", "SetTem", "TemUn", "TemRec", "WdSpd", "Air", "Blo", "Health", "SwhSlp", "Lig", "SwingLfRig", "SwUpDn", "Quiet", "Tur", "StHt", "SvSt", "HeatCoolType"]}}
72 | 2020-11-08 11:51:26 DEBUG (MainThread) [greeclimate.network] Recived packet:
73 | {"t": "pack", "i": 0, "uid": 0, "cid": "f4911e7aca59", "tcid": "", "pack": {"t": "dat", "mac": "f4911e7aca59", "r": 200, "cols": ["Pow", "Mod", "SetTem", "TemUn", "TemRec", "WdSpd", "Air", "Blo", "Health", "SwhSlp", "Lig", "SwingLfRig", "SwUpDn", "Quiet", "Tur", "StHt", "SvSt", "HeatCoolType"], "dat": [1, 4, 23, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0]}}
74 | 2020-11-08 11:51:26 DEBUG (MainThread) [homeassistant.components.gree.bridge] Finished fetching gree-1e7aca59 data in 0.019 seconds
75 |
76 | 2020-11-08 11:52:26 DEBUG (MainThread) [greeclimate.device] Updating device properties for (Device: 1e7aca59 @ 192.168.1.29:7000 (mac: f4911e7aca59))
77 | 2020-11-08 11:52:26 DEBUG (MainThread) [greeclimate.network] Sending packet:
78 | {"cid": "app", "i": 0, "t": "pack", "uid": 0, "tcid": "f4911e7aca59", "pack": {"mac": "f4911e7aca59", "t": "status", "cols": ["Pow", "Mod", "SetTem", "TemUn", "TemRec", "WdSpd", "Air", "Blo", "Health", "SwhSlp", "Lig", "SwingLfRig", "SwUpDn", "Quiet", "Tur", "StHt", "SvSt", "HeatCoolType"]}}
79 | 2020-11-08 11:52:26 DEBUG (MainThread) [greeclimate.network] Recived packet:
80 | {"t": "pack", "i": 0, "uid": 0, "cid": "f4911e7aca59", "tcid": "", "pack": {"t": "dat", "mac": "f4911e7aca59", "r": 200, "cols": ["Pow", "Mod", "SetTem", "TemUn", "TemRec", "WdSpd", "Air", "Blo", "Health", "SwhSlp", "Lig", "SwingLfRig", "SwUpDn", "Quiet", "Tur", "StHt", "SvSt", "HeatCoolType"], "dat": [1, 4, 23, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0]}}
81 | 2020-11-08 11:52:26 DEBUG (MainThread) [homeassistant.components.gree.bridge] Finished fetching gree-1e7aca59 data in 0.030 seconds
82 |
83 | 2020-11-08 11:52:45 DEBUG (MainThread) [greeclimate.device] Pushing state updates to (Device: 1e7aca59 @ 192.168.1.29:7000 (mac: f4911e7aca59))
84 | 2020-11-08 11:52:45 DEBUG (MainThread) [greeclimate.device] Sending remote state update Lig -> 1
85 | 2020-11-08 11:52:45 DEBUG (MainThread) [greeclimate.network] Sending packet:
86 | {"cid": "app", "i": 0, "t": "pack", "uid": 0, "tcid": "f4911e7aca59", "pack": {"opt": ["Lig"], "p": [1], "t": "cmd"}}
87 | 2020-11-08 11:52:45 DEBUG (MainThread) [greeclimate.network] Recived packet:
88 | {"t": "pack", "i": 0, "uid": 0, "cid": "f4911e7aca59", "tcid": "", "pack": {"t": "res", "mac": "f4911e7aca59", "r": 200, "opt": ["Lig"], "p": [1], "val": [1]}}
89 |
90 | 2020-11-08 11:52:57 DEBUG (MainThread) [greeclimate.device] Pushing state updates to (Device: 1e7aca59 @ 192.168.1.29:7000 (mac: f4911e7aca59))
91 | 2020-11-08 11:52:57 DEBUG (MainThread) [greeclimate.device] Sending remote state update WdSpd -> 5
92 | 2020-11-08 11:52:57 DEBUG (MainThread) [greeclimate.network] Sending packet:
93 | {"cid": "app", "i": 0, "t": "pack", "uid": 0, "tcid": "f4911e7aca59", "pack": {"opt": ["WdSpd"], "p": [5], "t": "cmd"}}
94 | 2020-11-08 11:52:57 DEBUG (MainThread) [greeclimate.network] Recived packet:
95 | {"t": "pack", "i": 0, "uid": 0, "cid": "f4911e7aca59", "tcid": "", "pack": {"t": "res", "mac": "f4911e7aca59", "r": 200, "opt": ["WdSpd"], "p": [5], "val": [5]}}
96 |
97 | 2020-11-08 11:53:01 DEBUG (MainThread) [greeclimate.device] Pushing state updates to (Device: 1e7aca59 @ 192.168.1.29:7000 (mac: f4911e7aca59))
98 | 2020-11-08 11:53:01 DEBUG (MainThread) [greeclimate.device] Sending remote state update WdSpd -> 0
99 | 2020-11-08 11:53:01 DEBUG (MainThread) [greeclimate.network] Sending packet:
100 | {"cid": "app", "i": 0, "t": "pack", "uid": 0, "tcid": "f4911e7aca59", "pack": {"opt": ["WdSpd"], "p": [0], "t": "cmd"}}
101 | 2020-11-08 11:53:01 DEBUG (MainThread) [greeclimate.network] Recived packet:
102 | {"t": "pack", "i": 0, "uid": 0, "cid": "f4911e7aca59", "tcid": "", "pack": {"t": "res", "mac": "f4911e7aca59", "r": 200, "opt": ["WdSpd"], "p": [0], "val": [0]}}
103 |
104 | 2020-11-08 11:53:25 DEBUG (MainThread) [greeclimate.device] Updating device properties for (Device: 1e7aca59 @ 192.168.1.29:7000 (mac: f4911e7aca59))
105 | 2020-11-08 11:53:26 DEBUG (MainThread) [greeclimate.network] Sending packet:
106 | {"cid": "app", "i": 0, "t": "pack", "uid": 0, "tcid": "f4911e7aca59", "pack": {"mac": "f4911e7aca59", "t": "status", "cols": ["Pow", "Mod", "SetTem", "TemUn", "TemRec", "WdSpd", "Air", "Blo", "Health", "SwhSlp", "Lig", "SwingLfRig", "SwUpDn", "Quiet", "Tur", "StHt", "SvSt", "HeatCoolType"]}}
107 | 2020-11-08 11:53:26 DEBUG (MainThread) [greeclimate.network] Recived packet:
108 | {"t": "pack", "i": 0, "uid": 0, "cid": "f4911e7aca59", "tcid": "", "pack": {"t": "dat", "mac": "f4911e7aca59", "r": 200, "cols": ["Pow", "Mod", "SetTem", "TemUn", "TemRec", "WdSpd", "Air", "Blo", "Health", "SwhSlp", "Lig", "SwingLfRig", "SwUpDn", "Quiet", "Tur", "StHt", "SvSt", "HeatCoolType"], "dat": [1, 4, 23, 0, 0, 0, 0, 0, 1, 0, 1, 0, 1, 0, 0, 0, 0, 0]}}
109 | 2020-11-08 11:53:26 DEBUG (MainThread) [homeassistant.components.gree.bridge] Finished fetching gree-1e7aca59 data in 0.023 seconds
110 |
--------------------------------------------------------------------------------
/tests/test_network.py:
--------------------------------------------------------------------------------
1 | import asyncio
2 | import json
3 | import socket
4 | from threading import Thread
5 | from unittest.mock import patch, MagicMock
6 |
7 | import pytest
8 |
9 | from greeclimate.deviceinfo import DeviceInfo
10 | from greeclimate.network import (
11 | BroadcastListenerProtocol,
12 | DeviceProtocolBase2,
13 | IPAddr,
14 | DeviceProtocol2, Commands, Response,
15 | )
16 | from .common import (
17 | DEFAULT_RESPONSE,
18 | DEFAULT_TIMEOUT,
19 | DISCOVERY_REQUEST,
20 | DISCOVERY_RESPONSE,
21 | Responder,
22 | DEFAULT_REQUEST, generate_response, FakeCipher,
23 | )
24 | from .test_device import get_mock_info
25 |
26 |
27 | class FakeDiscoveryProtocol(BroadcastListenerProtocol):
28 | """Fake discovery class."""
29 |
30 | def __init__(self):
31 | super().__init__(timeout=1, drained=None)
32 | self.packets = asyncio.Queue()
33 |
34 | def packet_received(self, obj, addr: IPAddr) -> None:
35 | self.packets.put_nowait(obj)
36 |
37 |
38 | class FakeDeviceProtocol(DeviceProtocol2):
39 | """Fake discovery class."""
40 |
41 | def __init__(self, drained: asyncio.Event = None):
42 | super().__init__(timeout=1, drained=drained)
43 | self.packets = asyncio.Queue()
44 | self.device_cipher = FakeCipher(b"1234567890123456")
45 |
46 | def packet_received(self, obj, addr: IPAddr) -> None:
47 | self.packets.put_nowait(obj)
48 |
49 |
50 | @pytest.mark.asyncio
51 | @pytest.mark.parametrize(
52 | "addr,family", [(("127.0.0.1", 7000), socket.AF_INET)]
53 | )
54 | async def test_close_connection(addr, family):
55 | """Test closing the connection."""
56 | # Run the listener portion now
57 | loop = asyncio.get_event_loop()
58 |
59 | bcast = (addr[0], 7000)
60 | local_addr = (addr[0], 0)
61 |
62 | with patch.object(DeviceProtocolBase2, "connection_lost") as mock:
63 | dp2 = FakeDiscoveryProtocol()
64 | await loop.create_datagram_endpoint(
65 | lambda: dp2,
66 | local_addr=local_addr,
67 | )
68 |
69 | # Send the scan command
70 | data = DISCOVERY_REQUEST
71 | await dp2.send(data, bcast)
72 | dp2.close()
73 |
74 | # Wait on the scan response
75 | with pytest.raises(asyncio.TimeoutError):
76 | task = asyncio.create_task(dp2.packets.get())
77 | await asyncio.wait_for(task, DEFAULT_TIMEOUT)
78 | (response, _) = task.result()
79 |
80 | assert not response
81 | assert len(response) == 0
82 |
83 | assert mock.call_count == 1
84 |
85 |
86 | @pytest.mark.asyncio
87 | async def test_set_get_key():
88 | """Test the encryption key property."""
89 | key = "faketestkey"
90 | dp2 = DeviceProtocolBase2()
91 | dp2.device_cipher = FakeCipher(key.encode())
92 | assert dp2.device_cipher.key == key
93 |
94 |
95 | @pytest.mark.asyncio
96 | @pytest.mark.parametrize("addr", [(("127.0.0.1", 7001))])
97 | async def test_connection_error(addr):
98 | """Test the encryption key property."""
99 | dp2 = DeviceProtocolBase2()
100 |
101 | loop = asyncio.get_event_loop()
102 | transport, _ = await loop.create_datagram_endpoint(
103 | lambda: dp2,
104 | local_addr=addr,
105 | )
106 |
107 | # Send the scan command
108 | data = DISCOVERY_REQUEST
109 | await dp2.send(data, (addr[0], 7000))
110 |
111 | with pytest.raises(RuntimeError):
112 | dp2.connection_lost(RuntimeError())
113 | assert transport.is_closing()
114 |
115 |
116 | @pytest.mark.asyncio
117 | @pytest.mark.parametrize("addr", [(("127.0.0.1", 7001))])
118 | async def test_pause_resume(addr):
119 | """Test the encryption key property."""
120 | event = asyncio.Event()
121 | dp2 = DeviceProtocolBase2(drained=event)
122 |
123 | loop = asyncio.get_event_loop()
124 | transport, _ = await loop.create_datagram_endpoint(
125 | lambda: dp2,
126 | local_addr=addr,
127 | )
128 |
129 | dp2.pause_writing()
130 | assert not event.is_set()
131 |
132 | dp2.resume_writing()
133 | assert event.is_set()
134 |
135 | dp2.close()
136 | assert transport.is_closing()
137 |
138 |
139 | @pytest.mark.asyncio
140 | @pytest.mark.parametrize(
141 | "addr,family", [(("127.0.0.1", 7000), socket.AF_INET)]
142 | )
143 | async def test_broadcast_recv(addr, family):
144 | """Create a socket broadcast responder, an async broadcast listener, test discovery responses."""
145 | with Responder(family, addr[1]) as sock:
146 |
147 | def responder(s):
148 | (d, addr) = s.recvfrom(2048)
149 | p = json.loads(d)
150 | assert p == DISCOVERY_REQUEST
151 |
152 | p = json.dumps(DISCOVERY_RESPONSE)
153 | s.sendto(p.encode(), addr)
154 |
155 | serv = Thread(target=responder, args=(sock,))
156 | serv.start()
157 |
158 | # Run the listener portion now
159 | loop = asyncio.get_event_loop()
160 |
161 | bcast = (addr[0], 7000)
162 | local_addr = (addr[0], 0)
163 |
164 | dp2 = FakeDiscoveryProtocol()
165 | dp2.device_cipher = FakeCipher(b"1234567890123456")
166 | await loop.create_datagram_endpoint(
167 | lambda: dp2,
168 | local_addr=local_addr,
169 | )
170 |
171 | # Send the scan command
172 | data = DISCOVERY_REQUEST
173 | await dp2.send(data, bcast)
174 |
175 | # Wait on the scan response
176 | task = asyncio.create_task(dp2.packets.get())
177 | await asyncio.wait_for(task, DEFAULT_TIMEOUT)
178 | response = task.result()
179 |
180 | assert response == DISCOVERY_RESPONSE
181 | serv.join(timeout=DEFAULT_TIMEOUT)
182 |
183 |
184 | @pytest.mark.asyncio
185 | @pytest.mark.parametrize(
186 | "addr,family",
187 | [
188 | (("127.0.0.1", 7000), socket.AF_INET),
189 | ],
190 | )
191 | async def test_broadcast_timeout(addr, family):
192 | """Create an async broadcast listener, test discovery responses."""
193 |
194 | # Run the listener portion now
195 | loop = asyncio.get_event_loop()
196 |
197 | bcast = (addr[0], 7000)
198 | local_addr = (addr[0], 0)
199 |
200 | dp2 = FakeDiscoveryProtocol()
201 | await loop.create_datagram_endpoint(
202 | lambda: dp2,
203 | local_addr=local_addr,
204 | )
205 |
206 | # Send the scan command
207 | await dp2.send(DISCOVERY_REQUEST, bcast)
208 |
209 | # Wait on the scan response
210 | task = asyncio.create_task(dp2.packets.get())
211 | with pytest.raises(asyncio.TimeoutError):
212 | await asyncio.wait_for(task, DEFAULT_TIMEOUT)
213 |
214 | with pytest.raises(asyncio.CancelledError):
215 | response = task.result()
216 | assert len(response) == 0
217 |
218 |
219 | @pytest.mark.asyncio
220 | @pytest.mark.parametrize("addr,family", [(("127.0.0.1", 7000), socket.AF_INET)])
221 | async def test_datagram_connect(addr, family):
222 | """Create a socket responder, an async connection, test send and recv."""
223 | with Responder(family, addr[1], bcast=False) as sock:
224 |
225 | def responder(s):
226 | (d, addr) = s.recvfrom(2048)
227 | p = json.dumps(DEFAULT_RESPONSE)
228 | s.sendto(p.encode(), addr)
229 |
230 | serv = Thread(target=responder, args=(sock,))
231 | serv.start()
232 |
233 | # Run the listener portion now
234 | loop = asyncio.get_event_loop()
235 | drained = asyncio.Event()
236 |
237 | remote_addr = (addr[0], 7000)
238 | transport, protocol = await loop.create_datagram_endpoint(
239 | lambda: FakeDeviceProtocol(drained=drained), remote_addr=remote_addr
240 | )
241 |
242 | # Send the scan command
243 | await protocol.send(DEFAULT_REQUEST, None, FakeCipher(b"1234567890123456"))
244 |
245 | # Wait on the scan response
246 | task = asyncio.create_task(protocol.packets.get())
247 | await asyncio.wait_for(task, DEFAULT_TIMEOUT)
248 | response = task.result()
249 |
250 | assert response == DEFAULT_RESPONSE
251 |
252 | sock.close()
253 | serv.join(timeout=DEFAULT_TIMEOUT)
254 |
255 |
256 | def test_bindok_handling():
257 | """Test the bindok response."""
258 | response = generate_response({"t": "bindok", "key": "fake-key"})
259 | protocol = DeviceProtocol2(timeout=DEFAULT_TIMEOUT)
260 | protocol.device_cipher = FakeCipher(b"1234567890123456")
261 |
262 | with patch.object(DeviceProtocol2, "handle_device_bound") as mock:
263 | protocol.datagram_received(json.dumps(response).encode(), ("0.0.0.0", 0))
264 | assert mock.call_count == 1
265 | assert mock.call_args[0][0] == "fake-key"
266 |
267 |
268 | def test_create_bind_message():
269 | # Arrange
270 | device_info = DeviceInfo(*get_mock_info())
271 | protocol = DeviceProtocol2()
272 |
273 | # Act
274 | result = protocol.create_bind_message(device_info)
275 |
276 | # Assert
277 | assert isinstance(result, dict)
278 | assert result == {
279 | 'cid': 'app',
280 | 'i': 1, # Default key encryption
281 | 't': 'pack',
282 | 'uid': 0,
283 | 'tcid': device_info.mac,
284 | 'pack': {
285 | 't': 'bind',
286 | 'mac': device_info.mac,
287 | 'uid': 0
288 | }
289 | }
290 |
291 |
292 | def test_create_status_message():
293 | # Arrange
294 | device_info = DeviceInfo(*get_mock_info())
295 | protocol = DeviceProtocol2()
296 |
297 | # Act
298 | result = protocol.create_status_message(device_info, 'test')
299 |
300 | # Assert
301 | assert isinstance(result, dict)
302 | assert result == {
303 | 'cid': 'app',
304 | 'i': 0, # Device key encryption
305 | 't': 'pack',
306 | 'uid': 0,
307 | 'tcid': device_info.mac,
308 | 'pack': {
309 | 't': 'status',
310 | 'mac': device_info.mac,
311 | 'cols': ['test'],
312 | }
313 | }
314 |
315 | def test_create_command_message():
316 | # Arrange
317 | device_info = DeviceInfo(*get_mock_info())
318 | protocol = DeviceProtocol2()
319 |
320 | # Act
321 | result = protocol.create_command_message(device_info, **{'key': 'value'})
322 |
323 | # Assert
324 | assert isinstance(result, dict)
325 | assert result == {
326 | 'cid': 'app',
327 | 'i': 0, # Device key encryption
328 | 't': 'pack',
329 | 'uid': 0,
330 | 'tcid': device_info.mac,
331 | 'pack': {
332 | 't': 'cmd',
333 | 'mac': device_info.mac,
334 | 'opt': ['key'],
335 | 'p': ['value'],
336 | }
337 | }
338 |
339 |
340 | class DeviceProtocol2Test(DeviceProtocol2):
341 | def __init__(self):
342 | super().__init__(timeout=DEFAULT_TIMEOUT)
343 | self.state = {}
344 | self.key = None
345 | self.unknown = False
346 |
347 | def handle_state_update(self, **kwargs) -> None:
348 | self.state = dict(kwargs)
349 |
350 | def handle_device_bound(self, key: str) -> None:
351 | self._ready.set()
352 | self.key = key
353 |
354 | def handle_unknown_packet(self, obj, addr: IPAddr) -> None:
355 | self.unknown = True
356 |
357 |
358 | def test_handle_state_update():
359 |
360 | # Arrange
361 | protocol = DeviceProtocol2Test()
362 | state = {'key': 'value'}
363 |
364 | # Act
365 | protocol.packet_received({
366 | 'pack': {
367 | 't': 'dat',
368 | 'cols': list(state.keys()),
369 | 'dat': list(state.values())
370 | }
371 | }, ("0.0.0.0", 0))
372 |
373 | # Assert
374 | assert protocol.state == state
375 | assert protocol.state == {'key': 'value'}
376 |
377 |
378 | def test_handle_result_update():
379 |
380 | # Arrange
381 | protocol = DeviceProtocol2Test()
382 | state = {'key': 'value'}
383 |
384 | # Act
385 | protocol.packet_received({
386 | 'pack': {
387 | 't': 'res',
388 | 'opt': list(state.keys()),
389 | 'val': list(state.values())
390 | }
391 | }, ("0.0.0.0", 0))
392 |
393 | # Assert
394 | assert protocol.state == state
395 | assert protocol.state == {'key': 'value'}
396 |
397 |
398 | def test_handle_device_bound():
399 | # Arrange
400 | protocol = DeviceProtocol2Test()
401 |
402 | # Act
403 | protocol.packet_received({
404 | 'pack': {
405 | 't': 'bindok',
406 | 'key': 'fake-key'
407 | }
408 | }, ("0.0.0.0", 0))
409 |
410 | # Assert
411 | assert protocol._ready.is_set()
412 | assert protocol.key == "fake-key"
413 |
414 |
415 | def test_handle_unknown_packet():
416 | # Arrange
417 | protocol = DeviceProtocol2Test()
418 |
419 | # Act
420 | protocol.packet_received({
421 | 'pack': {
422 | 't': 'unknown'
423 | }
424 | }, ("0.0.0.0", 0))
425 |
426 | # Assert
427 | assert protocol.unknown is True
428 |
429 |
430 | @pytest.mark.parametrize("use_default_key,command,data",
431 | [(1, Commands.BIND, {"uid": 0}),
432 | (1, Commands.SCAN, None),
433 | (0, Commands.STATUS, {'cols': ['test']}),
434 | (0, Commands.CMD, {'opt': ['key'], 'p': ['value']})])
435 | def test_generate_payload(use_default_key, command, data):
436 | # Arrange
437 | device_info = DeviceInfo(*get_mock_info())
438 | protocol = DeviceProtocol2()
439 |
440 | # Act
441 | result = protocol._generate_payload(command, device_info, data)
442 |
443 | # Assert
444 | expected = {
445 | 'cid': 'app',
446 | 'i': use_default_key, # Device key encryption
447 | 't': Commands.PACK.value if data is not None else command.value,
448 | 'uid': 0,
449 | 'tcid': device_info.mac,
450 | }
451 | if data:
452 | expected['pack'] = {'t': command.value, 'mac': device_info.mac}
453 | expected['pack'].update(data)
454 |
455 | assert isinstance(result, dict)
456 | assert result == expected
457 |
458 |
459 | @pytest.mark.asyncio
460 | @pytest.mark.parametrize("event_name, data",[
461 | (Response.BIND_OK, {'key': 'fake-key'}),
462 | (Response.DATA, {'cols': ['test'], 'dat': ['value']}),
463 | (Response.RESULT, {'opt': ['key'], 'val': ['value']})
464 | ])
465 | async def test_add_and_remove_handler(event_name, data):
466 | # Arrange
467 | protocol = DeviceProtocol2()
468 | callback = MagicMock()
469 | event_data = {'pack': {'t': event_name.value}}
470 | event_data['pack'].update(data)
471 |
472 | # Act
473 | protocol.add_handler(event_name, callback)
474 |
475 | # Assert that the handler was added
476 | assert event_name in protocol._handlers
477 | assert callback in protocol._handlers[event_name]
478 |
479 | # Trigger the event
480 | protocol.packet_received(event_data, ("0.0.0.0", 0))
481 |
482 | # Check that the callback was called
483 | callback.assert_called_once()
484 |
485 | # Now remove the handler
486 | protocol.remove_handler(event_name, callback)
487 |
488 | # Assert that the handler was removed
489 | assert callback not in protocol._handlers[event_name]
490 |
491 | # Reset the callback
492 | callback.reset_mock()
493 |
494 | # Trigger the event again
495 | protocol.packet_received(event_data, ("0.0.0.0", 0))
496 |
497 | # Check that the callback was not called this time
498 | callback.assert_not_called()
499 |
500 |
501 | def test_packet_received_not_implemented():
502 | # Arrange
503 | protocol = DeviceProtocolBase2()
504 |
505 | # Act
506 | with pytest.raises(NotImplementedError):
507 | protocol.packet_received({}, ("0.0.0.0", 0))
508 |
509 |
510 | def test_packet_received_invalid_data():
511 | # Arrange
512 | protocol = DeviceProtocol2()
513 |
514 | # Act
515 | protocol.packet_received(None, ("0.0.0.0", 0))
516 | protocol.packet_received({}, ("0.0.0.0", 0))
517 | protocol.packet_received({"pack"}, ("0.0.0.0", 0))
518 |
519 | with patch.object(protocol, "handle_unknown_packet") as mock:
520 | protocol.packet_received({"pack": {"t": "unknown"}}, ("0.0.0.0", 0))
521 | mock.assert_called_once()
522 |
523 |
524 | def test_set_get_cipher():
525 | # Arrange
526 | protocol = DeviceProtocolBase2()
527 | cipher = FakeCipher(b"1234567890123456")
528 |
529 | # Act
530 | protocol.device_cipher = cipher
531 |
532 | # Assert
533 | assert protocol.device_cipher == cipher
534 |
535 |
536 | def test_cipher_is_not_set():
537 | # Arrange
538 | protocol = DeviceProtocolBase2()
539 |
540 | # Act
541 | key = None
542 | with pytest.raises(ValueError):
543 | key = protocol.device_key
544 |
545 | assert key is None
546 |
547 | with pytest.raises(ValueError):
548 | protocol.device_key = "fake-key"
549 |
550 |
551 | def test_add_invalid_handler():
552 | # Arrange
553 | protocol = DeviceProtocol2()
554 | callback = MagicMock()
555 |
556 | # Act
557 | with pytest.raises(ValueError):
558 | protocol.add_handler(Response("invalid"), callback)
559 |
560 | with pytest.raises(ValueError):
561 | protocol.add_handler(Response("invalid"), callback)
562 |
563 |
564 | def test_device_key_get_set():
565 | # Arrange
566 | protocol = DeviceProtocolBase2
567 | key = "fake-key"
568 |
569 | # Act
570 | protocol.device_key = key
571 |
572 | # Assert
573 | assert protocol.device_key == key
574 |
--------------------------------------------------------------------------------
/greeclimate/device.py:
--------------------------------------------------------------------------------
1 | import asyncio
2 | import enum
3 | import logging
4 | import re
5 | from asyncio import AbstractEventLoop
6 | from enum import IntEnum, unique
7 | from typing import Union
8 |
9 | from greeclimate.cipher import CipherV1, CipherV2
10 | from greeclimate.deviceinfo import DeviceInfo
11 | from greeclimate.exceptions import DeviceNotBoundError, DeviceTimeoutError
12 | from greeclimate.network import DeviceProtocol2
13 | from greeclimate.taskable import Taskable
14 |
15 |
16 | class Props(enum.Enum):
17 | POWER = "Pow"
18 | MODE = "Mod"
19 |
20 | # Dehumidifier fields
21 | HUM_SET = "Dwet"
22 | HUM_SENSOR = "DwatSen"
23 | CLEAN_FILTER = "Dfltr"
24 | WATER_FULL = "DwatFul"
25 | DEHUMIDIFIER_MODE = "Dmod"
26 |
27 | TEMP_SET = "SetTem"
28 | TEMP_SENSOR = "TemSen"
29 | TEMP_UNIT = "TemUn"
30 | TEMP_BIT = "TemRec"
31 | FAN_SPEED = "WdSpd"
32 | FRESH_AIR = "Air"
33 | XFAN = "Blo"
34 | ANION = "Health"
35 | SLEEP = "SwhSlp"
36 | SLEEP_MODE = "SlpMod"
37 | LIGHT = "Lig"
38 | SWING_HORIZ = "SwingLfRig"
39 | SWING_VERT = "SwUpDn"
40 | QUIET = "Quiet"
41 | TURBO = "Tur"
42 | STEADY_HEAT = "StHt"
43 | POWER_SAVE = "SvSt"
44 | UNKNOWN_HEATCOOLTYPE = "HeatCoolType"
45 |
46 |
47 | @unique
48 | class TemperatureUnits(IntEnum):
49 | C = 0
50 | F = 1
51 |
52 |
53 | @unique
54 | class Mode(IntEnum):
55 | Auto = 0
56 | Cool = 1
57 | Dry = 2
58 | Fan = 3
59 | Heat = 4
60 |
61 |
62 | @unique
63 | class FanSpeed(IntEnum):
64 | Auto = 0
65 | Low = 1
66 | MediumLow = 2
67 | Medium = 3
68 | MediumHigh = 4
69 | High = 5
70 |
71 |
72 | @unique
73 | class HorizontalSwing(IntEnum):
74 | Default = 0
75 | FullSwing = 1
76 | Left = 2
77 | LeftCenter = 3
78 | Center = 4
79 | RightCenter = 5
80 | Right = 6
81 |
82 |
83 | @unique
84 | class VerticalSwing(IntEnum):
85 | Default = 0
86 | FullSwing = 1
87 | FixedUpper = 2
88 | FixedUpperMiddle = 3
89 | FixedMiddle = 4
90 | FixedLowerMiddle = 5
91 | FixedLower = 6
92 | SwingUpper = 7
93 | SwingUpperMiddle = 8
94 | SwingMiddle = 9
95 | SwingLowerMiddle = 10
96 | SwingLower = 11
97 |
98 |
99 | class DehumidifierMode(IntEnum):
100 | Default = 0
101 | AnionOnly = 9
102 |
103 |
104 | def generate_temperature_record(temp_f):
105 | temSet = round((temp_f - 32.0) * 5.0 / 9.0)
106 | temRec = (int)((((temp_f - 32.0) * 5.0 / 9.0) - temSet) > 0)
107 | return {"f": temp_f, "temSet": temSet, "temRec": temRec}
108 |
109 |
110 | TEMP_MIN = 8
111 | TEMP_MAX = 30
112 | TEMP_OFFSET = 40
113 | TEMP_MIN_F = 46
114 | TEMP_MAX_F = 86
115 | TEMP_MIN_TABLE = -60
116 | TEMP_MAX_TABLE = 60
117 | TEMP_MIN_TABLE_F = -76
118 | TEMP_MAX_TABLE_F = 140
119 | TEMP_TABLE = [generate_temperature_record(x) for x in range(TEMP_MIN_TABLE_F, TEMP_MAX_TABLE_F + 1)]
120 | HUMIDITY_MIN = 30
121 | HUMIDITY_MAX = 80
122 |
123 |
124 | class Device(DeviceProtocol2, Taskable):
125 | """Class representing a physical device, it's state and properties.
126 |
127 | Devices must be bound, either by discovering their presence, or supplying a persistent
128 | device key which is then used for communication (and encryption) with the unit. See the
129 | `bind` function for more details on how to do this.
130 |
131 | Once a device is bound occasionally call `update_state` to request and update state from
132 | the HVAC, as it is possible that it changes state from other sources.
133 |
134 | Attributes:
135 | power: A boolean indicating if the unit is on or off
136 | mode: An int indicating operating mode, see `Mode` enum for possible values
137 | target_temperature: The target temperature, ignore if in Auto, Fan or Steady Heat mode
138 | temperature_units: An int indicating unit of measurement, see `TemperatureUnits` enum for possible values
139 | current_temperature: The current temperature
140 | fan_speed: An int indicating fan speed, see `FanSpeed` enum for possible values
141 | fresh_air: A boolean indicating if fresh air valve is open, if present
142 | xfan: A boolean to enable the fan to dry the coil, only used for cool and dry modes
143 | anion: A boolean to enable the ozone generator, if present
144 | sleep: A boolean to enable sleep mode, which adjusts temperature over time
145 | light: A boolean to enable the light on the unit, if present
146 | horizontal_swing: An int to control the horizontal blade position, see `HorizontalSwing` enum for possible values
147 | vertical_swing: An int to control the vertical blade position, see `VerticalSwing` enum for possible values
148 | quiet: A boolean to enable quiet operation
149 | turbo: A boolean to enable turbo operation (heat or cool faster initially)
150 | steady_heat: When enabled unit will maintain a target temperature of 8 degrees C
151 | power_save: A boolen to enable power save operation
152 | target_humidity: An int to set the target relative humidity
153 | current_humidity: The current relative humidity
154 | clean_filter: A bool to indicate the filter needs cleaning
155 | water_full: A bool to indicate the water tank is full
156 | """
157 |
158 | def __init__(self, device_info: DeviceInfo, timeout: int = 120, bind_timeout: int = 10, loop: AbstractEventLoop = None):
159 | """Initialize the device object
160 |
161 | Args:
162 | device_info (DeviceInfo): Information about the physical device
163 | timeout (int): Timeout for device communication
164 | bind_timeout (int): Timeout for binding to the device, keep this short to prevent delays determining the
165 | correct device cipher to use
166 | loop (AbstractEventLoop): The event loop to run the device operations on
167 | """
168 | DeviceProtocol2.__init__(self, timeout)
169 | Taskable.__init__(self, loop)
170 | self._logger = logging.getLogger(__name__)
171 | self.device_info: DeviceInfo = device_info
172 |
173 | self._bind_timeout = bind_timeout
174 |
175 | """ Device properties """
176 | self.hid = None
177 | self.version = None
178 | self.check_version = True
179 | self._properties = {}
180 | self._dirty = []
181 |
182 | async def bind(
183 | self,
184 | key: str = None,
185 | cipher: Union[CipherV1, CipherV2, None] = None,
186 | ):
187 | """Run the binding procedure.
188 |
189 | Binding is a finicky procedure, and happens in 1 of 2 ways:
190 | 1 - Without the key, binding must pass the device info structure immediately following
191 | the search devices procedure. There is only a small window to complete registration.
192 | 2 - With a key, binding is implicit and no further action is required
193 |
194 | Both approaches result in a device_key which is used as like a persistent session id.
195 |
196 | Args:
197 | cipher (CipherV1 | CipherV2): The cipher type to use for encryption, if None will attempt to detect the correct one
198 | key (str): The device key, when provided binding is a NOOP, if None binding will
199 | attempt to negotiate the key with the device. cipher must be provided.
200 |
201 | Raises:
202 | DeviceNotBoundError: If binding was unsuccessful and no key returned
203 | DeviceTimeoutError: The device didn't respond
204 | """
205 |
206 | if key:
207 | if not cipher:
208 | raise ValueError("cipher must be provided when key is provided")
209 | else:
210 | cipher.key = key
211 | self.device_cipher = cipher
212 | return
213 |
214 | if not self.device_info:
215 | raise DeviceNotBoundError
216 |
217 | if self._transport is None:
218 | self._transport, _ = await self._loop.create_datagram_endpoint(
219 | lambda: self, remote_addr=(self.device_info.ip, self.device_info.port)
220 | )
221 |
222 | self._logger.info("Starting device binding to %s", str(self.device_info))
223 |
224 | try:
225 | if cipher is not None:
226 | await self.__bind_internal(cipher)
227 | else:
228 | """ Try binding with CipherV1 first, if that fails try CipherV2"""
229 | try:
230 | self._logger.info("Attempting to bind to device using CipherV1")
231 | await self.__bind_internal(CipherV1())
232 | except asyncio.TimeoutError:
233 | self._logger.info("Attempting to bind to device using CipherV2")
234 | await self.__bind_internal(CipherV2())
235 |
236 | except asyncio.TimeoutError:
237 | raise DeviceTimeoutError
238 |
239 | if not self.device_cipher:
240 | raise DeviceNotBoundError
241 | else:
242 | self._logger.info("Bound to device using key %s", self.device_cipher.key)
243 |
244 | async def __bind_internal(self, cipher: Union[CipherV1, CipherV2]):
245 | """Internal binding procedure, do not call directly"""
246 | await self.send(self.create_bind_message(self.device_info), cipher=cipher)
247 | task = asyncio.create_task(self.ready.wait())
248 | await asyncio.wait_for(task, timeout=self._bind_timeout)
249 |
250 | def handle_device_bound(self, key: str) -> None:
251 | """Handle the device bound message from the device"""
252 | self.device_cipher.key = key
253 |
254 | async def request_version(self) -> None:
255 | """Request the firmware version from the device."""
256 | if not self.device_cipher:
257 | await self.bind()
258 |
259 | try:
260 | await self.send(self.create_status_message(self.device_info, "hid"))
261 |
262 | except asyncio.TimeoutError:
263 | raise DeviceTimeoutError
264 |
265 | async def update_state(self, wait_for: float = 30):
266 | """Update the internal state of the device structure of the physical device, 0 for no wait
267 |
268 | Args:
269 | wait_for (object): How long to wait for an update from the device
270 | """
271 | if not self.device_cipher:
272 | await self.bind()
273 |
274 | self._logger.debug("Updating device properties for (%s)", str(self.device_info))
275 |
276 | props = [x.value for x in Props]
277 | if not self.hid:
278 | props.append("hid")
279 |
280 | try:
281 | await self.send(self.create_status_message(self.device_info, *props))
282 |
283 | except asyncio.TimeoutError:
284 | raise DeviceTimeoutError
285 |
286 | def handle_state_update(self, **kwargs) -> None:
287 | """Handle incoming information about the firmware version of the device"""
288 |
289 | # Ex: hid = 362001000762+U-CS532AE(LT)V3.31.bin
290 | if "hid" in kwargs:
291 | self.hid = kwargs.pop("hid")
292 | match = re.search(r"(?<=V)([\d.]+)\.bin$", self.hid)
293 | self.version = match and match.group(1)
294 | self._logger.info(f"Device version is {self.version}, hid {self.hid}")
295 |
296 | self._properties.update(kwargs)
297 |
298 | if self.check_version and Props.TEMP_SENSOR.value in kwargs:
299 | self.check_version = False
300 | temp = self.get_property(Props.TEMP_SENSOR)
301 | self._logger.debug(f"Checking for temperature offset, reported temp {temp}")
302 | if temp and temp < TEMP_OFFSET:
303 | self.version = "4.0"
304 | self._logger.info(f"Device version changed to {self.version}, hid {self.hid}")
305 | self._logger.debug(f"Using device temperature {self.current_temperature}")
306 |
307 | async def push_state_update(self, wait_for: float = 30):
308 | """Push any pending state updates to the unit
309 |
310 | Args:
311 | wait_for (object): How long to wait for an update from the device, 0 for no wait
312 | """
313 | if not self._dirty:
314 | return
315 |
316 | if not self.device_cipher:
317 | await self.bind()
318 |
319 | self._logger.debug("Pushing state updates to (%s)", str(self.device_info))
320 |
321 | props = {}
322 | for name in self._dirty:
323 | value = self._properties.get(name)
324 | self._logger.debug("Sending remote state update %s -> %s", name, value)
325 | props[name] = value
326 | if name == Props.TEMP_SET.value:
327 | props[Props.TEMP_BIT.value] = self._properties.get(Props.TEMP_BIT.value)
328 | props[Props.TEMP_UNIT.value] = self._properties.get(
329 | Props.TEMP_UNIT.value
330 | )
331 |
332 | self._dirty.clear()
333 |
334 | try:
335 | await self.send(self.create_command_message(self.device_info, **props))
336 |
337 | except asyncio.TimeoutError:
338 | raise DeviceTimeoutError
339 |
340 | def __eq__(self, other):
341 | """Compare two devices for equality based on their properties state and device info."""
342 | return self.device_info == other.device_info \
343 | and self.raw_properties == other.raw_properties \
344 | and self.device_cipher.key == other.device_cipher.key
345 |
346 | def __ne__(self, other):
347 | return not self.__eq__(other)
348 |
349 | @property
350 | def raw_properties(self) -> dict:
351 | return self._properties
352 |
353 | def get_property(self, name):
354 | """Generic lookup of properties tracked from the physical device"""
355 | if self._properties:
356 | return self._properties.get(name.value)
357 | return None
358 |
359 | def set_property(self, name, value):
360 | """Generic setting of properties for the physical device"""
361 | if not self._properties:
362 | self._properties = {}
363 |
364 | if self._properties.get(name.value) == value:
365 | return
366 | else:
367 | self._properties[name.value] = value
368 | if name.value not in self._dirty:
369 | self._dirty.append(name.value)
370 |
371 | @property
372 | def power(self) -> bool:
373 | return bool(self.get_property(Props.POWER))
374 |
375 | @power.setter
376 | def power(self, value: int):
377 | self.set_property(Props.POWER, int(value))
378 |
379 | @property
380 | def mode(self) -> int:
381 | return self.get_property(Props.MODE)
382 |
383 | @mode.setter
384 | def mode(self, value: int):
385 | self.set_property(Props.MODE, int(value))
386 |
387 | def _convert_to_units(self, value, bit):
388 | if self.temperature_units != TemperatureUnits.F.value:
389 | return value
390 |
391 | if value < TEMP_MIN_TABLE or value > TEMP_MAX_TABLE:
392 | raise ValueError(f"Specified temperature {value} is out of range.")
393 |
394 | matching_temset = [t for t in TEMP_TABLE if t["temSet"] == value]
395 |
396 | try:
397 | f = next(t for t in matching_temset if t["temRec"] == bit)
398 | except StopIteration:
399 | f = matching_temset[0]
400 |
401 | return f["f"]
402 |
403 | @property
404 | def target_temperature(self) -> int:
405 | temset = self.get_property(Props.TEMP_SET)
406 | temrec = self.get_property(Props.TEMP_BIT)
407 | return self._convert_to_units(temset, temrec)
408 |
409 | @target_temperature.setter
410 | def target_temperature(self, value: int):
411 | def validate(val):
412 | if val > TEMP_MAX or val < TEMP_MIN:
413 | raise ValueError(f"Specified temperature {val} is out of range.")
414 |
415 | if self.temperature_units == 1:
416 | rec = generate_temperature_record(value)
417 | validate(rec["temSet"])
418 | self.set_property(Props.TEMP_SET, rec["temSet"])
419 | self.set_property(Props.TEMP_BIT, rec["temRec"])
420 | else:
421 | validate(value)
422 | self.set_property(Props.TEMP_SET, int(value))
423 |
424 | @property
425 | def temperature_units(self) -> int:
426 | return self.get_property(Props.TEMP_UNIT)
427 |
428 | @temperature_units.setter
429 | def temperature_units(self, value: int):
430 | self.set_property(Props.TEMP_UNIT, int(value))
431 |
432 | @property
433 | def current_temperature(self) -> int:
434 | prop = self.get_property(Props.TEMP_SENSOR)
435 | bit = self.get_property(Props.TEMP_BIT)
436 | if prop is not None:
437 | v = self.version and int(self.version.split(".")[0])
438 | try:
439 | if v == 4:
440 | return self._convert_to_units(prop, bit)
441 | elif prop != 0:
442 | return self._convert_to_units(prop - TEMP_OFFSET, bit)
443 | except ValueError:
444 | logging.warning("Converting unexpected set temperature value %s", prop)
445 |
446 | return self.target_temperature
447 |
448 | @property
449 | def fan_speed(self) -> int:
450 | return self.get_property(Props.FAN_SPEED)
451 |
452 | @fan_speed.setter
453 | def fan_speed(self, value: int):
454 | self.set_property(Props.FAN_SPEED, int(value))
455 |
456 | @property
457 | def fresh_air(self) -> bool:
458 | return bool(self.get_property(Props.FRESH_AIR))
459 |
460 | @fresh_air.setter
461 | def fresh_air(self, value: bool):
462 | self.set_property(Props.FRESH_AIR, int(value))
463 |
464 | @property
465 | def xfan(self) -> bool:
466 | return bool(self.get_property(Props.XFAN))
467 |
468 | @xfan.setter
469 | def xfan(self, value: bool):
470 | self.set_property(Props.XFAN, int(value))
471 |
472 | @property
473 | def anion(self) -> bool:
474 | return bool(self.get_property(Props.ANION))
475 |
476 | @anion.setter
477 | def anion(self, value: bool):
478 | self.set_property(Props.ANION, int(value))
479 |
480 | @property
481 | def sleep(self) -> bool:
482 | return bool(self.get_property(Props.SLEEP))
483 |
484 | @sleep.setter
485 | def sleep(self, value: bool):
486 | self.set_property(Props.SLEEP, int(value))
487 | self.set_property(Props.SLEEP_MODE, int(value))
488 |
489 | @property
490 | def light(self) -> bool:
491 | return bool(self.get_property(Props.LIGHT))
492 |
493 | @light.setter
494 | def light(self, value: bool):
495 | self.set_property(Props.LIGHT, int(value))
496 |
497 | @property
498 | def horizontal_swing(self) -> int:
499 | return self.get_property(Props.SWING_HORIZ)
500 |
501 | @horizontal_swing.setter
502 | def horizontal_swing(self, value: int):
503 | self.set_property(Props.SWING_HORIZ, int(value))
504 |
505 | @property
506 | def vertical_swing(self) -> int:
507 | return self.get_property(Props.SWING_VERT)
508 |
509 | @vertical_swing.setter
510 | def vertical_swing(self, value: int):
511 | self.set_property(Props.SWING_VERT, int(value))
512 |
513 | @property
514 | def quiet(self) -> bool:
515 | return self.get_property(Props.QUIET)
516 |
517 | @quiet.setter
518 | def quiet(self, value: bool):
519 | self.set_property(Props.QUIET, 2 if value else 0)
520 |
521 | @property
522 | def turbo(self) -> bool:
523 | return bool(self.get_property(Props.TURBO))
524 |
525 | @turbo.setter
526 | def turbo(self, value: bool):
527 | self.set_property(Props.TURBO, int(value))
528 |
529 | @property
530 | def steady_heat(self) -> bool:
531 | return bool(self.get_property(Props.STEADY_HEAT))
532 |
533 | @steady_heat.setter
534 | def steady_heat(self, value: bool):
535 | self.set_property(Props.STEADY_HEAT, int(value))
536 |
537 | @property
538 | def power_save(self) -> bool:
539 | return bool(self.get_property(Props.POWER_SAVE))
540 |
541 | @power_save.setter
542 | def power_save(self, value: bool):
543 | self.set_property(Props.POWER_SAVE, int(value))
544 |
545 | @property
546 | def target_humidity(self) -> int:
547 | 15 + (self.get_property(Props.HUM_SET) * 5)
548 |
549 | @target_humidity.setter
550 | def target_humidity(self, value: int):
551 | def validate(val):
552 | if value > HUMIDITY_MAX or val < HUMIDITY_MIN:
553 | raise ValueError(f"Specified temperature {val} is out of range.")
554 |
555 | self.set_property(Props.HUM_SET, (value - 15) // 5)
556 |
557 | @property
558 | def dehumidifier_mode(self):
559 | return self.get_property(Props.DEHUMIDIFIER_MODE)
560 |
561 | @property
562 | def current_humidity(self) -> int:
563 | return self.get_property(Props.HUM_SENSOR)
564 |
565 | @property
566 | def clean_filter(self) -> bool:
567 | return bool(self.get_property(Props.CLEAN_FILTER))
568 |
569 | @property
570 | def water_full(self) -> bool:
571 | return bool(self.get_property(Props.WATER_FULL))
572 |
--------------------------------------------------------------------------------
/tests/test_device.py:
--------------------------------------------------------------------------------
1 | import asyncio
2 | import enum
3 |
4 | import pytest
5 |
6 | from greeclimate.cipher import CipherV1
7 | from greeclimate.device import Device, DeviceInfo, Props, TemperatureUnits
8 | from greeclimate.exceptions import DeviceNotBoundError, DeviceTimeoutError
9 |
10 |
11 | class FakeProps(enum.Enum):
12 | FAKE = "fake"
13 |
14 |
15 | def get_mock_info():
16 | return (
17 | "1.1.1.0",
18 | "7000",
19 | "aabbcc001122",
20 | "MockDevice1",
21 | "MockBrand",
22 | "MockModel",
23 | "0.0.1-fake",
24 | )
25 |
26 |
27 | def get_mock_state():
28 | return {
29 | "Pow": 1,
30 | "Mod": 3,
31 | "SetTem": 25,
32 | "TemSen": 29,
33 | "TemUn": 0,
34 | "WdSpd": 0,
35 | "Air": 0,
36 | "Blo": 0,
37 | "Health": 0,
38 | "SwhSlp": 0,
39 | "SlpMod": 0,
40 | "Lig": 1,
41 | "SwingLfRig": 1,
42 | "SwUpDn": 1,
43 | "Quiet": 0,
44 | "Tur": 0,
45 | "StHt": 0,
46 | "SvSt": 0,
47 | "TemRec": 0,
48 | "HeatCoolType": 0,
49 | "hid": "362001000762+U-CS532AE(LT)V3.31.bin",
50 | "Dmod": 0,
51 | "Dwet": 5,
52 | "DwatSen": 58,
53 | "Dfltr": 0,
54 | "DwatFul": 0,
55 | }
56 |
57 |
58 | def get_mock_state_off():
59 | return {
60 | "Pow": 0,
61 | "Mod": 0,
62 | "SetTem": 0,
63 | "TemSen": 0,
64 | "TemUn": 0,
65 | "WdSpd": 0,
66 | "Air": 0,
67 | "Blo": 0,
68 | "Health": 0,
69 | "SwhSlp": 0,
70 | "SlpMod": 0,
71 | "Lig": 0,
72 | "SwingLfRig": 0,
73 | "SwUpDn": 0,
74 | "Quiet": 0,
75 | "Tur": 0,
76 | "StHt": 0,
77 | "SvSt": 0,
78 | "TemRec": 0,
79 | "HeatCoolType": 0,
80 | "Dmod": 0,
81 | "Dwet": 0,
82 | "DwatSen": 0,
83 | "Dfltr": 0,
84 | "DwatFul": 0,
85 | }
86 |
87 |
88 | def get_mock_state_on():
89 | return {
90 | "Pow": 1,
91 | "Mod": 1,
92 | "SetTem": 1,
93 | "TemSen": 1,
94 | "TemUn": 1,
95 | "WdSpd": 1,
96 | "Air": 1,
97 | "Blo": 1,
98 | "Health": 1,
99 | "SwhSlp": 1,
100 | "SlpMod": 1,
101 | "Lig": 1,
102 | "SwingLfRig": 1,
103 | "SwUpDn": 1,
104 | "Quiet": 2,
105 | "Tur": 1,
106 | "StHt": 1,
107 | "SvSt": 1,
108 | "TemRec": 0,
109 | "HeatCoolType": 0,
110 | "Dmod": 0,
111 | "Dwet": 3,
112 | "DwatSen": 1,
113 | "Dfltr": 0,
114 | "DwatFul": 0,
115 | }
116 |
117 |
118 | def get_mock_state_no_temperature():
119 | return {
120 | "Pow": 1,
121 | "Mod": 3,
122 | "SetTem": 25,
123 | "TemUn": 0,
124 | "WdSpd": 0,
125 | "Air": 0,
126 | "Blo": 0,
127 | "Health": 0,
128 | "SwhSlp": 0,
129 | "SlpMod": 0,
130 | "Lig": 1,
131 | "SwingLfRig": 1,
132 | "SwUpDn": 1,
133 | "Quiet": 0,
134 | "Tur": 0,
135 | "StHt": 0,
136 | "SvSt": 0,
137 | "TemRec": 0,
138 | "HeatCoolType": 0,
139 | "Dmod": 0,
140 | "Dwet": 1,
141 | "DwatSen": 1,
142 | "Dfltr": 0,
143 | "DwatFul": 0,
144 | }
145 |
146 |
147 | def get_mock_state_bad_temp():
148 | return {"TemSen": 69, "hid": "362001060297+U-CS532AF(MTK).bin"}
149 |
150 |
151 | def get_mock_state_0c_v4_temp():
152 | return {"TemSen": 0, "hid": "362001000762+U-CS532AE(LT)V4.bin"}
153 |
154 |
155 | def get_mock_state_0c_v3_temp():
156 | return {"TemSen": 0, "hid": "362001000762+U-CS532AE(LT)V3.31.bin"}
157 |
158 |
159 | async def generate_device_mock_async():
160 | d = Device(DeviceInfo("1.1.1.1", 7000, "f4911e7aca59", "1e7aca59"))
161 | await d.bind(key="St8Vw1Yz4Bc7Ef0H", cipher=CipherV1())
162 | return d
163 |
164 |
165 | def test_device_info_equality(send):
166 | """The only way to get the key through binding is by scanning first"""
167 |
168 | props = [
169 | "1.1.1.0",
170 | "7000",
171 | "aabbcc001122",
172 | "MockDevice1",
173 | "MockBrand",
174 | "MockModel",
175 | "0.0.1-fake",
176 | ]
177 |
178 | # When all properties match the device info is the same
179 | assert DeviceInfo(*props) == DeviceInfo(*props)
180 |
181 | # When any property differs the device info is not the same
182 | for i in range(2, len(props)):
183 | new_props = props.copy()
184 | new_props[i] = "modified_prop"
185 | assert DeviceInfo(*new_props) != DeviceInfo(*props)
186 |
187 |
188 | @pytest.mark.asyncio
189 | async def test_get_device_info(cipher, send):
190 | """Initialize device, check properties."""
191 |
192 | info = DeviceInfo(*get_mock_info())
193 | device = Device(info)
194 |
195 | assert device.device_info == info
196 |
197 | fake_key = "abcdefgh12345678"
198 | await device.bind(key=fake_key, cipher=CipherV1())
199 |
200 | assert device.device_cipher is not None
201 | assert device.device_cipher.key == fake_key
202 |
203 |
204 | @pytest.mark.asyncio
205 | async def test_device_bind(cipher, send):
206 | """Check that the device returns a device key when binding."""
207 |
208 | info = DeviceInfo(*get_mock_info())
209 | device = Device(info, timeout=1)
210 | fake_key = "abcdefgh12345678"
211 |
212 | def fake_send(*args, **kwargs):
213 | """Emulate a bind event"""
214 | device.device_cipher = CipherV1(fake_key.encode())
215 | device.ready.set()
216 | device.handle_device_bound(fake_key)
217 | send.side_effect = fake_send
218 |
219 | assert device.device_info == info
220 | await device.bind()
221 | assert send.call_count == 1
222 |
223 | assert device.device_cipher is not None
224 | assert device.device_cipher.key == fake_key
225 |
226 | # Bind with cipher already set
227 | await device.bind()
228 | assert send.call_count == 2
229 |
230 |
231 | @pytest.mark.asyncio
232 | async def test_device_bind_timeout(cipher, send):
233 | """Check that the device handles timeout errors when binding."""
234 | info = DeviceInfo(*get_mock_info())
235 | device = Device(info, timeout=1)
236 |
237 | with pytest.raises(DeviceTimeoutError):
238 | await device.bind()
239 | assert send.call_count == 1
240 |
241 | assert device.device_cipher is None
242 |
243 |
244 | @pytest.mark.asyncio
245 | async def test_device_bind_none(cipher, send):
246 | """Check that the device handles bad binding sequences."""
247 | info = DeviceInfo(*get_mock_info())
248 | device = Device(info)
249 |
250 | def fake_send(*args, **kwargs):
251 | device.ready.set()
252 | send.side_effect = fake_send
253 |
254 | with pytest.raises(DeviceNotBoundError):
255 | await device.bind()
256 | assert send.call_count == 1
257 |
258 | assert device.device_cipher is None
259 |
260 |
261 | @pytest.mark.asyncio
262 | async def test_device_late_bind_from_update(cipher, send):
263 | """Check that the device handles late binding sequences."""
264 | info = DeviceInfo(*get_mock_info())
265 | device = Device(info, timeout=1)
266 | fake_key = "abcdefgh12345678"
267 |
268 | def fake_send(*args, **kwargs):
269 | device.device_cipher = CipherV1(fake_key.encode())
270 | device.handle_device_bound(fake_key)
271 | device.ready.set()
272 | send.side_effect = fake_send
273 |
274 | await device.update_state()
275 | assert send.call_count == 2
276 | assert device.device_cipher.key == fake_key
277 |
278 | device.power = True
279 |
280 | send.side_effect = None
281 | await device.push_state_update()
282 |
283 | assert device.device_cipher is not None
284 | assert device.device_cipher.key == fake_key
285 |
286 |
287 | @pytest.mark.asyncio
288 | async def test_device_late_bind_from_request_version(cipher, send):
289 | """Check that the device handles late binding sequences."""
290 | info = DeviceInfo(*get_mock_info())
291 | device = Device(info, timeout=1)
292 | fake_key = "abcdefgh12345678"
293 |
294 | def fake_send(*args, **kwargs):
295 | device.device_cipher = CipherV1(fake_key.encode())
296 | device.handle_device_bound(fake_key)
297 | device.ready.set()
298 | send.side_effect = fake_send
299 |
300 | await device.request_version()
301 | assert send.call_count == 2
302 | assert device.device_cipher.key == fake_key
303 |
304 |
305 | @pytest.mark.asyncio
306 | async def test_device_bind_no_cipher(cipher, send):
307 | """Check that the device handles late binding sequences."""
308 | info = DeviceInfo(*get_mock_info())
309 | device = Device(info, timeout=1)
310 | fake_key = "abcdefgh12345678"
311 |
312 | with pytest.raises(ValueError):
313 | await device.bind(fake_key)
314 |
315 |
316 | @pytest.mark.asyncio
317 | async def test_device_bind_no_device_info(cipher, send):
318 | """Check that the device handles late binding sequences."""
319 | device = Device(None, timeout=1)
320 |
321 | with pytest.raises(DeviceNotBoundError):
322 | await device.bind()
323 |
324 |
325 | @pytest.mark.asyncio
326 | async def test_update_properties(cipher, send):
327 | """Check that properties can be updates."""
328 | device = await generate_device_mock_async()
329 |
330 | for p in Props:
331 | assert device.get_property(p) is None
332 |
333 | def fake_send(*args, **kwargs):
334 | state = get_mock_state()
335 | device.handle_state_update(**state)
336 | send.side_effect = fake_send
337 |
338 | await device.update_state()
339 |
340 | for p in Props:
341 | assert device.get_property(p) is not None
342 | assert device.get_property(p) == get_mock_state()[p.value]
343 |
344 |
345 | @pytest.mark.asyncio
346 | async def test_update_properties_timeout(cipher, send):
347 | """Check that timeouts are handled when properties are updates."""
348 | device = await generate_device_mock_async()
349 |
350 | send.side_effect = asyncio.TimeoutError
351 | with pytest.raises(DeviceTimeoutError):
352 | await device.update_state()
353 |
354 |
355 | @pytest.mark.asyncio
356 | async def test_set_properties_not_dirty(cipher, send):
357 | """Check that the state isn't pushed when properties unchanged."""
358 | device = await generate_device_mock_async()
359 |
360 | await device.push_state_update()
361 | assert send.call_count == 0
362 |
363 |
364 | @pytest.mark.asyncio
365 | async def test_set_properties(cipher, send):
366 | """Check that state is pushed when properties are updated."""
367 | device = await generate_device_mock_async()
368 |
369 | device.power = True
370 | device.mode = 1
371 | device.temperature_units = 1
372 | device.fan_speed = 1
373 | device.fresh_air = True
374 | device.xfan = True
375 | device.anion = True
376 | device.sleep = True
377 | device.light = True
378 | device.horizontal_swing = 1
379 | device.vertical_swing = 1
380 | device.quiet = True
381 | device.turbo = True
382 | device.steady_heat = True
383 | device.power_save = True
384 | device.target_humidity = 30
385 |
386 | await device.push_state_update()
387 | send.assert_called_once()
388 |
389 | for p in Props:
390 | if p not in (
391 | Props.TEMP_SENSOR,
392 | Props.TEMP_SET,
393 | Props.TEMP_BIT,
394 | Props.UNKNOWN_HEATCOOLTYPE,
395 | Props.HUM_SENSOR,
396 | Props.DEHUMIDIFIER_MODE,
397 | Props.WATER_FULL,
398 | Props.CLEAN_FILTER,
399 | ):
400 | assert device.get_property(p) is not None
401 | assert device.get_property(p) == get_mock_state_on()[p.value]
402 |
403 |
404 | @pytest.mark.asyncio
405 | async def test_set_properties_timeout(cipher, send):
406 | """Check timeout handling when pushing state changes."""
407 | device = await generate_device_mock_async()
408 |
409 | device.power = True
410 | device.mode = 1
411 | device.temperature_units = 1
412 | device.fan_speed = 1
413 | device.fresh_air = True
414 | device.xfan = True
415 | device.anion = True
416 | device.sleep = True
417 | device.light = True
418 | device.horizontal_swing = 1
419 | device.vertical_swing = 1
420 | device.quiet = True
421 | device.turbo = True
422 | device.steady_heat = True
423 | device.power_save = True
424 |
425 | assert len(device._dirty)
426 |
427 | send.reset_mock()
428 | send.side_effect = [asyncio.TimeoutError, asyncio.TimeoutError, asyncio.TimeoutError]
429 | with pytest.raises(DeviceTimeoutError):
430 | await device.push_state_update()
431 |
432 |
433 | @pytest.mark.asyncio
434 | async def test_uninitialized_properties(cipher, send):
435 | """Check uninitialized property handling."""
436 | device = await generate_device_mock_async()
437 |
438 | assert not device.power
439 | assert device.mode is None
440 | assert device.target_temperature is None
441 | assert device.current_temperature is None
442 | assert device.temperature_units is None
443 | assert device.fan_speed is None
444 | assert not device.fresh_air
445 | assert not device.xfan
446 | assert not device.anion
447 | assert not device.sleep
448 | assert not device.light
449 | assert device.horizontal_swing is None
450 | assert device.vertical_swing is None
451 | assert not device.quiet
452 | assert not device.turbo
453 | assert not device.steady_heat
454 | assert not device.power_save
455 |
456 |
457 | @pytest.mark.asyncio
458 | async def test_update_current_temp_unsupported(cipher, send):
459 | """Check that properties can be updates."""
460 | device = await generate_device_mock_async()
461 |
462 | def fake_send(*args, **kwargs):
463 | state = get_mock_state_no_temperature()
464 | device.handle_state_update(**state)
465 | send.side_effect = fake_send
466 |
467 | await device.update_state()
468 |
469 | assert device.get_property(Props.TEMP_SENSOR) is None
470 | assert device.current_temperature == device.target_temperature
471 |
472 |
473 | @pytest.mark.asyncio
474 | @pytest.mark.parametrize(
475 | "temsen,hid",
476 | [
477 | (69, "362001000762+U-CS532AE(LT)V3.31.bin"),
478 | (61, "362001061060+U-W04HV3.29.bin"),
479 | (62, "362001061147+U-ZX6045RV1.01.bin"),
480 | ],
481 | )
482 | async def test_update_current_temp_v3(temsen, hid, cipher, send):
483 | """Check that properties can be updates."""
484 | device = await generate_device_mock_async()
485 |
486 | def fake_send(*args, **kwargs):
487 | device.handle_state_update(TemSen=temsen, hid=hid)
488 | send.side_effect = fake_send
489 |
490 | await device.update_state()
491 |
492 | assert device.get_property(Props.TEMP_SENSOR) is not None
493 | assert device.current_temperature == temsen - 40
494 |
495 |
496 | @pytest.mark.asyncio
497 | @pytest.mark.parametrize(
498 | "temsen,hid",
499 | [
500 | (21, "362001060297+U-CS532AF(MTK)V4.bin"),
501 | (21, "362001060297+U-CS532AF(MTK)V2.bin"),
502 | (22, "362001061383+U-BL3332_JDV1.bin"),
503 | (23, "362001061217+U-W04NV7.bin"),
504 | ],
505 | )
506 | async def test_update_current_temp_v4(temsen, hid, cipher, send):
507 | """Check that properties can be updates."""
508 | device = await generate_device_mock_async()
509 |
510 | def fake_send(*args, **kwargs):
511 | device.handle_state_update(TemSen=temsen, hid=hid)
512 | send.side_effect = fake_send
513 |
514 | await device.update_state()
515 |
516 | assert device.get_property(Props.TEMP_SENSOR) is not None
517 | assert device.current_temperature == temsen
518 |
519 |
520 | @pytest.mark.asyncio
521 | async def test_update_current_temp_bad(cipher, send):
522 | """Check that properties can be updates."""
523 | device = await generate_device_mock_async()
524 |
525 | def fake_send(*args, **kwargs):
526 | device.handle_state_update(**get_mock_state_bad_temp())
527 | send.side_effect = fake_send
528 |
529 | await device.update_state()
530 |
531 | assert device.current_temperature == get_mock_state_bad_temp()["TemSen"] - 40
532 |
533 |
534 | @pytest.mark.asyncio
535 | async def test_update_current_temp_0C_v4(cipher, send):
536 | """Check that properties can be updates."""
537 | device = await generate_device_mock_async()
538 |
539 | def fake_send(*args, **kwargs):
540 | device.handle_state_update(**get_mock_state_0c_v4_temp())
541 | send.side_effect = fake_send
542 |
543 | await device.update_state()
544 |
545 | assert device.current_temperature == get_mock_state_0c_v4_temp()["TemSen"]
546 |
547 |
548 | @pytest.mark.asyncio
549 | async def test_update_current_temp_0C_v3(cipher, send):
550 | """Check for devices without a temperature sensor."""
551 | device = await generate_device_mock_async()
552 |
553 | def fake_send(*args, **kwargs):
554 | device.handle_state_update(**get_mock_state_0c_v3_temp())
555 | send.side_effect = fake_send
556 |
557 | await device.update_state()
558 |
559 | assert device.current_temperature == device.target_temperature
560 |
561 |
562 | @pytest.mark.asyncio
563 | @pytest.mark.parametrize("temperature", [18, 19, 20, 21, 22])
564 | async def test_send_temperature_celsius(temperature, cipher, send):
565 | """Check that temperature is set and read properly in C."""
566 | state = get_mock_state()
567 | state["TemSen"] = temperature + 40
568 | device = await generate_device_mock_async()
569 | device.temperature_units = TemperatureUnits.C
570 | device.target_temperature = temperature
571 |
572 | await device.push_state_update()
573 | assert send.call_count == 1
574 |
575 | def fake_send(*args, **kwargs):
576 | device.handle_state_update(**state)
577 | send.side_effect = fake_send
578 |
579 | await device.update_state()
580 |
581 | assert device.current_temperature == temperature
582 |
583 |
584 | @pytest.mark.asyncio
585 | @pytest.mark.parametrize(
586 | "temperature", [60, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 86]
587 | )
588 | async def test_send_temperature_farenheit(temperature, cipher, send):
589 | """Check that temperature is set and read properly in F."""
590 | temSet = round((temperature - 32.0) * 5.0 / 9.0)
591 | temRec = (int)((((temperature - 32.0) * 5.0 / 9.0) - temSet) > 0)
592 |
593 | state = get_mock_state()
594 | state["TemSen"] = temSet + 40
595 | state["TemRec"] = temRec
596 | state["TemUn"] = 1
597 | device = await generate_device_mock_async()
598 |
599 | device.temperature_units = TemperatureUnits.F
600 | device.target_temperature = temperature
601 |
602 | await device.push_state_update()
603 | assert send.call_count == 1
604 |
605 | def fake_send(*args, **kwargs):
606 | device.handle_state_update(**state)
607 | send.side_effect = fake_send
608 |
609 | await device.update_state()
610 |
611 | assert device.current_temperature == temperature
612 |
613 |
614 | @pytest.mark.asyncio
615 | @pytest.mark.parametrize("temperature", [-270, -61, 61, 100])
616 | async def test_send_temperature_out_of_range_celsius(temperature, cipher, send):
617 | """Check that bad temperatures raise the appropriate error."""
618 | device = await generate_device_mock_async()
619 |
620 | device.temperature_units = TemperatureUnits.C
621 | with pytest.raises(ValueError):
622 | device.target_temperature = temperature
623 |
624 |
625 | @pytest.mark.asyncio
626 | @pytest.mark.parametrize("temperature", [-270, -61, 141])
627 | async def test_send_temperature_out_of_range_farenheit_set(temperature, cipher, send):
628 | """Check that bad temperatures raise the appropriate error."""
629 | device = await generate_device_mock_async()
630 |
631 | for p in Props:
632 | assert device.get_property(p) is None
633 |
634 | device.temperature_units = TemperatureUnits.F
635 | with pytest.raises(ValueError):
636 | device.target_temperature = temperature
637 |
638 |
639 | @pytest.mark.asyncio
640 | @pytest.mark.parametrize("temperature", [-270, 150])
641 | async def test_send_temperature_out_of_range_farenheit_get(temperature, cipher, send):
642 | """Check that bad temperatures raise the appropriate error."""
643 | device = await generate_device_mock_async()
644 |
645 | device.set_property(Props.TEMP_SET, 20)
646 | device.set_property(Props.TEMP_SENSOR, temperature)
647 | device.set_property(Props.TEMP_BIT, 0)
648 | device.temperature_units = TemperatureUnits.F
649 |
650 | t = device.current_temperature
651 | assert t == 68
652 |
653 |
654 | @pytest.mark.asyncio
655 | async def test_enable_disable_sleep_mode(cipher, send):
656 | """Check that properties can be updates."""
657 | device = await generate_device_mock_async()
658 |
659 | device.sleep = True
660 | await device.push_state_update()
661 | assert send.call_count == 1
662 |
663 | assert device.get_property(Props.SLEEP) == 1
664 | assert device.get_property(Props.SLEEP_MODE) == 1
665 |
666 | device.sleep = False
667 | await device.push_state_update()
668 | assert send.call_count == 2
669 |
670 | assert device.get_property(Props.SLEEP) == 0
671 | assert device.get_property(Props.SLEEP_MODE) == 0
672 |
673 |
674 | @pytest.mark.asyncio
675 | @pytest.mark.parametrize(
676 | "temperature", [59, 77, 86]
677 | )
678 | async def test_mismatch_temrec_farenheit(temperature, cipher, send):
679 | """Check that temperature is set and read properly in F."""
680 | temSet = round((temperature - 32.0) * 5.0 / 9.0)
681 | temRec = (int)((((temperature - 32.0) * 5.0 / 9.0) - temSet) > 0)
682 |
683 | state = get_mock_state()
684 | state["TemSen"] = temSet + 40
685 | # Now, we alter the temRec on the device so it is not found in the table.
686 | state["TemRec"] = (temRec + 1) % 2
687 | state["TemUn"] = 1
688 | device = await generate_device_mock_async()
689 | device.temperature_units = TemperatureUnits.F
690 | device.target_temperature = temperature
691 |
692 | await device.push_state_update()
693 | assert send.call_count == 1
694 |
695 | def fake_send(*args, **kwargs):
696 | device.handle_state_update(**state)
697 | send.side_effect = None
698 |
699 | await device.update_state()
700 |
701 | assert device.current_temperature == temperature
702 |
703 |
704 | @pytest.mark.asyncio
705 | async def test_device_equality(send):
706 | """Check that two devices with the same info and key are equal."""
707 |
708 | info1 = DeviceInfo(*get_mock_info())
709 | device1 = Device(info1)
710 | await device1.bind(key="fake_key", cipher=CipherV1())
711 |
712 | info2 = DeviceInfo(*get_mock_info())
713 | device2 = Device(info2)
714 | await device2.bind(key="fake_key", cipher=CipherV1())
715 |
716 | assert device1 == device2
717 |
718 | # Change the key of the second device
719 | await device2.bind(key="another_fake_key", cipher=CipherV1())
720 | assert device1 != device2
721 |
722 | # Change the info of the second device
723 | info2 = DeviceInfo(*get_mock_info())
724 | device2 = Device(info2)
725 | device2.power = True
726 | await device2.bind(key="fake_key", cipher=CipherV1())
727 | assert device1 != device2
728 |
729 |
730 | def test_device_key_set_get():
731 | """Check that the device key can be set and retrieved."""
732 | device = Device(DeviceInfo(*get_mock_info()))
733 | device.device_cipher = CipherV1()
734 | device.device_key = "fake_key"
735 | assert device.device_key == "fake_key"
736 |
--------------------------------------------------------------------------------
/LICENSE.txt:
--------------------------------------------------------------------------------
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 | .
--------------------------------------------------------------------------------