-
-
Notifications
You must be signed in to change notification settings - Fork 599
Cache miIO protocol sequence IDs across CLI invocations #2063
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
14cc971
Cache miIO protocol sequence IDs across CLI invocations
Acrobot 9eb28f3
Run ruff format on changed files
Acrobot c0a80a3
Flatten test classes into top-level functions
syssi 9064869
Fix ruff: remove parentheses from pytest.fixture decorator
syssi File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,61 @@ | ||
| """Cache for device connection state. | ||
|
|
||
| Persists the miIO protocol message sequence counter between CLI invocations. | ||
| Without this, restarting the CLI resets the counter to 0, and devices ignore | ||
| messages with sequence IDs they've already seen, causing timeouts. | ||
| """ | ||
|
|
||
| import hashlib | ||
| import json | ||
| import logging | ||
| from pathlib import Path | ||
| from typing import TypedDict | ||
|
|
||
| from platformdirs import user_cache_dir | ||
|
|
||
| _LOGGER = logging.getLogger(__name__) | ||
|
|
||
| CACHE_DIR = Path(user_cache_dir("python-miio")) | ||
|
|
||
|
|
||
| class DeviceState(TypedDict): | ||
| """Cached state for a single device. | ||
|
|
||
| seq: The miIO protocol message sequence counter. Each message sent to a | ||
| device increments this counter, and the device tracks seen IDs to | ||
| deduplicate. Persisting it avoids ID reuse across CLI invocations. | ||
| """ | ||
|
|
||
| seq: int | ||
|
|
||
|
|
||
| def _cache_path(ip: str) -> Path: | ||
| """Return the cache file path for a device IP. | ||
|
|
||
| Uses a hash of the IP to avoid filesystem issues with IPv6 colons. | ||
| """ | ||
| ip_hash = hashlib.sha256(ip.encode()).hexdigest()[:16] | ||
| return CACHE_DIR / f"{ip_hash}.json" | ||
|
|
||
|
|
||
| def read_cache(ip: str) -> DeviceState: | ||
| """Read cached connection state for a device.""" | ||
| path = _cache_path(ip) | ||
| try: | ||
| data = json.loads(path.read_text()) | ||
| seq = int(data["seq"]) | ||
| _LOGGER.debug("Loaded cache for %s: seq=%d", ip, seq) | ||
| return DeviceState(seq=seq) | ||
| except FileNotFoundError: | ||
| return DeviceState(seq=0) | ||
| except (json.JSONDecodeError, KeyError, TypeError, ValueError) as ex: | ||
| _LOGGER.warning("Corrupt cache for %s, ignoring: %s", ip, ex) | ||
| return DeviceState(seq=0) | ||
|
|
||
|
|
||
| def write_cache(ip: str, state: DeviceState) -> None: | ||
| """Write connection state to cache for a device.""" | ||
| path = _cache_path(ip) | ||
| path.parent.mkdir(parents=True, exist_ok=True) | ||
| path.write_text(json.dumps(state)) | ||
| _LOGGER.debug("Wrote cache for %s: %s", ip, state) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,83 @@ | ||
| import json | ||
| from pathlib import Path | ||
|
|
||
| import pytest | ||
|
|
||
| from miio.device_cache import DeviceState, _cache_path, read_cache, write_cache | ||
|
|
||
|
|
||
| @pytest.fixture | ||
| def cache_dir(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path: | ||
| monkeypatch.setattr("miio.device_cache.CACHE_DIR", tmp_path) | ||
| return tmp_path | ||
|
|
||
|
|
||
| def test_cache_path_ipv4(cache_dir: Path) -> None: | ||
| path = _cache_path("192.168.1.1") | ||
| assert path.parent == cache_dir | ||
| assert path.suffix == ".json" | ||
|
|
||
|
|
||
| def test_cache_path_ipv6(cache_dir: Path) -> None: | ||
| path = _cache_path("fe80::1") | ||
| assert path.parent == cache_dir | ||
| assert path.suffix == ".json" | ||
| assert ":" not in path.name | ||
|
|
||
|
|
||
| def test_cache_path_different_ips(cache_dir: Path) -> None: | ||
| assert _cache_path("192.168.1.1") != _cache_path("192.168.1.2") | ||
|
|
||
|
|
||
| def test_cache_path_same_ip(cache_dir: Path) -> None: | ||
| assert _cache_path("192.168.1.1") == _cache_path("192.168.1.1") | ||
|
|
||
|
|
||
| def test_read_cache_missing_file(cache_dir: Path) -> None: | ||
| state: DeviceState = read_cache("192.168.1.1") | ||
| assert state["seq"] == 0 | ||
|
|
||
|
|
||
| def test_read_cache_written_data(cache_dir: Path) -> None: | ||
| write_cache("192.168.1.1", DeviceState(seq=42)) | ||
| state: DeviceState = read_cache("192.168.1.1") | ||
| assert state["seq"] == 42 | ||
|
|
||
|
|
||
| def test_read_cache_corrupt_json(cache_dir: Path) -> None: | ||
| _cache_path("192.168.1.1").write_text("not json") | ||
| state: DeviceState = read_cache("192.168.1.1") | ||
| assert state["seq"] == 0 | ||
|
|
||
|
|
||
| def test_read_cache_missing_seq_key(cache_dir: Path) -> None: | ||
| _cache_path("192.168.1.1").write_text(json.dumps({"other": 123})) | ||
| state: DeviceState = read_cache("192.168.1.1") | ||
| assert state["seq"] == 0 | ||
|
|
||
|
|
||
| def test_read_cache_non_int_seq(cache_dir: Path) -> None: | ||
| _cache_path("192.168.1.1").write_text(json.dumps({"seq": "not_a_number"})) | ||
| state: DeviceState = read_cache("192.168.1.1") | ||
| assert state["seq"] == 0 | ||
|
|
||
|
|
||
| def test_write_cache_creates_directory( | ||
| tmp_path: Path, monkeypatch: pytest.MonkeyPatch | ||
| ) -> None: | ||
| nested = tmp_path / "sub" / "dir" | ||
| monkeypatch.setattr("miio.device_cache.CACHE_DIR", nested) | ||
| write_cache("192.168.1.1", DeviceState(seq=5)) | ||
| assert nested.exists() | ||
|
|
||
|
|
||
| def test_write_cache_overwrites_existing(cache_dir: Path) -> None: | ||
| write_cache("192.168.1.1", DeviceState(seq=10)) | ||
| write_cache("192.168.1.1", DeviceState(seq=20)) | ||
| assert read_cache("192.168.1.1")["seq"] == 20 | ||
|
|
||
|
|
||
| def test_write_cache_valid_json(cache_dir: Path) -> None: | ||
| write_cache("192.168.1.1", DeviceState(seq=99)) | ||
| data: dict = json.loads(_cache_path("192.168.1.1").read_text()) | ||
| assert data == {"seq": 99} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.