pyanova-ble 0.1.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- pyanova_ble-0.1.0/.gitignore +10 -0
- pyanova_ble-0.1.0/LICENSE +21 -0
- pyanova_ble-0.1.0/PKG-INFO +91 -0
- pyanova_ble-0.1.0/README.md +70 -0
- pyanova_ble-0.1.0/pyproject.toml +68 -0
- pyanova_ble-0.1.0/src/pyanova_ble/__init__.py +38 -0
- pyanova_ble-0.1.0/src/pyanova_ble/__main__.py +36 -0
- pyanova_ble-0.1.0/src/pyanova_ble/client.py +358 -0
- pyanova_ble-0.1.0/src/pyanova_ble/const.py +20 -0
- pyanova_ble-0.1.0/src/pyanova_ble/exceptions.py +13 -0
- pyanova_ble-0.1.0/src/pyanova_ble/models.py +49 -0
- pyanova_ble-0.1.0/src/pyanova_ble/py.typed +0 -0
- pyanova_ble-0.1.0/tests/__init__.py +0 -0
- pyanova_ble-0.1.0/tests/conftest.py +121 -0
- pyanova_ble-0.1.0/tests/test_client.py +353 -0
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Ian Foster
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: pyanova-ble
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Control the original Bluetooth Anova Precision Cooker
|
|
5
|
+
Project-URL: Homepage, https://github.com/lanrat/pyanova-ble
|
|
6
|
+
Project-URL: Issues, https://github.com/lanrat/pyanova-ble/issues
|
|
7
|
+
Author: Ian Foster
|
|
8
|
+
License-Expression: MIT
|
|
9
|
+
License-File: LICENSE
|
|
10
|
+
Classifier: Development Status :: 4 - Beta
|
|
11
|
+
Classifier: Framework :: AsyncIO
|
|
12
|
+
Classifier: Intended Audience :: Developers
|
|
13
|
+
Classifier: Operating System :: OS Independent
|
|
14
|
+
Classifier: Programming Language :: Python :: 3
|
|
15
|
+
Classifier: Topic :: Home Automation
|
|
16
|
+
Classifier: Typing :: Typed
|
|
17
|
+
Requires-Python: >=3.12
|
|
18
|
+
Requires-Dist: bleak-retry-connector>=3.5
|
|
19
|
+
Requires-Dist: bleak>=0.22
|
|
20
|
+
Description-Content-Type: text/markdown
|
|
21
|
+
|
|
22
|
+
# pyanova-ble
|
|
23
|
+
|
|
24
|
+
Async Python library for the original Bluetooth Anova Precision Cooker (the
|
|
25
|
+
model before Wi-Fi, which Anova no longer supports). Used by the Home
|
|
26
|
+
Assistant `anova_ble` integration.
|
|
27
|
+
|
|
28
|
+
```python
|
|
29
|
+
from bleak import BleakScanner
|
|
30
|
+
from pyanova_ble import AnovaBLE, TemperatureUnit
|
|
31
|
+
|
|
32
|
+
device = await BleakScanner.find_device_by_address("AA:BB:CC:DD:EE:FF")
|
|
33
|
+
cooker = AnovaBLE(device)
|
|
34
|
+
print(await cooker.async_get_state())
|
|
35
|
+
await cooker.async_set_target_temperature(56.5, TemperatureUnit.CELSIUS)
|
|
36
|
+
await cooker.async_start()
|
|
37
|
+
await cooker.async_start_timer(90)
|
|
38
|
+
await cooker.async_disconnect()
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
Run `python -m pyanova_ble` to list nearby cookers, or
|
|
42
|
+
`python -m pyanova_ble <address>` to print one's details and state.
|
|
43
|
+
|
|
44
|
+
The cooker accepts one connection at a time and does not advertise while
|
|
45
|
+
connected, so call `async_disconnect()` when done to let other clients in.
|
|
46
|
+
|
|
47
|
+
## Protocol
|
|
48
|
+
|
|
49
|
+
Checked against a cooker with firmware 2.7.6.
|
|
50
|
+
|
|
51
|
+
- The cooker advertises the name `Anova` and service
|
|
52
|
+
`0000ffe0-0000-1000-8000-00805f9b34fb`.
|
|
53
|
+
- Commands are ASCII ending in `\r`, written without response to
|
|
54
|
+
characteristic `0000ffe1-0000-1000-8000-00805f9b34fb`. Replies end in `\r`
|
|
55
|
+
and arrive as notifications on the same characteristic; replies longer than
|
|
56
|
+
20 bytes are split over several notifications.
|
|
57
|
+
- Replies do not name the command they answer, so send one command at a time.
|
|
58
|
+
Unknown commands get no reply.
|
|
59
|
+
- The cooker drops a command written within about 0.25 s of subscribing to
|
|
60
|
+
notifications; the client waits 1 s.
|
|
61
|
+
- For a few seconds after power-up the cooker does not answer commands.
|
|
62
|
+
|
|
63
|
+
| Command | Reply | Notes |
|
|
64
|
+
| --- | --- | --- |
|
|
65
|
+
| `status` | `running`, `stopped`, `low water`, `power loss` | Alarms stay until cleared or fixed. |
|
|
66
|
+
| `read unit` / `set unit c` | `c` or `f` | Changing the unit converts the target. |
|
|
67
|
+
| `read set temp` / `set temp 56.5` | `56.5` | Range 0.0–99.5 °C or 32.0–211.8 °F. Out-of-range values are ignored and the reply is the old target. |
|
|
68
|
+
| `read temp` | `55.9` | Water temperature. |
|
|
69
|
+
| `start` / `stop` | `start` / `stop` | `start` also starts the last timer set; `stop` resets the time left. |
|
|
70
|
+
| `set timer 90` | `90` | Minutes, 0–6000. Shown by `read timer` only once started. The cooker keeps it and runs it on every `start`; `set timer 0` turns that off. |
|
|
71
|
+
| `start time` / `stop time` | `start time` / `stop time` | Start or pause the timer; only works while cooking (no reply otherwise). The cooker keeps cooking when the timer ends. |
|
|
72
|
+
| `read timer` | `42 running` | Minutes left, `running` or `stopped`. |
|
|
73
|
+
| `read cal` / `cal 0.5` | `0.5` / `cal 0.5` | Calibration offset, −9.9 to 9.9; kept when the unit changes. |
|
|
74
|
+
| `clear alarm` | `clear alarm` | |
|
|
75
|
+
| `version` | `ver 2.7.6` | |
|
|
76
|
+
| `get id card` | `anova f56-0123456789a` | Unique per cooker. |
|
|
77
|
+
|
|
78
|
+
## Development
|
|
79
|
+
|
|
80
|
+
```bash
|
|
81
|
+
uv sync
|
|
82
|
+
uv run pytest
|
|
83
|
+
uv run ruff check && uv run ruff format --check && uv run mypy
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
## Releasing
|
|
87
|
+
|
|
88
|
+
Bump `version` in `pyproject.toml`, then publish a GitHub release. The
|
|
89
|
+
release workflow builds the package and uploads it to PyPI with trusted
|
|
90
|
+
publishing (configure the `pypi` environment and the trusted publisher on
|
|
91
|
+
PyPI first).
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
# pyanova-ble
|
|
2
|
+
|
|
3
|
+
Async Python library for the original Bluetooth Anova Precision Cooker (the
|
|
4
|
+
model before Wi-Fi, which Anova no longer supports). Used by the Home
|
|
5
|
+
Assistant `anova_ble` integration.
|
|
6
|
+
|
|
7
|
+
```python
|
|
8
|
+
from bleak import BleakScanner
|
|
9
|
+
from pyanova_ble import AnovaBLE, TemperatureUnit
|
|
10
|
+
|
|
11
|
+
device = await BleakScanner.find_device_by_address("AA:BB:CC:DD:EE:FF")
|
|
12
|
+
cooker = AnovaBLE(device)
|
|
13
|
+
print(await cooker.async_get_state())
|
|
14
|
+
await cooker.async_set_target_temperature(56.5, TemperatureUnit.CELSIUS)
|
|
15
|
+
await cooker.async_start()
|
|
16
|
+
await cooker.async_start_timer(90)
|
|
17
|
+
await cooker.async_disconnect()
|
|
18
|
+
```
|
|
19
|
+
|
|
20
|
+
Run `python -m pyanova_ble` to list nearby cookers, or
|
|
21
|
+
`python -m pyanova_ble <address>` to print one's details and state.
|
|
22
|
+
|
|
23
|
+
The cooker accepts one connection at a time and does not advertise while
|
|
24
|
+
connected, so call `async_disconnect()` when done to let other clients in.
|
|
25
|
+
|
|
26
|
+
## Protocol
|
|
27
|
+
|
|
28
|
+
Checked against a cooker with firmware 2.7.6.
|
|
29
|
+
|
|
30
|
+
- The cooker advertises the name `Anova` and service
|
|
31
|
+
`0000ffe0-0000-1000-8000-00805f9b34fb`.
|
|
32
|
+
- Commands are ASCII ending in `\r`, written without response to
|
|
33
|
+
characteristic `0000ffe1-0000-1000-8000-00805f9b34fb`. Replies end in `\r`
|
|
34
|
+
and arrive as notifications on the same characteristic; replies longer than
|
|
35
|
+
20 bytes are split over several notifications.
|
|
36
|
+
- Replies do not name the command they answer, so send one command at a time.
|
|
37
|
+
Unknown commands get no reply.
|
|
38
|
+
- The cooker drops a command written within about 0.25 s of subscribing to
|
|
39
|
+
notifications; the client waits 1 s.
|
|
40
|
+
- For a few seconds after power-up the cooker does not answer commands.
|
|
41
|
+
|
|
42
|
+
| Command | Reply | Notes |
|
|
43
|
+
| --- | --- | --- |
|
|
44
|
+
| `status` | `running`, `stopped`, `low water`, `power loss` | Alarms stay until cleared or fixed. |
|
|
45
|
+
| `read unit` / `set unit c` | `c` or `f` | Changing the unit converts the target. |
|
|
46
|
+
| `read set temp` / `set temp 56.5` | `56.5` | Range 0.0–99.5 °C or 32.0–211.8 °F. Out-of-range values are ignored and the reply is the old target. |
|
|
47
|
+
| `read temp` | `55.9` | Water temperature. |
|
|
48
|
+
| `start` / `stop` | `start` / `stop` | `start` also starts the last timer set; `stop` resets the time left. |
|
|
49
|
+
| `set timer 90` | `90` | Minutes, 0–6000. Shown by `read timer` only once started. The cooker keeps it and runs it on every `start`; `set timer 0` turns that off. |
|
|
50
|
+
| `start time` / `stop time` | `start time` / `stop time` | Start or pause the timer; only works while cooking (no reply otherwise). The cooker keeps cooking when the timer ends. |
|
|
51
|
+
| `read timer` | `42 running` | Minutes left, `running` or `stopped`. |
|
|
52
|
+
| `read cal` / `cal 0.5` | `0.5` / `cal 0.5` | Calibration offset, −9.9 to 9.9; kept when the unit changes. |
|
|
53
|
+
| `clear alarm` | `clear alarm` | |
|
|
54
|
+
| `version` | `ver 2.7.6` | |
|
|
55
|
+
| `get id card` | `anova f56-0123456789a` | Unique per cooker. |
|
|
56
|
+
|
|
57
|
+
## Development
|
|
58
|
+
|
|
59
|
+
```bash
|
|
60
|
+
uv sync
|
|
61
|
+
uv run pytest
|
|
62
|
+
uv run ruff check && uv run ruff format --check && uv run mypy
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
## Releasing
|
|
66
|
+
|
|
67
|
+
Bump `version` in `pyproject.toml`, then publish a GitHub release. The
|
|
68
|
+
release workflow builds the package and uploads it to PyPI with trusted
|
|
69
|
+
publishing (configure the `pypi` environment and the trusted publisher on
|
|
70
|
+
PyPI first).
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["hatchling"]
|
|
3
|
+
build-backend = "hatchling.build"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "pyanova-ble"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "Control the original Bluetooth Anova Precision Cooker"
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
license = "MIT"
|
|
11
|
+
license-files = ["LICENSE"]
|
|
12
|
+
authors = [{ name = "Ian Foster" }]
|
|
13
|
+
requires-python = ">=3.12"
|
|
14
|
+
dependencies = [
|
|
15
|
+
"bleak>=0.22",
|
|
16
|
+
"bleak-retry-connector>=3.5",
|
|
17
|
+
]
|
|
18
|
+
classifiers = [
|
|
19
|
+
"Development Status :: 4 - Beta",
|
|
20
|
+
"Framework :: AsyncIO",
|
|
21
|
+
"Intended Audience :: Developers",
|
|
22
|
+
"Operating System :: OS Independent",
|
|
23
|
+
"Programming Language :: Python :: 3",
|
|
24
|
+
"Topic :: Home Automation",
|
|
25
|
+
"Typing :: Typed",
|
|
26
|
+
]
|
|
27
|
+
|
|
28
|
+
[project.urls]
|
|
29
|
+
Homepage = "https://github.com/lanrat/pyanova-ble"
|
|
30
|
+
Issues = "https://github.com/lanrat/pyanova-ble/issues"
|
|
31
|
+
|
|
32
|
+
[dependency-groups]
|
|
33
|
+
dev = [
|
|
34
|
+
"mypy>=1.13",
|
|
35
|
+
"pytest>=8.3",
|
|
36
|
+
"pytest-asyncio>=0.24",
|
|
37
|
+
"pytest-cov>=6.0",
|
|
38
|
+
"ruff>=0.8",
|
|
39
|
+
]
|
|
40
|
+
|
|
41
|
+
[tool.hatch.build.targets.sdist]
|
|
42
|
+
include = ["src", "tests", "README.md", "LICENSE"]
|
|
43
|
+
|
|
44
|
+
[tool.pytest.ini_options]
|
|
45
|
+
asyncio_mode = "auto"
|
|
46
|
+
testpaths = ["tests"]
|
|
47
|
+
addopts = "--cov=pyanova_ble --cov-report=term-missing --cov-fail-under=100"
|
|
48
|
+
|
|
49
|
+
[tool.coverage.report]
|
|
50
|
+
exclude_also = ["if TYPE_CHECKING:", "if __name__ == .__main__.:"]
|
|
51
|
+
|
|
52
|
+
[tool.coverage.run]
|
|
53
|
+
omit = ["src/pyanova_ble/__main__.py"]
|
|
54
|
+
|
|
55
|
+
[tool.mypy]
|
|
56
|
+
strict = true
|
|
57
|
+
files = ["src", "tests"]
|
|
58
|
+
|
|
59
|
+
[tool.ruff]
|
|
60
|
+
target-version = "py312"
|
|
61
|
+
src = ["src", "tests"]
|
|
62
|
+
|
|
63
|
+
[tool.ruff.lint]
|
|
64
|
+
select = ["E", "F", "W", "I", "B", "UP", "SIM", "RUF", "D", "PT", "ASYNC"]
|
|
65
|
+
ignore = ["D203", "D213"]
|
|
66
|
+
|
|
67
|
+
[tool.ruff.lint.per-file-ignores]
|
|
68
|
+
"tests/*" = ["D"]
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
"""Control the original Bluetooth Anova Precision Cooker."""
|
|
2
|
+
|
|
3
|
+
from .client import AnovaBLE
|
|
4
|
+
from .const import (
|
|
5
|
+
CHARACTERISTIC_UUID,
|
|
6
|
+
LOCAL_NAME,
|
|
7
|
+
MAX_CALIBRATION,
|
|
8
|
+
MAX_TEMP_C,
|
|
9
|
+
MAX_TEMP_F,
|
|
10
|
+
MIN_CALIBRATION,
|
|
11
|
+
MIN_TEMP_C,
|
|
12
|
+
MIN_TEMP_F,
|
|
13
|
+
SERVICE_UUID,
|
|
14
|
+
TIMER_MAX_MINUTES,
|
|
15
|
+
)
|
|
16
|
+
from .exceptions import AnovaBLEError, AnovaBLENotRunningError, AnovaBLERejectedError
|
|
17
|
+
from .models import AnovaDeviceInfo, AnovaState, AnovaStatus, TemperatureUnit
|
|
18
|
+
|
|
19
|
+
__all__ = [
|
|
20
|
+
"CHARACTERISTIC_UUID",
|
|
21
|
+
"LOCAL_NAME",
|
|
22
|
+
"MAX_CALIBRATION",
|
|
23
|
+
"MAX_TEMP_C",
|
|
24
|
+
"MAX_TEMP_F",
|
|
25
|
+
"MIN_CALIBRATION",
|
|
26
|
+
"MIN_TEMP_C",
|
|
27
|
+
"MIN_TEMP_F",
|
|
28
|
+
"SERVICE_UUID",
|
|
29
|
+
"TIMER_MAX_MINUTES",
|
|
30
|
+
"AnovaBLE",
|
|
31
|
+
"AnovaBLEError",
|
|
32
|
+
"AnovaBLENotRunningError",
|
|
33
|
+
"AnovaBLERejectedError",
|
|
34
|
+
"AnovaDeviceInfo",
|
|
35
|
+
"AnovaState",
|
|
36
|
+
"AnovaStatus",
|
|
37
|
+
"TemperatureUnit",
|
|
38
|
+
]
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
"""Find Anova cookers, or print one's details and state.
|
|
2
|
+
|
|
3
|
+
python -m pyanova_ble # list nearby cookers
|
|
4
|
+
python -m pyanova_ble <address> # print a cooker's details and state
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
import asyncio
|
|
8
|
+
import sys
|
|
9
|
+
|
|
10
|
+
from bleak import BleakScanner
|
|
11
|
+
|
|
12
|
+
from . import LOCAL_NAME, AnovaBLE
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
async def _main(address: str | None) -> int:
|
|
16
|
+
if address is None:
|
|
17
|
+
devices = await BleakScanner.discover(timeout=10, return_adv=True)
|
|
18
|
+
for device, adv in devices.values():
|
|
19
|
+
if adv.local_name == LOCAL_NAME:
|
|
20
|
+
print(device.address, adv.rssi)
|
|
21
|
+
return 0
|
|
22
|
+
found = await BleakScanner.find_device_by_address(address, timeout=20)
|
|
23
|
+
if found is None:
|
|
24
|
+
print(f"{address} not found", file=sys.stderr)
|
|
25
|
+
return 1
|
|
26
|
+
client = AnovaBLE(found)
|
|
27
|
+
try:
|
|
28
|
+
print(await client.async_get_device_info())
|
|
29
|
+
print(await client.async_get_state())
|
|
30
|
+
finally:
|
|
31
|
+
await client.async_disconnect()
|
|
32
|
+
return 0
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
if __name__ == "__main__":
|
|
36
|
+
sys.exit(asyncio.run(_main(sys.argv[1] if len(sys.argv) > 1 else None)))
|
|
@@ -0,0 +1,358 @@
|
|
|
1
|
+
"""Bluetooth client for the original Anova Precision Cooker.
|
|
2
|
+
|
|
3
|
+
The cooker exposes one characteristic: ASCII commands ending in a carriage
|
|
4
|
+
return are written to it, and replies end in a carriage return too. A reply
|
|
5
|
+
longer than 20 bytes is split over several notifications. Replies do not name
|
|
6
|
+
the command they answer, so commands are sent one at a time under a lock.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
import asyncio
|
|
10
|
+
import logging
|
|
11
|
+
from collections.abc import AsyncIterator
|
|
12
|
+
from contextlib import asynccontextmanager
|
|
13
|
+
|
|
14
|
+
from bleak.backends.device import BLEDevice
|
|
15
|
+
from bleak.exc import BleakError
|
|
16
|
+
from bleak_retry_connector import (
|
|
17
|
+
BleakClientWithServiceCache,
|
|
18
|
+
BleakNotFoundError,
|
|
19
|
+
establish_connection,
|
|
20
|
+
)
|
|
21
|
+
|
|
22
|
+
from .const import CHARACTERISTIC_UUID
|
|
23
|
+
from .exceptions import AnovaBLEError, AnovaBLENotRunningError, AnovaBLERejectedError
|
|
24
|
+
from .models import AnovaDeviceInfo, AnovaState, AnovaStatus, TemperatureUnit
|
|
25
|
+
|
|
26
|
+
_LOGGER = logging.getLogger(__name__)
|
|
27
|
+
|
|
28
|
+
COMMAND_TIMEOUT = 5.0
|
|
29
|
+
# The cooker drops a command written too soon after subscribing; 0.5 s was
|
|
30
|
+
# reliable on hardware, so wait twice that.
|
|
31
|
+
CONNECT_SETTLE = 1.0
|
|
32
|
+
|
|
33
|
+
CMD_STATUS = "status"
|
|
34
|
+
CMD_READ_UNIT = "read unit"
|
|
35
|
+
CMD_READ_TARGET_TEMP = "read set temp"
|
|
36
|
+
CMD_READ_CURRENT_TEMP = "read temp"
|
|
37
|
+
CMD_READ_TIMER = "read timer"
|
|
38
|
+
CMD_READ_CALIBRATION = "read cal"
|
|
39
|
+
CMD_READ_VERSION = "version"
|
|
40
|
+
CMD_READ_ID_CARD = "get id card"
|
|
41
|
+
CMD_SET_TARGET_TEMP = "set temp {}"
|
|
42
|
+
CMD_SET_UNIT = "set unit {}"
|
|
43
|
+
CMD_SET_TIMER = "set timer {}"
|
|
44
|
+
CMD_SET_CALIBRATION = "cal {}"
|
|
45
|
+
CMD_START = "start"
|
|
46
|
+
CMD_STOP = "stop"
|
|
47
|
+
CMD_START_TIMER = "start time"
|
|
48
|
+
CMD_STOP_TIMER = "stop time"
|
|
49
|
+
CMD_CLEAR_ALARM = "clear alarm"
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def _convert(
|
|
53
|
+
value: float, from_unit: TemperatureUnit, to_unit: TemperatureUnit
|
|
54
|
+
) -> float:
|
|
55
|
+
if from_unit is to_unit:
|
|
56
|
+
return value
|
|
57
|
+
if to_unit is TemperatureUnit.FAHRENHEIT:
|
|
58
|
+
return value * 9 / 5 + 32
|
|
59
|
+
return (value - 32) * 5 / 9
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def _is_number(reply: str) -> bool:
|
|
63
|
+
try:
|
|
64
|
+
float(reply)
|
|
65
|
+
except ValueError:
|
|
66
|
+
return False
|
|
67
|
+
return True
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def _parse_float(reply: str) -> float:
|
|
71
|
+
try:
|
|
72
|
+
return float(reply)
|
|
73
|
+
except ValueError as err:
|
|
74
|
+
raise AnovaBLEError(f"Unexpected reply, expected a number: {reply!r}") from err
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def _parse_int(reply: str) -> int:
|
|
78
|
+
try:
|
|
79
|
+
return int(reply)
|
|
80
|
+
except ValueError as err:
|
|
81
|
+
raise AnovaBLEError(
|
|
82
|
+
f"Unexpected reply, expected a whole number: {reply!r}"
|
|
83
|
+
) from err
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def _parse_prefixed(reply: str, prefix: str) -> str:
|
|
87
|
+
if not reply.startswith(prefix):
|
|
88
|
+
raise AnovaBLEError(f"Unexpected reply, expected {prefix!r}: {reply!r}")
|
|
89
|
+
return reply.removeprefix(prefix)
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def _parse_status(reply: str) -> AnovaStatus | None:
|
|
93
|
+
# A unit or a number answers another command: replies are out of step.
|
|
94
|
+
if reply.lower() in TemperatureUnit or _is_number(reply):
|
|
95
|
+
raise AnovaBLEError(f"Unexpected status reply: {reply!r}")
|
|
96
|
+
try:
|
|
97
|
+
return AnovaStatus(reply)
|
|
98
|
+
except ValueError:
|
|
99
|
+
_LOGGER.debug("Unknown status %r", reply)
|
|
100
|
+
return None
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def _parse_unit(reply: str) -> TemperatureUnit:
|
|
104
|
+
try:
|
|
105
|
+
return TemperatureUnit(reply.lower())
|
|
106
|
+
except ValueError as err:
|
|
107
|
+
raise AnovaBLEError(f"Unexpected unit reply: {reply!r}") from err
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def _parse_timer(reply: str) -> tuple[int, bool]:
|
|
111
|
+
"""Parse e.g. "42 running" into minutes left and whether it runs."""
|
|
112
|
+
minutes, _, state = reply.partition(" ")
|
|
113
|
+
if state not in ("running", "stopped"):
|
|
114
|
+
raise AnovaBLEError(f"Unexpected timer reply: {reply!r}")
|
|
115
|
+
return _parse_int(minutes), state == "running"
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def _expect_echo(reply: str, command: str) -> None:
|
|
119
|
+
if reply != command:
|
|
120
|
+
raise AnovaBLEError(f"Unexpected reply to {command!r}: {reply!r}")
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
class AnovaBLE:
|
|
124
|
+
"""Talk to an Anova Precision Cooker over Bluetooth."""
|
|
125
|
+
|
|
126
|
+
def __init__(self, ble_device: BLEDevice) -> None:
|
|
127
|
+
"""Initialize the client."""
|
|
128
|
+
self._ble_device = ble_device
|
|
129
|
+
self._client: BleakClientWithServiceCache | None = None
|
|
130
|
+
self._lock = asyncio.Lock()
|
|
131
|
+
self._reply: asyncio.Future[str] | None = None
|
|
132
|
+
self._reply_buffer = bytearray()
|
|
133
|
+
|
|
134
|
+
@property
|
|
135
|
+
def address(self) -> str:
|
|
136
|
+
"""Return the Bluetooth address of the cooker."""
|
|
137
|
+
return self._ble_device.address
|
|
138
|
+
|
|
139
|
+
@property
|
|
140
|
+
def is_connected(self) -> bool:
|
|
141
|
+
"""Return whether a connection to the cooker is open."""
|
|
142
|
+
return self._client is not None and self._client.is_connected
|
|
143
|
+
|
|
144
|
+
def set_ble_device(self, ble_device: BLEDevice) -> None:
|
|
145
|
+
"""Update the device used for the next connection, e.g. a closer proxy."""
|
|
146
|
+
self._ble_device = ble_device
|
|
147
|
+
|
|
148
|
+
async def async_get_state(self) -> AnovaState:
|
|
149
|
+
"""Read the status, unit, temperatures, timer and calibration."""
|
|
150
|
+
async with self._session():
|
|
151
|
+
status = _parse_status(await self._async_command(CMD_STATUS))
|
|
152
|
+
unit = _parse_unit(await self._async_command(CMD_READ_UNIT))
|
|
153
|
+
target = _parse_float(await self._async_command(CMD_READ_TARGET_TEMP))
|
|
154
|
+
current = _parse_float(await self._async_command(CMD_READ_CURRENT_TEMP))
|
|
155
|
+
timer_minutes, timer_running = _parse_timer(
|
|
156
|
+
await self._async_command(CMD_READ_TIMER)
|
|
157
|
+
)
|
|
158
|
+
calibration = _parse_float(await self._async_command(CMD_READ_CALIBRATION))
|
|
159
|
+
return AnovaState(
|
|
160
|
+
status=status,
|
|
161
|
+
unit=unit,
|
|
162
|
+
target_temperature=target,
|
|
163
|
+
current_temperature=current,
|
|
164
|
+
timer_minutes=timer_minutes,
|
|
165
|
+
timer_running=timer_running,
|
|
166
|
+
calibration=calibration,
|
|
167
|
+
)
|
|
168
|
+
|
|
169
|
+
async def async_get_device_info(self) -> AnovaDeviceInfo:
|
|
170
|
+
"""Read the firmware version and serial number."""
|
|
171
|
+
async with self._session():
|
|
172
|
+
version = _parse_prefixed(
|
|
173
|
+
await self._async_command(CMD_READ_VERSION), "ver "
|
|
174
|
+
)
|
|
175
|
+
serial = _parse_prefixed(
|
|
176
|
+
await self._async_command(CMD_READ_ID_CARD), "anova "
|
|
177
|
+
)
|
|
178
|
+
return AnovaDeviceInfo(firmware_version=version, serial_number=serial)
|
|
179
|
+
|
|
180
|
+
async def async_start(self) -> None:
|
|
181
|
+
"""Start cooking; this also starts the last timer set, if any."""
|
|
182
|
+
await self._async_echo_command(CMD_START)
|
|
183
|
+
|
|
184
|
+
async def async_stop(self) -> None:
|
|
185
|
+
"""Stop cooking; this resets the time left on the timer."""
|
|
186
|
+
await self._async_echo_command(CMD_STOP)
|
|
187
|
+
|
|
188
|
+
async def async_set_target_temperature(
|
|
189
|
+
self, temperature: float, unit: TemperatureUnit
|
|
190
|
+
) -> None:
|
|
191
|
+
"""Set the target temperature, given in ``unit``.
|
|
192
|
+
|
|
193
|
+
Raises AnovaBLERejectedError when the cooker keeps its old target,
|
|
194
|
+
which it does for values outside its range.
|
|
195
|
+
"""
|
|
196
|
+
async with self._session():
|
|
197
|
+
device_unit = _parse_unit(await self._async_command(CMD_READ_UNIT))
|
|
198
|
+
value = f"{_convert(temperature, unit, device_unit):.1f}"
|
|
199
|
+
reply = _parse_float(
|
|
200
|
+
await self._async_command(CMD_SET_TARGET_TEMP.format(value))
|
|
201
|
+
)
|
|
202
|
+
if reply != float(value):
|
|
203
|
+
raise AnovaBLERejectedError(
|
|
204
|
+
f"Cooker kept {reply} instead of {value} {device_unit}"
|
|
205
|
+
)
|
|
206
|
+
|
|
207
|
+
async def async_set_unit(self, unit: TemperatureUnit) -> None:
|
|
208
|
+
"""Switch the cooker's unit; it converts its target temperature."""
|
|
209
|
+
async with self._session():
|
|
210
|
+
reply = _parse_unit(await self._async_command(CMD_SET_UNIT.format(unit)))
|
|
211
|
+
if reply is not unit:
|
|
212
|
+
raise AnovaBLERejectedError(f"Cooker kept unit {reply} instead of {unit}")
|
|
213
|
+
|
|
214
|
+
async def async_start_timer(self, minutes: int | None = None) -> None:
|
|
215
|
+
"""Start the timer, from ``minutes`` or where it was paused.
|
|
216
|
+
|
|
217
|
+
The timer counts down while cooking and does not stop the cooker when
|
|
218
|
+
it reaches zero. The cooker keeps the duration and starts it again
|
|
219
|
+
with every async_start(). Raises AnovaBLENotRunningError when not
|
|
220
|
+
cooking, since the cooker ignores the timer then.
|
|
221
|
+
"""
|
|
222
|
+
set_minutes: int | None = None
|
|
223
|
+
async with self._session():
|
|
224
|
+
status = _parse_status(await self._async_command(CMD_STATUS))
|
|
225
|
+
if status is AnovaStatus.RUNNING and minutes is not None:
|
|
226
|
+
set_minutes = _parse_int(
|
|
227
|
+
await self._async_command(CMD_SET_TIMER.format(minutes))
|
|
228
|
+
)
|
|
229
|
+
if status is AnovaStatus.RUNNING and set_minutes == minutes:
|
|
230
|
+
_expect_echo(
|
|
231
|
+
await self._async_command(CMD_START_TIMER), CMD_START_TIMER
|
|
232
|
+
)
|
|
233
|
+
if status is not AnovaStatus.RUNNING:
|
|
234
|
+
raise AnovaBLENotRunningError("The timer only runs while cooking")
|
|
235
|
+
if set_minutes != minutes:
|
|
236
|
+
raise AnovaBLERejectedError(
|
|
237
|
+
f"Cooker set the timer to {set_minutes} instead of {minutes}"
|
|
238
|
+
)
|
|
239
|
+
|
|
240
|
+
async def async_stop_timer(self) -> None:
|
|
241
|
+
"""Pause the timer; cooking continues."""
|
|
242
|
+
await self._async_echo_command(CMD_STOP_TIMER)
|
|
243
|
+
|
|
244
|
+
async def async_clear_alarm(self) -> None:
|
|
245
|
+
"""Clear an alarm such as low water."""
|
|
246
|
+
await self._async_echo_command(CMD_CLEAR_ALARM)
|
|
247
|
+
|
|
248
|
+
async def async_set_calibration(self, offset: float) -> None:
|
|
249
|
+
"""Set the temperature calibration offset.
|
|
250
|
+
|
|
251
|
+
Raises AnovaBLERejectedError when the cooker keeps its old offset,
|
|
252
|
+
which it does for values outside its range.
|
|
253
|
+
"""
|
|
254
|
+
value = f"{offset:.1f}"
|
|
255
|
+
async with self._session():
|
|
256
|
+
reply = _parse_float(
|
|
257
|
+
_parse_prefixed(
|
|
258
|
+
await self._async_command(CMD_SET_CALIBRATION.format(value)),
|
|
259
|
+
"cal ",
|
|
260
|
+
)
|
|
261
|
+
)
|
|
262
|
+
if reply != float(value):
|
|
263
|
+
raise AnovaBLERejectedError(
|
|
264
|
+
f"Cooker kept calibration {reply} instead of {value}"
|
|
265
|
+
)
|
|
266
|
+
|
|
267
|
+
async def async_disconnect(self) -> None:
|
|
268
|
+
"""Close the connection, freeing the Bluetooth connection slot."""
|
|
269
|
+
async with self._lock:
|
|
270
|
+
await self._async_disconnect()
|
|
271
|
+
|
|
272
|
+
async def _async_echo_command(self, command: str) -> None:
|
|
273
|
+
async with self._session():
|
|
274
|
+
_expect_echo(await self._async_command(command), command)
|
|
275
|
+
|
|
276
|
+
@asynccontextmanager
|
|
277
|
+
async def _session(self) -> AsyncIterator[None]:
|
|
278
|
+
"""Hold the lock; after any error, drop the connection.
|
|
279
|
+
|
|
280
|
+
A missing or unexpected reply means later replies may answer earlier
|
|
281
|
+
commands, so the next command starts on a fresh connection.
|
|
282
|
+
"""
|
|
283
|
+
async with self._lock:
|
|
284
|
+
try:
|
|
285
|
+
yield
|
|
286
|
+
except AnovaBLEError:
|
|
287
|
+
await self._async_disconnect()
|
|
288
|
+
raise
|
|
289
|
+
|
|
290
|
+
async def _async_disconnect(self) -> None:
|
|
291
|
+
client, self._client = self._client, None
|
|
292
|
+
if client is None:
|
|
293
|
+
return
|
|
294
|
+
# Also after the link was lost, to release the client's D-Bus
|
|
295
|
+
# connection and notification subscription.
|
|
296
|
+
try:
|
|
297
|
+
await client.disconnect()
|
|
298
|
+
except (BleakError, TimeoutError):
|
|
299
|
+
_LOGGER.debug("%s: error while disconnecting", self.address)
|
|
300
|
+
|
|
301
|
+
async def _async_ensure_connected(self) -> BleakClientWithServiceCache:
|
|
302
|
+
if self._client is not None:
|
|
303
|
+
if self._client.is_connected:
|
|
304
|
+
return self._client
|
|
305
|
+
await self._async_disconnect()
|
|
306
|
+
try:
|
|
307
|
+
client = await establish_connection(
|
|
308
|
+
BleakClientWithServiceCache,
|
|
309
|
+
self._ble_device,
|
|
310
|
+
self._ble_device.name or self.address,
|
|
311
|
+
self._handle_disconnect,
|
|
312
|
+
ble_device_callback=lambda: self._ble_device,
|
|
313
|
+
)
|
|
314
|
+
except (BleakNotFoundError, BleakError, TimeoutError) as err:
|
|
315
|
+
raise AnovaBLEError(f"Could not connect to {self.address}: {err}") from err
|
|
316
|
+
try:
|
|
317
|
+
await client.start_notify(CHARACTERISTIC_UUID, self._handle_notify)
|
|
318
|
+
except (BleakError, TimeoutError) as err:
|
|
319
|
+
await client.disconnect()
|
|
320
|
+
raise AnovaBLEError(
|
|
321
|
+
f"Could not subscribe to {self.address}, not an Anova?: {err}"
|
|
322
|
+
) from err
|
|
323
|
+
await asyncio.sleep(CONNECT_SETTLE)
|
|
324
|
+
self._client = client
|
|
325
|
+
return client
|
|
326
|
+
|
|
327
|
+
async def _async_command(self, command: str) -> str:
|
|
328
|
+
client = await self._async_ensure_connected()
|
|
329
|
+
reply: asyncio.Future[str] = asyncio.get_running_loop().create_future()
|
|
330
|
+
self._reply = reply
|
|
331
|
+
self._reply_buffer.clear()
|
|
332
|
+
try:
|
|
333
|
+
await client.write_gatt_char(
|
|
334
|
+
CHARACTERISTIC_UUID, f"{command}\r".encode(), response=False
|
|
335
|
+
)
|
|
336
|
+
async with asyncio.timeout(COMMAND_TIMEOUT):
|
|
337
|
+
text = await reply
|
|
338
|
+
except (BleakError, TimeoutError) as err:
|
|
339
|
+
raise AnovaBLEError(
|
|
340
|
+
f"No reply from {self.address} to {command!r}: {err}"
|
|
341
|
+
) from err
|
|
342
|
+
finally:
|
|
343
|
+
self._reply = None
|
|
344
|
+
_LOGGER.debug("%s: %r -> %r", self.address, command, text)
|
|
345
|
+
return text
|
|
346
|
+
|
|
347
|
+
def _handle_notify(self, _sender: object, data: bytearray) -> None:
|
|
348
|
+
if self._reply is None or self._reply.done():
|
|
349
|
+
_LOGGER.debug("%s: unexpected notification %r", self.address, data)
|
|
350
|
+
return
|
|
351
|
+
self._reply_buffer += data
|
|
352
|
+
if self._reply_buffer.endswith(b"\r"):
|
|
353
|
+
self._reply.set_result(self._reply_buffer.decode(errors="replace").strip())
|
|
354
|
+
|
|
355
|
+
def _handle_disconnect(self, _client: object) -> None:
|
|
356
|
+
_LOGGER.debug("%s: disconnected", self.address)
|
|
357
|
+
if self._reply is not None and not self._reply.done():
|
|
358
|
+
self._reply.set_exception(BleakError("Disconnected"))
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
"""Constants of the Anova Precision Cooker's Bluetooth protocol."""
|
|
2
|
+
|
|
3
|
+
SERVICE_UUID = "0000ffe0-0000-1000-8000-00805f9b34fb"
|
|
4
|
+
CHARACTERISTIC_UUID = "0000ffe1-0000-1000-8000-00805f9b34fb"
|
|
5
|
+
# The cooker advertises exactly this name.
|
|
6
|
+
LOCAL_NAME = "Anova"
|
|
7
|
+
|
|
8
|
+
# Target temperatures the cooker accepts; the °C maximum is lower than the
|
|
9
|
+
# °F maximum converted.
|
|
10
|
+
MIN_TEMP_C = 0.0
|
|
11
|
+
MAX_TEMP_C = 99.5
|
|
12
|
+
MIN_TEMP_F = 32.0
|
|
13
|
+
MAX_TEMP_F = 211.8
|
|
14
|
+
|
|
15
|
+
TIMER_MAX_MINUTES = 6000
|
|
16
|
+
|
|
17
|
+
# The calibration offset keeps its value when the unit changes, so its unit
|
|
18
|
+
# is not known.
|
|
19
|
+
MIN_CALIBRATION = -9.9
|
|
20
|
+
MAX_CALIBRATION = 9.9
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
"""Exceptions raised by pyanova-ble."""
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
class AnovaBLEError(Exception):
|
|
5
|
+
"""The cooker could not be reached or gave an unexpected reply."""
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class AnovaBLERejectedError(AnovaBLEError):
|
|
9
|
+
"""The cooker kept its old value, e.g. because the new one is out of range."""
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class AnovaBLENotRunningError(AnovaBLEError):
|
|
13
|
+
"""The command only works while the cooker is cooking."""
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
"""Data read from the cooker."""
|
|
2
|
+
|
|
3
|
+
from dataclasses import dataclass
|
|
4
|
+
from enum import StrEnum
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
class TemperatureUnit(StrEnum):
|
|
8
|
+
"""Temperature unit the cooker is set to."""
|
|
9
|
+
|
|
10
|
+
CELSIUS = "c"
|
|
11
|
+
FAHRENHEIT = "f"
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class AnovaStatus(StrEnum):
|
|
15
|
+
"""What the cooker reports as its status."""
|
|
16
|
+
|
|
17
|
+
RUNNING = "running"
|
|
18
|
+
STOPPED = "stopped"
|
|
19
|
+
# Alarms; the cooker is not heating while one is shown.
|
|
20
|
+
LOW_WATER = "low water"
|
|
21
|
+
POWER_LOSS = "power loss"
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
@dataclass(frozen=True, slots=True)
|
|
25
|
+
class AnovaState:
|
|
26
|
+
"""State read from the cooker, with temperatures in its own unit."""
|
|
27
|
+
|
|
28
|
+
# None when the cooker reports a status this library does not know.
|
|
29
|
+
status: AnovaStatus | None
|
|
30
|
+
unit: TemperatureUnit
|
|
31
|
+
target_temperature: float
|
|
32
|
+
current_temperature: float
|
|
33
|
+
# Minutes left; 0 until a timer is started.
|
|
34
|
+
timer_minutes: int
|
|
35
|
+
timer_running: bool
|
|
36
|
+
calibration: float
|
|
37
|
+
|
|
38
|
+
@property
|
|
39
|
+
def running(self) -> bool:
|
|
40
|
+
"""Return whether the cooker is cooking."""
|
|
41
|
+
return self.status is AnovaStatus.RUNNING
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
@dataclass(frozen=True, slots=True)
|
|
45
|
+
class AnovaDeviceInfo:
|
|
46
|
+
"""Details of the cooker that do not change."""
|
|
47
|
+
|
|
48
|
+
firmware_version: str
|
|
49
|
+
serial_number: str
|
|
File without changes
|
|
File without changes
|
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
"""Fixtures for pyanova-ble tests: a fake cooker answering like the real one."""
|
|
2
|
+
|
|
3
|
+
import asyncio
|
|
4
|
+
from collections.abc import Callable, Generator
|
|
5
|
+
from unittest.mock import AsyncMock, MagicMock, patch
|
|
6
|
+
|
|
7
|
+
import pytest
|
|
8
|
+
from bleak.backends.device import BLEDevice
|
|
9
|
+
|
|
10
|
+
from pyanova_ble import CHARACTERISTIC_UUID, AnovaBLE
|
|
11
|
+
from pyanova_ble import client as client_module
|
|
12
|
+
|
|
13
|
+
ADDRESS = "AA:BB:CC:DD:EE:FF"
|
|
14
|
+
|
|
15
|
+
# Replies to commands that take a value, built from the value sent.
|
|
16
|
+
SET_COMMANDS: dict[str, Callable[[str], str]] = {
|
|
17
|
+
"set temp ": lambda value: value,
|
|
18
|
+
"set unit ": lambda value: value,
|
|
19
|
+
"set timer ": lambda value: value,
|
|
20
|
+
"cal ": lambda value: f"cal {value}",
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class FakeCooker:
|
|
25
|
+
"""Answer commands the way the cooker does, in notifications of 20 bytes."""
|
|
26
|
+
|
|
27
|
+
def __init__(self) -> None:
|
|
28
|
+
"""Initialize the fake cooker."""
|
|
29
|
+
self.replies: dict[str, str | None] = {
|
|
30
|
+
"status": "running",
|
|
31
|
+
"read unit": "c",
|
|
32
|
+
"read set temp": "56.5",
|
|
33
|
+
"read temp": "55.9",
|
|
34
|
+
"read timer": "42 running",
|
|
35
|
+
"read cal": "0.0",
|
|
36
|
+
"version": "ver 2.7.6",
|
|
37
|
+
"get id card": "anova f56-0123456789a",
|
|
38
|
+
"start": "start",
|
|
39
|
+
"stop": "stop",
|
|
40
|
+
"start time": "start time",
|
|
41
|
+
"stop time": "stop time",
|
|
42
|
+
"clear alarm": "clear alarm",
|
|
43
|
+
}
|
|
44
|
+
# Replies to send instead of echoing the value, keyed by command prefix.
|
|
45
|
+
self.set_replies: dict[str, str] = {}
|
|
46
|
+
self.chunk_size = 20
|
|
47
|
+
self.written: list[str] = []
|
|
48
|
+
self.notify: Callable[[object, bytearray], None] | None = None
|
|
49
|
+
self.disconnected: Callable[[object], None] | None = None
|
|
50
|
+
self.connect = MagicMock()
|
|
51
|
+
self.client = MagicMock()
|
|
52
|
+
self.client.is_connected = True
|
|
53
|
+
self.client.start_notify = AsyncMock(side_effect=self._start_notify)
|
|
54
|
+
self.client.write_gatt_char = AsyncMock(side_effect=self._write)
|
|
55
|
+
self.client.disconnect = AsyncMock(side_effect=self._disconnect)
|
|
56
|
+
|
|
57
|
+
async def _start_notify(
|
|
58
|
+
self, uuid: str, callback: Callable[[object, bytearray], None]
|
|
59
|
+
) -> None:
|
|
60
|
+
assert uuid == CHARACTERISTIC_UUID
|
|
61
|
+
self.notify = callback
|
|
62
|
+
|
|
63
|
+
def _reply(self, command: str) -> str | None:
|
|
64
|
+
for prefix, build in SET_COMMANDS.items():
|
|
65
|
+
if command.startswith(prefix):
|
|
66
|
+
return self.set_replies.get(prefix) or build(
|
|
67
|
+
command.removeprefix(prefix)
|
|
68
|
+
)
|
|
69
|
+
return self.replies[command]
|
|
70
|
+
|
|
71
|
+
async def _write(self, uuid: str, data: bytes, response: bool) -> None:
|
|
72
|
+
assert uuid == CHARACTERISTIC_UUID
|
|
73
|
+
assert response is False
|
|
74
|
+
text = data.decode()
|
|
75
|
+
assert text.endswith("\r")
|
|
76
|
+
command = text[:-1]
|
|
77
|
+
self.written.append(command)
|
|
78
|
+
reply = self._reply(command)
|
|
79
|
+
if reply is None:
|
|
80
|
+
return
|
|
81
|
+
assert self.notify is not None
|
|
82
|
+
payload = f"{reply}\r".encode()
|
|
83
|
+
for start in range(0, len(payload), self.chunk_size):
|
|
84
|
+
asyncio.get_running_loop().call_soon(
|
|
85
|
+
self.notify, None, bytearray(payload[start : start + self.chunk_size])
|
|
86
|
+
)
|
|
87
|
+
|
|
88
|
+
async def _disconnect(self) -> None:
|
|
89
|
+
self.client.is_connected = False
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
@pytest.fixture
|
|
93
|
+
def cooker() -> Generator[FakeCooker]:
|
|
94
|
+
"""Patch connecting to return a fake cooker."""
|
|
95
|
+
fake = FakeCooker()
|
|
96
|
+
|
|
97
|
+
async def _connect(
|
|
98
|
+
_client_class: type,
|
|
99
|
+
_device: object,
|
|
100
|
+
_name: str,
|
|
101
|
+
disconnected_callback: Callable[[object], None],
|
|
102
|
+
**kwargs: object,
|
|
103
|
+
) -> MagicMock:
|
|
104
|
+
fake.disconnected = disconnected_callback
|
|
105
|
+
fake.client.is_connected = True
|
|
106
|
+
return fake.client
|
|
107
|
+
|
|
108
|
+
with (
|
|
109
|
+
patch.object(
|
|
110
|
+
client_module, "establish_connection", side_effect=_connect
|
|
111
|
+
) as connect,
|
|
112
|
+
patch.object(client_module, "CONNECT_SETTLE", 0),
|
|
113
|
+
):
|
|
114
|
+
fake.connect = connect
|
|
115
|
+
yield fake
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
@pytest.fixture
|
|
119
|
+
def anova() -> AnovaBLE:
|
|
120
|
+
"""Return a client for the fake cooker."""
|
|
121
|
+
return AnovaBLE(BLEDevice(ADDRESS, "Anova", None))
|
|
@@ -0,0 +1,353 @@
|
|
|
1
|
+
"""Test the Anova Bluetooth client against a fake cooker."""
|
|
2
|
+
|
|
3
|
+
import asyncio
|
|
4
|
+
from collections.abc import Awaitable, Callable
|
|
5
|
+
from unittest.mock import patch
|
|
6
|
+
|
|
7
|
+
import pytest
|
|
8
|
+
from bleak.backends.device import BLEDevice
|
|
9
|
+
from bleak.exc import BleakError
|
|
10
|
+
|
|
11
|
+
from pyanova_ble import (
|
|
12
|
+
AnovaBLE,
|
|
13
|
+
AnovaBLEError,
|
|
14
|
+
AnovaBLENotRunningError,
|
|
15
|
+
AnovaBLERejectedError,
|
|
16
|
+
AnovaDeviceInfo,
|
|
17
|
+
AnovaState,
|
|
18
|
+
AnovaStatus,
|
|
19
|
+
TemperatureUnit,
|
|
20
|
+
)
|
|
21
|
+
from pyanova_ble import client as client_module
|
|
22
|
+
|
|
23
|
+
from .conftest import ADDRESS, FakeCooker
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
async def test_get_state(cooker: FakeCooker, anova: AnovaBLE) -> None:
|
|
27
|
+
"""Test reading the state, reusing one connection."""
|
|
28
|
+
state = await anova.async_get_state()
|
|
29
|
+
assert state == AnovaState(
|
|
30
|
+
status=AnovaStatus.RUNNING,
|
|
31
|
+
unit=TemperatureUnit.CELSIUS,
|
|
32
|
+
target_temperature=56.5,
|
|
33
|
+
current_temperature=55.9,
|
|
34
|
+
timer_minutes=42,
|
|
35
|
+
timer_running=True,
|
|
36
|
+
calibration=0.0,
|
|
37
|
+
)
|
|
38
|
+
assert state.running
|
|
39
|
+
|
|
40
|
+
cooker.replies["status"] = "stopped"
|
|
41
|
+
cooker.replies["read unit"] = "F"
|
|
42
|
+
cooker.replies["read timer"] = "0 stopped"
|
|
43
|
+
state = await anova.async_get_state()
|
|
44
|
+
assert state.status is AnovaStatus.STOPPED
|
|
45
|
+
assert not state.running
|
|
46
|
+
assert state.unit is TemperatureUnit.FAHRENHEIT
|
|
47
|
+
assert state.timer_running is False
|
|
48
|
+
assert cooker.connect.call_count == 1
|
|
49
|
+
assert anova.is_connected
|
|
50
|
+
assert anova.address == ADDRESS
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
@pytest.mark.parametrize(
|
|
54
|
+
("reply", "status"),
|
|
55
|
+
[
|
|
56
|
+
pytest.param("low water", AnovaStatus.LOW_WATER, id="low_water"),
|
|
57
|
+
pytest.param("power loss", AnovaStatus.POWER_LOSS, id="power_loss"),
|
|
58
|
+
pytest.param("heater error", None, id="unknown"),
|
|
59
|
+
],
|
|
60
|
+
)
|
|
61
|
+
async def test_alarm_status(
|
|
62
|
+
cooker: FakeCooker, anova: AnovaBLE, reply: str, status: AnovaStatus | None
|
|
63
|
+
) -> None:
|
|
64
|
+
"""Test alarms and unknown statuses read as not running."""
|
|
65
|
+
cooker.replies["status"] = reply
|
|
66
|
+
state = await anova.async_get_state()
|
|
67
|
+
assert state.status is status
|
|
68
|
+
assert not state.running
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
async def test_reply_split_over_notifications(
|
|
72
|
+
cooker: FakeCooker, anova: AnovaBLE
|
|
73
|
+
) -> None:
|
|
74
|
+
"""Test a reply split over several notifications is joined."""
|
|
75
|
+
cooker.chunk_size = 3
|
|
76
|
+
state = await anova.async_get_state()
|
|
77
|
+
assert state.running
|
|
78
|
+
assert state.target_temperature == 56.5
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
async def test_get_device_info(cooker: FakeCooker, anova: AnovaBLE) -> None:
|
|
82
|
+
"""Test reading the firmware version and serial number."""
|
|
83
|
+
assert await anova.async_get_device_info() == AnovaDeviceInfo(
|
|
84
|
+
firmware_version="2.7.6", serial_number="f56-0123456789a"
|
|
85
|
+
)
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
@pytest.mark.parametrize(
|
|
89
|
+
("method", "commands"),
|
|
90
|
+
[
|
|
91
|
+
pytest.param("async_start", ["start"], id="start"),
|
|
92
|
+
pytest.param("async_stop", ["stop"], id="stop"),
|
|
93
|
+
pytest.param("async_stop_timer", ["stop time"], id="stop_timer"),
|
|
94
|
+
pytest.param("async_clear_alarm", ["clear alarm"], id="clear_alarm"),
|
|
95
|
+
],
|
|
96
|
+
)
|
|
97
|
+
async def test_echo_commands(
|
|
98
|
+
cooker: FakeCooker, anova: AnovaBLE, method: str, commands: list[str]
|
|
99
|
+
) -> None:
|
|
100
|
+
"""Test commands the cooker answers by repeating them."""
|
|
101
|
+
await getattr(anova, method)()
|
|
102
|
+
assert cooker.written == commands
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
@pytest.mark.parametrize(
|
|
106
|
+
("device_unit", "temperature", "unit", "command"),
|
|
107
|
+
[
|
|
108
|
+
pytest.param("c", 60.0, TemperatureUnit.CELSIUS, "set temp 60.0", id="c"),
|
|
109
|
+
pytest.param("f", 60.0, TemperatureUnit.CELSIUS, "set temp 140.0", id="c_to_f"),
|
|
110
|
+
pytest.param(
|
|
111
|
+
"c", 140.0, TemperatureUnit.FAHRENHEIT, "set temp 60.0", id="f_to_c"
|
|
112
|
+
),
|
|
113
|
+
],
|
|
114
|
+
)
|
|
115
|
+
async def test_set_target_temperature(
|
|
116
|
+
cooker: FakeCooker,
|
|
117
|
+
anova: AnovaBLE,
|
|
118
|
+
device_unit: str,
|
|
119
|
+
temperature: float,
|
|
120
|
+
unit: TemperatureUnit,
|
|
121
|
+
command: str,
|
|
122
|
+
) -> None:
|
|
123
|
+
"""Test the target is converted to the unit the cooker is set to."""
|
|
124
|
+
cooker.replies["read unit"] = device_unit
|
|
125
|
+
await anova.async_set_target_temperature(temperature, unit)
|
|
126
|
+
assert cooker.written == ["read unit", command]
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
async def test_set_unit(cooker: FakeCooker, anova: AnovaBLE) -> None:
|
|
130
|
+
"""Test switching the unit."""
|
|
131
|
+
await anova.async_set_unit(TemperatureUnit.FAHRENHEIT)
|
|
132
|
+
assert cooker.written == ["set unit f"]
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
async def test_set_calibration(cooker: FakeCooker, anova: AnovaBLE) -> None:
|
|
136
|
+
"""Test setting the calibration offset."""
|
|
137
|
+
await anova.async_set_calibration(-1.25)
|
|
138
|
+
assert cooker.written == ["cal -1.2"]
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
@pytest.mark.parametrize(
|
|
142
|
+
("minutes", "commands"),
|
|
143
|
+
[
|
|
144
|
+
pytest.param(90, ["status", "set timer 90", "start time"], id="new"),
|
|
145
|
+
pytest.param(None, ["status", "start time"], id="resume"),
|
|
146
|
+
],
|
|
147
|
+
)
|
|
148
|
+
async def test_start_timer(
|
|
149
|
+
cooker: FakeCooker, anova: AnovaBLE, minutes: int | None, commands: list[str]
|
|
150
|
+
) -> None:
|
|
151
|
+
"""Test starting a new timer or resuming a paused one."""
|
|
152
|
+
await anova.async_start_timer(minutes)
|
|
153
|
+
assert cooker.written == commands
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
async def test_start_timer_not_running(cooker: FakeCooker, anova: AnovaBLE) -> None:
|
|
157
|
+
"""Test the timer is not started while not cooking."""
|
|
158
|
+
cooker.replies["status"] = "stopped"
|
|
159
|
+
with pytest.raises(AnovaBLENotRunningError):
|
|
160
|
+
await anova.async_start_timer(90)
|
|
161
|
+
assert cooker.written == ["status"]
|
|
162
|
+
assert anova.is_connected
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
@pytest.mark.parametrize(
|
|
166
|
+
("prefix", "reply", "call", "match"),
|
|
167
|
+
[
|
|
168
|
+
pytest.param(
|
|
169
|
+
"set temp ",
|
|
170
|
+
"56.5",
|
|
171
|
+
lambda a: a.async_set_target_temperature(150.0, TemperatureUnit.CELSIUS),
|
|
172
|
+
"kept 56.5",
|
|
173
|
+
id="temperature",
|
|
174
|
+
),
|
|
175
|
+
pytest.param(
|
|
176
|
+
"set unit ",
|
|
177
|
+
"c",
|
|
178
|
+
lambda a: a.async_set_unit(TemperatureUnit.FAHRENHEIT),
|
|
179
|
+
"kept unit c",
|
|
180
|
+
id="unit",
|
|
181
|
+
),
|
|
182
|
+
pytest.param(
|
|
183
|
+
"set timer ",
|
|
184
|
+
"6000",
|
|
185
|
+
lambda a: a.async_start_timer(9999),
|
|
186
|
+
"6000 instead of 9999",
|
|
187
|
+
id="timer",
|
|
188
|
+
),
|
|
189
|
+
pytest.param(
|
|
190
|
+
"cal ",
|
|
191
|
+
"cal 9.9",
|
|
192
|
+
lambda a: a.async_set_calibration(12.0),
|
|
193
|
+
"kept calibration 9.9",
|
|
194
|
+
id="calibration",
|
|
195
|
+
),
|
|
196
|
+
],
|
|
197
|
+
)
|
|
198
|
+
async def test_value_rejected(
|
|
199
|
+
cooker: FakeCooker,
|
|
200
|
+
anova: AnovaBLE,
|
|
201
|
+
prefix: str,
|
|
202
|
+
reply: str,
|
|
203
|
+
call: Callable[[AnovaBLE], Awaitable[object]],
|
|
204
|
+
match: str,
|
|
205
|
+
) -> None:
|
|
206
|
+
"""Test the cooker keeping its old value raises, keeping the connection."""
|
|
207
|
+
cooker.set_replies[prefix] = reply
|
|
208
|
+
with pytest.raises(AnovaBLERejectedError, match=match):
|
|
209
|
+
await call(anova)
|
|
210
|
+
assert anova.is_connected
|
|
211
|
+
|
|
212
|
+
|
|
213
|
+
@pytest.mark.parametrize(
|
|
214
|
+
("command", "reply", "call"),
|
|
215
|
+
[
|
|
216
|
+
pytest.param("status", "c", lambda a: a.async_get_state(), id="status_unit"),
|
|
217
|
+
pytest.param(
|
|
218
|
+
"status", "56.5", lambda a: a.async_get_state(), id="status_number"
|
|
219
|
+
),
|
|
220
|
+
pytest.param("read unit", "x", lambda a: a.async_get_state(), id="unit"),
|
|
221
|
+
pytest.param(
|
|
222
|
+
"read temp", "low water", lambda a: a.async_get_state(), id="temperature"
|
|
223
|
+
),
|
|
224
|
+
pytest.param("read timer", "42", lambda a: a.async_get_state(), id="timer"),
|
|
225
|
+
pytest.param(
|
|
226
|
+
"read timer", "x running", lambda a: a.async_get_state(), id="timer_minutes"
|
|
227
|
+
),
|
|
228
|
+
pytest.param(
|
|
229
|
+
"version", "stopped", lambda a: a.async_get_device_info(), id="version"
|
|
230
|
+
),
|
|
231
|
+
pytest.param("start", "stopped", lambda a: a.async_start(), id="start"),
|
|
232
|
+
],
|
|
233
|
+
)
|
|
234
|
+
async def test_unexpected_reply(
|
|
235
|
+
cooker: FakeCooker,
|
|
236
|
+
anova: AnovaBLE,
|
|
237
|
+
command: str,
|
|
238
|
+
reply: str,
|
|
239
|
+
call: Callable[[AnovaBLE], Awaitable[object]],
|
|
240
|
+
) -> None:
|
|
241
|
+
"""Test an out-of-step reply raises and drops the connection."""
|
|
242
|
+
cooker.replies[command] = reply
|
|
243
|
+
with pytest.raises(AnovaBLEError, match="Unexpected"):
|
|
244
|
+
await call(anova)
|
|
245
|
+
cooker.client.disconnect.assert_awaited_once()
|
|
246
|
+
assert not anova.is_connected
|
|
247
|
+
|
|
248
|
+
|
|
249
|
+
async def test_calibration_reply_without_prefix(
|
|
250
|
+
cooker: FakeCooker, anova: AnovaBLE
|
|
251
|
+
) -> None:
|
|
252
|
+
"""Test a calibration reply that does not start with "cal " raises."""
|
|
253
|
+
cooker.set_replies["cal "] = "running"
|
|
254
|
+
with pytest.raises(AnovaBLEError, match="Unexpected"):
|
|
255
|
+
await anova.async_set_calibration(1.0)
|
|
256
|
+
assert not anova.is_connected
|
|
257
|
+
|
|
258
|
+
|
|
259
|
+
async def test_timer_reply_not_a_number(cooker: FakeCooker, anova: AnovaBLE) -> None:
|
|
260
|
+
"""Test a set timer reply that is not a number raises."""
|
|
261
|
+
cooker.set_replies["set timer "] = "stopped"
|
|
262
|
+
with pytest.raises(AnovaBLEError, match="whole number"):
|
|
263
|
+
await anova.async_start_timer(5)
|
|
264
|
+
assert not anova.is_connected
|
|
265
|
+
|
|
266
|
+
|
|
267
|
+
async def test_lost_link_released_before_reconnect(
|
|
268
|
+
cooker: FakeCooker, anova: AnovaBLE
|
|
269
|
+
) -> None:
|
|
270
|
+
"""Test a client whose link dropped is disconnected before connecting again."""
|
|
271
|
+
await anova.async_start()
|
|
272
|
+
cooker.client.is_connected = False
|
|
273
|
+
await anova.async_stop()
|
|
274
|
+
cooker.client.disconnect.assert_awaited_once()
|
|
275
|
+
assert cooker.connect.call_count == 2
|
|
276
|
+
|
|
277
|
+
|
|
278
|
+
async def test_no_reply_disconnects(cooker: FakeCooker, anova: AnovaBLE) -> None:
|
|
279
|
+
"""Test a missing reply closes the connection so a late one is not misread."""
|
|
280
|
+
cooker.replies["status"] = None
|
|
281
|
+
with (
|
|
282
|
+
patch.object(client_module, "COMMAND_TIMEOUT", 0),
|
|
283
|
+
pytest.raises(AnovaBLEError, match="No reply"),
|
|
284
|
+
):
|
|
285
|
+
await anova.async_get_state()
|
|
286
|
+
cooker.client.disconnect.assert_awaited_once()
|
|
287
|
+
assert not anova.is_connected
|
|
288
|
+
|
|
289
|
+
|
|
290
|
+
async def test_disconnect_while_waiting(cooker: FakeCooker, anova: AnovaBLE) -> None:
|
|
291
|
+
"""Test losing the connection while waiting for a reply raises."""
|
|
292
|
+
cooker.replies["status"] = None
|
|
293
|
+
task = asyncio.create_task(anova.async_get_state())
|
|
294
|
+
await asyncio.sleep(0)
|
|
295
|
+
await asyncio.sleep(0)
|
|
296
|
+
assert cooker.disconnected is not None
|
|
297
|
+
cooker.client.is_connected = False
|
|
298
|
+
cooker.disconnected(None)
|
|
299
|
+
with pytest.raises(AnovaBLEError, match="Disconnected"):
|
|
300
|
+
await task
|
|
301
|
+
|
|
302
|
+
|
|
303
|
+
async def test_unexpected_notification_ignored(
|
|
304
|
+
cooker: FakeCooker, anova: AnovaBLE
|
|
305
|
+
) -> None:
|
|
306
|
+
"""Test a notification with no command waiting is ignored."""
|
|
307
|
+
await anova.async_start()
|
|
308
|
+
assert cooker.notify is not None
|
|
309
|
+
cooker.notify(None, bytearray(b"stray\r"))
|
|
310
|
+
assert cooker.disconnected is not None
|
|
311
|
+
cooker.disconnected(None)
|
|
312
|
+
|
|
313
|
+
|
|
314
|
+
@pytest.mark.parametrize(
|
|
315
|
+
"error", [BleakError("boom"), TimeoutError()], ids=["bleak", "timeout"]
|
|
316
|
+
)
|
|
317
|
+
async def test_connect_error(
|
|
318
|
+
cooker: FakeCooker, anova: AnovaBLE, error: Exception
|
|
319
|
+
) -> None:
|
|
320
|
+
"""Test a failed connection raises."""
|
|
321
|
+
cooker.connect.side_effect = error
|
|
322
|
+
with pytest.raises(AnovaBLEError, match="Could not connect"):
|
|
323
|
+
await anova.async_start()
|
|
324
|
+
|
|
325
|
+
|
|
326
|
+
async def test_subscribe_error(cooker: FakeCooker, anova: AnovaBLE) -> None:
|
|
327
|
+
"""Test a device without the Anova characteristic raises and is released."""
|
|
328
|
+
cooker.client.start_notify.side_effect = BleakError("no characteristic")
|
|
329
|
+
with pytest.raises(AnovaBLEError, match="not an Anova"):
|
|
330
|
+
await anova.async_start()
|
|
331
|
+
cooker.client.disconnect.assert_awaited_once()
|
|
332
|
+
|
|
333
|
+
|
|
334
|
+
async def test_disconnect(cooker: FakeCooker, anova: AnovaBLE) -> None:
|
|
335
|
+
"""Test disconnecting, including errors and when never connected."""
|
|
336
|
+
await anova.async_disconnect()
|
|
337
|
+
cooker.client.disconnect.assert_not_called()
|
|
338
|
+
|
|
339
|
+
await anova.async_start()
|
|
340
|
+
cooker.client.disconnect.side_effect = BleakError("boom")
|
|
341
|
+
await anova.async_disconnect()
|
|
342
|
+
assert not anova.is_connected
|
|
343
|
+
|
|
344
|
+
|
|
345
|
+
async def test_set_ble_device_used_for_next_connection(
|
|
346
|
+
cooker: FakeCooker, anova: AnovaBLE
|
|
347
|
+
) -> None:
|
|
348
|
+
"""Test a newer device, e.g. via a closer proxy, is used to reconnect."""
|
|
349
|
+
new_device = BLEDevice(ADDRESS, "Anova", None)
|
|
350
|
+
anova.set_ble_device(new_device)
|
|
351
|
+
await anova.async_start()
|
|
352
|
+
assert cooker.connect.call_args.args[1] is new_device
|
|
353
|
+
assert cooker.connect.call_args.kwargs["ble_device_callback"]() is new_device
|