psyclone-client for Python 2.3.2: pure Python, steady connections, and remote modules
psyclone-client connects a Python program to a running Psyclone system from the outside:
– it posts messages into the system by post name;
– it receives what the system’s triggers send out, by trigger name.
It works over UDP, TCP or WebSocket. Messages are CMSDK DataMessages, byte for byte the same as the C++ library makes them, in the full or the packed form.
It is pure Python with only the standard library. One wheel installs on Python 3.8 and later, on every operating system. There is nothing to compile.
pip install psyclone-client
Version 2.3.2 gives the Python client the same connection behaviour as the Kotlin/Java client, and adds RemoteModule, which lets a Python program be a full module of the system.
Five lines to a running system π
from psyclone_client import PsycloneClient, DataMessage
with PsycloneClient.websocket("ws://host:18600/phone", device="py-1") as psy: # or .udp(host, port), .tcp(...)
psy.on_trigger("Playout", lambda m: print("got", m.get_data("audio"))) # pushed by the system
psy.post("AudioFrame", DataMessage().set_data("audio", b"...")) # into the system
reply = psy.request("Question", DataMessage().set_string("Text", "hi"), timeout=3) # or None
The service it talks to is a few lines of PsySpec in any Psyclone 2.3+ system:
<service name="Phone">
<post name="AudioFrame" type="Voice.Audio.Frame"/>
<trigger name="Playout" type="Voice.Playout.Chunk"/>
</service>
<interface name="PhoneTCP" port="18600" protocol="HTTP" service="Phone"/> <!-- HTTP + WebSocket -->
<interface name="PhoneUDP" port="18600" ip="UDP" protocol="Message" service="Phone"/>
Connections that look after themselves π
The 2.3.2 client keeps its connections healthy on its own.
Keepalive on every transport. The client sends one every keepalive_interval (15 s) and right after connecting. A Psyclone 2.3.2 service answers at once and posts nothing. The answer carries the round-trip time, PsyVersion and PsyFeatures. An older service drops the keepalive, but only after refreshing the peer’s address, which keeps a UDP path through NAT open.
Dead links are noticed. Once the service has answered, keepalive_miss_limit (3) silent intervals mean the link is dead:
– TCP and WebSocket reconnect;
– UDP reports the link down and opens a new socket.
Reconnects back off with jitter. The delays start at 0.5 s and double to 10 s, each spread by Β±20 % (reconnect_jitter), so many clients don’t all come back at the same instant.
The packed form is negotiated. packed_mode=PackedMode.AUTO is the default. The client sends the full form until the service shows that it reads the packed form, then it switches. That is about 3x less overhead for small messages. PackedMode.FULL and PackedMode.PACKED fix the form, and packed=True/False from 2.3.1 still works.
You can see what is going on. stats() returns a ConnectionStats snapshot:
from psyclone_client import PsycloneClient, DataMessage
psy = PsycloneClient.udp("host", 18600, "sensor-7", keepalive_interval=10)
if psy.wait_server(5): # the service answered a keepalive
print("server", psy.stats().server_version, psy.server_features)
psy.post("Reading", DataMessage().set_double("Value", 21.5))
s = psy.stats()
print(s) # one log line
print(s.rtt_smoothed_ms, s.disconnects, s.packed_active, s.keepalives_answered)
psy.close()
The snapshot holds: – connects, drops, failed attempts and dead-link drops; – messages and bytes in each direction; – requests and timeouts; – keepalives sent and answered; – the RTT (last, smoothed, min, max); – the server’s version and features, and the last error.
as_dict() gives the same fields as a dict for your metrics.
Fits into asyncio π§΅
Handlers run on the client’s reader thread. To run them somewhere else, pass callback: any callable that runs a function, such as an asyncio loop’s call_soon_threadsafe:
import asyncio
from psyclone_client import PsycloneClient
async def main():
loop = asyncio.get_running_loop()
queue = asyncio.Queue()
psy = PsycloneClient.websocket("ws://host:18600/phone", device="py-async", callback=loop.call_soon_threadsafe)
psy.on_trigger("Playout", queue.put_nowait) # runs on the event loop
while True:
msg = await queue.get()
print(msg.get_string("Text"))
asyncio.run(main())
on_state_changed(lambda up, error: ...) reports each connect and drop. remove_handler(handler) takes a handler away again.
Be a module: RemoteModule π°οΈ
With a Psyclone 2.3.2 host, a Python program can be a full module of the system: – its triggers fire it; – it posts by post name; – it retrieves from whiteboards and queries catalogs; – PsyProbe can stop it, start it and change its parameters.
The spec declares the module and its host:
<service name="Modules">
<modules auth="key"/>
</service>
<interface name="ModTCP" port="18700" protocol="Message" service="Modules"/>
<module name="Asr" type="remote" service="Modules">
<trigger name="Audio" type="Voice.Audio.Frame"/>
<post name="Text" type="Voice.Asr.Text"/>
<retrieve name="Recent" source="ConvWB" type="Voice.Asr.Text" maxcount="10"/>
</module>
The program can use handlers, or pull messages one at a time like a crank:
from psyclone_client import PsycloneClient, RemoteModule, RemoteModuleError, Auth, DataMessage
psy = PsycloneClient.tcp("host", 18700, "asr-box-1")
try:
asr = RemoteModule.attach(psy, "Asr", Auth.key("psy_<id>_<secret>")) # or Auth.token(t), Auth.none()
except RemoteModuleError as e:
raise SystemExit("refused: %s" % e.status) # denied, unknown, busy, timeout, ...
print(asr.posts, asr.triggers) # the contract, from the server
asr.on_stop(lambda reason: print("stopped:", reason))
asr.on_dropped(lambda count, from_seq, reason: print("missed", count, "from", from_seq, reason))
while True:
m = asr.wait_for_new_message(1.0) # crank-style pull, or None
if m is not None and asr.current_trigger_name == "Audio":
asr.post("Text", DataMessage().set_string("Text", recognise(m)))
What the library does for you:
– The key’s secret never travels. The library proves the key with an HMAC on a nonce from the host. The key’s account needs the permission modules.attach.Asr.
– Resume after a reconnect. The library resumes the session with Resume and LastSeq. The host replays the triggers it kept in its resume buffer (256 messages / 5 s by default), and on_dropped reports anything it could not keep.
– Re-attach after a lease. If the host says the lease ran out, the library attaches again by itself (auto_reattach).
Dynamic modules build their contract at run time, inside the host’s <allow> policy:
from psyclone_client import Trigger
ext = RemoteModule.attach(psy, "Ext.Logger", Auth.key(api_key)) # a name inside <allow names>
ext.subscribe(Trigger("All", "Voice.*").max_age(1000).has_key("Text"))
ext.declare_post("Note", "Ext.Logger.Note")
ext.declare_parameter("Mode", "quiet")
ext.on_parameter(lambda name, value: print(name, "=", value)) # PsyProbe edits arrive here
rows = ext.retrieve_from("ConvWB", type="Voice.Asr.*", max_count=20) # ad hoc, inside <allow retrieve>
The library keeps the subscriptions and declarations, and sends them again when a new session starts.
retrieve, query, post_confirmed and describe wait for the host’s reply. Call them from a handler only when the client has a callback that runs handlers on another thread. The pull loop above has no such problem.
More on remote modules.
The same DataMessage as C++ π§¬
m = DataMessage().set_string("Name", "x").set_int("N", 42).set_double("Gain", 0.7).set_data("pcm", b"\0\1")
m["Other"] = 5 # by Python type: str, int, float, bytes, DataMessage
m.to_bytes(); m.to_packed_bytes() # the two wire forms
DataMessage.from_bytes(wire) # either form
The camelCase names of the C++ binding also work (setString, getInt, getBytes, fromBytes, …), so code moves easily between psyclone-client and cmsdk3. The test suite checks the codec against golden messages written by the C++ library.
Tested from Python 3.8 to 3.14 β
The 2.3.2 test suite has 49 tests. It covers the codec, the local transports and keepalive, plus live tests that start a real Psyclone for remote modules (declared and dynamic, resume after a cut link, dropped reports). It passes on:
– Python 3.8, 3.10, 3.12 and 3.14 on Linux;
– Python 3.10, 3.12, 3.13 and 3.14 on macOS.
psyclone-client or cmsdk3?
psyclone-client: for programs outside the system that talk to its services or attach as remote modules. It is pure Python (3.8+) with no native code.cmsdk3: the full C++ binding behind Python cranks inside Psyclone. It is now on PyPI as well: pip install cmsdk3.
Licence: BSD with the CADIA clause (CMSDK).
Read more
- User Guide ch. 11: Client libraries and Remote modules
- Release post: Psyclone AIOS 2.3.2
- psyclone-client on PyPI
- Psyclone: psyclone.cmlabs.com
- CMSDK: cmsdk.cmlabs.com
