Psyclone from Kotlin, Java and Android: psyclone-client 2.3.2
Java, Kotlin and Android programs connect to a Psyclone system with one library, com.cmlabs:psyclone-client. It uses the system’s own message model:
– a program posts messages by post name;
– it receives what the system sends back by trigger name, as the modules inside the system do.
Version 2.3.2 makes the library hold its connections well on real networks: phones that switch from Wi-Fi to mobile data, laptops that sleep, servers behind NAT. It also adds RemoteModule, which lets a JVM program become a full module of the system.
The library is one dependency with no native code, free and open source (BSD).
Install π¦
// Gradle (Kotlin DSL)
implementation("com.cmlabs:psyclone-client:2.3.2")
<!-- Maven -->
<dependency>
<groupId>com.cmlabs</groupId>
<artifactId>psyclone-client</artifactId>
<version>2.3.2</version>
</dependency>
It runs on any JVM 17 or later and on Android 8 (API 26) and later. It depends only on the CMSDK message codec, com.cmlabs:cmsdk-kotlin, which comes in with the client, and on the Kotlin standard library. It needs no OkHttp, no java.net.http and no JNI.
From Kotlin π£
import cmlabs.cmsdk.DataMessage
import cmlabs.psyclone.client.PsycloneClient
val psy = PsycloneClient.webSocket("wss://host:8443/phone", device = "phone-1") // or .udp(host, port), .tcp(...)
psy.onTrigger("Playout") { msg -> play(msg.getData("audio")) } // pushed by the system
psy.post("AudioFrame", DataMessage().setData("audio", opus)) // into the system
val answer = psy.request("Question", DataMessage().setString("Text", "hi")) // reply, or null on timeout
psy.close()
From Java β
import cmlabs.cmsdk.DataMessage;
import cmlabs.psyclone.client.PsycloneClient;
PsycloneClient psy = PsycloneClient.udp("host", 18600, "sensor-7");
psy.onTrigger("Command", msg -> handle(msg)); // pushed by the system
psy.post("Reading", new DataMessage().setDouble("Value", 21.5)); // into the system
System.out.println(psy.stats()); // one-line connection summary
On the Psyclone side the client talks to a <service>. Its posts say what incoming data becomes, and its triggers say what goes back out:
<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"/>
Programs outside never post raw message types, so the system stays in control of what gets in.
What’s new in 2.3.2 π
Keepalive and dead links
On every transport the client sends a keepalive every 15 s (keepAliveIntervalMs), and one right after connecting. A Psyclone 2.3.2 service answers it at once, without posting anything. The reply carries the round-trip time, whether the service reads the packed form, its version and its features.
Once the service has answered, keepAliveMissLimit (3) silent intervals mean the link is dead:
– TCP and WebSocket drop the socket and reconnect. This catches half-open sockets after a network change, which the operating system can take minutes to notice.
– UDP reports the link down (isConnected is false), opens a new socket, and comes back up on the next reply.
An older service drops the keepalive, but only after it has refreshed the peer’s address. So the UDP path through NAT stays open either way.
Packed form by default
PackedMode.AUTO is the default. The client sends the full DataMessage form until the service shows that it reads the packed form, then it switches. That is about 3x less overhead for small messages. You can fix the form with PackedMode.FULL or PackedMode.PACKED. isPackedActive tells you which form is in use.
Reconnects with jitter
TCP and WebSocket reconnect by themselves: from 500 ms, doubling to 10 s, with each delay spread by Β±20 % (reconnectDelays, reconnectJitter). The spread stops a fleet of devices from all reconnecting in the same instant after an outage. onStateChanged reports each connect, drop and failed attempt.
Stats
stats() returns a ConnectionStats snapshot with:
– the state and how long the connection has been up;
– connects, drops, failed attempts and dead-link drops;
– messages and bytes in each direction, and send failures;
– requests and timeouts;
– keepalives sent and answered;
– the round-trip time (last, smoothed, min, max);
– the server’s version and features, and the last error.
toString() gives one log line, and Java code uses the getters:
ConnectionStats s = psy.stats();
System.out.println("rtt " + s.getRttSmoothedMs() + " ms, drops " + s.getDisconnects() + ", packed " + s.getPackedActive());
TLS that checks the name on the desktop JVM
wss:// and tls() use the platform trust store, or your own CA through sslSocketFactory(...). The hostname is checked: on the JVM during the TLS handshake, and on Android by the platform verifier. In 2.3.1, wss:// with hostname checking failed on the desktop JVM, because the JDK’s default verifier refuses every name. That is fixed in 2.3.2.
Become a module: RemoteModule π°οΈ
With a Psyclone 2.3.2 host, a JVM program can be a full module of the system: triggers, posts, whiteboard retrieves, catalog queries, and PsyProbe stop and start. The spec declares <module name="Asr" type="remote" service="Modules">, and the program attaches:
import cmlabs.psyclone.client.RemoteModule
import java.util.concurrent.Executors
val psy = PsycloneClient.tcp("host", 18700, device = "asr-box-1",
options = PsycloneClient.Options().callbackExecutor(Executors.newSingleThreadExecutor()))
val asr = RemoteModule.attach(psy, "Asr", RemoteModule.Auth.key("psy_<id>_<secret>")) // or .token(t), .none()
asr.onTrigger("Audio") { msg -> asr.post("Text", DataMessage().setString("Text", recognise(msg))) }
val recent: List<DataMessage> = asr.retrieve("Recent", maxCount = 5)
asr.onStop { reason -> pause() }
asr.onStart { reason -> resume() }
From Java the same calls are static and use lambdas:
RemoteModule asr = RemoteModule.attach(psy, "Asr", RemoteModule.Auth.key(apiKey));
asr.onTrigger("Audio", msg -> asr.post("Text", new DataMessage().setString("Text", recognise(msg))));
After a reconnect, the module resumes its session by itself, and the host replays the triggers it missed. onDropped { count, fromSeq, reason -> } reports anything the host could not keep. The details are in our post on remote modules.
On Android π€
- Requirements: minSdk 26. Add the
INTERNETpermission to the app manifest. - What the client uses: only
java.netsockets,HttpURLConnectionand its own RFC 6455 WebSocket client. - How it is checked:
./gradlew animalsnifferMain :client:animalsnifferMainchecks the compiled classes against the Android API 26 signatures;- both jars dex cleanly with
d8 --min-api 26; - 2.3.2 also fixes a codec call that older Android runtimes did not have (
ByteBuffer.position(int)).
- Threads: pass the main executor to
Options.callbackExecutor(...)when handlers touch the UI. Create the client off the main thread, because the UDP socket opens in the factory call.
Tested against a real Psyclone β
The live tests start a real Psyclone with the engine’s own test systems. They cover:
– UDP, TCP Message, WebSocket and wss;
– packed-form negotiation and keepalive RTT;
– a device moving to a new address;
– a burst of 1000 datagrams;
– every transport recovering when the system restarts;
– HTTP request/reply;
– remote modules: attach with API keys, takeover, lease expiry, dynamic modules and resume after a cut link.
For 2.3.2: 59 tests run, 7 skipped, 0 failed, at the release tag on Linux and on the release candidate on macOS.
What about Java inside Psyclone?
Modules inside a Psyclone system are written in C++ or Python. The old Windows-only Java (SWIG/JNI) bindings had been unmaintained for years, and 2.3.2 removes them. There are no Java cranks. A JVM program takes part in a system through this library, and with RemoteModule it can now be a full module.
Read more
- User Guide ch. 11: Client libraries and Remote modules
- Release post: Psyclone AIOS 2.3.2
- com.cmlabs:psyclone-client on Maven Central
- Psyclone: psyclone.cmlabs.com
- CMSDK: cmsdk.cmlabs.com
