Applicable Scenarios
This Skill is triggered when a developer describes the following scenarios:
- Integrating / connecting to the DJI Cloud API 2 SDK (Java)
- Listening to drone or dock status (OSD, online status, battery level, etc.)
- Controlling the drone (takeoff, return-to-home/cancel return-to-home, emergency stop, point-of-interest flight; landing is implemented via returnHome)
- Starting / stopping live streams
- Managing flight tasks (creating, pausing, resuming waypoint routes)
- Encountering SDK-related errors (errorCode, initialization failure, null return)
- Managing devices (list, bind, unbind, detail query)
SDK Mental Model
The DJI Cloud API 2 Java SDK isevent-driven, and the core pattern is listen / cancel:
FlightHubSDK(静态入口)
→ initialize(FlightHubSdkConfig) ← 同步阻塞,返回 ErrorCode,必须检查
→ getWorkspaceInstance() ← 可能返回 null
→ workspace.getDeviceManageModule().getDeviceList(cb)
→ getDroneInstance(sn) ← 可能返回 null
→ getDockInstance(sn) ← 可能返回 null
→ drone.getXxxModule() ← 通过子模块 getter 访问能力
→ module.listenXxx(callback) ← 返回 int listenId (≥0 成功, <0 失败)
→ module.cancelListenXxx(id) ← 服务关闭时必须调用
Note:listenDroneOnlineStatus is in DeviceStateModule(not DroneOsdModule),listenDeviceHMS is in DeviceHMSModule(not DroneOsdModule).
Modular Access Pattern(v3.1.0) — device instances expose submodules via getter methods:
drone.getControlAuthModule()— Flight controller/payload control authoritydrone.getFlightControlModule()— Return-to-home, emergency stop, joystick, DRC real-time telemetry (drcOsdInfo/drcBatteriesInfo)drone.getTakeoffModule()— Takeoff, command task events (listenCommandTaskEvent)drone.getDroneOsdModule()— WebSocket telemetry listening (position/battery/speed/attitude/payload, etc.; the push channel uses the WebSocket configured innotificationServerAddress, not MQTT)drone.getDeviceStateModule()— Online status (listenDroneOnlineStatus)drone.getDeviceHMSModule()— Health management alerts (listenDeviceHMS)drone.getDrcModule()— DRC link connect/disconnect, link status listeningdrone.getFlyToPointModule()— Point-of-interest flight (start/drcStop/updateTargetPoints)drone.getCameraControlModule()— Camera control, DRC laser ranging (listenDrcCameraMeasureTarget), DRC camera statusdrone.getLiveDeviceModule()— Live streaming device management (listenLiveAvailableRange)drone.getPoiModule()— Point-of-interest orbitingdock.getDeviceStateModule()— Dock online status (listenDockOnlineStatus)dock.getDeviceHMSModule()— Dock health management alertsdock.getDockOsdModule()— Dock telemetry (position/weather/storage/network, etc.)dock.getDockControlModule()— Dock auxiliary device control (camera switching/air conditioning/fill light/charging/dock cover); for the full method list + enums seecloudapi2-device-management/references/device-lifecycle.mdworkspace.getWaylineManageModule()— Waypoint route asset management (list/detail/upload import/rename/copy/splice/batch download and delete); see for detailsprompts/add-wayline-management.md
Callback parameter order is not uniform(a high-frequency pitfall;do not infer by the "query/command" dichotomy):
⚠️ there is no uniform rule. For APIs of the same query type,
getDeviceListis(data, error), whilegetWaylineList/getWaylineDetailis instead(error, result). Inferring the order by API name or "query type/command type"will definitely be wrong。
| API | Actual signature | Category |
|---|---|---|
getDeviceList |
(deviceList, error) —— data first |
Query (exception) |
getWaylineList |
(error, result) —— error first |
Query (violates "query = data first") |
getWaylineDetail |
(error, result) —— error first |
Query (violates "query=data first") |
takeoff / returnHome and other command types |
(error, result) —— error first |
commands |
- When generating code,you mustuse
javap -p <Callback 接口>or have the compiler report an error directly to confirm the actual signature (if the parameter order is reversed, the parameter names won't cause an error, but usingerroras a result will cause an NPE / type mismatch at the call site—be sure to check the specific internal interfaces inFlightHubCallback). - When unsure, write it according to
(error, result)first, then verify with the compiler;getDeviceListis a rare data-first exception in the whole repository.
Unified error response structure(shared by all callbacks):
FlightHubError {
FlightHubSdkErrorCode errorCode; // SDK 层枚举
int httpCode; // HTTP 状态码(0=网络层失败)
int serverCode; // 服务端业务码(0=成功)
int deviceCode; // 设备端错误码(0=无设备错误)
String serverMessage; // 服务端错误描述
}
Standard import list (copy and use; do not guess package paths from memory)
The SDK's classes are distributed across four packages,classes with the same name exist repeatedly in multiple packages, and importing the wrong package will be blocked directly by the compiler with cannot find symbol or incompatible types :
| Package | Contents | Representative classes |
|---|---|---|
com.dji.flighthubsdk |
Static entry points and callback interfaces | FlightHubSDK、FlightHubCallback |
com.dji.flighthubsdk.bean |
Configuration / error / data transfer objects (the only correct source) | FlightHubSdkConfig、HeaderKeyValue、FlightHubError、DeviceTopo |
com.dji.flighthubsdk.generated |
Error code enums, native interfaces, and callback parameters | FlightHubSdkErrorCode |
com.dji.flighthubsdk.core |
Device instances and capability modules | Workspace、Drone、DroneOsdModule , etc. |
com.dji.flighthubsdk.value |
Business enums in OSD / parameters (40+) | DroneModeCode、CameraMode、DockAirConditionerState |
⚠️
FlightHubSdkConfig/HeaderKeyValue/FlightHubError/DeviceTopoIn thegeneratedpackage there is also a copy with the same name, but the method signatures and callback parameters ofFlightHubSDKuse thebeanpackage. Importing thegeneratedversion will report an error in the callback lambdaincompatible types。⚠️
FlightHubSdkErrorCodeis in thegeneratedandvaluepackageseach has an enum with the same name, and the two are incompatible。FlightHubSDK.initialize()/setHttpHeaders()the return value of,FlightHubError.getErrorCode()all use thegeneratedpackage;valuethe one in the package only appears in some OSD fields (withgetValue()/fromValue()). When judging the initialization result, always importcom.dji.flighthubsdk.generated.FlightHubSdkErrorCode。⚠️
valuethe enum in the package (such as theAircraftModeCode.getModeCode()returned byDroneModeCode)does not need to and cannot be replaced by hardcoded int, and when comparison is needed, directlyimport com.dji.flighthubsdk.value.DroneModeCodeand then write it as enum constants.⚠️ Callback interfaces (
DeviceListCallback、AircraftLocationCallback, etc.) are allFlightHubCallback'sinternal interfaces, and do not need to be imported separately; when you need to explicitly write the type, useFlightHubCallback.XxxCallback。
// 静态入口 + 回调接口
import com.dji.flighthubsdk.FlightHubSDK;
import com.dji.flighthubsdk.FlightHubCallback;
// 配置 / 错误 / 数据传输对象
import com.dji.flighthubsdk.bean.FlightHubSdkConfig;
import com.dji.flighthubsdk.bean.HeaderKeyValue;
import com.dji.flighthubsdk.bean.FlightHubError;
import com.dji.flighthubsdk.bean.DeviceTopo;
// 错误码枚举
import com.dji.flighthubsdk.generated.FlightHubSdkErrorCode;
// 实例与 JNI 加载器
import com.dji.flighthubsdk.core.JniLibraryLoader;
import com.dji.flighthubsdk.core.Workspace;
import com.dji.flighthubsdk.core.Drone;
import com.dji.flighthubsdk.core.Dock;
// 能力模块(通过实例 getter 获取)
import com.dji.flighthubsdk.core.DeviceManageModule;
import com.dji.flighthubsdk.core.DroneOsdModule;
import com.dji.flighthubsdk.core.DeviceStateModule;
import com.dji.flighthubsdk.core.DeviceHMSModule;
import com.dji.flighthubsdk.core.ControlAuthModule;
import com.dji.flighthubsdk.core.FlightControlModule;
import com.dji.flighthubsdk.core.TakeoffModule;
import com.dji.flighthubsdk.core.DrcModule;
import com.dji.flighthubsdk.core.FlyToPointModule;
import com.dji.flighthubsdk.core.CameraControlModule;
import com.dji.flighthubsdk.core.LiveDeviceModule;
import com.dji.flighthubsdk.core.PoiModule;
import com.dji.flighthubsdk.core.DockOsdModule;
import com.dji.flighthubsdk.core.DockControlModule;
import com.dji.flighthubsdk.core.WaylineManageModule;
Spring Boot 3 annotations all come from
jakarta.*(such asjakarta.annotation.PostConstruct、jakarta.annotation.PreDestroy), notjavax.*。
6 core rules (hard constraints that must be followed when generating code)
Rule 1: Auth header injection → initialize → check return value
The SDK uses the gateway header injectionauthentication model (no setToken/setAppId); complete initialization is divided into four steps:
Step zero: explicitly load JNI first (otherwise auth header injection silently fails)
import com.dji.flighthubsdk.core.JniLibraryLoader;
JniLibraryLoader.loadLibrary(); // 必须先调用,再注入鉴权头
⚠️
setHttpHeaders/setWebSocketAuthHeadersgoes through native; when JNI is not loaded, the two only returnERROR_NOT_INITIALIZED(and will not throw exceptions, so the auth header is silently not injected → WebSocket handshake 401). This is the most common root cause of "configuration is all correct but still 401".
Step one: inject the auth header (must be before initialize)
// SDK 鉴权通过 HTTP + WebSocket 双通道头注入,不是 appId/appSecret
// key/value 是网关约定的头名与头值,由 FH2 服务端决定(测试环境常见 user_id / paas_test),
// 不一定是 Authorization / Bearer —— 以服务端提供的鉴权头对为准。
List<HeaderKeyValue> headers = new ArrayList<>();
headers.add(new HeaderKeyValue(authKey, authValue)); // 例如 ("user_id", "paas_test")
FlightHubSDK.setHttpHeaders(headers); // HTTP 请求鉴权
FlightHubSDK.setWebSocketAuthHeaders(headers); // WebSocket 推送鉴权
// 必须检查返回值:两者任一非 SUCCESS,说明注入失败,后续推送必然 401
⚠️ If initialize is called without injecting the auth header, the WebSocket handshake will return 401 Unauthorized, and all push functionality will fail.
Step 2: Build config and initialize
FlightHubSdkConfig config = new FlightHubSdkConfig();
config.setAddress("https://<fh2-host>"); // HTTP 地址,含协议前缀
config.setPort("30812"); // HTTP 端口,注意是 String 类型
config.setNotificationServerAddress("wss://<fh2-host>:30812/openapi/v0.9/notification/ws/v1/notifications"); // WebSocket 推送地址
config.setLogLevel("info"); // 可选:debug / info / warn / error
⚠️
notificationServerAddressIf not set, WebSocket URL parsing will fail, and functions such as OSD monitoring and device status push will all be unavailable.portis of type String , not int.
Step 3: Check the return value
// ✅ 正确:检查返回值
FlightHubSdkErrorCode code = FlightHubSDK.initialize(config);
if (code != FlightHubSdkErrorCode.SUCCESS) {
throw new IllegalStateException("SDK init failed: " + code);
}
// ❌ 错误:未检查返回值
FlightHubSDK.initialize(config); // 可能返回 ERROR_INIT_FAILED
Workspace ws = FlightHubSDK.getWorkspaceInstance(); // null
Rule 2: All callbacks must check errorCode
// ✅ 正确(注意:回调参数顺序是 data 在前、error 在后)
workspace.getDeviceManageModule().getDeviceList((devices, error) -> {
if (error.getErrorCode() != FlightHubSdkErrorCode.SUCCESS) {
log.error("获取设备列表失败: sdk={}, server={}", error.getErrorCode(), error.getServerCode());
return;
}
// 安全使用 devices
});
// ❌ 错误:errorCode 非 SUCCESS 时 devices 可能为 null
workspace.getDeviceManageModule().getDeviceList((devices, error) -> {
devices.forEach(d -> ...); // NPE
});
Rule 3: listenId must be saved, and must be canceled on close
// ✅ 正确(Spring Boot)— 订阅位置 + 电量(OSD 由多个独立 listener 组成)
@Component
public class DroneTelemetryListener {
private int locationListenId = -1;
private int batteryListenId = -1;
@PostConstruct
public void start() {
Drone drone = FlightHubSDK.getDroneInstance(sn);
if (drone == null) return;
DroneOsdModule osd = drone.getDroneOsdModule();
locationListenId = osd.listenAircraftLocation(loc -> handleLocation(loc));
if (locationListenId < 0) log.error("订阅位置失败");
batteryListenId = osd.listenAircraftBatteryInfo(bat -> handleBattery(bat));
if (batteryListenId < 0) log.error("订阅电量失败");
}
@PreDestroy
public void stop() {
Drone drone = FlightHubSDK.getDroneInstance(sn);
if (drone == null) return;
DroneOsdModule osd = drone.getDroneOsdModule();
if (locationListenId >= 0) osd.cancelListenAircraftLocation(locationListenId);
if (batteryListenId >= 0) osd.cancelListenAircraftBatteryInfo(batteryListenId);
}
}
// ❌ 错误:不保存 listenId → 无法 cancel → 回调泄漏
drone.getDroneOsdModule().listenAircraftLocation(loc -> { ... }); // listenId 被丢弃
Rule 4: Flight control commands must first acquire control and release it after use
// ✅ 正确:acquire → 指令 → release(无论成败)
ControlAuthModule auth = drone.getControlAuthModule();
auth.acquireFlightControlAuthority(acquireError -> {
if (acquireError.getErrorCode() != FlightHubSdkErrorCode.SUCCESS) {
log.error("获取控制权失败: {}", acquireError.getErrorCode());
return;
}
drone.getFlightControlModule().returnHome(cmdError -> {
// 无论成败都释放控制权
auth.releaseFlightControlAuthority(e -> {});
if (cmdError.getErrorCode() != FlightHubSdkErrorCode.SUCCESS) {
log.error("返航失败: {}", cmdError.getErrorCode());
}
});
});
// ❌ 错误:未抢权直接发指令 → 返回权限错误
drone.getFlightControlModule().returnHome(error -> { ... });
Rule 5: getDroneInstance / getDockInstance / module getters may return null
// ✅ 正确
Drone drone = FlightHubSDK.getDroneInstance(sn);
if (drone == null) {
log.warn("Drone not found or offline: {}", sn);
return;
}
// 模块 getter 也可能返回 null(如设备不支持该模块)
CameraControlModule cam = drone.getCameraControlModule();
if (cam == null) {
log.warn("CameraControlModule not available: {}", sn);
return;
}
// ❌ 错误:NPE
FlightHubSDK.getDroneInstance(sn).getDroneOsdModule().listenAircraftLocation(...);
Rule 6: Dangerous operations must output a risk warning first (output behavior rule)
When generating code for the following operations,you must, before the code block,output a structured warning block; directly providing code is prohibited:
Applicable operations:takeoff / returnHome / drcEmergencyStop / drcEmergencyLanding / drcForceLanding / flyToPoint
Mandatory output format(must cover each item):
⚠️ **危险操作警告**
- 操作类型:[takeoff / returnHome / drcEmergencyStop / drcEmergencyLanding / drcForceLanding / flyToPoint]
- 不可逆性:[具体描述,如"drcForceLanding 强制降落并停转螺旋桨,不可撤销"或"drcEmergencyStop 立即悬停,螺旋桨保持运转"]
- 物理影响:此代码将控制真实无人机执行物理动作,操作失误可能导致坠机或财产损失
- 生产建议:务必实现前端二次确认弹窗(confirm dialog);建议支持 dry_run 参数做预校验
Rule constraints:
- ❌ Prohibited:directly outputting flight control code without the above warning
- ❌ Prohibited:writing the warning only in code comments (users may not read comments)
- ✅ The warning must be presented outside the code blockoutside, as a separate paragraph
- ✅ If the user has already confirmed awareness of the risk in the same conversation, subsequent similar operations may omit the warning
For the detailed "why" of each rule and more positive and negative examples, see
references/核心规则详解.md
Rule scope of application
| Rule | Applicable operations | Not applicable |
|---|---|---|
| Rule 1 initialize | At application startup (once) | — |
| Rule 2 errorCode | All callbacks | — |
| Rule 3 listenId/cancel | listenXxx() subscription type |
Command-style operations (one-time callbacks such as returnHome/takeoff) |
| Rule 4 acquire/release | Flight control commands (takeoff/returnHome/returnHomeCancel/drcEmergencyStop/drcEmergencyLanding/drcForceLanding/flyToPoint) | Query type, monitoring type, waypoint missions (self-managed control) |
| Rule 5 null check | getDroneInstance / getDockInstance / getWorkspaceInstance / module getters (getCameraControlModule, etc.) | — |
| Rule 6 dangerous operation warning | takeoff/returnHome/drcEmergencyStop/drcEmergencyLanding/drcForceLanding/flyToPoint code generation | Query type, monitoring type, code review (non-generation scenarios) |
Asynchronous callback bridging pattern (required reading for REST interfaces)
All SDK operations are asynchronous callbacks, but Spring Boot Controllers need to return synchronously. The standard bridging approach:
public void executeWithCallback(Drone drone) {
CompletableFuture<Void> future = new CompletableFuture<>();
drone.getFlightControlModule().returnHome(error -> {
if (error.getErrorCode() != FlightHubSdkErrorCode.SUCCESS) {
future.completeExceptionally(new RuntimeException("失败: " + error.getErrorCode()));
} else {
future.complete(null);
}
});
// Controller 层等待结果(带超时保护)
try {
future.get(30, TimeUnit.SECONDS);
} catch (TimeoutException e) {
throw new RuntimeException("SDK 回调超时");
}
}
⚠️ SDK callbacks execute onnon-main threads(the SDK's internal thread pool); operations on shared state require thread-safety protection.
Decision tree routing
用户问题
├─ getDroneInstance / getDockInstance / getWorkspaceInstance 返回 null
│ → 加载 references/设备管理流程.md#常见问题 + references/错误码诊断.md#常见问题速查
├─ 报错 / errorCode / httpCode / serverCode
│ → 加载 references/错误码诊断.md,按 4 层优先级定位
├─ 接入新功能 / 添加模块 / 订阅数据
│ → 先判断是订阅式(规则3)还是命令式(规则4),按对应规则生成代码
├─ 质量检查 / 自检 / review
│ → 加载 references/接入质量检查清单.md
└─ SDK 概念 / 架构 / "xxx 是什么"
→ 加载 references/文档检索与问答.md
Anti-hallucination rules (mandatory)
- Example code must come from this Skill's references/ or the SDK documentation provided by the user, and API signatures, field names, enum values, or code snippets must not be generated from model memory
- Do not fabricate from memory— If you are unsure whether an API exists or whether the parameters are correct, you must explicitly tell the user that "the SDK documentation needs to be confirmed"
- Citations must be traceable— Any SDK call suggestion must be traceable to a references/ documentation path or the official protocol documentation
Uncovered modules (known gaps, fabrication prohibited)
The following official SDK modules are explicitly not coveredby this Skill. When related requirements arise, you must tell the user that "the SDK documentation needs to be confirmed" and must not fabricate the calling method from memory:
| Module | Description |
|---|---|
DeployModule |
Deployment-related capabilities, use cloudapi2-skeleton-deploy / cloudapi2-mcp-deploy Skill |
TerraBuildModule |
3D reconstruction, only covered on the MCP side (cloudapi2-mcp-guide) |
TestFlightModule |
Test flight function |
CustomSEIModule |
Custom SEI delivery |
FlashLedModule |
Fill light control |
LiveSyncModule |
Live streaming sync |
PullStreamModule |
Stream pulling |
RelayControlModule |
Relay control |
Shared specification
The 6 core rules of this Skill are also included in
skills/_shared/constraints-common.yaml(the SSOT for cross-Skill shared constraints). Other Skills gain awareness of these rules by referencing this file. For cross-Skill routing rules, seeskills/_shared/skill-routing.md. When the user's intent is found to fall under the responsibility of another Skill, switch according to the handover protocol. For the output format, seeskills/_shared/output-format.md. References are lazily loaded on demand; do not read all references/ at once.