SDKJava (Android) SDK

运行方式

Android Java SDK:运行方式

当前版本 · 2.0.0

运行方式

启动设备后只选择一种运行方式。普通 Android app 优先使用 runBackground(),让 app 工作线程协调 UI 和退出流程。

方式调用app 的责任
后台循环sdk.runBackground()业务结束时 requestStop、join、stop、disconnect
当前线程循环sdk.runForever()在专用工作线程调用,从控制线程请求停止
手动更新sdk.update()处理返回的任务/等待结果,不忙等

手动更新

ManualRuntime.run(...) 在固定次数的更新中逐步推进 Glove 业务:每次 update() 后调用一次 sleep(),没有可等待任务时短暂让出线程,然后打印最新的目标输出。它接收端口、左右手、算法包和正的更新次数。

import android.content.Context;
import com.qnbot.sdk.Sdk;
import com.qnbot.sdk.SdkConfig;
import com.qnbot.sdk.SleepResult;
import com.qnbot.sdk.android.SerialTransport;
import com.qnbot.sdk.channel.ReadChannel;
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;
import com.qnbot.sdk.glove.HandJointCommand;

/**
 * Advances Glove work manually for a requested number of updates.
 *
 * <p>Pass the host {@link Context}, an authorized transport, the glove port and side, the installed
 * algorithm package, and a positive update count. Each step waits for scheduled work, yields
 * briefly when the SDK has none, then prints the latest retargeted output.
 */
public final class ManualRuntime {
  private ManualRuntime() {}

  public static void run(Context context, SerialTransport transport, String port, Side side,
      String packageId, int updates) throws InterruptedException {
    if (updates <= 0)
      throw new IllegalArgumentException("updates must be positive");
    SdkConfig config = SdkConfig.builder()
        .device(GloveConfig.builder()
                    .name("primary")
                    .side(side)
                    .connection(SerialConnection.port(port))
                    .build())
        .target(TargetConfig.builder()
                    .name("openxr_hand")
                    .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();
      ReadChannel<HandJointCommand> output = device.output("openxr_hand");
      glove.start();
      for (int step = 0; step < updates; step++) {
        SleepResult outcome = glove.update().sleep();
        if (outcome == SleepResult.STOPPED)
          break;
        if (outcome == SleepResult.NO_TASKS) {
          // Preparation or Capture still needs the caller; yield instead of spinning.
          Thread.sleep(10);
        }
        output.latest().ifPresent(sample
            -> System.out.println("retargeting sequence=" + sample.sequence
                + " target=" + sample.value.target + " joints=" + sample.value.joints));
      }
    }
  }
}

从控制线程调用 requestStop() 结束循环。每次 update() 后调用一次 sleep()。hasNextTask 只表示是否有定时任务截止时间;它为 false 时,事件驱动任务仍可能需要等待。READY 继续循环,STOPPED 结束循环,NO_TASKS 表示当前没有可等待的工作。示例只在 NO_TASKS 时短暂休眠以避免忙等;不要用固定延时替代 SDK 等待。手动循环返回且会话结束时,按生命周期关闭 SDK。

后台与异步运行

ForegroundRuntime 在调用线程用 runForever() 持续读取目标输出,完整代码见读取 Retargeting 数据。BackgroundRuntime 在 SDK 后台线程运行固定时长,结束后 requestStop() 并 join()。

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;

/**
 * Runs retargeting on the SDK background thread for a fixed duration.
 *
 * <p>Pass the host {@link Context}, an authorized transport, the glove port and side, the installed
 * algorithm package, and the positive run time. The target subscription prints commands; cleanup
 * requests stop and joins the runner.
 */
public final class BackgroundRuntime {
  private BackgroundRuntime() {}

  public static void run(Context context, SerialTransport transport, String port, Side side,
      String packageId, double seconds) 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())
        .target(TargetConfig.builder()
                    .name("openxr_hand")
                    .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("openxr_hand")
          .subscribe(sample
              -> System.out.println("retargeting sequence=" + sample.sequence
                  + " target=" + sample.value.target + " joints=" + sample.value.joints));
      glove.start();
      glove.runBackground();
      try {
        Thread.sleep((long) (seconds * 1_000));
      } finally {
        glove.requestStop();
        glove.join();
      }
    }
    System.out.println("background stopped");
  }
}

