### Configure Console and File Logging in C++ Source: https://context7.com/dji-sdk/edge-sdk/llms.txt This C++ code snippet demonstrates how to set up a flexible logging system for the DJI Edge SDK. It includes examples for a color-supported console logger and a file logger, allowing customization of log levels and output functions. The SDK is initialized with these configurations, and logging macros are used to output messages. ```cpp #include "logger.h" #include #include using namespace edge_sdk; // Console logger with color support ErrorCode ConsoleLogger(const uint8_t* data, uint32_t len) { printf("%s", data); return kOk; } // File logger std::ofstream log_file("edge_sdk.log", std::ios::app); ErrorCode FileLogger(const uint8_t* data, uint32_t len) { log_file.write(reinterpret_cast(data), len); log_file.flush(); return kOk; } int main() { Options options; // ... other configuration ... // Add console logger (debug level, with color) LoggerConsole console_logger = { .level = kLevelDebug, // Log all levels: Error, Warn, Info, Debug .output_func = ConsoleLogger, .is_support_color = true }; options.logger_console_lists.push_back(console_logger); // Add file logger (info level only, no color) LoggerConsole file_logger = { .level = kLevelInfo, // Log Error, Warn, Info only .output_func = FileLogger, .is_support_color = false }; options.logger_console_lists.push_back(file_logger); ESDKInit::Instance()->Init(options); // Use logging macros in your code DEBUG("Debug message: processing frame %d", 42); INFO("Application started successfully"); WARN("Connection quality degraded"); ERROR("Failed to process frame: %s", "timeout"); return 0; } ``` -------------------------------- ### CMake Project Setup and Compiler Flags Source: https://github.com/dji-sdk/edge-sdk/blob/master/CMakeLists.txt Initializes the CMake project, sets C and C++ compiler flags, and defines common flags for optimization and coverage. It also sets the C and C++ compilers to gcc and g++ respectively. ```cmake cmake_minimum_required(VERSION 3.9) project(dji_edge_sdk_demo CXX) set(MODULE_SAMPLE_SRC "") set(SAMPLE_LIB edge_sample) set(CMAKE_C_FLAGS "-pthread -std=gnu99") set(CMAKE_EXE_LINKER_FLAGS "-pthread") set(CMAKE_C_COMPILER "gcc") set(CMAKE_CXX_COMPILER "g++") set(COMMON_CXX_FLAGS "-std=c++14 -pthread") set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${COMMON_CXX_FLAGS} -fprofile-arcs -ftest-coverage -Wno-deprecated-declarations") set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -fprofile-arcs -ftest-coverage") set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -fprofile-arcs -ftest-coverage -lgcov") add_definitions(-D_GNU_SOURCE) ``` -------------------------------- ### Error Handling Source: https://context7.com/dji-sdk/edge-sdk/llms.txt Details the error codes and provides an example of how to handle them during SDK initialization and operation. ```APIDOC ## Error Handling ### Description The DJI Edge SDK utilizes a comprehensive enumeration of error codes (`ErrorCode`) to indicate the success or failure of various operations. This section details common error codes and demonstrates how to implement robust error handling in your application. ### Method Various (e.g., Initialization, Liveview operations) ### Endpoint N/A ### Parameters N/A ### Request Example N/A ### Response #### Success Response (200) Operations return `kOk` (0) upon successful completion. #### Error Codes - **`kOk` (0)**: Success. - **`kErrorInvalidArgument` (-1)**: An invalid argument was provided to a function. - **`kErrorSystemError` (-2)**: A general system error occurred. - **`kErrorInvalidOperation` (-3)**: The operation is not valid in the current state. - **`kErrorRepeatOperation` (-4)**: The operation was attempted too soon after a previous one. - **`kErrorNullPointer` (-5)**: A null pointer was passed where an object was expected. - **`kErrorParamOutOfRange` (-6)**: A parameter value is outside its allowed range. - **`kErrorParamGetFailure` (-7)**: Failed to retrieve a parameter's value. - **`kErrorParamSetFailure` (-8)**: Failed to set a parameter's value. - **`kErrorSendPackFailure` (-9)**: Failed to send a data packet. - **`kErrorRequestTimeout` (-10)**: The request timed out waiting for a response. - **`kErrorAuthVerifyFailure` (-11)**: Authentication verification failed. - **`kErrorEncryptFailure` (-12)**: Data encryption failed. - **`kErrorDecryptFailure` (-13)**: Data decryption failed. - **`kErrorInvalidRespond` (-14)**: An invalid response was received. - **`kErrorRemoteFailure` (-15)**: An error occurred on a remote service. - **`kErrorNoVideoID` (-16)**: No video ID available, likely due to aircraft not being paired. - **`kErrorConnectFailure` (-17)**: Failed to establish a connection. #### Response Example **Example of handling initialization errors:** ```cpp #include "error_code.h" #include "init.h" #include using namespace edge_sdk; const char* ErrorCodeToString(ErrorCode code) { switch (code) { case kOk: return "Success"; case kErrorInvalidArgument: return "Invalid argument"; // ... other error codes ... case kErrorConnectFailure: return "Connection failure"; default: return "Unknown error"; } } int main() { Options options; // ... configure options ... auto rc = ESDKInit::Instance()->Init(options); if (rc != kOk) { std::cerr << "Init failed: " << ErrorCodeToString(rc) << " (code: " << rc << ")" << std::endl; // Handle specific errors switch (rc) { case kErrorAuthVerifyFailure: std::cerr << "Check your app credentials on DJI Developer Portal" << std::endl; break; case kErrorConnectFailure: std::cerr << "Verify dock is powered on and network is configured" << std::endl; break; default: break; } return -1; } // ... proceed with SDK usage ... return 0; } ``` ``` -------------------------------- ### Error Handling with SDK Error Codes (C++) Source: https://context7.com/dji-sdk/edge-sdk/llms.txt Demonstrates how to handle errors returned by DJI Edge SDK operations using a comprehensive error code enumeration. It includes a utility function to convert error codes to human-readable strings and provides examples of handling specific initialization and liveview errors. ```cpp #include "error_code.h" #include "init.h" #include "liveview.h" #include using namespace edge_sdk; const char* ErrorCodeToString(ErrorCode code) { switch (code) { case kOk: return "Success"; case kErrorInvalidArgument: return "Invalid argument"; case kErrorSystemError: return "System error"; case kErrorInvalidOperation: return "Invalid operation"; case kErrorRepeatOperation: return "Repeat operation"; case kErrorNullPointer: return "Null pointer"; case kErrorParamOutOfRange: return "Parameter out of range"; case kErrorParamGetFailure: return "Parameter get failure"; case kErrorParamSetFailure: return "Parameter set failure"; case kErrorSendPackFailure: return "Send packet failure"; case kErrorRequestTimeout: return "Request timeout"; case kErrorAuthVerifyFailure: return "Auth verification failure"; case kErrorEncryptFailure: return "Encryption failure"; case kErrorDecryptFailure: return "Decryption failure"; case kErrorInvalidRespond: return "Invalid response"; case kErrorRemoteFailure: return "Remote failure"; case kErrorNoVideoID: return "No video ID (check if aircraft is paired)"; case kErrorConnectFailure: return "Connection failure"; default: return "Unknown error"; } } int main() { Options options; // ... configure options ... auto rc = ESDKInit::Instance()->Init(options); if (rc != kOk) { std::cerr << "Init failed: " << ErrorCodeToString(rc) << " (code: " << rc << ")" << std::endl; // Handle specific errors switch (rc) { case kErrorAuthVerifyFailure: std::cerr << "Check your app credentials on DJI Developer Portal" << std::endl; break; case kErrorConnectFailure: std::cerr << "Verify dock is powered on and network is configured" << std::endl; break; default: break; } return -1; } auto liveview = CreateLiveview(); // ... configure liveview options ... rc = liveview->StartH264Stream(); if (rc == kErrorNoVideoID) { std::cerr << "No video ID - ensure aircraft is paired with dock" << std::endl; std::cerr << "Verify cloud can open live stream before retrying" << std::endl; } return 0; } ``` -------------------------------- ### Initialize DJI Edge SDK (ESDK) with C++ Source: https://context7.com/dji-sdk/edge-sdk/llms.txt Demonstrates the initialization process for the DJI Edge SDK using C++. It involves configuring SDK options, setting application credentials, defining logging behavior, and providing a custom KeyStore for secure communication. The initialization requires specific product information and app details obtained from the DJI Developer Portal. Successful initialization enables access to SDK features and device information. ```cpp #include "init.h" #include "logger.h" #include using namespace edge_sdk; // Custom logging function ErrorCode PrintConsoleFunc(const uint8_t* data, uint16_t dataLen) { printf("%s", data); return kOk; } // Custom KeyStore implementation for RSA key management class MyKeyStore : public KeyStore { public: ErrorCode RSA2048_GetDERPrivateKey(std::string& private_key) const override { // Load your persistent RSA2048 DER private key // Keys should be securely generated and stored persistently private_key = loaded_private_key_; return kOk; } ErrorCode RSA2048_GetDERPublicKey(std::string& public_key) const override { // Load your persistent RSA2048 DER public key public_key = loaded_public_key_; return kOk; } private: std::string loaded_private_key_; std::string loaded_public_key_; }; int main() { // Configure SDK options Options option; option.product_name = "MyEdgeDevice-1.0"; option.vendor_name = "MyCompany"; option.serial_number = "SN0000100010101"; // Unique per device option.firmware_version = {1, 0, 0, 0}; // {major, minor, modify, debug} // Set app credentials from DJI Developer Portal AppInfo app_info; app_info.app_name = "my_edge_app"; app_info.app_id = "your_app_id"; app_info.app_key = "your_app_key"; app_info.app_license = "your_app_license"; app_info.developer_account = "your_developer_account"; option.app_info = app_info; // Configure logging LoggerConsole console = {kLevelDebug, PrintConsoleFunc, true}; option.logger_console_lists.push_back(console); // Set key store for secure communication option.key_store = std::make_shared(); // Initialize SDK auto rc = ESDKInit::Instance()->Init(option); if (rc != kOk) { std::cout << "Edge SDK init failed: " << rc << std::endl; return -1; } // Get device information after initialization auto firmware = ESDKInit::Instance()->GetFirmwareVersion(); std::cout << "Firmware: " << (int)firmware.major_version << "." << (int)firmware.minor_version << std::endl; // Your application code here... // Cleanup ESDKInit::Instance()->DeInit(); return 0; } ``` -------------------------------- ### Manage Aircraft Media Files with MediaManager in C++ Source: https://context7.com/dji-sdk/edge-sdk/llms.txt This C++ code snippet demonstrates how to use the MediaManager to list and download media files from an aircraft. It initializes the MediaManager, retrieves a list of files with detailed metadata, and then downloads the first file in the list. Dependencies include the DJI Edge SDK headers and standard C++ libraries for I/O operations. The function returns an integer status code, with 0 indicating success. ```cpp #include "media_manager.h" #include #include #include using namespace edge_sdk; int main() { // Assume SDK is already initialized // Get MediaManager singleton and create a file reader auto manager = MediaManager::Instance(); auto reader = manager->CreateMediaFilesReader(); // Initialize the reader auto rc = reader->Init(); if (rc != kOk) { std::cerr << "Failed to init reader: " << rc << std::endl; return -1; } // Get list of available media files MediaFilesReader::MediaFileList file_list; int32_t count = reader->FileList(file_list); std::cout << "Found " << count << " media files" << std::endl; // Iterate through files and display metadata for (const auto& file : file_list) { std::cout << "File: " << file->file_name << std::endl; std::cout << " Path: " << file->file_path << std::endl; std::cout << " Size: " << file->file_size << " bytes" << std::endl; std::cout << " Type: " << (file->file_type == MediaFile::kFileTypeJpeg ? "JPEG" : "MP4") << std::endl; std::cout << " Camera: " << file->camera_attr << std::endl; std::cout << " Location: " << file->latitude << ", " << file->longitude << std::endl; std::cout << " Altitude: " << file->absolute_altitude << "m (abs), " << file->relative_altitude << "m (rel)" << std::endl; std::cout << " Gimbal Yaw: " << file->gimbal_yaw_degree << " degrees" << std::endl; if (file->file_type == MediaFile::kFileTypeJpeg) { std::cout << " Dimensions: " << file->image_width << "x" << file->image_height << std::endl; } else { std::cout << " Duration: " << file->video_duration << " seconds" << std::endl; } } // Download a specific file if (!file_list.empty()) { auto& target_file = file_list.front(); // Open the remote file auto fd = reader->Open(target_file->file_path); if (fd < 0) { std::cerr << "Failed to open file: " << target_file->file_path << std::endl; } else { // Read file contents std::vector buffer(1024 * 1024); // 1MB buffer std::ofstream output(target_file->file_name, std::ios::binary); size_t total_read = 0; size_t bytes_read; while ((bytes_read = reader->Read(fd, buffer.data(), buffer.size())) > 0) { output.write(reinterpret_cast(buffer.data()), bytes_read); total_read += bytes_read; // Progress reporting float progress = (float)total_read * 100.0f / target_file->file_size; std::cout << "\rDownloading: " << progress << "%" << std::flush; } std::cout << std::endl; reader->Close(fd); output.close(); std::cout << "Downloaded: " << target_file->file_name << std::endl; } } reader->DeInit(); return 0; } ``` -------------------------------- ### Observe and Process New Media Files with MediaManager (C++) Source: https://context7.com/dji-sdk/edge-sdk/llms.txt This snippet shows how to register a callback for new media files using MediaManager. It utilizes a queue and a worker thread for asynchronous processing, including reading file content and simulating analysis. Dependencies include the DJI Edge SDK's media_manager, standard C++ libraries for threading and synchronization. ```cpp #include "media_manager.h" #include #include #include #include #include using namespace edge_sdk; std::queue pending_files; std::mutex queue_mutex; std::condition_variable queue_cv; std::shared_ptr reader; // Callback invoked when new media file is available ErrorCode OnNewMediaFile(const MediaFile& file) { std::cout << "New file detected: " << file.file_name << std::endl; std::lock_guard lock(queue_mutex); pending_files.push(file); queue_cv.notify_one(); return kOk; } // Worker thread to process incoming files void ProcessMediaFiles() { std::vector file_data; char buffer[1024 * 1024]; // 1MB read buffer while (true) { MediaFile file; { std::unique_lock lock(queue_mutex); queue_cv.wait(lock, []{ return !pending_files.empty(); }); file = pending_files.front(); pending_files.pop(); } std::cout << "Processing: " << file.file_name << std::endl; // Read the file content auto fd = reader->Open(file.file_path); if (fd >= 0) { file_data.clear(); size_t nread; while ((nread = reader->Read(fd, buffer, sizeof(buffer))) > 0) { file_data.insert(file_data.end(), buffer, buffer + nread); } reader->Close(fd); // Process the file (e.g., AI analysis, cloud upload, etc.) std::cout << "Loaded " << file_data.size() << " bytes from " << file.file_name << std::endl; // Example: Run object detection on image // auto results = ai_model->Detect(file_data); } } } int main() { // Assume SDK initialized auto manager = MediaManager::Instance(); // Configure upload and deletion policies // Disable automatic cloud upload (we'll handle files locally) manager->SetDroneNestUploadCloud(false); // Keep files on dock after processing (don't auto-delete) manager->SetDroneNestAutoDelete(false); // Create reader for file access reader = manager->CreateMediaFilesReader(); reader->Init(); // Register observer for new files auto rc = manager->RegisterMediaFilesObserver(OnNewMediaFile); if (rc != kOk) { std::cerr << "Failed to register observer: " << rc << std::endl; return -1; } // Start processing thread std::thread worker(ProcessMediaFiles); worker.detach(); // Keep main thread running while (true) { std::this_thread::sleep_for(std::chrono::seconds(1)); } return 0; } ``` -------------------------------- ### Static Library and Media Manager Executables Source: https://github.com/dji-sdk/edge-sdk/blob/master/CMakeLists.txt Creates a static library for sample modules and defines executable targets for media file operations. These executables are linked against the created static library. ```cmake add_library(${SAMPLE_LIB} STATIC ${MODULE_SAMPLE_SRC}) add_executable(sample_read_media_file examples/media_manager/sample_read_media_file.cc) target_link_libraries(sample_read_media_file ${SAMPLE_LIB}) add_executable(sample_media_file_list examples/media_manager/sample_media_file_list.cc) target_link_libraries(sample_media_file_list ${SAMPLE_LIB}) add_executable(sample_set_upload_cloud_strategy examples/media_manager/sample_set_upload_cloud_strategy.cc) target_link_libraries(sample_set_upload_cloud_strategy ${SAMPLE_LIB}) ``` -------------------------------- ### Subscribe to Aircraft Live H264 Video Streams in C++ Source: https://context7.com/dji-sdk/edge-sdk/llms.txt This C++ code demonstrates how to subscribe to and process H264 video streams from aircraft cameras using the DJI Edge SDK's Liveview module. It includes setting up callbacks for video data and stream status, configuring stream quality and camera source, and managing the stream lifecycle. Dependencies include the Edge SDK headers and standard C++ libraries for threading and I/O. ```cpp #include "liveview.h" #include #include #include using namespace edge_sdk; class VideoStreamHandler { public: // H264 stream callback - called for each received video frame ErrorCode OnH264Data(const uint8_t* buf, uint32_t len) { // Process H264 data - decode, analyze, or forward to AI pipeline bytes_received_ += len; frame_count_++; // Example: Feed to FFmpeg decoder or your video processing pipeline // decoder->ProcessFrame(buf, len); return kOk; } // Status callback - monitor stream availability void OnStatusChanged(const Liveview::LiveviewStatus& status) { // Status bits indicate available stream qualities: // bit0: adaptive, bit1: 540p, bit2: 720p, bit3: 720pHigh // bit4: 1080p, bit5: 1080pHigh stream_available_ = (status != 0); std::cout << "Liveview status: " << status << " (available: " << stream_available_ << ")" << std::endl; } std::atomic stream_available_{false}; std::atomic bytes_received_{0}; std::atomic frame_count_{0}; }; int main() { // Assume SDK is already initialized via ESDKInit::Instance()->Init() VideoStreamHandler handler; // Create liveview instance auto liveview = CreateLiveview(); // Configure stream options Liveview::Options options; options.camera = Liveview::kCameraTypePayload; // or kCameraTypeFpv options.quality = Liveview::kStreamQuality1080pHigh; // 1920x1080 @ 8Mbps options.callback = std::bind(&VideoStreamHandler::OnH264Data, &handler, std::placeholders::_1, std::placeholders::_2); // Initialize liveview auto rc = liveview->Init(options); if (rc != kOk) { std::cerr << "Liveview init failed: " << rc << std::endl; return -1; } // Subscribe to stream status changes liveview->SubscribeLiveviewStatus( std::bind(&VideoStreamHandler::OnStatusChanged, &handler, std::placeholders::_1)); // Wait for stream to become available while (!handler.stream_available_) { std::this_thread::sleep_for(std::chrono::seconds(1)); } // Start receiving H264 stream rc = liveview->StartH264Stream(); if (rc != kOk) { std::cerr << "Failed to start stream: " << rc << std::endl; return -1; } // Switch camera source (for payload camera only) liveview->SetCameraSource(Liveview::kCameraSourceZoom); // or kCameraSourceWide, kCameraSourceIR // Let stream run for demonstration std::this_thread::sleep_for(std::chrono::seconds(60)); // Stop and cleanup liveview->StopH264Stream(); liveview->DeInit(); std::cout << "Received " << handler.bytes_received_ << " bytes, " << handler.frame_count_ << " frames" << std::endl; return 0; } ``` -------------------------------- ### Live View and Media Processing Executables Source: https://github.com/dji-sdk/edge-sdk/blob/master/CMakeLists.txt Defines executable targets for live view and media processing functionalities, provided both OpenCV and FFmpeg are found. It links these executables against the sample library and necessary OpenCV/FFmpeg libraries. ```cmake if (OpenCV_FOUND AND FFMPEG_FOUND) file(GLOB_RECURSE MODULE_SAMPLE_SRC ${MODULE_SAMPLE_SRC} examples/liveview/sample_liveview.cc examples/liveview/stream_decoder.cc examples/liveview/ffmpeg_stream_decoder.cc examples/liveview/image_processor_thread.cc examples/liveview/stream_processor_thread.cc examples/common/util_misc.cc examples/common/image_processor.cc examples/common/image_processor_yolovfastest.cc) link_libraries(${OpenCV_LIBS}) link_libraries(${FFMPEG_LIBRARIES}) add_executable(sample_liveview examples/liveview/sample_liveview_main.cc) target_link_libraries(sample_liveview ${SAMPLE_LIB}) add_executable(test_liveview examples/liveview/test_liveview_main.cc) add_executable(test_liveview_dual examples/liveview/test_liveview_dual_main.cc) target_link_libraries(test_liveview ${SAMPLE_LIB}) target_link_libraries(test_liveview_dual ${SAMPLE_LIB}) add_executable(pressure_test examples/test/pressure_test.cc) target_link_libraries(pressure_test ${SAMPLE_LIB}) endif () ``` -------------------------------- ### Executable Output Path Configuration Source: https://github.com/dji-sdk/edge-sdk/blob/master/CMakeLists.txt Sets the output directory for executable files. If not already defined, it sets the executable output path to a 'bin' subdirectory within the binary directory. ```cmake if (NOT EXECUTABLE_OUTPUT_PATH) set(EXECUTABLE_OUTPUT_PATH ${CMAKE_BINARY_DIR}/bin) endif () ``` -------------------------------- ### Library Linking and Path Configuration Source: https://github.com/dji-sdk/edge-sdk/blob/master/CMakeLists.txt Configures library linking paths and specific libraries required by the project. This includes linking against the edge_sample library, standard C++ library, and external libraries like crypto and ssh2. ```cmake link_directories(${CMAKE_CURRENT_LIST_DIR}/lib/${CMAKE_HOST_SYSTEM_PROCESSOR}) link_directories(${CMAKE_BINARY_DIR}) link_libraries(-ledgesdk -lstdc++) link_libraries(-lcrypto) link_libraries(-lssh2) ``` -------------------------------- ### Cloud API Custom Data Transmission (C++) Source: https://context7.com/dji-sdk/edge-sdk/llms.txt Enables bidirectional custom data transmission between the Edge SDK and cloud services using MQTT. Messages are limited to 256 bytes and follow a specific JSON format. It includes registering a message handler for incoming cloud messages and sending telemetry data to the cloud. ```cpp #include "cloud_api.h" #include #include #include using namespace edge_sdk; // Handler for messages received from cloud // Cloud sends to: thing/product/${gateway_sn}/services // Format: {"method": "custom_data_transmission_to_esdk", "data": {"value": "..."}} void OnCloudMessage(const uint8_t* data, uint32_t len) { std::string message(reinterpret_cast(data), len); std::cout << "Received from cloud: " << message << std::endl; // Parse and handle the message // Example: Process command, respond with status, etc. if (message == "status_request") { // Send status back to cloud const char* response = "status:ok,temp:45,battery:85"; CloudAPI_SendCustomEventsMessage( reinterpret_cast(response), strlen(response)); } } int main() { // Assume SDK initialized // Register handler for incoming cloud messages // Note: Handler should not perform long-running tasks (use task queue instead) auto rc = CloudAPI_RegisterCustomServicesMessageHandler(OnCloudMessage); if (rc != kOk) { std::cerr << "Failed to register cloud handler: " << rc << std::endl; return -1; } // Send events to cloud // SDK publishes to: thing/product/${gateway_sn}/events // Format: {"method": "custom_data_transmission_from_esdk", "data": {"value": "..."}} // Example: Send periodic telemetry int counter = 0; while (true) { char message[256]; snprintf(message, sizeof(message), "{\"type\":\"telemetry\",\"seq\":%d,\"data\":\"edge_device_active\"}", counter++); rc = CloudAPI_SendCustomEventsMessage( reinterpret_cast(message), strlen(message)); if (rc == kOk) { std::cout << "Sent to cloud: " << message << std::endl; } else { std::cerr << "Failed to send message: " << rc << std::endl; } std::this_thread::sleep_for(std::chrono::seconds(5)); } return 0; } ``` -------------------------------- ### OpenCV Dependency Check and Configuration Source: https://github.com/dji-sdk/edge-sdk/blob/master/CMakeLists.txt Finds the OpenCV package and configures build definitions based on its presence and version. If OpenCV is found, it prints its include directories and libraries, and defines preprocessor macros for OpenCV version detection. ```cmake find_package(OpenCV QUIET) if (OpenCV_FOUND) message("\n${PROJECT_NAME}...") message(STATUS "Found OpenCV installed in the system, will use it to display image in AdvancedSensing APIs") message(STATUS " - Includes: ${OpenCV_INCLUDE_DIRS}") message(STATUS " - Libraries: ${OpenCV_LIBRARIES}") add_definitions(-DOPEN_CV_INSTALLED) execute_process(COMMAND opencv_version OUTPUT_VARIABLE OPENCV_VERSION) if (${OPENCV_VERSION} STRLESS "4.0.0") add_definitions(-DOPEN_CV_VERSION_3) else () add_definitions(-DOPEN_CV_VERSION_4) endif () else () message(STATUS "\nDID NOT FIND OPENCV IN THE SYSTEM, SOME EXECUTABLE FILES WILL NOT BE BUILT!!\n") endif () ``` -------------------------------- ### FFmpeg Dependency Check and Configuration Source: https://github.com/dji-sdk/edge-sdk/blob/master/CMakeLists.txt Finds the FFmpeg package and configures build definitions based on its presence and version. It checks for FFmpeg version 4.x.x and defines a preprocessor macro if found. If FFmpeg is not found, it warns the user. ```cmake set(CMAKE_MODULE_PATH ${CMAKE_CURRENT_SOURCE_DIR}/third_party) find_package(FFMPEG QUIET) if (FFMPEG_FOUND) message(STATUS "Found FFMPEG installed in the system") message(STATUS " - Includes: ${FFMPEG_INCLUDE_DIR}") message(STATUS " - Libraries: ${FFMPEG_LIBRARIES}") EXECUTE_PROCESS(COMMAND ffmpeg -version OUTPUT_VARIABLE ffmpeg_version_output OUTPUT_STRIP_TRAILING_WHITESPACE ) string(REGEX MATCH "version.*Copyright" ffmpeg_version_line ${ffmpeg_version_output}) string(REGEX MATCH " .* " ffmpeg_version ${ffmpeg_version_line}) string(REGEX MATCH "^ 5.*$" ffmpeg_major_version ${ffmpeg_version}) if (HEAD${ffmpeg_major_version} STREQUAL "HEAD") message(STATUS " - Version: ${ffmpeg_version}") else () message(FATAL_ERROR " - Not support FFMPEG version: ${ffmpeg_major_version}, please install 4.x.x instead.") endif () include_directories(${FFMPEG_INCLUDE_DIR}) add_definitions(-DFFMPEG_INSTALLED) else () message(STATUS "\nDID NOT FIND FFMPEG IN THE SYSTEM, SOME EXECUTABLE FILES WILL NOT BE BUILT!!\n") endif (FFMPEG_FOUND) ``` -------------------------------- ### File Globbing and Include Directories Source: https://github.com/dji-sdk/edge-sdk/blob/master/CMakeLists.txt Uses file globbing to recursively find source files for modules and sets up include directories for project headers. This helps in organizing and finding source files across different directories. ```cmake file(GLOB_RECURSE MODULE_SAMPLE_SRC examples/init/pre_init.cc examples/init/key_store_default.cc) include_directories(include) include_directories(examples) include_directories(examples/common) ``` -------------------------------- ### Cloud API Executable Source: https://github.com/dji-sdk/edge-sdk/blob/master/CMakeLists.txt Defines an executable target for interacting with the cloud API. This executable is linked against the sample library. ```cmake add_executable(sample_cloud_api examples/cloud_api/sample_cloud_api.cc) target_link_libraries(sample_cloud_api ${SAMPLE_LIB}) ``` -------------------------------- ### Cloud API - Custom Data Transmission Source: https://context7.com/dji-sdk/edge-sdk/llms.txt Enables bidirectional custom data transmission between the Edge SDK and cloud services using the MQTT protocol. Supports sending custom events and receiving custom services messages. ```APIDOC ## Cloud API - Custom Data Transmission ### Description This API facilitates custom data exchange between the Edge SDK and cloud services using MQTT. It allows sending telemetry or commands from the edge device to the cloud and receiving commands or status updates from the cloud to the edge device. Messages are limited to 256 bytes. ### Method POST (Implicit via CloudAPI_SendCustomEventsMessage) ### Endpoint - **Sending to Cloud**: `thing/product/${gateway_sn}/events` - **Receiving from Cloud**: `thing/product/${gateway_sn}/services` ### Parameters #### Query Parameters None #### Request Body **For Sending Events (from Edge to Cloud):** - **`method`** (string) - Required - Must be `"custom_data_transmission_from_esdk"`. - **`data`** (object) - Required - Contains the custom payload. - **`value`** (string) - The actual data payload (e.g., telemetry data, status). **For Receiving Services (from Cloud to Edge):** - **`method`** (string) - Required - Must be `"custom_data_transmission_to_esdk"`. - **`data`** (object) - Required - Contains the command or data from the cloud. - **`value`** (string) - The actual command or data payload. ### Request Example **Sending Telemetry from Edge to Cloud:** ```json { "method": "custom_data_transmission_from_esdk", "data": { "value": "{\"type\":\"telemetry\",\"seq\":0,\"data\":\"edge_device_active\"}" } } ``` ### Response #### Success Response (200) **When sending messages:** The SDK returns `kOk` upon successful queuing for transmission. **When receiving messages:** The `OnCloudMessage` callback is invoked with the received data. #### Response Example **Example of a message received by `OnCloudMessage` callback:** ```json { "method": "custom_data_transmission_to_esdk", "data": { "value": "status_request" } } ``` **Example of a response sent from `OnCloudMessage` callback:** ``` status:ok,temp:45,battery:85 ``` ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.