DJI Cloud API Demo Web

repository·main·Indexed 42 days ago

https://github.com/dji-sdk/cloud-api-demo-web

A reference implementation for integrating DJI hardware with third-party cloud platforms using the DJI Cloud API. It provides examples for sending device commands via postSendCmd, managing device logs, updating hardware properties with putDeviceProps, performing OTA firmware upgrades, and managing flight areas. Note: This is a learning tool and not a production-ready solution; maintenance ceased as of April 10, 2025.

Tokens
10.5K
Snippets
29
Records
41
Agent score
54%

What's inside DJI Cloud API Demo Web

  1. What is the DJI Cloud API?

    main
    The DJI Cloud API allows developers to focus on implementing cloud service interfaces without needing to build or deeply customize a mobile application. By using the Cloud API, developers can leverage DJI Pilot 2 to communicate directly with a third-party cloud platform, eliminating the need to 'reinvent the wheel' for standard flight control and data management features.
  2. Important: DJI Cloud API Demo End of Maintenance Notice

    main

    As of April 10, 2025, DJI has ceased updates and technical support for the DJI Cloud API Demo projects.

    Critical Security Warning:

    • This project is a reference implementation intended only to help developers understand API calling logic.
    • It is not a production-ready solution.
    • It may contain unpatched security vulnerabilities (e.g., data leaks, unauthorized access).
    • Do not use Demo code directly in production environments. If you must use it, perform a thorough security audit or avoid exposing services based on this Demo to the public internet.

    DJI assumes no responsibility for business losses, data risks, or third-party disputes resulting from the direct use of Demo code.

  3. Configure AMap settings via AMapConfig

    main

    The AMapConfig constant provides the configuration object required for initializing the AMap (Gaode Maps) service within the application. It automatically pulls the key from the global CURRENT_CONFIG.amapKey.

    It specifies version 2.0 and includes a predefined list of plugins to enable advanced map features such as editors (Circle, Polygon, Polyline), tools (Scale, ToolBar, RangingTool), and weather services.

    export const AMapConfig = {
      key: CURRENT_CONFIG.amapKey,
      version: '2.0',
      plugins: [
        'AMap.Scale',
        'AMap.ToolBar',
        'AMap.ControlBar',
        'AMap.ElasticMarker',
        'AMap.MapType',
        'AMap.Geocoder',
        'AMap.CircleEditor',
        'AMap.PolygonEditor',
        'AMap.PolylineEditor',
        'AMap.PolyEditor',
        'AMap.RangingTool',
        'AMap.Weather',
        'AMap.MouseTool',
        'AMap.MoveAnimation'
      ]
    }
  4. Use the default singleAxios instance

    main

    The module exports a default singleAxios instance. This instance is pre-configured with unified request interceptors but does not have unified response interceptors bound by default. Use this for standard API calls where you want consistent request behavior across the application.

    import singleAxios from '@/api/http'
    
    // Use the instance directly for HTTP requests
    const response = await singleAxios.get('/api/endpoint')
  5. Upload device logs with postDeviceUpgrade

    main

    Submits device log data to the server.

    Parameters (Body):

    • device_sn (string): The serial number of the device.
    • happen_time (string): The time the event occurred.
    • logs_information (string): Description of the anomaly or log content.
    • files (Array): An array of objects containing:
      • list (DeviceLogItem[]): The actual log items.
      • device_sn (string): Device serial number.
      • module (DOMAIN): The domain of the log.

    Returns: A promise resolving to an IWorkspaceResponse<{}>.

    await postDeviceUpgrade({
      device_sn: 'SN123',
      happen_time: '2023-10-27T10:00:00Z',
      logs_information: 'System error detected',
      files: [{
        device_sn: 'SN123',
        module: DOMAIN.SYSTEM,
        list: [{ boot_index: 1, start_time: 1698390000, end_time: 1698393600, size: 1024 }]
      }]
    });
  6. Cancel or delete device log uploads

    main

    There are two ways to stop or remove log upload activities:

    1. Cancel an ongoing upload

    Use cancelDeviceLogUpload to stop an active upload process.

    • Body: device_sn (string), status (DeviceLogUploadAction, e.g., 'cancel'), and module_list (DOMAIN[]).

    2. Delete a specific log record

    Use deleteDeviceLogUpload to remove a specific log entry from the system.

    • Body: device_sn (string) and logs_id (string).

    Both methods return an IWorkspaceResponse<{}>.

    // Cancel
    await cancelDeviceLogUpload({
      device_sn: 'SN123',
      status: 'cancel',
      module_list: [DOMAIN.SYSTEM]
    });
    
    // Delete
    await deleteDeviceLogUpload({
      device_sn: 'SN123',
      logs_id: 'log_id_abc'
    });
  7. Use ConnectWebSocket for DJI Cloud API communication

    main

    The ConnectWebSocket class provides a managed WebSocket client that handles automatic reconnection logic using reconnecting-websocket. It is designed to establish a connection to a DJI Cloud API endpoint, handle incoming messages via a registered callback, and allow sending data payloads.

    Key Lifecycle Methods

    • initSocket(): Initializes the connection. It configures reconnection delays (min 5s, max 20s) and a maximum of 5 retries. It should only be called once.
    • registerMessageHandler(handler): Sets the callback function that will be executed whenever a new message is received from the server.
    • sendMessage(options): Sends a JSON-stringified payload to the server.
    • close(): Manually closes the WebSocket connection.

    Reconnection Behavior

    The client automatically attempts to reconnect if the connection is lost. The delay between attempts starts at 5 seconds and increases by a factor of 1.3 for each subsequent failure, up to a maximum delay of 20 seconds.

    import ConnectWebSocket from './websocket';
    
    const ws = new ConnectWebSocket('ws://your-api-endpoint');
    
    // 1. Register a handler to process incoming data
    ws.registerMessageHandler((data) => {
      console.log('Received message:', data);
    });
    
    // 2. Initialize the connection
    ws.initSocket();
    
    // 3. Send a message
    ws.sendMessage({
      data: { type: 'command', payload: { action: 'start' } }
    });
  8. Manage User and Platform Information

    main

    Retrieve details about the current platform, the logged-in user, or list all users within a specific workspace.

    • getPlatformInfo(): Returns current workspace/platform info.
    • getUserInfo(): Returns information about the currently authenticated user.
    • getAllUsersInfo(wid: string, body: IPage): Retrieves a paginated list of users in workspace wid. Requires an IPage object with page and page_size.
    • updateUserInfo(wid: string, user_id: string, body: {}): Updates a specific user's information in workspace wid.
  9. Manage Device Firmware

    main

    Handle firmware queries, uploads, and status updates.

    • getFirmwares(workspace_id: string, page: IPage, body: FirmwareQueryParam): Queries available firmware based on device name, product version, and status.
    • importFirmareFile(workspaceId: string, param: FormData): Uploads a new firmware file using FormData.
    • changeFirmareStatus(workspaceId: string, firmwareId: string, param: {status: boolean}): Toggles the status of a specific firmware entry.
  10. Manage Device Bindings and Topology

    main

    Control how devices are associated with workspaces and retrieve device relationship data.

    • bindDevice(body: BindBody): Binds a device to a user and workspace.
      • BindBody requires device_sn, user_id, and workspace_id.
    • unbindDevice(device_sn: string): Removes the binding for the specified device serial number.
    • getDeviceTopo(workspace_id: string): Retrieves the device topology for a workspace.
    • getDeviceBySn(workspace_id: string, device_sn: string): Fetches details for a specific device.
    • getBindingDevices(workspace_id: string, body: IPage, domain: number): Lists devices bound to a workspace, filtered by domain and pagination.
  11. Get device firmware upgrade information

    main

    Use getDeviceUpgradeInfo to retrieve the latest firmware release notes and version information for a specific device. It returns an array of upgrade information objects containing the product version, release notes, and release time.

    import { getDeviceUpgradeInfo } from '@/api/device-upgrade';
    
    const info = await getDeviceUpgradeInfo({
      device_name: 'your_device_name'
    });
    // info.data contains GetDeviceUpgradeInfoRsp[]