AsyncRuntime 用 next() 和 Flow.Publisher 完成一次异步读取和连续流读取,并通过中断取消等待。

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.channel.Sample;
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;
import com.qnbot.sdk.glove.HandJointCommand;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Flow;
import java.util.concurrent.atomic.AtomicReference;

/**
 * Reads one retargeted sample with next(), then a bounded Flow stream.
 *
 * <p>Pass the host {@link Context}, an authorized transport, the glove port and side, the installed
 * algorithm package, and a positive sample count. The SDK background thread advances work; the
 * caller awaits the asynchronous reads and runner termination, then requests stop and joins during
 * cleanup. Interrupting the worker cancels the wait.
 */
public final class AsyncRuntime {
  private AsyncRuntime() {}

  /** Waits for either side; a failed runner stays the primary error. */
  private static void await(CompletableFuture<?> result, CompletableFuture<Void> runner)
      throws Exception {
    try {
      CompletableFuture.anyOf(result, runner).get();
    } catch (ExecutionException error) {
      if (runner.isCompletedExceptionally())
        runner.get();
      throw error;
    }
  }

  public static void run(Context context, SerialTransport transport, String port, Side side,
      String packageId, int samples) throws Exception {
    if (samples <= 0)
      throw new IllegalArgumentException("samples must be positive");
    SdkConfig config = SdkConfig.builder()
        .device(GloveConfig.builder()
                    .name("primary")
                    .side(side)
                    .connection(SerialConnection.port(port))
                    .build())
        .target(TargetConfig.builder()
                    .name("openxr_hand")
                    .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();
      ReadChannel<HandJointCommand> output = device.output("openxr_hand");
      CompletableFuture<Void> streamed = new CompletableFuture<>();
      AtomicReference<Flow.Subscription> active = new AtomicReference<>();
      var subscriber = new Flow.Subscriber<Sample<HandJointCommand>>() {
        private Flow.Subscription subscription;
        private int received;

        @Override
        public void onSubscribe(Flow.Subscription subscription) {
          this.subscription = subscription;
          active.set(subscription);
          subscription.request(1);
        }

        @Override
        public void onNext(Sample<HandJointCommand> sample) {
          try {
            System.out.println("stream retargeting sequence=" + sample.sequence
                + " target=" + sample.value.target + " joints=" + sample.value.joints);
            if (++received == samples)
              streamed.complete(null);
            else
              subscription.request(1);
          } catch (RuntimeException error) {
            streamed.completeExceptionally(error);
          }
        }

        @Override
        public void onError(Throwable error) {
          streamed.completeExceptionally(error);
        }

        @Override
        public void onComplete() {
          streamed.complete(null);
        }
      };
      glove.start();
      glove.runBackground();
      CompletableFuture<Void> runner = CompletableFuture.runAsync(glove::join);
      CompletableFuture<Sample<HandJointCommand>> next = output.next().toCompletableFuture();
      try {
        await(next, runner);
        if (runner.isCompletedExceptionally())
          runner.get();
        if (!next.isDone())
          throw new IllegalStateException("Background run ended before the first output sample");
        Sample<HandJointCommand> first = next.get();
        System.out.println("next retargeting sequence=" + first.sequence
            + " target=" + first.value.target + " joints=" + first.value.joints);

        output.publisher().subscribe(subscriber);
        await(streamed, runner);
        if (runner.isCompletedExceptionally())
          runner.get();
        if (!streamed.isDone())
          throw new IllegalStateException(
              "Background run ended before output consumption finished");
        streamed.get();
      } finally {
        next.cancel(false);
        Flow.Subscription subscription = active.get();
        if (subscription != null)
          subscription.cancel();
        // Stop only while the background join is still running, then observe its result.
        if (!runner.isDone())
          glove.requestStop();
        runner.join();
      }
    }
  }
}

外部帧输入

没有物理手套或使用自研输入时,将 GloveConfig.connection 设为 ExternalConnection.INSTANCE。配置和选择设备后调用 device.pushFrame(frame)。采集提示与确认的页面说明见采集。

ExternalInputManualUpdate 由应用提交外部帧并手动推进,同时在外部帧循环中处理采集提示。完整流程如下:

