laifen-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.
- laifen_ble-0.1.0/.gitignore +12 -0
- laifen_ble-0.1.0/LICENSE +21 -0
- laifen_ble-0.1.0/PKG-INFO +97 -0
- laifen_ble-0.1.0/README.md +67 -0
- laifen_ble-0.1.0/pyproject.toml +71 -0
- laifen_ble-0.1.0/src/laifen_ble/__init__.py +31 -0
- laifen_ble-0.1.0/src/laifen_ble/const.py +7 -0
- laifen_ble-0.1.0/src/laifen_ble/device.py +158 -0
- laifen_ble-0.1.0/src/laifen_ble/exceptions.py +17 -0
- laifen_ble-0.1.0/src/laifen_ble/models.py +34 -0
- laifen_ble-0.1.0/src/laifen_ble/protocol.py +112 -0
- laifen_ble-0.1.0/src/laifen_ble/py.typed +0 -0
- laifen_ble-0.1.0/tests/test_device.py +291 -0
- laifen_ble-0.1.0/tests/test_init.py +18 -0
- laifen_ble-0.1.0/tests/test_protocol.py +147 -0
laifen_ble-0.1.0/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Jakub Znamenáček
|
|
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,97 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: laifen-ble
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Bluetooth LE library for Laifen Wave electric toothbrushes
|
|
5
|
+
Project-URL: Homepage, https://github.com/bzumik1/laifen-ble
|
|
6
|
+
Project-URL: Issues, https://github.com/bzumik1/laifen-ble/issues
|
|
7
|
+
Author: Jakub Znamenáček
|
|
8
|
+
License-Expression: MIT
|
|
9
|
+
License-File: LICENSE
|
|
10
|
+
Classifier: Development Status :: 3 - Alpha
|
|
11
|
+
Classifier: Framework :: AsyncIO
|
|
12
|
+
Classifier: Intended Audience :: Developers
|
|
13
|
+
Classifier: Operating System :: OS Independent
|
|
14
|
+
Classifier: Programming Language :: Python :: 3
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
18
|
+
Classifier: Topic :: Home Automation
|
|
19
|
+
Requires-Python: >=3.12
|
|
20
|
+
Requires-Dist: bleak-retry-connector>=3.5.0
|
|
21
|
+
Requires-Dist: bleak>=0.22.0
|
|
22
|
+
Provides-Extra: lint
|
|
23
|
+
Requires-Dist: mypy>=1.10.0; extra == 'lint'
|
|
24
|
+
Requires-Dist: ruff>=0.6.0; extra == 'lint'
|
|
25
|
+
Provides-Extra: test
|
|
26
|
+
Requires-Dist: pytest-asyncio>=0.24.0; extra == 'test'
|
|
27
|
+
Requires-Dist: pytest-cov>=5.0.0; extra == 'test'
|
|
28
|
+
Requires-Dist: pytest>=8.0.0; extra == 'test'
|
|
29
|
+
Description-Content-Type: text/markdown
|
|
30
|
+
|
|
31
|
+
# laifen-ble
|
|
32
|
+
|
|
33
|
+
Async Bluetooth LE library for the **Laifen Wave** electric toothbrush (`LFTB01-P`).
|
|
34
|
+
|
|
35
|
+
It reads the toothbrush state (active mode, per-mode settings, battery level, brushing time,
|
|
36
|
+
running state and feature flags) and, when its format is known, the firmware version. It is
|
|
37
|
+
built on [bleak](https://github.com/hbldh/bleak) and
|
|
38
|
+
[bleak-retry-connector](https://github.com/Bluetooth-Devices/bleak-retry-connector) and is
|
|
39
|
+
intended to be used by the Home Assistant `laifen` integration.
|
|
40
|
+
|
|
41
|
+
## Supported devices
|
|
42
|
+
|
|
43
|
+
| Model | Advertised name | Status |
|
|
44
|
+
|---|---|---|
|
|
45
|
+
| Laifen Wave (plastic, stainless steel and aluminium shells) | `LFTB01-P-xxxx` | Supported |
|
|
46
|
+
| Laifen Wave SE, Wave Pro and other models | `LFTB01-SE-…`, `LFTB02-…` | Not supported (different protocol) |
|
|
47
|
+
|
|
48
|
+
## Usage
|
|
49
|
+
|
|
50
|
+
```python
|
|
51
|
+
import asyncio
|
|
52
|
+
|
|
53
|
+
from bleak import BleakScanner
|
|
54
|
+
|
|
55
|
+
from laifen_ble import LaifenToothbrush, is_supported
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
async def main() -> None:
|
|
59
|
+
device = await BleakScanner.find_device_by_filter(
|
|
60
|
+
lambda device, advertisement: is_supported(advertisement.local_name)
|
|
61
|
+
)
|
|
62
|
+
toothbrush = LaifenToothbrush(device)
|
|
63
|
+
toothbrush.register_callback(lambda: print(toothbrush.state))
|
|
64
|
+
await toothbrush.connect()
|
|
65
|
+
print(toothbrush.firmware_version, toothbrush.state)
|
|
66
|
+
await asyncio.sleep(30)
|
|
67
|
+
await toothbrush.disconnect()
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
asyncio.run(main())
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
The toothbrush only advertises while it is awake (after a button press) and disconnects on its
|
|
74
|
+
own about a minute after the last activity. While connected it pushes its state on every change,
|
|
75
|
+
so registered callbacks are called whenever the state, the firmware version or the connection
|
|
76
|
+
changes.
|
|
77
|
+
|
|
78
|
+
## Protocol
|
|
79
|
+
|
|
80
|
+
The protocol was documented by
|
|
81
|
+
[marc-alexis-com/laifen-toolbox](https://github.com/marc-alexis-com/laifen-toolbox/blob/main/docs/PROTOCOL.md)
|
|
82
|
+
and earlier explored by [UrbanTechIO/Laifen](https://github.com/UrbanTechIO/Laifen). This
|
|
83
|
+
library only sends the documented read requests.
|
|
84
|
+
|
|
85
|
+
## Development
|
|
86
|
+
|
|
87
|
+
```bash
|
|
88
|
+
python -m venv .venv
|
|
89
|
+
. .venv/bin/activate
|
|
90
|
+
pip install -e '.[test,lint]'
|
|
91
|
+
pytest
|
|
92
|
+
ruff check . && ruff format --check . && mypy src
|
|
93
|
+
```
|
|
94
|
+
|
|
95
|
+
## License
|
|
96
|
+
|
|
97
|
+
MIT
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
# laifen-ble
|
|
2
|
+
|
|
3
|
+
Async Bluetooth LE library for the **Laifen Wave** electric toothbrush (`LFTB01-P`).
|
|
4
|
+
|
|
5
|
+
It reads the toothbrush state (active mode, per-mode settings, battery level, brushing time,
|
|
6
|
+
running state and feature flags) and, when its format is known, the firmware version. It is
|
|
7
|
+
built on [bleak](https://github.com/hbldh/bleak) and
|
|
8
|
+
[bleak-retry-connector](https://github.com/Bluetooth-Devices/bleak-retry-connector) and is
|
|
9
|
+
intended to be used by the Home Assistant `laifen` integration.
|
|
10
|
+
|
|
11
|
+
## Supported devices
|
|
12
|
+
|
|
13
|
+
| Model | Advertised name | Status |
|
|
14
|
+
|---|---|---|
|
|
15
|
+
| Laifen Wave (plastic, stainless steel and aluminium shells) | `LFTB01-P-xxxx` | Supported |
|
|
16
|
+
| Laifen Wave SE, Wave Pro and other models | `LFTB01-SE-…`, `LFTB02-…` | Not supported (different protocol) |
|
|
17
|
+
|
|
18
|
+
## Usage
|
|
19
|
+
|
|
20
|
+
```python
|
|
21
|
+
import asyncio
|
|
22
|
+
|
|
23
|
+
from bleak import BleakScanner
|
|
24
|
+
|
|
25
|
+
from laifen_ble import LaifenToothbrush, is_supported
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
async def main() -> None:
|
|
29
|
+
device = await BleakScanner.find_device_by_filter(
|
|
30
|
+
lambda device, advertisement: is_supported(advertisement.local_name)
|
|
31
|
+
)
|
|
32
|
+
toothbrush = LaifenToothbrush(device)
|
|
33
|
+
toothbrush.register_callback(lambda: print(toothbrush.state))
|
|
34
|
+
await toothbrush.connect()
|
|
35
|
+
print(toothbrush.firmware_version, toothbrush.state)
|
|
36
|
+
await asyncio.sleep(30)
|
|
37
|
+
await toothbrush.disconnect()
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
asyncio.run(main())
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
The toothbrush only advertises while it is awake (after a button press) and disconnects on its
|
|
44
|
+
own about a minute after the last activity. While connected it pushes its state on every change,
|
|
45
|
+
so registered callbacks are called whenever the state, the firmware version or the connection
|
|
46
|
+
changes.
|
|
47
|
+
|
|
48
|
+
## Protocol
|
|
49
|
+
|
|
50
|
+
The protocol was documented by
|
|
51
|
+
[marc-alexis-com/laifen-toolbox](https://github.com/marc-alexis-com/laifen-toolbox/blob/main/docs/PROTOCOL.md)
|
|
52
|
+
and earlier explored by [UrbanTechIO/Laifen](https://github.com/UrbanTechIO/Laifen). This
|
|
53
|
+
library only sends the documented read requests.
|
|
54
|
+
|
|
55
|
+
## Development
|
|
56
|
+
|
|
57
|
+
```bash
|
|
58
|
+
python -m venv .venv
|
|
59
|
+
. .venv/bin/activate
|
|
60
|
+
pip install -e '.[test,lint]'
|
|
61
|
+
pytest
|
|
62
|
+
ruff check . && ruff format --check . && mypy src
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
## License
|
|
66
|
+
|
|
67
|
+
MIT
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["hatchling>=1.27.0"]
|
|
3
|
+
build-backend = "hatchling.build"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "laifen-ble"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "Bluetooth LE library for Laifen Wave electric toothbrushes"
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
license = "MIT"
|
|
11
|
+
license-files = ["LICENSE"]
|
|
12
|
+
authors = [{ name = "Jakub Znamenáček" }]
|
|
13
|
+
requires-python = ">=3.12"
|
|
14
|
+
classifiers = [
|
|
15
|
+
"Development Status :: 3 - Alpha",
|
|
16
|
+
"Framework :: AsyncIO",
|
|
17
|
+
"Intended Audience :: Developers",
|
|
18
|
+
"Operating System :: OS Independent",
|
|
19
|
+
"Programming Language :: Python :: 3",
|
|
20
|
+
"Programming Language :: Python :: 3.12",
|
|
21
|
+
"Programming Language :: Python :: 3.13",
|
|
22
|
+
"Programming Language :: Python :: 3.14",
|
|
23
|
+
"Topic :: Home Automation",
|
|
24
|
+
]
|
|
25
|
+
dependencies = [
|
|
26
|
+
"bleak>=0.22.0",
|
|
27
|
+
"bleak-retry-connector>=3.5.0",
|
|
28
|
+
]
|
|
29
|
+
|
|
30
|
+
[project.optional-dependencies]
|
|
31
|
+
test = [
|
|
32
|
+
"pytest>=8.0.0",
|
|
33
|
+
"pytest-asyncio>=0.24.0",
|
|
34
|
+
"pytest-cov>=5.0.0",
|
|
35
|
+
]
|
|
36
|
+
lint = [
|
|
37
|
+
"mypy>=1.10.0",
|
|
38
|
+
"ruff>=0.6.0",
|
|
39
|
+
]
|
|
40
|
+
|
|
41
|
+
[project.urls]
|
|
42
|
+
Homepage = "https://github.com/bzumik1/laifen-ble"
|
|
43
|
+
Issues = "https://github.com/bzumik1/laifen-ble/issues"
|
|
44
|
+
|
|
45
|
+
[tool.hatch.build.targets.sdist]
|
|
46
|
+
include = ["src", "tests", "README.md", "LICENSE"]
|
|
47
|
+
|
|
48
|
+
[tool.hatch.build.targets.wheel]
|
|
49
|
+
packages = ["src/laifen_ble"]
|
|
50
|
+
|
|
51
|
+
[tool.pytest.ini_options]
|
|
52
|
+
asyncio_mode = "auto"
|
|
53
|
+
asyncio_default_fixture_loop_scope = "function"
|
|
54
|
+
testpaths = ["tests"]
|
|
55
|
+
addopts = "--cov=laifen_ble --cov-report=term-missing"
|
|
56
|
+
|
|
57
|
+
[tool.ruff]
|
|
58
|
+
target-version = "py312"
|
|
59
|
+
src = ["src", "tests"]
|
|
60
|
+
|
|
61
|
+
[tool.ruff.lint]
|
|
62
|
+
select = ["E", "F", "W", "I", "B", "UP", "SIM", "RUF", "PL", "ASYNC"]
|
|
63
|
+
ignore = ["PLR2004"]
|
|
64
|
+
|
|
65
|
+
[tool.ruff.lint.isort]
|
|
66
|
+
force-sort-within-sections = true
|
|
67
|
+
combine-as-imports = true
|
|
68
|
+
|
|
69
|
+
[tool.mypy]
|
|
70
|
+
strict = true
|
|
71
|
+
python_version = "3.12"
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from .const import LOCAL_NAME_PREFIX, MANUFACTURER_ID, SERVICE_UUID
|
|
4
|
+
from .device import LaifenToothbrush
|
|
5
|
+
from .exceptions import (
|
|
6
|
+
InvalidFrameError,
|
|
7
|
+
LaifenConnectionError,
|
|
8
|
+
LaifenError,
|
|
9
|
+
UnsupportedStateError,
|
|
10
|
+
)
|
|
11
|
+
from .models import LaifenState, Mode, ModeSettings
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def is_supported(local_name: str | None) -> bool:
|
|
15
|
+
return local_name is not None and local_name.startswith(LOCAL_NAME_PREFIX)
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
__all__ = [
|
|
19
|
+
"LOCAL_NAME_PREFIX",
|
|
20
|
+
"MANUFACTURER_ID",
|
|
21
|
+
"SERVICE_UUID",
|
|
22
|
+
"InvalidFrameError",
|
|
23
|
+
"LaifenConnectionError",
|
|
24
|
+
"LaifenError",
|
|
25
|
+
"LaifenState",
|
|
26
|
+
"LaifenToothbrush",
|
|
27
|
+
"Mode",
|
|
28
|
+
"ModeSettings",
|
|
29
|
+
"UnsupportedStateError",
|
|
30
|
+
"is_supported",
|
|
31
|
+
]
|
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import asyncio
|
|
4
|
+
from collections.abc import Callable
|
|
5
|
+
import logging
|
|
6
|
+
|
|
7
|
+
from bleak.backends.characteristic import BleakGATTCharacteristic
|
|
8
|
+
from bleak.backends.device import BLEDevice
|
|
9
|
+
from bleak.exc import BleakError
|
|
10
|
+
from bleak_retry_connector import BleakClientWithServiceCache, establish_connection
|
|
11
|
+
|
|
12
|
+
from .const import CHARACTERISTIC_UUID, STATE_TIMEOUT
|
|
13
|
+
from .exceptions import InvalidFrameError, LaifenConnectionError
|
|
14
|
+
from .models import LaifenState
|
|
15
|
+
from .protocol import (
|
|
16
|
+
READ_STATE,
|
|
17
|
+
Command,
|
|
18
|
+
Kind,
|
|
19
|
+
decode_frame,
|
|
20
|
+
decode_state,
|
|
21
|
+
decode_version,
|
|
22
|
+
)
|
|
23
|
+
|
|
24
|
+
_LOGGER = logging.getLogger(__name__)
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class LaifenToothbrush:
|
|
28
|
+
def __init__(self, address_or_ble_device: BLEDevice | str) -> None:
|
|
29
|
+
if isinstance(address_or_ble_device, BLEDevice):
|
|
30
|
+
self._address = address_or_ble_device.address
|
|
31
|
+
self._ble_device: BLEDevice | None = address_or_ble_device
|
|
32
|
+
else:
|
|
33
|
+
self._address = address_or_ble_device
|
|
34
|
+
self._ble_device = None
|
|
35
|
+
self._client: BleakClientWithServiceCache | None = None
|
|
36
|
+
self._connect_lock = asyncio.Lock()
|
|
37
|
+
self._callbacks: list[Callable[[], None]] = []
|
|
38
|
+
self._state: LaifenState | None = None
|
|
39
|
+
self._firmware_version: str | None = None
|
|
40
|
+
self._state_received = asyncio.Event()
|
|
41
|
+
|
|
42
|
+
@property
|
|
43
|
+
def address(self) -> str:
|
|
44
|
+
return self._address
|
|
45
|
+
|
|
46
|
+
@property
|
|
47
|
+
def name(self) -> str:
|
|
48
|
+
if self._ble_device is not None and self._ble_device.name:
|
|
49
|
+
return self._ble_device.name
|
|
50
|
+
return self._address
|
|
51
|
+
|
|
52
|
+
@property
|
|
53
|
+
def connected(self) -> bool:
|
|
54
|
+
return self._client is not None and self._client.is_connected
|
|
55
|
+
|
|
56
|
+
@property
|
|
57
|
+
def state(self) -> LaifenState | None:
|
|
58
|
+
return self._state
|
|
59
|
+
|
|
60
|
+
@property
|
|
61
|
+
def firmware_version(self) -> str | None:
|
|
62
|
+
return self._firmware_version
|
|
63
|
+
|
|
64
|
+
def set_ble_device(self, ble_device: BLEDevice) -> None:
|
|
65
|
+
self._ble_device = ble_device
|
|
66
|
+
|
|
67
|
+
def register_callback(self, callback: Callable[[], None]) -> Callable[[], None]:
|
|
68
|
+
self._callbacks.append(callback)
|
|
69
|
+
|
|
70
|
+
def unregister() -> None:
|
|
71
|
+
self._callbacks.remove(callback)
|
|
72
|
+
|
|
73
|
+
return unregister
|
|
74
|
+
|
|
75
|
+
async def connect(self) -> None:
|
|
76
|
+
async with self._connect_lock:
|
|
77
|
+
if self.connected:
|
|
78
|
+
return
|
|
79
|
+
ble_device = self._ble_device
|
|
80
|
+
if ble_device is None:
|
|
81
|
+
raise LaifenConnectionError(f"{self.name} has not been seen yet")
|
|
82
|
+
try:
|
|
83
|
+
client = await establish_connection(
|
|
84
|
+
BleakClientWithServiceCache,
|
|
85
|
+
ble_device,
|
|
86
|
+
self.name,
|
|
87
|
+
disconnected_callback=self._handle_disconnect,
|
|
88
|
+
ble_device_callback=lambda: self._ble_device or ble_device,
|
|
89
|
+
)
|
|
90
|
+
except (BleakError, TimeoutError) as err:
|
|
91
|
+
raise LaifenConnectionError(
|
|
92
|
+
f"Failed to connect to {self.name}: {err}"
|
|
93
|
+
) from err
|
|
94
|
+
self._client = client
|
|
95
|
+
self._state_received.clear()
|
|
96
|
+
try:
|
|
97
|
+
await client.start_notify(
|
|
98
|
+
CHARACTERISTIC_UUID, self._handle_notification
|
|
99
|
+
)
|
|
100
|
+
await client.write_gatt_char(
|
|
101
|
+
CHARACTERISTIC_UUID, READ_STATE, response=True
|
|
102
|
+
)
|
|
103
|
+
async with asyncio.timeout(STATE_TIMEOUT):
|
|
104
|
+
await self._state_received.wait()
|
|
105
|
+
except (BleakError, TimeoutError) as err:
|
|
106
|
+
await self._disconnect_client()
|
|
107
|
+
raise LaifenConnectionError(
|
|
108
|
+
f"Failed to read the state of {self.name}: {err}"
|
|
109
|
+
) from err
|
|
110
|
+
self._notify_callbacks()
|
|
111
|
+
|
|
112
|
+
async def disconnect(self) -> None:
|
|
113
|
+
async with self._connect_lock:
|
|
114
|
+
await self._disconnect_client()
|
|
115
|
+
|
|
116
|
+
async def _disconnect_client(self) -> None:
|
|
117
|
+
client = self._client
|
|
118
|
+
self._client = None
|
|
119
|
+
if client is None:
|
|
120
|
+
return
|
|
121
|
+
try:
|
|
122
|
+
await client.disconnect()
|
|
123
|
+
except BleakError as err:
|
|
124
|
+
_LOGGER.debug("%s: Error while disconnecting: %s", self.name, err)
|
|
125
|
+
|
|
126
|
+
def _handle_disconnect(self, client: BleakClientWithServiceCache) -> None:
|
|
127
|
+
if client is not self._client:
|
|
128
|
+
return
|
|
129
|
+
_LOGGER.debug("%s: Disconnected", self.name)
|
|
130
|
+
self._client = None
|
|
131
|
+
self._notify_callbacks()
|
|
132
|
+
|
|
133
|
+
def _handle_notification(
|
|
134
|
+
self, _characteristic: BleakGATTCharacteristic, data: bytearray
|
|
135
|
+
) -> None:
|
|
136
|
+
try:
|
|
137
|
+
frame = decode_frame(bytes(data))
|
|
138
|
+
except InvalidFrameError as err:
|
|
139
|
+
_LOGGER.debug("%s: Ignoring frame: %s", self.name, err)
|
|
140
|
+
return
|
|
141
|
+
if frame.kind != Kind.REPORT:
|
|
142
|
+
return
|
|
143
|
+
if frame.command == Command.STATE:
|
|
144
|
+
try:
|
|
145
|
+
self._state = decode_state(frame.payload)
|
|
146
|
+
except InvalidFrameError as err:
|
|
147
|
+
_LOGGER.debug("%s: Ignoring state: %s", self.name, err)
|
|
148
|
+
return
|
|
149
|
+
self._state_received.set()
|
|
150
|
+
elif frame.command == Command.VERSION:
|
|
151
|
+
self._firmware_version = decode_version(frame.payload)
|
|
152
|
+
else:
|
|
153
|
+
return
|
|
154
|
+
self._notify_callbacks()
|
|
155
|
+
|
|
156
|
+
def _notify_callbacks(self) -> None:
|
|
157
|
+
for callback in list(self._callbacks):
|
|
158
|
+
callback()
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
class LaifenError(Exception):
|
|
5
|
+
pass
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class LaifenConnectionError(LaifenError):
|
|
9
|
+
pass
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class InvalidFrameError(LaifenError):
|
|
13
|
+
pass
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class UnsupportedStateError(InvalidFrameError):
|
|
17
|
+
pass
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from dataclasses import dataclass
|
|
4
|
+
from enum import IntEnum
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
class Mode(IntEnum):
|
|
8
|
+
MODE_1 = 0
|
|
9
|
+
MODE_2 = 1
|
|
10
|
+
MODE_3 = 2
|
|
11
|
+
HIGH_FREQUENCY = 3
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
@dataclass(frozen=True, slots=True)
|
|
15
|
+
class ModeSettings:
|
|
16
|
+
strength: int
|
|
17
|
+
range: int
|
|
18
|
+
speed: int
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
@dataclass(frozen=True, slots=True)
|
|
22
|
+
class LaifenState:
|
|
23
|
+
mode: Mode
|
|
24
|
+
mode_settings: dict[Mode, ModeSettings]
|
|
25
|
+
airplane_mode: bool
|
|
26
|
+
battery_level: int
|
|
27
|
+
reminder_30s: bool
|
|
28
|
+
brushing_time: int
|
|
29
|
+
high_frequency: bool
|
|
30
|
+
running: bool
|
|
31
|
+
|
|
32
|
+
@property
|
|
33
|
+
def active_mode_settings(self) -> ModeSettings:
|
|
34
|
+
return self.mode_settings[self.mode]
|
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from dataclasses import dataclass
|
|
4
|
+
from enum import IntEnum
|
|
5
|
+
|
|
6
|
+
from .exceptions import InvalidFrameError, UnsupportedStateError
|
|
7
|
+
from .models import LaifenState, Mode, ModeSettings
|
|
8
|
+
|
|
9
|
+
HEADER = 0xAA
|
|
10
|
+
MINIMUM_FRAME_LENGTH = 5
|
|
11
|
+
SUPPORTED_STATE_LENGTHS = (20, 21, 23)
|
|
12
|
+
VERSION_LENGTH = 9
|
|
13
|
+
VERSION_LETTER_INDEX = 3
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class Command(IntEnum):
|
|
17
|
+
VERSION = 0x01
|
|
18
|
+
STATE = 0x0A
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class Kind(IntEnum):
|
|
22
|
+
READ = 0x00
|
|
23
|
+
WRITE = 0x01
|
|
24
|
+
REPORT = 0x02
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
@dataclass(frozen=True, slots=True)
|
|
28
|
+
class Frame:
|
|
29
|
+
command: int
|
|
30
|
+
kind: int
|
|
31
|
+
payload: bytes
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def checksum(data: bytes) -> int:
|
|
35
|
+
result = 0
|
|
36
|
+
for byte in data:
|
|
37
|
+
result ^= byte
|
|
38
|
+
return result
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def encode_frame(command: Command, kind: Kind, payload: bytes = b"") -> bytes:
|
|
42
|
+
body = bytes((HEADER, command, kind, len(payload))) + payload
|
|
43
|
+
return body + bytes((checksum(body),))
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def decode_frame(data: bytes) -> Frame:
|
|
47
|
+
if len(data) < MINIMUM_FRAME_LENGTH:
|
|
48
|
+
raise InvalidFrameError(f"Frame too short: {data.hex()}")
|
|
49
|
+
if data[0] != HEADER:
|
|
50
|
+
raise InvalidFrameError(f"Unexpected header: {data.hex()}")
|
|
51
|
+
if len(data) != MINIMUM_FRAME_LENGTH + data[3]:
|
|
52
|
+
raise InvalidFrameError(f"Length mismatch: {data.hex()}")
|
|
53
|
+
if checksum(data[:-1]) != data[-1]:
|
|
54
|
+
raise InvalidFrameError(f"Checksum mismatch: {data.hex()}")
|
|
55
|
+
return Frame(command=data[1], kind=data[2], payload=bytes(data[4:-1]))
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def _flag(value: int) -> bool:
|
|
59
|
+
return value == 0x01
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def _mode_settings(payload: bytes, offset: int) -> ModeSettings:
|
|
63
|
+
return ModeSettings(
|
|
64
|
+
strength=payload[offset],
|
|
65
|
+
range=payload[offset + 1],
|
|
66
|
+
speed=payload[offset + 2],
|
|
67
|
+
)
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def decode_state(payload: bytes) -> LaifenState:
|
|
71
|
+
if len(payload) not in SUPPORTED_STATE_LENGTHS:
|
|
72
|
+
raise UnsupportedStateError(f"Unsupported state length {len(payload)}")
|
|
73
|
+
try:
|
|
74
|
+
mode = Mode(payload[0])
|
|
75
|
+
except ValueError as err:
|
|
76
|
+
raise InvalidFrameError(f"Unknown mode {payload[0]}") from err
|
|
77
|
+
return LaifenState(
|
|
78
|
+
mode=mode,
|
|
79
|
+
mode_settings={
|
|
80
|
+
Mode.MODE_1: _mode_settings(payload, 1),
|
|
81
|
+
Mode.MODE_2: _mode_settings(payload, 4),
|
|
82
|
+
Mode.MODE_3: _mode_settings(payload, 7),
|
|
83
|
+
Mode.HIGH_FREQUENCY: _mode_settings(payload, 10),
|
|
84
|
+
},
|
|
85
|
+
airplane_mode=_flag(payload[13]),
|
|
86
|
+
battery_level=payload[14],
|
|
87
|
+
reminder_30s=_flag(payload[15]),
|
|
88
|
+
brushing_time=int.from_bytes(payload[16:18], "big"),
|
|
89
|
+
high_frequency=_flag(payload[18]),
|
|
90
|
+
running=_flag(payload[19]),
|
|
91
|
+
)
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def _signed(value: int) -> int:
|
|
95
|
+
return value - 0x100 if value > 0x7F else value
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def decode_version(payload: bytes) -> str | None:
|
|
99
|
+
if len(payload) != VERSION_LENGTH:
|
|
100
|
+
return None
|
|
101
|
+
parts = [
|
|
102
|
+
chr(byte) if index == VERSION_LETTER_INDEX else str(_signed(byte))
|
|
103
|
+
for index, byte in enumerate(payload)
|
|
104
|
+
]
|
|
105
|
+
return (
|
|
106
|
+
f"V{parts[0]}.{parts[1]}.{parts[2]}."
|
|
107
|
+
f"{parts[3]}{parts[4]}{parts[5]}.{parts[6]}{parts[7]}{parts[8]}"
|
|
108
|
+
)
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
READ_STATE = encode_frame(Command.STATE, Kind.READ)
|
|
112
|
+
READ_VERSION = encode_frame(Command.VERSION, Kind.READ)
|
|
File without changes
|
|
@@ -0,0 +1,291 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from collections.abc import Callable, Generator
|
|
4
|
+
from typing import Any
|
|
5
|
+
from unittest.mock import AsyncMock, MagicMock, patch
|
|
6
|
+
|
|
7
|
+
from bleak.backends.device import BLEDevice
|
|
8
|
+
from bleak.exc import BleakError
|
|
9
|
+
import pytest
|
|
10
|
+
|
|
11
|
+
from laifen_ble import LaifenConnectionError, LaifenToothbrush, Mode
|
|
12
|
+
from laifen_ble.const import CHARACTERISTIC_UUID
|
|
13
|
+
from laifen_ble.protocol import READ_STATE
|
|
14
|
+
|
|
15
|
+
STATE_FRAME = bytes.fromhex("aa0a021400010a070a0a0a040a0a140101005d010078010085")
|
|
16
|
+
VERSION_FRAME = bytes.fromhex("aa010209020008590404030003f3")
|
|
17
|
+
ACK_FRAME = bytes.fromhex("aa05020100ac")
|
|
18
|
+
READ_REQUEST_FRAME = bytes.fromhex("aa0a0000a0")
|
|
19
|
+
ADDRESS = "C0:00:00:00:A2:20"
|
|
20
|
+
NAME = "LFTB01-P-A220"
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class FakeClient:
|
|
24
|
+
def __init__(self, respond: bool = True) -> None:
|
|
25
|
+
self.is_connected = True
|
|
26
|
+
self.respond = respond
|
|
27
|
+
self.notify_callback: Callable[[Any, bytearray], None] | None = None
|
|
28
|
+
self.disconnected_callback: Callable[[Any], None] | None = None
|
|
29
|
+
self.start_notify = AsyncMock(side_effect=self._start_notify)
|
|
30
|
+
self.write_gatt_char = AsyncMock(side_effect=self._write)
|
|
31
|
+
self.disconnect = AsyncMock(side_effect=self._disconnect)
|
|
32
|
+
|
|
33
|
+
async def _start_notify(
|
|
34
|
+
self, _uuid: str, callback: Callable[[Any, bytearray], None]
|
|
35
|
+
) -> None:
|
|
36
|
+
self.notify_callback = callback
|
|
37
|
+
self.notify(VERSION_FRAME)
|
|
38
|
+
|
|
39
|
+
async def _write(self, _uuid: str, data: bytes, response: bool) -> None:
|
|
40
|
+
if self.respond and data == READ_STATE:
|
|
41
|
+
self.notify(STATE_FRAME)
|
|
42
|
+
|
|
43
|
+
async def _disconnect(self) -> None:
|
|
44
|
+
self.is_connected = False
|
|
45
|
+
|
|
46
|
+
def notify(self, data: bytes) -> None:
|
|
47
|
+
assert self.notify_callback is not None
|
|
48
|
+
self.notify_callback(MagicMock(), bytearray(data))
|
|
49
|
+
|
|
50
|
+
def drop(self) -> None:
|
|
51
|
+
self.is_connected = False
|
|
52
|
+
assert self.disconnected_callback is not None
|
|
53
|
+
self.disconnected_callback(self)
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
@pytest.fixture(autouse=True)
|
|
57
|
+
def short_state_timeout() -> Generator[None]:
|
|
58
|
+
with patch("laifen_ble.device.STATE_TIMEOUT", 0.01):
|
|
59
|
+
yield
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
@pytest.fixture
|
|
63
|
+
def ble_device() -> BLEDevice:
|
|
64
|
+
return BLEDevice(ADDRESS, NAME, details=None)
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
@pytest.fixture
|
|
68
|
+
def client() -> FakeClient:
|
|
69
|
+
return FakeClient()
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
@pytest.fixture
|
|
73
|
+
def establish(client: FakeClient) -> Generator[AsyncMock]:
|
|
74
|
+
async def _establish(*_args: Any, **kwargs: Any) -> FakeClient:
|
|
75
|
+
client.disconnected_callback = kwargs["disconnected_callback"]
|
|
76
|
+
return client
|
|
77
|
+
|
|
78
|
+
with patch(
|
|
79
|
+
"laifen_ble.device.establish_connection", side_effect=_establish
|
|
80
|
+
) as mock:
|
|
81
|
+
yield mock
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
async def test_connect_reads_state(
|
|
85
|
+
ble_device: BLEDevice, client: FakeClient, establish: AsyncMock
|
|
86
|
+
) -> None:
|
|
87
|
+
toothbrush = LaifenToothbrush(ble_device)
|
|
88
|
+
callback = MagicMock()
|
|
89
|
+
toothbrush.register_callback(callback)
|
|
90
|
+
|
|
91
|
+
await toothbrush.connect()
|
|
92
|
+
|
|
93
|
+
assert toothbrush.connected
|
|
94
|
+
assert toothbrush.address == ADDRESS
|
|
95
|
+
assert toothbrush.name == NAME
|
|
96
|
+
assert toothbrush.firmware_version == "V2.0.8.Y44.303"
|
|
97
|
+
assert toothbrush.state is not None
|
|
98
|
+
assert toothbrush.state.battery_level == 93
|
|
99
|
+
assert toothbrush.state.mode is Mode.MODE_1
|
|
100
|
+
client.write_gatt_char.assert_awaited_once_with(
|
|
101
|
+
CHARACTERISTIC_UUID, READ_REQUEST_FRAME, response=True
|
|
102
|
+
)
|
|
103
|
+
assert callback.call_count == 3
|
|
104
|
+
assert establish.call_args.kwargs["ble_device_callback"]() is ble_device
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
async def test_connect_when_connected_is_noop(
|
|
108
|
+
ble_device: BLEDevice, establish: AsyncMock
|
|
109
|
+
) -> None:
|
|
110
|
+
toothbrush = LaifenToothbrush(ble_device)
|
|
111
|
+
await toothbrush.connect()
|
|
112
|
+
await toothbrush.connect()
|
|
113
|
+
assert establish.await_count == 1
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
async def test_connect_failure(ble_device: BLEDevice) -> None:
|
|
117
|
+
toothbrush = LaifenToothbrush(ble_device)
|
|
118
|
+
with (
|
|
119
|
+
patch(
|
|
120
|
+
"laifen_ble.device.establish_connection",
|
|
121
|
+
side_effect=BleakError("out of slots"),
|
|
122
|
+
),
|
|
123
|
+
pytest.raises(LaifenConnectionError),
|
|
124
|
+
):
|
|
125
|
+
await toothbrush.connect()
|
|
126
|
+
assert not toothbrush.connected
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
async def test_connect_state_timeout(
|
|
130
|
+
ble_device: BLEDevice, establish: AsyncMock
|
|
131
|
+
) -> None:
|
|
132
|
+
silent_client = FakeClient(respond=False)
|
|
133
|
+
|
|
134
|
+
async def _establish(*_args: Any, **kwargs: Any) -> FakeClient:
|
|
135
|
+
silent_client.disconnected_callback = kwargs["disconnected_callback"]
|
|
136
|
+
return silent_client
|
|
137
|
+
|
|
138
|
+
establish.side_effect = _establish
|
|
139
|
+
toothbrush = LaifenToothbrush(ble_device)
|
|
140
|
+
|
|
141
|
+
with pytest.raises(LaifenConnectionError):
|
|
142
|
+
await toothbrush.connect()
|
|
143
|
+
|
|
144
|
+
assert not toothbrush.connected
|
|
145
|
+
silent_client.disconnect.assert_awaited_once()
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
async def test_connect_disconnect_error_is_ignored(
|
|
149
|
+
ble_device: BLEDevice, establish: AsyncMock
|
|
150
|
+
) -> None:
|
|
151
|
+
silent_client = FakeClient(respond=False)
|
|
152
|
+
silent_client.disconnect.side_effect = BleakError("gone")
|
|
153
|
+
|
|
154
|
+
async def _establish(*_args: Any, **kwargs: Any) -> FakeClient:
|
|
155
|
+
return silent_client
|
|
156
|
+
|
|
157
|
+
establish.side_effect = _establish
|
|
158
|
+
toothbrush = LaifenToothbrush(ble_device)
|
|
159
|
+
|
|
160
|
+
with pytest.raises(LaifenConnectionError):
|
|
161
|
+
await toothbrush.connect()
|
|
162
|
+
|
|
163
|
+
assert not toothbrush.connected
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
async def test_pushed_state_updates(
|
|
167
|
+
ble_device: BLEDevice, client: FakeClient, establish: AsyncMock
|
|
168
|
+
) -> None:
|
|
169
|
+
toothbrush = LaifenToothbrush(ble_device)
|
|
170
|
+
await toothbrush.connect()
|
|
171
|
+
callback = MagicMock()
|
|
172
|
+
toothbrush.register_callback(callback)
|
|
173
|
+
|
|
174
|
+
running = bytearray(STATE_FRAME)
|
|
175
|
+
running[23] = 0x01
|
|
176
|
+
running[-1] ^= 0x01
|
|
177
|
+
client.notify(bytes(running))
|
|
178
|
+
|
|
179
|
+
assert toothbrush.state is not None
|
|
180
|
+
assert toothbrush.state.running is True
|
|
181
|
+
callback.assert_called_once()
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
@pytest.mark.parametrize(
|
|
185
|
+
"frame",
|
|
186
|
+
[
|
|
187
|
+
ACK_FRAME,
|
|
188
|
+
bytes.fromhex("aa0a0000a0"),
|
|
189
|
+
bytes.fromhex("0102030405060702ff2a"),
|
|
190
|
+
bytes.fromhex("aa0a020f") + bytes(15) + bytes((0xAA ^ 0x0A ^ 0x02 ^ 0x0F,)),
|
|
191
|
+
],
|
|
192
|
+
ids=["ack", "request_echo", "filler", "unsupported_state"],
|
|
193
|
+
)
|
|
194
|
+
async def test_ignored_frames(
|
|
195
|
+
ble_device: BLEDevice, client: FakeClient, establish: AsyncMock, frame: bytes
|
|
196
|
+
) -> None:
|
|
197
|
+
toothbrush = LaifenToothbrush(ble_device)
|
|
198
|
+
await toothbrush.connect()
|
|
199
|
+
state = toothbrush.state
|
|
200
|
+
callback = MagicMock()
|
|
201
|
+
toothbrush.register_callback(callback)
|
|
202
|
+
|
|
203
|
+
client.notify(frame)
|
|
204
|
+
|
|
205
|
+
assert toothbrush.state is state
|
|
206
|
+
callback.assert_not_called()
|
|
207
|
+
|
|
208
|
+
|
|
209
|
+
async def test_unexpected_disconnect(
|
|
210
|
+
ble_device: BLEDevice, client: FakeClient, establish: AsyncMock
|
|
211
|
+
) -> None:
|
|
212
|
+
toothbrush = LaifenToothbrush(ble_device)
|
|
213
|
+
await toothbrush.connect()
|
|
214
|
+
callback = MagicMock()
|
|
215
|
+
toothbrush.register_callback(callback)
|
|
216
|
+
|
|
217
|
+
client.drop()
|
|
218
|
+
|
|
219
|
+
assert not toothbrush.connected
|
|
220
|
+
assert toothbrush.state is not None
|
|
221
|
+
callback.assert_called_once()
|
|
222
|
+
|
|
223
|
+
|
|
224
|
+
async def test_stale_disconnect_is_ignored(
|
|
225
|
+
ble_device: BLEDevice, client: FakeClient, establish: AsyncMock
|
|
226
|
+
) -> None:
|
|
227
|
+
toothbrush = LaifenToothbrush(ble_device)
|
|
228
|
+
await toothbrush.connect()
|
|
229
|
+
callback = MagicMock()
|
|
230
|
+
toothbrush.register_callback(callback)
|
|
231
|
+
|
|
232
|
+
assert client.disconnected_callback is not None
|
|
233
|
+
client.disconnected_callback(FakeClient())
|
|
234
|
+
|
|
235
|
+
assert toothbrush.connected
|
|
236
|
+
callback.assert_not_called()
|
|
237
|
+
|
|
238
|
+
|
|
239
|
+
async def test_disconnect(
|
|
240
|
+
ble_device: BLEDevice, client: FakeClient, establish: AsyncMock
|
|
241
|
+
) -> None:
|
|
242
|
+
toothbrush = LaifenToothbrush(ble_device)
|
|
243
|
+
await toothbrush.connect()
|
|
244
|
+
|
|
245
|
+
await toothbrush.disconnect()
|
|
246
|
+
await toothbrush.disconnect()
|
|
247
|
+
|
|
248
|
+
assert not toothbrush.connected
|
|
249
|
+
client.disconnect.assert_awaited_once()
|
|
250
|
+
|
|
251
|
+
|
|
252
|
+
async def test_unregister_callback(
|
|
253
|
+
ble_device: BLEDevice, client: FakeClient, establish: AsyncMock
|
|
254
|
+
) -> None:
|
|
255
|
+
toothbrush = LaifenToothbrush(ble_device)
|
|
256
|
+
callback = MagicMock()
|
|
257
|
+
unregister = toothbrush.register_callback(callback)
|
|
258
|
+
unregister()
|
|
259
|
+
|
|
260
|
+
await toothbrush.connect()
|
|
261
|
+
|
|
262
|
+
callback.assert_not_called()
|
|
263
|
+
|
|
264
|
+
|
|
265
|
+
async def test_connect_without_ble_device(establish: AsyncMock) -> None:
|
|
266
|
+
toothbrush = LaifenToothbrush(ADDRESS)
|
|
267
|
+
assert toothbrush.address == ADDRESS
|
|
268
|
+
assert toothbrush.name == ADDRESS
|
|
269
|
+
|
|
270
|
+
with pytest.raises(LaifenConnectionError):
|
|
271
|
+
await toothbrush.connect()
|
|
272
|
+
|
|
273
|
+
establish.assert_not_called()
|
|
274
|
+
|
|
275
|
+
|
|
276
|
+
async def test_connect_after_ble_device_is_set(
|
|
277
|
+
ble_device: BLEDevice, establish: AsyncMock
|
|
278
|
+
) -> None:
|
|
279
|
+
toothbrush = LaifenToothbrush(ADDRESS)
|
|
280
|
+
toothbrush.set_ble_device(ble_device)
|
|
281
|
+
|
|
282
|
+
await toothbrush.connect()
|
|
283
|
+
|
|
284
|
+
assert toothbrush.connected
|
|
285
|
+
assert toothbrush.name == NAME
|
|
286
|
+
|
|
287
|
+
|
|
288
|
+
def test_set_ble_device(ble_device: BLEDevice) -> None:
|
|
289
|
+
toothbrush = LaifenToothbrush(ble_device)
|
|
290
|
+
toothbrush.set_ble_device(BLEDevice(ADDRESS, None, details=None))
|
|
291
|
+
assert toothbrush.name == ADDRESS
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import pytest
|
|
4
|
+
|
|
5
|
+
from laifen_ble import is_supported
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
@pytest.mark.parametrize(
|
|
9
|
+
("local_name", "expected"),
|
|
10
|
+
[
|
|
11
|
+
("LFTB01-P-A220", True),
|
|
12
|
+
("LFTB01-SE-1234", False),
|
|
13
|
+
("LFTB02-S-412B", False),
|
|
14
|
+
(None, False),
|
|
15
|
+
],
|
|
16
|
+
)
|
|
17
|
+
def test_is_supported(local_name: str | None, expected: bool) -> None:
|
|
18
|
+
assert is_supported(local_name) is expected
|
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import pytest
|
|
4
|
+
|
|
5
|
+
from laifen_ble import InvalidFrameError, Mode, ModeSettings, UnsupportedStateError
|
|
6
|
+
from laifen_ble.protocol import (
|
|
7
|
+
READ_STATE,
|
|
8
|
+
READ_VERSION,
|
|
9
|
+
Command,
|
|
10
|
+
Kind,
|
|
11
|
+
checksum,
|
|
12
|
+
decode_frame,
|
|
13
|
+
decode_state,
|
|
14
|
+
decode_version,
|
|
15
|
+
encode_frame,
|
|
16
|
+
)
|
|
17
|
+
|
|
18
|
+
STATE_FRAME = bytes.fromhex("aa0a021400010a070a0a0a040a0a140101005d010078010085")
|
|
19
|
+
VERSION_FRAME = bytes.fromhex("aa010209020008590404030003f3")
|
|
20
|
+
ACK_FRAME = bytes.fromhex("aa05020100ac")
|
|
21
|
+
STATE_21_FRAME = bytes.fromhex("aa0a0215020205050406060a0a0a140a0a004f00012c000000cf")
|
|
22
|
+
STATE_21_RUNNING_FRAME = bytes.fromhex(
|
|
23
|
+
"aa0a0215020205050406060a0a0a140a0a004f00012c000100ce"
|
|
24
|
+
)
|
|
25
|
+
VERSION_19_FRAME = bytes.fromhex("aa01021302000903585858540001420000590404030003a4")
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def test_checksum() -> None:
|
|
29
|
+
assert checksum(bytes.fromhex("aa0a0000")) == 0xA0
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def test_read_commands() -> None:
|
|
33
|
+
assert bytes.fromhex("aa0a0000a0") == READ_STATE
|
|
34
|
+
assert bytes.fromhex("aa010000ab") == READ_VERSION
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def test_encode_frame_with_payload() -> None:
|
|
38
|
+
assert encode_frame(Command.STATE, Kind.WRITE, b"\x01") == bytes.fromhex(
|
|
39
|
+
"aa0a010101a1"
|
|
40
|
+
)
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def test_decode_frame() -> None:
|
|
44
|
+
frame = decode_frame(ACK_FRAME)
|
|
45
|
+
assert frame.command == 0x05
|
|
46
|
+
assert frame.kind == Kind.REPORT
|
|
47
|
+
assert frame.payload == b"\x00"
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
@pytest.mark.parametrize(
|
|
51
|
+
"data",
|
|
52
|
+
[
|
|
53
|
+
bytes.fromhex("aa0a02"),
|
|
54
|
+
bytes.fromhex("bb05020100ac"),
|
|
55
|
+
bytes.fromhex("aa05020200ac"),
|
|
56
|
+
bytes.fromhex("aa05020100ad"),
|
|
57
|
+
],
|
|
58
|
+
ids=["too_short", "bad_header", "bad_length", "bad_checksum"],
|
|
59
|
+
)
|
|
60
|
+
def test_decode_frame_invalid(data: bytes) -> None:
|
|
61
|
+
with pytest.raises(InvalidFrameError):
|
|
62
|
+
decode_frame(data)
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def test_decode_state() -> None:
|
|
66
|
+
state = decode_state(decode_frame(STATE_FRAME).payload)
|
|
67
|
+
assert state.mode is Mode.MODE_1
|
|
68
|
+
assert state.mode_settings == {
|
|
69
|
+
Mode.MODE_1: ModeSettings(strength=1, range=10, speed=7),
|
|
70
|
+
Mode.MODE_2: ModeSettings(strength=10, range=10, speed=10),
|
|
71
|
+
Mode.MODE_3: ModeSettings(strength=4, range=10, speed=10),
|
|
72
|
+
Mode.HIGH_FREQUENCY: ModeSettings(strength=20, range=1, speed=1),
|
|
73
|
+
}
|
|
74
|
+
assert state.active_mode_settings == ModeSettings(strength=1, range=10, speed=7)
|
|
75
|
+
assert state.airplane_mode is False
|
|
76
|
+
assert state.battery_level == 93
|
|
77
|
+
assert state.reminder_30s is True
|
|
78
|
+
assert state.brushing_time == 120
|
|
79
|
+
assert state.high_frequency is True
|
|
80
|
+
assert state.running is False
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def test_decode_state_running_in_high_frequency() -> None:
|
|
84
|
+
payload = bytearray(decode_frame(STATE_FRAME).payload)
|
|
85
|
+
payload[0] = Mode.HIGH_FREQUENCY
|
|
86
|
+
payload[19] = 0x01
|
|
87
|
+
state = decode_state(bytes(payload))
|
|
88
|
+
assert state.mode is Mode.HIGH_FREQUENCY
|
|
89
|
+
assert state.running is True
|
|
90
|
+
assert state.active_mode_settings == ModeSettings(strength=20, range=1, speed=1)
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
@pytest.mark.parametrize("length", [21, 23])
|
|
94
|
+
def test_decode_state_longer_layouts(length: int) -> None:
|
|
95
|
+
payload = decode_frame(STATE_FRAME).payload + bytes(length - 20)
|
|
96
|
+
assert decode_state(payload).battery_level == 93
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def test_decode_state_flag_requires_exact_one() -> None:
|
|
100
|
+
payload = bytearray(decode_frame(STATE_FRAME).payload)
|
|
101
|
+
payload[19] = 0x02
|
|
102
|
+
assert decode_state(bytes(payload)).running is False
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def test_decode_state_unsupported_length() -> None:
|
|
106
|
+
with pytest.raises(UnsupportedStateError):
|
|
107
|
+
decode_state(bytes(15))
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def test_decode_state_unknown_mode() -> None:
|
|
111
|
+
payload = bytearray(decode_frame(STATE_FRAME).payload)
|
|
112
|
+
payload[0] = 0x04
|
|
113
|
+
with pytest.raises(InvalidFrameError):
|
|
114
|
+
decode_state(bytes(payload))
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def test_decode_version() -> None:
|
|
118
|
+
assert decode_version(decode_frame(VERSION_FRAME).payload) == "V2.0.8.Y44.303"
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def test_decode_version_signed_bytes() -> None:
|
|
122
|
+
assert decode_version(bytes.fromhex("ff0008590404030003")) == "V-1.0.8.Y44.303"
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def test_decode_version_unknown_format() -> None:
|
|
126
|
+
assert decode_version(decode_frame(VERSION_19_FRAME).payload) is None
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def test_decode_state_21_byte_payload() -> None:
|
|
130
|
+
state = decode_state(decode_frame(STATE_21_FRAME).payload)
|
|
131
|
+
assert state.mode is Mode.MODE_3
|
|
132
|
+
assert state.mode_settings == {
|
|
133
|
+
Mode.MODE_1: ModeSettings(strength=2, range=5, speed=5),
|
|
134
|
+
Mode.MODE_2: ModeSettings(strength=4, range=6, speed=6),
|
|
135
|
+
Mode.MODE_3: ModeSettings(strength=10, range=10, speed=10),
|
|
136
|
+
Mode.HIGH_FREQUENCY: ModeSettings(strength=20, range=10, speed=10),
|
|
137
|
+
}
|
|
138
|
+
assert state.airplane_mode is False
|
|
139
|
+
assert state.battery_level == 79
|
|
140
|
+
assert state.reminder_30s is False
|
|
141
|
+
assert state.brushing_time == 300
|
|
142
|
+
assert state.high_frequency is False
|
|
143
|
+
assert state.running is False
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def test_decode_state_21_byte_payload_running() -> None:
|
|
147
|
+
assert decode_state(decode_frame(STATE_21_RUNNING_FRAME).payload).running is True
|