Data channels & read methods
Android Java SDK: Data channels & read methods
Data channels & read methods
ReadChannel<T> supports latest() for a retained snapshot, next() for a CompletionStage<Sample<T>> resolving with the next sample, and subscribe(Consumer<Sample<T>>) for continuous callbacks until unsubscribed. publisher() provides continuous consumption with explicit demand.
Continuous telemetry
The public Telemetry example subscribes to both Exo telemetry and connection status before start, then prints each sample's sequence, encoder counts, joint radians, connection state, stale flag, reconnect count and last error.
import android.content.Context;
import com.qnbot.sdk.Sdk;
import com.qnbot.sdk.SdkConfig;
import com.qnbot.sdk.android.SerialTransport;
import com.qnbot.sdk.config.SerialConnection;
import com.qnbot.sdk.exo.Exo;
import com.qnbot.sdk.exo.ExoConfig;
import com.qnbot.sdk.exo.ExoDevice;
/**
* Subscribes to Exo telemetry and connection status.
*
* <p>Supply an Android {@link Context}, an authorized {@link SerialTransport} and the device port.
*/
public final class Telemetry {
private Telemetry() {}
public static void run(Context context, SerialTransport transport, String port) {
SdkConfig config = SdkConfig.builder()
.device(ExoConfig.builder()
.connection(SerialConnection.port(port))
.build())
.build();
try (Sdk sdk = new Sdk(config, context, transport); Exo exo = sdk.exo()) {
ExoDevice device = exo.device();
// Subscribe before start so both channels are ready when the first sample arrives.
device.telemetry().subscribe(sample
-> System.out.println("telemetry sequence=" + sample.sequence
+ " leftEncoders=" + sample.value.payload.leftArm.encoderCounts
+ " rightEncoders=" + sample.value.payload.rightArm.encoderCounts
+ " leftRadians=" + sample.value.payload.leftArm.jointPositionsRad
+ " rightRadians=" + sample.value.payload.rightArm.jointPositionsRad));
device.status().subscribe(sample
-> System.out.println("status sequence=" + sample.sequence + " connected="
+ sample.value.connected + " stale=" + sample.value.stale + " reconnects="
+ sample.value.reconnectCount + " error=" + sample.value.lastError));
exo.start();
exo.runForever();
}
}
}Run Telemetry.run(context, transport, port) on a worker thread. exo.runForever() blocks the calling worker until the SDK is stopped or closed from another thread.
Configure callback delivery
device.telemetry().withConfig(SubscriptionConfig.latest(30.0)).subscribe(...) coalesces pending samples to the newest value and caps the callback rate; SubscriptionConfig.fifo(128, 30.0) keeps bounded order with the same cap. Keep the returned Subscription and call unsubscribe() when finished. Callbacks execute on worker threads; do not update Android Views directly or wait for SDK shutdown inside a callback. Keep the returned CompletionStage and call its toCompletableFuture().cancel(false) to cancel that pending one-shot read. Channels belonging to closed devices or SDKs cannot be reused.
| Configuration | Pending data | Use |
|---|---|---|
SubscriptionConfig.latest() | Coalesce to the newest value | Live UI |
SubscriptionConfig.latest(30.0) | Newest value, configured 30 Hz cap | Reduce UI update load |
SubscriptionConfig.fifo(128) | At most 128; drop oldest when full | Bounded ordered processing |
SubscriptionConfig.fifo(128, 30.0) | Bounded FIFO with a callback rate cap | Bound consumer load |
Configuration boundaries
Capacity must be positive; maxRateHz must be positive and finite. Omitting the rate adds no extra cap. Configuration affects only new callbacks created from the withConfig() view, not the original channel, existing subscriptions, latest() or next(). StateChannel.withConfig() retains set() and clear().
The first available sample is delivered immediately. Callback work counts within the rate period; only the remaining time is waited. A callback exceeding the period earns no extra full-period wait, and idle/slow periods earn no catch-up credit. The cap controls window cadence with one sample of boundary allowance, not equal spacing or device/algorithm computation rate. Uncapped subscriptions add no fixed 200 Hz limit. FIFO is not lossless recording: overflow drops the oldest pending samples.
Handset payloads
Start with leftHandset or rightHandset inside sample.value.payload to read the left or right handset. These correspond to the raw arrays Joystick_Left_Data and Joystick_Right_Data. Indices start at 0; both sides use the same format.
| Array index | SDK field | Physical input | Meaning |
|---|---|---|---|
[0] | axisXRaw | Joystick X axis | Raw axis value |
[1] | axisYRaw | Joystick Y axis | Raw axis value |
[2] | buttonMask | Buttons, joystick press, and SW | Independent 16-bit button mask per side; check individual bits |
[3] | triggerRaw | Trigger | Separate raw analog value; read directly |
raw means a device reading; the SDK does not define normalized ranges for axes or triggers. Read triggerRaw for the trigger. buttonMask packs digital button and switch states and does not contain trigger travel.
The public Handset example checks capabilities.handsets before subscribing, then prints the axes, triggers and button masks of both handsets from every telemetry sample. If the capability is absent, it reports that instead of printing an empty state.
import android.content.Context;
import com.qnbot.sdk.Sdk;
import com.qnbot.sdk.SdkConfig;
import com.qnbot.sdk.android.SerialTransport;
import com.qnbot.sdk.config.SerialConnection;
import com.qnbot.sdk.exo.Exo;
import com.qnbot.sdk.exo.ExoConfig;
import com.qnbot.sdk.exo.ExoDevice;
/**
* Prints Exo handset axes, triggers and buttons.
*
* <p>Supply an Android {@link Context}, an authorized {@link SerialTransport} and the device port;
* the device must report handset capability.
*/
public final class Handset {
private Handset() {}
public static void run(Context context, SerialTransport transport, String port) {
SdkConfig config = SdkConfig.builder()
.device(ExoConfig.builder()
.connection(SerialConnection.port(port))
.build())
.build();
try (Sdk sdk = new Sdk(config, context, transport); Exo exo = sdk.exo()) {
ExoDevice device = exo.device();
if (!device.getDeviceInfo().capabilities.handsets) {
System.out.println("Device has no handset capability");
return;
}
// Subscribe before start so the channel is ready when the first sample arrives.
device.telemetry().subscribe(sample
-> System.out.println("handsets sequence=" + sample.sequence
+ " left=" + sample.value.payload.leftHandset.axisXRaw + ","
+ sample.value.payload.leftHandset.axisYRaw
+ " right=" + sample.value.payload.rightHandset.axisXRaw + ","
+ sample.value.payload.rightHandset.axisYRaw
+ " leftTrigger=" + sample.value.payload.leftHandset.triggerRaw
+ " rightTrigger=" + sample.value.payload.rightHandset.triggerRaw
+ " leftButtons=" + sample.value.payload.leftHandset.buttonMask
+ " rightButtons=" + sample.value.payload.rightHandset.buttonMask));
exo.start();
exo.runForever();
}
}
}Plus handset controlsInteractive example
Click the 3D model or 16-bit mask map to toggle controls and sync the example word.
Loading 3D…
sample.value.payload. leftHandset.buttonMask(mask & 0x0002) == 00x10xF0x10xFRegular buttons are active low ((button_value & mask) == 0 means pressed), while the switch is active high ((button_value & 0x0020) != 0 means on). Both handsets share the same mapping and are read independently; STD uses only bits 0–5 (without Back, Mode, Start, BkT, or BkB).
This example checks A, B, and SW independently on both handsets. Use the masks in the table and the same active-low check for the other buttons.
device.telemetry().subscribe(sample -> {
com.qnbot.sdk.exo.ExoHandsetState left = sample.value.payload.leftHandset;
com.qnbot.sdk.exo.ExoHandsetState right = sample.value.payload.rightHandset;
System.out.println("left A=" + ((left.buttonMask & 0x0002) == 0)
+ " B=" + ((left.buttonMask & 0x0004) == 0)
+ " SW=" + ((left.buttonMask & 0x0020) != 0));
System.out.println("right A=" + ((right.buttonMask & 0x0002) == 0)
+ " B=" + ((right.buttonMask & 0x0004) == 0)
+ " SW=" + ((right.buttonMask & 0x0020) != 0));
});Check each bit separately for simultaneous presses instead of treating the entire integer as a single button identifier.
IMU payloads
The public Imu example checks capabilities.imus, then prints each non-null torso or extra IMU state with acceleration, angular velocity and orientation. If the capability is absent, it reports that instead of printing an empty state.
import android.content.Context;
import com.qnbot.sdk.Sdk;
import com.qnbot.sdk.SdkConfig;
import com.qnbot.sdk.android.SerialTransport;
import com.qnbot.sdk.config.SerialConnection;
import com.qnbot.sdk.exo.Exo;
import com.qnbot.sdk.exo.ExoConfig;
import com.qnbot.sdk.exo.ExoDevice;
import com.qnbot.sdk.exo.ExoImuState;
/**
* Prints supported Exo IMU samples.
*
* <p>Supply an Android {@link Context}, an authorized {@link SerialTransport} and the device port;
* the device must report IMU capability.
*/
public final class Imu {
private Imu() {}
public static void run(Context context, SerialTransport transport, String port) {
SdkConfig config = SdkConfig.builder()
.device(ExoConfig.builder()
.connection(SerialConnection.port(port))
.build())
.build();
try (Sdk sdk = new Sdk(config, context, transport); Exo exo = sdk.exo()) {
ExoDevice device = exo.device();
if (!device.getDeviceInfo().capabilities.imus) {
System.out.println("Device has no IMU capability");
return;
}
// The payload carries a torso IMU and an optional extra IMU; print whichever is present.
device.telemetry().subscribe(sample -> {
for (ExoImuState imu :
new ExoImuState[] {sample.value.payload.torsoImu, sample.value.payload.extraImu}) {
if (imu != null)
System.out.println("IMU sequence=" + sample.sequence + " acceleration="
+ imu.accelerationMps2 + " angularVelocity=" + imu.angularVelocityRadS
+ " quaternion=" + imu.orientationXyzw);
}
});
exo.start();
exo.runForever();
}
}
}Continuous asynchronous Publisher
channel.publisher() returns Flow.Publisher<Sample<T>>. The helper below is a documentation helper, not one of the SDK main examples: it requests one more sample after processing each item. Keep the value returned by attach() and call cancel() from a worker when finished. The app supplies consume, failure and completed, and posts UI work to the main thread.
import com.qnbot.sdk.channel.ReadChannel;
import com.qnbot.sdk.channel.Sample;
import com.qnbot.sdk.channel.Subscription;
import java.util.concurrent.Flow;
import java.util.function.Consumer;
public final class SampleSubscriber<T> implements Flow.Subscriber<Sample<T>> {
private final Consumer<Sample<T>> consume;
private final Consumer<Throwable> failure;
private final Runnable completed;
private volatile Flow.Subscription subscription;
public SampleSubscriber(Consumer<Sample<T>> consume,
Consumer<Throwable> failure, Runnable completed) {
this.consume = consume;
this.failure = failure;
this.completed = completed;
}
public static <T> SampleSubscriber<T> attach(ReadChannel<T> channel,
Consumer<Sample<T>> consume, Consumer<Throwable> failure, Runnable completed) {
SampleSubscriber<T> subscriber = new SampleSubscriber<>(consume, failure, completed);
channel.publisher().subscribe(subscriber);
return subscriber;
}
@Override public void onSubscribe(Flow.Subscription value) {
subscription = value;
value.request(1);
}
@Override public void onNext(Sample<T> sample) {
consume.accept(sample);
subscription.request(1);
}
@Override public void onError(Throwable error) { failure.accept(error); }
@Override public void onComplete() { completed.run(); }
public void cancel() {
Flow.Subscription current = subscription;
if (current != null) current.cancel();
}
}Pass device.telemetry().withConfig(SubscriptionConfig.latest(30.0)) to attach() for Exo telemetry. A view configured with fifo(capacity, rate) also works. Each subscriber owns an independent subscription.
onSubscribearrives first; positiverequest(n)adds demand.Long.MAX_VALUEmeans continuous demand. Zero or negative demand terminates with oneIllegalArgumentException.- Samples arriving without demand are discarded and later requests do not replay them. FIFO does not guarantee retention during no-demand periods. Resuming demand receives subsequent callbacks; use
latest()separately for current state. - Slow
onNextuses the same Latest/FIFO capacity, drop-oldest andmaxRateHzbehavior as callbacks. Publisher adds no second buffer or rate limiter. FIFO preserves the order of retained delivered samples only. cancel()is repeatable and sends noonComplete. Outside a callback it waits for an in-flight callback; inside a callback it releases the subscription after return.- Closing the SDK or corresponding device completes an active subscriber once. Registration or decoding failure sends one
onError. Device failures continue through status and health channels.
Do not close devices or the SDK in subscriber callbacks. Schedule closure on a worker outside the callback. Enable standard desugaring as described in Installation & requirements to retain API26 support.