import android.content.Context;
import com.qnbot.sdk.Sdk;
import com.qnbot.sdk.SdkConfig;
import com.qnbot.sdk.SleepResult;
import com.qnbot.sdk.android.SerialTransport;
import com.qnbot.sdk.channel.ReadChannel;
import com.qnbot.sdk.config.AlgorithmsConfig;
import com.qnbot.sdk.config.DeviceSelector;
import com.qnbot.sdk.config.Side;
import com.qnbot.sdk.config.TargetAlgorithm;
import com.qnbot.sdk.config.TargetConfig;
import com.qnbot.sdk.glove.ExternalConnection;
import com.qnbot.sdk.glove.ExternalGloveFrame;
import com.qnbot.sdk.glove.Glove;
import com.qnbot.sdk.glove.GloveConfig;
import com.qnbot.sdk.glove.GloveDevice;
import com.qnbot.sdk.glove.GloveNodePose;
import com.qnbot.sdk.glove.calibration.CalibrationJobState;
import com.qnbot.sdk.glove.calibration.CalibrationProgress;
import com.qnbot.sdk.glove.capture.CaptureConfig;
import com.qnbot.sdk.glove.capture.CaptureControl;
import com.qnbot.sdk.glove.capture.CaptureInteractionMode;
import com.qnbot.sdk.glove.capture.CaptureProgress;
import com.qnbot.sdk.glove.capture.CaptureSessionState;
import com.qnbot.sdk.glove.capture.CaptureStageState;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.function.BooleanSupplier;
import java.util.function.Predicate;
import java.util.function.Supplier;

/**
 * Pushes application-owned glove frames while the caller advances the SDK manually, then prints
 * the first retargeting output.
 *
 * <p>Supply the Android Context, transport, side, package ID, Capture interaction and confirm
 * callback. Pass null frames for the built-in synthetic input; the loop ends after 60 seconds,
 * on cancellation, or when the frame supplier returns null.
 */
public final class ExternalInputManualUpdate {
  private ExternalInputManualUpdate() {}

  /**
   * confirm must return promptly: true confirms the displayed action, false leaves it pending.
   * cancelled stops the loop before output is published; both callbacks run on the caller thread.
   */
  public static void run(Context context, SerialTransport transport, Side side, String packageId,
      CaptureConfig captureConfig, Supplier<ExternalGloveFrame> frames, Predicate<String> confirm,
      BooleanSupplier cancelled) throws Exception {
    SdkConfig config = SdkConfig.builder()
                           .device(GloveConfig.builder()
                                       .name("primary")
                                       .side(side)
                                       .connection(ExternalConnection.INSTANCE)
                                       .build())
                           .algorithms(new AlgorithmsConfig(null, captureConfig))
                           .target(TargetConfig.builder()
                                       .name("openxr_hand")
                                       .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();
      var output = device.output("openxr_hand");
      ReadChannel<CaptureProgress> captureProgress = device.captureProgress();
      ReadChannel<CalibrationProgress> calibrationProgress =
          device.calibrationProgress("openxr_hand");
      CaptureControl captureControl = device.captureControl();
      Set<String> handledRequestIds = new HashSet<>();
      glove.start();
      long deadline = System.nanoTime() + 60_000_000_000L;
      int step = 1;
      while (!cancelled.getAsBoolean() && System.nanoTime() < deadline
          && output.latest().isEmpty()) {
        failIfPreparationFailed(captureProgress, calibrationProgress);
        ExternalGloveFrame input = frames == null ? frame(step++) : frames.get();
        if (input == null) {
          break;
        }
        device.pushFrame(input);
        var update = glove.update();
        if (captureConfig.interaction == CaptureInteractionMode.EXTERNAL) {
          handleCapturePrompt(captureProgress, captureControl, handledRequestIds, confirm,
              device.name());
        }
        if (!update.hasNextTask) {
          Thread.sleep(10);
        } else if (update.sleep() == SleepResult.STOPPED) {
          break;
        }
      }
      if (cancelled.getAsBoolean()) {
        return;
      }
      var sample = output.latest().orElseThrow(
          ()
              -> new IllegalStateException("External input did not publish retargeting output "
                  + "before input ended or timed out"));
      System.out.println("latest retargeting output sequence=" + sample.sequence
          + " target=" + sample.value.target + " joints=" + sample.value.joints);
    }
    System.out.println("external manual input complete");
  }

