1"""PsycloneClient: post into a Psyclone system by post name, receive its triggers by trigger name."""
6from concurrent.futures
import Future
7from concurrent.futures
import TimeoutError
as FutureTimeout
9from .datamessage
import DataMessage, Layout
10from .stats
import StatsCounters
11from .transports
import TcpTransport, UdpTransport, WebSocketTransport
16REQUEST_ID =
"PsyClientRequestID"
19KEEPALIVE =
"PsyKeepAlive"
20KEEPALIVE_SENT =
"PsyKeepAliveSent"
21KEEPALIVE_REPLY =
"PsyKeepAliveReply"
25 """Which DataMessage wire form the client sends."""
36 return len(data) >= 8
and int.from_bytes(data[4:8],
"little") == Layout.PACKEDDATAMESSAGEID
40 """Client settings (all optional keyword arguments of the factory functions).
42 packed_mode: PackedMode.AUTO (default), FULL or PACKED. packed: True = PACKED, False = FULL (kept from
43 2.3.1; prefer packed_mode). reconnect, reconnect_min, reconnect_max (seconds): TCP/WebSocket reconnect
44 backoff (UDP: reopening a socket), spread by +-reconnect_jitter (0..1, default 0.2).
45 keepalive_interval (s, default 15; 0 = none, AUTO still sends one keepalive after connecting to negotiate
46 the packed form), keepalive_miss_limit (default 3; once the service has answered keepalives, silence
47 for this many intervals = a dead connection; 0 = never).
48 connect_timeout (s), ping_interval (s, WebSocket keep-alive, 0 = none), headers (WebSocket upgrade),
49 ssl_context (wss:// and tls(); None = the system's trust store), local_port (UDP), max_message_bytes,
50 callback: a callable that runs handlers, e.g. ``loop.call_soon_threadsafe``; None = the reader thread.
53 def __init__(self, packed=None, reconnect=True, reconnect_min=0.5, reconnect_max=10.0, connect_timeout=5.0,
54 ping_interval=20.0, headers=None, ssl_context=None, local_port=0, max_message_bytes=64 << 20,
55 callback=None, packed_mode=None, reconnect_jitter=0.2, keepalive_interval=15.0,
56 keepalive_miss_limit=3):
57 if packed_mode
is None:
58 packed_mode = PackedMode.AUTO
if packed
is None else (PackedMode.PACKED
if packed
else PackedMode.FULL)
59 if packed_mode
not in (PackedMode.FULL, PackedMode.PACKED, PackedMode.AUTO):
60 raise ValueError(
"packed_mode must be PackedMode.FULL, PACKED or AUTO: %r" % (packed_mode,))
78 """True when the packed form is forced (PackedMode.PACKED)."""
83 self.
packed_mode = PackedMode.PACKED
if v
else PackedMode.FULL
87 """What the transport calls (on its reader thread)."""
94 self.
c._on_bytes(data)
97 self.
c._on_text_frame(text)
100 self.
c._on_state(connected, error)
104 """A client for a Psyclone ``<service>``, over UDP, TCP or WebSocket.
108 psy = PsycloneClient.websocket("wss://host:8443/phone", device="phone-1")
109 psy.on_trigger("Playout", lambda msg: play(msg.get_data("audio"))) # the system pushes to us
110 psy.post("AudioFrame", DataMessage().set_data("audio", opus)) # fire-and-forget into it
111 answer = psy.request("Question", DataMessage().set_string("Text", "hi")) # reply, or None
114 Every message sent names one of the service's posts in ``PsyPost`` (the service applies that post's
115 type; a client never sets a type) and carries ``PsyDevice`` when ``device`` is set. Every message
116 received carries ``PsyTrigger``. ``request()`` adds ``PsyClientRequestID`` and waits for the reply
117 carrying it back: a responder that copies the request (the built-in ``Simple`` crank) does; one that
118 builds a new message must copy ``PsyClientRequestID`` and ``PsyServiceConnection``.
120 Every ``keepalive_interval`` (and right after connecting) the client sends a keepalive
121 (``PsyPost=PsyKeepAlive``, ``PsyKeepAlive=<seq>``). A Psyclone 2.3.2+ service answers it without posting
122 anything (round-trip time, ``PsyPacked``, ``PsyVersion``; 2.3.2+ also ``PsyFeatures``); an older one
123 drops it after refreshing the peer's address, which still keeps a UDP path (NAT) open, and keeps a
124 2.3.2+ service from forgetting a silent UDP peer. Once a service has answered keepalives, a connection
125 that stays silent for ``keepalive_miss_limit`` intervals is treated as dead: TCP/WebSocket reconnect,
126 UDP reports the link down and opens a new socket.
128 Handlers run on the reader thread unless ``callback`` is given. TCP and WebSocket reconnect by
129 themselves, with a doubling, jittered back-off; nothing is queued while a pipe is down (``post()``
130 returns False). The service learns a UDP peer's address from its first datagram (the first keepalive
146 self.
_prefix =
"r%x-" % (int.from_bytes(os.urandom(6),
"little"))
152 self.
_stream =
not isinstance(transport, UdpTransport)
163 transport.start(
_Sink(self))
168 def udp(cls, host, port, device=None, **options):
169 """UDP to an ``<interface ip="UDP" protocol="Message">``; keep messages under ~1200 bytes on mobile."""
174 def tcp(cls, host, port, device=None, **options):
175 """TCP to an ``<interface protocol="Message">`` (CMSDK Message framing)."""
177 return cls(
TcpTransport(host, port,
False, o), device, o)
180 def tls(cls, host, port, device=None, **options):
181 """TCP + TLS to an ``<interface protocol="Message">`` with encryption."""
183 return cls(
TcpTransport(host, port,
True, o), device, o)
187 """WebSocket (``ws://`` or ``wss://``) to a service's HTTP interface; any path."""
195 msg = DataMessage.from_bytes(data)
196 except (ValueError, UnicodeDecodeError, IndexError, KeyError):
201 if msg.has(KEEPALIVE):
202 if msg.has(KEEPALIVE_REPLY):
219 self.
_counters.last_receive = time.monotonic()
229 """Count what arrived; a UDP link that was judged dead is up again."""
231 self.
_counters.last_receive = time.monotonic()
243 c.connected_since = time.time()
247 c.connected_since = 0.0
249 elif not up
and error
is not None:
250 c.add(
"connect_failures")
254 if notify
and not self.
_closed:
255 self.
_dispatch([(
lambda u=up, e=error, f=f: f(u, e),
None)
for f
in list(self.
_state)], raw=
True)
259 c.add(
"keepalives_answered")
261 sent_us = msg.get_int(KEEPALIVE_SENT)
262 if sent_us
is not None:
263 rtt_us = time.monotonic_ns() // 1000 - sent_us
264 if 0 <= rtt_us <= 600000000:
265 c.rtt(rtt_us / 1000.0)
266 v = msg.get_string(
"PsyVersion")
269 f = msg.get_string(
"PsyFeatures")
271 c.server_features = [x.strip()
for x
in f.split(
",")
if x.strip()]
272 if self.
options.packed_mode == PackedMode.AUTO
and msg.get_int(
"PsyPacked") == 1:
276 """Every keepalive interval: judge the link, then send a keepalive (also at once after connecting)."""
277 interval = self.
options.keepalive_interval
278 next_tick = time.monotonic() + interval
if interval > 0
else None
280 timeout =
None if next_tick
is None else max(0.0, next_tick - time.monotonic())
281 woken = self.
_wake.wait(timeout)
288 next_tick = time.monotonic() + interval
291 except Exception
as e:
295 limit = self.
options.keepalive_miss_limit
297 silent = time.monotonic() - self.
_counters.last_receive
298 if silent > self.
options.keepalive_interval * limit:
299 why = TimeoutError(
"nothing received for %d ms (keepalives unanswered)" % int(silent * 1000))
305 self.
_counters.last_receive = time.monotonic()
312 m =
DataMessage().set_string(POST, KEEPALIVE).set_int(KEEPALIVE, next(self.
_ka_seq)) \
313 .set_int(KEEPALIVE_SENT, time.monotonic_ns() // 1000)
314 if self.
device is not None:
315 m.set_string(DEVICE, self.
device)
316 data = m.to_packed_bytes()
if self.
packed_active else m.to_bytes()
319 self.
_counters.add(
"bytes_sent", len(data))
323 rid = msg.get_string(REQUEST_ID)
331 if self.
_modules and msg.has(
"PsyModule"):
332 for listener
in list(self.
_modules):
335 trig = msg.get_string(TRIGGER)
336 calls = [(h, msg)
for h
in self.
_handlers.get(trig, ())] + [(h, msg)
for h
in self.
_any]
341 """Run fn() where handlers run (the ``callback`` executor, or here)."""
348 h()
if raw
else h(arg)
351 traceback.print_exc()
361 """'udp', 'tcp', 'tls', 'ws' or 'wss'."""
366 """Stream transports: while the socket is up. UDP: while its socket is open and (once the service has
367 answered keepalives) the service keeps answering."""
371 """A ConnectionStats snapshot of this connection's counters, state and round-trip times."""
377 """The service's PsyFeatures from its last keepalive reply (a list; empty before Psyclone 2.3.2)."""
378 return list(self.
_counters.server_features)
381 """Call handler(msg) for every message the service trigger named ``trigger`` sends."""
382 self.
_handlers.setdefault(trigger, []).append(handler)
386 """Call handler(msg) for every message received (after trigger handlers), except request replies."""
387 self.
_any.append(handler)
391 """WebSocket text frames: handler(str). Without one they arrive as messages with a ``Text`` entry."""
392 self.
_text.append(handler)
396 """listener(connected, error) when the connection comes up or goes down (error is None for a clean
397 change); failed reconnect attempts are reported as (False, error) too. UDP: up while its socket is
398 open and, once the service has answered a keepalive, while it keeps answering."""
399 self.
_state.append(listener)
403 """Remove ``handler`` from on_any_message and every on_trigger list."""
404 if handler
in self.
_any:
405 self.
_any.remove(handler)
407 while handler
in lst:
410 def post(self, post, msg=None):
411 """Post ``msg`` (sets ``PsyPost`` and ``PsyDevice`` on it) as the service post named ``post``.
412 Returns False when the pipe is down (nothing is queued)."""
414 raise RuntimeError(
"client closed")
417 msg.set_string(POST, post)
418 if self.
device is not None:
419 msg.set_string(DEVICE, self.
device)
420 data = msg.to_packed_bytes()
if self.
packed_active else msg.to_bytes()
424 self.
_counters.add(
"bytes_sent", len(data))
430 """Send a WebSocket text frame (posted as a ``Text`` entry to the service's only post)."""
434 self.
_counters.add(
"bytes_sent", len(text))
440 """Post and return a concurrent.futures.Future for the reply (TimeoutError after ``timeout`` s)."""
447 msg.set_string(REQUEST_ID, rid)
448 if not self.
post(post, msg):
451 f.set_exception(ConnectionError(
"not connected"))
458 if gone
is not None and not gone.done():
460 gone.set_exception(TimeoutError(
"no reply to %s within %.1f s" % (post, timeout)))
461 t = threading.Timer(timeout, expire)
464 f.add_done_callback(
lambda _f: t.cancel())
467 def request(self, post, msg=None, timeout=5.0):
468 """Blocking request: the reply DataMessage, or None on timeout or when the pipe is down."""
470 return self.
request_async(post, msg, timeout).result(timeout + 1.0)
471 except (TimeoutError, FutureTimeout, ConnectionError):
475 """Wait until connected (``connected``); True if it is."""
476 end = time.monotonic() + timeout
478 if self.
_closed or time.monotonic() > end:
484 """Wait until the service has answered a keepalive (a Psyclone 2.3.2+ service; AUTO has then
485 negotiated the packed form); True if it has."""
486 end = time.monotonic() + timeout
488 if self.
_closed or time.monotonic() > end:
503 f.set_exception(ConnectionError(
"client closed"))
on_state(self, connected, error)
__init__(self, packed=None, reconnect=True, reconnect_min=0.5, reconnect_max=10.0, connect_timeout=5.0, ping_interval=20.0, headers=None, ssl_context=None, local_port=0, max_message_bytes=64<< 20, callback=None, packed_mode=None, reconnect_jitter=0.2, keepalive_interval=15.0, keepalive_miss_limit=3)
_state_changed(self, transport_up, error)
on_trigger(self, trigger, handler)
wait_server(self, timeout)
_on_state(self, connected, error)
request(self, post, msg=None, timeout=5.0)
_dispatch(self, calls, raw=False)
post(self, post, msg=None)
tcp(cls, host, port, device=None, **options)
on_any_message(self, handler)
websocket(cls, url, device=None, **options)
_on_text_frame(self, text)
tls(cls, host, port, device=None, **options)
request_async(self, post, msg=None, timeout=5.0)
remove_handler(self, handler)
__init__(self, transport, device, options)
# a new connection may reach another server negotiate again _stream
udp(cls, host, port, device=None, **options)
on_state_changed(self, listener)
bool server_answers_keepalive
wait_connected(self, timeout)
_keepalive_reply(self, msg)