震动反馈
Android Java SDK:震动反馈
当前版本 · 1.4.0
震动反馈
设备启动后先检查 device.getDeviceInfo().capabilities.haptics,再通过 device.haptics() 设置左右强度。范围是 0–100,null 保留该侧原值;一次 set() 至少提供一侧。
公开示例 Haptics 先检查触觉能力,启动 SDK,按 left 和 right 设置两侧强度,保持 holdSeconds 秒,并在 finally 中清除,保证中断的保持也会释放马达。
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.ExoHaptics;
/**
* Sets Exo haptics for a hold duration, then clears them before the SDK closes.
*
* <p>Supply an Android {@link Context}, an authorized {@link SerialTransport}, the device port and
* the left/right strengths; the device must report haptics capability.
*/
public final class Haptics {
private Haptics() {}
public static void run(Context context, SerialTransport transport, String port, int left,
int right, double holdSeconds) throws Exception {
if (!Double.isFinite(holdSeconds) || holdSeconds < 0)
throw new IllegalArgumentException("holdSeconds must be finite and nonnegative");
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.haptics) {
System.out.println("Device has no haptics capability");
return;
}
exo.start();
// Clear in a finally block so an interrupted hold still releases the motors.
try {
device.haptics().set(new ExoHaptics(left, right));
Thread.sleep((long) (holdSeconds * 1000));
} finally {
device.haptics().clear();
}
}
}
}在已授权传输和显式端口下于工作线程运行,强度取 0 到 100,保持时长为有限非负值。由 app 计时;示例不会自动生成脉冲或停止。重连不会重放旧触觉。StateChannel<ExoHaptics> 还支持最新值、单次异步读取、callback 和 Publisher。
按 ExoControlException.kind() 处理失败;command()、deviceCode()、detail() 提供上下文。类型涵盖未连接、生命周期错误、不支持、不可用、忙、超时、协议、固件拒绝、传输和取消。不要解析错误文本,也不要通过重试掩盖不支持或参数错误。