hapbeat-python-sdk 0.2.0__py3-none-any.whl → 0.3.0__py3-none-any.whl
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.
- hapbeat/__init__.py +14 -4
- hapbeat/cli.py +14 -2
- hapbeat/client.py +225 -4
- hapbeat/hapbeat.py +293 -78
- hapbeat/launchpad.py +2 -1
- hapbeat/netif.py +270 -0
- hapbeat/osc.py +4 -2
- hapbeat/protocol.py +165 -23
- hapbeat/stream.py +766 -0
- hapbeat/stream_lease.py +182 -0
- {hapbeat_python_sdk-0.2.0.dist-info → hapbeat_python_sdk-0.3.0.dist-info}/METADATA +17 -9
- hapbeat_python_sdk-0.3.0.dist-info/RECORD +20 -0
- {hapbeat_python_sdk-0.2.0.dist-info → hapbeat_python_sdk-0.3.0.dist-info}/WHEEL +1 -1
- hapbeat/clip.py +0 -121
- hapbeat_python_sdk-0.2.0.dist-info/RECORD +0 -18
- {hapbeat_python_sdk-0.2.0.dist-info → hapbeat_python_sdk-0.3.0.dist-info}/entry_points.txt +0 -0
- {hapbeat_python_sdk-0.2.0.dist-info → hapbeat_python_sdk-0.3.0.dist-info}/licenses/LICENSE +0 -0
- {hapbeat_python_sdk-0.2.0.dist-info → hapbeat_python_sdk-0.3.0.dist-info}/top_level.txt +0 -0
hapbeat/__init__.py
CHANGED
|
@@ -17,9 +17,15 @@ from __future__ import annotations
|
|
|
17
17
|
|
|
18
18
|
from . import protocol
|
|
19
19
|
from .client import DEFAULT_BROADCAST, DEFAULT_PORT, UdpClient
|
|
20
|
-
from .clip import ClipStreamer
|
|
21
20
|
from .eventmap import EventDef, EventMap
|
|
22
21
|
from .hapbeat import Device, Hapbeat, connect
|
|
22
|
+
from .stream import (
|
|
23
|
+
DeferredReason,
|
|
24
|
+
PlaybackStatus,
|
|
25
|
+
StreamEndpoint,
|
|
26
|
+
StreamHub,
|
|
27
|
+
StreamPlayback,
|
|
28
|
+
)
|
|
23
29
|
from .wav import WavPcm, read_wav_pcm16
|
|
24
30
|
|
|
25
31
|
try: # populated from installed package metadata
|
|
@@ -28,9 +34,9 @@ try: # populated from installed package metadata
|
|
|
28
34
|
try:
|
|
29
35
|
__version__ = version("hapbeat-python-sdk")
|
|
30
36
|
except PackageNotFoundError: # running from a source checkout
|
|
31
|
-
__version__ = "0.
|
|
37
|
+
__version__ = "0.3.0+local"
|
|
32
38
|
except ImportError: # pragma: no cover
|
|
33
|
-
__version__ = "0.
|
|
39
|
+
__version__ = "0.3.0+local"
|
|
34
40
|
|
|
35
41
|
__all__ = [
|
|
36
42
|
"connect",
|
|
@@ -38,7 +44,11 @@ __all__ = [
|
|
|
38
44
|
"Device",
|
|
39
45
|
"EventMap",
|
|
40
46
|
"EventDef",
|
|
41
|
-
"
|
|
47
|
+
"StreamHub",
|
|
48
|
+
"StreamPlayback",
|
|
49
|
+
"StreamEndpoint",
|
|
50
|
+
"PlaybackStatus",
|
|
51
|
+
"DeferredReason",
|
|
42
52
|
"WavPcm",
|
|
43
53
|
"read_wav_pcm16",
|
|
44
54
|
"UdpClient",
|
hapbeat/cli.py
CHANGED
|
@@ -33,6 +33,8 @@ def build_parser() -> argparse.ArgumentParser:
|
|
|
33
33
|
p_play = sub.add_parser("play", help="play an event by id")
|
|
34
34
|
p_play.add_argument("event_id")
|
|
35
35
|
p_play.add_argument("--gain", type=float, default=None, help="0..1 (default: kit baseline)")
|
|
36
|
+
p_play.add_argument("--pan", type=float, default=0.0,
|
|
37
|
+
help="-1 left .. 0 centre .. +1 right (default 0)")
|
|
36
38
|
_add_common(p_play)
|
|
37
39
|
|
|
38
40
|
p_stop = sub.add_parser("stop", help="stop one event id")
|
|
@@ -106,9 +108,19 @@ def main(argv: list[str] | None = None) -> int:
|
|
|
106
108
|
|
|
107
109
|
hb = connect(port=args.port, default_target=getattr(args, "target", ""), keepalive=False)
|
|
108
110
|
try:
|
|
111
|
+
if args.command in ("play", "stop", "stop-all"):
|
|
112
|
+
# Discover before sending. Without a PONG the SDK knows no devices,
|
|
113
|
+
# so the command would go out as a broadcast — which the AP holds
|
|
114
|
+
# back until the next DTIM beacon, and which on a multi-homed host
|
|
115
|
+
# may leave through an interface with no Hapbeat behind it. One
|
|
116
|
+
# reply is enough to pick the subnet and unicast, and it normally
|
|
117
|
+
# arrives in a few milliseconds; the wait only costs the full
|
|
118
|
+
# window when nothing is there to answer.
|
|
119
|
+
hb.discover(timeout=0.4, stop_early=True)
|
|
120
|
+
|
|
109
121
|
if args.command == "play":
|
|
110
|
-
ok = hb.play(args.event_id, args.gain)
|
|
111
|
-
print(f"play {args.event_id} gain={args.gain if args.gain is not None else 'baseline'} -> {'sent' if ok else 'FAILED'}")
|
|
122
|
+
ok = hb.play(args.event_id, args.gain, pan=args.pan)
|
|
123
|
+
print(f"play {args.event_id} gain={args.gain if args.gain is not None else 'baseline'} pan={args.pan} -> {'sent' if ok else 'FAILED'}")
|
|
112
124
|
elif args.command == "stop":
|
|
113
125
|
print("sent" if hb.stop(args.event_id) else "FAILED")
|
|
114
126
|
elif args.command == "stop-all":
|
hapbeat/client.py
CHANGED
|
@@ -13,6 +13,13 @@ Design note — port binding:
|
|
|
13
13
|
back to an ephemeral bind: sends still work and PING replies still arrive
|
|
14
14
|
at the ephemeral source port; only async broadcast pushes on 7700 are
|
|
15
15
|
missed, which level-1 does not rely on.
|
|
16
|
+
|
|
17
|
+
Design note — broadcast destinations:
|
|
18
|
+
Discovery fans out across every local subnet (see :class:`BroadcastRoute`),
|
|
19
|
+
while playback goes to exactly one destination. Keeping those two apart is
|
|
20
|
+
not a detail: firmware older than v0.3.0 does not de-duplicate PLAY/STOP by
|
|
21
|
+
sequence number, so a device reachable on two destinations would fire the
|
|
22
|
+
haptic twice. PING and CONNECT_STATUS are idempotent and safe to duplicate.
|
|
16
23
|
"""
|
|
17
24
|
|
|
18
25
|
from __future__ import annotations
|
|
@@ -21,9 +28,10 @@ import logging
|
|
|
21
28
|
import socket
|
|
22
29
|
import threading
|
|
23
30
|
import time
|
|
24
|
-
from typing import Callable, Iterable, Optional
|
|
31
|
+
from typing import Callable, Iterable, List, Optional
|
|
25
32
|
|
|
26
33
|
from . import protocol
|
|
34
|
+
from .netif import local_ipv4_subnets
|
|
27
35
|
|
|
28
36
|
logger = logging.getLogger("hapbeat")
|
|
29
37
|
|
|
@@ -32,6 +40,87 @@ DEFAULT_BROADCAST = "255.255.255.255"
|
|
|
32
40
|
|
|
33
41
|
PongCallback = Callable[[dict, str], None]
|
|
34
42
|
|
|
43
|
+
# Stand-in "destination" for the case where a whole fan-out failed, so that
|
|
44
|
+
# outage gets the same once-per-outage treatment as a single address.
|
|
45
|
+
_ALL_DESTINATIONS = "all broadcast destinations"
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def _to_uint32(dotted: str) -> int:
|
|
49
|
+
a, b, c, d = (int(p) for p in dotted.split("."))
|
|
50
|
+
return (a << 24) | (b << 16) | (c << 8) | d
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def _to_dotted(value: int) -> str:
|
|
54
|
+
return "{}.{}.{}.{}".format(
|
|
55
|
+
(value >> 24) & 0xFF, (value >> 16) & 0xFF, (value >> 8) & 0xFF, value & 0xFF
|
|
56
|
+
)
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
class BroadcastRoute:
|
|
60
|
+
"""One address the SDK can broadcast to.
|
|
61
|
+
|
|
62
|
+
``255.255.255.255`` leaves a multi-homed host through the single interface
|
|
63
|
+
with the lowest metric. On a machine running Hyper-V / WSL2 / Docker that is
|
|
64
|
+
often an always-up virtual switch with no Hapbeat behind it — and no
|
|
65
|
+
Ethernet cable is needed for that to happen, which is why the symptom looks
|
|
66
|
+
nothing like "multi-homed". A subnet-directed address (``192.168.0.255``)
|
|
67
|
+
resolves through the directly-connected route for its subnet instead, so the
|
|
68
|
+
metric never applies. That is also why hapbeat-helper kept working on such a
|
|
69
|
+
host: it finds devices over mDNS and unicasts, which resolves the same way.
|
|
70
|
+
"""
|
|
71
|
+
|
|
72
|
+
__slots__ = ("addr", "network", "mask", "limited")
|
|
73
|
+
|
|
74
|
+
def __init__(self, addr: str, network: int = 0, mask: int = 0,
|
|
75
|
+
limited: bool = False) -> None:
|
|
76
|
+
self.addr = addr
|
|
77
|
+
self.network = network
|
|
78
|
+
self.mask = mask
|
|
79
|
+
self.limited = limited
|
|
80
|
+
|
|
81
|
+
def contains(self, ip: str) -> bool:
|
|
82
|
+
"""Whether ``ip`` sits on this route's subnet."""
|
|
83
|
+
if self.limited or not self.mask:
|
|
84
|
+
return False
|
|
85
|
+
try:
|
|
86
|
+
return (_to_uint32(ip) & self.mask) == self.network
|
|
87
|
+
except (ValueError, AttributeError):
|
|
88
|
+
return False
|
|
89
|
+
|
|
90
|
+
def __repr__(self) -> str: # pragma: no cover — debugging aid
|
|
91
|
+
return f"BroadcastRoute({self.addr})"
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def enumerate_broadcast_routes() -> List[BroadcastRoute]:
|
|
95
|
+
"""One destination per local IPv4 subnet, plus the limited broadcast.
|
|
96
|
+
|
|
97
|
+
The address comes from each interface's real mask rather than being assumed
|
|
98
|
+
to end in ``.255``: a /16 broadcasts to ``x.y.255.255`` and a /25 to
|
|
99
|
+
``x.y.z.127``, and the subnet itself is whatever the router hands out.
|
|
100
|
+
Deduplicated by address — two interfaces on one subnet (a laptop docked over
|
|
101
|
+
Ethernet while Wi-Fi is still up) would otherwise deliver every packet twice.
|
|
102
|
+
|
|
103
|
+
The limited broadcast is always kept as a catch-all, so SoftAP setups and
|
|
104
|
+
platforms whose interfaces cannot be enumerated behave exactly as before.
|
|
105
|
+
"""
|
|
106
|
+
routes: List[BroadcastRoute] = []
|
|
107
|
+
seen = set()
|
|
108
|
+
|
|
109
|
+
for ip, prefix in local_ipv4_subnets():
|
|
110
|
+
try:
|
|
111
|
+
ip_value = _to_uint32(ip)
|
|
112
|
+
except ValueError:
|
|
113
|
+
continue
|
|
114
|
+
mask = (0xFFFFFFFF << (32 - prefix)) & 0xFFFFFFFF
|
|
115
|
+
addr = _to_dotted((ip_value & mask) | (~mask & 0xFFFFFFFF))
|
|
116
|
+
if addr in seen:
|
|
117
|
+
continue
|
|
118
|
+
seen.add(addr)
|
|
119
|
+
routes.append(BroadcastRoute(addr, network=ip_value & mask, mask=mask))
|
|
120
|
+
|
|
121
|
+
routes.append(BroadcastRoute(DEFAULT_BROADCAST, limited=True))
|
|
122
|
+
return routes
|
|
123
|
+
|
|
35
124
|
|
|
36
125
|
class UdpClient:
|
|
37
126
|
"""Broadcast-capable UDP socket plus a PONG receive loop."""
|
|
@@ -51,16 +140,35 @@ class UdpClient:
|
|
|
51
140
|
# also receive the device's unsolicited broadcasts (daemon use).
|
|
52
141
|
self.bind_port = bind_port
|
|
53
142
|
self.broadcast_addr = broadcast_addr
|
|
143
|
+
# An explicit broadcast_addr is the caller naming the destination, so
|
|
144
|
+
# honour it verbatim: no enumeration, no fan-out, no route locking.
|
|
145
|
+
# This doubles as the escape hatch for anyone who does need to pin the
|
|
146
|
+
# destination by hand, which is why there is no separate setting.
|
|
147
|
+
self._auto_routes = broadcast_addr == DEFAULT_BROADCAST
|
|
148
|
+
self._routes: List[BroadcastRoute] = []
|
|
149
|
+
# The route a device actually answered on; None until the first PONG.
|
|
150
|
+
# Written from the receive thread, read from every sending thread —
|
|
151
|
+
# rebinding one attribute, which is atomic under the GIL.
|
|
152
|
+
self._locked_route: Optional[BroadcastRoute] = None
|
|
54
153
|
self._sock: Optional[socket.socket] = None
|
|
55
154
|
self._thread: Optional[threading.Thread] = None
|
|
56
155
|
self._running = False
|
|
57
156
|
self._bound_well_known = False
|
|
157
|
+
# Destinations currently in a failed state, so each outage is reported
|
|
158
|
+
# once rather than once per packet. See _note_send_failed.
|
|
159
|
+
self._failed_destinations: set[str] = set()
|
|
58
160
|
self._pong_callbacks: list[PongCallback] = []
|
|
59
161
|
|
|
60
162
|
# ── Lifecycle ───────────────────────────────────────────────────
|
|
61
163
|
def open(self) -> None:
|
|
62
164
|
if self._sock is not None:
|
|
63
165
|
return
|
|
166
|
+
# Enumerated per open() rather than once per process: the host's
|
|
167
|
+
# interfaces change when a laptop is docked, a VPN comes up or Wi-Fi
|
|
168
|
+
# moves to another network.
|
|
169
|
+
self._routes = enumerate_broadcast_routes() if self._auto_routes else []
|
|
170
|
+
self._locked_route = None
|
|
171
|
+
self._failed_destinations = set()
|
|
64
172
|
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
|
|
65
173
|
sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
|
|
66
174
|
# Windows only: a prior sendto() to an unreachable peer queues an ICMP
|
|
@@ -131,20 +239,129 @@ class UdpClient:
|
|
|
131
239
|
pass
|
|
132
240
|
|
|
133
241
|
# ── Send ────────────────────────────────────────────────────────
|
|
242
|
+
def broadcast_destination(self) -> str:
|
|
243
|
+
"""The single address a broadcast currently goes to.
|
|
244
|
+
|
|
245
|
+
Once a device has answered this is its subnet's broadcast address;
|
|
246
|
+
before that (and whenever the caller named ``broadcast_addr``) it is the
|
|
247
|
+
limited broadcast, exactly as it has always been.
|
|
248
|
+
"""
|
|
249
|
+
locked = self._locked_route
|
|
250
|
+
return locked.addr if locked is not None else self.broadcast_addr
|
|
251
|
+
|
|
252
|
+
def _note_send_failed(self, dst: str, exc: OSError) -> None:
|
|
253
|
+
"""Report a failed send at most once per destination, per outage.
|
|
254
|
+
|
|
255
|
+
A link that fails keeps failing, and stream chunks go out roughly 100
|
|
256
|
+
times a second — logging every one would bury the very lines an operator
|
|
257
|
+
needs. Tracked per destination rather than globally: a host normally has
|
|
258
|
+
an adapter that can never carry a broadcast (Bluetooth PAN, Wi-Fi
|
|
259
|
+
Direct, a virtual switch), and one shared flag would flip to "failed" and
|
|
260
|
+
back to "recovered" on every single fan-out. Cleared when that same
|
|
261
|
+
destination works again, so a later, unrelated outage is still reported.
|
|
262
|
+
"""
|
|
263
|
+
if dst in self._failed_destinations:
|
|
264
|
+
return
|
|
265
|
+
self._failed_destinations.add(dst)
|
|
266
|
+
logger.warning(
|
|
267
|
+
"UDP send to %s:%d failed: %s. The socket stays open; further send "
|
|
268
|
+
"errors to this destination are silenced until it recovers.",
|
|
269
|
+
dst, self.port, exc)
|
|
270
|
+
|
|
271
|
+
def _note_send_ok(self, dst: str) -> None:
|
|
272
|
+
"""Say once that a destination works again.
|
|
273
|
+
|
|
274
|
+
Without this an unattended installation's log shows when haptics broke
|
|
275
|
+
but never whether they came back.
|
|
276
|
+
"""
|
|
277
|
+
if dst not in self._failed_destinations:
|
|
278
|
+
return
|
|
279
|
+
self._failed_destinations.discard(dst)
|
|
280
|
+
logger.info("UDP sending to %s recovered.", dst)
|
|
281
|
+
|
|
134
282
|
def send(self, packet: bytes, addr: Optional[str] = None) -> bool:
|
|
135
|
-
"""Send a prebuilt packet. ``addr=None`` -> broadcast.
|
|
283
|
+
"""Send a prebuilt packet. ``addr=None`` -> broadcast.
|
|
284
|
+
|
|
285
|
+
One destination only. A failure is reported but never tears anything
|
|
286
|
+
down: a lost datagram says nothing about whether the socket is still
|
|
287
|
+
usable, and closing it here is what turns one Wi-Fi hiccup into a
|
|
288
|
+
session that never recovers.
|
|
289
|
+
"""
|
|
136
290
|
sock = self._sock
|
|
137
291
|
if sock is None:
|
|
138
292
|
logger.error("send before open()")
|
|
139
293
|
return False
|
|
140
|
-
dst = self.
|
|
294
|
+
dst = self.broadcast_destination() if not addr else addr
|
|
141
295
|
try:
|
|
142
296
|
sock.sendto(packet, (dst, self.port))
|
|
297
|
+
self._note_send_ok(dst)
|
|
143
298
|
return True
|
|
144
299
|
except OSError as exc:
|
|
145
|
-
|
|
300
|
+
self._note_send_failed(dst, exc)
|
|
146
301
|
return False
|
|
147
302
|
|
|
303
|
+
def send_discovery(self, packet: bytes) -> bool:
|
|
304
|
+
"""Send on every candidate broadcast destination.
|
|
305
|
+
|
|
306
|
+
Reserved for PING and CONNECT_STATUS. Both are idempotent, so a device
|
|
307
|
+
reachable on two destinations simply receives the message twice with no
|
|
308
|
+
visible effect — whereas duplicating PLAY would fire the haptic twice on
|
|
309
|
+
firmware that predates sequence de-duplication. This fan-out is what
|
|
310
|
+
reaches a device the limited broadcast never gets to, and the PONG it
|
|
311
|
+
provokes is what pins playback to the right subnet.
|
|
312
|
+
"""
|
|
313
|
+
sock = self._sock
|
|
314
|
+
if sock is None:
|
|
315
|
+
logger.error("send before open()")
|
|
316
|
+
return False
|
|
317
|
+
# Already pinned to a subnet, or no enumeration to fan out over: one
|
|
318
|
+
# destination, same as any other packet.
|
|
319
|
+
if self._locked_route is not None or not self._routes:
|
|
320
|
+
return self.send(packet)
|
|
321
|
+
|
|
322
|
+
sent = False
|
|
323
|
+
last_error: Optional[OSError] = None
|
|
324
|
+
for route in self._routes:
|
|
325
|
+
try:
|
|
326
|
+
sock.sendto(packet, (route.addr, self.port))
|
|
327
|
+
sent = True
|
|
328
|
+
self._note_send_ok(route.addr)
|
|
329
|
+
except OSError as exc:
|
|
330
|
+
# Routine, and not worth a warning on its own: most hosts carry
|
|
331
|
+
# an adapter that can never take a broadcast (Bluetooth PAN,
|
|
332
|
+
# Wi-Fi Direct, an idle virtual switch). Trying anyway and
|
|
333
|
+
# letting the others through is exactly what this fan-out is
|
|
334
|
+
# for. Only total failure below is worth an operator's
|
|
335
|
+
# attention — the difference is "one path is dead" versus
|
|
336
|
+
# "discovery is dead".
|
|
337
|
+
last_error = exc
|
|
338
|
+
logger.debug("discovery send to %s:%d failed: %s",
|
|
339
|
+
route.addr, self.port, exc)
|
|
340
|
+
if sent:
|
|
341
|
+
# Clear the "nothing got out" state too, so a second, later outage
|
|
342
|
+
# is reported instead of being swallowed by the first one's flag.
|
|
343
|
+
self._note_send_ok(_ALL_DESTINATIONS)
|
|
344
|
+
elif last_error is not None:
|
|
345
|
+
self._note_send_failed(_ALL_DESTINATIONS, last_error)
|
|
346
|
+
return sent
|
|
347
|
+
|
|
348
|
+
def _lock_route_for(self, ip: str) -> None:
|
|
349
|
+
"""Pin broadcasts to the subnet a device actually replied from.
|
|
350
|
+
|
|
351
|
+
First reply wins, and the choice lasts until the socket is reopened.
|
|
352
|
+
With devices on two subnets at once this settles on whichever answered
|
|
353
|
+
first; broadcasts do not cross subnets anyway, so the alternative is not
|
|
354
|
+
reaching both, it is reaching neither reliably.
|
|
355
|
+
"""
|
|
356
|
+
if self._locked_route is not None or not self._routes:
|
|
357
|
+
return
|
|
358
|
+
for route in self._routes:
|
|
359
|
+
if route.contains(ip):
|
|
360
|
+
self._locked_route = route
|
|
361
|
+
logger.info("broadcasting to %s (a device answered from %s)",
|
|
362
|
+
route.addr, ip)
|
|
363
|
+
return
|
|
364
|
+
|
|
148
365
|
def send_many(self, packet: bytes, addrs: Iterable[str]) -> bool:
|
|
149
366
|
"""Unicast the same packet to several devices.
|
|
150
367
|
|
|
@@ -183,6 +400,10 @@ class UdpClient:
|
|
|
183
400
|
if pong is None:
|
|
184
401
|
continue
|
|
185
402
|
ip = addr[0]
|
|
403
|
+
# A reply proves which subnet the device is really on. Until this
|
|
404
|
+
# happens a broadcast still goes out limited, which on a multi-homed
|
|
405
|
+
# host may be leaving through an interface with no Hapbeat behind it.
|
|
406
|
+
self._lock_route_for(ip)
|
|
186
407
|
for cb in list(self._pong_callbacks):
|
|
187
408
|
try:
|
|
188
409
|
cb(pong, ip)
|