  private static void failIfPreparationFailed(ReadChannel<CaptureProgress> captureProgress,
      ReadChannel<CalibrationProgress> calibrationProgress) {
    captureProgress.latest().ifPresent(sample -> {
      var progress = sample.value;
      if (progress.sessionState == CaptureSessionState.FAILED
          || progress.sessionState == CaptureSessionState.CANCELLED) {
        throw new IllegalStateException(
            progress.failure == null ? "Capture stopped" : progress.failure.message);
      }
    });
    calibrationProgress.latest().ifPresent(sample -> {
      if (sample.value.job.state == CalibrationJobState.FAILED) {
        throw new IllegalStateException(sample.value.job.failure == null
                ? "Calibration stopped"
                : sample.value.job.failure.message);
      }
    });
  }

  private static void handleCapturePrompt(ReadChannel<CaptureProgress> captureProgress,
      CaptureControl captureControl, Set<String> handledRequestIds, Predicate<String> confirm,
      String sourceName) {
    captureProgress.latest().ifPresent(sample -> {
      var stage = sample.value.stage;
      if (stage.state == CaptureStageState.AWAITING_CONFIRMATION && stage.requestId != null
          && !handledRequestIds.contains(stage.requestId)
          && confirm.test(sourceName + " " + stage.prompt)) {
        captureControl.confirm(stage.requestId);
        handledRequestIds.add(stage.requestId);
      }
    });
  }

  private static ExternalGloveFrame frame(int step) {
    double offset = step * 0.001;
    return new ExternalGloveFrame(node(0.01 + offset, 0.02, 0.03), node(0.02 + offset, 0.03, 0.04),
        node(0.03 + offset, 0.04, 0.05), node(0.04 + offset, 0.05, 0.06),
        node(0.05 + offset, 0.06, 0.07), step * 10.0);
  }

  private static GloveNodePose node(double x, double y, double z) {
    return GloveNodePose.of(List.of(x, y, z), List.of(0.0, 0.0, 0.0, 1.0));
  }
}

ExternalInputRunBackground 使用 SDK 后台运行循环推进,并复用同一套提示处理:

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.AlgorithmsConfig;
import com.qnbot.sdk.config.DeviceSelector;
import com.qnbot.sdk.config.Side;
import com.qnbot.sdk.config.TargetAlgorithm;
import com.qnbot.sdk.config.TargetConfig;
import com.qnbot.sdk.glove.ExternalConnection;
import com.qnbot.sdk.glove.ExternalGloveFrame;
import com.qnbot.sdk.glove.Glove;
import com.qnbot.sdk.glove.GloveConfig;
import com.qnbot.sdk.glove.GloveDevice;
import com.qnbot.sdk.glove.GloveNodePose;
import com.qnbot.sdk.glove.calibration.CalibrationJobState;
import com.qnbot.sdk.glove.calibration.CalibrationProgress;
import com.qnbot.sdk.glove.capture.CaptureConfig;
import com.qnbot.sdk.glove.capture.CaptureControl;
import com.qnbot.sdk.glove.capture.CaptureInteractionMode;
import com.qnbot.sdk.glove.capture.CaptureProgress;
import com.qnbot.sdk.glove.capture.CaptureSessionState;
import com.qnbot.sdk.glove.capture.CaptureStageState;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.function.BooleanSupplier;
import java.util.function.Predicate;
import java.util.function.Supplier;

/**
 * Pushes application-owned glove frames while the SDK runs in the background, then prints the
 * first retargeting output.
 *
 * <p>Supply the Android Context, transport, side, package ID, Capture interaction and confirm
 * callback. Pass null frames for the built-in synthetic input; the loop ends after 60 seconds,
 * on cancellation, or when the frame supplier returns null.
 */
public final class ExternalInputRunBackground {
  private ExternalInputRunBackground() {}

