SDKJava (Android) SDK

Data channels & read methods

Android Java SDK: Data channels & read methods

Current version · 2.0.0

Data channels & read methods

pose() returns optional payload.hand / payload.wrist, and imu() returns per-sensor payload.imus plus an optional payload.magnetometer. pressure() provides raw readings and estimatedKpa; emf() provides raw I/Q paired with hand pose. See Reading raw data for device requirements, units and fields. Select emf() on a worker thread to establish paired acquisition.

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.

Configure callback delivery

SubscriptionConfig.run(...) takes the Context, authorized transport, port, side, positive run seconds, and a SubscriptionConfig.latest(...) or SubscriptionConfig.fifo(...) setting. It counts pose deliveries while the background runtime runs, then prints the sample count, observed rate and last sequence. The example class shares its name with com.qnbot.sdk.channel.SubscriptionConfig, so the source uses the fully qualified SDK type.

import android.content.Context;
import com.qnbot.sdk.Sdk;
import com.qnbot.sdk.SdkConfig;
import com.qnbot.sdk.android.SerialTransport;
import com.qnbot.sdk.channel.ReadChannel;
import com.qnbot.sdk.config.SerialConnection;
import com.qnbot.sdk.config.Side;
import com.qnbot.sdk.glove.Glove;
import com.qnbot.sdk.glove.GloveConfig;
import com.qnbot.sdk.glove.GlovePose;
import java.util.Locale;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;

/**
 * Counts pose deliveries under a configured subscription policy.
 *
 * <p>Pass the host {@link Context}, an authorized transport, the glove port and side, the positive
 * run time, and a latest/FIFO subscription configuration. The SDK background thread delivers
 * poses; the summary compares received samples with observed delivery rate.
 */
public final class SubscriptionConfig {
  private SubscriptionConfig() {}

  public static void run(Context context, SerialTransport transport, String port, Side side,
      double seconds, com.qnbot.sdk.channel.SubscriptionConfig subscription)
      throws InterruptedException {
    if (!Double.isFinite(seconds) || seconds <= 0)
      throw new IllegalArgumentException("seconds must be positive and finite");
    SdkConfig config = SdkConfig.builder()
        .device(GloveConfig.builder()
                    .name("primary")
                    .side(side)
                    .connection(SerialConnection.port(port))
                    .build())
        .build();
    AtomicInteger count = new AtomicInteger();
    AtomicLong firstAt = new AtomicLong();
    AtomicLong lastAt = new AtomicLong();
    AtomicLong lastSequence = new AtomicLong();
    try (Sdk sdk = new Sdk(config, context, transport); Glove glove = sdk.glove()) {
      ReadChannel<GlovePose> pose = glove.device().pose();
      pose.withConfig(subscription).subscribe(sample -> {
        long now = System.nanoTime();
        firstAt.compareAndSet(0, now);
        lastAt.set(now);
        count.incrementAndGet();
        lastSequence.set(sample.sequence);
      });
      glove.start();
      glove.runBackground();
      try {
        Thread.sleep((long) (seconds * 1_000));
      } finally {
        glove.requestStop();
        glove.join();
      }
    }
    double observedHz = count.get() > 1
        ? (count.get() - 1) / ((lastAt.get() - firstAt.get()) / 1_000_000_000.0)
        : 0.0;
    System.out.printf(Locale.ROOT, "samples=%d observed_hz=%.2f last_sequence=%d%n", count.get(),
        observedHz, lastSequence.get());
    System.out.println("subscription complete");
  }
}

When a callback subscription returns a Subscription, keep it 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.

ConfigurationPending dataUse
SubscriptionConfig.latest()Coalesce to the newest valueLive UI
SubscriptionConfig.latest(30.0)Newest value, configured 30 Hz capReduce UI update load
SubscriptionConfig.fifo(128)At most 128; drop oldest when fullBounded ordered processing
SubscriptionConfig.fifo(128, 30.0)Bounded FIFO with a callback rate capBound 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.

Multiple named outputs

MultipleOutputs.run(...) declares primary and backup TargetConfig outputs on one glove source and subscribes to each with device.output(name). The outputs are named and delivered independently, which suits driving a robot hand while recording or previewing.

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.DeviceSelector;
import com.qnbot.sdk.config.SerialConnection;
import com.qnbot.sdk.config.Side;
import com.qnbot.sdk.config.TargetAlgorithm;
import com.qnbot.sdk.config.TargetConfig;
import com.qnbot.sdk.glove.Glove;
import com.qnbot.sdk.glove.GloveConfig;
import com.qnbot.sdk.glove.GloveDevice;

/**
 * Reads two target outputs driven by one glove.
 *
 * <p>Pass the host {@link Context}, an authorized transport, the glove port and side, and the
 * installed algorithm package. Separate subscriptions label each output and close with the SDK.
 */
public final class MultipleOutputs {
  private MultipleOutputs() {}

  public static void run(Context context, SerialTransport transport, String port, Side side,
      String packageId) {
    SdkConfig config = SdkConfig.builder()
        .device(GloveConfig.builder()
                    .name("primary")
                    .side(side)
                    .connection(SerialConnection.port(port))
                    .build())
        .target(TargetConfig.builder()
                    .name("primary")
                    .side(side)
                    .source(new DeviceSelector("glove", "primary", side))
                    .algorithm(new TargetAlgorithm(packageId))
                    .build())
        .target(TargetConfig.builder()
                    .name("backup")
                    .side(side)
                    .source(new DeviceSelector("glove", "primary", side))
                    .algorithm(new TargetAlgorithm(packageId))
                    .build())
        .build();
    try (Sdk sdk = new Sdk(config, context, transport); Glove glove = sdk.glove()) {
      GloveDevice device = glove.device();
      device.output("primary")
          .subscribe(sample
              -> System.out.println("callback primary sequence=" + sample.sequence
                  + " target=" + sample.value.target + " joints=" + sample.value.joints));
      device.output("backup")
          .subscribe(sample
              -> System.out.println("callback backup sequence=" + sample.sequence
                  + " target=" + sample.value.target + " joints=" + sample.value.joints));
      glove.start();
      glove.runForever();
    }
  }
}

Always pass the configured output name when reading; use device.output() for the default output. Check calibration and status separately for each output; do not assume they share one result.

Continuous asynchronous Publisher

channel.publisher() returns Flow.Publisher<Sample<T>>. The public examples have no equivalent generic subscriber wrapper, so the SampleSubscriber below is a docs helper that demonstrates explicit demand. 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.pose().withConfig(SubscriptionConfig.latest(30.0)) to attach() for glove pose, or device.telemetry() for Exo. A view configured with fifo(capacity, rate) also works. Each subscriber owns an independent subscription.

  • onSubscribe arrives first; positive request(n) adds demand. Long.MAX_VALUE means continuous demand. Zero or negative demand terminates with one IllegalArgumentException.
  • 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 onNext uses the same Latest/FIFO capacity, drop-oldest and maxRateHz behavior as callbacks. Publisher adds no second buffer or rate limiter. FIFO preserves the order of retained delivered samples only.
  • cancel() is repeatable and sends no onComplete. 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.