hackrf-proxy-client 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.
@@ -0,0 +1,9 @@
1
+ target/
2
+ *.iq
3
+ *.cs8
4
+ captures/
5
+ __pycache__/
6
+ .venv/
7
+ dist/
8
+ *.egg-info/
9
+ uv.lock
@@ -0,0 +1,7 @@
1
+ Licensed under the Apache License, Version 2.0
2
+ <LICENSE-APACHE or
3
+ http://www.apache.org/licenses/LICENSE-2.0> or the MIT
4
+ license <LICENSE-MIT or http://opensource.org/licenses/MIT>,
5
+ at your option. All files in the project carrying such
6
+ notice may not be copied, modified, or distributed except
7
+ according to those terms.
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,25 @@
1
+ Copyright (c) 2026 Aetf <aetf at unlimited-code dot works>
2
+
3
+ Permission is hereby granted, free of charge, to any
4
+ person obtaining a copy of this software and associated
5
+ documentation files (the "Software"), to deal in the
6
+ Software without restriction, including without
7
+ limitation the rights to use, copy, modify, merge,
8
+ publish, distribute, sublicense, and/or sell copies of
9
+ the Software, and to permit persons to whom the Software
10
+ is furnished to do so, subject to the following
11
+ conditions:
12
+
13
+ The above copyright notice and this permission notice
14
+ shall be included in all copies or substantial portions
15
+ of the Software.
16
+
17
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
18
+ ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
19
+ TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
20
+ PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
21
+ SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
22
+ CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
23
+ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
24
+ IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
25
+ DEALINGS IN THE SOFTWARE.
@@ -0,0 +1,50 @@
1
+ Metadata-Version: 2.5
2
+ Name: hackrf-proxy-client
3
+ Version: 0.1.0
4
+ Summary: Async WebSocket client for the hackrf-proxyd network-attached OOK transceiver daemon
5
+ Project-URL: Homepage, https://github.com/Aetf/hackrf-proxy
6
+ Project-URL: Repository, https://github.com/Aetf/hackrf-proxy
7
+ Project-URL: Issues, https://github.com/Aetf/hackrf-proxy/issues
8
+ Project-URL: Changelog, https://github.com/Aetf/hackrf-proxy/blob/main/CHANGELOG.md
9
+ Author-email: Aetf <aetf@unlimited-code.works>
10
+ License-Expression: MIT OR Apache-2.0
11
+ License-File: COPYRIGHT
12
+ License-File: LICENSE-APACHE
13
+ License-File: LICENSE-MIT
14
+ Keywords: hackrf,home-assistant,ook,sdr,websocket
15
+ Classifier: Development Status :: 4 - Beta
16
+ Classifier: Framework :: AsyncIO
17
+ Classifier: Intended Audience :: Developers
18
+ Classifier: Operating System :: OS Independent
19
+ Classifier: Programming Language :: Python :: 3
20
+ Classifier: Topic :: Home Automation
21
+ Requires-Python: >=3.12
22
+ Requires-Dist: aiohttp>=3.9
23
+ Description-Content-Type: text/markdown
24
+
25
+ # hackrf-proxy-client
26
+
27
+ Async Python client for the
28
+ [hackrf-proxyd](https://github.com/Aetf/hackrf-proxy) daemon's WebSocket
29
+ protocol: a reconnecting connection with id-matched replies, `rx_frame` event
30
+ delivery, and availability that follows the radio rather than the socket.
31
+
32
+ Released in lockstep with the daemon from the same repository; a client is
33
+ compatible with any daemon of the same semver major version, and
34
+ `ProxyClient.is_compatible` reports the check.
35
+
36
+ ```python
37
+ import aiohttp
38
+ from hackrf_proxy_client import ProxyClient
39
+
40
+ async with aiohttp.ClientSession() as session:
41
+ client = ProxyClient(session, "radio-host", 8765)
42
+ await client.async_start()
43
+ await client.async_wait_connected(timeout=10)
44
+ await client.async_transmit(frequency=315_000_000, timings=[450, -450, 900])
45
+ await client.async_stop()
46
+ ```
47
+
48
+ ## License
49
+
50
+ MIT OR Apache-2.0, at your option.
@@ -0,0 +1,26 @@
1
+ # hackrf-proxy-client
2
+
3
+ Async Python client for the
4
+ [hackrf-proxyd](https://github.com/Aetf/hackrf-proxy) daemon's WebSocket
5
+ protocol: a reconnecting connection with id-matched replies, `rx_frame` event
6
+ delivery, and availability that follows the radio rather than the socket.
7
+
8
+ Released in lockstep with the daemon from the same repository; a client is
9
+ compatible with any daemon of the same semver major version, and
10
+ `ProxyClient.is_compatible` reports the check.
11
+
12
+ ```python
13
+ import aiohttp
14
+ from hackrf_proxy_client import ProxyClient
15
+
16
+ async with aiohttp.ClientSession() as session:
17
+ client = ProxyClient(session, "radio-host", 8765)
18
+ await client.async_start()
19
+ await client.async_wait_connected(timeout=10)
20
+ await client.async_transmit(frequency=315_000_000, timings=[450, -450, 900])
21
+ await client.async_stop()
22
+ ```
23
+
24
+ ## License
25
+
26
+ MIT OR Apache-2.0, at your option.
@@ -0,0 +1,63 @@
1
+ [build-system]
2
+ requires = ["hatchling", "hatch-vcs"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "hackrf-proxy-client"
7
+ dynamic = ["version"]
8
+ description = "Async WebSocket client for the hackrf-proxyd network-attached OOK transceiver daemon"
9
+ readme = "README.md"
10
+ license = "MIT OR Apache-2.0"
11
+ # Copies of the repository-root files: wheel metadata forbids parent paths.
12
+ license-files = ["LICENSE-MIT", "LICENSE-APACHE", "COPYRIGHT"]
13
+ requires-python = ">=3.12"
14
+ authors = [{ name = "Aetf", email = "aetf@unlimited-code.works" }]
15
+ keywords = ["hackrf", "sdr", "ook", "websocket", "home-assistant"]
16
+ classifiers = [
17
+ "Development Status :: 4 - Beta",
18
+ "Intended Audience :: Developers",
19
+ "Operating System :: OS Independent",
20
+ "Programming Language :: Python :: 3",
21
+ "Framework :: AsyncIO",
22
+ "Topic :: Home Automation",
23
+ ]
24
+ dependencies = ["aiohttp>=3.9"]
25
+
26
+ [project.urls]
27
+ Homepage = "https://github.com/Aetf/hackrf-proxy"
28
+ Repository = "https://github.com/Aetf/hackrf-proxy"
29
+ Issues = "https://github.com/Aetf/hackrf-proxy/issues"
30
+ Changelog = "https://github.com/Aetf/hackrf-proxy/blob/main/CHANGELOG.md"
31
+
32
+ [dependency-groups]
33
+ dev = ["pytest>=8", "pytest-aiohttp>=1.0", "basedpyright>=1.29"]
34
+
35
+ # The client is versioned in lockstep with the daemon: both come from the
36
+ # repository's vX.Y.Z tag, which release-plz derives from Cargo.toml. The
37
+ # compatibility contract is same-major.
38
+ [tool.hatch.version]
39
+ source = "vcs"
40
+ raw-options = { root = "../.." }
41
+
42
+ [tool.ruff]
43
+ line-length = 100
44
+
45
+ [tool.ruff.lint]
46
+ select = ["E", "F", "W", "I", "UP", "B", "SIM", "D"]
47
+ # D203/D213: incompatible pairs. D401: descriptive-prose docstrings by design.
48
+ ignore = ["D203", "D213", "D401"]
49
+
50
+ [tool.ruff.lint.per-file-ignores]
51
+ "tests/*" = ["D"]
52
+
53
+ [tool.pytest.ini_options]
54
+ testpaths = ["tests"]
55
+ asyncio_mode = "auto"
56
+
57
+ [tool.basedpyright]
58
+ typeCheckingMode = "strict"
59
+ # basedpyright's opinions beyond pyright strict; prose-typed code keeps Any at
60
+ # the JSON boundary on purpose.
61
+ reportAny = false
62
+ reportExplicitAny = false
63
+ reportUnusedCallResult = false
@@ -0,0 +1,17 @@
1
+ """Async WebSocket client for the hackrf-proxyd daemon."""
2
+
3
+ from .client import (
4
+ PROTOCOL_VERSION,
5
+ REQUEST_TIMEOUT,
6
+ ProxyClient,
7
+ ProxyError,
8
+ __version__,
9
+ )
10
+
11
+ __all__ = [
12
+ "PROTOCOL_VERSION",
13
+ "REQUEST_TIMEOUT",
14
+ "ProxyClient",
15
+ "ProxyError",
16
+ "__version__",
17
+ ]
@@ -0,0 +1,370 @@
1
+ """WebSocket client for the hackrf-proxyd daemon.
2
+
3
+ Thin on purpose: it moves raw OOK timings and knows nothing about any
4
+ appliance. The daemon's protocol is documented in `proxyd/README.md`.
5
+
6
+ Client and daemon are released from the same repository under one version
7
+ number, and the compatibility contract is semver: a client works with any
8
+ daemon of the same major version. The wire-level `v` field is the daemon's
9
+ own last-resort gate; `is_compatible` is this side's check, from the version
10
+ the daemon reports in its status reply.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import asyncio
16
+ import contextlib
17
+ import logging
18
+ from collections.abc import Callable
19
+ from datetime import UTC, datetime
20
+ from importlib.metadata import PackageNotFoundError
21
+ from importlib.metadata import version as _package_version
22
+ from typing import Any
23
+
24
+ import aiohttp
25
+
26
+ _LOGGER = logging.getLogger(__name__)
27
+
28
+ try:
29
+ # `or "0.0.0"` covers a damaged install whose metadata lacks a version.
30
+ __version__ = _package_version("hackrf-proxy-client") or "0.0.0"
31
+ except PackageNotFoundError: # running from a checkout, not an install
32
+ __version__ = "0.0.0"
33
+
34
+ #: Protocol version this client speaks. The daemon refuses anything else by
35
+ #: name rather than misreading it.
36
+ PROTOCOL_VERSION = 1
37
+
38
+
39
+ def _semver_major(version_string: str) -> int | None:
40
+ """The major component, or None when the string is not a version."""
41
+ head = version_string.split(".", 1)[0]
42
+ return int(head) if head.isdigit() else None
43
+
44
+
45
+ #: How long to wait for a reply. Generous because a reply arrives when the
46
+ #: transmission is *over*, and the daemon allows up to 30 seconds of air time
47
+ #: per request, plus whatever is queued ahead of it on a shared radio.
48
+ REQUEST_TIMEOUT = 60.0
49
+
50
+ _INITIAL_BACKOFF = 1.0
51
+ _MAX_BACKOFF = 60.0
52
+
53
+
54
+ class ProxyError(Exception):
55
+ """The daemon refused a request, or could not be reached."""
56
+
57
+
58
+ class ProxyClient:
59
+ """A reconnecting client for one daemon.
60
+
61
+ Holds a single connection and multiplexes requests over it. Replies are
62
+ matched by id, which is not optional: the daemon pushes events at any time,
63
+ and a transmission's own `device_state` event overtakes its reply.
64
+ """
65
+
66
+ def __init__(
67
+ self,
68
+ session: aiohttp.ClientSession,
69
+ host: str,
70
+ port: int,
71
+ *,
72
+ on_rx_frame: Callable[[dict[str, Any]], None] | None = None,
73
+ ) -> None:
74
+ """Initialize the client."""
75
+ self._session = session
76
+ self._url = f"ws://{host}:{port}"
77
+ self._on_rx_frame = on_rx_frame
78
+ self._availability_listeners: list[Callable[[bool], None]] = []
79
+ #: Told about anything the diagnostics show, not only availability.
80
+ #: The radio moving between idle, receiving and transmitting does not
81
+ #: change availability at all, so a listener on that alone would show a
82
+ #: state that only ever updated when something broke.
83
+ self._update_listeners: list[Callable[[], None]] = []
84
+
85
+ self._socket: aiohttp.ClientWebSocketResponse | None = None
86
+ self._task: asyncio.Task[None] | None = None
87
+ self._pending: dict[str, asyncio.Future[dict[str, Any]]] = {}
88
+ self._next_id = 0
89
+ self._connected = asyncio.Event()
90
+ self._closing = False
91
+ #: Board and firmware of the radio, once the daemon has reported them.
92
+ self.device: str | None = None
93
+ #: The daemon's own version.
94
+ self.daemon_version: str | None = None
95
+
96
+ #: What the radio was last seen doing: `receiving`, `transmitting`,
97
+ #: `idle` or `faulted`, and `None` while there is no connection to ask.
98
+ #: This is the refinement `available` cannot carry — a transmitter that
99
+ #: is unavailable is either unreachable or broken, and which of the two
100
+ #: is the entire question when something stops working.
101
+ self.state: str | None = None
102
+ #: When the current connection was established, and how many previous
103
+ #: ones ended. Kept because an intermittent link is invisible from a
104
+ #: connected socket: the only trace it leaves is how recently this one
105
+ #: started.
106
+ self.connected_since: datetime | None = None
107
+ self.disconnects = 0
108
+ #: When the receiver last heard anything at all. The one reading that
109
+ #: says whether the receive path works, rather than whether the daemon
110
+ #: is answering.
111
+ self.last_rx_frame: datetime | None = None
112
+
113
+ def add_availability_listener(
114
+ self, listener: Callable[[bool], None]
115
+ ) -> Callable[[], None]:
116
+ """Subscribe to availability changes, returning an unsubscribe."""
117
+ self._availability_listeners.append(listener)
118
+
119
+ def unsubscribe() -> None:
120
+ with contextlib.suppress(ValueError):
121
+ self._availability_listeners.remove(listener)
122
+
123
+ return unsubscribe
124
+
125
+ def add_update_listener(self, listener: Callable[[], None]) -> Callable[[], None]:
126
+ """Subscribe to any observable change, returning an unsubscribe."""
127
+ self._update_listeners.append(listener)
128
+
129
+ def unsubscribe() -> None:
130
+ with contextlib.suppress(ValueError):
131
+ self._update_listeners.remove(listener)
132
+
133
+ return unsubscribe
134
+
135
+ def _notify(self) -> None:
136
+ for listener in list(self._update_listeners):
137
+ listener()
138
+
139
+ @property
140
+ def available(self) -> bool:
141
+ """Whether the daemon is currently connected."""
142
+ return self._connected.is_set()
143
+
144
+ @property
145
+ def is_compatible(self) -> bool | None:
146
+ """Whether the daemon's major version matches this client's.
147
+
148
+ None while no daemon version has been seen, or when either side's
149
+ version cannot be parsed — unknown is not the same as incompatible.
150
+ """
151
+ if self.daemon_version is None:
152
+ return None
153
+ ours = _semver_major(__version__)
154
+ theirs = _semver_major(self.daemon_version)
155
+ if ours is None or theirs is None:
156
+ return None
157
+ return ours == theirs
158
+
159
+ @property
160
+ def url(self) -> str:
161
+ """The daemon's WebSocket URL."""
162
+ return self._url
163
+
164
+ async def async_start(self) -> None:
165
+ """Begin connecting, and keep the connection up."""
166
+ self._closing = False
167
+ self._task = asyncio.create_task(self._run())
168
+
169
+ async def async_stop(self) -> None:
170
+ """Disconnect and stop reconnecting."""
171
+ self._closing = True
172
+ if self._task is not None:
173
+ self._task.cancel()
174
+ with contextlib.suppress(asyncio.CancelledError):
175
+ await self._task
176
+ self._task = None
177
+ if self._socket is not None:
178
+ await self._socket.close()
179
+
180
+ async def async_wait_connected(self, timeout: float) -> None:
181
+ """Wait for the first successful connection."""
182
+ async with asyncio.timeout(timeout):
183
+ await self._connected.wait()
184
+
185
+ async def async_status(self) -> dict[str, Any]:
186
+ """Ask the daemon what state it is in."""
187
+ return await self._request({"type": "status"})
188
+
189
+ async def async_transmit(
190
+ self,
191
+ *,
192
+ frequency: int,
193
+ timings: list[int],
194
+ repeat: int = 0,
195
+ gap_us: int | None = None,
196
+ output_power: float | None = None,
197
+ ) -> int:
198
+ """Transmit OOK timings, returning the air time in microseconds.
199
+
200
+ Returns when the transmission is over, not when it is queued.
201
+ """
202
+ request: dict[str, Any] = {
203
+ "type": "transmit",
204
+ "frequency": frequency,
205
+ "timings": timings,
206
+ "repeat": repeat,
207
+ }
208
+ if gap_us is not None:
209
+ request["gap_us"] = gap_us
210
+ if output_power is not None:
211
+ # The platform expresses power as a 0..1 fraction; the daemon takes
212
+ # the radio's own 0..47 dB TX VGA setting.
213
+ request["txvga_db"] = max(0, min(47, round(output_power * 47)))
214
+
215
+ reply = await self._request(request)
216
+ return int(reply.get("duration_us", 0))
217
+
218
+ async def _request(self, payload: dict[str, Any]) -> dict[str, Any]:
219
+ """Send a request and await the reply that carries its id."""
220
+ socket = self._socket
221
+ if socket is None or not self._connected.is_set():
222
+ raise ProxyError(f"not connected to {self._url}")
223
+
224
+ self._next_id += 1
225
+ request_id = str(self._next_id)
226
+ message = {"v": PROTOCOL_VERSION, "id": request_id, **payload}
227
+
228
+ future: asyncio.Future[dict[str, Any]] = asyncio.get_running_loop().create_future()
229
+ self._pending[request_id] = future
230
+ try:
231
+ await socket.send_json(message)
232
+ async with asyncio.timeout(REQUEST_TIMEOUT):
233
+ reply = await future
234
+ except TimeoutError as err:
235
+ raise ProxyError(f"{self._url} did not answer in time") from err
236
+ except aiohttp.ClientError as err:
237
+ raise ProxyError(f"failed to reach {self._url}: {err}") from err
238
+ finally:
239
+ self._pending.pop(request_id, None)
240
+
241
+ if reply.get("type") == "error":
242
+ raise ProxyError(str(reply.get("message", "unspecified error")))
243
+ return reply
244
+
245
+ async def _run(self) -> None:
246
+ """Keep a connection up, reconnecting with a widening backoff."""
247
+ backoff = _INITIAL_BACKOFF
248
+ while not self._closing:
249
+ try:
250
+ async with self._session.ws_connect(self._url, heartbeat=30) as socket:
251
+ _LOGGER.debug("connected to %s", self._url)
252
+ self._socket = socket
253
+ backoff = _INITIAL_BACKOFF
254
+ await self._read_until_closed(socket)
255
+ except asyncio.CancelledError:
256
+ raise
257
+ except (aiohttp.ClientError, OSError) as err:
258
+ _LOGGER.debug("connection to %s failed: %s", self._url, err)
259
+ finally:
260
+ self._socket = None
261
+ # Only a connection that was actually established counts as a
262
+ # drop. Otherwise a daemon that is simply not running yet would
263
+ # add one per backoff interval and read as a flapping link.
264
+ if self.connected_since is not None:
265
+ self.disconnects += 1
266
+ self.connected_since = None
267
+ self.state = None
268
+ self._set_available(False)
269
+ self._notify()
270
+ self._fail_pending(ProxyError(f"disconnected from {self._url}"))
271
+
272
+ if self._closing:
273
+ return
274
+ await asyncio.sleep(backoff)
275
+ backoff = min(backoff * 2, _MAX_BACKOFF)
276
+
277
+ async def _read_until_closed(self, socket: aiohttp.ClientWebSocketResponse) -> None:
278
+ """Dispatch messages until the connection ends."""
279
+ # Only report available once the daemon has actually answered, rather
280
+ # than when the socket opens: a TCP connection to a wedged daemon would
281
+ # otherwise look healthy.
282
+ try:
283
+ status = await asyncio.wait_for(_first_status(socket), timeout=10)
284
+ except (TimeoutError, aiohttp.ClientError):
285
+ _LOGGER.debug("%s did not answer a status request", self._url)
286
+ return
287
+ self.device = status.get("device")
288
+ self.daemon_version = status.get("daemon_version")
289
+ if self.is_compatible is False:
290
+ _LOGGER.warning(
291
+ "%s runs daemon %s, which is a different major version than "
292
+ "client %s; same-major is the supported pairing",
293
+ self._url,
294
+ self.daemon_version,
295
+ __version__,
296
+ )
297
+ self.state = status.get("state")
298
+ self.connected_since = datetime.now(UTC)
299
+ self._set_available(True)
300
+ self._notify()
301
+
302
+ async for message in socket:
303
+ if message.type is not aiohttp.WSMsgType.TEXT:
304
+ continue
305
+ try:
306
+ payload = message.json()
307
+ except ValueError:
308
+ _LOGGER.warning("%s sent malformed JSON", self._url)
309
+ continue
310
+ self._dispatch(payload)
311
+
312
+ def _dispatch(self, payload: dict[str, Any]) -> None:
313
+ """Route a message to whoever is waiting for it."""
314
+ request_id = payload.get("id")
315
+ if request_id is not None and (future := self._pending.get(str(request_id))):
316
+ if not future.done():
317
+ future.set_result(payload)
318
+ return
319
+
320
+ kind = payload.get("type")
321
+ if kind == "rx_frame":
322
+ self.last_rx_frame = datetime.now(UTC)
323
+ self._notify()
324
+ if self._on_rx_frame is not None:
325
+ self._on_rx_frame(payload)
326
+ elif kind == "device_state":
327
+ # The radio can fault while the connection stays up. Availability
328
+ # follows the radio, because a transmitter that cannot transmit is
329
+ # not available in any sense a consumer cares about.
330
+ self.state = payload.get("state")
331
+ self._set_available(self.state != "faulted")
332
+ self._notify()
333
+ elif kind == "error":
334
+ _LOGGER.warning("%s reported: %s", self._url, payload.get("message"))
335
+
336
+ def _set_available(self, available: bool) -> None:
337
+ if available == self._connected.is_set():
338
+ return
339
+ if available:
340
+ self._connected.set()
341
+ else:
342
+ self._connected.clear()
343
+ for listener in list(self._availability_listeners):
344
+ listener(available)
345
+
346
+ def _fail_pending(self, error: Exception) -> None:
347
+ for future in self._pending.values():
348
+ if not future.done():
349
+ future.set_exception(error)
350
+ self._pending.clear()
351
+
352
+
353
+ async def _first_status(socket: aiohttp.ClientWebSocketResponse) -> dict[str, Any]:
354
+ """Send one status request and read until its reply arrives.
355
+
356
+ Used only during connection setup, where nothing else is in flight yet;
357
+ events that arrive meanwhile are dropped rather than dispatched, which is
358
+ harmless because the entity has not been told it is available.
359
+ """
360
+ await socket.send_json({"v": PROTOCOL_VERSION, "id": "hello", "type": "status"})
361
+ async for message in socket:
362
+ if message.type is not aiohttp.WSMsgType.TEXT:
363
+ continue
364
+ try:
365
+ payload = message.json()
366
+ except ValueError:
367
+ continue
368
+ if payload.get("id") == "hello":
369
+ return payload
370
+ raise aiohttp.ClientError("connection closed during handshake")
@@ -0,0 +1,167 @@
1
+ """The client against a scripted daemon, and the cross-language protocol pin."""
2
+
3
+ # The tests exercise the module's internals on purpose.
4
+ # pyright: reportPrivateUsage=false
5
+
6
+ from __future__ import annotations
7
+
8
+ import asyncio
9
+ import json
10
+ import re
11
+ from collections.abc import Callable
12
+ from pathlib import Path
13
+ from typing import Any, cast
14
+
15
+ import aiohttp
16
+ import pytest
17
+ from aiohttp import web
18
+ from aiohttp.pytest_plugin import AiohttpServer
19
+
20
+ from hackrf_proxy_client import PROTOCOL_VERSION, ProxyClient, ProxyError
21
+ from hackrf_proxy_client.client import _semver_major
22
+
23
+ REPO_ROOT = Path(__file__).resolve().parents[3]
24
+
25
+
26
+ def test_protocol_version_matches_the_daemon() -> None:
27
+ """The Rust and Python ends of the wire declare the same version.
28
+
29
+ Same repository, one wire protocol, two declarations — this is the test
30
+ that keeps them from drifting apart.
31
+ """
32
+ wire = (REPO_ROOT / "proxyd" / "src" / "wire.rs").read_text()
33
+ match = re.search(r"pub const PROTOCOL_VERSION: u32 = (\d+);", wire)
34
+ assert match is not None, "wire.rs no longer declares PROTOCOL_VERSION"
35
+ assert int(match.group(1)) == PROTOCOL_VERSION
36
+
37
+
38
+ def test_semver_major_parsing() -> None:
39
+ assert _semver_major("1.2.3") == 1
40
+ assert _semver_major("0.1.0") == 0
41
+ assert _semver_major("10.0.0-rc.1") == 10
42
+ assert _semver_major("unknown") is None
43
+
44
+
45
+ class ScriptedDaemon:
46
+ """Just enough of hackrf-proxyd's WebSocket protocol to exercise the client."""
47
+
48
+ def __init__(self, daemon_version: str = "0.0.0") -> None:
49
+ self.daemon_version = daemon_version
50
+ self.transmits: list[dict[str, Any]] = []
51
+ self._socket: web.WebSocketResponse | None = None
52
+
53
+ async def handler(self, request: web.Request) -> web.WebSocketResponse:
54
+ socket = web.WebSocketResponse()
55
+ await socket.prepare(request)
56
+ self._socket = socket
57
+ async for message in socket:
58
+ if message.type is not aiohttp.WSMsgType.TEXT:
59
+ continue
60
+ payload: dict[str, Any] = json.loads(message.data)
61
+ reply: dict[str, Any] = {"id": payload["id"]}
62
+ if payload["type"] == "status":
63
+ reply |= {
64
+ "type": "status",
65
+ "state": "receiving",
66
+ "device": "HackRF One r9",
67
+ "daemon_version": self.daemon_version,
68
+ }
69
+ elif payload["type"] == "transmit":
70
+ self.transmits.append(payload)
71
+ # A transmission's own device_state events overtake its reply
72
+ # on the real wire; reproduce that so id matching is what the
73
+ # test exercises, not luck.
74
+ await socket.send_json({"type": "device_state", "state": "transmitting"})
75
+ await socket.send_json({"type": "device_state", "state": "receiving"})
76
+ reply |= {"type": "transmitted", "duration_us": 81_100}
77
+ await socket.send_json(reply)
78
+ return socket
79
+
80
+ async def push(self, payload: dict[str, Any]) -> None:
81
+ assert self._socket is not None
82
+ await self._socket.send_json(payload)
83
+
84
+
85
+ async def _connected_client(
86
+ aiohttp_server: AiohttpServer,
87
+ daemon: ScriptedDaemon,
88
+ *,
89
+ on_rx_frame: Callable[[dict[str, Any]], None] | None = None,
90
+ ) -> tuple[ProxyClient, aiohttp.ClientSession]:
91
+ app = web.Application()
92
+ app.router.add_get("/", daemon.handler)
93
+ server = await aiohttp_server(app)
94
+ # TestServer.port is only partially typed upstream; it is an int once the
95
+ # server has started, and it has.
96
+ port = cast(int, server.port)
97
+ session = aiohttp.ClientSession()
98
+ client = ProxyClient(session, server.host, port, on_rx_frame=on_rx_frame)
99
+ await client.async_start()
100
+ await client.async_wait_connected(timeout=5)
101
+ return client, session
102
+
103
+
104
+ async def test_connects_and_reports_the_daemon(aiohttp_server: AiohttpServer) -> None:
105
+ daemon = ScriptedDaemon()
106
+ client, session = await _connected_client(aiohttp_server, daemon)
107
+ try:
108
+ assert client.available
109
+ assert client.state == "receiving"
110
+ assert client.device == "HackRF One r9"
111
+ assert client.daemon_version == "0.0.0"
112
+ assert client.is_compatible is True # both majors are 0
113
+ finally:
114
+ await client.async_stop()
115
+ await session.close()
116
+
117
+
118
+ async def test_transmit_returns_air_time_despite_overtaking_events(
119
+ aiohttp_server: AiohttpServer,
120
+ ) -> None:
121
+ daemon = ScriptedDaemon()
122
+ client, session = await _connected_client(aiohttp_server, daemon)
123
+ try:
124
+ duration = await client.async_transmit(
125
+ frequency=315_000_000, timings=[450, -450, 1350], repeat=9
126
+ )
127
+ assert duration == 81_100
128
+ (request,) = daemon.transmits
129
+ assert request["v"] == PROTOCOL_VERSION
130
+ assert request["frequency"] == 315_000_000
131
+ assert request["repeat"] == 9
132
+ finally:
133
+ await client.async_stop()
134
+ await session.close()
135
+
136
+
137
+ async def test_rx_frames_reach_the_callback(aiohttp_server: AiohttpServer) -> None:
138
+ daemon = ScriptedDaemon()
139
+ heard: list[dict[str, Any]] = []
140
+ client, session = await _connected_client(aiohttp_server, daemon, on_rx_frame=heard.append)
141
+ try:
142
+ await daemon.push({"type": "rx_frame", "frequency": 315_000_000, "timings": [450, -450]})
143
+ async with asyncio.timeout(5):
144
+ while not heard:
145
+ await asyncio.sleep(0.01)
146
+ assert heard[0]["timings"] == [450, -450]
147
+ assert client.last_rx_frame is not None
148
+ finally:
149
+ await client.async_stop()
150
+ await session.close()
151
+
152
+
153
+ async def test_a_different_major_reads_as_incompatible(aiohttp_server: AiohttpServer) -> None:
154
+ daemon = ScriptedDaemon(daemon_version="99.0.0")
155
+ client, session = await _connected_client(aiohttp_server, daemon)
156
+ try:
157
+ assert client.is_compatible is False
158
+ finally:
159
+ await client.async_stop()
160
+ await session.close()
161
+
162
+
163
+ async def test_requests_fail_cleanly_when_disconnected() -> None:
164
+ async with aiohttp.ClientSession() as session:
165
+ client = ProxyClient(session, "localhost", 1)
166
+ with pytest.raises(ProxyError):
167
+ await client.async_status()