hapbeat-python-sdk 0.1.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 +15 -5
- hapbeat/cli.py +22 -4
- hapbeat/client.py +268 -9
- hapbeat/eventmap.py +1 -1
- hapbeat/hapbeat.py +399 -59
- hapbeat/launchpad.py +3 -2
- hapbeat/netif.py +270 -0
- hapbeat/osc.py +4 -2
- hapbeat/protocol.py +210 -23
- hapbeat/stream.py +766 -0
- hapbeat/stream_lease.py +182 -0
- hapbeat/update_check.py +213 -0
- {hapbeat_python_sdk-0.1.0.dist-info → hapbeat_python_sdk-0.3.0.dist-info}/METADATA +49 -20
- hapbeat_python_sdk-0.3.0.dist-info/RECORD +20 -0
- {hapbeat_python_sdk-0.1.0.dist-info → hapbeat_python_sdk-0.3.0.dist-info}/WHEEL +1 -1
- hapbeat/clip.py +0 -121
- hapbeat_python_sdk-0.1.0.dist-info/RECORD +0 -17
- {hapbeat_python_sdk-0.1.0.dist-info → hapbeat_python_sdk-0.3.0.dist-info}/entry_points.txt +0 -0
- {hapbeat_python_sdk-0.1.0.dist-info → hapbeat_python_sdk-0.3.0.dist-info}/licenses/LICENSE +0 -0
- {hapbeat_python_sdk-0.1.0.dist-info → hapbeat_python_sdk-0.3.0.dist-info}/top_level.txt +0 -0
hapbeat/__init__.py
CHANGED
|
@@ -5,7 +5,7 @@ Quick start::
|
|
|
5
5
|
import hapbeat
|
|
6
6
|
|
|
7
7
|
hb = hapbeat.connect(app_name="MyExperiment")
|
|
8
|
-
hb.play("
|
|
8
|
+
hb.play("sample-kit.sine_100hz", gain=0.3)
|
|
9
9
|
hb.stop_all()
|
|
10
10
|
hb.close()
|
|
11
11
|
|
|
@@ -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
|
@@ -3,8 +3,8 @@
|
|
|
3
3
|
Examples::
|
|
4
4
|
|
|
5
5
|
hapbeat scan
|
|
6
|
-
hapbeat play
|
|
7
|
-
hapbeat stop
|
|
6
|
+
hapbeat play sample-kit.sine_100hz --gain 0.3
|
|
7
|
+
hapbeat stop sample-kit.sine_100hz
|
|
8
8
|
hapbeat stop-all
|
|
9
9
|
hapbeat osc-bridge --listen 7702
|
|
10
10
|
hapbeat launchpad
|
|
@@ -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")
|
|
@@ -72,6 +74,12 @@ def build_parser() -> argparse.ArgumentParser:
|
|
|
72
74
|
def main(argv: list[str] | None = None) -> int:
|
|
73
75
|
args = build_parser().parse_args(argv)
|
|
74
76
|
|
|
77
|
+
# 新しい版が出ていれば stderr に 1 行だけ (同じ版では 2 回目を出さない)。
|
|
78
|
+
# キャッシュが無ければ裏で取りに行くだけでコマンドは待たせない。
|
|
79
|
+
# ライブラリ import 側では絶対に呼ばない — CLI 実行時のみ (DEC-053 §5.4)。
|
|
80
|
+
from . import update_check
|
|
81
|
+
update_check.notify_cli(__version__)
|
|
82
|
+
|
|
75
83
|
if args.command == "osc-bridge":
|
|
76
84
|
from .osc import OscBridge
|
|
77
85
|
|
|
@@ -100,9 +108,19 @@ def main(argv: list[str] | None = None) -> int:
|
|
|
100
108
|
|
|
101
109
|
hb = connect(port=args.port, default_target=getattr(args, "target", ""), keepalive=False)
|
|
102
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
|
+
|
|
103
121
|
if args.command == "play":
|
|
104
|
-
ok = hb.play(args.event_id, args.gain)
|
|
105
|
-
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'}")
|
|
106
124
|
elif args.command == "stop":
|
|
107
125
|
print("sent" if hb.stop(args.event_id) else "FAILED")
|
|
108
126
|
elif args.command == "stop-all":
|
hapbeat/client.py
CHANGED
|
@@ -1,8 +1,10 @@
|
|
|
1
1
|
"""UDP transport for the Hapbeat SDK.
|
|
2
2
|
|
|
3
|
-
Owns one datagram socket configured for broadcast. Sends
|
|
4
|
-
the LAN broadcast address and runs a background
|
|
5
|
-
replies so device discovery works.
|
|
3
|
+
Owns one datagram socket configured for broadcast. Sends packets either to a
|
|
4
|
+
known device (unicast) or to the LAN broadcast address, and runs a background
|
|
5
|
+
thread that collects PONG replies so device discovery works. Which of the two
|
|
6
|
+
a given packet takes is decided one layer up, in :class:`hapbeat.Hapbeat`,
|
|
7
|
+
which is the layer that tracks devices.
|
|
6
8
|
|
|
7
9
|
Design note — port binding:
|
|
8
10
|
The standard transport is Wi-Fi UDP broadcast (see workspace CLAUDE.md).
|
|
@@ -11,6 +13,13 @@ Design note — port binding:
|
|
|
11
13
|
back to an ephemeral bind: sends still work and PING replies still arrive
|
|
12
14
|
at the ephemeral source port; only async broadcast pushes on 7700 are
|
|
13
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.
|
|
14
23
|
"""
|
|
15
24
|
|
|
16
25
|
from __future__ import annotations
|
|
@@ -19,9 +28,10 @@ import logging
|
|
|
19
28
|
import socket
|
|
20
29
|
import threading
|
|
21
30
|
import time
|
|
22
|
-
from typing import Callable, Optional
|
|
31
|
+
from typing import Callable, Iterable, List, Optional
|
|
23
32
|
|
|
24
33
|
from . import protocol
|
|
34
|
+
from .netif import local_ipv4_subnets
|
|
25
35
|
|
|
26
36
|
logger = logging.getLogger("hapbeat")
|
|
27
37
|
|
|
@@ -30,6 +40,87 @@ DEFAULT_BROADCAST = "255.255.255.255"
|
|
|
30
40
|
|
|
31
41
|
PongCallback = Callable[[dict, str], None]
|
|
32
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
|
+
|
|
33
124
|
|
|
34
125
|
class UdpClient:
|
|
35
126
|
"""Broadcast-capable UDP socket plus a PONG receive loop."""
|
|
@@ -49,18 +140,51 @@ class UdpClient:
|
|
|
49
140
|
# also receive the device's unsolicited broadcasts (daemon use).
|
|
50
141
|
self.bind_port = bind_port
|
|
51
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
|
|
52
153
|
self._sock: Optional[socket.socket] = None
|
|
53
154
|
self._thread: Optional[threading.Thread] = None
|
|
54
155
|
self._running = False
|
|
55
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()
|
|
56
160
|
self._pong_callbacks: list[PongCallback] = []
|
|
57
161
|
|
|
58
162
|
# ── Lifecycle ───────────────────────────────────────────────────
|
|
59
163
|
def open(self) -> None:
|
|
60
164
|
if self._sock is not None:
|
|
61
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()
|
|
62
172
|
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
|
|
63
173
|
sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
|
|
174
|
+
# Windows only: a prior sendto() to an unreachable peer queues an ICMP
|
|
175
|
+
# port-unreachable, which Winsock surfaces as ConnectionResetError
|
|
176
|
+
# (WinError 10054) on the *next* recvfrom() — even on this unconnected
|
|
177
|
+
# socket. Once we unicast (a device that is off, rebooting, or being
|
|
178
|
+
# reflashed is unreachable) that becomes routine, and the recv loop
|
|
179
|
+
# below would die on it: the SDK would then go deaf to ALL PONGs until
|
|
180
|
+
# the process restarts. SIO_UDP_CONNRESET=False tells Windows to ignore
|
|
181
|
+
# those resets. No-op elsewhere (the constant is Windows-only).
|
|
182
|
+
# Same fix as hapbeat-helper f06fa04, which shipped before this SDK.
|
|
183
|
+
if hasattr(socket, "SIO_UDP_CONNRESET"):
|
|
184
|
+
try:
|
|
185
|
+
sock.ioctl(socket.SIO_UDP_CONNRESET, False)
|
|
186
|
+
except OSError as exc:
|
|
187
|
+
logger.debug("SIO_UDP_CONNRESET ioctl failed (non-fatal): %s", exc)
|
|
64
188
|
if self.bind_port == self.port:
|
|
65
189
|
# Only when contending for the shared well-known port do we ask to
|
|
66
190
|
# reuse it; an ephemeral bind needs no reuse and must not steal a
|
|
@@ -115,20 +239,142 @@ class UdpClient:
|
|
|
115
239
|
pass
|
|
116
240
|
|
|
117
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
|
+
|
|
118
282
|
def send(self, packet: bytes, addr: Optional[str] = None) -> bool:
|
|
119
|
-
"""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
|
+
"""
|
|
120
290
|
sock = self._sock
|
|
121
291
|
if sock is None:
|
|
122
292
|
logger.error("send before open()")
|
|
123
293
|
return False
|
|
124
|
-
dst = self.
|
|
294
|
+
dst = self.broadcast_destination() if not addr else addr
|
|
125
295
|
try:
|
|
126
296
|
sock.sendto(packet, (dst, self.port))
|
|
297
|
+
self._note_send_ok(dst)
|
|
127
298
|
return True
|
|
128
299
|
except OSError as exc:
|
|
129
|
-
|
|
300
|
+
self._note_send_failed(dst, exc)
|
|
130
301
|
return False
|
|
131
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
|
+
|
|
365
|
+
def send_many(self, packet: bytes, addrs: Iterable[str]) -> bool:
|
|
366
|
+
"""Unicast the same packet to several devices.
|
|
367
|
+
|
|
368
|
+
Returns True if at least one send succeeded. One unreachable device
|
|
369
|
+
(powered off between its last PONG and now) must not stop the packet
|
|
370
|
+
from reaching the others, so failures are logged and skipped.
|
|
371
|
+
"""
|
|
372
|
+
sent = False
|
|
373
|
+
for addr in addrs:
|
|
374
|
+
if self.send(packet, addr):
|
|
375
|
+
sent = True
|
|
376
|
+
return sent
|
|
377
|
+
|
|
132
378
|
# ── Recv loop ───────────────────────────────────────────────────
|
|
133
379
|
def _recv_loop(self) -> None:
|
|
134
380
|
while self._running:
|
|
@@ -139,12 +385,25 @@ class UdpClient:
|
|
|
139
385
|
data, addr = sock.recvfrom(4096)
|
|
140
386
|
except socket.timeout:
|
|
141
387
|
continue
|
|
142
|
-
except OSError:
|
|
143
|
-
|
|
388
|
+
except OSError as exc:
|
|
389
|
+
if not self._running or self._sock is None:
|
|
390
|
+
break # closed by close() — expected exit
|
|
391
|
+
# Still running: residual ICMP-unreachable (should be
|
|
392
|
+
# suppressed by SIO_UDP_CONNRESET above, but stay defensive in
|
|
393
|
+
# case the ioctl was unavailable) or a brief NIC flap. Breaking
|
|
394
|
+
# here is exactly what makes an SDK go permanently deaf to
|
|
395
|
+
# PONGs, so back off briefly and keep listening.
|
|
396
|
+
logger.debug("UDP recv transient error (continuing): %s", exc)
|
|
397
|
+
time.sleep(0.2)
|
|
398
|
+
continue
|
|
144
399
|
pong = protocol.parse_pong(data)
|
|
145
400
|
if pong is None:
|
|
146
401
|
continue
|
|
147
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)
|
|
148
407
|
for cb in list(self._pong_callbacks):
|
|
149
408
|
try:
|
|
150
409
|
cb(pong, ip)
|
hapbeat/eventmap.py
CHANGED
|
@@ -139,7 +139,7 @@ class EventMap:
|
|
|
139
139
|
{
|
|
140
140
|
"kit": "kits/my-kit", # kit folder, relative to this file
|
|
141
141
|
"events": {
|
|
142
|
-
"
|
|
142
|
+
"sample-kit.sine_100hz": { "target": "player_1/chest", "gain": 0.8 },
|
|
143
143
|
"rain.loop": { "target": "*/back" }
|
|
144
144
|
}
|
|
145
145
|
}
|