  /**
   * confirm must return promptly: true confirms the displayed action, false leaves it pending.
   * cancelled stops the frame loop; both callbacks run on the caller thread.
   */
  public static void run(Context context, SerialTransport transport, Side side, String packageId,
      CaptureConfig captureConfig, Supplier<ExternalGloveFrame> frames, Predicate<String> confirm,
      BooleanSupplier cancelled) throws Exception {
    SdkConfig config = SdkConfig.builder()
                           .device(GloveConfig.builder()
                                       .name("primary")
                                       .side(side)
                                       .connection(ExternalConnection.INSTANCE)
                                       .build())
                           .algorithms(new AlgorithmsConfig(null, captureConfig))
                           .target(TargetConfig.builder()
                                       .name("openxr_hand")
                                       .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();
      var output = device.output("openxr_hand");
      ReadChannel<CaptureProgress> captureProgress = device.captureProgress();
      ReadChannel<CalibrationProgress> calibrationProgress =
          device.calibrationProgress("openxr_hand");
      CaptureControl captureControl = device.captureControl();
      Set<String> handledRequestIds = new HashSet<>();
      glove.start();
      glove.runBackground();
      try {
        long deadline = System.nanoTime() + 60_000_000_000L;
        int step = 1;
        while (!cancelled.getAsBoolean() && System.nanoTime() < deadline
            && output.latest().isEmpty()) {
          failIfPreparationFailed(captureProgress, calibrationProgress);
          ExternalGloveFrame input = frames == null ? frame(step++) : frames.get();
          if (input == null) {
            break;
          }
          device.pushFrame(input);
          if (captureConfig.interaction == CaptureInteractionMode.EXTERNAL) {
            handleCapturePrompt(captureProgress, captureControl, handledRequestIds, confirm,
                device.name());
          }
          Thread.sleep(10);
        }
        if (cancelled.getAsBoolean()) {
          return;
        }
        var sample = output.latest().orElseThrow(
            ()
                -> new IllegalStateException("External input did not publish retargeting output "
                    + "before input ended or timed out"));
        System.out.println("latest retargeting output sequence=" + sample.sequence);
      } finally {
        glove.requestStop();
        glove.join();
      }
    }
    System.out.println("external background input complete");
  }

  private static void failIfPreparationFailed(ReadChannel<CaptureProgress> captureProgress,
      ReadChannel<CalibrationProgress> calibrationProgress) {
    captureProgress.latest().ifPresent(sample -> {
      var progress = sample.value;
      if (progress.sessionState == CaptureSessionState.FAILED
          || progress.sessionState == CaptureSessionState.CANCELLED) {
        throw new IllegalStateException(
            progress.failure == null ? "Capture stopped" : progress.failure.message);
      }
    });
    calibrationProgress.latest().ifPresent(sample -> {
      if (sample.value.job.state == CalibrationJobState.FAILED) {
        throw new IllegalStateException(sample.value.job.failure == null
                ? "Calibration stopped"
                : sample.value.job.failure.message);
      }
    });
  }

  private static void handleCapturePrompt(ReadChannel<CaptureProgress> captureProgress,
      CaptureControl captureControl, Set<String> handledRequestIds, Predicate<String> confirm,
      String sourceName) {
    captureProgress.latest().ifPresent(sample -> {
      var stage = sample.value.stage;
      if (stage.state == CaptureStageState.AWAITING_CONFIRMATION && stage.requestId != null
          && !handledRequestIds.contains(stage.requestId)
          && confirm.test(sourceName + " " + stage.prompt)) {
        captureControl.confirm(stage.requestId);
        handledRequestIds.add(stage.requestId);
      }
    });
  }

  private static ExternalGloveFrame frame(int step) {
    double offset = step * 0.001;
    return new ExternalGloveFrame(node(0.01 + offset, 0.02, 0.03), node(0.02 + offset, 0.03, 0.04),
        node(0.03 + offset, 0.04, 0.05), node(0.04 + offset, 0.05, 0.06),
        node(0.05 + offset, 0.06, 0.07), step * 10.0);
  }

  private static GloveNodePose node(double x, double y, double z) {
    return GloveNodePose.of(List.of(x, y, z), List.of(0.0, 0.0, 0.0, 1.0));
  }
}

ExternalGloveFrame 需要 thumb、index、middle、ring、pinky 五个 GloveNodePose,位置三维、旋转四维且按 xyzw 排列;四元数不能全为零。timestampMs 可为空,有值时必须有限。使用 GloveNodePose.of(position, quaternionXyzw) 创建每根手指的数据。

手动模式按输入和 update() 推进业务;上述循环运行时,从另一线程持续提交外部帧;NO_TASKS 不表示外部输入或校准已经完成。后台模式保持后台循环运行,不再同时调用 update()。