first commit

This commit is contained in:
DESKTOP-4HD0KC3\ZhangZhuo
2024-10-30 15:04:53 +08:00
commit e7d6f4c57b
723 changed files with 7515585 additions and 0 deletions

View File

@ -0,0 +1,179 @@
/**
********************************************************************
* @file test_camera_manager_entry.cpp
* @brief
*
* @copyright (c) 2018 DJI. All rights reserved.
*
* All information contained herein is, and remains, the property of DJI.
* The intellectual and technical concepts contained herein are proprietary
* to DJI and may be covered by U.S. and foreign patents, patents in process,
* and protected by trade secret or copyright law. Dissemination of this
* information, including but not limited to data and other proprietary
* material(s) incorporated within the information, in any form, is strictly
* prohibited without the express written consent of DJI.
*
* If you receive this source code without DJIs authorization, you may not
* further disseminate the information, and you must immediately remove the
* source code and notify DJI of its removal. DJI reserves the right to pursue
* legal actions against you for any loss(es) or damage(s) caused by your
* failure to do so.
*
*********************************************************************
*/
/* Includes ------------------------------------------------------------------*/
#include <iostream>
#include <string>
#include <dji_logger.h>
#include <dji_typedef.h>
#include "utils/util_misc.h"
#include "dji_camera_manager.h"
#include "camera_manager/test_camera_manager.h"
#include "camera_manager/test_camera_manager_entry.h"
#include "test_camera_manager_entry.h"
using namespace std;
/* Private constants ---------------------------------------------------------*/
static const char *s_cameraManagerSampleSelectList[] = {
[E_DJI_TEST_CAMERA_MANAGER_SAMPLE_SELECT_SET_CAMERA_SHUTTER_SPEED] = "Set camera shutter speed |",
[E_DJI_TEST_CAMERA_MANAGER_SAMPLE_SELECT_SET_CAMERA_APERTURE] = "Set camera aperture |",
[E_DJI_TEST_CAMERA_MANAGER_SAMPLE_SELECT_SET_CAMERA_EV] = "Set camera ev |",
[E_DJI_TEST_CAMERA_MANAGER_SAMPLE_SELECT_SET_CAMERA_ISO] = "Set camera iso |",
[E_DJI_TEST_CAMERA_MANAGER_SAMPLE_SELECT_SET_CAMERA_FOCUS_POINT] = "Set camera focus point |",
[E_DJI_TEST_CAMERA_MANAGER_SAMPLE_SELECT_SET_CAMERA_TAP_ZOOM_POINT] = "Set camera tap zoom point |",
[E_DJI_TEST_CAMERA_MANAGER_SAMPLE_SELECT_SET_CAMERA_ZOOM_PARAM] = "Set camera zoom param |",
[E_DJI_TEST_CAMERA_MANAGER_SAMPLE_SELECT_SHOOT_SINGLE_PHOTO] = "Shoot single photo |",
[E_DJI_TEST_CAMERA_MANAGER_SAMPLE_SELECT_SHOOT_BURST_PHOTO] = "Shoot busrt photo |",
[E_DJI_TEST_CAMERA_MANAGER_SAMPLE_SELECT_SHOOT_INTERVAL_PHOTO] = "Shoot interval photo |",
[E_DJI_TEST_CAMERA_MANAGER_SAMPLE_SELECT_RECORD_VIDEO] = "Record video |",
[E_DJI_TEST_CAMERA_MANAGER_SAMPLE_SELECT_DOWNLOAD_AND_DELETE_MEDIA_FILE] = "Download and delete media file |",
[E_DJI_TEST_CAMERA_MANAGER_SAMPLE_SELECT_DOWNLOAD_FILE_LIST_BY_SLICES] = "Download file list by slices |",
[E_DJI_TEST_CAMERA_MANAGER_SAMPLE_SELECT_THERMOMETRY] = "Thermometry test |",
[E_DJI_TEST_CAMERA_MANAGER_SAMPLE_SELECT_GET_LIDAR_RANGING_INFO] = "Get lidar ranging info |",
[E_DJI_TEST_CAMERA_MANAGER_SAMPLE_SELECT_IR_CAMERA_ZOOM_PARAM] = "Set ir camera zoom param |",
[E_DJI_TEST_CAMERA_MANAGER_SAMPLE_SELECT_SET_NIGHT_SCENE_MODE] = "Set night scene mode |",
[E_DJI_TEST_CAMERA_MANAGER_SAMPLE_SELECT_SET_CAPTURE_RECORDING_STREAMS] = "Set capture or recording streams storage type |",
[E_DJI_TEST_CAMERA_MANAGER_SAMPLE_SELECT_SHOW_STORAGE_INFO] = "Show storage info |",
[E_DJI_TEST_CAMERA_MANAGER_SAMPLE_SELECT_FORMAT_SD_CARD] = "Format SD card |",
[E_DJI_TEST_CAMERA_MANAGER_SAMPLE_SELECT_SET_LINK_ZOOM] = "Set synchronized split screen zoom |",
[E_DJI_TEST_CAMERA_MANAGER_SAMPLE_SELECT_SET_USER_CUSTOM_DIR_FILE_NAME] = "Set custom directory or file name of media file |",
[E_DJI_TEST_CAMERA_MANAGER_SAMPLE_SELECT_RESET_CAMERA_SETTINGS] = "Reset camera settings |",
[E_DJI_TEST_CAMERA_MANAGER_SAMPLE_SELECT_SET_AE_LOCK_MODE] = "Set AE lock mode |",
[E_DJI_TEST_CAMERA_MANAGER_SAMPLE_SELECT_SET_FOCUS_RING_VALUE] = "Set focus ring value |",
[E_DJI_TEST_CAMERA_MANAGER_SAMPLE_SELECT_CONNECT_STATUS_TEST] = "Camera connect status test |",
[E_DJI_TEST_CAMERA_MANAGER_SAMPLE_SELECT_SET_GET_PHOTO_VIDEO_PARAM] = "Set camera photo and video storage param |",
[E_DJI_TEST_CAMERA_MANAGER_SAMPLE_SELECT_SET_METERING_MODE] = "Set camera metering mode |",
[E_DJI_TEST_CAMERA_MANAGER_SAMPLE_SELECT_SET_METERING_POINT] = "Set and get camera metering point |",
[E_DJI_TEST_CAMERA_MANAGER_SAMPLE_SELECT_FFC_MODE_AND_TRRIGER] = "Set FFC mode and trriger a FFC |",
[E_DJI_TEST_CAMERA_MANAGER_SAMPLE_SELECT_SET_GAIN_MODE] = "Set infrared camera gain mode |",
[E_DJI_TEST_CAMERA_MANAGER_SAMPLE_SELECT_GET_CAMERA_STATUS] = "Get camera status, capturing & recording status etc |",
[E_DJI_TEST_CAMERA_MANAGER_SAMPLE_SELECT_SUBSCRIBE_POINT_CLOUD] = "Subscribe point cloud |",
};
/* Private types -------------------------------------------------------------*/
/* Private values -------------------------------------------------------------*/
/* Private functions declaration ---------------------------------------------*/
static void DjiTest_CmareManagerShowStringList(const char **list, int size)
{
for (int i = 0; i < size; i++) {
printf("| [%2d] %s\r\n", i, list[i]);
}
}
static void DjiTest_CameraManagerShowSampleSelectList(void)
{
DjiTest_CmareManagerShowStringList(s_cameraManagerSampleSelectList,
UTIL_ARRAY_SIZE(s_cameraManagerSampleSelectList));
}
/* Exported functions definition ---------------------------------------------*/
void DjiUser_RunCameraManagerSample(void)
{
T_DjiOsalHandler *osalHandler = DjiPlatform_GetOsalHandler();
string mountPositionStr;
int posNum;
E_DjiMountPosition cameraMountPosition;
string sampleSelectStr;
int sampleSelectNum;
E_DjiTestCameraManagerSampleSelect cameraSample;
USER_LOG_INFO("DjiUser_RunCameraManagerSample");
while (true) {
osalHandler->TaskSleepMs(10);
cout
<< "| Available position: |"
<<
endl;
cout
<< "| [1] Select gimbal mount position at NO.1 payload port |"
<<
endl;
cout
<< "| [2] Select gimbal mount position at NO.2 payload port |"
<<
endl;
cout
<< "| [3] Select gimbal mount position at NO.3 payload port |"
<<
endl;
cout
<< "| [q] Quit |"
<<
endl;
cout << "Please input number to select position (input q to quit): ";
cin >> mountPositionStr;
if (mountPositionStr == "q") {
return;
}
posNum = atoi(mountPositionStr.c_str());
if (posNum > 3 || posNum < 1) {
USER_LOG_ERROR("Input mount position is invalid");
continue;
} else {
break;
}
}
cameraMountPosition = E_DjiMountPosition(posNum);
while (true) {
osalHandler->TaskSleepMs(10);
cout << "\nAvailable samples:\n";
DjiTest_CameraManagerShowSampleSelectList();
cout << "Please input number to select sample (input q to quit): ";
cin >> sampleSelectStr;
if (sampleSelectStr == "q") {
return;
}
sampleSelectNum = atoi(sampleSelectStr.c_str());
if (sampleSelectNum < 0 ||
sampleSelectNum >= (int) E_DJI_TEST_CAMERA_MANAGER_SAMPLE_SELECT_INDEX_MAX) {
USER_LOG_ERROR("Input camera sample is invalid");
continue;
}
cameraSample = (E_DjiTestCameraManagerSampleSelect) sampleSelectNum;
cout << "Start test: position " << cameraMountPosition
<< ", sample " << cameraSample << endl;
DjiTest_CameraManagerRunSample(cameraMountPosition, cameraSample);
}
}
/* Private functions definition-----------------------------------------------*/
/****************** (C) COPYRIGHT DJI Innovations *****END OF FILE****/

View File

@ -0,0 +1,52 @@
/**
********************************************************************
* @file test_camera_manager_entry.h
* @brief This is the header file for "test_camera_manager_entry.c", defining the structure and
* (exported) function prototypes.
*
* @copyright (c) 2018 DJI. All rights reserved.
*
* All information contained herein is, and remains, the property of DJI.
* The intellectual and technical concepts contained herein are proprietary
* to DJI and may be covered by U.S. and foreign patents, patents in process,
* and protected by trade secret or copyright law. Dissemination of this
* information, including but not limited to data and other proprietary
* material(s) incorporated within the information, in any form, is strictly
* prohibited without the express written consent of DJI.
*
* If you receive this source code without DJIs authorization, you may not
* further disseminate the information, and you must immediately remove the
* source code and notify DJI of its removal. DJI reserves the right to pursue
* legal actions against you for any loss(es) or damage(s) caused by your
* failure to do so.
*
*********************************************************************
*/
/* Define to prevent recursive inclusion -------------------------------------*/
#ifndef TEST_CAMERA_MANAGER_ENTRY_H
#define TEST_CAMERA_MANAGER_ENTRY_H
/* Includes ------------------------------------------------------------------*/
#ifdef __cplusplus
extern "C" {
#endif
/* Exported constants --------------------------------------------------------*/
/* Exported types ------------------------------------------------------------*/
/* Exported functions --------------------------------------------------------*/
/**
* @brief Run camera Manager sample.
* @return void.
*/
void DjiUser_RunCameraManagerSample(void);
#ifdef __cplusplus
}
#endif
#endif // TEST_CAMERA_MANAGER_ENTRY_H
/************************ (C) COPYRIGHT DJI Innovations *******END OF FILE******/

View File

@ -0,0 +1,68 @@
{
"rc_lost_action": {
"desc_cn": "失控行为",
"desc_en": "rc lost action",
"desc_range": "go_home/hover/landing",
"value": "go_home"
},
"go_home_altitude": {
"desc_cn": "返航高度",
"desc_en": "go home altitude",
"desc_range": "0 - 1500",
"value": 60
},
"flying_speed": {
"desc_cn": "飞行速度",
"desc_en": "flying speed",
"desc_range": "0 - 10",
"value": 5.0
},
"home_point_latitude": {
"desc_cn": "home点纬度",
"desc_en": "home point latitude",
"desc_range": "-90 - 90",
"value": 22.5425
},
"home_point_longitude": {
"desc_cn": "home点经度",
"desc_en": "home point longitude",
"desc_range": "-180 - 180",
"value": 113.9575
},
"rtk_enable": {
"desc_cn": "RTK开关",
"desc_en": "RTK Enable",
"desc_range": "true/false",
"value": "false"
},
"HorizontalVisualObstacleAvoidanceEnable": {
"desc_cn": "水平视觉避障开关",
"desc_en": "Horizontal Visual Avoidance",
"desc_range": "true/false",
"value": "false"
},
"HorizontalRadarObstacleAvoidanceEnable": {
"desc_cn": "水平TOF避障开关",
"desc_en": "Horizontal TOF Avoidance",
"desc_range": "true/false",
"value": "false"
},
"UpwardsVisualObstacleAvoidanceEnable": {
"desc_cn": "上视觉避障开关",
"desc_en": "Upwards Visual Avoidance",
"desc_range": "true/false",
"value": "false"
},
"UpwardsRadarObstacleAvoidanceEnable": {
"desc_cn": "上TOF开关",
"desc_en": "Upwards TOF Avoidance",
"desc_range": "true/false",
"value": "false"
},
"DownwardsVisualObstacleAvoidanceEnable": {
"desc_cn": "下视觉避障开关",
"desc_en": "Downwards Visual Avoidance",
"desc_range": "true/false",
"value": "false"
}
}

View File

@ -0,0 +1,48 @@
/**
********************************************************************
* @file test_flight_controller_command_flying.h
* @brief This is the header file for "test_flight_controller_command_flying.c", defining the structure and
* (exported) function prototypes.
*
* @copyright (c) 2018 DJI. All rights reserved.
*
* All information contained herein is, and remains, the property of DJI.
* The intellectual and technical concepts contained herein are proprietary
* to DJI and may be covered by U.S. and foreign patents, patents in process,
* and protected by trade secret or copyright law. Dissemination of this
* information, including but not limited to data and other proprietary
* material(s) incorporated within the information, in any form, is strictly
* prohibited without the express written consent of DJI.
*
* If you receive this source code without DJIs authorization, you may not
* further disseminate the information, and you must immediately remove the
* source code and notify DJI of its removal. DJI reserves the right to pursue
* legal actions against you for any loss(es) or damage(s) caused by your
* failure to do so.
*
*********************************************************************
*/
/* Define to prevent recursive inclusion -------------------------------------*/
#ifndef TEST_FLIGHT_CONTROLLER_COMMAND_FLYING_H
#define TEST_FLIGHT_CONTROLLER_COMMAND_FLYING_H
/* Includes ------------------------------------------------------------------*/
#ifdef __cplusplus
extern "C" {
#endif
/* Exported constants --------------------------------------------------------*/
/* Exported types ------------------------------------------------------------*/
/* Exported functions --------------------------------------------------------*/
void DjiUser_RunFlightControllerCommandFlyingSample(void);
#ifdef __cplusplus
}
#endif
#endif // TEST_FLIGHT_CONTROLLER_COMMAND_FLYING_H
/************************ (C) COPYRIGHT DJI Innovations *******END OF FILE******/

View File

@ -0,0 +1,113 @@
/**
********************************************************************
* @file test_flight_controller_entry.cpp
* @brief
*
* @copyright (c) 2018 DJI. All rights reserved.
*
* All information contained herein is, and remains, the property of DJI.
* The intellectual and technical concepts contained herein are proprietary
* to DJI and may be covered by U.S. and foreign patents, patents in process,
* and protected by trade secret or copyright law. Dissemination of this
* information, including but not limited to data and other proprietary
* material(s) incorporated within the information, in any form, is strictly
* prohibited without the express written consent of DJI.
*
* If you receive this source code without DJIs authorization, you may not
* further disseminate the information, and you must immediately remove the
* source code and notify DJI of its removal. DJI reserves the right to pursue
* legal actions against you for any loss(es) or damage(s) caused by your
* failure to do so.
*
*********************************************************************
*/
/* Includes ------------------------------------------------------------------*/
#include <iostream>
#include <flight_control/test_flight_control.h>
#include "test_flight_controller_entry.h"
#include "dji_logger.h"
#include "test_flight_controller_command_flying.h"
#include <waypoint_v2/test_waypoint_v2.h>
#include <waypoint_v3/test_waypoint_v3.h>
#include <interest_point/test_interest_point.h>
/* Private constants ---------------------------------------------------------*/
/* Private types -------------------------------------------------------------*/
/* Private values -------------------------------------------------------------*/
/* Private functions declaration ---------------------------------------------*/
/* Exported functions definition ---------------------------------------------*/
void DjiUser_RunFlightControllerSample(void)
{
T_DjiOsalHandler *osalHandler = DjiPlatform_GetOsalHandler();
char inputSelectSample;
start:
osalHandler->TaskSleepMs(100);
std::cout
<< "\n"
<< "| Available commands: |\n"
<< "| [0] Flight controller sample - control flying with keyboard |\n"
<< "| [1] Flight controller sample - take off landing |\n"
<< "| [2] Flight controller sample - take off position ctrl landing |\n"
<< "| [3] Flight controller sample - take off go home force landing |\n"
<< "| [4] Flight controller sample - take off velocity ctrl landing |\n"
<< "| [5] Flight controller sample - arrest flying |\n"
<< "| [6] Flight controller sample - set get parameters |\n"
<< "| [7] Waypoint 2.0 sample - run airline mission by settings (only support on M300 RTK) |\n"
<< "| [8] Waypoint 3.0 sample - run airline mission by kmz file (not support on M300 RTK) |\n"
<< "| [9] Interest point sample - run interest point mission by settings (only support on M3E/M3T) |\n"
<< "| [a] EU-C6 FTS trigger sample - receive fts callback to trigger parachute function (only support on M3D/M3DT) |\n"
<< std::endl;
std::cin >> inputSelectSample;
switch (inputSelectSample) {
case '0':
DjiUser_RunFlightControllerCommandFlyingSample();
goto start;
case '1':
DjiTest_FlightControlRunSample(E_DJI_TEST_FLIGHT_CTRL_SAMPLE_SELECT_TAKE_OFF_LANDING);
goto start;
case '2':
DjiTest_FlightControlRunSample(E_DJI_TEST_FLIGHT_CTRL_SAMPLE_SELECT_TAKE_OFF_POSITION_CTRL_LANDING);
goto start;
case '3':
DjiTest_FlightControlRunSample(E_DJI_TEST_FLIGHT_CTRL_SAMPLE_SELECT_TAKE_OFF_GO_HOME_FORCE_LANDING);
goto start;
case '4':
DjiTest_FlightControlRunSample(E_DJI_TEST_FLIGHT_CTRL_SAMPLE_SELECT_TAKE_OFF_VELOCITY_CTRL_LANDING);
goto start;
case '5':
DjiTest_FlightControlRunSample(E_DJI_TEST_FLIGHT_CTRL_SAMPLE_SELECT_ARREST_FLYING);
goto start;
case '6':
DjiTest_FlightControlRunSample(E_DJI_TEST_FLIGHT_CTRL_SAMPLE_SELECT_SET_GET_PARAM);
goto start;
case '7':
DjiTest_WaypointV2RunSample();
break;
case '8':
DjiTest_WaypointV3RunSample();
break;
case '9':
DjiTest_InterestPointRunSample();
break;
case 'a':
DjiTest_FlightControlRunSample(E_DJI_TEST_FLIGHT_CTRL_SAMPLE_SELECT_FTS_TRIGGER);
break;
case 'q':
break;
default:
USER_LOG_ERROR("Input command is invalid");
goto start;
}
}
/* Private functions definition-----------------------------------------------*/
/****************** (C) COPYRIGHT DJI Innovations *****END OF FILE****/

View File

@ -0,0 +1,49 @@
/**
********************************************************************
* @file test_flight_controller_entry.h
* @brief This is the header file for "test_flight_controller_entry.c", defining the structure and
* (exported) function prototypes.
*
* @copyright (c) 2018 DJI. All rights reserved.
*
* All information contained herein is, and remains, the property of DJI.
* The intellectual and technical concepts contained herein are proprietary
* to DJI and may be covered by U.S. and foreign patents, patents in process,
* and protected by trade secret or copyright law. Dissemination of this
* information, including but not limited to data and other proprietary
* material(s) incorporated within the information, in any form, is strictly
* prohibited without the express written consent of DJI.
*
* If you receive this source code without DJIs authorization, you may not
* further disseminate the information, and you must immediately remove the
* source code and notify DJI of its removal. DJI reserves the right to pursue
* legal actions against you for any loss(es) or damage(s) caused by your
* failure to do so.
*
*********************************************************************
*/
/* Define to prevent recursive inclusion -------------------------------------*/
#ifndef TEST_FLIGHT_CONTROLLER_ENTRY_H
#define TEST_FLIGHT_CONTROLLER_ENTRY_H
/* Includes ------------------------------------------------------------------*/
#include <gimbal_manager/test_gimbal_manager.h>
#ifdef __cplusplus
extern "C" {
#endif
/* Exported constants --------------------------------------------------------*/
/* Exported types ------------------------------------------------------------*/
/* Exported functions --------------------------------------------------------*/
void DjiUser_RunFlightControllerSample(void);
#ifdef __cplusplus
}
#endif
#endif // TEST_FLIGHT_CONTROLLER_ENTRY_H
/************************ (C) COPYRIGHT DJI Innovations *******END OF FILE******/

View File

@ -0,0 +1,453 @@
/**
********************************************************************
* @file test_gimbal_entry.cpp
* @version V2.0.0
* @date 2023/3/28
* @brief
*
* @copyright (c) 2018-2023 DJI. All rights reserved.
*
* All information contained herein is, and remains, the property of DJI.
* The intellectual and technical concepts contained herein are proprietary
* to DJI and may be covered by U.S. and foreign patents, patents in process,
* and protected by trade secret or copyright law. Dissemination of this
* information, including but not limited to data and other proprietary
* material(s) incorporated within the information, in any form, is strictly
* prohibited without the express written consent of DJI.
*
* If you receive this source code without DJIs authorization, you may not
* further disseminate the information, and you must immediately remove the
* source code and notify DJI of its removal. DJI reserves the right to pursue
* legal actions against you for any loss(es) or damage(s) caused by your
* failure to do so.
*
*********************************************************************
*/
/* Includes ------------------------------------------------------------------*/
#include <stdexcept>
#include "test_gimbal_entry.hpp"
#include "dji_logger.h"
#include "utils/util_misc.h"
#include "dji_gimbal.h"
#include "dji_gimbal_manager.h"
#include <iostream>
#include "dji_aircraft_info.h"
#include "dji_fc_subscription.h"
#include <math.h>
/* Private constants ---------------------------------------------------------*/
/* Private types -------------------------------------------------------------*/
typedef enum {
E_DJI_TEST_GIMBAL_MANAGER_SAMPLE_SELECT_ROTATE_GIMBAL_ON_FREE_MODE,
E_DJI_TEST_GIMBAL_MANAGER_SAMPLE_SELECT_ROTATE_GIMBAL_ON_YAW_FOLLOW_MODE,
E_DJI_TEST_GIMBAL_MANAGER_SAMPLE_SELECT_SET_PITCH_RANGE_EXTENSION_MODE,
E_DJI_TEST_GIMBAL_MANAGER_SAMPLE_SELECT_SET_CONTROLLER_MAX_SPEED_PERCENTAGE,
E_DJI_TEST_GIMBAL_MANAGER_SAMPLE_SELECT_SET_CONTROLLER_SMOOTH_FACTOR,
E_DJI_TEST_GIMBAL_MANAGER_SAMPLE_SELECT_RESET_GIMBAL_SETTINGS,
E_DJI_TEST_GIMBAL_MANAGER_SAMPLE_SELECT_ROTATE_GIMBAL_BY_KEYBOARD,
E_DJI_TEST_GIMBAL_MANAGER_SAMPLE_SELECT_QUIT,
} E_DjiTestGimbalManagerSampleSelect;
/* Private values -------------------------------------------------------------*/
static const char *s_gimbalManagerSampleList[] = {
[E_DJI_TEST_GIMBAL_MANAGER_SAMPLE_SELECT_ROTATE_GIMBAL_ON_FREE_MODE] =
"| [0] Gimbal manager sample - Rotate gimbal on free mode |",
[E_DJI_TEST_GIMBAL_MANAGER_SAMPLE_SELECT_ROTATE_GIMBAL_ON_YAW_FOLLOW_MODE] =
"| [1] Gimbal manager sample - Rotate gimbal on yaw follow mode |",
[E_DJI_TEST_GIMBAL_MANAGER_SAMPLE_SELECT_SET_PITCH_RANGE_EXTENSION_MODE] =
"| [2] Gimbal manager sample - Set pitch range extension mode |",
[E_DJI_TEST_GIMBAL_MANAGER_SAMPLE_SELECT_SET_CONTROLLER_MAX_SPEED_PERCENTAGE] =
"| [3] Gimbal manager sample - Set controller max speed percentage |",
[E_DJI_TEST_GIMBAL_MANAGER_SAMPLE_SELECT_SET_CONTROLLER_SMOOTH_FACTOR] =
"| [4] Gimbal manager sample - Set controller smooth factor |",
[E_DJI_TEST_GIMBAL_MANAGER_SAMPLE_SELECT_RESET_GIMBAL_SETTINGS] =
"| [5] Gimbal manager sample - Reset gimbal settings |",
[E_DJI_TEST_GIMBAL_MANAGER_SAMPLE_SELECT_ROTATE_GIMBAL_BY_KEYBOARD] =
"| [6] Gimbal manager sample - Rotate gimbal by keyboard input and read back value |",
[E_DJI_TEST_GIMBAL_MANAGER_SAMPLE_SELECT_QUIT] =
"| [q] Gimbal manager sample - Quit |",
};
/* Private functions declaration ---------------------------------------------*/
void DjiTest_GimbalManagerShowSampleSelectList(const char **SampleList, uint8_t size);
/* Exported functions definition ---------------------------------------------*/
void DjiUser_RunGimbalManagerSample(void)
{
T_DjiOsalHandler *osalHandler = DjiPlatform_GetOsalHandler();
char inputTestCase;
char mountPosition;
E_DjiMountPosition gimbalMountPosition;
T_DjiReturnCode returnCode;
start:
osalHandler->TaskSleepMs(100);
std::cout
<< "| Available position: |"
<<
std::endl;
std::cout
<< "| [1] Select gimbal mount position at NO.1 payload port |"
<<
std::endl;
std::cout
<< "| [2] Select gimbal mount position at NO.2 payload port |"
<<
std::endl;
std::cout
<< "| [3] Select gimbal mount position at NO.3 payload port |"
<<
std::endl;
std::cout
<< "| [q] Quit |"
<<
std::endl;
std::cin >> mountPosition;
if (mountPosition == 'q') {
return;
}
if (mountPosition > '3' || mountPosition < '1') {
USER_LOG_ERROR("Input mount position is invalid");
goto start;
}
gimbalMountPosition = E_DjiMountPosition(mountPosition - '0');
osalHandler->TaskSleepMs(100);
std::cout
<< "| Available commands: |"
<<
std::endl;
DjiTest_GimbalManagerShowSampleSelectList(s_gimbalManagerSampleList, UTIL_ARRAY_SIZE(s_gimbalManagerSampleList));
std::cin >> inputTestCase;
switch (inputTestCase) {
case '0':
DjiTest_GimbalManagerRunSample(gimbalMountPosition, DJI_GIMBAL_MODE_FREE);
goto start;
case '1':
DjiTest_GimbalManagerRunSample(gimbalMountPosition, DJI_GIMBAL_MODE_YAW_FOLLOW);
goto start;
case '2': {
int32_t enableFlag;
osalHandler->TaskSleepMs(10);
printf("Input enable flag: ");
scanf("%d", &enableFlag);
returnCode = DjiGimbalManager_Init();
if (returnCode != DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS) {
USER_LOG_ERROR("Init gimbal manager error, return code 0x%08X", returnCode);
return;
}
returnCode = DjiGimbalManager_SetPitchRangeExtensionEnabled(gimbalMountPosition, (bool)enableFlag);
if (returnCode != DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS) {
USER_LOG_ERROR("Failed!");
}
USER_LOG_INFO("Set gimbal's pitch range extension mode as %d successfully!", enableFlag);
goto start;
break;
}
case '3': {
int32_t percentage;
osalHandler->TaskSleepMs(10);
printf("Input max speed percentage of yaw axis: ");
scanf("%d", &percentage);
returnCode = DjiGimbalManager_Init();
if (returnCode != DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS) {
USER_LOG_ERROR("Init gimbal manager error, return code 0x%08X", returnCode);
return;
}
returnCode = DjiGimbalManager_SetControllerMaxSpeedPercentage(gimbalMountPosition, DJI_GIMBAL_AXIS_YAW, (uint8_t)percentage);
if (returnCode != DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS) {
USER_LOG_ERROR("Failed!");
}
USER_LOG_INFO("Set yaw axis's max speed percentage to %d successfully!", percentage);
osalHandler->TaskSleepMs(10);
printf("Input max speed percentage of pitch axis: ");
scanf("%d", &percentage);
returnCode = DjiGimbalManager_SetControllerMaxSpeedPercentage(gimbalMountPosition, DJI_GIMBAL_AXIS_PITCH, (uint8_t)percentage);
if (returnCode != DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS) {
USER_LOG_ERROR("Failed!");
}
USER_LOG_INFO("Set pitch axis's max speed percentage to %d successfully!", percentage);
goto start;
break;
}
case '4': {
int32_t factor;
osalHandler->TaskSleepMs(10);
printf("Input yaw axis's smooth factor: ");
scanf("%d", &factor);
returnCode = DjiGimbalManager_Init();
if (returnCode != DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS) {
USER_LOG_ERROR("Init gimbal manager error, return code 0x%08X", returnCode);
return;
}
returnCode = DjiGimbalManager_SetControllerSmoothFactor(gimbalMountPosition, DJI_GIMBAL_AXIS_YAW, (uint8_t)factor);
if (returnCode != DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS) {
USER_LOG_ERROR("Failed!");
}
USER_LOG_INFO("Set yaw axis smooth factor to %d successfully!", factor);
osalHandler->TaskSleepMs(10);
printf("Input pitch axis's smooth factor: ");
scanf("%d", &factor);
returnCode = DjiGimbalManager_SetControllerSmoothFactor(gimbalMountPosition, DJI_GIMBAL_AXIS_PITCH, (uint8_t)factor);
if (returnCode != DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS) {
USER_LOG_ERROR("Failed!");
}
USER_LOG_INFO("Set pitch axis smooth factor to %d successfully!", factor);
goto start;
break;
}
case '5': {
returnCode = DjiGimbalManager_Init();
if (returnCode != DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS) {
USER_LOG_ERROR("Init gimbal manager error, return code 0x%08X", returnCode);
return;
}
returnCode = DjiGimbalManager_RestoreFactorySettings(gimbalMountPosition);
if (returnCode != DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS) {
USER_LOG_ERROR("Failed!");
}
USER_LOG_INFO("Reset gimbal factory settings successfully!");
goto start;
break;
}
case '6': {
uint32_t gimbalMode;
uint32_t rotateMode;
dji_f32_t pitch, roll, yaw;
T_DjiGimbalManagerRotation rotation;
T_DjiAircraftInfoBaseInfo baseInfo;
E_DjiAircraftSeries aircraftSeries;
returnCode = DjiGimbalManager_Init();
if (returnCode != DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS) {
USER_LOG_ERROR("Init gimbal manager error, return code 0x%08X", returnCode);
return;
}
returnCode = DjiAircraftInfo_GetBaseInfo(&baseInfo);
if (returnCode != DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS) {
USER_LOG_ERROR("Failed to get aircraft base info, return code 0x%08X", returnCode);
goto end;
}
aircraftSeries = baseInfo.aircraftSeries;
if (aircraftSeries == DJI_AIRCRAFT_SERIES_M300 || aircraftSeries == DJI_AIRCRAFT_SERIES_M350) {
returnCode = DjiFcSubscription_SubscribeTopic(DJI_FC_SUBSCRIPTION_TOPIC_IMU_ATTI_NAVI_DATA_WITH_TIMESTAMP, DJI_DATA_SUBSCRIPTION_TOPIC_50_HZ, NULL);
if (returnCode != DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS) {
USER_LOG_ERROR("DjiFcSubscription_SubscribeTopic %d return %d",
DJI_FC_SUBSCRIPTION_TOPIC_IMU_ATTI_NAVI_DATA_WITH_TIMESTAMP, returnCode);
goto end;
}
returnCode = DjiFcSubscription_SubscribeTopic(DJI_FC_SUBSCRIPTION_TOPIC_QUATERNION, DJI_DATA_SUBSCRIPTION_TOPIC_50_HZ, NULL);
if (returnCode != DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS) {
USER_LOG_ERROR("DjiFcSubscription_SubscribeTopic %d return %d", DJI_FC_SUBSCRIPTION_TOPIC_QUATERNION, returnCode);
goto end;
}
}
if (aircraftSeries == DJI_AIRCRAFT_SERIES_M300 || aircraftSeries == DJI_AIRCRAFT_SERIES_M350) {
returnCode = DjiFcSubscription_SubscribeTopic(DJI_FC_SUBSCRIPTION_TOPIC_THREE_GIMBAL_DATA, DJI_DATA_SUBSCRIPTION_TOPIC_50_HZ, NULL);
if (returnCode != DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS) {
USER_LOG_ERROR("DjiFcSubscription_SubscribeTopic %d return %d", DJI_FC_SUBSCRIPTION_TOPIC_THREE_GIMBAL_DATA, returnCode);
goto end;
}
USER_LOG_INFO("Subscribe topic DJI_FC_SUBSCRIPTION_TOPIC_THREE_GIMBAL_DATA succefully.");
}
else if (aircraftSeries == DJI_AIRCRAFT_SERIES_M30 || aircraftSeries == DJI_AIRCRAFT_SERIES_M3 ||
aircraftSeries == DJI_AIRCRAFT_SERIES_M3D) {
returnCode = DjiFcSubscription_SubscribeTopic(DJI_FC_SUBSCRIPTION_TOPIC_GIMBAL_ANGLES, DJI_DATA_SUBSCRIPTION_TOPIC_50_HZ, NULL);
if (returnCode != DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS) {
USER_LOG_ERROR("DjiFcSubscription_SubscribeTopic %d return %d", DJI_FC_SUBSCRIPTION_TOPIC_GIMBAL_ANGLES, returnCode);
goto end;
}
USER_LOG_INFO("Subscribe topic DJI_FC_SUBSCRIPTION_TOPIC_GIMBAL_ANGLES succefully.");
}
while (1) {
T_DjiFcSubscriptionQuaternion quat;
T_DjiFcSubscriptionThreeGimbalData threeGimbalData = {0};
T_DjiFcSubscriptionGimbalAngles gimbalAngles = {0};
T_DjiDataTimestamp timestamp = {0};
dji_f32_t nPitch, nRoll, nYaw;
dji_f32_t qPitch, qRoll, qYaw;
dji_f32_t yawOffset = 0;
T_DjiFcSubscriptionImuAttiNaviDataWithTimestamp naviData = {0};
osalHandler->TaskSleepMs(5);
printf("gimbal mode: 0: free, 1: fpv, 2: yaw-follow, 3: exit sample\n");
printf("rotate mode: 0: rel, 1: abs\n");
printf("Input gimbal mode, rotate mode, p, r, y(range in 0 ~ 360 deg if in abs mode): ");
scanf("%d", &gimbalMode);
if (gimbalMode == 3) {
break;
}
scanf("%d %f %f %f", &rotateMode, &pitch, &roll, &yaw);
printf("gimbale mode %d, rotate mode %d, p %f, r %f, y %f\n",
gimbalMode, rotateMode, pitch, roll, yaw);
returnCode = DjiGimbalManager_SetMode(gimbalMountPosition, (E_DjiGimbalMode)gimbalMode);
if (returnCode != DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS) {
USER_LOG_ERROR("DjiGimbalManager_SetMode return 0x%08X", returnCode);
goto end;
}
rotation.rotationMode = (E_DjiGimbalRotationMode)rotateMode;
rotation.pitch = pitch;
rotation.roll = roll;
rotation.yaw = yaw;
rotation.time = 0.5;
if (aircraftSeries == DJI_AIRCRAFT_SERIES_M300 || aircraftSeries == DJI_AIRCRAFT_SERIES_M350) {
osalHandler->TaskSleepMs(20);
returnCode = DjiFcSubscription_GetLatestValueOfTopic(DJI_FC_SUBSCRIPTION_TOPIC_IMU_ATTI_NAVI_DATA_WITH_TIMESTAMP,
(uint8_t *) &naviData,
sizeof(T_DjiFcSubscriptionImuAttiNaviDataWithTimestamp),
&timestamp);
if (returnCode != DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS) {
USER_LOG_ERROR("returnCode = 0x%08X", returnCode);
}
nYaw = (dji_f64_t) atan2f(2 * naviData.q[1] * naviData.q[2] + 2 * naviData.q[0] * naviData.q[3],
-2 * naviData.q[2] * naviData.q[2] - 2 * naviData.q[3] * naviData.q[3] + 1) * 57.3;
returnCode = DjiFcSubscription_GetLatestValueOfTopic(DJI_FC_SUBSCRIPTION_TOPIC_QUATERNION,
(uint8_t *) &quat,
sizeof(T_DjiFcSubscriptionQuaternion),
&timestamp);
if (returnCode != DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS) {
USER_LOG_ERROR("DjiFcSubscription_GetLatestValueOfTopic return %x%08X", returnCode);
goto end;
}
qYaw = (dji_f64_t) atan2f(2 * quat.q1 * quat.q2 + 2 * quat.q0 * quat.q3,
-2 * quat.q2 * quat.q2 - 2 * quat.q3 * quat.q3 + 1) * 57.3;
yawOffset = nYaw - qYaw;
if (rotation.rotationMode == DJI_GIMBAL_ROTATION_MODE_ABSOLUTE_ANGLE) {
rotation.yaw += yawOffset;
}
}
returnCode = DjiGimbalManager_Rotate(gimbalMountPosition, rotation);
if (returnCode == DJI_ERROR_GIMBAL_MODULE_CODE_PITCH_REACH_POSITIVE_LIMIT ||
returnCode == DJI_ERROR_GIMBAL_MODULE_CODE_PITCH_REACH_NEGATIVE_LIMIT ||
returnCode == DJI_ERROR_GIMBAL_MODULE_CODE_ROLL_REACH_POSITIVE_LIMIT ||
returnCode == DJI_ERROR_GIMBAL_MODULE_CODE_ROLL_REACH_NEGATIVE_LIMIT ||
returnCode == DJI_ERROR_GIMBAL_MODULE_CODE_YAW_REACH_POSITIVE_LIMIT ||
returnCode == DJI_ERROR_GIMBAL_MODULE_CODE_YAW_REACH_NEGATIVE_LIMIT) {
USER_LOG_WARN("Reach limitation!");
}
else if (returnCode != DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS) {
USER_LOG_ERROR("DjiGimbalManager_Rotate return %x%08X", returnCode);
goto end;
}
osalHandler->TaskSleepMs(2000);
if (aircraftSeries == DJI_AIRCRAFT_SERIES_M300 || aircraftSeries == DJI_AIRCRAFT_SERIES_M350) {
returnCode = DjiFcSubscription_GetLatestValueOfTopic(DJI_FC_SUBSCRIPTION_TOPIC_THREE_GIMBAL_DATA,
(uint8_t *) &threeGimbalData,
sizeof(T_DjiFcSubscriptionThreeGimbalData),
&timestamp);
if (returnCode != DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS) {
USER_LOG_ERROR("DjiFcSubscription_GetLatestValueOfTopic return %x%08X", returnCode);
goto end;
}
if (threeGimbalData.anglesData[0].yaw < 0) {
threeGimbalData.anglesData[0].yaw = 360 + threeGimbalData.anglesData[0].yaw;
}
USER_LOG_INFO("reab back gimbal's (p, r, y): p=%.4f r=%.4f y=%.4f",
threeGimbalData.anglesData[gimbalMountPosition - 1].pitch,
threeGimbalData.anglesData[gimbalMountPosition - 1].roll,
threeGimbalData.anglesData[gimbalMountPosition - 1].yaw);
}
else if (aircraftSeries == DJI_AIRCRAFT_SERIES_M30 || aircraftSeries == DJI_AIRCRAFT_SERIES_M3 ||
aircraftSeries == DJI_AIRCRAFT_SERIES_M3D) {
returnCode = DjiFcSubscription_GetLatestValueOfTopic(DJI_FC_SUBSCRIPTION_TOPIC_GIMBAL_ANGLES,
(uint8_t *) &gimbalAngles,
sizeof(T_DjiFcSubscriptionGimbalAngles),
&timestamp);
if (returnCode != DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS) {
USER_LOG_ERROR("DjiFcSubscription_GetLatestValueOfTopic return %x%08X", returnCode);
goto end;
}
if (gimbalAngles.z < 0) {
gimbalAngles.z = 360 + gimbalAngles.z;
}
USER_LOG_INFO("read back gimbal's (p, r, y): p=%.4f r=%.4f y=%.4f",
gimbalAngles.x, gimbalAngles.y, gimbalAngles.z);
}
}
break;
}
case 'q':
break;
default:
USER_LOG_ERROR("Input command is invalid");
goto start;
}
end:
returnCode = DjiGimbalManager_Deinit();
if (returnCode != DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS) {
USER_LOG_ERROR("Deinit gimbal manager error, return code 0x%08X", returnCode);
return;
}
USER_LOG_INFO("Gimbal sample end");
return;
}
/* Private functions definition-----------------------------------------------*/
void DjiTest_GimbalManagerShowSampleSelectList(const char **SampleList, uint8_t size) {
uint8_t i = 0;
for (i = 0; i < size; i++) {
std::cout << SampleList[i] << std::endl;
}
}
/****************** (C) COPYRIGHT DJI Innovations *****END OF FILE****/

View File

@ -0,0 +1,52 @@
/**
********************************************************************
* @file test_gimbal_entry.hpp
* @version V2.0.0
* @date 2023/3/28
* @brief This is the header file for "test_gimbal_entry.cpp", defining the structure and
* (exported) function prototypes.
*
* @copyright (c) 2018-2023 DJI. All rights reserved.
*
* All information contained herein is, and remains, the property of DJI.
* The intellectual and technical concepts contained herein are proprietary
* to DJI and may be covered by U.S. and foreign patents, patents in process,
* and protected by trade secret or copyright law. Dissemination of this
* information, including but not limited to data and other proprietary
* material(s) incorporated within the information, in any form, is strictly
* prohibited without the express written consent of DJI.
*
* If you receive this source code without DJIs authorization, you may not
* further disseminate the information, and you must immediately remove the
* source code and notify DJI of its removal. DJI reserves the right to pursue
* legal actions against you for any loss(es) or damage(s) caused by your
* failure to do so.
*
*********************************************************************
*/
/* Define to prevent recursive inclusion -------------------------------------*/
#ifndef TEST_GIMBAL_ENTRY_H
#define TEST_GIMBAL_ENTRY_H
/* Includes ------------------------------------------------------------------*/
#include <gimbal_manager/test_gimbal_manager.h>
#ifdef __cplusplus
extern "C" {
#endif
/* Exported constants --------------------------------------------------------*/
/* Exported types ------------------------------------------------------------*/
/* Exported functions --------------------------------------------------------*/
void DjiUser_RunGimbalManagerSample(void);
#ifdef __cplusplus
}
#endif
#endif // TEST_GIMBAL_ENTRY_H
/************************ (C) COPYRIGHT DJI Innovations *******END OF FILE******/

View File

@ -0,0 +1,82 @@
/**
********************************************************************
* @file hms_manager_entry.cpp
* @brief
*
* @copyright (c) 2018 DJI. All rights reserved.
*
* All information contained herein is, and remains, the property of DJI.
* The intellectual and technical concepts contained herein are proprietary
* to DJI and may be covered by U.S. and foreign patents, patents in process,
* and protected by trade secret or copyright law. Dissemination of this
* information, including but not limited to data and other proprietary
* material(s) incorporated within the information, in any form, is strictly
* prohibited without the express written consent of DJI.
*
* If you receive this source code without DJIs authorization, you may not
* further disseminate the information, and you must immediately remove the
* source code and notify DJI of its removal. DJI reserves the right to pursue
* legal actions against you for any loss(es) or damage(s) caused by your
* failure to do so.
*
*********************************************************************
*/
/* Includes ------------------------------------------------------------------*/
#include "hms_manager_entry.h"
#include "dji_platform.h"
#include <iostream>
#include "dji_logger.h"
#include "hms/test_hms.h"
/* Private constants ---------------------------------------------------------*/
/* Private types -------------------------------------------------------------*/
/* Private values -------------------------------------------------------------*/
/* Private functions declaration ---------------------------------------------*/
/* Exported functions definition ---------------------------------------------*/
void DjiUser_RunHmsManagerSample(void)
{
T_DjiOsalHandler *osalHandler = DjiPlatform_GetOsalHandler();
char inputSelectSample;
start:
osalHandler->TaskSleepMs(100);
std::cout
<< "\n"
<< "| Available commands: |\n"
<< "| [0] Hms manager sample - Chinese language |\n"
<< "| [1] Hms manager sample - English language |\n"
<< "| [2] Hms manager sample - Japanese language |\n"
<< "| [3] Hms manager sample - French language |\n"
<< std::endl;
std::cin >> inputSelectSample;
switch (inputSelectSample) {
case '0':
DjiTest_HmsManagerRunSample(DJI_MOBILE_APP_LANGUAGE_CHINESE);
goto start;
case '1':
DjiTest_HmsManagerRunSample(DJI_MOBILE_APP_LANGUAGE_ENGLISH);
goto start;
case '2':
DjiTest_HmsManagerRunSample(DJI_MOBILE_APP_LANGUAGE_JAPANESE);
goto start;
case '3':
DjiTest_HmsManagerRunSample(DJI_MOBILE_APP_LANGUAGE_FRENCH);
goto start;
case 'q':
break;
default:
USER_LOG_ERROR("Input command is invalid");
goto start;
}
}
/* Private functions definition-----------------------------------------------*/
/****************** (C) COPYRIGHT DJI Innovations *****END OF FILE****/

View File

@ -0,0 +1,49 @@
/**
********************************************************************
* @file hms_manager_entry.h
* @brief This is the header file for "hms_manager_entry.c", defining the structure and
* (exported) function prototypes.
*
* @copyright (c) 2018 DJI. All rights reserved.
*
* All information contained herein is, and remains, the property of DJI.
* The intellectual and technical concepts contained herein are proprietary
* to DJI and may be covered by U.S. and foreign patents, patents in process,
* and protected by trade secret or copyright law. Dissemination of this
* information, including but not limited to data and other proprietary
* material(s) incorporated within the information, in any form, is strictly
* prohibited without the express written consent of DJI.
*
* If you receive this source code without DJIs authorization, you may not
* further disseminate the information, and you must immediately remove the
* source code and notify DJI of its removal. DJI reserves the right to pursue
* legal actions against you for any loss(es) or damage(s) caused by your
* failure to do so.
*
*********************************************************************
*/
/* Define to prevent recursive inclusion -------------------------------------*/
#ifndef HMS_MANAGER_ENTRY_H
#define HMS_MANAGER_ENTRY_H
/* Includes ------------------------------------------------------------------*/
#ifdef __cplusplus
extern "C" {
#endif
/* Exported constants --------------------------------------------------------*/
/* Exported types ------------------------------------------------------------*/
/* Exported functions --------------------------------------------------------*/
void DjiUser_RunHmsManagerSample(void);
#ifdef __cplusplus
}
#endif
#endif // HMS_MANAGER_ENTRY_H
/************************ (C) COPYRIGHT DJI Innovations *******END OF FILE******/

View File

@ -0,0 +1,95 @@
/**
********************************************************************
* @file dji_camera_image_handler.cpp
* @brief
*
* @copyright (c) 2021 DJI. All rights reserved.
*
* All information contained herein is, and remains, the property of DJI.
* The intellectual and technical concepts contained herein are proprietary
* to DJI and may be covered by U.S. and foreign patents, patents in process,
* and protected by trade secret or copyright law. Dissemination of this
* information, including but not limited to data and other proprietary
* material(s) incorporated within the information, in any form, is strictly
* prohibited without the express written consent of DJI.
*
* If you receive this source code without DJIs authorization, you may not
* further disseminate the information, and you must immediately remove the
* source code and notify DJI of its removal. DJI reserves the right to pursue
* legal actions against you for any loss(es) or damage(s) caused by your
* failure to do so.
*
*********************************************************************
*/
/* Includes ------------------------------------------------------------------*/
#include "dji_camera_image_handler.hpp"
/* Private constants ---------------------------------------------------------*/
/* Private types -------------------------------------------------------------*/
/* Private values -------------------------------------------------------------*/
/* Private functions declaration ---------------------------------------------*/
/* Exported functions definition ---------------------------------------------*/
DJICameraImageHandler::DJICameraImageHandler() : m_newImageFlag(false)
{
pthread_mutex_init(&m_mutex, NULL);
pthread_cond_init(&m_condv, NULL);
}
DJICameraImageHandler::~DJICameraImageHandler()
{
pthread_mutex_destroy(&m_mutex);
pthread_cond_destroy(&m_condv);
}
bool DJICameraImageHandler::getNewImageWithLock(CameraRGBImage &copyOfImage, int timeoutMilliSec)
{
int result;
/*! @note
* Here result == 0 means successful.
* Because this is the behavior of pthread_cond_timedwait.
*/
pthread_mutex_lock(&m_mutex);
if (m_newImageFlag) {
/* At this point, a copy of m_img is made, so it is safe to
* do any modifications to copyOfImage in user code.
*/
copyOfImage = m_img;
m_newImageFlag = false;
result = 0;
} else {
struct timespec absTimeout;
clock_gettime(CLOCK_REALTIME, &absTimeout);
absTimeout.tv_nsec += timeoutMilliSec * 1e6;
result = pthread_cond_timedwait(&m_condv, &m_mutex, &absTimeout);
if (result == 0) {
copyOfImage = m_img;
m_newImageFlag = false;
}
}
pthread_mutex_unlock(&m_mutex);
return (result == 0) ? true : false;
}
void DJICameraImageHandler::writeNewImageWithLock(uint8_t *buf, int bufSize, int width, int height)
{
pthread_mutex_lock(&m_mutex);
m_img.rawData.assign(buf, buf + bufSize);
m_img.height = height;
m_img.width = width;
m_newImageFlag = true;
pthread_cond_signal(&m_condv);
pthread_mutex_unlock(&m_mutex);
}
/* Private functions definition-----------------------------------------------*/
/****************** (C) COPYRIGHT DJI Innovations *****END OF FILE****/

View File

@ -0,0 +1,74 @@
/**
********************************************************************
* @file dji_camera_image_handler.hpp
* @brief This is the header file for "dji_camera_image_handler.cpp", defining the structure and
* (exported) function prototypes.
*
* @copyright (c) 2021 DJI. All rights reserved.
*
* All information contained herein is, and remains, the property of DJI.
* The intellectual and technical concepts contained herein are proprietary
* to DJI and may be covered by U.S. and foreign patents, patents in process,
* and protected by trade secret or copyright law. Dissemination of this
* information, including but not limited to data and other proprietary
* material(s) incorporated within the information, in any form, is strictly
* prohibited without the express written consent of DJI.
*
* If you receive this source code without DJIs authorization, you may not
* further disseminate the information, and you must immediately remove the
* source code and notify DJI of its removal. DJI reserves the right to pursue
* legal actions against you for any loss(es) or damage(s) caused by your
* failure to do so.
*
*********************************************************************
*/
/* Define to prevent recursive inclusion -------------------------------------*/
#ifndef DJI_CAMERA_IMAGE_HANDLER_H
#define DJI_CAMERA_IMAGE_HANDLER_H
/* Includes ------------------------------------------------------------------*/
#include "pthread.h"
#include <cstdint>
#include <vector>
#ifdef __cplusplus
extern "C" {
#endif
/* Exported constants --------------------------------------------------------*/
/* Exported types ------------------------------------------------------------*/
struct CameraRGBImage {
std::vector<uint8_t> rawData;
int height;
int width;
};
typedef void (*CameraImageCallback)(CameraRGBImage pImg, void *userData);
typedef void (*H264Callback)(const uint8_t *buf, int bufLen, void *userData);
class DJICameraImageHandler {
public:
DJICameraImageHandler();
~DJICameraImageHandler();
void writeNewImageWithLock(uint8_t *buf, int bufSize, int width, int height);
bool getNewImageWithLock(CameraRGBImage &copyOfImage, int timeoutMilliSec);
private:
pthread_mutex_t m_mutex;
pthread_cond_t m_condv;
CameraRGBImage m_img;
bool m_newImageFlag;
};
/* Exported functions --------------------------------------------------------*/
#ifdef __cplusplus
}
#endif
#endif // DJI_CAMERA_IMAGE_HANDLER_H
/************************ (C) COPYRIGHT DJI Innovations *******END OF FILE******/

View File

@ -0,0 +1,284 @@
/**
********************************************************************
* @file dji_camera_stream_decoder.cpp
* @brief
*
* @copyright (c) 2021 DJI. All rights reserved.
*
* All information contained herein is, and remains, the property of DJI.
* The intellectual and technical concepts contained herein are proprietary
* to DJI and may be covered by U.S. and foreign patents, patents in process,
* and protected by trade secret or copyright law. Dissemination of this
* information, including but not limited to data and other proprietary
* material(s) incorporated within the information, in any form, is strictly
* prohibited without the express written consent of DJI.
*
* If you receive this source code without DJIs authorization, you may not
* further disseminate the information, and you must immediately remove the
* source code and notify DJI of its removal. DJI reserves the right to pursue
* legal actions against you for any loss(es) or damage(s) caused by your
* failure to do so.
*
*********************************************************************
*/
/* Includes ------------------------------------------------------------------*/
#include "dji_camera_stream_decoder.hpp"
#include "unistd.h"
#include "pthread.h"
#include "dji_logger.h"
/* Private constants ---------------------------------------------------------*/
/* Private types -------------------------------------------------------------*/
/* Private values -------------------------------------------------------------*/
/* Private functions declaration ---------------------------------------------*/
/* Exported functions definition ---------------------------------------------*/
DJICameraStreamDecoder::DJICameraStreamDecoder()
: initSuccess(false),
cbThreadIsRunning(false),
cbThreadStatus(-1),
cb(nullptr),
cbUserParam(nullptr),
#ifdef FFMPEG_INSTALLED
pCodecCtx(nullptr),
pCodec(nullptr),
pCodecParserCtx(nullptr),
pSwsCtx(nullptr),
pFrameYUV(nullptr),
pFrameRGB(nullptr),
rgbBuf(nullptr),
#endif
bufSize(0)
{
pthread_mutex_init(&decodemutex, nullptr);
}
DJICameraStreamDecoder::~DJICameraStreamDecoder()
{
pthread_mutex_destroy(&decodemutex);
if(cb)
{
registerCallback(nullptr, nullptr);
}
cleanup();
}
bool DJICameraStreamDecoder::init()
{
pthread_mutex_lock(&decodemutex);
if (true == initSuccess) {
USER_LOG_INFO("Decoder already initialized.\n");
return true;
}
#ifdef FFMPEG_INSTALLED
avcodec_register_all();
pCodecCtx = avcodec_alloc_context3(nullptr);
if (!pCodecCtx) {
return false;
}
pCodecCtx->thread_count = 4;
pCodec = avcodec_find_decoder(AV_CODEC_ID_H264);
if (!pCodec || avcodec_open2(pCodecCtx, pCodec, nullptr) < 0) {
return false;
}
pCodecParserCtx = av_parser_init(AV_CODEC_ID_H264);
if (!pCodecParserCtx) {
return false;
}
pFrameYUV = av_frame_alloc();
if (!pFrameYUV) {
return false;
}
pFrameRGB = av_frame_alloc();
if (!pFrameRGB) {
return false;
}
pSwsCtx = nullptr;
pCodecCtx->flags2 |= AV_CODEC_FLAG2_SHOW_ALL;
#endif
initSuccess = true;
pthread_mutex_unlock(&decodemutex);
return true;
}
void DJICameraStreamDecoder::cleanup()
{
pthread_mutex_lock(&decodemutex);
initSuccess = false;
#ifdef FFMPEG_INSTALLED
if (nullptr != pSwsCtx) {
sws_freeContext(pSwsCtx);
pSwsCtx = nullptr;
}
if (nullptr != pFrameYUV) {
av_free(pFrameYUV);
pFrameYUV = nullptr;
}
if (nullptr != pCodecParserCtx) {
av_parser_close(pCodecParserCtx);
pCodecParserCtx = nullptr;
}
if (nullptr != pCodec) {
avcodec_close(pCodecCtx);
pCodec = nullptr;
}
if (nullptr != pCodecCtx) {
av_free(pCodecCtx);
pCodecCtx = nullptr;
}
if (nullptr != rgbBuf) {
av_free(rgbBuf);
rgbBuf = nullptr;
}
if (nullptr != pFrameRGB) {
av_free(pFrameRGB);
pFrameRGB = nullptr;
}
#endif
pthread_mutex_unlock(&decodemutex);
}
void *DJICameraStreamDecoder::callbackThreadEntry(void *p)
{
//DSTATUS_PRIVATE("****** Decoder Callback Thread Start ******\n");
usleep(50 * 1000);
static_cast<DJICameraStreamDecoder *>(p)->callbackThreadFunc();
return nullptr;
}
void DJICameraStreamDecoder::callbackThreadFunc()
{
while (cbThreadIsRunning) {
CameraRGBImage copyOfImage;
if (!decodedImageHandler.getNewImageWithLock(copyOfImage, 1000)) {
//DDEBUG_PRIVATE("Decoder Callback Thread: Get image time out\n");
continue;
}
if (cb) {
(*cb)(copyOfImage, cbUserParam);
}
}
}
void DJICameraStreamDecoder::decodeBuffer(const uint8_t *buf, int bufLen)
{
const uint8_t *pData = buf;
int remainingLen = bufLen;
int processedLen = 0;
#ifdef FFMPEG_INSTALLED
AVPacket pkt;
av_init_packet(&pkt);
pthread_mutex_lock(&decodemutex);
while (remainingLen > 0) {
if (!pCodecParserCtx || !pCodecCtx) {
//DSTATUS("Invalid decoder ctx.");
break;
}
processedLen = av_parser_parse2(pCodecParserCtx, pCodecCtx,
&pkt.data, &pkt.size,
pData, remainingLen,
AV_NOPTS_VALUE, AV_NOPTS_VALUE, AV_NOPTS_VALUE);
remainingLen -= processedLen;
pData += processedLen;
if (pkt.size > 0) {
int gotPicture = 0;
avcodec_decode_video2(pCodecCtx, pFrameYUV, &gotPicture, &pkt);
if (!gotPicture) {
////DSTATUS_PRIVATE("Got Frame, but no picture\n");
continue;
} else {
int w = pFrameYUV->width;
int h = pFrameYUV->height;
////DSTATUS_PRIVATE("Got picture! size=%dx%d\n", w, h);
if (nullptr == pSwsCtx) {
pSwsCtx = sws_getContext(w, h, pCodecCtx->pix_fmt,
w, h, AV_PIX_FMT_RGB24,
4, nullptr, nullptr, nullptr);
}
if (nullptr == rgbBuf) {
bufSize = avpicture_get_size(AV_PIX_FMT_RGB24, w, h);
rgbBuf = (uint8_t *) av_malloc(bufSize);
avpicture_fill((AVPicture *) pFrameRGB, rgbBuf, AV_PIX_FMT_RGB24, w, h);
}
if (nullptr != pSwsCtx && nullptr != rgbBuf) {
sws_scale(pSwsCtx,
(uint8_t const *const *) pFrameYUV->data, pFrameYUV->linesize, 0, pFrameYUV->height,
pFrameRGB->data, pFrameRGB->linesize);
pFrameRGB->height = h;
pFrameRGB->width = w;
decodedImageHandler.writeNewImageWithLock(pFrameRGB->data[0], bufSize, w, h);
}
}
}
}
pthread_mutex_unlock(&decodemutex);
av_free_packet(&pkt);
#endif
}
bool DJICameraStreamDecoder::registerCallback(CameraImageCallback f, void *param)
{
cb = f;
cbUserParam = param;
/* When users register a non-nullptr callback, we will start the callback thread. */
if (nullptr != cb) {
if (!cbThreadIsRunning) {
cbThreadStatus = pthread_create(&callbackThread, nullptr, callbackThreadEntry, this);
if (0 == cbThreadStatus) {
//DSTATUS_PRIVATE("User callback thread created successfully!\n");
cbThreadIsRunning = true;
return true;
} else {
//DERROR_PRIVATE("User called thread creation failed!\n");
cbThreadIsRunning = false;
return false;
}
} else {
//DERROR_PRIVATE("Callback thread already running!\n");
return true;
}
} else {
if (cbThreadStatus == 0) {
cbThreadIsRunning = false;
pthread_join(callbackThread, nullptr);
cbThreadStatus = -1;
}
return true;
}
}
/* Private functions definition-----------------------------------------------*/
/****************** (C) COPYRIGHT DJI Innovations *****END OF FILE****/

View File

@ -0,0 +1,101 @@
/**
********************************************************************
* @file dji_camera_stream_decoder.hpp
* @brief This is the header file for "dji_camera_stream_decoder.cpp", defining the structure and
* (exported) function prototypes.
*
* @copyright (c) 2021 DJI. All rights reserved.
*
* All information contained herein is, and remains, the property of DJI.
* The intellectual and technical concepts contained herein are proprietary
* to DJI and may be covered by U.S. and foreign patents, patents in process,
* and protected by trade secret or copyright law. Dissemination of this
* information, including but not limited to data and other proprietary
* material(s) incorporated within the information, in any form, is strictly
* prohibited without the express written consent of DJI.
*
* If you receive this source code without DJIs authorization, you may not
* further disseminate the information, and you must immediately remove the
* source code and notify DJI of its removal. DJI reserves the right to pursue
* legal actions against you for any loss(es) or damage(s) caused by your
* failure to do so.
*
*********************************************************************
*/
/* Define to prevent recursive inclusion -------------------------------------*/
#ifndef DJI_CAMERA_STREAM_DECCODER_H
#define DJI_CAMERA_STREAM_DECCODER_H
/* Includes ------------------------------------------------------------------*/
extern "C" {
#ifdef FFMPEG_INSTALLED
#include <libavcodec/avcodec.h>
#include <libavformat/avformat.h>
#include <libswscale/swscale.h>
#endif
}
#include "pthread.h"
#include "dji_camera_image_handler.hpp"
#ifdef __cplusplus
extern "C" {
#endif
/* Exported constants --------------------------------------------------------*/
/* Exported types ------------------------------------------------------------*/
class DJICameraStreamDecoder {
public:
DJICameraStreamDecoder();
~DJICameraStreamDecoder();
bool init();
void cleanup();
void callbackThreadFunc();
void decodeBuffer(const uint8_t *pBuf, int len);
static void *callbackThreadEntry(void *p);
bool registerCallback(CameraImageCallback f, void *param);
DJICameraImageHandler decodedImageHandler;
private:
pthread_t callbackThread;
bool initSuccess;
bool cbThreadIsRunning;
int cbThreadStatus;
CameraImageCallback cb;
void *cbUserParam;
pthread_mutex_t decodemutex;
#ifdef FFMPEG_INSTALLED
AVCodecContext *pCodecCtx;
AVCodec *pCodec;
AVCodecParserContext *pCodecParserCtx;
SwsContext *pSwsCtx;
AVFrame *pFrameYUV;
AVFrame *pFrameRGB;
#endif
uint8_t *rgbBuf;
size_t bufSize;
};
/* Exported functions --------------------------------------------------------*/
#ifdef __cplusplus
}
#endif
#endif // DJI_CAMERA_STREAM_DECCODER_H
/************************ (C) COPYRIGHT DJI Innovations *******END OF FILE******/

View File

@ -0,0 +1,209 @@
/**
********************************************************************
* @file test_liveview.cpp
* @brief
*
* @copyright (c) 2021 DJI. All rights reserved.
*
* All information contained herein is, and remains, the property of DJI.
* The intellectual and technical concepts contained herein are proprietary
* to DJI and may be covered by U.S. and foreign patents, patents in process,
* and protected by trade secret or copyright law. Dissemination of this
* information, including but not limited to data and other proprietary
* material(s) incorporated within the information, in any form, is strictly
* prohibited without the express written consent of DJI.
*
* If you receive this source code without DJIs authorization, you may not
* further disseminate the information, and you must immediately remove the
* source code and notify DJI of its removal. DJI reserves the right to pursue
* legal actions against you for any loss(es) or damage(s) caused by your
* failure to do so.
*
*********************************************************************
*/
/* Includes ------------------------------------------------------------------*/
#include "test_liveview.hpp"
/* Private constants ---------------------------------------------------------*/
/* Private types -------------------------------------------------------------*/
/* Private values -------------------------------------------------------------*/
std::map<::E_DjiLiveViewCameraPosition, DJICameraStreamDecoder *> streamDecoder;
/* Private functions declaration ---------------------------------------------*/
static void LiveviewConvertH264ToRgbCallback(E_DjiLiveViewCameraPosition position, const uint8_t *buf, uint32_t bufLen);
/* Exported functions definition ---------------------------------------------*/
LiveviewSample::LiveviewSample()
{
T_DjiReturnCode returnCode;
returnCode = DjiLiveview_Init();
if (returnCode != DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS) {
throw ("Liveview init failed");
}
streamDecoder = {
{DJI_LIVEVIEW_CAMERA_POSITION_FPV, (new DJICameraStreamDecoder())},
{DJI_LIVEVIEW_CAMERA_POSITION_NO_1, (new DJICameraStreamDecoder())},
{DJI_LIVEVIEW_CAMERA_POSITION_NO_2, (new DJICameraStreamDecoder())},
{DJI_LIVEVIEW_CAMERA_POSITION_NO_3, (new DJICameraStreamDecoder())},
};
}
LiveviewSample::~LiveviewSample()
{
T_DjiReturnCode returnCode;
returnCode = DjiLiveview_Deinit();
if (returnCode != DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS) {
perror("Liveview deinit failed");
}
for (auto pair : streamDecoder) {
if (pair.second) {
delete pair.second;
}
}
}
T_DjiReturnCode LiveviewSample::StartFpvCameraStream(CameraImageCallback callback, void *userData)
{
auto deocder = streamDecoder.find(DJI_LIVEVIEW_CAMERA_POSITION_FPV);
if ((deocder != streamDecoder.end()) && deocder->second) {
deocder->second->init();
deocder->second->registerCallback(callback, userData);
return DjiLiveview_StartH264Stream(DJI_LIVEVIEW_CAMERA_POSITION_FPV, DJI_LIVEVIEW_CAMERA_SOURCE_DEFAULT,
LiveviewConvertH264ToRgbCallback);
} else {
return DJI_ERROR_SYSTEM_MODULE_CODE_NOT_FOUND;
}
}
T_DjiReturnCode LiveviewSample::StartMainCameraStream(CameraImageCallback callback, void *userData)
{
auto deocder = streamDecoder.find(DJI_LIVEVIEW_CAMERA_POSITION_NO_1);
if ((deocder != streamDecoder.end()) && deocder->second) {
deocder->second->init();
deocder->second->registerCallback(callback, userData);
return DjiLiveview_StartH264Stream(DJI_LIVEVIEW_CAMERA_POSITION_NO_1, DJI_LIVEVIEW_CAMERA_SOURCE_DEFAULT,
LiveviewConvertH264ToRgbCallback);
} else {
return DJI_ERROR_SYSTEM_MODULE_CODE_NOT_FOUND;
}
}
T_DjiReturnCode LiveviewSample::StartViceCameraStream(CameraImageCallback callback, void *userData)
{
auto deocder = streamDecoder.find(DJI_LIVEVIEW_CAMERA_POSITION_NO_2);
if ((deocder != streamDecoder.end()) && deocder->second) {
deocder->second->init();
deocder->second->registerCallback(callback, userData);
return DjiLiveview_StartH264Stream(DJI_LIVEVIEW_CAMERA_POSITION_NO_2, DJI_LIVEVIEW_CAMERA_SOURCE_DEFAULT,
LiveviewConvertH264ToRgbCallback);
} else {
return DJI_ERROR_SYSTEM_MODULE_CODE_NOT_FOUND;
}
}
T_DjiReturnCode LiveviewSample::StartTopCameraStream(CameraImageCallback callback, void *userData)
{
auto deocder = streamDecoder.find(DJI_LIVEVIEW_CAMERA_POSITION_NO_3);
if ((deocder != streamDecoder.end()) && deocder->second) {
deocder->second->init();
deocder->second->registerCallback(callback, userData);
return DjiLiveview_StartH264Stream(DJI_LIVEVIEW_CAMERA_POSITION_NO_3, DJI_LIVEVIEW_CAMERA_SOURCE_DEFAULT,
LiveviewConvertH264ToRgbCallback);
} else {
return DJI_ERROR_SYSTEM_MODULE_CODE_NOT_FOUND;
}
}
T_DjiReturnCode LiveviewSample::StopFpvCameraStream()
{
T_DjiReturnCode returnCode;
returnCode = DjiLiveview_StopH264Stream(DJI_LIVEVIEW_CAMERA_POSITION_FPV, DJI_LIVEVIEW_CAMERA_SOURCE_DEFAULT);
if (returnCode != DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS) {
return returnCode;
}
auto deocder = streamDecoder.find(DJI_LIVEVIEW_CAMERA_POSITION_FPV);
if ((deocder != streamDecoder.end()) && deocder->second) {
deocder->second->cleanup();
}
return DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS;
}
T_DjiReturnCode LiveviewSample::StopMainCameraStream()
{
T_DjiReturnCode returnCode;
returnCode = DjiLiveview_StopH264Stream(DJI_LIVEVIEW_CAMERA_POSITION_NO_1, DJI_LIVEVIEW_CAMERA_SOURCE_DEFAULT);
if (returnCode != DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS) {
return returnCode;
}
auto deocder = streamDecoder.find(DJI_LIVEVIEW_CAMERA_POSITION_NO_1);
if ((deocder != streamDecoder.end()) && deocder->second) {
deocder->second->cleanup();
}
return DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS;
}
T_DjiReturnCode LiveviewSample::StopViceCameraStream()
{
T_DjiReturnCode returnCode;
returnCode = DjiLiveview_StopH264Stream(DJI_LIVEVIEW_CAMERA_POSITION_NO_2, DJI_LIVEVIEW_CAMERA_SOURCE_DEFAULT);
if (returnCode != DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS) {
return returnCode;
}
auto deocder = streamDecoder.find(DJI_LIVEVIEW_CAMERA_POSITION_NO_2);
if ((deocder != streamDecoder.end()) && deocder->second) {
deocder->second->cleanup();
}
return DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS;
}
T_DjiReturnCode LiveviewSample::StopTopCameraStream()
{
T_DjiReturnCode returnCode;
returnCode = DjiLiveview_StopH264Stream(DJI_LIVEVIEW_CAMERA_POSITION_NO_3, DJI_LIVEVIEW_CAMERA_SOURCE_DEFAULT);
if (returnCode != DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS) {
return returnCode;
}
auto deocder = streamDecoder.find(DJI_LIVEVIEW_CAMERA_POSITION_NO_3);
if ((deocder != streamDecoder.end()) && deocder->second) {
deocder->second->cleanup();
}
return DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS;
}
/* Private functions definition-----------------------------------------------*/
static void LiveviewConvertH264ToRgbCallback(E_DjiLiveViewCameraPosition position, const uint8_t *buf, uint32_t bufLen)
{
auto deocder = streamDecoder.find(position);
if ((deocder != streamDecoder.end()) && deocder->second) {
deocder->second->decodeBuffer(buf, bufLen);
}
}
/****************** (C) COPYRIGHT DJI Innovations *****END OF FILE****/

View File

@ -0,0 +1,70 @@
/**
********************************************************************
* @file test_liveview.hpp
* @brief This is the header file for "test_liveview.cpp", defining the structure and
* (exported) function prototypes.
*
* @copyright (c) 2021 DJI. All rights reserved.
*
* All information contained herein is, and remains, the property of DJI.
* The intellectual and technical concepts contained herein are proprietary
* to DJI and may be covered by U.S. and foreign patents, patents in process,
* and protected by trade secret or copyright law. Dissemination of this
* information, including but not limited to data and other proprietary
* material(s) incorporated within the information, in any form, is strictly
* prohibited without the express written consent of DJI.
*
* If you receive this source code without DJIs authorization, you may not
* further disseminate the information, and you must immediately remove the
* source code and notify DJI of its removal. DJI reserves the right to pursue
* legal actions against you for any loss(es) or damage(s) caused by your
* failure to do so.
*
*********************************************************************
*/
/* Define to prevent recursive inclusion -------------------------------------*/
#ifndef TEST_LIVEVIEW_H
#define TEST_LIVEVIEW_H
/* Includes ------------------------------------------------------------------*/
#include "dji_liveview.h"
#include <map>
#include "dji_camera_stream_decoder.hpp"
#ifdef __cplusplus
extern "C" {
#endif
/* Exported constants --------------------------------------------------------*/
/* Exported types ------------------------------------------------------------*/
using namespace std;
class LiveviewSample {
public:
LiveviewSample();
~LiveviewSample();
T_DjiReturnCode StartFpvCameraStream(CameraImageCallback callback, void *userData);
T_DjiReturnCode StopFpvCameraStream();
T_DjiReturnCode StartMainCameraStream(CameraImageCallback callback, void *userData);
T_DjiReturnCode StopMainCameraStream();
T_DjiReturnCode StartViceCameraStream(CameraImageCallback callback, void *userData);
T_DjiReturnCode StopViceCameraStream();
T_DjiReturnCode StartTopCameraStream(CameraImageCallback callback, void *userData);
T_DjiReturnCode StopTopCameraStream();
};
/* Exported functions --------------------------------------------------------*/
#ifdef __cplusplus
}
#endif
#endif // TEST_LIVEVIEW_H
/************************ (C) COPYRIGHT DJI Innovations *******END OF FILE******/

View File

@ -0,0 +1,307 @@
/**
********************************************************************
* @file test_liveview_entry.cpp
* @brief
*
* @copyright (c) 2021 DJI. All rights reserved.
*
* All information contained herein is, and remains, the property of DJI.
* The intellectual and technical concepts contained herein are proprietary
* to DJI and may be covered by U.S. and foreign patents, patents in process,
* and protected by trade secret or copyright law. Dissemination of this
* information, including but not limited to data and other proprietary
* material(s) incorporated within the information, in any form, is strictly
* prohibited without the express written consent of DJI.
*
* If you receive this source code without DJIs authorization, you may not
* further disseminate the information, and you must immediately remove the
* source code and notify DJI of its removal. DJI reserves the right to pursue
* legal actions against you for any loss(es) or damage(s) caused by your
* failure to do so.
*
*********************************************************************
*/
/* Includes ------------------------------------------------------------------*/
#include <iostream>
#include <dji_logger.h>
#include "test_liveview_entry.hpp"
#include "test_liveview.hpp"
#ifdef OPEN_CV_INSTALLED
#include "opencv2/opencv.hpp"
#include "opencv2/dnn.hpp"
#include "opencv2/highgui/highgui.hpp"
#include "../../../sample_c/module_sample/utils/util_misc.h"
using namespace cv;
#endif
using namespace std;
/* Private constants ---------------------------------------------------------*/
/* Private types -------------------------------------------------------------*/
/* Private values -------------------------------------------------------------*/
const char *classNames[] = {"background", "person", "bicycle", "car", "motorcycle", "airplane", "bus", "train", "truck",
"boat", "traffic light",
"fire hydrant", "background", "stop sign", "parking meter", "bench", "bird", "cat", "dog",
"horse", "sheep", "cow", "elephant", "bear", "zebra", "giraffe", "background", "backpack",
"umbrella", "background", "background", "handbag", "tie", "suitcase", "frisbee", "skis",
"snowboard", "sports ball", "kite", "baseball bat", "baseball glove", "skateboard",
"surfboard", "tennis racket",
"bottle", "background", "wine glass", "cup", "fork", "knife", "spoon", "bowl", "banana",
"apple", "sandwich", "orange", "broccoli", "carrot", "hot dog", "pizza", "donut",
"cake", "chair", "couch", "potted plant", "bed", "background", "dining table", "background",
"background", "toilet", "background", "tv", "laptop", "mouse", "remote", "keyboard",
"cell phone", "microwave", "oven", "toaster", "sink", "refrigerator", "background", "book",
"clock", "vase", "scissors", "teddy bear", "hair drier", "toothbrush"};
const size_t inWidth = 320;
const size_t inHeight = 300;
const float WHRatio = inWidth / (float) inHeight;
static int32_t s_demoIndex = -1;
char curFileDirPath[DJI_FILE_PATH_SIZE_MAX];
char tempFileDirPath[DJI_FILE_PATH_SIZE_MAX];
char prototxtFileDirPath[DJI_FILE_PATH_SIZE_MAX];
char weightsFileDirPath[DJI_FILE_PATH_SIZE_MAX];
/* Private functions declaration ---------------------------------------------*/
static void DjiUser_ShowRgbImageCallback(CameraRGBImage img, void *userData);
static T_DjiReturnCode DjiUser_GetCurrentFileDirPath(const char *filePath, uint32_t pathBufferSize, char *dirPath);
/* Exported functions definition ---------------------------------------------*/
void DjiUser_RunCameraStreamViewSample()
{
char cameraIndexChar = 0;
char demoIndexChar = 0;
char isQuit = 0;
CameraRGBImage camImg;
char fpvName[] = "FPV_CAM";
char mainName[] = "MAIN_CAM";
char viceName[] = "VICE_CAM";
char topName[] = "TOP_CAM";
T_DjiReturnCode returnCode;
LiveviewSample *liveviewSample;
try {
liveviewSample = new LiveviewSample();
} catch (...) {
return;
}
returnCode = DjiUser_GetCurrentFileDirPath(__FILE__, DJI_FILE_PATH_SIZE_MAX, curFileDirPath);
if (returnCode != DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS) {
USER_LOG_ERROR("Get file current path error, stat = 0x%08llX", returnCode);
}
cout << "Please choose the stream demo you want to run\n\n"
<< "--> [0] Normal RGB image display\n"
<< "--> [1] Binary image display\n"
<< "--> [2] Faces detection demo\n"
<< "--> [3] Tensorflow Object detection demo\n"
<< endl;
cin >> demoIndexChar;
switch (demoIndexChar) {
case '0':
s_demoIndex = 0;
break;
case '1':
s_demoIndex = 1;
break;
case '2':
s_demoIndex = 2;
break;
case '3':
s_demoIndex = 3;
break;
default:
cout << "No demo selected";
delete liveviewSample;
return;
}
cout << "Please enter the type of camera stream you want to view\n\n"
<< "--> [0] Fpv Camera\n"
<< "--> [1] Main Camera\n"
<< "--> [2] Vice Camera\n"
<< "--> [3] Top Camera\n"
<< endl;
cin >> cameraIndexChar;
switch (cameraIndexChar) {
case '0':
liveviewSample->StartFpvCameraStream(&DjiUser_ShowRgbImageCallback, &fpvName);
break;
case '1':
liveviewSample->StartMainCameraStream(&DjiUser_ShowRgbImageCallback, &mainName);
break;
case '2':
liveviewSample->StartViceCameraStream(&DjiUser_ShowRgbImageCallback, &viceName);
break;
case '3':
liveviewSample->StartTopCameraStream(&DjiUser_ShowRgbImageCallback, &topName);
break;
default:
cout << "No camera selected";
delete liveviewSample;
return;
}
cout << "Please enter the 'q' or 'Q' to quit camera stream view\n"
<< endl;
while (true) {
cin >> isQuit;
if (isQuit == 'q' || isQuit == 'Q') {
break;
}
}
switch (cameraIndexChar) {
case '0':
liveviewSample->StopFpvCameraStream();
break;
case '1':
liveviewSample->StopMainCameraStream();
break;
case '2':
liveviewSample->StopViceCameraStream();
break;
case '3':
liveviewSample->StopTopCameraStream();
break;
default:
cout << "No camera selected";
delete liveviewSample;
return;
}
delete liveviewSample;
}
/* Private functions definition-----------------------------------------------*/
static void DjiUser_ShowRgbImageCallback(CameraRGBImage img, void *userData)
{
string name = string(reinterpret_cast<char *>(userData));
#ifdef OPEN_CV_INSTALLED
Mat mat(img.height, img.width, CV_8UC3, img.rawData.data(), img.width * 3);
if (s_demoIndex == 0) {
cvtColor(mat, mat, COLOR_RGB2BGR);
imshow(name, mat);
} else if (s_demoIndex == 1) {
cvtColor(mat, mat, COLOR_RGB2GRAY);
Mat mask;
cv::threshold(mat, mask, 0, 255, cv::THRESH_BINARY | cv::THRESH_OTSU);
imshow(name, mask);
} else if (s_demoIndex == 2) {
cvtColor(mat, mat, COLOR_RGB2BGR);
snprintf(tempFileDirPath, DJI_FILE_PATH_SIZE_MAX, "%s/data/haarcascade_frontalface_alt.xml", curFileDirPath);
auto faceDetector = cv::CascadeClassifier(tempFileDirPath);
std::vector<Rect> faces;
faceDetector.detectMultiScale(mat, faces, 1.1, 3, 0, Size(50, 50));
for (int i = 0; i < faces.size(); ++i) {
cout << "index: " << i;
cout << " x: " << faces[i].x;
cout << " y: " << faces[i].y << endl;
cv::rectangle(mat, cv::Point(faces[i].x, faces[i].y),
cv::Point(faces[i].x + faces[i].width, faces[i].y + faces[i].height),
Scalar(0, 0, 255), 2, 1, 0);
}
imshow(name, mat);
} else if (s_demoIndex == 3) {
snprintf(prototxtFileDirPath, DJI_FILE_PATH_SIZE_MAX,
"%s/data/tensorflow/ssd_inception_v2_coco_2017_11_17.pbtxt",
curFileDirPath);
//Attention: If you want to run the Tensorflow Object detection demo, Please download the tensorflow model.
//Download Url: http://download.tensorflow.org/models/object_detection/ssd_inception_v2_coco_2017_11_17.tar.gz
snprintf(weightsFileDirPath, DJI_FILE_PATH_SIZE_MAX, "%s/data/tensorflow/frozen_inference_graph.pb",
curFileDirPath);
dnn::Net net = cv::dnn::readNetFromTensorflow(weightsFileDirPath, prototxtFileDirPath);
Size frame_size = mat.size();
Size cropSize;
if (frame_size.width / (float) frame_size.height > WHRatio) {
cropSize = Size(static_cast<int>(frame_size.height * WHRatio),
frame_size.height);
} else {
cropSize = Size(frame_size.width,
static_cast<int>(frame_size.width / WHRatio));
}
Rect crop(Point((frame_size.width - cropSize.width) / 2,
(frame_size.height - cropSize.height) / 2),
cropSize);
cv::Mat blob = cv::dnn::blobFromImage(mat, 1, Size(300, 300));
net.setInput(blob);
Mat output = net.forward();
Mat detectionMat(output.size[2], output.size[3], CV_32F, output.ptr<float>());
mat = mat(crop);
float confidenceThreshold = 0.50;
for (int i = 0; i < detectionMat.rows; i++) {
float confidence = detectionMat.at<float>(i, 2);
if (confidence > confidenceThreshold) {
auto objectClass = (size_t) (detectionMat.at<float>(i, 1));
int xLeftBottom = static_cast<int>(detectionMat.at<float>(i, 3) * mat.cols);
int yLeftBottom = static_cast<int>(detectionMat.at<float>(i, 4) * mat.rows);
int xRightTop = static_cast<int>(detectionMat.at<float>(i, 5) * mat.cols);
int yRightTop = static_cast<int>(detectionMat.at<float>(i, 6) * mat.rows);
ostringstream ss;
ss << confidence;
String conf(ss.str());
Rect object((int) xLeftBottom, (int) yLeftBottom,
(int) (xRightTop - xLeftBottom),
(int) (yRightTop - yLeftBottom));
rectangle(mat, object, Scalar(0, 255, 0), 2);
String label = String(classNames[objectClass]) + ": " + conf;
int baseLine = 0;
Size labelSize = getTextSize(label, FONT_HERSHEY_SIMPLEX, 0.5, 1, &baseLine);
rectangle(mat, Rect(Point(xLeftBottom, yLeftBottom - labelSize.height),
Size(labelSize.width, labelSize.height + baseLine)), Scalar(0, 255, 0), cv::FILLED);
putText(mat, label, Point(xLeftBottom, yLeftBottom), FONT_HERSHEY_SIMPLEX, 0.5, Scalar(0, 0, 0));
}
}
imshow(name, mat);
}
cv::waitKey(1);
#endif
}
static T_DjiReturnCode DjiUser_GetCurrentFileDirPath(const char *filePath, uint32_t pathBufferSize, char *dirPath)
{
uint32_t i = strlen(filePath) - 1;
uint32_t dirPathLen;
while (filePath[i] != '/') {
i--;
}
dirPathLen = i + 1;
if (dirPathLen + 1 > pathBufferSize) {
return DJI_ERROR_SYSTEM_MODULE_CODE_INVALID_PARAMETER;
}
memcpy(dirPath, filePath, dirPathLen);
dirPath[dirPathLen] = 0;
return DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS;
}
/****************** (C) COPYRIGHT DJI Innovations *****END OF FILE****/

View File

@ -0,0 +1,48 @@
/**
********************************************************************
* @file test_liveview_entry.hpp
* @brief This is the header file for "test_liveview_entry.cpp", defining the structure and
* (exported) function prototypes.
*
* @copyright (c) 2021 DJI. All rights reserved.
*
* All information contained herein is, and remains, the property of DJI.
* The intellectual and technical concepts contained herein are proprietary
* to DJI and may be covered by U.S. and foreign patents, patents in process,
* and protected by trade secret or copyright law. Dissemination of this
* information, including but not limited to data and other proprietary
* material(s) incorporated within the information, in any form, is strictly
* prohibited without the express written consent of DJI.
*
* If you receive this source code without DJIs authorization, you may not
* further disseminate the information, and you must immediately remove the
* source code and notify DJI of its removal. DJI reserves the right to pursue
* legal actions against you for any loss(es) or damage(s) caused by your
* failure to do so.
*
*********************************************************************
*/
/* Define to prevent recursive inclusion -------------------------------------*/
#ifndef TEST_LIVEVIEW_ENTRY_H
#define TEST_LIVEVIEW_ENTRY_H
/* Includes ------------------------------------------------------------------*/
#ifdef __cplusplus
extern "C" {
#endif
/* Exported constants --------------------------------------------------------*/
/* Exported types ------------------------------------------------------------*/
/* Exported functions --------------------------------------------------------*/
void DjiUser_RunCameraStreamViewSample();
#ifdef __cplusplus
}
#endif
#endif // TEST_LIVEVIEW_ENTRY_H
/************************ (C) COPYRIGHT DJI Innovations *******END OF FILE******/

View File

@ -0,0 +1,125 @@
/**
********************************************************************
* @file test_perception.cpp
* @brief
*
* @copyright (c) 2021 DJI. All rights reserved.
*
* All information contained herein is, and remains, the property of DJI.
* The intellectual and technical concepts contained herein are proprietary
* to DJI and may be covered by U.S. and foreign patents, patents in process,
* and protected by trade secret or copyright law. Dissemination of this
* information, including but not limited to data and other proprietary
* material(s) incorporated within the information, in any form, is strictly
* prohibited without the express written consent of DJI.
*
* If you receive this source code without DJIs authorization, you may not
* further disseminate the information, and you must immediately remove the
* source code and notify DJI of its removal. DJI reserves the right to pursue
* legal actions against you for any loss(es) or damage(s) caused by your
* failure to do so.
*
*********************************************************************
*/
/* Includes ------------------------------------------------------------------*/
#include <stdexcept>
#include "test_perception.hpp"
#include "dji_logger.h"
/* Private constants ---------------------------------------------------------*/
/* Private types -------------------------------------------------------------*/
/* Private values -------------------------------------------------------------*/
/* Private functions declaration ---------------------------------------------*/
/* Exported functions definition ---------------------------------------------*/
PerceptionSample::PerceptionSample()
{
T_DjiReturnCode returnCode;
returnCode = DjiPerception_Init();
if (returnCode != DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS) {
if (returnCode == DJI_ERROR_SYSTEM_MODULE_CODE_NONSUPPORT) {
USER_LOG_ERROR("Perception feature will support on later version.");
}
throw ("Perception init failed");
}
}
PerceptionSample::~PerceptionSample()
{
T_DjiReturnCode returnCode;
returnCode = DjiPerception_Deinit();
if (returnCode != DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS) {
perror("Perception deinit failed");
}
}
T_DjiReturnCode PerceptionSample::SubscribeFrontImage(DjiPerceptionImageCallback callback)
{
return DjiPerception_SubscribePerceptionImage(DJI_PERCEPTION_RECTIFY_FRONT, callback);
}
T_DjiReturnCode PerceptionSample::SubscribeRearImage(DjiPerceptionImageCallback callback)
{
return DjiPerception_SubscribePerceptionImage(DJI_PERCEPTION_RECTIFY_REAR, callback);
}
T_DjiReturnCode PerceptionSample::SubscribeLeftImage(DjiPerceptionImageCallback callback)
{
return DjiPerception_SubscribePerceptionImage(DJI_PERCEPTION_RECTIFY_LEFT, callback);
}
T_DjiReturnCode PerceptionSample::SubscribeRightImage(DjiPerceptionImageCallback callback)
{
return DjiPerception_SubscribePerceptionImage(DJI_PERCEPTION_RECTIFY_RIGHT, callback);
}
T_DjiReturnCode PerceptionSample::SubscribeUpImage(DjiPerceptionImageCallback callback)
{
return DjiPerception_SubscribePerceptionImage(DJI_PERCEPTION_RECTIFY_UP, callback);
}
T_DjiReturnCode PerceptionSample::SubscribeDownImage(DjiPerceptionImageCallback callback)
{
return DjiPerception_SubscribePerceptionImage(DJI_PERCEPTION_RECTIFY_DOWN, callback);
}
T_DjiReturnCode PerceptionSample::UnSubscribeFrontImage()
{
return DjiPerception_UnsubscribePerceptionImage(DJI_PERCEPTION_RECTIFY_FRONT);
}
T_DjiReturnCode PerceptionSample::UnSubscribeRearImage()
{
return DjiPerception_UnsubscribePerceptionImage(DJI_PERCEPTION_RECTIFY_REAR);
}
T_DjiReturnCode PerceptionSample::UnSubscribeLeftImage()
{
return DjiPerception_UnsubscribePerceptionImage(DJI_PERCEPTION_RECTIFY_LEFT);
}
T_DjiReturnCode PerceptionSample::UnSubscribeRightImage()
{
return DjiPerception_UnsubscribePerceptionImage(DJI_PERCEPTION_RECTIFY_RIGHT);
}
T_DjiReturnCode PerceptionSample::UnSubscribeUpImage()
{
return DjiPerception_UnsubscribePerceptionImage(DJI_PERCEPTION_RECTIFY_UP);
}
T_DjiReturnCode PerceptionSample::UnSubscribeDownImage()
{
return DjiPerception_UnsubscribePerceptionImage(DJI_PERCEPTION_RECTIFY_DOWN);
}
/* Private functions definition-----------------------------------------------*/
/****************** (C) COPYRIGHT DJI Innovations *****END OF FILE****/

View File

@ -0,0 +1,70 @@
/**
********************************************************************
* @file test_perception.hpp
* @brief This is the header file for "test_perception.cpp", defining the structure and
* (exported) function prototypes.
*
* @copyright (c) 2021 DJI. All rights reserved.
*
* All information contained herein is, and remains, the property of DJI.
* The intellectual and technical concepts contained herein are proprietary
* to DJI and may be covered by U.S. and foreign patents, patents in process,
* and protected by trade secret or copyright law. Dissemination of this
* information, including but not limited to data and other proprietary
* material(s) incorporated within the information, in any form, is strictly
* prohibited without the express written consent of DJI.
*
* If you receive this source code without DJIs authorization, you may not
* further disseminate the information, and you must immediately remove the
* source code and notify DJI of its removal. DJI reserves the right to pursue
* legal actions against you for any loss(es) or damage(s) caused by your
* failure to do so.
*
*********************************************************************
*/
/* Define to prevent recursive inclusion -------------------------------------*/
#ifndef TEST_PERCEPTION_H
#define TEST_PERCEPTION_H
/* Includes ------------------------------------------------------------------*/
#include "dji_perception.h"
#ifdef __cplusplus
extern "C" {
#endif
/* Exported constants --------------------------------------------------------*/
/* Exported types ------------------------------------------------------------*/
using namespace std;
class PerceptionSample {
public:
PerceptionSample();
~PerceptionSample();
T_DjiReturnCode SubscribeFrontImage(DjiPerceptionImageCallback callback);
T_DjiReturnCode SubscribeRearImage(DjiPerceptionImageCallback callback);
T_DjiReturnCode SubscribeLeftImage(DjiPerceptionImageCallback callback);
T_DjiReturnCode SubscribeRightImage(DjiPerceptionImageCallback callback);
T_DjiReturnCode SubscribeUpImage(DjiPerceptionImageCallback callback);
T_DjiReturnCode SubscribeDownImage(DjiPerceptionImageCallback callback);
T_DjiReturnCode UnSubscribeFrontImage();
T_DjiReturnCode UnSubscribeRearImage();
T_DjiReturnCode UnSubscribeLeftImage();
T_DjiReturnCode UnSubscribeRightImage();
T_DjiReturnCode UnSubscribeUpImage();
T_DjiReturnCode UnSubscribeDownImage();
private:
};
/* Exported functions --------------------------------------------------------*/
#ifdef __cplusplus
}
#endif
#endif // TEST_PERCEPTION_H
/************************ (C) COPYRIGHT DJI Innovations *******END OF FILE******/

View File

@ -0,0 +1,394 @@
/**
********************************************************************
* @file test_perception_entry.cpp
* @brief
*
* @copyright (c) 2021 DJI. All rights reserved.
*
* All information contained herein is, and remains, the property of DJI.
* The intellectual and technical concepts contained herein are proprietary
* to DJI and may be covered by U.S. and foreign patents, patents in process,
* and protected by trade secret or copyright law. Dissemination of this
* information, including but not limited to data and other proprietary
* material(s) incorporated within the information, in any form, is strictly
* prohibited without the express written consent of DJI.
*
* If you receive this source code without DJIs authorization, you may not
* further disseminate the information, and you must immediately remove the
* source code and notify DJI of its removal. DJI reserves the right to pursue
* legal actions against you for any loss(es) or damage(s) caused by your
* failure to do so.
*
*********************************************************************
*/
/* Includes ------------------------------------------------------------------*/
#include <dirent.h>
#include "test_perception_entry.hpp"
#include "dji_logger.h"
#include "dji_perception.h"
#include "test_perception.hpp"
#include <iostream>
#ifdef OPEN_CV_INSTALLED
#include "opencv2/opencv.hpp"
#include "opencv2/highgui/highgui.hpp"
#endif
/* Private constants ---------------------------------------------------------*/
#define USER_PERCEPTION_TASK_STACK_SIZE (1024)
#define USER_PERCEPTION_DIRECTION_NUM (12)
#define FPS_STRING_LEN (50)
/* Private types -------------------------------------------------------------*/
typedef struct {
T_DjiPerceptionImageInfo info;
uint8_t *imageRawBuffer;
T_DjiMutexHandle mutex;
bool gotData;
} T_DjiTestStereoImagePacket;
typedef struct {
E_DjiPerceptionCameraPosition cameraPosition;
char const *name;
} T_DjiTestPerceptionCameraPositionName;
typedef struct {
E_DjiPerceptionDirection direction;
char const *name;
} T_DjiTestPerceptionDirectionName;
/* Private values -------------------------------------------------------------*/
static T_DjiTaskHandle s_stereoImageThread;
static T_DjiTestStereoImagePacket s_stereoImagePacket = {
.info = {0},
.imageRawBuffer = nullptr,
.mutex = nullptr,
.gotData = false};
static const T_DjiTestPerceptionDirectionName directionName[] = {
{.direction = DJI_PERCEPTION_RECTIFY_DOWN, .name = "down"},
{.direction = DJI_PERCEPTION_RECTIFY_FRONT, .name = "front"},
{.direction = DJI_PERCEPTION_RECTIFY_REAR, .name = "rear"},
{.direction = DJI_PERCEPTION_RECTIFY_UP, .name = "up"},
{.direction = DJI_PERCEPTION_RECTIFY_LEFT, .name = "left"},
{.direction = DJI_PERCEPTION_RECTIFY_RIGHT, .name = "right"},
};
static const T_DjiTestPerceptionCameraPositionName positionName[] = {
{.cameraPosition = RECTIFY_DOWN_LEFT, .name = "down_l"},
{.cameraPosition = RECTIFY_DOWN_RIGHT, .name = "down_r"},
{.cameraPosition = RECTIFY_FRONT_LEFT, .name = "front_l"},
{.cameraPosition = RECTIFY_FRONT_RIGHT, .name = "front_r"},
{.cameraPosition = RECTIFY_REAR_LEFT, .name = "rear_l"},
{.cameraPosition = RECTIFY_REAR_RIGHT, .name = "rear_r"},
{.cameraPosition = RECTIFY_UP_LEFT, .name = "up_l"},
{.cameraPosition = RECTIFY_UP_RIGHT, .name = "up_r"},
{.cameraPosition = RECTIFY_LEFT_LEFT, .name = "left_l"},
{.cameraPosition = RECTIFY_LEFT_RIGHT, .name = "left_r"},
{.cameraPosition = RECTIFY_RIGHT_LEFT, .name = "right_l"},
{.cameraPosition = RECTIFY_RIGHT_RIGHT, .name = "right_r"},
};
/* Private functions declaration ---------------------------------------------*/
static void DjiTest_PerceptionImageCallback(T_DjiPerceptionImageInfo imageInfo, uint8_t *imageRawBuffer,
uint32_t bufferLen);
static void *DjiTest_StereoImagesDisplayTask(void *arg);
/* Exported functions definition ---------------------------------------------*/
void DjiUser_RunStereoVisionViewSample(void)
{
T_DjiOsalHandler *osalHandler = DjiPlatform_GetOsalHandler();
char inputChar;
char isQuit;
T_DjiReturnCode returnCode;
T_DjiPerceptionCameraParametersPacket cameraParametersPacket = {0};
PerceptionSample *perceptionSample;
try {
perceptionSample = new PerceptionSample;
} catch (...) {
return;
}
returnCode = osalHandler->MutexCreate(&s_stereoImagePacket.mutex);
if (returnCode != DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS) {
USER_LOG_ERROR("Crete mutex failed, return code:0x%08X", returnCode);
goto DeletePerception;
}
returnCode = osalHandler->TaskCreate("user_perception_task", DjiTest_StereoImagesDisplayTask,
USER_PERCEPTION_TASK_STACK_SIZE, &s_stereoImagePacket, &s_stereoImageThread);
if (returnCode != DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS) {
USER_LOG_ERROR("Crete task failed, return code:0x%08X", returnCode);
goto DestroyMutex;
}
returnCode = DjiPerception_GetStereoCameraParameters(&cameraParametersPacket);
if (returnCode != DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS) {
USER_LOG_ERROR("Get camera parameters failed, return code:0x%08X", returnCode);
goto DestroyTask;
}
for (int i = 0; i < cameraParametersPacket.directionNum; i++) {
USER_LOG_INFO(" [%-05s] leftIntrinsics = {%f, %f, %f, %f, %f, %f, %f, %f, %f }",
directionName[cameraParametersPacket.cameraParameters[i].direction].name,
cameraParametersPacket.cameraParameters[i].leftIntrinsics[0],
cameraParametersPacket.cameraParameters[i].leftIntrinsics[1],
cameraParametersPacket.cameraParameters[i].leftIntrinsics[2],
cameraParametersPacket.cameraParameters[i].leftIntrinsics[3],
cameraParametersPacket.cameraParameters[i].leftIntrinsics[4],
cameraParametersPacket.cameraParameters[i].leftIntrinsics[5],
cameraParametersPacket.cameraParameters[i].leftIntrinsics[6],
cameraParametersPacket.cameraParameters[i].leftIntrinsics[7],
cameraParametersPacket.cameraParameters[i].leftIntrinsics[8]);
USER_LOG_INFO("[%-05s] rightIntrinsics = {%f, %f, %f, %f, %f, %f, %f, %f, %f }",
directionName[cameraParametersPacket.cameraParameters[i].direction].name,
cameraParametersPacket.cameraParameters[i].rightIntrinsics[0],
cameraParametersPacket.cameraParameters[i].rightIntrinsics[1],
cameraParametersPacket.cameraParameters[i].rightIntrinsics[2],
cameraParametersPacket.cameraParameters[i].rightIntrinsics[3],
cameraParametersPacket.cameraParameters[i].rightIntrinsics[4],
cameraParametersPacket.cameraParameters[i].rightIntrinsics[5],
cameraParametersPacket.cameraParameters[i].rightIntrinsics[6],
cameraParametersPacket.cameraParameters[i].rightIntrinsics[7],
cameraParametersPacket.cameraParameters[i].rightIntrinsics[8]);
USER_LOG_INFO("[%-05s] rotationLeftInRight = {%f, %f, %f, %f, %f, %f, %f, %f, %f }",
directionName[cameraParametersPacket.cameraParameters[i].direction].name,
cameraParametersPacket.cameraParameters[i].rotationLeftInRight[0],
cameraParametersPacket.cameraParameters[i].rotationLeftInRight[1],
cameraParametersPacket.cameraParameters[i].rotationLeftInRight[2],
cameraParametersPacket.cameraParameters[i].rotationLeftInRight[3],
cameraParametersPacket.cameraParameters[i].rotationLeftInRight[4],
cameraParametersPacket.cameraParameters[i].rotationLeftInRight[5],
cameraParametersPacket.cameraParameters[i].rotationLeftInRight[6],
cameraParametersPacket.cameraParameters[i].rotationLeftInRight[7],
cameraParametersPacket.cameraParameters[i].rotationLeftInRight[8]);
USER_LOG_INFO("[%-05s] translationLeftInRight = {%f, %f, %f }\r\n",
directionName[cameraParametersPacket.cameraParameters[i].direction].name,
cameraParametersPacket.cameraParameters[i].translationLeftInRight[0],
cameraParametersPacket.cameraParameters[i].translationLeftInRight[1],
cameraParametersPacket.cameraParameters[i].translationLeftInRight[2]);
osalHandler->TaskSleepMs(100);
}
while (true) {
std::cout
<< "| Available commands: |"
<<
std::endl;
std::cout
<< "| [d] Subscribe down stereo camera pair images |"
<<
std::endl;
std::cout
<< "| [f] Subscribe front stereo camera pair images |"
<<
std::endl;
std::cout
<< "| [r] Subscribe rear stereo camera pair images |"
<<
std::endl;
std::cout
<< "| [u] Subscribe up stereo camera pair images |"
<<
std::endl;
std::cout
<< "| [l] Subscribe left stereo camera pair images |"
<<
std::endl;
std::cout
<< "| [t] Subscribe right stereo camera pair images |"
<<
std::endl;
std::cout
<< "| [q] quit |"
<<
std::endl;
std::cin >> inputChar;
switch (inputChar) {
case 'd':
USER_LOG_INFO("Subscribe down stereo camera pair images.");
perceptionSample->SubscribeDownImage(DjiTest_PerceptionImageCallback);
break;
case 'f':
USER_LOG_INFO("Subscribe front stereo camera pair images.");
perceptionSample->SubscribeFrontImage(DjiTest_PerceptionImageCallback);
break;
case 'r':
USER_LOG_INFO("Subscribe rear stereo camera pair images.");
perceptionSample->SubscribeRearImage(DjiTest_PerceptionImageCallback);
break;
case 'u':
USER_LOG_INFO("Subscribe up stereo camera pair images.");
perceptionSample->SubscribeUpImage(DjiTest_PerceptionImageCallback);
break;
case 'l':
USER_LOG_INFO("Subscribe left stereo camera pair images.");
perceptionSample->SubscribeLeftImage(DjiTest_PerceptionImageCallback);
break;
case 't':
USER_LOG_INFO("Subscribe right stereo camera pair images.");
perceptionSample->SubscribeRightImage(DjiTest_PerceptionImageCallback);
break;
case 'g':
USER_LOG_INFO("Do stereo camera parameters subscription");
break;
case 'q':
goto DestroyTask;
default:
break;
}
while (true) {
cin >> isQuit;
if (isQuit == 'q' || isQuit == 'Q') {
break;
}
}
switch (inputChar) {
case 'd':
USER_LOG_INFO("Unsubscribe down stereo camera pair images.");
perceptionSample->UnSubscribeDownImage();
break;
case 'f':
USER_LOG_INFO("Unsubscribe front stereo camera pair images.");
perceptionSample->UnSubscribeFrontImage();
break;
case 'r':
USER_LOG_INFO("Unsubscribe rear stereo camera pair images.");
perceptionSample->UnSubscribeRearImage();
break;
case 'u':
USER_LOG_INFO("Unsubscribe up stereo camera pair images.");
perceptionSample->UnSubscribeUpImage();
break;
case 'l':
USER_LOG_INFO("Unsubscribe left stereo camera pair images.");
perceptionSample->UnSubscribeLeftImage();
break;
case 't':
USER_LOG_INFO("Unsubscribe right stereo camera pair images.");
perceptionSample->UnSubscribeRightImage();
break;
default:
break;
}
#ifdef OPEN_CV_INSTALLED
cv::destroyAllWindows();
#endif
}
DestroyTask:
returnCode = osalHandler->TaskDestroy(s_stereoImageThread);
if (returnCode != DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS) {
USER_LOG_ERROR("Destroy task failed, return code:0x%08X", returnCode);
}
DestroyMutex:
returnCode = osalHandler->MutexDestroy(s_stereoImagePacket.mutex);
if (returnCode != DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS) {
USER_LOG_ERROR("Destroy mutex failed, return code:0x%08X", returnCode);
}
DeletePerception:
delete perceptionSample;
}
/* Private functions definition-----------------------------------------------*/
static void DjiTest_PerceptionImageCallback(T_DjiPerceptionImageInfo imageInfo, uint8_t *imageRawBuffer,
uint32_t bufferLen)
{
T_DjiOsalHandler *osalHandler = DjiPlatform_GetOsalHandler();
USER_LOG_INFO("image info : dataId(%d) seq(%d) timestamp(%llu) datatype(%d) index(%d) h(%d) w(%d) dir(%d) "
"bpp(%d) bufferlen(%d)", imageInfo.dataId, imageInfo.sequence, imageInfo.timeStamp,
imageInfo.dataType,
imageInfo.rawInfo.index, imageInfo.rawInfo.height, imageInfo.rawInfo.width,
imageInfo.rawInfo.direction,
imageInfo.rawInfo.bpp, bufferLen);
if (imageRawBuffer) {
osalHandler->MutexLock(s_stereoImagePacket.mutex);
s_stereoImagePacket.info = imageInfo;
if (s_stereoImagePacket.imageRawBuffer) osalHandler->Free(s_stereoImagePacket.imageRawBuffer);
s_stereoImagePacket.imageRawBuffer = (uint8_t *) osalHandler->Malloc(bufferLen);
memcpy(s_stereoImagePacket.imageRawBuffer, imageRawBuffer, bufferLen);
s_stereoImagePacket.gotData = true;
osalHandler->MutexUnlock(s_stereoImagePacket.mutex);
}
}
static void *DjiTest_StereoImagesDisplayTask(void *arg)
{
T_DjiOsalHandler *osalHandler = DjiPlatform_GetOsalHandler();
auto *pack = (T_DjiTestStereoImagePacket *) arg;
char nameStr[32] = {0};
char fpsStr[20] = "FPS: ";
int fps = 0;
double timePrev[USER_PERCEPTION_DIRECTION_NUM] = {0};
double timeNow[USER_PERCEPTION_DIRECTION_NUM] = {0};
double timeFess[USER_PERCEPTION_DIRECTION_NUM] = {0};
int count[USER_PERCEPTION_DIRECTION_NUM] = {1};
char showFpsString[USER_PERCEPTION_DIRECTION_NUM][FPS_STRING_LEN] = {0};
int i = 0;
while (true) {
osalHandler->TaskSleepMs(1);
#ifdef OPEN_CV_INSTALLED
/*! Get data here */
osalHandler->MutexLock(pack->mutex);
if (!pack->gotData) {
osalHandler->MutexUnlock(pack->mutex);
continue;
}
cv::Mat cv_img_stereo = cv::Mat(pack->info.rawInfo.height, pack->info.rawInfo.width, CV_8U);
int copySize = pack->info.rawInfo.height * pack->info.rawInfo.width;
if (pack->imageRawBuffer) {
memcpy(cv_img_stereo.data, pack->imageRawBuffer, copySize);
osalHandler->Free(pack->imageRawBuffer);
pack->imageRawBuffer = NULL;
}
for (i = 0; i < sizeof(positionName) / sizeof(T_DjiTestPerceptionCameraPositionName); ++i) {
if (positionName[i].cameraPosition == pack->info.dataType) {
sprintf(nameStr, "Image position: %s", positionName[i].name);
break;
}
}
pack->gotData = false;
osalHandler->MutexUnlock(pack->mutex);
if (i < USER_PERCEPTION_DIRECTION_NUM) {
/*! Calculate frame rate */
timeNow[i] = (double) cv::getTickCount();
if (timePrev[i] != 0) {
timeFess[i] = (timeNow[i] - timePrev[i]) / cv::getTickFrequency() + timeFess[i];
count[i]++;
}
if (timeFess[i] > 1) {
memset(&showFpsString[i][0], 0, FPS_STRING_LEN);
fps = count[i] / timeFess[i];
timeFess[i] = 0;
count[i] = 0;
sprintf(&showFpsString[i][0], "%s%d", fpsStr, fps);
}
timePrev[i] = timeNow[i];
cv::putText(cv_img_stereo, &showFpsString[i][0], cv::Point(5, 20),
cv::FONT_HERSHEY_SIMPLEX, 0.5, cv::Scalar(0, 0, 0));
}
cv::imshow(nameStr, cv_img_stereo);
cv::waitKey(1);
#else
osalHandler->TaskSleepMs(1000);
USER_LOG_WARN("Please install opencv to run this stereo image display sample.");
#endif
}
}
/****************** (C) COPYRIGHT DJI Innovations *****END OF FILE****/

View File

@ -0,0 +1,49 @@
/**
********************************************************************
* @file test_perception_entry.hpp
* @brief This is the header file for "test_perception_entry.cpp", defining the structure and
* (exported) function prototypes.
*
* @copyright (c) 2021 DJI. All rights reserved.
*
* All information contained herein is, and remains, the property of DJI.
* The intellectual and technical concepts contained herein are proprietary
* to DJI and may be covered by U.S. and foreign patents, patents in process,
* and protected by trade secret or copyright law. Dissemination of this
* information, including but not limited to data and other proprietary
* material(s) incorporated within the information, in any form, is strictly
* prohibited without the express written consent of DJI.
*
* If you receive this source code without DJIs authorization, you may not
* further disseminate the information, and you must immediately remove the
* source code and notify DJI of its removal. DJI reserves the right to pursue
* legal actions against you for any loss(es) or damage(s) caused by your
* failure to do so.
*
*********************************************************************
*/
/* Define to prevent recursive inclusion -------------------------------------*/
#ifndef TEST_PERCEPTION_ENTRY_H
#define TEST_PERCEPTION_ENTRY_H
/* Includes ------------------------------------------------------------------*/
#include "dji_perception.h"
#ifdef __cplusplus
extern "C" {
#endif
/* Exported constants --------------------------------------------------------*/
/* Exported types ------------------------------------------------------------*/
/* Exported functions --------------------------------------------------------*/
void DjiUser_RunStereoVisionViewSample(void);
#ifdef __cplusplus
}
#endif
#endif // TEST_PERCEPTION_ENTRY_H
/************************ (C) COPYRIGHT DJI Innovations *******END OF FILE******/

View File

@ -0,0 +1,181 @@
#
# Find the native FFMPEG includes and library
#
# This module defines
# FFMPEG_INCLUDE_DIR, where to find avcodec.h, avformat.h ...
# FFMPEG_LIBRARIES, the libraries to link against to use FFMPEG.
# FFMPEG_FOUND, If false, do not try to use FFMPEG.
# also defined, but not for general use are
# FFMPEG_avformat_LIBRARY and FFMPEG_avcodec_LIBRARY, where to find the FFMPEG library.
# This is useful to do it this way so that we can always add more libraries
# if needed to FFMPEG_LIBRARIES if ffmpeg ever changes...
# if ffmpeg headers are all in one directory
FIND_PATH(FFMPEG_INCLUDE_DIR avformat.h
PATHS
$ENV{FFMPEG_DIR}/include
$ENV{OSGDIR}/include
$ENV{OSG_ROOT}/include
~/Library/Frameworks
/Library/Frameworks
/usr/local/include
/usr/include
/sw/include # Fink
/opt/local/include # DarwinPorts
/opt/csw/include # Blastwave
/opt/include
/usr/freeware/include
PATH_SUFFIXES ffmpeg
DOC "Location of FFMPEG Headers"
)
# if ffmpeg headers are seperated to each of libavformat, libavcodec etc..
IF( NOT FFMPEG_INCLUDE_DIR )
FIND_PATH(FFMPEG_INCLUDE_DIR libavformat/avformat.h
PATHS
$ENV{FFMPEG_DIR}/include
$ENV{OSGDIR}/include
$ENV{OSG_ROOT}/include
~/Library/Frameworks
/Library/Frameworks
/usr/local/include
/usr/include
/sw/include # Fink
/opt/local/include # DarwinPorts
/opt/csw/include # Blastwave
/opt/include
/usr/freeware/include
PATH_SUFFIXES ffmpeg
DOC "Location of FFMPEG Headers"
)
ENDIF( NOT FFMPEG_INCLUDE_DIR )
# we want the -I include line to use the parent directory of ffmpeg as
# ffmpeg uses relative includes such as <ffmpeg/avformat.h> or <libavcodec/avformat.h>
get_filename_component(FFMPEG_INCLUDE_DIR ${FFMPEG_INCLUDE_DIR} ABSOLUTE)
FIND_LIBRARY(FFMPEG_avformat_LIBRARY avformat
/usr/local/lib
/usr/lib
)
FIND_LIBRARY(FFMPEG_avcodec_LIBRARY avcodec
/usr/local/lib
/usr/lib
)
FIND_LIBRARY(FFMPEG_avutil_LIBRARY avutil
/usr/local/lib
/usr/lib
)
FIND_LIBRARY(FFMPEG_vorbis_LIBRARY vorbis
/usr/local/lib
/usr/lib
)
FIND_LIBRARY(FFMPEG_dc1394_LIBRARY dc1394_control
/usr/local/lib
/usr/lib
)
FIND_LIBRARY(FFMPEG_vorbisenc_LIBRARY vorbisenc
/usr/local/lib
/usr/lib
)
FIND_LIBRARY(FFMPEG_theora_LIBRARY theora
/usr/local/lib
/usr/lib
)
FIND_LIBRARY(FFMPEG_dts_LIBRARY dts
/usr/local/lib
/usr/lib
)
FIND_LIBRARY(FFMPEG_gsm_LIBRARY gsm
/usr/local/lib
/usr/lib
)
FIND_LIBRARY(FFMPEG_swscale_LIBRARY swscale
/usr/local/lib
/usr/lib
)
FIND_LIBRARY(FFMPEG_z_LIBRARY z
/usr/local/lib
/usr/lib
)
SET(FFMPEG_LIBRARIES)
IF(FFMPEG_INCLUDE_DIR)
IF(FFMPEG_avformat_LIBRARY)
IF(FFMPEG_avcodec_LIBRARY)
IF(FFMPEG_avutil_LIBRARY)
SET( FFMPEG_FOUND "YES" )
SET( FFMPEG_BASIC_LIBRARIES
${FFMPEG_avcodec_LIBRARY}
${FFMPEG_avformat_LIBRARY}
${FFMPEG_avutil_LIBRARY}
)
# swscale is always a part of newer ffmpeg distros
IF(FFMPEG_swscale_LIBRARY)
LIST(APPEND FFMPEG_BASIC_LIBRARIES ${FFMPEG_swscale_LIBRARY})
ENDIF(FFMPEG_swscale_LIBRARY)
SET(FFMPEG_LIBRARIES ${FFMPEG_BASIC_LIBRARIES})
IF(FFMPEG_vorbis_LIBRARY)
LIST(APPEND FFMPEG_LIBRARIES ${FFMPEG_vorbis_LIBRARY})
ENDIF(FFMPEG_vorbis_LIBRARY)
IF(FFMPEG_dc1394_LIBRARY)
LIST(APPEND FFMPEG_LIBRARIES ${FFMPEG_dc1394_LIBRARY})
ENDIF(FFMPEG_dc1394_LIBRARY)
IF(FFMPEG_vorbisenc_LIBRARY)
LIST(APPEND FFMPEG_LIBRARIES ${FFMPEG_vorbisenc_LIBRARY})
ENDIF(FFMPEG_vorbisenc_LIBRARY)
IF(FFMPEG_theora_LIBRARY)
LIST(APPEND FFMPEG_LIBRARIES ${FFMPEG_theora_LIBRARY})
ENDIF(FFMPEG_theora_LIBRARY)
IF(FFMPEG_dts_LIBRARY)
LIST(APPEND FFMPEG_LIBRARIES ${FFMPEG_dts_LIBRARY})
ENDIF(FFMPEG_dts_LIBRARY)
IF(FFMPEG_gsm_LIBRARY)
LIST(APPEND FFMPEG_LIBRARIES ${FFMPEG_gsm_LIBRARY})
ENDIF(FFMPEG_gsm_LIBRARY)
IF(FFMPEG_z_LIBRARY)
LIST(APPEND FFMPEG_LIBRARIES ${FFMPEG_z_LIBRARY})
ENDIF(FFMPEG_z_LIBRARY)
SET(FFMPEG_LIBRARIES ${FFMPEG_LIBRARIES} CACHE INTERNAL "All presently found FFMPEG libraries.")
ENDIF(FFMPEG_avutil_LIBRARY)
ENDIF(FFMPEG_avcodec_LIBRARY)
ENDIF(FFMPEG_avformat_LIBRARY)
ENDIF(FFMPEG_INCLUDE_DIR)
MARK_AS_ADVANCED(
FFMPEG_INCLUDE_DIR
FFMPEG_avformat_LIBRARY
FFMPEG_avcodec_LIBRARY
FFMPEG_avutil_LIBRARY
FFMPEG_vorbis_LIBRARY
FFMPEG_dc1394_LIBRARY
FFMPEG_vorbisenc_LIBRARY
FFMPEG_theora_LIBRARY
FFMPEG_dts_LIBRARY
FFMPEG_gsm_LIBRARY
FFMPEG_swscale_LIBRARY
FFMPEG_z_LIBRARY
)

View File

@ -0,0 +1,34 @@
#
# Find the native LIBUSB includes and library
#
# This module defines
# LIBUSB_INCLUDE_DIR, where to find libusb.h
# LIBUSB_LIBRARY, the libraries to link against to use LIBUSB.
# LIBUSB_FOUND, If false, do not try to use LIBUSB.
FIND_PATH(LIBUSB_INCLUDE_DIR libusb.h
PATHS
/usr/local/include/libusb-1.0
/usr/include/libusb-1.0
/opt/local/include
/opt/include
)
get_filename_component(LIBUSB_INCLUDE_DIR ${LIBUSB_INCLUDE_DIR} ABSOLUTE)
FIND_LIBRARY(LIBUSB_LIBRARY usb-1.0
/usr/local/lib
/usr/lib
)
IF (LIBUSB_INCLUDE_DIR)
IF (LIBUSB_LIBRARY)
SET(LIBUSB_FOUND "YES")
ENDIF (LIBUSB_LIBRARY)
ENDIF (LIBUSB_INCLUDE_DIR)
MARK_AS_ADVANCED(
LIBUSB_INCLUDE_DIR
LIBUSB_LIBRARY
LIBUSB_FOUND
)

View File

@ -0,0 +1,34 @@
#
# Find the native OPUS includes and library
#
# This module defines
# OPUS_INCLUDE_DIR, where to find opus.h
# OPUS_LIBRARY, the libraries to link against to use OPUS.
# OPUS_FOUND, If false, do not try to use OPUS.
FIND_PATH(OPUS_INCLUDE_DIR opus.h
PATHS
/usr/local/include/opus
/usr/include/opus
/opt/local/include
/opt/include
)
get_filename_component(OPUS_INCLUDE_DIR ${OPUS_INCLUDE_DIR} ABSOLUTE)
FIND_LIBRARY(OPUS_LIBRARY opus
/usr/local/lib
/usr/lib
)
IF (OPUS_INCLUDE_DIR)
IF (OPUS_LIBRARY)
SET(OPUS_FOUND "YES")
ENDIF (OPUS_LIBRARY)
ENDIF (OPUS_INCLUDE_DIR)
MARK_AS_ADVANCED(
OPUS_INCLUDE_DIR
OPUS_LIBRARY
OPUS_FOUND
)

View File

@ -0,0 +1,347 @@
/**
********************************************************************
* @file osal.c
* @brief
*
* @copyright (c) 2021 DJI. All rights reserved.
*
* All information contained herein is, and remains, the property of DJI.
* The intellectual and technical concepts contained herein are proprietary
* to DJI and may be covered by U.S. and foreign patents, patents in process,
* and protected by trade secret or copyright law. Dissemination of this
* information, including but not limited to data and other proprietary
* material(s) incorporated within the information, in any form, is strictly
* prohibited without the express written consent of DJI.
*
* If you receive this source code without DJIs authorization, you may not
* further disseminate the information, and you must immediately remove the
* source code and notify DJI of its removal. DJI reserves the right to pursue
* legal actions against you for any loss(es) or damage(s) caused by your
* failure to do so.
*
*********************************************************************
*/
/* Includes ------------------------------------------------------------------*/
#include "osal.h"
#include "dji_typedef.h"
/* Private constants ---------------------------------------------------------*/
/* Private types -------------------------------------------------------------*/
/* Private values -------------------------------------------------------------*/
static uint32_t s_localTimeMsOffset = 0;
static uint64_t s_localTimeUsOffset = 0;
/* Private functions declaration ---------------------------------------------*/
/* Exported functions definition ---------------------------------------------*/
/* Private functions definition-----------------------------------------------*/
/* Private functions declaration ---------------------------------------------*/
/* Exported functions definition ---------------------------------------------*/
T_DjiReturnCode Osal_TaskCreate(const char *name, void *(*taskFunc)(void *), uint32_t stackSize, void *arg,
T_DjiTaskHandle *task)
{
int result;
char nameDealed[16] = {0};
*task = malloc(sizeof(pthread_t));
if (*task == NULL) {
return DJI_ERROR_SYSTEM_MODULE_CODE_MEMORY_ALLOC_FAILED;
}
result = pthread_create(*task, NULL, taskFunc, arg);
if (result != 0) {
return DJI_ERROR_SYSTEM_MODULE_CODE_SYSTEM_ERROR;
}
if (name != NULL)
strncpy(nameDealed, name, sizeof(nameDealed) - 1);
result = pthread_setname_np(*(pthread_t *) *task, nameDealed);
if (result != 0) {
return DJI_ERROR_SYSTEM_MODULE_CODE_SYSTEM_ERROR;
}
pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL);
return DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS;
}
T_DjiReturnCode Osal_TaskDestroy(T_DjiTaskHandle task)
{
pthread_cancel(*(pthread_t *) task);
free(task);
return DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS;
}
T_DjiReturnCode Osal_TaskSleepMs(uint32_t timeMs)
{
usleep(1000 * timeMs);
return DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS;
}
/**
* @brief Declare the mutex container, initialize the mutex, and
* create mutex ID.
* @param mutex: pointer to the created mutex ID.
* @return an enum that represents a status of PSDK
*/
T_DjiReturnCode Osal_MutexCreate(T_DjiMutexHandle *mutex)
{
int result;
if (!mutex) {
return DJI_ERROR_SYSTEM_MODULE_CODE_INVALID_PARAMETER;
}
*mutex = malloc(sizeof(pthread_mutex_t));
if (*mutex == NULL) {
return DJI_ERROR_SYSTEM_MODULE_CODE_MEMORY_ALLOC_FAILED;
}
result = pthread_mutex_init(*mutex, NULL);
if (result != 0) {
return DJI_ERROR_SYSTEM_MODULE_CODE_SYSTEM_ERROR;
}
return DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS;
}
/**
* @brief Delete the created mutex.
* @param mutex: pointer to the created mutex ID.
* @return an enum that represents a status of PSDK
*/
T_DjiReturnCode Osal_MutexDestroy(T_DjiMutexHandle mutex)
{
int result = 0;
if (!mutex) {
return DJI_ERROR_SYSTEM_MODULE_CODE_INVALID_PARAMETER;
}
result = pthread_mutex_destroy(mutex);
if (result != 0) {
return DJI_ERROR_SYSTEM_MODULE_CODE_SYSTEM_ERROR;
}
free(mutex);
return DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS;
}
/**
* @brief Acquire and lock the mutex when peripheral access is required
* @param mutex: pointer to the created mutex ID.
* @return an enum that represents a status of PSDK
*/
T_DjiReturnCode Osal_MutexLock(T_DjiMutexHandle mutex)
{
int result = 0;
if (!mutex) {
return DJI_ERROR_SYSTEM_MODULE_CODE_INVALID_PARAMETER;
}
result = pthread_mutex_lock(mutex);
if (result != 0) {
return DJI_ERROR_SYSTEM_MODULE_CODE_SYSTEM_ERROR;
}
return DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS;
}
/**
* @brief Unlock and release the mutex, when done with the peripheral access.
* @param mutex: pointer to the created mutex ID.
* @return an enum that represents a status of PSDK
*/
T_DjiReturnCode Osal_MutexUnlock(T_DjiMutexHandle mutex)
{
int result = 0;
if (!mutex) {
return DJI_ERROR_SYSTEM_MODULE_CODE_INVALID_PARAMETER;
}
result = pthread_mutex_unlock(mutex);
if (result != 0) {
return DJI_ERROR_SYSTEM_MODULE_CODE_SYSTEM_ERROR;
}
return DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS;
}
/**
* @brief Declare the semaphore container, initialize the semaphore, and
* create semaphore ID.
* @param semaphore: pointer to the created semaphore ID.
* @param initValue: initial value of semaphore.
* @return an enum that represents a status of PSDK
*/
T_DjiReturnCode Osal_SemaphoreCreate(uint32_t initValue, T_DjiSemaHandle *semaphore)
{
int result;
*semaphore = malloc(sizeof(sem_t));
if (*semaphore == NULL) {
return
DJI_ERROR_SYSTEM_MODULE_CODE_MEMORY_ALLOC_FAILED;
}
result = sem_init(*semaphore, 0, (unsigned int) initValue);
if (result != 0) {
return
DJI_ERROR_SYSTEM_MODULE_CODE_SYSTEM_ERROR;
}
return
DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS;
}
/**
* @brief Delete the created semaphore.
* @param semaphore: pointer to the created semaphore ID.
* @return an enum that represents a status of PSDK
*/
T_DjiReturnCode Osal_SemaphoreDestroy(T_DjiSemaHandle semaphore)
{
int result;
result = sem_destroy((sem_t *) semaphore);
if (result != 0) {
return DJI_ERROR_SYSTEM_MODULE_CODE_SYSTEM_ERROR;
}
free(semaphore);
return DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS;
}
/**
* @brief Wait the semaphore until token becomes available.
* @param semaphore: pointer to the created semaphore ID.
* @return an enum that represents a status of PSDK
*/
T_DjiReturnCode Osal_SemaphoreWait(T_DjiSemaHandle semaphore)
{
int result;
result = sem_wait(semaphore);
if (result != 0) {
return DJI_ERROR_SYSTEM_MODULE_CODE_SYSTEM_ERROR;
}
return DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS;
}
/**
* @brief Wait the semaphore until token becomes available.
* @param semaphore: pointer to the created semaphore ID.
* @param waitTime: timeout value of waiting semaphore, unit: millisecond.
* @return an enum that represents a status of PSDK
*/
T_DjiReturnCode Osal_SemaphoreTimedWait(T_DjiSemaHandle semaphore, uint32_t waitTime)
{
int result;
struct timespec semaphoreWaitTime;
struct timeval systemTime;
gettimeofday(&systemTime, NULL);
systemTime.tv_usec += waitTime * 1000;
if (systemTime.tv_usec >= 1000000) {
systemTime.tv_sec += systemTime.tv_usec / 1000000;
systemTime.tv_usec %= 1000000;
}
semaphoreWaitTime.tv_sec = systemTime.tv_sec;
semaphoreWaitTime.tv_nsec = systemTime.tv_usec * 1000;
result = sem_timedwait(semaphore, &semaphoreWaitTime);
if (result != 0) {
return DJI_ERROR_SYSTEM_MODULE_CODE_SYSTEM_ERROR;
}
return DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS;
}
/**
* @brief Release the semaphore token.
* @param semaphore: pointer to the created semaphore ID.
* @return an enum that represents a status of PSDK
*/
T_DjiReturnCode Osal_SemaphorePost(T_DjiSemaHandle semaphore)
{
int result;
result = sem_post(semaphore);
if (result != 0) {
return DJI_ERROR_SYSTEM_MODULE_CODE_SYSTEM_ERROR;
}
return DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS;
}
/**
* @brief Get the system time for ms.
* @return an uint32 that the time of system, uint:ms
*/
T_DjiReturnCode Osal_GetTimeMs(uint32_t *ms)
{
struct timeval time;
gettimeofday(&time, NULL);
*ms = (time.tv_sec * 1000 + time.tv_usec / 1000);
if (s_localTimeMsOffset == 0) {
s_localTimeMsOffset = *ms;
} else {
*ms = *ms - s_localTimeMsOffset;
}
return DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS;
}
T_DjiReturnCode Osal_GetTimeUs(uint64_t *us)
{
struct timeval time;
gettimeofday(&time, NULL);
*us = (time.tv_sec * 1000000 + time.tv_usec);
if (s_localTimeUsOffset == 0) {
s_localTimeUsOffset = *us;
} else {
*us = *us - s_localTimeMsOffset;
}
return DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS;
}
T_DjiReturnCode Osal_GetRandomNum(uint16_t *randomNum)
{
srand(time(NULL));
*randomNum = random() % 65535;
return DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS;
}
void *Osal_Malloc(uint32_t size)
{
return malloc(size);
}
void Osal_Free(void *ptr)
{
free(ptr);
}
/****************** (C) COPYRIGHT DJI Innovations *****END OF FILE****/

View File

@ -0,0 +1,78 @@
/**
********************************************************************
* @file osal.h
* @version V2.0.0
* @date 2019/8/28
* @brief This is the header file for "osal.c", defining the structure and
* (exported) function prototypes.
*
* @copyright (c) 2021 DJI. All rights reserved.
*
* All information contained herein is, and remains, the property of DJI.
* The intellectual and technical concepts contained herein are proprietary
* to DJI and may be covered by U.S. and foreign patents, patents in process,
* and protected by trade secret or copyright law. Dissemination of this
* information, including but not limited to data and other proprietary
* material(s) incorporated within the information, in any form, is strictly
* prohibited without the express written consent of DJI.
*
* If you receive this source code without DJIs authorization, you may not
* further disseminate the information, and you must immediately remove the
* source code and notify DJI of its removal. DJI reserves the right to pursue
* legal actions against you for any loss(es) or damage(s) caused by your
* failure to do so.
*
*********************************************************************
*/
/* Define to prevent recursive inclusion -------------------------------------*/
#ifndef OSAL_H
#define OSAL_H
/* Includes ------------------------------------------------------------------*/
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <semaphore.h>
#include <sys/time.h>
#include <unistd.h>
#include "dji_platform.h"
#ifdef __cplusplus
extern "C" {
#endif
/* Exported constants --------------------------------------------------------*/
/* Exported types ------------------------------------------------------------*/
/* Exported functions --------------------------------------------------------*/
T_DjiReturnCode Osal_TaskCreate(const char *name, void *(*taskFunc)(void *),
uint32_t stackSize, void *arg, T_DjiTaskHandle *task);
T_DjiReturnCode Osal_TaskDestroy(T_DjiTaskHandle task);
T_DjiReturnCode Osal_TaskSleepMs(uint32_t timeMs);
T_DjiReturnCode Osal_MutexCreate(T_DjiMutexHandle *mutex);
T_DjiReturnCode Osal_MutexDestroy(T_DjiMutexHandle mutex);
T_DjiReturnCode Osal_MutexLock(T_DjiMutexHandle mutex);
T_DjiReturnCode Osal_MutexUnlock(T_DjiMutexHandle mutex);
T_DjiReturnCode Osal_SemaphoreCreate(uint32_t initValue, T_DjiSemaHandle *semaphore);
T_DjiReturnCode Osal_SemaphoreDestroy(T_DjiSemaHandle semaphore);
T_DjiReturnCode Osal_SemaphoreWait(T_DjiSemaHandle semaphore);
T_DjiReturnCode Osal_SemaphoreTimedWait(T_DjiSemaHandle semaphore, uint32_t waitTime);
T_DjiReturnCode Osal_SemaphorePost(T_DjiSemaHandle semaphore);
T_DjiReturnCode Osal_GetTimeMs(uint32_t *ms);
T_DjiReturnCode Osal_GetTimeUs(uint64_t *us);
T_DjiReturnCode Osal_GetRandomNum(uint16_t *randomNum);
void *Osal_Malloc(uint32_t size);
void Osal_Free(void *ptr);
#ifdef __cplusplus
}
#endif
#endif // OSAL_H
/************************ (C) COPYRIGHT DJI Innovations *******END OF FILE******/

View File

@ -0,0 +1,288 @@
/**
********************************************************************
* @file osal_fs.c
* @brief
*
* @copyright (c) 2021 DJI. All rights reserved.
*
* All information contained herein is, and remains, the property of DJI.
* The intellectual and technical concepts contained herein are proprietary
* to DJI and may be covered by U.S. and foreign patents, patents in process,
* and protected by trade secret or copyright law. Dissemination of this
* information, including but not limited to data and other proprietary
* material(s) incorporated within the information, in any form, is strictly
* prohibited without the express written consent of DJI.
*
* If you receive this source code without DJIs authorization, you may not
* further disseminate the information, and you must immediately remove the
* source code and notify DJI of its removal. DJI reserves the right to pursue
* legal actions against you for any loss(es) or damage(s) caused by your
* failure to do so.
*
*********************************************************************
*/
/* Includes ------------------------------------------------------------------*/
#include "osal_fs.h"
#include "stdio.h"
#include "stdlib.h"
#include "unistd.h"
#include <sys/stat.h>
#include <dirent.h>
#include "time.h"
/* Private constants ---------------------------------------------------------*/
/* Private types -------------------------------------------------------------*/
/* Private values -------------------------------------------------------------*/
/* Private functions declaration ---------------------------------------------*/
/* Exported functions definition ---------------------------------------------*/
T_DjiReturnCode Osal_FileOpen(const char *fileName, const char *fileMode, T_DjiFileHandle *fileObj)
{
if (fileName == NULL || fileMode == NULL || fileObj == NULL) {
return DJI_ERROR_SYSTEM_MODULE_CODE_INVALID_PARAMETER;
}
*fileObj = fopen(fileName, fileMode);
if (*fileObj == NULL) {
goto out;
}
return DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS;
out:
free(*fileObj);
return DJI_ERROR_SYSTEM_MODULE_CODE_SYSTEM_ERROR;
}
T_DjiReturnCode Osal_FileClose(T_DjiFileHandle fileObj)
{
int32_t ret;
if (fileObj == NULL) {
return DJI_ERROR_SYSTEM_MODULE_CODE_INVALID_PARAMETER;
}
ret = fclose(fileObj);
if (ret < 0) {
return DJI_ERROR_SYSTEM_MODULE_CODE_SYSTEM_ERROR;
}
return DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS;
}
T_DjiReturnCode Osal_FileWrite(T_DjiFileHandle fileObj, const uint8_t *buf, uint32_t len, uint32_t *realLen)
{
int32_t ret;
if (fileObj == NULL || buf == NULL || len == 0 || realLen == NULL) {
return DJI_ERROR_SYSTEM_MODULE_CODE_INVALID_PARAMETER;
}
ret = fwrite(buf, 1, len, fileObj);
if (ret >= 0) {
*realLen = ret;
} else {
return DJI_ERROR_SYSTEM_MODULE_CODE_SYSTEM_ERROR;
}
return DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS;
}
T_DjiReturnCode Osal_FileRead(T_DjiFileHandle fileObj, uint8_t *buf, uint32_t len, uint32_t *realLen)
{
int32_t ret;
if (fileObj == NULL || buf == NULL || len == 0 || realLen == NULL) {
return DJI_ERROR_SYSTEM_MODULE_CODE_INVALID_PARAMETER;
}
ret = fread(buf, 1, len, fileObj);
if (ret >= 0) {
*realLen = ret;
} else {
return DJI_ERROR_SYSTEM_MODULE_CODE_SYSTEM_ERROR;
}
return DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS;
}
T_DjiReturnCode Osal_FileSeek(T_DjiFileHandle fileObj, uint32_t offset)
{
int32_t ret;
if (fileObj == NULL) {
return DJI_ERROR_SYSTEM_MODULE_CODE_INVALID_PARAMETER;
}
ret = fseek(fileObj, offset, SEEK_SET);
if (ret < 0) {
return DJI_ERROR_SYSTEM_MODULE_CODE_SYSTEM_ERROR;
}
return DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS;
}
T_DjiReturnCode Osal_FileSync(T_DjiFileHandle fileObj)
{
int32_t ret;
if (fileObj == NULL) {
return DJI_ERROR_SYSTEM_MODULE_CODE_INVALID_PARAMETER;
}
ret = fflush(fileObj);
if (ret < 0) {
return DJI_ERROR_SYSTEM_MODULE_CODE_SYSTEM_ERROR;
}
return DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS;
}
T_DjiReturnCode Osal_DirOpen(const char *filePath, T_DjiDirHandle *dirObj)
{
if (filePath == NULL) {
return DJI_ERROR_SYSTEM_MODULE_CODE_INVALID_PARAMETER;
}
*dirObj = opendir(filePath);
if (*dirObj == NULL) {
return DJI_ERROR_SYSTEM_MODULE_CODE_SYSTEM_ERROR;
}
return DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS;
}
T_DjiReturnCode Osal_DirClose(T_DjiDirHandle dirObj)
{
int32_t ret;
if (dirObj == NULL) {
return DJI_ERROR_SYSTEM_MODULE_CODE_INVALID_PARAMETER;
}
ret = closedir((DIR *) dirObj);
if (ret < 0) {
return DJI_ERROR_SYSTEM_MODULE_CODE_SYSTEM_ERROR;
}
return DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS;
}
T_DjiReturnCode Osal_DirRead(T_DjiDirHandle dirObj, T_DjiFileInfo *fileInfo)
{
struct dirent *dirent;
if (dirObj == NULL || fileInfo == NULL) {
return DJI_ERROR_SYSTEM_MODULE_CODE_INVALID_PARAMETER;
}
dirent = readdir((DIR *) dirObj);
if (!dirent) {
return DJI_ERROR_SYSTEM_MODULE_CODE_SYSTEM_ERROR;
}
if (dirent->d_type == DT_DIR) {
fileInfo->isDir = true;
} else {
fileInfo->isDir = false;
}
strcpy(fileInfo->path, dirent->d_name);
return DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS;
}
T_DjiReturnCode Osal_Mkdir(const char *filePath)
{
int32_t ret;
if (filePath == NULL) {
return DJI_ERROR_SYSTEM_MODULE_CODE_INVALID_PARAMETER;
}
ret = mkdir(filePath, S_IRWXU);
if (ret < 0) {
return DJI_ERROR_SYSTEM_MODULE_CODE_SYSTEM_ERROR;
}
return DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS;
}
T_DjiReturnCode Osal_Unlink(const char *filePath)
{
int32_t ret;
if (filePath == NULL) {
return DJI_ERROR_SYSTEM_MODULE_CODE_INVALID_PARAMETER;
}
if (filePath[strlen(filePath) - 1] == '/') {
ret = rmdir(filePath);
if (ret < 0) {
return DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS;
}
} else {
ret = unlink(filePath);
if (ret < 0) {
return DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS;
}
}
return DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS;
}
T_DjiReturnCode Osal_Rename(const char *oldFilePath, const char *newFilePath)
{
int32_t ret;
if (oldFilePath == NULL || newFilePath == NULL) {
return DJI_ERROR_SYSTEM_MODULE_CODE_INVALID_PARAMETER;
}
ret = rename(oldFilePath, newFilePath);
if (ret < 0) {
return DJI_ERROR_SYSTEM_MODULE_CODE_SYSTEM_ERROR;
}
return DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS;
}
T_DjiReturnCode Osal_Stat(const char *filePath, T_DjiFileInfo *fileInfo)
{
struct stat st;
int32_t ret;
struct tm *fileTm;
if (filePath == NULL || fileInfo == NULL) {
return DJI_ERROR_SYSTEM_MODULE_CODE_INVALID_PARAMETER;
}
ret = stat(filePath, &st);
if (ret < 0) {
return DJI_ERROR_SYSTEM_MODULE_CODE_SYSTEM_ERROR;
}
fileTm = localtime(&(st.st_ctime));
if (fileTm == NULL) {
return DJI_ERROR_SYSTEM_MODULE_CODE_SYSTEM_ERROR;
}
fileInfo->size = st.st_size;
fileInfo->createTime.year = fileTm->tm_year + 1900 - 1980;
fileInfo->createTime.month = fileTm->tm_mon;
fileInfo->createTime.day = fileTm->tm_mday;
fileInfo->createTime.hour = fileTm->tm_hour;
fileInfo->createTime.minute = fileTm->tm_min;
fileInfo->createTime.second = fileTm->tm_sec;
return DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS;
}
/* Private functions definition-----------------------------------------------*/
/****************** (C) COPYRIGHT DJI Innovations *****END OF FILE****/

View File

@ -0,0 +1,73 @@
/**
********************************************************************
* @file osal_fs.h
* @brief This is the header file for "osal_fs.c", defining the structure and
* (exported) function prototypes.
*
* @copyright (c) 2021 DJI. All rights reserved.
*
* All information contained herein is, and remains, the property of DJI.
* The intellectual and technical concepts contained herein are proprietary
* to DJI and may be covered by U.S. and foreign patents, patents in process,
* and protected by trade secret or copyright law. Dissemination of this
* information, including but not limited to data and other proprietary
* material(s) incorporated within the information, in any form, is strictly
* prohibited without the express written consent of DJI.
*
* If you receive this source code without DJIs authorization, you may not
* further disseminate the information, and you must immediately remove the
* source code and notify DJI of its removal. DJI reserves the right to pursue
* legal actions against you for any loss(es) or damage(s) caused by your
* failure to do so.
*
*********************************************************************
*/
/* Define to prevent recursive inclusion -------------------------------------*/
#ifndef OSAL_FS_H
#define OSAL_FS_H
/* Includes ------------------------------------------------------------------*/
#include "dji_platform.h"
#ifdef __cplusplus
extern "C" {
#endif
/* Exported constants --------------------------------------------------------*/
/* Exported types ------------------------------------------------------------*/
/* Exported functions --------------------------------------------------------*/
T_DjiReturnCode Osal_FileOpen(const char *fileName, const char *fileMode, T_DjiFileHandle *fileObj);
T_DjiReturnCode Osal_FileClose(T_DjiFileHandle fileObj);
T_DjiReturnCode Osal_FileWrite(T_DjiFileHandle fileObj, const uint8_t *buf, uint32_t len, uint32_t *realLen);
T_DjiReturnCode Osal_FileRead(T_DjiFileHandle fileObj, uint8_t *buf, uint32_t len, uint32_t *realLen);
T_DjiReturnCode Osal_FileSeek(T_DjiFileHandle fileObj, uint32_t offset);
T_DjiReturnCode Osal_FileSync(T_DjiFileHandle fileObj);
T_DjiReturnCode Osal_DirOpen(const char *filePath, T_DjiDirHandle *dirObj);
T_DjiReturnCode Osal_DirClose(T_DjiDirHandle dirObj);
T_DjiReturnCode Osal_DirRead(T_DjiDirHandle dirObj, T_DjiFileInfo *fileInfo);
T_DjiReturnCode Osal_Mkdir(const char *filePath);
T_DjiReturnCode Osal_Unlink(const char *filePath);
T_DjiReturnCode Osal_Rename(const char *oldFilePath, const char *newFilePath);
T_DjiReturnCode Osal_Stat(const char *filePath, T_DjiFileInfo *fileInfo);
#ifdef __cplusplus
}
#endif
#endif // OSAL_FS_H
/************************ (C) COPYRIGHT DJI Innovations *******END OF FILE******/

View File

@ -0,0 +1,299 @@
/**
********************************************************************
* @file osal_socket.c
* @brief
*
* @copyright (c) 2021 DJI. All rights reserved.
*
* All information contained herein is, and remains, the property of DJI.
* The intellectual and technical concepts contained herein are proprietary
* to DJI and may be covered by U.S. and foreign patents, patents in process,
* and protected by trade secret or copyright law. Dissemination of this
* information, including but not limited to data and other proprietary
* material(s) incorporated within the information, in any form, is strictly
* prohibited without the express written consent of DJI.
*
* If you receive this source code without DJIs authorization, you may not
* further disseminate the information, and you must immediately remove the
* source code and notify DJI of its removal. DJI reserves the right to pursue
* legal actions against you for any loss(es) or damage(s) caused by your
* failure to do so.
*
*********************************************************************
*/
/* Includes ------------------------------------------------------------------*/
#include "osal_socket.h"
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include "stdlib.h"
/* Private constants ---------------------------------------------------------*/
#define SOCKET_RECV_BUF_MAX_SIZE (1000 * 1000 * 10)
/* Private types -------------------------------------------------------------*/
typedef struct {
int socketFd;
} T_SocketHandleStruct;
/* Private values -------------------------------------------------------------*/
/* Private functions declaration ---------------------------------------------*/
/* Exported functions definition ---------------------------------------------*/
T_DjiReturnCode Osal_Socket(E_DjiSocketMode mode, T_DjiSocketHandle *socketHandle)
{
T_SocketHandleStruct *socketHandleStruct;
socklen_t optlen = sizeof(int);
int rcvBufSize = SOCKET_RECV_BUF_MAX_SIZE;
int opt = 1;
/*! set the socket default read buffer to 20MByte */
system("echo 20000000 > /proc/sys/net/core/rmem_default");
/*! set the socket max read buffer to 50MByte */
system("echo 50000000 > /proc/sys/net/core/rmem_max");
if (socketHandle == NULL) {
return DJI_ERROR_SYSTEM_MODULE_CODE_INVALID_PARAMETER;
}
socketHandleStruct = malloc(sizeof(T_SocketHandleStruct));
if (socketHandleStruct == NULL) {
return DJI_ERROR_SYSTEM_MODULE_CODE_MEMORY_ALLOC_FAILED;
}
if (mode == DJI_SOCKET_MODE_UDP) {
socketHandleStruct->socketFd = socket(PF_INET, SOCK_DGRAM, 0);
if (setsockopt(socketHandleStruct->socketFd, SOL_SOCKET, SO_REUSEADDR, &opt, optlen) < 0) {
goto out;
}
if (setsockopt(socketHandleStruct->socketFd, SOL_SOCKET, SO_RCVBUF, &rcvBufSize, optlen) < 0)
{
goto out;
}
} else if (mode == DJI_SOCKET_MODE_TCP) {
socketHandleStruct->socketFd = socket(PF_INET, SOCK_STREAM, 0);
} else {
goto out;
}
*socketHandle = socketHandleStruct;
return DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS;
out:
close(socketHandleStruct->socketFd);
free(socketHandleStruct);
return DJI_ERROR_SYSTEM_MODULE_CODE_SYSTEM_ERROR;
}
T_DjiReturnCode Osal_Close(T_DjiSocketHandle socketHandle)
{
T_SocketHandleStruct *socketHandleStruct = (T_SocketHandleStruct *) socketHandle;
int32_t ret;
if (socketHandleStruct->socketFd <= 0) {
return DJI_ERROR_SYSTEM_MODULE_CODE_INVALID_PARAMETER;
}
ret = close(socketHandleStruct->socketFd);
if (ret < 0) {
return DJI_ERROR_SYSTEM_MODULE_CODE_SYSTEM_ERROR;
}
free(socketHandle);
return DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS;
}
T_DjiReturnCode Osal_Bind(T_DjiSocketHandle socketHandle, const char *ipAddr, uint32_t port)
{
T_SocketHandleStruct *socketHandleStruct = (T_SocketHandleStruct *) socketHandle;
struct sockaddr_in addr;
int32_t ret;
if (socketHandle == NULL || ipAddr == NULL || port == 0) {
return DJI_ERROR_SYSTEM_MODULE_CODE_INVALID_PARAMETER;
}
bzero(&addr, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_port = htons(port);
addr.sin_addr.s_addr = inet_addr(ipAddr);
ret = bind(socketHandleStruct->socketFd, (struct sockaddr *) &addr, sizeof(struct sockaddr_in));
if (ret < 0) {
return DJI_ERROR_SYSTEM_MODULE_CODE_SYSTEM_ERROR;
}
return DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS;
}
T_DjiReturnCode Osal_UdpSendData(T_DjiSocketHandle socketHandle, const char *ipAddr, uint32_t port,
const uint8_t *buf, uint32_t len, uint32_t *realLen)
{
struct sockaddr_in addr;
T_SocketHandleStruct *socketHandleStruct = (T_SocketHandleStruct *) socketHandle;
int32_t ret;
if (socketHandle <= 0 || ipAddr == NULL || port == 0 || buf == NULL || len == 0 || realLen == NULL) {
return DJI_ERROR_SYSTEM_MODULE_CODE_INVALID_PARAMETER;
}
bzero(&addr, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_port = htons(port);
addr.sin_addr.s_addr = inet_addr(ipAddr);
ret = sendto(socketHandleStruct->socketFd, buf, len, 0, (struct sockaddr *) &addr, sizeof(struct sockaddr_in));
if (ret >= 0) {
*realLen = ret;
} else {
return DJI_ERROR_SYSTEM_MODULE_CODE_SYSTEM_ERROR;
}
return DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS;
}
T_DjiReturnCode Osal_UdpRecvData(T_DjiSocketHandle socketHandle, char *ipAddr, uint32_t *port,
uint8_t *buf, uint32_t len, uint32_t *realLen)
{
struct sockaddr_in addr;
T_SocketHandleStruct *socketHandleStruct = (T_SocketHandleStruct *) socketHandle;
uint32_t addrLen = 0;
int32_t ret;
if (socketHandle == NULL || ipAddr == NULL || port == 0 || buf == NULL || len == 0 || realLen == NULL) {
return DJI_ERROR_SYSTEM_MODULE_CODE_INVALID_PARAMETER;
}
ret = recvfrom(socketHandleStruct->socketFd, buf, len, 0, (struct sockaddr *) &addr, &addrLen);
if (ret >= 0) {
*realLen = ret;
strcpy(ipAddr, inet_ntoa(addr.sin_addr));
*port = ntohs(addr.sin_port);
} else {
return DJI_ERROR_SYSTEM_MODULE_CODE_SYSTEM_ERROR;
}
return DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS;
}
T_DjiReturnCode Osal_TcpListen(T_DjiSocketHandle socketHandle)
{
int32_t ret;
T_SocketHandleStruct *socketHandleStruct = (T_SocketHandleStruct *) socketHandle;
if (socketHandle == NULL) {
return DJI_ERROR_SYSTEM_MODULE_CODE_INVALID_PARAMETER;
}
ret = listen(socketHandleStruct->socketFd, 5);
if (ret < 0) {
return DJI_ERROR_SYSTEM_MODULE_CODE_SYSTEM_ERROR;
}
return DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS;
}
T_DjiReturnCode Osal_TcpAccept(T_DjiSocketHandle socketHandle, char *ipAddr, uint32_t *port,
T_DjiSocketHandle *outSocketHandle)
{
T_SocketHandleStruct *socketHandleStruct = (T_SocketHandleStruct *) socketHandle;
T_SocketHandleStruct *outSocketHandleStruct;
struct sockaddr_in addr;
uint32_t addrLen = 0;
if (socketHandle == NULL || ipAddr == NULL) {
return DJI_ERROR_SYSTEM_MODULE_CODE_INVALID_PARAMETER;
}
outSocketHandleStruct = malloc(sizeof(T_SocketHandleStruct));
if (outSocketHandleStruct == NULL) {
return DJI_ERROR_SYSTEM_MODULE_CODE_MEMORY_ALLOC_FAILED;
}
outSocketHandleStruct->socketFd = accept(socketHandleStruct->socketFd, (struct sockaddr *) &addr, &addrLen);
if (outSocketHandleStruct->socketFd < 0) {
free(outSocketHandleStruct);
return DJI_ERROR_SYSTEM_MODULE_CODE_SYSTEM_ERROR;
}
*port = ntohs(addr.sin_port);
*outSocketHandle = outSocketHandleStruct;
return DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS;
}
T_DjiReturnCode Osal_TcpConnect(T_DjiSocketHandle socketHandle, const char *ipAddr, uint32_t port)
{
struct sockaddr_in addr;
T_SocketHandleStruct *socketHandleStruct = (T_SocketHandleStruct *) socketHandle;
int32_t ret;
if (socketHandle == NULL || ipAddr == NULL || port == 0) {
return DJI_ERROR_SYSTEM_MODULE_CODE_INVALID_PARAMETER;
}
bzero(&addr, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_port = htons(port);
addr.sin_addr.s_addr = inet_addr(ipAddr);
ret = connect(socketHandleStruct->socketFd, (struct sockaddr *) &addr, sizeof(struct sockaddr_in));
if (ret < 0) {
return DJI_ERROR_SYSTEM_MODULE_CODE_SYSTEM_ERROR;
}
return DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS;
}
T_DjiReturnCode Osal_TcpSendData(T_DjiSocketHandle socketHandle,
const uint8_t *buf, uint32_t len, uint32_t *realLen)
{
T_SocketHandleStruct *socketHandleStruct = (T_SocketHandleStruct *) socketHandle;
int32_t ret;
if (socketHandle == NULL || buf == NULL || len == 0 || realLen == NULL) {
return DJI_ERROR_SYSTEM_MODULE_CODE_INVALID_PARAMETER;
}
ret = send(socketHandleStruct->socketFd, buf, len, 0);
if (ret >= 0) {
*realLen = ret;
} else {
return DJI_ERROR_SYSTEM_MODULE_CODE_SYSTEM_ERROR;
}
return DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS;
}
T_DjiReturnCode Osal_TcpRecvData(T_DjiSocketHandle socketHandle,
uint8_t *buf, uint32_t len, uint32_t *realLen)
{
T_SocketHandleStruct *socketHandleStruct = (T_SocketHandleStruct *) socketHandle;
int32_t ret;
if (socketHandle == NULL || buf == NULL || len == 0 || realLen == NULL) {
return DJI_ERROR_SYSTEM_MODULE_CODE_INVALID_PARAMETER;
}
ret = recv(socketHandleStruct->socketFd, buf, len, 0);
if (ret >= 0) {
*realLen = ret;
} else {
return DJI_ERROR_SYSTEM_MODULE_CODE_SYSTEM_ERROR;
}
return DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS;
}
/* Private functions definition-----------------------------------------------*/
/****************** (C) COPYRIGHT DJI Innovations *****END OF FILE****/

View File

@ -0,0 +1,72 @@
/**
********************************************************************
* @file osal_socket.h
* @brief This is the header file for "osal_socket.c", defining the structure and
* (exported) function prototypes.
*
* @copyright (c) 2021 DJI. All rights reserved.
*
* All information contained herein is, and remains, the property of DJI.
* The intellectual and technical concepts contained herein are proprietary
* to DJI and may be covered by U.S. and foreign patents, patents in process,
* and protected by trade secret or copyright law. Dissemination of this
* information, including but not limited to data and other proprietary
* material(s) incorporated within the information, in any form, is strictly
* prohibited without the express written consent of DJI.
*
* If you receive this source code without DJIs authorization, you may not
* further disseminate the information, and you must immediately remove the
* source code and notify DJI of its removal. DJI reserves the right to pursue
* legal actions against you for any loss(es) or damage(s) caused by your
* failure to do so.
*
*********************************************************************
*/
/* Define to prevent recursive inclusion -------------------------------------*/
#ifndef OSAL_SOCKET_H
#define OSAL_SOCKET_H
/* Includes ------------------------------------------------------------------*/
#include "dji_platform.h"
#ifdef __cplusplus
extern "C" {
#endif
/* Exported constants --------------------------------------------------------*/
/* Exported types ------------------------------------------------------------*/
/* Exported functions --------------------------------------------------------*/
T_DjiReturnCode Osal_Socket(E_DjiSocketMode mode, T_DjiSocketHandle *socketHandle);
T_DjiReturnCode Osal_Close(T_DjiSocketHandle socketHandle);
T_DjiReturnCode Osal_Bind(T_DjiSocketHandle socketHandle, const char *ipAddr, uint32_t port);
T_DjiReturnCode Osal_UdpSendData(T_DjiSocketHandle socketHandle, const char *ipAddr, uint32_t port,
const uint8_t *buf, uint32_t len, uint32_t *realLen);
T_DjiReturnCode Osal_UdpRecvData(T_DjiSocketHandle socketHandle, char *ipAddr, uint32_t *port,
uint8_t *buf, uint32_t len, uint32_t *realLen);
T_DjiReturnCode Osal_TcpListen(T_DjiSocketHandle socketHandle);
T_DjiReturnCode Osal_TcpAccept(T_DjiSocketHandle socketHandle, char *ipAddr, uint32_t *port,
T_DjiSocketHandle *outSocketHandle);
T_DjiReturnCode Osal_TcpConnect(T_DjiSocketHandle socketHandle, const char *ipAddr, uint32_t port);
T_DjiReturnCode Osal_TcpSendData(T_DjiSocketHandle socketHandle,
const uint8_t *buf, uint32_t len, uint32_t *realLen);
T_DjiReturnCode Osal_TcpRecvData(T_DjiSocketHandle socketHandle,
uint8_t *buf, uint32_t len, uint32_t *realLen);
#ifdef __cplusplus
}
#endif
#endif // OSAL_SOCKET_H
/************************ (C) COPYRIGHT DJI Innovations *******END OF FILE******/

View File

@ -0,0 +1,143 @@
cmake_minimum_required(VERSION 3.5)
project(dji_sdk_demo_linux_cxx CXX)
set(CMAKE_C_FLAGS "-pthread -std=gnu99")
set(CMAKE_CXX_FLAGS "-std=c++11 -pthread")
set(CMAKE_EXE_LINKER_FLAGS "-pthread")
set(CMAKE_C_COMPILER "gcc")
set(CMAKE_CXX_COMPILER "g++")
add_definitions(-D_GNU_SOURCE)
if (MEMORY_LEAK_CHECK_ON MATCHES TRUE)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fsanitize=leak")
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -fsanitize=leak")
set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -lasan")
endif ()
if (BUILD_TEST_CASES_ON MATCHES TRUE)
set(COMMON_CXX_FLAGS "-std=c++11 -pthread")
set(CMAKE_CXX_FLAGS "${CMAKE_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")
endif ()
include_directories(../../../module_sample)
include_directories(../../../../sample_c/module_sample)
include_directories(../common)
include_directories(../manifold2/application)
file(GLOB_RECURSE MODULE_SAMPLE_SRC
../../../module_sample/liveview/*.c*
../../../module_sample/camera_manager/*.c*
../../../module_sample/perception/*.c*
../../../module_sample/gimbal/*.c*
../../../module_sample/flight_controller/*.c*
../../../module_sample/hms_manager/*.c*
../../../../sample_c/module_sample/*.c
)
file(GLOB_RECURSE MODULE_COMMON_SRC ../common/*.c*)
file(GLOB_RECURSE MODULE_HAL_SRC hal/*.c*)
file(GLOB_RECURSE MODULE_APP_SRC application/*.c*)
execute_process(COMMAND uname -m
OUTPUT_VARIABLE DEVICE_SYSTEM_ID)
if (DEVICE_SYSTEM_ID MATCHES x86_64)
set(TOOLCHAIN_NAME x86_64-linux-gnu-gcc)
add_definitions(-DPLATFORM_ARCH_x86_64=1)
elseif (DEVICE_SYSTEM_ID MATCHES aarch64)
set(TOOLCHAIN_NAME aarch64-linux-gnu-gcc)
add_definitions(-DPLATFORM_ARCH_aarch64=1)
else ()
message(FATAL_ERROR "FATAL: Please confirm your platform.")
endif ()
set(CMAKE_MODULE_PATH ${CMAKE_CURRENT_SOURCE_DIR}/../common/3rdparty)
link_directories(${CMAKE_CURRENT_LIST_DIR}/../../../../../psdk_lib/lib/${TOOLCHAIN_NAME})
link_libraries(${CMAKE_CURRENT_LIST_DIR}/../../../../../psdk_lib/lib/${TOOLCHAIN_NAME}/libpayloadsdk.a -lstdc++)
add_executable(${PROJECT_NAME}
${MODULE_APP_SRC}
${MODULE_SAMPLE_SRC}
${MODULE_COMMON_SRC}
${MODULE_HAL_SRC})
# Try to see if user has OpenCV installed
# if yes, default callback will display the image
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)
else ()
message(STATUS "Did not find OpenCV in the system, image data is inside RecvContainer as raw data")
endif ()
find_package(FFMPEG REQUIRED)
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 ()
target_link_libraries(${PROJECT_NAME} ${FFMPEG_LIBRARIES})
include_directories(${FFMPEG_INCLUDE_DIR})
add_definitions(-DFFMPEG_INSTALLED)
else ()
message(STATUS "Cannot Find FFMPEG")
endif (FFMPEG_FOUND)
include_directories(${CMAKE_CURRENT_LIST_DIR}/../../../../../psdk_lib/include)
find_package(OPUS REQUIRED)
if (OPUS_FOUND)
message(STATUS "Found OPUS installed in the system")
message(STATUS " - Includes: ${OPUS_INCLUDE_DIR}")
message(STATUS " - Libraries: ${OPUS_LIBRARY}")
add_definitions(-DOPUS_INSTALLED)
target_link_libraries(${PROJECT_NAME} /usr/local/lib/libopus.a)
else ()
message(STATUS "Cannot Find OPUS")
endif (OPUS_FOUND)
find_package(LIBUSB REQUIRED)
if (LIBUSB_FOUND)
message(STATUS "Found LIBUSB installed in the system")
message(STATUS " - Includes: ${LIBUSB_INCLUDE_DIR}")
message(STATUS " - Libraries: ${LIBUSB_LIBRARY}")
add_definitions(-DLIBUSB_INSTALLED)
target_link_libraries(${PROJECT_NAME} usb-1.0)
else ()
message(STATUS "Cannot Find LIBUSB")
endif (LIBUSB_FOUND)
if (NOT EXECUTABLE_OUTPUT_PATH)
set(EXECUTABLE_OUTPUT_PATH ${CMAKE_BINARY_DIR}/bin)
endif ()
target_link_libraries(${PROJECT_NAME} m)
add_custom_command(TARGET ${PROJECT_NAME}
PRE_LINK COMMAND cmake ..
WORKING_DIRECTORY ${CMAKE_BINARY_DIR})
target_include_directories(${PROJECT_NAME} PRIVATE ${OpenCV_INCLUDE_DIRS})
if (OpenCV_FOUND)
target_link_libraries(${PROJECT_NAME} ${OpenCV_LIBS})
endif ()

View File

@ -0,0 +1,535 @@
/**
********************************************************************
* @file application.cpp
* @brief
*
* @copyright (c) 2021 DJI. All rights reserved.
*
* All information contained herein is, and remains, the property of DJI.
* The intellectual and technical concepts contained herein are proprietary
* to DJI and may be covered by U.S. and foreign patents, patents in process,
* and protected by trade secret or copyright law. Dissemination of this
* information, including but not limited to data and other proprietary
* material(s) incorporated within the information, in any form, is strictly
* prohibited without the express written consent of DJI.
*
* If you receive this source code without DJIs authorization, you may not
* further disseminate the information, and you must immediately remove the
* source code and notify DJI of its removal. DJI reserves the right to pursue
* legal actions against you for any loss(es) or damage(s) caused by your
* failure to do so.
*
*********************************************************************
*/
/* Includes ------------------------------------------------------------------*/
#include "application.hpp"
#include "dji_sdk_app_info.h"
#include <dji_platform.h>
#include <dji_logger.h>
#include <dji_core.h>
#include <dji_aircraft_info.h>
#include <csignal>
#include "dji_sdk_config.h"
#include "../common/osal/osal.h"
#include "../common/osal/osal_fs.h"
#include "../common/osal/osal_socket.h"
#include "../manifold2/hal/hal_usb_bulk.h"
#include "../manifold2/hal/hal_uart.h"
#include "../manifold2/hal/hal_network.h"
#include "utils/dji_config_manager.h"
#include <gimbal_emu/test_payload_gimbal_emu.h>
#include <camera_emu/test_payload_cam_emu_media.h>
#include <camera_emu/test_payload_cam_emu_base.h>
#include "widget/test_widget.h"
#include "widget/test_widget_speaker.h"
#include <power_management/test_power_management.h>
#include "data_transmission/test_data_transmission.h"
/* Private constants ---------------------------------------------------------*/
#define DJI_LOG_PATH "Logs/DJI"
#define DJI_LOG_INDEX_FILE_NAME "Logs/index"
#define DJI_LOG_FOLDER_NAME "Logs"
#define DJI_LOG_PATH_MAX_SIZE (128)
#define DJI_LOG_FOLDER_NAME_MAX_SIZE (32)
#define DJI_SYSTEM_CMD_STR_MAX_SIZE (64)
#define DJI_LOG_MAX_COUNT (10)
#define USER_UTIL_UNUSED(x) ((x) = (x))
#define USER_UTIL_MIN(a, b) (((a) < (b)) ? (a) : (b))
#define USER_UTIL_MAX(a, b) (((a) > (b)) ? (a) : (b))
#define DJI_USE_SDK_CONFIG_BY_JSON (0)
/* Private types -------------------------------------------------------------*/
/* Private values -------------------------------------------------------------*/
static FILE *s_djiLogFile;
static FILE *s_djiLogFileCnt;
/* Private functions declaration ---------------------------------------------*/
static void DjiUser_NormalExitHandler(int signalNum);
static T_DjiReturnCode DjiTest_HighPowerApplyPinInit();
static T_DjiReturnCode DjiTest_WriteHighPowerApplyPin(E_DjiPowerManagementPinState pinState);
/* Exported functions definition ---------------------------------------------*/
Application::Application(int argc, char **argv)
{
Application::DjiUser_SetupEnvironment(argc, argv);
Application::DjiUser_ApplicationStart();
Osal_TaskSleepMs(3000);
}
Application::~Application()
= default;
/* Private functions definition-----------------------------------------------*/
void Application::DjiUser_SetupEnvironment(int argc, char **argv)
{
T_DjiReturnCode returnCode;
T_DjiOsalHandler osalHandler = {0};
T_DjiHalUartHandler uartHandler = {0};
T_DjiHalUsbBulkHandler usbBulkHandler = {0};
T_DjiLoggerConsole printConsole;
T_DjiLoggerConsole localRecordConsole;
T_DjiFileSystemHandler fileSystemHandler = {0};
T_DjiSocketHandler socketHandler{0};
T_DjiHalNetworkHandler networkHandler = {0};
T_DjiUserLinkConfig linkConfig;
networkHandler.NetworkInit = HalNetWork_Init;
networkHandler.NetworkDeInit = HalNetWork_DeInit;
networkHandler.NetworkGetDeviceInfo = HalNetWork_GetDeviceInfo;
socketHandler.Socket = Osal_Socket;
socketHandler.Bind = Osal_Bind;
socketHandler.Close = Osal_Close;
socketHandler.UdpSendData = Osal_UdpSendData;
socketHandler.UdpRecvData = Osal_UdpRecvData;
socketHandler.TcpListen = Osal_TcpListen;
socketHandler.TcpAccept = Osal_TcpAccept;
socketHandler.TcpConnect = Osal_TcpConnect;
socketHandler.TcpSendData = Osal_TcpSendData;
socketHandler.TcpRecvData = Osal_TcpRecvData;
osalHandler.TaskCreate = Osal_TaskCreate;
osalHandler.TaskDestroy = Osal_TaskDestroy;
osalHandler.TaskSleepMs = Osal_TaskSleepMs;
osalHandler.MutexCreate = Osal_MutexCreate;
osalHandler.MutexDestroy = Osal_MutexDestroy;
osalHandler.MutexLock = Osal_MutexLock;
osalHandler.MutexUnlock = Osal_MutexUnlock;
osalHandler.SemaphoreCreate = Osal_SemaphoreCreate;
osalHandler.SemaphoreDestroy = Osal_SemaphoreDestroy;
osalHandler.SemaphoreWait = Osal_SemaphoreWait;
osalHandler.SemaphoreTimedWait = Osal_SemaphoreTimedWait;
osalHandler.SemaphorePost = Osal_SemaphorePost;
osalHandler.Malloc = Osal_Malloc;
osalHandler.Free = Osal_Free;
osalHandler.GetTimeMs = Osal_GetTimeMs;
osalHandler.GetTimeUs = Osal_GetTimeUs;
osalHandler.GetRandomNum = Osal_GetRandomNum;
printConsole.func = DjiUser_PrintConsole;
printConsole.consoleLevel = DJI_LOGGER_CONSOLE_LOG_LEVEL_INFO;
printConsole.isSupportColor = true;
localRecordConsole.consoleLevel = DJI_LOGGER_CONSOLE_LOG_LEVEL_DEBUG;
localRecordConsole.func = DjiUser_LocalWrite;
localRecordConsole.isSupportColor = false;
uartHandler.UartInit = HalUart_Init;
uartHandler.UartDeInit = HalUart_DeInit;
uartHandler.UartWriteData = HalUart_WriteData;
uartHandler.UartReadData = HalUart_ReadData;
uartHandler.UartGetStatus = HalUart_GetStatus;
usbBulkHandler.UsbBulkInit = HalUsbBulk_Init;
usbBulkHandler.UsbBulkDeInit = HalUsbBulk_DeInit;
usbBulkHandler.UsbBulkWriteData = HalUsbBulk_WriteData;
usbBulkHandler.UsbBulkReadData = HalUsbBulk_ReadData;
usbBulkHandler.UsbBulkGetDeviceInfo = HalUsbBulk_GetDeviceInfo;
fileSystemHandler.FileOpen = Osal_FileOpen,
fileSystemHandler.FileClose = Osal_FileClose,
fileSystemHandler.FileWrite = Osal_FileWrite,
fileSystemHandler.FileRead = Osal_FileRead,
fileSystemHandler.FileSync = Osal_FileSync,
fileSystemHandler.FileSeek = Osal_FileSeek,
fileSystemHandler.DirOpen = Osal_DirOpen,
fileSystemHandler.DirClose = Osal_DirClose,
fileSystemHandler.DirRead = Osal_DirRead,
fileSystemHandler.Mkdir = Osal_Mkdir,
fileSystemHandler.Unlink = Osal_Unlink,
fileSystemHandler.Rename = Osal_Rename,
fileSystemHandler.Stat = Osal_Stat,
returnCode = DjiPlatform_RegOsalHandler(&osalHandler);
if (returnCode != DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS) {
throw std::runtime_error("Register osal handler error.");
}
returnCode = DjiPlatform_RegHalUartHandler(&uartHandler);
if (returnCode != DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS) {
throw std::runtime_error("Register hal uart handler error.");
}
#if DJI_USE_SDK_CONFIG_BY_JSON
if (argc > 1) {
DjiUserConfigManager_LoadConfiguration(argv[1]);
} else {
DjiUserConfigManager_LoadConfiguration(nullptr);
}
DjiUserConfigManager_GetLinkConfig(&linkConfig);
if (linkConfig.type == DJI_USER_LINK_CONFIG_USE_UART_AND_NETWORK_DEVICE) {
returnCode = DjiPlatform_RegHalNetworkHandler(&networkHandler);
if (returnCode != DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS) {
throw std::runtime_error("Register hal network handler error");
}
} else if (linkConfig.type == DJI_USER_LINK_CONFIG_USE_UART_AND_USB_BULK_DEVICE) {
returnCode = DjiPlatform_RegHalUsbBulkHandler(&usbBulkHandler);
if (returnCode != DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS) {
throw std::runtime_error("Register hal usb bulk handler error.");
}
} else {
/*!< Attention: Only use uart hardware connection. */
}
#else
#if (CONFIG_HARDWARE_CONNECTION == DJI_USE_UART_AND_USB_BULK_DEVICE)
returnCode = DjiPlatform_RegHalUsbBulkHandler(&usbBulkHandler);
if (returnCode != DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS) {
throw std::runtime_error("Register hal usb bulk handler error.");
}
#elif (CONFIG_HARDWARE_CONNECTION == DJI_USE_UART_AND_NETWORK_DEVICE)
returnCode = DjiPlatform_RegHalNetworkHandler(&networkHandler);
if (returnCode != DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS) {
throw std::runtime_error("Register hal network handler error");
}
#elif (CONFIG_HARDWARE_CONNECTION == DJI_USE_ONLY_UART)
/*!< Attention: Only use uart hardware connection.
*/
#endif
#endif
//Attention: if you want to use camera stream view function, please uncomment it.
returnCode = DjiPlatform_RegSocketHandler(&socketHandler);
if (returnCode != DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS) {
throw std::runtime_error("register osal socket handler error");
}
returnCode = DjiPlatform_RegFileSystemHandler(&fileSystemHandler);
if (returnCode != DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS) {
throw std::runtime_error("Register osal filesystem handler error.");
}
if (DjiUser_LocalWriteFsInit(DJI_LOG_PATH) != DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS) {
throw std::runtime_error("File system init error.");
}
returnCode = DjiLogger_AddConsole(&printConsole);
if (returnCode != DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS) {
throw std::runtime_error("Add printf console error.");
}
returnCode = DjiLogger_AddConsole(&localRecordConsole);
if (returnCode != DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS) {
throw std::runtime_error("Add printf console error.");
}
}
void Application::DjiUser_ApplicationStart()
{
T_DjiUserInfo userInfo;
T_DjiReturnCode returnCode;
T_DjiAircraftInfoBaseInfo aircraftInfoBaseInfo;
T_DjiFirmwareVersion firmwareVersion = {
.majorVersion = 1,
.minorVersion = 0,
.modifyVersion = 0,
.debugVersion = 0,
};
// attention: when the program is hand up ctrl-c will generate the coredump file
signal(SIGTERM, DjiUser_NormalExitHandler);
#if DJI_USE_SDK_CONFIG_BY_JSON
DjiUserConfigManager_GetAppInfo(&userInfo);
#else
returnCode = DjiUser_FillInUserInfo(&userInfo);
if (returnCode != DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS) {
throw std::runtime_error("Fill user info error, please check user info config.");
}
#endif
returnCode = DjiCore_Init(&userInfo);
if (returnCode != DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS) {
sleep(1);
throw std::runtime_error("Core init error.");
}
returnCode = DjiAircraftInfo_GetBaseInfo(&aircraftInfoBaseInfo);
if (returnCode != DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS) {
throw std::runtime_error("Get aircraft base info error.");
}
if (aircraftInfoBaseInfo.mountPosition != DJI_MOUNT_POSITION_EXTENSION_PORT
&& DJI_MOUNT_POSITION_EXTENSION_LITE_PORT != aircraftInfoBaseInfo.mountPosition) {
throw std::runtime_error("Please run this sample on extension port.");
}
returnCode = DjiCore_SetAlias("PSDK_APPALIAS");
if (returnCode != DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS) {
throw std::runtime_error("Set alias error.");
}
returnCode = DjiCore_SetFirmwareVersion(firmwareVersion);
if (returnCode != DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS) {
throw std::runtime_error("Set firmware version error.");
}
returnCode = DjiCore_SetSerialNumber("PSDK12345678XX");
if (returnCode != DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS) {
throw std::runtime_error("Set serial number error");
}
#ifdef CONFIG_MODULE_SAMPLE_CAMERA_EMU_ON
returnCode = DjiTest_CameraEmuBaseStartService();
if (returnCode != DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS) {
USER_LOG_ERROR("camera emu common init error");
}
#endif
#ifdef CONFIG_MODULE_SAMPLE_CAMERA_MEDIA_ON
returnCode = DjiTest_CameraEmuMediaStartService();
if (returnCode != DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS) {
USER_LOG_ERROR("camera emu media init error");
}
#endif
#ifdef CONFIG_MODULE_SAMPLE_GIMBAL_EMU_ON
returnCode = DjiTest_GimbalStartService();
if (returnCode != DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS) {
USER_LOG_ERROR("psdk gimbal init error");
}
#endif
#ifdef CONFIG_MODULE_SAMPLE_WIDGET_ON
returnCode = DjiTest_WidgetStartService();
if (returnCode != DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS) {
USER_LOG_ERROR("widget sample init error");
}
#endif
#ifdef CONFIG_MODULE_SAMPLE_WIDGET_SPEAKER_ON
returnCode = DjiTest_WidgetSpeakerStartService();
if (returnCode != DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS) {
USER_LOG_ERROR("widget speaker test init error");
}
#endif
#ifdef CONFIG_MODULE_SAMPLE_POWER_MANAGEMENT_ON
T_DjiTestApplyHighPowerHandler applyHighPowerHandler = {
.pinInit = DjiTest_HighPowerApplyPinInit,
.pinWrite = DjiTest_WriteHighPowerApplyPin,
};
returnCode = DjiTest_RegApplyHighPowerHandler(&applyHighPowerHandler);
if (returnCode != DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS) {
USER_LOG_ERROR("regsiter apply high power handler error");
}
returnCode = DjiTest_PowerManagementStartService();
if (returnCode != DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS) {
USER_LOG_ERROR("power management init error");
}
#endif
#ifdef CONFIG_MODULE_SAMPLE_DATA_TRANSMISSION_ON
returnCode = DjiTest_DataTransmissionStartService();
if (returnCode != DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS) {
USER_LOG_ERROR("widget sample init error");
}
#endif
returnCode = DjiCore_ApplicationStart();
if (returnCode != DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS) {
throw std::runtime_error("Start sdk application error.");
}
USER_LOG_INFO("Application start.");
}
T_DjiReturnCode Application::DjiUser_PrintConsole(const uint8_t *data, uint16_t dataLen)
{
printf("%s", data);
return DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS;
}
T_DjiReturnCode Application::DjiUser_LocalWrite(const uint8_t *data, uint16_t dataLen)
{
int32_t realLen;
if (s_djiLogFile == nullptr) {
return DJI_ERROR_SYSTEM_MODULE_CODE_UNKNOWN;
}
realLen = fwrite(data, 1, dataLen, s_djiLogFile);
fflush(s_djiLogFile);
if (realLen == dataLen) {
return DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS;
} else {
return DJI_ERROR_SYSTEM_MODULE_CODE_UNKNOWN;
}
}
T_DjiReturnCode Application::DjiUser_FillInUserInfo(T_DjiUserInfo *userInfo)
{
memset(userInfo->appName, 0, sizeof(userInfo->appName));
memset(userInfo->appId, 0, sizeof(userInfo->appId));
memset(userInfo->appKey, 0, sizeof(userInfo->appKey));
memset(userInfo->appLicense, 0, sizeof(userInfo->appLicense));
memset(userInfo->developerAccount, 0, sizeof(userInfo->developerAccount));
memset(userInfo->baudRate, 0, sizeof(userInfo->baudRate));
if (strlen(USER_APP_NAME) >= sizeof(userInfo->appName) ||
strlen(USER_APP_ID) > sizeof(userInfo->appId) ||
strlen(USER_APP_KEY) > sizeof(userInfo->appKey) ||
strlen(USER_APP_LICENSE) > sizeof(userInfo->appLicense) ||
strlen(USER_DEVELOPER_ACCOUNT) >= sizeof(userInfo->developerAccount) ||
strlen(USER_BAUD_RATE) > sizeof(userInfo->baudRate)) {
USER_LOG_ERROR("Length of user information string is beyond limit. Please check.");
return DJI_ERROR_SYSTEM_MODULE_CODE_INVALID_PARAMETER;
}
if (!strcmp(USER_APP_NAME, "your_app_name") ||
!strcmp(USER_APP_ID, "your_app_id") ||
!strcmp(USER_APP_KEY, "your_app_key") ||
!strcmp(USER_BAUD_RATE, "your_app_license") ||
!strcmp(USER_DEVELOPER_ACCOUNT, "your_developer_account") ||
!strcmp(USER_BAUD_RATE, "your_baud_rate")) {
USER_LOG_ERROR(
"Please fill in correct user information to 'samples/sample_c++/platform/linux/manifold2/application/dji_sdk_app_info.h' file.");
return DJI_ERROR_SYSTEM_MODULE_CODE_INVALID_PARAMETER;
}
strncpy(userInfo->appName, USER_APP_NAME, sizeof(userInfo->appName) - 1);
memcpy(userInfo->appId, USER_APP_ID, USER_UTIL_MIN(sizeof(userInfo->appId), strlen(USER_APP_ID)));
memcpy(userInfo->appKey, USER_APP_KEY, USER_UTIL_MIN(sizeof(userInfo->appKey), strlen(USER_APP_KEY)));
memcpy(userInfo->appLicense, USER_APP_LICENSE,
USER_UTIL_MIN(sizeof(userInfo->appLicense), strlen(USER_APP_LICENSE)));
memcpy(userInfo->baudRate, USER_BAUD_RATE, USER_UTIL_MIN(sizeof(userInfo->baudRate), strlen(USER_BAUD_RATE)));
strncpy(userInfo->developerAccount, USER_DEVELOPER_ACCOUNT, sizeof(userInfo->developerAccount) - 1);
return DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS;
}
T_DjiReturnCode Application::DjiUser_LocalWriteFsInit(const char *path)
{
T_DjiReturnCode djiReturnCode = DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS;
char filePath[DJI_LOG_PATH_MAX_SIZE];
char systemCmd[DJI_SYSTEM_CMD_STR_MAX_SIZE];
char folderName[DJI_LOG_FOLDER_NAME_MAX_SIZE];
time_t currentTime = time(nullptr);
struct tm *localTime = localtime(&currentTime);
uint16_t logFileIndex = 0;
uint16_t currentLogFileIndex;
uint8_t ret;
if (localTime == nullptr) {
printf("Get local time error.\r\n");
return DJI_ERROR_SYSTEM_MODULE_CODE_SYSTEM_ERROR;
}
if (access(DJI_LOG_FOLDER_NAME, F_OK) != 0) {
sprintf(folderName, "mkdir %s", DJI_LOG_FOLDER_NAME);
ret = system(folderName);
if (ret != 0) {
printf("Create new log folder error, ret:%d.\r\n", ret);
return DJI_ERROR_SYSTEM_MODULE_CODE_SYSTEM_ERROR;
}
}
s_djiLogFileCnt = fopen(DJI_LOG_INDEX_FILE_NAME, "rb+");
if (s_djiLogFileCnt == nullptr) {
s_djiLogFileCnt = fopen(DJI_LOG_INDEX_FILE_NAME, "wb+");
if (s_djiLogFileCnt == nullptr) {
return DJI_ERROR_SYSTEM_MODULE_CODE_SYSTEM_ERROR;
}
} else {
ret = fseek(s_djiLogFileCnt, 0, SEEK_SET);
if (ret != 0) {
printf("Seek log count file error, ret: %d, errno: %d.\r\n", ret, errno);
return DJI_ERROR_SYSTEM_MODULE_CODE_SYSTEM_ERROR;
}
ret = fread((uint16_t *) &logFileIndex, 1, sizeof(uint16_t), s_djiLogFileCnt);
if (ret != sizeof(uint16_t)) {
printf("Read log file index error.\r\n");
}
}
currentLogFileIndex = logFileIndex;
logFileIndex++;
ret = fseek(s_djiLogFileCnt, 0, SEEK_SET);
if (ret != 0) {
printf("Seek log file error, ret: %d, errno: %d.\r\n", ret, errno);
return DJI_ERROR_SYSTEM_MODULE_CODE_SYSTEM_ERROR;
}
ret = fwrite((uint16_t *) &logFileIndex, 1, sizeof(uint16_t), s_djiLogFileCnt);
if (ret != sizeof(uint16_t)) {
printf("Write log file index error.\r\n");
fclose(s_djiLogFileCnt);
return DJI_ERROR_SYSTEM_MODULE_CODE_SYSTEM_ERROR;
}
fclose(s_djiLogFileCnt);
sprintf(filePath, "%s_%04d_%04d%02d%02d_%02d-%02d-%02d.log", path, currentLogFileIndex,
localTime->tm_year + 1900, localTime->tm_mon + 1, localTime->tm_mday,
localTime->tm_hour, localTime->tm_min, localTime->tm_sec);
s_djiLogFile = fopen(filePath, "wb+");
if (s_djiLogFile == nullptr) {
USER_LOG_ERROR("Open filepath time error.");
return DJI_ERROR_SYSTEM_MODULE_CODE_SYSTEM_ERROR;
}
if (logFileIndex >= DJI_LOG_MAX_COUNT) {
sprintf(systemCmd, "rm -rf %s_%04d*.log", path, currentLogFileIndex - DJI_LOG_MAX_COUNT);
ret = system(systemCmd);
if (ret != 0) {
printf("Remove file error, ret:%d.\r\n", ret);
return DJI_ERROR_SYSTEM_MODULE_CODE_SYSTEM_ERROR;
}
}
sprintf(systemCmd, "ln -sfrv %s " DJI_LOG_FOLDER_NAME "/latest.log", filePath);
system(systemCmd);
return djiReturnCode;
}
static void DjiUser_NormalExitHandler(int signalNum)
{
USER_UTIL_UNUSED(signalNum);
exit(0);
}
static T_DjiReturnCode DjiTest_HighPowerApplyPinInit()
{
return DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS;
}
static T_DjiReturnCode DjiTest_WriteHighPowerApplyPin(E_DjiPowerManagementPinState pinState)
{
//attention: please pull up the HWPR pin state by hardware.
return DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS;
}
/****************** (C) COPYRIGHT DJI Innovations *****END OF FILE****/

View File

@ -0,0 +1,67 @@
/**
********************************************************************
* @file dji_application.hpp
* @brief This is the header file for "dji_application.cpp", defining the structure and
* (exported) function prototypes.
*
* @copyright (c) 2021 DJI. All rights reserved.
*
* All information contained herein is, and remains, the property of DJI.
* The intellectual and technical concepts contained herein are proprietary
* to DJI and may be covered by U.S. and foreign patents, patents in process,
* and protected by trade secret or copyright law. Dissemination of this
* information, including but not limited to data and other proprietary
* material(s) incorporated within the information, in any form, is strictly
* prohibited without the express written consent of DJI.
*
* If you receive this source code without DJIs authorization, you may not
* further disseminate the information, and you must immediately remove the
* source code and notify DJI of its removal. DJI reserves the right to pursue
* legal actions against you for any loss(es) or damage(s) caused by your
* failure to do so.
*
*********************************************************************
*/
/* Define to prevent recursive inclusion -------------------------------------*/
#ifndef APPLICATION_H
#define APPLICATION_H
/* Includes ------------------------------------------------------------------*/
#include <iostream>
#include <fstream>
#include "dji_typedef.h"
#include "dji_core.h"
#ifdef __cplusplus
extern "C" {
#endif
/* Exported constants --------------------------------------------------------*/
/* Exported types ------------------------------------------------------------*/
using namespace std;
class Application {
public:
Application(int argc, char **argv);
~Application();
private:
static void DjiUser_SetupEnvironment(int argc, char **argv);
static void DjiUser_ApplicationStart();
static T_DjiReturnCode DjiUser_PrintConsole(const uint8_t *data, uint16_t dataLen);
static T_DjiReturnCode DjiUser_LocalWrite(const uint8_t *data, uint16_t dataLen);
static T_DjiReturnCode DjiUser_FillInUserInfo(T_DjiUserInfo *userInfo);
static T_DjiReturnCode DjiUser_LocalWriteFsInit(const char *path);
};
/* Exported functions --------------------------------------------------------*/
#ifdef __cplusplus
}
#endif
#endif // APPLICATION_H
/************************ (C) COPYRIGHT DJI Innovations *******END OF FILE******/

View File

@ -0,0 +1,55 @@
/**
********************************************************************
* @file dji_sdk_app_info.h
* @brief This is the header file for defining the structure and (exported) function prototypes.
*
* @copyright (c) 2018 DJI. All rights reserved.
*
* All information contained herein is, and remains, the property of DJI.
* The intellectual and technical concepts contained herein are proprietary
* to DJI and may be covered by U.S. and foreign patents, patents in process,
* and protected by trade secret or copyright law. Dissemination of this
* information, including but not limited to data and other proprietary
* material(s) incorporated within the information, in any form, is strictly
* prohibited without the express written consent of DJI.
*
* If you receive this source code without DJIs authorization, you may not
* further disseminate the information, and you must immediately remove the
* source code and notify DJI of its removal. DJI reserves the right to pursue
* legal actions against you for any loss(es) or damage(s) caused by your
* failure to do so.
*
*********************************************************************
*/
/* Define to prevent recursive inclusion -------------------------------------*/
#ifndef DJI_SDK_APP_INFO_H
#define DJI_SDK_APP_INFO_H
/* Includes ------------------------------------------------------------------*/
#ifdef __cplusplus
extern "C" {
#endif
/* Exported constants --------------------------------------------------------*/
// ATTENTION: User must goto https://developer.dji.com/user/apps/#all to create your own dji sdk application, get dji sdk application
// information then fill in the application information here.
#define USER_APP_NAME "your_app_name"
#define USER_APP_ID "your_app_id"
#define USER_APP_KEY "your_app_key"
#define USER_APP_LICENSE "your_app_license"
#define USER_DEVELOPER_ACCOUNT "your_developer_account"
#define USER_BAUD_RATE "460800"
/* Exported types ------------------------------------------------------------*/
/* Exported functions --------------------------------------------------------*/
#ifdef __cplusplus
}
#endif
#endif // DJI_SDK_APP_INFO_H
/************************ (C) COPYRIGHT DJI Innovations *******END OF FILE******/

View File

@ -0,0 +1,66 @@
/**
********************************************************************
* @file dji_sdk_config.h
* @brief This is the header file for "dji_config.c", defining the structure and
* (exported) function prototypes.
*
* @copyright (c) 2021 DJI. All rights reserved.
*
* All information contained herein is, and remains, the property of DJI.
* The intellectual and technical concepts contained herein are proprietary
* to DJI and may be covered by U.S. and foreign patents, patents in process,
* and protected by trade secret or copyright law. Dissemination of this
* information, including but not limited to data and other proprietary
* material(s) incorporated within the information, in any form, is strictly
* prohibited without the express written consent of DJI.
*
* If you receive this source code without DJIs authorization, you may not
* further disseminate the information, and you must immediately remove the
* source code and notify DJI of its removal. DJI reserves the right to pursue
* legal actions against you for any loss(es) or damage(s) caused by your
* failure to do so.
*
*********************************************************************
*/
/* Define to prevent recursive inclusion -------------------------------------*/
#ifndef DJI_SDK_CONFIG_H
#define DJI_SDK_CONFIG_H
/* Includes ------------------------------------------------------------------*/
#ifdef __cplusplus
extern "C" {
#endif
/* Exported constants --------------------------------------------------------*/
#define DJI_USE_ONLY_UART (0)
#define DJI_USE_UART_AND_USB_BULK_DEVICE (1)
#define DJI_USE_UART_AND_NETWORK_DEVICE (2)
/*!< Attention: Select your hardware connection mode here.
* */
#define CONFIG_HARDWARE_CONNECTION DJI_USE_ONLY_UART
/*!< Attention: Select the sample you want to run here.
* */
#define CONFIG_MODULE_SAMPLE_GIMBAL_EMU_ON
#define CONFIG_MODULE_SAMPLE_WIDGET_ON
#define CONFIG_MODULE_SAMPLE_WIDGET_SPEAKER_ON
#define CONFIG_MODULE_SAMPLE_POWER_MANAGEMENT_ON
#define CONFIG_MODULE_SAMPLE_DATA_TRANSMISSION_ON
/* Exported types ------------------------------------------------------------*/
/* Exported functions --------------------------------------------------------*/
#ifdef __cplusplus
}
#endif
#endif // DJI_SDK_CONFIG_H
/************************ (C) COPYRIGHT DJI Innovations *******END OF FILE******/

View File

@ -0,0 +1,36 @@
{
"dji_sdk_app_info": {
"user_app_name": "your_app_name",
"user_app_id": "your_app_id",
"user_app_key": "your_app_key",
"user_app_license": "your_app_license",
"user_develop_account": "your_developer_account",
"user_baud_rate": "460800"
},
"dji_sdk_link_config": {
"link_available": "use_only_uart/use_uart_and_usb_bulk_device/use_uart_and_network_device",
"link_select": "use_uart_and_network_device",
"uart_config": {
"uart1_device_name": "/dev/ttyUSB0",
"uart2_device_enable": "true",
"uart2_device_name": "/dev/ttyACM0"
},
"network_config": {
"network_device_name": "enxf8e43b7bbc2c",
"network_usb_adapter_vid": "0x0B95",
"network_usb_adapter_pid": "0x1790"
},
"usb_bulk_config": {
"usb_device_vid": "0x0B95",
"usb_device_pid": "0x1790",
"usb_bulk1_device_name": "/dev/usb-ffs/bulk1",
"usb_bulk1_interface_num": "2",
"usb_bulk1_endpoint_in": "0x83",
"usb_bulk1_endpoint_out": "0x02",
"usb_bulk2_device_name": "/dev/usb-ffs/bulk2",
"usb_bulk2_interface_num": "3",
"usb_bulk2_endpoint_in": "0x84",
"usb_bulk2_endpoint_out": "0x03"
}
}
}

View File

@ -0,0 +1,119 @@
/**
********************************************************************
* @file main.cpp
* @brief
*
* @copyright (c) 2021 DJI. All rights reserved.
*
* All information contained herein is, and remains, the property of DJI.
* The intellectual and technical concepts contained herein are proprietary
* to DJI and may be covered by U.S. and foreign patents, patents in process,
* and protected by trade secret or copyright law. Dissemination of this
* information, including but not limited to data and other proprietary
* material(s) incorporated within the information, in any form, is strictly
* prohibited without the express written consent of DJI.
*
* If you receive this source code without DJIs authorization, you may not
* further disseminate the information, and you must immediately remove the
* source code and notify DJI of its removal. DJI reserves the right to pursue
* legal actions against you for any loss(es) or damage(s) caused by your
* failure to do so.
*
*********************************************************************
*/
/* Includes ------------------------------------------------------------------*/
#include <liveview/test_liveview_entry.hpp>
#include <perception/test_perception_entry.hpp>
#include <flight_control/test_flight_control.h>
#include <gimbal/test_gimbal_entry.hpp>
#include "application.hpp"
#include "fc_subscription/test_fc_subscription.h"
#include <gimbal_emu/test_payload_gimbal_emu.h>
#include <camera_emu/test_payload_cam_emu_media.h>
#include <camera_emu/test_payload_cam_emu_base.h>
#include <dji_logger.h>
#include "widget/test_widget.h"
#include "widget/test_widget_speaker.h"
#include <power_management/test_power_management.h>
#include "data_transmission/test_data_transmission.h"
#include <flight_controller/test_flight_controller_entry.h>
#include <positioning/test_positioning.h>
#include <hms_manager/hms_manager_entry.h>
#include "camera_manager/test_camera_manager_entry.h"
/* Private constants ---------------------------------------------------------*/
/* Private types -------------------------------------------------------------*/
/* Private values -------------------------------------------------------------*/
/* Private functions declaration ---------------------------------------------*/
/* Exported functions definition ---------------------------------------------*/
int main(int argc, char **argv)
{
Application application(argc, argv);
char inputChar;
T_DjiOsalHandler *osalHandler = DjiPlatform_GetOsalHandler();
T_DjiReturnCode returnCode;
T_DjiTestApplyHighPowerHandler applyHighPowerHandler;
start:
std::cout
<< "\n"
<< "| Available commands: |\n"
<< "| [0] Fc subscribe sample - subscribe quaternion and gps data |\n"
<< "| [1] Flight controller sample - you can control flying by PSDK |\n"
<< "| [2] Hms info manager sample - get health manger system info by language |\n"
<< "| [a] Gimbal manager sample - you can control gimbal by PSDK |\n"
<< "| [c] Camera stream view sample - display the camera video stream |\n"
<< "| [d] Stereo vision view sample - display the stereo image |\n"
<< "| [e] Run camera manager sample - you can test camera's functions interactively |\n"
<< "| [f] Start rtk positioning sample - you can receive rtk rtcm data when rtk signal is ok |\n"
<< std::endl;
std::cin >> inputChar;
switch (inputChar) {
case '0':
DjiTest_FcSubscriptionRunSample();
break;
case '1':
DjiUser_RunFlightControllerSample();
break;
case '2':
DjiUser_RunHmsManagerSample();
break;
case 'a':
DjiUser_RunGimbalManagerSample();
break;
case 'c':
DjiUser_RunCameraStreamViewSample();
break;
case 'd':
DjiUser_RunStereoVisionViewSample();
break;
case 'e':
DjiUser_RunCameraManagerSample();
break;
case 'f':
returnCode = DjiTest_PositioningStartService();
if (returnCode != DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS) {
USER_LOG_ERROR("rtk positioning sample init error");
break;
}
USER_LOG_INFO("Start rtk positioning sample successfully");
break;
default:
break;
}
osalHandler->TaskSleepMs(2000);
goto start;
}
/* Private functions definition-----------------------------------------------*/
/****************** (C) COPYRIGHT DJI Innovations *****END OF FILE****/

View File

@ -0,0 +1,110 @@
/**
********************************************************************
* @file hal_network.c
* @version V2.0.0
* @date 3/27/20
* @brief
*
* @copyright (c) 2021 DJI. All rights reserved.
*
* All information contained herein is, and remains, the property of DJI.
* The intellectual and technical concepts contained herein are proprietary
* to DJI and may be covered by U.S. and foreign patents, patents in process,
* and protected by trade secret or copyright law. Dissemination of this
* information, including but not limited to data and other proprietary
* material(s) incorporated within the information, in any form, is strictly
* prohibited without the express written consent of DJI.
*
* If you receive this source code without DJIs authorization, you may not
* further disseminate the information, and you must immediately remove the
* source code and notify DJI of its removal. DJI reserves the right to pursue
* legal actions against you for any loss(es) or damage(s) caused by your
* failure to do so.
*
*********************************************************************
*/
/* Includes ------------------------------------------------------------------*/
#include "string.h"
#include "stdlib.h"
#include "stdio.h"
#include "hal_network.h"
#include "dji_logger.h"
#include "utils/dji_config_manager.h"
/* Private constants ---------------------------------------------------------*/
/* Private types -------------------------------------------------------------*/
/* Private values -------------------------------------------------------------*/
/* Private functions declaration ---------------------------------------------*/
/* Exported functions definition ---------------------------------------------*/
T_DjiReturnCode HalNetWork_Init(const char *ipAddr, const char *netMask, T_DjiNetworkHandle *halObj)
{
int32_t ret;
char cmdStr[LINUX_CMD_STR_MAX_SIZE];
char networkDeviceName[USER_DEVICE_NAME_STR_MAX_SIZE];
T_DjiUserLinkConfig linkConfig = {0};
if (ipAddr == NULL || netMask == NULL) {
USER_LOG_ERROR("hal network config param error");
return DJI_ERROR_SYSTEM_MODULE_CODE_INVALID_PARAMETER;
}
//Attention: need root permission to config ip addr and netmask.
memset(cmdStr, 0, sizeof(cmdStr));
if (DjiUserConfigManager_IsEnable()) {
DjiUserConfigManager_GetLinkConfig(&linkConfig);
strcpy(networkDeviceName, linkConfig.networkConfig.networkDeviceName);
} else {
strcpy(networkDeviceName, LINUX_NETWORK_DEV);
}
snprintf(cmdStr, sizeof(cmdStr), "ifconfig %s up", networkDeviceName);
ret = system(cmdStr);
if (ret != DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS) {
USER_LOG_ERROR("Can't open the network."
"Probably the program not execute with root permission."
"Please use the root permission to execute the program.");
return DJI_ERROR_SYSTEM_MODULE_CODE_SYSTEM_ERROR;
}
snprintf(cmdStr, sizeof(cmdStr), "ifconfig %s %s netmask %s", networkDeviceName, ipAddr, netMask);
ret = system(cmdStr);
if (ret != DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS) {
USER_LOG_ERROR("Can't config the ip address of network."
"Probably the program not execute with root permission."
"Please use the root permission to execute the program.");
return DJI_ERROR_SYSTEM_MODULE_CODE_SYSTEM_ERROR;
}
return DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS;
}
T_DjiReturnCode HalNetWork_DeInit(T_DjiNetworkHandle halObj)
{
return DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS;
}
T_DjiReturnCode HalNetWork_GetDeviceInfo(T_DjiHalNetworkDeviceInfo *deviceInfo)
{
T_DjiUserLinkConfig linkConfig = {0};
if (DjiUserConfigManager_IsEnable()) {
DjiUserConfigManager_GetLinkConfig(&linkConfig);
deviceInfo->usbNetAdapter.vid = linkConfig.networkConfig.networkUsbAdapterVid;
deviceInfo->usbNetAdapter.pid = linkConfig.networkConfig.networkUsbAdapterPid;
} else {
deviceInfo->usbNetAdapter.vid = USB_NET_ADAPTER_VID;
deviceInfo->usbNetAdapter.pid = USB_NET_ADAPTER_PID;
}
return DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS;
}
/* Private functions definition-----------------------------------------------*/
/****************** (C) COPYRIGHT DJI Innovations *****END OF FILE****/

View File

@ -0,0 +1,73 @@
/**
********************************************************************
* @file hal_network.h
* @brief This is the header file for "hal_network.c", defining the structure and
* (exported) function prototypes.
*
* @copyright (c) 2021 DJI. All rights reserved.
*
* All information contained herein is, and remains, the property of DJI.
* The intellectual and technical concepts contained herein are proprietary
* to DJI and may be covered by U.S. and foreign patents, patents in process,
* and protected by trade secret or copyright law. Dissemination of this
* information, including but not limited to data and other proprietary
* material(s) incorporated within the information, in any form, is strictly
* prohibited without the express written consent of DJI.
*
* If you receive this source code without DJIs authorization, you may not
* further disseminate the information, and you must immediately remove the
* source code and notify DJI of its removal. DJI reserves the right to pursue
* legal actions against you for any loss(es) or damage(s) caused by your
* failure to do so.
*
*********************************************************************
*/
/* Define to prevent recursive inclusion -------------------------------------*/
#ifndef HAL_NETWORK_H
#define HAL_NETWORK_H
/* Includes ------------------------------------------------------------------*/
#include "dji_platform.h"
#ifdef __cplusplus
extern "C" {
#endif
/* Exported constants --------------------------------------------------------*/
/** @attention User can config network card name here, if your device is not MF2C/G, please comment below and add your
* NIC name micro define as #define 'LINUX_NETWORK_DEV "your NIC name"'.
*/
#ifdef PLATFORM_ARCH_x86_64
#define LINUX_NETWORK_DEV "enxf8e43b7bbc2c"
#else
#define LINUX_NETWORK_DEV "l4tbr0"
#endif
/**
* @attention
*/
#ifdef PLATFORM_ARCH_x86_64
#define USB_NET_ADAPTER_VID (0x0B95)
#define USB_NET_ADAPTER_PID (0x1790)
#else
#define USB_NET_ADAPTER_VID (0x0955)
#define USB_NET_ADAPTER_PID (0x7020)
#endif
#define LINUX_CMD_STR_MAX_SIZE (128)
/* Exported types ------------------------------------------------------------*/
/* Exported functions --------------------------------------------------------*/
T_DjiReturnCode HalNetWork_Init(const char *ipAddr, const char *netMask, T_DjiNetworkHandle *halObj);
T_DjiReturnCode HalNetWork_DeInit(T_DjiNetworkHandle halObj);
T_DjiReturnCode HalNetWork_GetDeviceInfo(T_DjiHalNetworkDeviceInfo *deviceInfo);
#ifdef __cplusplus
}
#endif
#endif // HAL_NETWORK_H
/************************ (C) COPYRIGHT DJI Innovations *******END OF FILE******/

View File

@ -0,0 +1,280 @@
/**
********************************************************************
* @file hal_uart.c
* @brief
*
* @copyright (c) 2021 DJI. All rights reserved.
*
* All information contained herein is, and remains, the property of DJI.
* The intellectual and technical concepts contained herein are proprietary
* to DJI and may be covered by U.S. and foreign patents, patents in process,
* and protected by trade secret or copyright law. Dissemination of this
* information, including but not limited to data and other proprietary
* material(s) incorporated within the information, in any form, is strictly
* prohibited without the express written consent of DJI.
*
* If you receive this source code without DJIs authorization, you may not
* further disseminate the information, and you must immediately remove the
* source code and notify DJI of its removal. DJI reserves the right to pursue
* legal actions against you for any loss(es) or damage(s) caused by your
* failure to do so.
*
*********************************************************************
*/
/* Includes ------------------------------------------------------------------*/
#include <dji_logger.h>
#include "hal_uart.h"
#include "utils/dji_config_manager.h"
/* Private constants ---------------------------------------------------------*/
#define UART_DEV_NAME_STR_SIZE (128)
#define DJI_SYSTEM_CMD_STR_MAX_SIZE (64)
#define DJI_SYSTEM_RESULT_STR_MAX_SIZE (128)
/* Private types -------------------------------------------------------------*/
typedef struct {
int uartFd;
} T_UartHandleStruct;
/* Private values -------------------------------------------------------------*/
/* Private functions declaration ---------------------------------------------*/
/* Exported functions definition ---------------------------------------------*/
T_DjiReturnCode HalUart_Init(E_DjiHalUartNum uartNum, uint32_t baudRate, T_DjiUartHandle *uartHandle)
{
T_UartHandleStruct *uartHandleStruct;
struct termios options;
struct flock lock;
T_DjiReturnCode returnCode = DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS;
char uartName[UART_DEV_NAME_STR_SIZE];
char uart1Name[UART_DEV_NAME_STR_SIZE];
char uart2Name[UART_DEV_NAME_STR_SIZE];
char systemCmd[DJI_SYSTEM_CMD_STR_MAX_SIZE];
char *ret = NULL;
char lineBuf[DJI_SYSTEM_RESULT_STR_MAX_SIZE] = {0};
FILE *fp;
T_DjiUserLinkConfig linkConfig = {0};
uartHandleStruct = malloc(sizeof(T_UartHandleStruct));
if (uartHandleStruct == NULL) {
return DJI_ERROR_SYSTEM_MODULE_CODE_MEMORY_ALLOC_FAILED;
}
if (DjiUserConfigManager_IsEnable()) {
DjiUserConfigManager_GetLinkConfig(&linkConfig);
strcpy(uart1Name, linkConfig.uartConfig.uart1DeviceName);
strcpy(uart2Name, linkConfig.uartConfig.uart2DeviceName);
} else {
strcpy(uart1Name, LINUX_UART_DEV1);
strcpy(uart2Name, LINUX_UART_DEV2);
}
if (uartNum == DJI_HAL_UART_NUM_0) {
strcpy(uartName, uart1Name);
} else if (uartNum == DJI_HAL_UART_NUM_1) {
strcpy(uartName, uart2Name);
} else {
goto free_uart_handle;
}
#ifdef USE_CLION_DEBUG
sprintf(systemCmd, "ls -l %s", uartName);
fp = popen(systemCmd, "r");
if (fp == NULL) {
goto free_uart_handle;
}
ret = fgets(lineBuf, sizeof(lineBuf), fp);
if (ret == NULL) {
goto close_fp;
}
if (strstr(lineBuf, "crwxrwxrwx") == NULL) {
USER_LOG_ERROR("Can't operation the device. "
"Probably the device has not operation permission. "
"Please execute command 'sudo chmod 777 %s' to add permission. ", uartName);
goto close_fp;
}
#else
sprintf(systemCmd, "chmod 777 %s", uartName);
fp = popen(systemCmd, "r");
if (fp == NULL) {
goto free_uart_handle;
}
#endif
uartHandleStruct->uartFd = open(uartName, (unsigned) O_RDWR | (unsigned) O_NOCTTY | (unsigned) O_NDELAY);
if (uartHandleStruct->uartFd == -1) {
goto close_fp;
}
// Forbid multiple psdk programs to access the serial port
lock.l_type = F_WRLCK;
lock.l_pid = getpid();
lock.l_whence = SEEK_SET;
lock.l_start = 0;
lock.l_len = 0;
if (fcntl(uartHandleStruct->uartFd, F_GETLK, &lock) < 0) {
goto close_uart_fd;
}
if (lock.l_type != F_UNLCK) {
goto close_uart_fd;
}
lock.l_type = F_WRLCK;
lock.l_pid = getpid();
lock.l_whence = SEEK_SET;
lock.l_start = 0;
lock.l_len = 0;
if (fcntl(uartHandleStruct->uartFd, F_SETLKW, &lock) < 0) {
goto close_uart_fd;
}
if (tcgetattr(uartHandleStruct->uartFd, &options) != 0) {
goto close_uart_fd;
}
switch (baudRate) {
case 115200:
cfsetispeed(&options, B115200);
cfsetospeed(&options, B115200);
break;
case 230400:
cfsetispeed(&options, B230400);
cfsetospeed(&options, B230400);
break;
case 460800:
cfsetispeed(&options, B460800);
cfsetospeed(&options, B460800);
break;
case 921600:
cfsetispeed(&options, B921600);
cfsetospeed(&options, B921600);
break;
case 1000000:
cfsetispeed(&options, B1000000);
cfsetospeed(&options, B1000000);
break;
default:
goto close_uart_fd;
}
options.c_cflag |= (unsigned) CLOCAL;
options.c_cflag |= (unsigned) CREAD;
options.c_cflag &= ~(unsigned) CRTSCTS;
options.c_cflag &= ~(unsigned) CSIZE;
options.c_cflag |= (unsigned) CS8;
options.c_cflag &= ~(unsigned) PARENB;
options.c_iflag &= ~(unsigned) INPCK;
options.c_cflag &= ~(unsigned) CSTOPB;
options.c_oflag &= ~(unsigned) OPOST;
options.c_lflag &= ~((unsigned) ICANON | (unsigned) ECHO | (unsigned) ECHOE | (unsigned) ISIG);
options.c_iflag &= ~((unsigned) BRKINT | (unsigned) ICRNL | (unsigned) INPCK | (unsigned) ISTRIP | (unsigned) IXON);
options.c_cc[VTIME] = 0;
options.c_cc[VMIN] = 0;
tcflush(uartHandleStruct->uartFd, TCIFLUSH);
if (tcsetattr(uartHandleStruct->uartFd, TCSANOW, &options) != 0) {
goto close_uart_fd;
}
*uartHandle = uartHandleStruct;
pclose(fp);
return returnCode;
close_uart_fd:
close(uartHandleStruct->uartFd);
close_fp:
pclose(fp);
free_uart_handle:
free(uartHandleStruct);
return DJI_ERROR_SYSTEM_MODULE_CODE_SYSTEM_ERROR;
}
T_DjiReturnCode HalUart_DeInit(T_DjiUartHandle uartHandle)
{
int32_t ret;
T_UartHandleStruct *uartHandleStruct = (T_UartHandleStruct *) uartHandle;
if (uartHandle == NULL) {
return DJI_ERROR_SYSTEM_MODULE_CODE_UNKNOWN;
}
ret = close(uartHandleStruct->uartFd);
if (ret < 0) {
return DJI_ERROR_SYSTEM_MODULE_CODE_SYSTEM_ERROR;
}
free(uartHandleStruct);
return DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS;
}
T_DjiReturnCode HalUart_WriteData(T_DjiUartHandle uartHandle, const uint8_t *buf, uint32_t len, uint32_t *realLen)
{
int32_t ret;
T_UartHandleStruct *uartHandleStruct = (T_UartHandleStruct *) uartHandle;
if (uartHandle == NULL || buf == NULL || len == 0 || realLen == NULL) {
return DJI_ERROR_SYSTEM_MODULE_CODE_INVALID_PARAMETER;
}
ret = write(uartHandleStruct->uartFd, buf, len);
if (ret >= 0) {
*realLen = ret;
} else {
return DJI_ERROR_SYSTEM_MODULE_CODE_SYSTEM_ERROR;
}
return DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS;
}
T_DjiReturnCode HalUart_ReadData(T_DjiUartHandle uartHandle, uint8_t *buf, uint32_t len, uint32_t *realLen)
{
int32_t ret;
T_UartHandleStruct *uartHandleStruct = (T_UartHandleStruct *) uartHandle;
if (uartHandle == NULL || buf == NULL || len == 0 || realLen == NULL) {
return DJI_ERROR_SYSTEM_MODULE_CODE_INVALID_PARAMETER;
}
ret = read(uartHandleStruct->uartFd, buf, len);
if (ret >= 0) {
*realLen = ret;
} else {
return DJI_ERROR_SYSTEM_MODULE_CODE_SYSTEM_ERROR;
}
return DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS;
}
T_DjiReturnCode HalUart_GetStatus(E_DjiHalUartNum uartNum, T_DjiUartStatus *status)
{
T_DjiUserLinkConfig linkConfig = {0};
if (uartNum == DJI_HAL_UART_NUM_0) {
status->isConnect = true;
} else if (uartNum == DJI_HAL_UART_NUM_1) {
if (DjiUserConfigManager_IsEnable()) {
DjiUserConfigManager_GetLinkConfig(&linkConfig);
status->isConnect = linkConfig.uartConfig.uart2DeviceEnable;
} else {
status->isConnect = true;
}
} else {
return DJI_ERROR_SYSTEM_MODULE_CODE_INVALID_PARAMETER;
}
return DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS;
}
/* Private functions definition-----------------------------------------------*/
/****************** (C) COPYRIGHT DJI Innovations *****END OF FILE****/

View File

@ -0,0 +1,65 @@
/**
********************************************************************
* @file hal_uart.h
* @brief This is the header file for "hal_uart.c", defining the structure and
* (exported) function prototypes.
*
* @copyright (c) 2021 DJI. All rights reserved.
*
* All information contained herein is, and remains, the property of DJI.
* The intellectual and technical concepts contained herein are proprietary
* to DJI and may be covered by U.S. and foreign patents, patents in process,
* and protected by trade secret or copyright law. Dissemination of this
* information, including but not limited to data and other proprietary
* material(s) incorporated within the information, in any form, is strictly
* prohibited without the express written consent of DJI.
*
* If you receive this source code without DJIs authorization, you may not
* further disseminate the information, and you must immediately remove the
* source code and notify DJI of its removal. DJI reserves the right to pursue
* legal actions against you for any loss(es) or damage(s) caused by your
* failure to do so.
*
*********************************************************************
*/
/* Define to prevent recursive inclusion -------------------------------------*/
#ifndef HAL_UART_H
#define HAL_UART_H
/* Includes ------------------------------------------------------------------*/
#include "stdint.h"
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <termios.h>
#include <unistd.h>
#include <string.h>
#include "stdlib.h"
#include "dji_platform.h"
#ifdef __cplusplus
extern "C" {
#endif
/* Exported constants --------------------------------------------------------*/
//User can config dev based on there environmental conditions
#define LINUX_UART_DEV1 "/dev/ttyUSB0"
#define LINUX_UART_DEV2 "/dev/ttyACM0"
/* Exported types ------------------------------------------------------------*/
/* Exported functions --------------------------------------------------------*/
T_DjiReturnCode HalUart_Init(E_DjiHalUartNum uartNum, uint32_t baudRate, T_DjiUartHandle *uartHandle);
T_DjiReturnCode HalUart_DeInit(T_DjiUartHandle uartHandle);
T_DjiReturnCode HalUart_WriteData(T_DjiUartHandle uartHandle, const uint8_t *buf, uint32_t len, uint32_t *realLen);
T_DjiReturnCode HalUart_ReadData(T_DjiUartHandle uartHandle, uint8_t *buf, uint32_t len, uint32_t *realLen);
T_DjiReturnCode HalUart_GetStatus(E_DjiHalUartNum uartNum, T_DjiUartStatus *status);
#ifdef __cplusplus
}
#endif
#endif // HAL_UART_H
/************************ (C) COPYRIGHT DJI Innovations *******END OF FILE******/

View File

@ -0,0 +1,280 @@
/**
********************************************************************
* @file hal_usb_bulk.c
* @brief
*
* @copyright (c) 2021 DJI. All rights reserved.
*
* All information contained herein is, and remains, the property of DJI.
* The intellectual and technical concepts contained herein are proprietary
* to DJI and may be covered by U.S. and foreign patents, patents in process,
* and protected by trade secret or copyright law. Dissemination of this
* information, including but not limited to data and other proprietary
* material(s) incorporated within the information, in any form, is strictly
* prohibited without the express written consent of DJI.
*
* If you receive this source code without DJIs authorization, you may not
* further disseminate the information, and you must immediately remove the
* source code and notify DJI of its removal. DJI reserves the right to pursue
* legal actions against you for any loss(es) or damage(s) caused by your
* failure to do so.
*
*********************************************************************
*/
/* Includes ------------------------------------------------------------------*/
#include "hal_usb_bulk.h"
#include "dji_logger.h"
#include "utils/dji_config_manager.h"
/* Private constants ---------------------------------------------------------*/
#define LINUX_USB_BULK_TRANSFER_TIMEOUT_MS (50)
#define LINUX_USB_BULK_TRANSFER_WAIT_FOREVER (-1)
/* Private types -------------------------------------------------------------*/
typedef struct {
#ifdef LIBUSB_INSTALLED
libusb_device_handle *handle;
#else
void *handle;
#endif
int32_t ep1;
int32_t ep2;
uint32_t interfaceNum;
T_DjiHalUsbBulkInfo usbBulkInfo;
} T_HalUsbBulkObj;
/* Private values -------------------------------------------------------------*/
/* Private functions declaration ---------------------------------------------*/
/* Exported functions definition ---------------------------------------------*/
T_DjiReturnCode HalUsbBulk_Init(T_DjiHalUsbBulkInfo usbBulkInfo, T_DjiUsbBulkHandle *usbBulkHandle)
{
int32_t ret;
struct libusb_device_handle *handle = NULL;
T_DjiUserLinkConfig linkConfig = {0};
char usbBulk1EpInFd[USER_DEVICE_NAME_STR_MAX_SIZE];
char usbBulk1EpOutFd[USER_DEVICE_NAME_STR_MAX_SIZE];
char usbBulk2EpInFd[USER_DEVICE_NAME_STR_MAX_SIZE];
char usbBulk2EpOutFd[USER_DEVICE_NAME_STR_MAX_SIZE];
uint8_t usbBulk1InterfaceNum;
uint8_t usbBulk2InterfaceNum;
*usbBulkHandle = malloc(sizeof(T_HalUsbBulkObj));
if (*usbBulkHandle == NULL) {
return DJI_ERROR_SYSTEM_MODULE_CODE_SYSTEM_ERROR;
}
if (usbBulkInfo.isUsbHost == true) {
#ifdef LIBUSB_INSTALLED
ret = libusb_init(NULL);
if (ret < 0) {
USER_LOG_ERROR("init usb bulk failed, errno = %d", ret);
return DJI_ERROR_SYSTEM_MODULE_CODE_SYSTEM_ERROR;
}
handle = libusb_open_device_with_vid_pid(NULL, usbBulkInfo.vid, usbBulkInfo.pid);
if (handle == NULL) {
USER_LOG_ERROR("open usb device failed");
return DJI_ERROR_SYSTEM_MODULE_CODE_SYSTEM_ERROR;
}
ret = libusb_claim_interface(handle, usbBulkInfo.channelInfo.interfaceNum);
if (ret != LIBUSB_SUCCESS) {
USER_LOG_ERROR("libusb claim interface failed, errno = %d", ret);
libusb_close(handle);
return DJI_ERROR_SYSTEM_MODULE_CODE_SYSTEM_ERROR;
}
((T_HalUsbBulkObj *) *usbBulkHandle)->handle = handle;
memcpy(&((T_HalUsbBulkObj *) *usbBulkHandle)->usbBulkInfo, &usbBulkInfo, sizeof(usbBulkInfo));
#endif
} else {
((T_HalUsbBulkObj *) *usbBulkHandle)->handle = handle;
memcpy(&((T_HalUsbBulkObj *) *usbBulkHandle)->usbBulkInfo, &usbBulkInfo, sizeof(usbBulkInfo));
((T_HalUsbBulkObj *) *usbBulkHandle)->interfaceNum = usbBulkInfo.channelInfo.interfaceNum;
if (DjiUserConfigManager_IsEnable()) {
DjiUserConfigManager_GetLinkConfig(&linkConfig);
usbBulk1InterfaceNum = linkConfig.usbBulkConfig.usbBulk1InterfaceNum;
usbBulk2InterfaceNum = linkConfig.usbBulkConfig.usbBulk2InterfaceNum;
snprintf(usbBulk1EpOutFd, sizeof(usbBulk1EpOutFd), "%s/ep1",
linkConfig.usbBulkConfig.usbBulk1DeviceName);
snprintf(usbBulk1EpInFd, sizeof(usbBulk1EpInFd), "%s/ep2",
linkConfig.usbBulkConfig.usbBulk1DeviceName);
snprintf(usbBulk2EpOutFd, sizeof(usbBulk2EpOutFd), "%s/ep1",
linkConfig.usbBulkConfig.usbBulk2DeviceName);
snprintf(usbBulk2EpInFd, sizeof(usbBulk2EpInFd), "%s/ep2",
linkConfig.usbBulkConfig.usbBulk2DeviceName);
} else {
usbBulk1InterfaceNum = LINUX_USB_BULK1_INTERFACE_NUM;
usbBulk2InterfaceNum = LINUX_USB_BULK2_INTERFACE_NUM;
strcpy(usbBulk1EpInFd, LINUX_USB_BULK1_EP_IN_FD);
strcpy(usbBulk1EpOutFd, LINUX_USB_BULK1_EP_OUT_FD);
strcpy(usbBulk2EpInFd, LINUX_USB_BULK2_EP_IN_FD);
strcpy(usbBulk2EpOutFd, LINUX_USB_BULK2_EP_OUT_FD);
}
if (usbBulkInfo.channelInfo.interfaceNum == usbBulk1InterfaceNum) {
((T_HalUsbBulkObj *) *usbBulkHandle)->ep1 = open(usbBulk1EpOutFd, O_RDWR);
if (((T_HalUsbBulkObj *) *usbBulkHandle)->ep1 < 0) {
return DJI_ERROR_SYSTEM_MODULE_CODE_SYSTEM_ERROR;
}
((T_HalUsbBulkObj *) *usbBulkHandle)->ep2 = open(usbBulk1EpInFd, O_RDWR);
if (((T_HalUsbBulkObj *) *usbBulkHandle)->ep2 < 0) {
return DJI_ERROR_SYSTEM_MODULE_CODE_SYSTEM_ERROR;
}
} else if (usbBulkInfo.channelInfo.interfaceNum == usbBulk2InterfaceNum) {
((T_HalUsbBulkObj *) *usbBulkHandle)->ep1 = open(usbBulk2EpOutFd, O_RDWR);
if (((T_HalUsbBulkObj *) *usbBulkHandle)->ep1 < 0) {
return DJI_ERROR_SYSTEM_MODULE_CODE_SYSTEM_ERROR;
}
((T_HalUsbBulkObj *) *usbBulkHandle)->ep2 = open(usbBulk2EpInFd, O_RDWR);
if (((T_HalUsbBulkObj *) *usbBulkHandle)->ep2 < 0) {
return DJI_ERROR_SYSTEM_MODULE_CODE_SYSTEM_ERROR;
}
}
}
return DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS;
}
T_DjiReturnCode HalUsbBulk_DeInit(T_DjiUsbBulkHandle usbBulkHandle)
{
struct libusb_device_handle *handle = NULL;
T_DjiOsalHandler *osalHandler = DjiPlatform_GetOsalHandler();
int32_t ret;
if (usbBulkHandle == NULL) {
return DJI_ERROR_SYSTEM_MODULE_CODE_SYSTEM_ERROR;
}
handle = ((T_HalUsbBulkObj *) usbBulkHandle)->handle;
if (((T_HalUsbBulkObj *) usbBulkHandle)->usbBulkInfo.isUsbHost == true) {
#ifdef LIBUSB_INSTALLED
ret = libusb_release_interface(handle,
((T_HalUsbBulkObj *) usbBulkHandle)->usbBulkInfo.channelInfo.interfaceNum);
if (ret != 0) {
USER_LOG_ERROR("release usb bulk interface failed, errno = %d", ret);
return DJI_ERROR_SYSTEM_MODULE_CODE_SYSTEM_ERROR;
}
libusb_exit(NULL);
#endif
} else {
close(((T_HalUsbBulkObj *) usbBulkHandle)->ep1);
close(((T_HalUsbBulkObj *) usbBulkHandle)->ep2);
}
free(usbBulkHandle);
return DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS;
}
T_DjiReturnCode HalUsbBulk_WriteData(T_DjiUsbBulkHandle usbBulkHandle, const uint8_t *buf, uint32_t len,
uint32_t *realLen)
{
int32_t ret;
int32_t actualLen;
struct libusb_device_handle *handle = NULL;
if (usbBulkHandle == NULL) {
return DJI_ERROR_SYSTEM_MODULE_CODE_SYSTEM_ERROR;
}
handle = ((T_HalUsbBulkObj *) usbBulkHandle)->handle;
if (((T_HalUsbBulkObj *) usbBulkHandle)->usbBulkInfo.isUsbHost == true) {
#ifdef LIBUSB_INSTALLED
ret = libusb_bulk_transfer(handle, ((T_HalUsbBulkObj *) usbBulkHandle)->usbBulkInfo.channelInfo.endPointOut,
(uint8_t *) buf, len, &actualLen, LINUX_USB_BULK_TRANSFER_TIMEOUT_MS);
if (ret < 0) {
USER_LOG_ERROR("Write usb bulk data failed, errno = %d", ret);
return DJI_ERROR_SYSTEM_MODULE_CODE_SYSTEM_ERROR;
}
*realLen = actualLen;
#endif
} else {
*realLen = write(((T_HalUsbBulkObj *) usbBulkHandle)->ep1, buf, len);
}
return DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS;
}
T_DjiReturnCode HalUsbBulk_ReadData(T_DjiUsbBulkHandle usbBulkHandle, uint8_t *buf, uint32_t len,
uint32_t *realLen)
{
int32_t ret;
struct libusb_device_handle *handle = NULL;
int32_t actualLen;
if (usbBulkHandle == NULL) {
return DJI_ERROR_SYSTEM_MODULE_CODE_SYSTEM_ERROR;
}
handle = ((T_HalUsbBulkObj *) usbBulkHandle)->handle;
if (((T_HalUsbBulkObj *) usbBulkHandle)->usbBulkInfo.isUsbHost == true) {
#ifdef LIBUSB_INSTALLED
ret = libusb_bulk_transfer(handle, ((T_HalUsbBulkObj *) usbBulkHandle)->usbBulkInfo.channelInfo.endPointIn,
buf, len, &actualLen, LINUX_USB_BULK_TRANSFER_WAIT_FOREVER);
if (ret < 0) {
USER_LOG_ERROR("Read usb bulk data failed, errno = %d", ret);
return DJI_ERROR_SYSTEM_MODULE_CODE_SYSTEM_ERROR;
}
*realLen = actualLen;
#endif
} else {
*realLen = read(((T_HalUsbBulkObj *) usbBulkHandle)->ep2, buf, len);
}
return DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS;
}
T_DjiReturnCode HalUsbBulk_GetDeviceInfo(T_DjiHalUsbBulkDeviceInfo *deviceInfo)
{
T_DjiUserLinkConfig linkConfig = {0};
if (DjiUserConfigManager_IsEnable()) {
DjiUserConfigManager_GetLinkConfig(&linkConfig);
//attention: this interface only be called in usb device mode.
deviceInfo->vid = linkConfig.usbBulkConfig.usbDeviceVid;
deviceInfo->pid = linkConfig.usbBulkConfig.usbDevicePid;
// This bulk channel is used to obtain DJI camera video stream and push 3rd-party camera video stream.
deviceInfo->channelInfo[DJI_HAL_USB_BULK_NUM_0].interfaceNum = linkConfig.usbBulkConfig.usbBulk1InterfaceNum;
deviceInfo->channelInfo[DJI_HAL_USB_BULK_NUM_0].endPointIn = linkConfig.usbBulkConfig.usbBulk1EndpointIn;
deviceInfo->channelInfo[DJI_HAL_USB_BULK_NUM_0].endPointOut = linkConfig.usbBulkConfig.usbBulk1EndpointOut;
// This bulk channel is used to obtain DJI perception image and download camera media file.
deviceInfo->channelInfo[DJI_HAL_USB_BULK_NUM_1].interfaceNum = linkConfig.usbBulkConfig.usbBulk2InterfaceNum;
deviceInfo->channelInfo[DJI_HAL_USB_BULK_NUM_1].endPointIn = linkConfig.usbBulkConfig.usbBulk2EndpointIn;
deviceInfo->channelInfo[DJI_HAL_USB_BULK_NUM_1].endPointOut = linkConfig.usbBulkConfig.usbBulk2EndpointOut;
} else {
//attention: this interface only be called in usb device mode.
deviceInfo->vid = LINUX_USB_VID;
deviceInfo->pid = LINUX_USB_PID;
// This bulk channel is used to obtain DJI camera video stream and push 3rd-party camera video stream.
deviceInfo->channelInfo[DJI_HAL_USB_BULK_NUM_0].interfaceNum = LINUX_USB_BULK1_INTERFACE_NUM;
deviceInfo->channelInfo[DJI_HAL_USB_BULK_NUM_0].endPointIn = LINUX_USB_BULK1_END_POINT_IN;
deviceInfo->channelInfo[DJI_HAL_USB_BULK_NUM_0].endPointOut = LINUX_USB_BULK1_END_POINT_OUT;
// This bulk channel is used to obtain DJI perception image and download camera media file.
deviceInfo->channelInfo[DJI_HAL_USB_BULK_NUM_1].interfaceNum = LINUX_USB_BULK2_INTERFACE_NUM;
deviceInfo->channelInfo[DJI_HAL_USB_BULK_NUM_1].endPointIn = LINUX_USB_BULK2_END_POINT_IN;
deviceInfo->channelInfo[DJI_HAL_USB_BULK_NUM_1].endPointOut = LINUX_USB_BULK2_END_POINT_OUT;
}
return DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS;
}
/* Private functions definition-----------------------------------------------*/
/****************** (C) COPYRIGHT DJI Innovations *****END OF FILE****/

View File

@ -0,0 +1,92 @@
/**
********************************************************************
* @file hal_usb_bulk.h
* @brief This is the header file for "hal_usb_bulk.c", defining the structure and
* (exported) function prototypes.
*
* @copyright (c) 2021 DJI. All rights reserved.
*
* All information contained herein is, and remains, the property of DJI.
* The intellectual and technical concepts contained herein are proprietary
* to DJI and may be covered by U.S. and foreign patents, patents in process,
* and protected by trade secret or copyright law. Dissemination of this
* information, including but not limited to data and other proprietary
* material(s) incorporated within the information, in any form, is strictly
* prohibited without the express written consent of DJI.
*
* If you receive this source code without DJIs authorization, you may not
* further disseminate the information, and you must immediately remove the
* source code and notify DJI of its removal. DJI reserves the right to pursue
* legal actions against you for any loss(es) or damage(s) caused by your
* failure to do so.
*
*********************************************************************
*/
/* Define to prevent recursive inclusion -------------------------------------*/
#ifndef HAL_USB_BULK_H
#define HAL_USB_BULK_H
/* Includes ------------------------------------------------------------------*/
#include "stdint.h"
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <termios.h>
#include <unistd.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#ifdef LIBUSB_INSTALLED
#include <libusb-1.0/libusb.h>
#endif
#include "dji_platform.h"
#ifdef __cplusplus
extern "C" {
#endif
/* Exported constants --------------------------------------------------------*/
#define LINUX_USB_BULK1_EP_OUT_FD "/dev/usb-ffs/bulk1/ep1"
#define LINUX_USB_BULK1_EP_IN_FD "/dev/usb-ffs/bulk1/ep2"
#define LINUX_USB_BULK1_INTERFACE_NUM (2)
#define LINUX_USB_BULK1_END_POINT_IN (0x83)
#define LINUX_USB_BULK1_END_POINT_OUT (2)
#define LINUX_USB_BULK2_EP_OUT_FD "/dev/usb-ffs/bulk2/ep1"
#define LINUX_USB_BULK2_EP_IN_FD "/dev/usb-ffs/bulk2/ep2"
#define LINUX_USB_BULK2_INTERFACE_NUM (3)
#define LINUX_USB_BULK2_END_POINT_IN (0x84)
#define LINUX_USB_BULK2_END_POINT_OUT (3)
#ifdef PLATFORM_ARCH_x86_64
#define LINUX_USB_VID (0x0B95)
#define LINUX_USB_PID (0x1790)
#else
#define LINUX_USB_VID (0x0955)
#define LINUX_USB_PID (0x7020)
#endif
/* Exported types ------------------------------------------------------------*/
/* Exported functions --------------------------------------------------------*/
T_DjiReturnCode HalUsbBulk_Init(T_DjiHalUsbBulkInfo usbBulkInfo, T_DjiUsbBulkHandle *usbBulkHandle);
T_DjiReturnCode HalUsbBulk_DeInit(T_DjiUsbBulkHandle usbBulkHandle);
T_DjiReturnCode HalUsbBulk_WriteData(T_DjiUsbBulkHandle usbBulkHandle, const uint8_t *buf, uint32_t len,
uint32_t *realLen);
T_DjiReturnCode HalUsbBulk_ReadData(T_DjiUsbBulkHandle usbBulkHandle, uint8_t *buf, uint32_t len, uint32_t *realLen);
T_DjiReturnCode HalUsbBulk_GetDeviceInfo(T_DjiHalUsbBulkDeviceInfo *deviceInfo);
#ifdef __cplusplus
}
#endif
#endif // HAL_USB_BULK_H
/************************ (C) COPYRIGHT DJI Innovations *******END OF FILE******/

View File

@ -0,0 +1,128 @@
cmake_minimum_required(VERSION 3.5)
project(dji_sdk_demo_on_jetson_cxx CXX)
set(CMAKE_C_FLAGS "-pthread -std=gnu99")
set(CMAKE_CXX_FLAGS "-std=c++11 -pthread")
set(CMAKE_EXE_LINKER_FLAGS "-pthread")
set(CMAKE_C_COMPILER "aarch64-linux-gnu-gcc")
set(CMAKE_CXX_COMPILER "aarch64-linux-gnu-g++")
add_definitions(-D_GNU_SOURCE)
if (BUILD_TEST_CASES_ON MATCHES TRUE)
set(CMAKE_CXX_FLAGS "${CMAKE_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")
endif ()
include_directories(../../../module_sample)
include_directories(../../../../sample_c/module_sample)
include_directories(../common)
include_directories(../nvidia_jetson/application)
file(GLOB_RECURSE MODULE_SAMPLE_SRC
../../../module_sample/liveview/*.c*
../../../module_sample/camera_manager/*.c*
../../../module_sample/perception/*.c*
../../../module_sample/gimbal/*.c*
../../../../sample_c/module_sample/*.c
)
file(GLOB_RECURSE MODULE_COMMON_SRC ../common/*.c*)
file(GLOB_RECURSE MODULE_HAL_SRC hal/*.c*)
file(GLOB_RECURSE MODULE_APP_SRC application/*.c*)
set(TOOLCHAIN_NAME aarch64-linux-gnu-gcc)
add_definitions(-DPLATFORM_ARCH_aarch64=1)
add_definitions(-DSYSTEM_ARCH_LINUX=1)
set(CMAKE_MODULE_PATH ${CMAKE_CURRENT_SOURCE_DIR}/../common/3rdparty)
link_directories(${CMAKE_CURRENT_LIST_DIR}/../../../../../psdk_lib/lib/${TOOLCHAIN_NAME})
link_libraries(${CMAKE_CURRENT_LIST_DIR}/../../../../../psdk_lib/lib/${TOOLCHAIN_NAME}/libpayloadsdk.a -lstdc++)
add_executable(${PROJECT_NAME}
${MODULE_APP_SRC}
${MODULE_SAMPLE_SRC}
${MODULE_COMMON_SRC}
${MODULE_HAL_SRC})
# Try to see if user has OpenCV installed
# if yes, default callback will display the image
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)
else ()
message(STATUS "Did not find OpenCV in the system, image data is inside RecvContainer as raw data")
endif ()
find_package(FFMPEG REQUIRED)
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 ()
target_link_libraries(${PROJECT_NAME} ${FFMPEG_LIBRARIES})
include_directories(${FFMPEG_INCLUDE_DIR})
add_definitions(-DFFMPEG_INSTALLED)
else ()
message(STATUS "Cannot Find FFMPEG")
endif (FFMPEG_FOUND)
include_directories(${CMAKE_CURRENT_LIST_DIR}/../../../../../psdk_lib/include)
find_package(OPUS REQUIRED)
if (OPUS_FOUND)
message(STATUS "Found OPUS installed in the system")
message(STATUS " - Includes: ${OPUS_INCLUDE_DIR}")
message(STATUS " - Libraries: ${OPUS_LIBRARY}")
add_definitions(-DOPUS_INSTALLED)
target_link_libraries(${PROJECT_NAME} /usr/local/lib/libopus.a)
else ()
message(STATUS "Cannot Find OPUS")
endif (OPUS_FOUND)
find_package(LIBUSB REQUIRED)
if (LIBUSB_FOUND)
message(STATUS "Found LIBUSB installed in the system")
message(STATUS " - Includes: ${LIBUSB_INCLUDE_DIR}")
message(STATUS " - Libraries: ${LIBUSB_LIBRARY}")
add_definitions(-DLIBUSB_INSTALLED)
target_link_libraries(${PROJECT_NAME} usb-1.0)
else ()
message(STATUS "Cannot Find LIBUSB")
endif (LIBUSB_FOUND)
if (NOT EXECUTABLE_OUTPUT_PATH)
set(EXECUTABLE_OUTPUT_PATH ${CMAKE_BINARY_DIR}/bin)
endif ()
target_link_libraries(${PROJECT_NAME} m)
add_custom_command(TARGET ${PROJECT_NAME}
PRE_LINK COMMAND cmake ..
WORKING_DIRECTORY ${CMAKE_BINARY_DIR})
target_include_directories(${PROJECT_NAME} PRIVATE ${OpenCV_INCLUDE_DIRS})
if (OpenCV_FOUND)
target_link_libraries(${PROJECT_NAME} ${OpenCV_LIBS})
endif ()

View File

@ -0,0 +1,420 @@
/**
********************************************************************
* @file application.cpp
* @brief
*
* @copyright (c) 2021 DJI. All rights reserved.
*
* All information contained herein is, and remains, the property of DJI.
* The intellectual and technical concepts contained herein are proprietary
* to DJI and may be covered by U.S. and foreign patents, patents in process,
* and protected by trade secret or copyright law. Dissemination of this
* information, including but not limited to data and other proprietary
* material(s) incorporated within the information, in any form, is strictly
* prohibited without the express written consent of DJI.
*
* If you receive this source code without DJIs authorization, you may not
* further disseminate the information, and you must immediately remove the
* source code and notify DJI of its removal. DJI reserves the right to pursue
* legal actions against you for any loss(es) or damage(s) caused by your
* failure to do so.
*
*********************************************************************
*/
/* Includes ------------------------------------------------------------------*/
#include "application.hpp"
#include "dji_sdk_app_info.h"
#include <dji_platform.h>
#include <dji_logger.h>
#include <dji_core.h>
#include <dji_aircraft_info.h>
#include <csignal>
#include "dji_sdk_config.h"
#include "../common/osal/osal.h"
#include "../common/osal/osal_fs.h"
#include "../common/osal/osal_socket.h"
#include "../manifold2/hal/hal_usb_bulk.h"
#include "../manifold2/hal/hal_uart.h"
#include "../manifold2/hal/hal_network.h"
/* Private constants ---------------------------------------------------------*/
#define DJI_LOG_PATH "Logs/DJI"
#define DJI_LOG_INDEX_FILE_NAME "Logs/latest"
#define DJI_LOG_FOLDER_NAME "Logs"
#define DJI_LOG_PATH_MAX_SIZE (128)
#define DJI_LOG_FOLDER_NAME_MAX_SIZE (32)
#define DJI_SYSTEM_CMD_STR_MAX_SIZE (64)
#define DJI_LOG_MAX_COUNT (10)
#define USER_UTIL_UNUSED(x) ((x) = (x))
#define USER_UTIL_MIN(a, b) (((a) < (b)) ? (a) : (b))
#define USER_UTIL_MAX(a, b) (((a) > (b)) ? (a) : (b))
/* Private types -------------------------------------------------------------*/
/* Private values -------------------------------------------------------------*/
static FILE *s_djiLogFile;
static FILE *s_djiLogFileCnt;
/* Private functions declaration ---------------------------------------------*/
static void DjiUser_NormalExitHandler(int signalNum);
/* Exported functions definition ---------------------------------------------*/
Application::Application(int argc, char **argv)
{
Application::DjiUser_SetupEnvironment();
Application::DjiUser_ApplicationStart();
Osal_TaskSleepMs(3000);
}
Application::~Application()
= default;
/* Private functions definition-----------------------------------------------*/
void Application::DjiUser_SetupEnvironment()
{
T_DjiReturnCode returnCode;
T_DjiOsalHandler osalHandler = {0};
T_DjiHalUartHandler uartHandler = {0};
T_DjiHalUsbBulkHandler usbBulkHandler = {0};
T_DjiLoggerConsole printConsole;
T_DjiLoggerConsole localRecordConsole;
T_DjiFileSystemHandler fileSystemHandler = {0};
T_DjiSocketHandler socketHandler = {0};
T_DjiHalNetworkHandler networkHandler = {0};
networkHandler.NetworkInit = HalNetWork_Init;
networkHandler.NetworkDeInit = HalNetWork_DeInit;
networkHandler.NetworkGetDeviceInfo = HalNetWork_GetDeviceInfo;
socketHandler.Socket = Osal_Socket;
socketHandler.Bind = Osal_Bind;
socketHandler.Close = Osal_Close;
socketHandler.UdpSendData = Osal_UdpSendData;
socketHandler.UdpRecvData = Osal_UdpRecvData;
socketHandler.TcpListen = Osal_TcpListen;
socketHandler.TcpAccept = Osal_TcpAccept;
socketHandler.TcpConnect = Osal_TcpConnect;
socketHandler.TcpSendData = Osal_TcpSendData;
socketHandler.TcpRecvData = Osal_TcpRecvData;
osalHandler.TaskCreate = Osal_TaskCreate;
osalHandler.TaskDestroy = Osal_TaskDestroy;
osalHandler.TaskSleepMs = Osal_TaskSleepMs;
osalHandler.MutexCreate = Osal_MutexCreate;
osalHandler.MutexDestroy = Osal_MutexDestroy;
osalHandler.MutexLock = Osal_MutexLock;
osalHandler.MutexUnlock = Osal_MutexUnlock;
osalHandler.SemaphoreCreate = Osal_SemaphoreCreate;
osalHandler.SemaphoreDestroy = Osal_SemaphoreDestroy;
osalHandler.SemaphoreWait = Osal_SemaphoreWait;
osalHandler.SemaphoreTimedWait = Osal_SemaphoreTimedWait;
osalHandler.SemaphorePost = Osal_SemaphorePost;
osalHandler.Malloc = Osal_Malloc;
osalHandler.Free = Osal_Free;
osalHandler.GetTimeMs = Osal_GetTimeMs;
osalHandler.GetTimeUs = Osal_GetTimeUs;
osalHandler.GetRandomNum = Osal_GetRandomNum,
printConsole.func = DjiUser_PrintConsole;
printConsole.consoleLevel = DJI_LOGGER_CONSOLE_LOG_LEVEL_INFO;
printConsole.isSupportColor = true;
localRecordConsole.consoleLevel = DJI_LOGGER_CONSOLE_LOG_LEVEL_DEBUG;
localRecordConsole.func = DjiUser_LocalWrite;
localRecordConsole.isSupportColor = false;
uartHandler.UartInit = HalUart_Init;
uartHandler.UartDeInit = HalUart_DeInit;
uartHandler.UartWriteData = HalUart_WriteData;
uartHandler.UartReadData = HalUart_ReadData;
uartHandler.UartGetStatus = HalUart_GetStatus;
usbBulkHandler.UsbBulkInit = HalUsbBulk_Init;
usbBulkHandler.UsbBulkDeInit = HalUsbBulk_DeInit;
usbBulkHandler.UsbBulkWriteData = HalUsbBulk_WriteData;
usbBulkHandler.UsbBulkReadData = HalUsbBulk_ReadData;
usbBulkHandler.UsbBulkGetDeviceInfo = HalUsbBulk_GetDeviceInfo;
fileSystemHandler.FileOpen = Osal_FileOpen,
fileSystemHandler.FileClose = Osal_FileClose,
fileSystemHandler.FileWrite = Osal_FileWrite,
fileSystemHandler.FileRead = Osal_FileRead,
fileSystemHandler.FileSync = Osal_FileSync,
fileSystemHandler.FileSeek = Osal_FileSeek,
fileSystemHandler.DirOpen = Osal_DirOpen,
fileSystemHandler.DirClose = Osal_DirClose,
fileSystemHandler.DirRead = Osal_DirRead,
fileSystemHandler.Mkdir = Osal_Mkdir,
fileSystemHandler.Unlink = Osal_Unlink,
fileSystemHandler.Rename = Osal_Rename,
fileSystemHandler.Stat = Osal_Stat,
returnCode = DjiPlatform_RegOsalHandler(&osalHandler);
if (returnCode != DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS) {
throw std::runtime_error("Register osal handler error.");
}
returnCode = DjiPlatform_RegHalUartHandler(&uartHandler);
if (returnCode != DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS) {
throw std::runtime_error("Register hal uart handler error.");
}
#if (CONFIG_HARDWARE_CONNECTION == DJI_USE_UART_AND_USB_BULK_DEVICE)
returnCode = DjiPlatform_RegHalUsbBulkHandler(&usbBulkHandler);
if (returnCode != DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS) {
throw std::runtime_error("Register hal usb bulk handler error.");
}
#elif (CONFIG_HARDWARE_CONNECTION == DJI_USE_UART_AND_NETWORK_DEVICE)
returnCode = DjiPlatform_RegHalNetworkHandler(&networkHandler);
if (returnCode != DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS) {
throw std::runtime_error("Register hal network handler error");
}
#elif (CONFIG_HARDWARE_CONNECTION == DJI_USE_ONLY_UART)
/*!< Attention: Only use uart hardware connection.
*/
#endif
//Attention: if you want to use camera stream view function, please uncomment it.
returnCode = DjiPlatform_RegSocketHandler(&socketHandler);
if (returnCode != DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS) {
throw std::runtime_error("register osal socket handler error");
}
returnCode = DjiPlatform_RegFileSystemHandler(&fileSystemHandler);
if (returnCode != DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS) {
throw std::runtime_error("Register osal filesystem handler error.");
}
if (DjiUser_LocalWriteFsInit(DJI_LOG_PATH) != DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS) {
throw std::runtime_error("File system init error.");
}
returnCode = DjiLogger_AddConsole(&printConsole);
if (returnCode != DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS) {
throw std::runtime_error("Add printf console error.");
}
returnCode = DjiLogger_AddConsole(&localRecordConsole);
if (returnCode != DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS) {
throw std::runtime_error("Add printf console error.");
}
}
void Application::DjiUser_ApplicationStart()
{
T_DjiUserInfo userInfo;
T_DjiReturnCode returnCode;
T_DjiAircraftInfoBaseInfo aircraftInfoBaseInfo;
T_DjiFirmwareVersion firmwareVersion = {
.majorVersion = 1,
.minorVersion = 0,
.modifyVersion = 0,
.debugVersion = 0,
};
// attention: when the program is hand up ctrl-c will generate the coredump file
signal(SIGTERM, DjiUser_NormalExitHandler);
returnCode = DjiUser_FillInUserInfo(&userInfo);
if (returnCode != DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS) {
throw std::runtime_error("Fill user info error, please check user info config.");
}
returnCode = DjiCore_Init(&userInfo);
if (returnCode != DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS) {
throw std::runtime_error("Core init error.");
}
returnCode = DjiAircraftInfo_GetBaseInfo(&aircraftInfoBaseInfo);
if (returnCode != DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS) {
throw std::runtime_error("Get aircraft base info error.");
}
if (aircraftInfoBaseInfo.mountPosition != DJI_MOUNT_POSITION_EXTENSION_PORT) {
throw std::runtime_error("Please run this sample on extension port.");
}
returnCode = DjiCore_SetAlias("PSDK_APPALIAS");
if (returnCode != DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS) {
throw std::runtime_error("Set alias error.");
}
returnCode = DjiCore_SetFirmwareVersion(firmwareVersion);
if (returnCode != DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS) {
throw std::runtime_error("Set firmware version error.");
}
returnCode = DjiCore_SetSerialNumber("PSDK12345678XX");
if (returnCode != DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS) {
throw std::runtime_error("Set serial number error");
}
returnCode = DjiCore_ApplicationStart();
if (returnCode != DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS) {
throw std::runtime_error("Start sdk application error.");
}
USER_LOG_INFO("Application start.");
}
T_DjiReturnCode Application::DjiUser_PrintConsole(const uint8_t *data, uint16_t dataLen)
{
printf("%s", data);
return DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS;
}
T_DjiReturnCode Application::DjiUser_LocalWrite(const uint8_t *data, uint16_t dataLen)
{
int32_t realLen;
if (s_djiLogFile == nullptr) {
return DJI_ERROR_SYSTEM_MODULE_CODE_UNKNOWN;
}
realLen = fwrite(data, 1, dataLen, s_djiLogFile);
fflush(s_djiLogFile);
if (realLen == dataLen) {
return DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS;
} else {
return DJI_ERROR_SYSTEM_MODULE_CODE_UNKNOWN;
}
}
T_DjiReturnCode Application::DjiUser_FillInUserInfo(T_DjiUserInfo *userInfo)
{
memset(userInfo->appName, 0, sizeof(userInfo->appName));
memset(userInfo->appId, 0, sizeof(userInfo->appId));
memset(userInfo->appKey, 0, sizeof(userInfo->appKey));
memset(userInfo->appLicense, 0, sizeof(userInfo->appLicense));
memset(userInfo->developerAccount, 0, sizeof(userInfo->developerAccount));
memset(userInfo->baudRate, 0, sizeof(userInfo->baudRate));
if (strlen(USER_APP_NAME) >= sizeof(userInfo->appName) ||
strlen(USER_APP_ID) > sizeof(userInfo->appId) ||
strlen(USER_APP_KEY) > sizeof(userInfo->appKey) ||
strlen(USER_APP_LICENSE) > sizeof(userInfo->appLicense) ||
strlen(USER_DEVELOPER_ACCOUNT) >= sizeof(userInfo->developerAccount) ||
strlen(USER_BAUD_RATE) > sizeof(userInfo->baudRate)) {
USER_LOG_ERROR("Length of user information string is beyond limit. Please check.");
return DJI_ERROR_SYSTEM_MODULE_CODE_INVALID_PARAMETER;
}
if (!strcmp(USER_APP_NAME, "your_app_name") ||
!strcmp(USER_APP_ID, "your_app_id") ||
!strcmp(USER_APP_KEY, "your_app_key") ||
!strcmp(USER_BAUD_RATE, "your_app_license") ||
!strcmp(USER_DEVELOPER_ACCOUNT, "your_developer_account") ||
!strcmp(USER_BAUD_RATE, "your_baud_rate")) {
USER_LOG_ERROR(
"Please fill in correct user information to 'samples/sample_c++/platform/linux/manifold2/application/dji_sdk_app_info.h' file.");
return DJI_ERROR_SYSTEM_MODULE_CODE_INVALID_PARAMETER;
}
strncpy(userInfo->appName, USER_APP_NAME, sizeof(userInfo->appName) - 1);
memcpy(userInfo->appId, USER_APP_ID, USER_UTIL_MIN(sizeof(userInfo->appId), strlen(USER_APP_ID)));
memcpy(userInfo->appKey, USER_APP_KEY, USER_UTIL_MIN(sizeof(userInfo->appKey), strlen(USER_APP_KEY)));
memcpy(userInfo->appLicense, USER_APP_LICENSE,
USER_UTIL_MIN(sizeof(userInfo->appLicense), strlen(USER_APP_LICENSE)));
memcpy(userInfo->baudRate, USER_BAUD_RATE, USER_UTIL_MIN(sizeof(userInfo->baudRate), strlen(USER_BAUD_RATE)));
strncpy(userInfo->developerAccount, USER_DEVELOPER_ACCOUNT, sizeof(userInfo->developerAccount) - 1);
return DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS;
}
T_DjiReturnCode Application::DjiUser_LocalWriteFsInit(const char *path)
{
T_DjiReturnCode djiReturnCode = DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS;
char filePath[DJI_LOG_PATH_MAX_SIZE];
char systemCmd[DJI_SYSTEM_CMD_STR_MAX_SIZE];
char folderName[DJI_LOG_FOLDER_NAME_MAX_SIZE];
time_t currentTime = time(nullptr);
struct tm *localTime = localtime(&currentTime);
uint16_t logFileIndex = 0;
uint16_t currentLogFileIndex;
uint8_t ret;
if (localTime == nullptr) {
printf("Get local time error.\r\n");
return DJI_ERROR_SYSTEM_MODULE_CODE_SYSTEM_ERROR;
}
if (access(DJI_LOG_FOLDER_NAME, F_OK) != 0) {
sprintf(folderName, "mkdir %s", DJI_LOG_FOLDER_NAME);
ret = system(folderName);
if (ret != 0) {
printf("Create new log folder error, ret:%d.\r\n", ret);
return DJI_ERROR_SYSTEM_MODULE_CODE_SYSTEM_ERROR;
}
}
s_djiLogFileCnt = fopen(DJI_LOG_INDEX_FILE_NAME, "rb+");
if (s_djiLogFileCnt == nullptr) {
s_djiLogFileCnt = fopen(DJI_LOG_INDEX_FILE_NAME, "wb+");
if (s_djiLogFileCnt == nullptr) {
return DJI_ERROR_SYSTEM_MODULE_CODE_SYSTEM_ERROR;
}
} else {
ret = fseek(s_djiLogFileCnt, 0, SEEK_SET);
if (ret != 0) {
printf("Seek log count file error, ret: %d, errno: %d.\r\n", ret, errno);
return DJI_ERROR_SYSTEM_MODULE_CODE_SYSTEM_ERROR;
}
ret = fread((uint16_t * ) & logFileIndex, 1, sizeof(uint16_t), s_djiLogFileCnt);
if (ret != sizeof(uint16_t)) {
printf("Read log file index error.\r\n");
}
}
currentLogFileIndex = logFileIndex;
logFileIndex++;
ret = fseek(s_djiLogFileCnt, 0, SEEK_SET);
if (ret != 0) {
printf("Seek log file error, ret: %d, errno: %d.\r\n", ret, errno);
return DJI_ERROR_SYSTEM_MODULE_CODE_SYSTEM_ERROR;
}
ret = fwrite((uint16_t * ) & logFileIndex, 1, sizeof(uint16_t), s_djiLogFileCnt);
if (ret != sizeof(uint16_t)) {
printf("Write log file index error.\r\n");
fclose(s_djiLogFileCnt);
return DJI_ERROR_SYSTEM_MODULE_CODE_SYSTEM_ERROR;
}
fclose(s_djiLogFileCnt);
sprintf(filePath, "%s_%04d_%04d%02d%02d_%02d-%02d-%02d.log", path, currentLogFileIndex,
localTime->tm_year + 1900, localTime->tm_mon + 1, localTime->tm_mday,
localTime->tm_hour, localTime->tm_min, localTime->tm_sec);
s_djiLogFile = fopen(filePath, "wb+");
if (s_djiLogFile == nullptr) {
USER_LOG_ERROR("Open filepath time error.");
return DJI_ERROR_SYSTEM_MODULE_CODE_SYSTEM_ERROR;
}
if (logFileIndex >= DJI_LOG_MAX_COUNT) {
sprintf(systemCmd, "rm -rf %s_%04d*.log", path, currentLogFileIndex - DJI_LOG_MAX_COUNT);
ret = system(systemCmd);
if (ret != 0) {
printf("Remove file error, ret:%d.\r\n", ret);
return DJI_ERROR_SYSTEM_MODULE_CODE_SYSTEM_ERROR;
}
}
return djiReturnCode;
}
static void DjiUser_NormalExitHandler(int signalNum)
{
USER_UTIL_UNUSED(signalNum);
exit(0);
}
/****************** (C) COPYRIGHT DJI Innovations *****END OF FILE****/

View File

@ -0,0 +1,67 @@
/**
********************************************************************
* @file dji_application.hpp
* @brief This is the header file for "dji_application.cpp", defining the structure and
* (exported) function prototypes.
*
* @copyright (c) 2021 DJI. All rights reserved.
*
* All information contained herein is, and remains, the property of DJI.
* The intellectual and technical concepts contained herein are proprietary
* to DJI and may be covered by U.S. and foreign patents, patents in process,
* and protected by trade secret or copyright law. Dissemination of this
* information, including but not limited to data and other proprietary
* material(s) incorporated within the information, in any form, is strictly
* prohibited without the express written consent of DJI.
*
* If you receive this source code without DJIs authorization, you may not
* further disseminate the information, and you must immediately remove the
* source code and notify DJI of its removal. DJI reserves the right to pursue
* legal actions against you for any loss(es) or damage(s) caused by your
* failure to do so.
*
*********************************************************************
*/
/* Define to prevent recursive inclusion -------------------------------------*/
#ifndef APPLICATION_H
#define APPLICATION_H
/* Includes ------------------------------------------------------------------*/
#include <iostream>
#include <fstream>
#include "dji_typedef.h"
#include "dji_core.h"
#ifdef __cplusplus
extern "C" {
#endif
/* Exported constants --------------------------------------------------------*/
/* Exported types ------------------------------------------------------------*/
using namespace std;
class Application {
public:
Application(int argc, char **argv);
~Application();
private:
static void DjiUser_SetupEnvironment();
static void DjiUser_ApplicationStart();
static T_DjiReturnCode DjiUser_PrintConsole(const uint8_t *data, uint16_t dataLen);
static T_DjiReturnCode DjiUser_LocalWrite(const uint8_t *data, uint16_t dataLen);
static T_DjiReturnCode DjiUser_FillInUserInfo(T_DjiUserInfo *userInfo);
static T_DjiReturnCode DjiUser_LocalWriteFsInit(const char *path);
};
/* Exported functions --------------------------------------------------------*/
#ifdef __cplusplus
}
#endif
#endif // APPLICATION_H
/************************ (C) COPYRIGHT DJI Innovations *******END OF FILE******/

View File

@ -0,0 +1,55 @@
/**
********************************************************************
* @file dji_sdk_app_info.h
* @brief This is the header file for defining the structure and (exported) function prototypes.
*
* @copyright (c) 2018 DJI. All rights reserved.
*
* All information contained herein is, and remains, the property of DJI.
* The intellectual and technical concepts contained herein are proprietary
* to DJI and may be covered by U.S. and foreign patents, patents in process,
* and protected by trade secret or copyright law. Dissemination of this
* information, including but not limited to data and other proprietary
* material(s) incorporated within the information, in any form, is strictly
* prohibited without the express written consent of DJI.
*
* If you receive this source code without DJIs authorization, you may not
* further disseminate the information, and you must immediately remove the
* source code and notify DJI of its removal. DJI reserves the right to pursue
* legal actions against you for any loss(es) or damage(s) caused by your
* failure to do so.
*
*********************************************************************
*/
/* Define to prevent recursive inclusion -------------------------------------*/
#ifndef DJI_SDK_APP_INFO_H
#define DJI_SDK_APP_INFO_H
/* Includes ------------------------------------------------------------------*/
#ifdef __cplusplus
extern "C" {
#endif
/* Exported constants --------------------------------------------------------*/
// ATTENTION: User must goto https://developer.dji.com/user/apps/#all to create your own dji sdk application, get dji sdk application
// information then fill in the application information here.
#define USER_APP_NAME "your_app_name"
#define USER_APP_ID "your_app_id"
#define USER_APP_KEY "your_app_key"
#define USER_APP_LICENSE "your_app_license"
#define USER_DEVELOPER_ACCOUNT "your_developer_account"
#define USER_BAUD_RATE "460800"
/* Exported types ------------------------------------------------------------*/
/* Exported functions --------------------------------------------------------*/
#ifdef __cplusplus
}
#endif
#endif // DJI_SDK_APP_INFO_H
/************************ (C) COPYRIGHT DJI Innovations *******END OF FILE******/

View File

@ -0,0 +1,54 @@
/**
********************************************************************
* @file dji_sdk_config.h
* @brief This is the header file for "dji_config.c", defining the structure and
* (exported) function prototypes.
*
* @copyright (c) 2021 DJI. All rights reserved.
*
* All information contained herein is, and remains, the property of DJI.
* The intellectual and technical concepts contained herein are proprietary
* to DJI and may be covered by U.S. and foreign patents, patents in process,
* and protected by trade secret or copyright law. Dissemination of this
* information, including but not limited to data and other proprietary
* material(s) incorporated within the information, in any form, is strictly
* prohibited without the express written consent of DJI.
*
* If you receive this source code without DJIs authorization, you may not
* further disseminate the information, and you must immediately remove the
* source code and notify DJI of its removal. DJI reserves the right to pursue
* legal actions against you for any loss(es) or damage(s) caused by your
* failure to do so.
*
*********************************************************************
*/
/* Define to prevent recursive inclusion -------------------------------------*/
#ifndef DJI_SDK_CONFIG_H
#define DJI_SDK_CONFIG_H
/* Includes ------------------------------------------------------------------*/
#ifdef __cplusplus
extern "C" {
#endif
/* Exported constants --------------------------------------------------------*/
#define DJI_USE_ONLY_UART (0)
#define DJI_USE_UART_AND_USB_BULK_DEVICE (1)
#define DJI_USE_UART_AND_NETWORK_DEVICE (2)
/*!< Attention: Select your hardware connection mode here.
* */
#define CONFIG_HARDWARE_CONNECTION DJI_USE_UART_AND_NETWORK_DEVICE
/* Exported types ------------------------------------------------------------*/
/* Exported functions --------------------------------------------------------*/
#ifdef __cplusplus
}
#endif
#endif // DJI_SDK_CONFIG_H
/************************ (C) COPYRIGHT DJI Innovations *******END OF FILE******/

View File

@ -0,0 +1,227 @@
/**
********************************************************************
* @file main.cpp
* @brief
*
* @copyright (c) 2021 DJI. All rights reserved.
*
* All information contained herein is, and remains, the property of DJI.
* The intellectual and technical concepts contained herein are proprietary
* to DJI and may be covered by U.S. and foreign patents, patents in process,
* and protected by trade secret or copyright law. Dissemination of this
* information, including but not limited to data and other proprietary
* material(s) incorporated within the information, in any form, is strictly
* prohibited without the express written consent of DJI.
*
* If you receive this source code without DJIs authorization, you may not
* further disseminate the information, and you must immediately remove the
* source code and notify DJI of its removal. DJI reserves the right to pursue
* legal actions against you for any loss(es) or damage(s) caused by your
* failure to do so.
*
*********************************************************************
*/
/* Includes ------------------------------------------------------------------*/
#include <liveview/test_liveview_entry.hpp>
#include <perception/test_perception_entry.hpp>
#include <flight_control/test_flight_control.h>
#include <gimbal/test_gimbal_entry.hpp>
#include <hms/test_hms.h>
#include <waypoint_v2/test_waypoint_v2.h>
#include <waypoint_v3/test_waypoint_v3.h>
#include <gimbal_manager/test_gimbal_manager.h>
#include "application.hpp"
#include "fc_subscription/test_fc_subscription.h"
#include <gimbal_emu/test_payload_gimbal_emu.h>
#include <camera_emu/test_payload_cam_emu_media.h>
#include <camera_emu/test_payload_cam_emu_base.h>
#include <dji_logger.h>
#include "widget/test_widget.h"
#include "widget/test_widget_speaker.h"
#include <power_management/test_power_management.h>
#include "data_transmission/test_data_transmission.h"
#include <camera_manager/test_camera_manager.h>
#include "camera_manager/test_camera_manager_entry.h"
/* Private constants ---------------------------------------------------------*/
/* Private types -------------------------------------------------------------*/
/* Private values -------------------------------------------------------------*/
/* Private functions declaration ---------------------------------------------*/
static T_DjiReturnCode DjiTest_HighPowerApplyPinInit();
static T_DjiReturnCode DjiTest_WriteHighPowerApplyPin(E_DjiPowerManagementPinState pinState);
/* Exported functions definition ---------------------------------------------*/
int main(int argc, char **argv)
{
Application application(argc, argv);
char inputChar;
T_DjiOsalHandler *osalHandler = DjiPlatform_GetOsalHandler();
T_DjiReturnCode returnCode;
T_DjiTestApplyHighPowerHandler applyHighPowerHandler;
start:
std::cout
<< "\n"
<< "| Available commands: |\n"
<< "| [0] Fc subscribe sample - subscribe quaternion and gps data |\n"
<< "| [1] Flight controller sample - take off landing |\n"
<< "| [2] Flight controller sample - take off position ctrl landing |\n"
<< "| [3] Flight controller sample - take off go home force landing |\n"
<< "| [4] Flight controller sample - take off velocity ctrl landing |\n"
<< "| [5] Flight controller sample - arrest flying |\n"
<< "| [6] Flight controller sample - set get parameters |\n"
<< "| [7] Hms info sample - get health manger system info |\n"
<< "| [8] Waypoint 2.0 sample - run airline mission by settings (only support on M300 RTK) |\n"
<< "| [9] Waypoint 3.0 sample - run airline mission by kmz file (not support on M300 RTK) |\n"
<< "| [a] Gimbal manager sample |\n"
<< "| [c] Camera stream view sample - display the camera video stream |\n"
<< "| [d] Stereo vision view sample - display the stereo image |\n"
<< "| [e] Start camera all features sample - you can operate the camera on DJI Pilot |\n"
<< "| [f] Start gimbal all features sample - you can operate the gimbal on DJI Pilot |\n"
<< "| [g] Start widget all features sample - you can operate the widget on DJI Pilot |\n"
<< "| [h] Start widget speaker sample - you can operate the speaker on DJI Pilot2 |\n"
<< "| [i] Start power management sample - you will see notification when aircraft power off |\n"
<< "| [j] Start data transmission sample - you can send or recv custom data on MSDK demo |\n"
<< "| [k] Run camera manager sample - you can test camera's functions interactively |\n"
<< std::endl;
std::cin >> inputChar;
switch (inputChar) {
case '0':
DjiTest_FcSubscriptionRunSample();
break;
case '1':
DjiTest_FlightControlRunSample(E_DJI_TEST_FLIGHT_CTRL_SAMPLE_SELECT_TAKE_OFF_LANDING);
break;
case '2':
DjiTest_FlightControlRunSample(E_DJI_TEST_FLIGHT_CTRL_SAMPLE_SELECT_TAKE_OFF_POSITION_CTRL_LANDING);
break;
case '3':
DjiTest_FlightControlRunSample(E_DJI_TEST_FLIGHT_CTRL_SAMPLE_SELECT_TAKE_OFF_GO_HOME_FORCE_LANDING);
break;
case '4':
DjiTest_FlightControlRunSample(E_DJI_TEST_FLIGHT_CTRL_SAMPLE_SELECT_TAKE_OFF_VELOCITY_CTRL_LANDING);
break;
case '5':
DjiTest_FlightControlRunSample(E_DJI_TEST_FLIGHT_CTRL_SAMPLE_SELECT_ARREST_FLYING);
break;
case '6':
DjiTest_FlightControlRunSample(E_DJI_TEST_FLIGHT_CTRL_SAMPLE_SELECT_SET_GET_PARAM);
break;
case '7':
DjiTest_HmsRunSample();
break;
case '8':
DjiTest_WaypointV2RunSample();
break;
case '9':
DjiTest_WaypointV3RunSample();
break;
case 'a':
DjiUser_RunGimbalManagerSample();
break;
case 'c':
DjiUser_RunCameraStreamViewSample();
break;
case 'd':
DjiUser_RunStereoVisionViewSample();
break;
case 'e':
returnCode = DjiTest_CameraEmuBaseStartService();
if (returnCode != DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS) {
USER_LOG_ERROR("camera emu common init error");
break;
}
if (DjiPlatform_GetSocketHandler() != nullptr) {
returnCode = DjiTest_CameraEmuMediaStartService();
if (returnCode != DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS) {
USER_LOG_ERROR("camera emu media init error");
break;
}
}
USER_LOG_INFO("Start camera all feautes sample successfully");
break;
case 'f':
if (DjiTest_GimbalStartService() != DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS) {
USER_LOG_ERROR("psdk gimbal init error");
break;
}
USER_LOG_INFO("Start gimbal all feautes sample successfully");
break;
case 'g':
returnCode = DjiTest_WidgetStartService();
if (returnCode != DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS) {
USER_LOG_ERROR("widget sample init error");
break;
}
USER_LOG_INFO("Start widget all feautes sample successfully");
break;
case 'h':
returnCode = DjiTest_WidgetSpeakerStartService();
if (returnCode != DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS) {
USER_LOG_ERROR("widget speaker test init error");
break;
}
USER_LOG_INFO("Start widget speaker sample successfully");
break;
case 'i':
applyHighPowerHandler.pinInit = DjiTest_HighPowerApplyPinInit;
applyHighPowerHandler.pinWrite = DjiTest_WriteHighPowerApplyPin;
returnCode = DjiTest_RegApplyHighPowerHandler(&applyHighPowerHandler);
if (returnCode != DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS) {
USER_LOG_ERROR("regsiter apply high power handler error");
break;
}
returnCode = DjiTest_PowerManagementStartService();
if (returnCode != DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS) {
USER_LOG_ERROR("power management init error");
break;
}
USER_LOG_INFO("Start power management sample successfully");
break;
case 'j':
returnCode = DjiTest_DataTransmissionStartService();
if (returnCode != DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS) {
USER_LOG_ERROR("data transmission sample init error");
break;
}
USER_LOG_INFO("Start data transmission sample successfully");
break;
case 'k':
DjiUser_RunCameraManagerSample();
break;
default:
break;
}
osalHandler->TaskSleepMs(2000);
goto start;
}
/* Private functions definition-----------------------------------------------*/
static T_DjiReturnCode DjiTest_HighPowerApplyPinInit()
{
return DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS;
}
static T_DjiReturnCode DjiTest_WriteHighPowerApplyPin(E_DjiPowerManagementPinState pinState)
{
//attention: please pull up the HWPR pin state by hardware.
return DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS;
}
/****************** (C) COPYRIGHT DJI Innovations *****END OF FILE****/

View File

@ -0,0 +1,92 @@
/**
********************************************************************
* @file hal_network.c
* @version V2.0.0
* @date 3/27/20
* @brief
*
* @copyright (c) 2021 DJI. All rights reserved.
*
* All information contained herein is, and remains, the property of DJI.
* The intellectual and technical concepts contained herein are proprietary
* to DJI and may be covered by U.S. and foreign patents, patents in process,
* and protected by trade secret or copyright law. Dissemination of this
* information, including but not limited to data and other proprietary
* material(s) incorporated within the information, in any form, is strictly
* prohibited without the express written consent of DJI.
*
* If you receive this source code without DJIs authorization, you may not
* further disseminate the information, and you must immediately remove the
* source code and notify DJI of its removal. DJI reserves the right to pursue
* legal actions against you for any loss(es) or damage(s) caused by your
* failure to do so.
*
*********************************************************************
*/
/* Includes ------------------------------------------------------------------*/
#include "string.h"
#include "stdlib.h"
#include "stdio.h"
#include "hal_network.h"
#include "dji_logger.h"
/* Private constants ---------------------------------------------------------*/
/* Private types -------------------------------------------------------------*/
/* Private values -------------------------------------------------------------*/
/* Private functions declaration ---------------------------------------------*/
/* Exported functions definition ---------------------------------------------*/
T_DjiReturnCode HalNetWork_Init(const char *ipAddr, const char *netMask, T_DjiNetworkHandle *halObj)
{
int32_t ret;
char cmdStr[LINUX_CMD_STR_MAX_SIZE];
if (ipAddr == NULL || netMask == NULL) {
USER_LOG_ERROR("hal network config param error");
return DJI_ERROR_SYSTEM_MODULE_CODE_INVALID_PARAMETER;
}
//Attention: need root permission to config ip addr and netmask.
memset(cmdStr, 0, sizeof(cmdStr));
snprintf(cmdStr, sizeof(cmdStr), "ifconfig %s up", LINUX_NETWORK_DEV);
ret = system(cmdStr);
if (ret != DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS) {
USER_LOG_ERROR("Can't open the network."
"Probably the program not execute with root permission."
"Please use the root permission to execute the program.");
return DJI_ERROR_SYSTEM_MODULE_CODE_SYSTEM_ERROR;
}
snprintf(cmdStr, sizeof(cmdStr), "ifconfig %s %s netmask %s", LINUX_NETWORK_DEV, ipAddr, netMask);
ret = system(cmdStr);
if (ret != DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS) {
USER_LOG_ERROR("Can't config the ip address of network."
"Probably the program not execute with root permission."
"Please use the root permission to execute the program.");
return DJI_ERROR_SYSTEM_MODULE_CODE_SYSTEM_ERROR;
}
return DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS;
}
T_DjiReturnCode HalNetWork_DeInit(T_DjiNetworkHandle halObj)
{
return DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS;
}
T_DjiReturnCode HalNetWork_GetDeviceInfo(T_DjiHalNetworkDeviceInfo *deviceInfo)
{
deviceInfo->usbNetAdapter.vid = USB_NET_ADAPTER_VID;
deviceInfo->usbNetAdapter.pid = USB_NET_ADAPTER_PID;
return DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS;
}
/* Private functions definition-----------------------------------------------*/
/****************** (C) COPYRIGHT DJI Innovations *****END OF FILE****/

View File

@ -0,0 +1,73 @@
/**
********************************************************************
* @file hal_network.h
* @brief This is the header file for "hal_network.c", defining the structure and
* (exported) function prototypes.
*
* @copyright (c) 2021 DJI. All rights reserved.
*
* All information contained herein is, and remains, the property of DJI.
* The intellectual and technical concepts contained herein are proprietary
* to DJI and may be covered by U.S. and foreign patents, patents in process,
* and protected by trade secret or copyright law. Dissemination of this
* information, including but not limited to data and other proprietary
* material(s) incorporated within the information, in any form, is strictly
* prohibited without the express written consent of DJI.
*
* If you receive this source code without DJIs authorization, you may not
* further disseminate the information, and you must immediately remove the
* source code and notify DJI of its removal. DJI reserves the right to pursue
* legal actions against you for any loss(es) or damage(s) caused by your
* failure to do so.
*
*********************************************************************
*/
/* Define to prevent recursive inclusion -------------------------------------*/
#ifndef HAL_NETWORK_H
#define HAL_NETWORK_H
/* Includes ------------------------------------------------------------------*/
#include "dji_platform.h"
#ifdef __cplusplus
extern "C" {
#endif
/* Exported constants --------------------------------------------------------*/
/** @attention User can config network card name here, if your device is not MF2C/G, please comment below and add your
* NIC name micro define as #define 'LINUX_NETWORK_DEV "your NIC name"'.
*/
#ifdef PLATFORM_ARCH_x86_64
#define LINUX_NETWORK_DEV "enxf8e43b7bbc2c"
#else
#define LINUX_NETWORK_DEV "l4tbr0"
#endif
/**
* @attention
*/
#ifdef PLATFORM_ARCH_x86_64
#define USB_NET_ADAPTER_VID (0x0B95)
#define USB_NET_ADAPTER_PID (0x1790)
#else
#define USB_NET_ADAPTER_VID (0x0955)
#define USB_NET_ADAPTER_PID (0x7020)
#endif
#define LINUX_CMD_STR_MAX_SIZE (128)
/* Exported types ------------------------------------------------------------*/
/* Exported functions --------------------------------------------------------*/
T_DjiReturnCode HalNetWork_Init(const char *ipAddr, const char *netMask, T_DjiNetworkHandle *halObj);
T_DjiReturnCode HalNetWork_DeInit(T_DjiNetworkHandle halObj);
T_DjiReturnCode HalNetWork_GetDeviceInfo(T_DjiHalNetworkDeviceInfo *deviceInfo);
#ifdef __cplusplus
}
#endif
#endif // HAL_NETWORK_H
/************************ (C) COPYRIGHT DJI Innovations *******END OF FILE******/

View File

@ -0,0 +1,260 @@
/**
********************************************************************
* @file hal_uart.c
* @brief
*
* @copyright (c) 2021 DJI. All rights reserved.
*
* All information contained herein is, and remains, the property of DJI.
* The intellectual and technical concepts contained herein are proprietary
* to DJI and may be covered by U.S. and foreign patents, patents in process,
* and protected by trade secret or copyright law. Dissemination of this
* information, including but not limited to data and other proprietary
* material(s) incorporated within the information, in any form, is strictly
* prohibited without the express written consent of DJI.
*
* If you receive this source code without DJIs authorization, you may not
* further disseminate the information, and you must immediately remove the
* source code and notify DJI of its removal. DJI reserves the right to pursue
* legal actions against you for any loss(es) or damage(s) caused by your
* failure to do so.
*
*********************************************************************
*/
/* Includes ------------------------------------------------------------------*/
#include <dji_logger.h>
#include "hal_uart.h"
/* Private constants ---------------------------------------------------------*/
#define UART_DEV_NAME_STR_SIZE (128)
#define DJI_SYSTEM_CMD_STR_MAX_SIZE (64)
#define DJI_SYSTEM_RESULT_STR_MAX_SIZE (128)
/* Private types -------------------------------------------------------------*/
typedef struct {
int uartFd;
} T_UartHandleStruct;
/* Private values -------------------------------------------------------------*/
/* Private functions declaration ---------------------------------------------*/
/* Exported functions definition ---------------------------------------------*/
T_DjiReturnCode HalUart_Init(E_DjiHalUartNum uartNum, uint32_t baudRate, T_DjiUartHandle *uartHandle)
{
T_UartHandleStruct *uartHandleStruct;
struct termios options;
struct flock lock;
T_DjiReturnCode returnCode = DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS;
char uartName[UART_DEV_NAME_STR_SIZE];
char systemCmd[DJI_SYSTEM_CMD_STR_MAX_SIZE];
char *ret = NULL;
char lineBuf[DJI_SYSTEM_RESULT_STR_MAX_SIZE] = {0};
FILE *fp;
uartHandleStruct = malloc(sizeof(T_UartHandleStruct));
if (uartHandleStruct == NULL) {
return DJI_ERROR_SYSTEM_MODULE_CODE_MEMORY_ALLOC_FAILED;
}
if (uartNum == DJI_HAL_UART_NUM_0) {
strcpy(uartName, LINUX_UART_DEV1);
} else if (uartNum == DJI_HAL_UART_NUM_1) {
strcpy(uartName, LINUX_UART_DEV2);
} else {
goto free_uart_handle;
}
#ifdef USE_CLION_DEBUG
sprintf(systemCmd, "ls -l %s", uartName);
fp = popen(systemCmd, "r");
if (fp == NULL) {
goto free_uart_handle;
}
ret = fgets(lineBuf, sizeof(lineBuf), fp);
if (ret == NULL) {
goto close_fp;
}
if (strstr(lineBuf, "crwxrwxrwx") == NULL) {
USER_LOG_ERROR("Can't operation the device. "
"Probably the device has not operation permission. "
"Please execute command 'sudo chmod 777 %s' to add permission. ", uartName);
goto close_fp;
}
#else
sprintf(systemCmd, "chmod 777 %s", uartName);
fp = popen(systemCmd, "r");
if (fp == NULL) {
return DJI_ERROR_SYSTEM_MODULE_CODE_SYSTEM_ERROR;
}
#endif
uartHandleStruct->uartFd = open(uartName, (unsigned) O_RDWR | (unsigned) O_NOCTTY | (unsigned) O_NDELAY);
if (uartHandleStruct->uartFd == -1) {
goto close_fp;
}
// Forbid multiple psdk programs to access the serial port
lock.l_type = F_WRLCK;
lock.l_pid = getpid();
lock.l_whence = SEEK_SET;
lock.l_start = 0;
lock.l_len = 0;
if (fcntl(uartHandleStruct->uartFd, F_GETLK, &lock) < 0) {
goto close_uart_fd;
}
if (lock.l_type != F_UNLCK) {
goto close_uart_fd;
}
lock.l_type = F_WRLCK;
lock.l_pid = getpid();
lock.l_whence = SEEK_SET;
lock.l_start = 0;
lock.l_len = 0;
if (fcntl(uartHandleStruct->uartFd, F_SETLKW, &lock) < 0) {
goto close_uart_fd;
}
if (tcgetattr(uartHandleStruct->uartFd, &options) != 0) {
goto close_uart_fd;
}
switch (baudRate) {
case 115200:
cfsetispeed(&options, B115200);
cfsetospeed(&options, B115200);
break;
case 230400:
cfsetispeed(&options, B230400);
cfsetospeed(&options, B230400);
break;
case 460800:
cfsetispeed(&options, B460800);
cfsetospeed(&options, B460800);
break;
case 921600:
cfsetispeed(&options, B921600);
cfsetospeed(&options, B921600);
break;
case 1000000:
cfsetispeed(&options, B1000000);
cfsetospeed(&options, B1000000);
break;
default:
goto close_uart_fd;
}
options.c_cflag |= (unsigned) CLOCAL;
options.c_cflag |= (unsigned) CREAD;
options.c_cflag &= ~(unsigned) CRTSCTS;
options.c_cflag &= ~(unsigned) CSIZE;
options.c_cflag |= (unsigned) CS8;
options.c_cflag &= ~(unsigned) PARENB;
options.c_iflag &= ~(unsigned) INPCK;
options.c_cflag &= ~(unsigned) CSTOPB;
options.c_oflag &= ~(unsigned) OPOST;
options.c_lflag &= ~((unsigned) ICANON | (unsigned) ECHO | (unsigned) ECHOE | (unsigned) ISIG);
options.c_iflag &= ~((unsigned) BRKINT | (unsigned) ICRNL | (unsigned) INPCK | (unsigned) ISTRIP | (unsigned) IXON);
options.c_cc[VTIME] = 0;
options.c_cc[VMIN] = 0;
tcflush(uartHandleStruct->uartFd, TCIFLUSH);
if (tcsetattr(uartHandleStruct->uartFd, TCSANOW, &options) != 0) {
goto close_uart_fd;
}
*uartHandle = uartHandleStruct;
pclose(fp);
return returnCode;
close_uart_fd:
close(uartHandleStruct->uartFd);
close_fp:
pclose(fp);
free_uart_handle:
free(uartHandleStruct);
return DJI_ERROR_SYSTEM_MODULE_CODE_SYSTEM_ERROR;
}
T_DjiReturnCode HalUart_DeInit(T_DjiUartHandle uartHandle)
{
int32_t ret;
T_UartHandleStruct *uartHandleStruct = (T_UartHandleStruct *) uartHandle;
if (uartHandle == NULL) {
return DJI_ERROR_SYSTEM_MODULE_CODE_UNKNOWN;
}
ret = close(uartHandleStruct->uartFd);
if (ret < 0) {
return DJI_ERROR_SYSTEM_MODULE_CODE_SYSTEM_ERROR;
}
free(uartHandleStruct);
return DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS;
}
T_DjiReturnCode HalUart_WriteData(T_DjiUartHandle uartHandle, const uint8_t *buf, uint32_t len, uint32_t *realLen)
{
int32_t ret;
T_UartHandleStruct *uartHandleStruct = (T_UartHandleStruct *) uartHandle;
if (uartHandle == NULL || buf == NULL || len == 0 || realLen == NULL) {
return DJI_ERROR_SYSTEM_MODULE_CODE_INVALID_PARAMETER;
}
ret = write(uartHandleStruct->uartFd, buf, len);
if (ret >= 0) {
*realLen = ret;
} else {
return DJI_ERROR_SYSTEM_MODULE_CODE_SYSTEM_ERROR;
}
return DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS;
}
T_DjiReturnCode HalUart_ReadData(T_DjiUartHandle uartHandle, uint8_t *buf, uint32_t len, uint32_t *realLen)
{
int32_t ret;
T_UartHandleStruct *uartHandleStruct = (T_UartHandleStruct *) uartHandle;
if (uartHandle == NULL || buf == NULL || len == 0 || realLen == NULL) {
return DJI_ERROR_SYSTEM_MODULE_CODE_INVALID_PARAMETER;
}
ret = read(uartHandleStruct->uartFd, buf, len);
if (ret >= 0) {
*realLen = ret;
} else {
return DJI_ERROR_SYSTEM_MODULE_CODE_SYSTEM_ERROR;
}
return DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS;
}
T_DjiReturnCode HalUart_GetStatus(E_DjiHalUartNum uartNum, T_DjiUartStatus *status)
{
if (uartNum == DJI_HAL_UART_NUM_0) {
status->isConnect = true;
} else if (uartNum == DJI_HAL_UART_NUM_1) {
status->isConnect = true;
} else {
return DJI_ERROR_SYSTEM_MODULE_CODE_INVALID_PARAMETER;
}
return DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS;
}
/* Private functions definition-----------------------------------------------*/
/****************** (C) COPYRIGHT DJI Innovations *****END OF FILE****/

View File

@ -0,0 +1,65 @@
/**
********************************************************************
* @file hal_uart.h
* @brief This is the header file for "hal_uart.c", defining the structure and
* (exported) function prototypes.
*
* @copyright (c) 2021 DJI. All rights reserved.
*
* All information contained herein is, and remains, the property of DJI.
* The intellectual and technical concepts contained herein are proprietary
* to DJI and may be covered by U.S. and foreign patents, patents in process,
* and protected by trade secret or copyright law. Dissemination of this
* information, including but not limited to data and other proprietary
* material(s) incorporated within the information, in any form, is strictly
* prohibited without the express written consent of DJI.
*
* If you receive this source code without DJIs authorization, you may not
* further disseminate the information, and you must immediately remove the
* source code and notify DJI of its removal. DJI reserves the right to pursue
* legal actions against you for any loss(es) or damage(s) caused by your
* failure to do so.
*
*********************************************************************
*/
/* Define to prevent recursive inclusion -------------------------------------*/
#ifndef HAL_UART_H
#define HAL_UART_H
/* Includes ------------------------------------------------------------------*/
#include "stdint.h"
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <termios.h>
#include <unistd.h>
#include <string.h>
#include "stdlib.h"
#include "dji_platform.h"
#ifdef __cplusplus
extern "C" {
#endif
/* Exported constants --------------------------------------------------------*/
//User can config dev based on there environmental conditions
#define LINUX_UART_DEV1 "/dev/ttyUSB0"
#define LINUX_UART_DEV2 "/dev/ttyACM0"
/* Exported types ------------------------------------------------------------*/
/* Exported functions --------------------------------------------------------*/
T_DjiReturnCode HalUart_Init(E_DjiHalUartNum uartNum, uint32_t baudRate, T_DjiUartHandle *uartHandle);
T_DjiReturnCode HalUart_DeInit(T_DjiUartHandle uartHandle);
T_DjiReturnCode HalUart_WriteData(T_DjiUartHandle uartHandle, const uint8_t *buf, uint32_t len, uint32_t *realLen);
T_DjiReturnCode HalUart_ReadData(T_DjiUartHandle uartHandle, uint8_t *buf, uint32_t len, uint32_t *realLen);
T_DjiReturnCode HalUart_GetStatus(E_DjiHalUartNum uartNum, T_DjiUartStatus *status);
#ifdef __cplusplus
}
#endif
#endif // HAL_UART_H
/************************ (C) COPYRIGHT DJI Innovations *******END OF FILE******/

View File

@ -0,0 +1,224 @@
/**
********************************************************************
* @file hal_usb_bulk.c
* @brief
*
* @copyright (c) 2021 DJI. All rights reserved.
*
* All information contained herein is, and remains, the property of DJI.
* The intellectual and technical concepts contained herein are proprietary
* to DJI and may be covered by U.S. and foreign patents, patents in process,
* and protected by trade secret or copyright law. Dissemination of this
* information, including but not limited to data and other proprietary
* material(s) incorporated within the information, in any form, is strictly
* prohibited without the express written consent of DJI.
*
* If you receive this source code without DJIs authorization, you may not
* further disseminate the information, and you must immediately remove the
* source code and notify DJI of its removal. DJI reserves the right to pursue
* legal actions against you for any loss(es) or damage(s) caused by your
* failure to do so.
*
*********************************************************************
*/
/* Includes ------------------------------------------------------------------*/
#include "hal_usb_bulk.h"
#include "dji_logger.h"
/* Private constants ---------------------------------------------------------*/
#define LINUX_USB_BULK_TRANSFER_TIMEOUT_MS (50)
#define LINUX_USB_BULK_TRANSFER_WAIT_FOREVER (-1)
/* Private types -------------------------------------------------------------*/
typedef struct {
#ifdef LIBUSB_INSTALLED
libusb_device_handle *handle;
#else
void *handle;
#endif
int32_t ep1;
int32_t ep2;
uint32_t interfaceNum;
T_DjiHalUsbBulkInfo usbBulkInfo;
} T_HalUsbBulkObj;
/* Private values -------------------------------------------------------------*/
/* Private functions declaration ---------------------------------------------*/
/* Exported functions definition ---------------------------------------------*/
T_DjiReturnCode HalUsbBulk_Init(T_DjiHalUsbBulkInfo usbBulkInfo, T_DjiUsbBulkHandle *usbBulkHandle)
{
int32_t ret;
struct libusb_device_handle *handle = NULL;
*usbBulkHandle = malloc(sizeof(T_HalUsbBulkObj));
if (*usbBulkHandle == NULL) {
return DJI_ERROR_SYSTEM_MODULE_CODE_SYSTEM_ERROR;
}
if (usbBulkInfo.isUsbHost == true) {
#ifdef LIBUSB_INSTALLED
ret = libusb_init(NULL);
if (ret < 0) {
return DJI_ERROR_SYSTEM_MODULE_CODE_SYSTEM_ERROR;
}
handle = libusb_open_device_with_vid_pid(NULL, usbBulkInfo.vid, usbBulkInfo.pid);
if (handle == NULL) {
return DJI_ERROR_SYSTEM_MODULE_CODE_SYSTEM_ERROR;
}
ret = libusb_claim_interface(handle, usbBulkInfo.channelInfo.interfaceNum);
if (ret != LIBUSB_SUCCESS) {
printf("libusb claim interface error");
libusb_close(handle);
return DJI_ERROR_SYSTEM_MODULE_CODE_SYSTEM_ERROR;
}
((T_HalUsbBulkObj *) *usbBulkHandle)->handle = handle;
memcpy(&((T_HalUsbBulkObj *) *usbBulkHandle)->usbBulkInfo, &usbBulkInfo, sizeof(usbBulkInfo));
#endif
} else {
((T_HalUsbBulkObj *) *usbBulkHandle)->handle = handle;
memcpy(&((T_HalUsbBulkObj *) *usbBulkHandle)->usbBulkInfo, &usbBulkInfo, sizeof(usbBulkInfo));
((T_HalUsbBulkObj *) *usbBulkHandle)->interfaceNum = usbBulkInfo.channelInfo.interfaceNum;
if (usbBulkInfo.channelInfo.interfaceNum == LINUX_USB_BULK1_INTERFACE_NUM) {
((T_HalUsbBulkObj *) *usbBulkHandle)->ep1 = open(LINUX_USB_BULK1_EP_OUT_FD, O_RDWR);
if (((T_HalUsbBulkObj *) *usbBulkHandle)->ep1 < 0) {
return DJI_ERROR_SYSTEM_MODULE_CODE_SYSTEM_ERROR;
}
((T_HalUsbBulkObj *) *usbBulkHandle)->ep2 = open(LINUX_USB_BULK1_EP_IN_FD, O_RDWR);
if (((T_HalUsbBulkObj *) *usbBulkHandle)->ep2 < 0) {
return DJI_ERROR_SYSTEM_MODULE_CODE_SYSTEM_ERROR;
}
} else if (usbBulkInfo.channelInfo.interfaceNum == LINUX_USB_BULK2_INTERFACE_NUM) {
((T_HalUsbBulkObj *) *usbBulkHandle)->ep1 = open(LINUX_USB_BULK2_EP_OUT_FD, O_RDWR);
if (((T_HalUsbBulkObj *) *usbBulkHandle)->ep1 < 0) {
return DJI_ERROR_SYSTEM_MODULE_CODE_SYSTEM_ERROR;
}
((T_HalUsbBulkObj *) *usbBulkHandle)->ep2 = open(LINUX_USB_BULK2_EP_IN_FD, O_RDWR);
if (((T_HalUsbBulkObj *) *usbBulkHandle)->ep2 < 0) {
return DJI_ERROR_SYSTEM_MODULE_CODE_SYSTEM_ERROR;
}
}
}
return DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS;
}
T_DjiReturnCode HalUsbBulk_DeInit(T_DjiUsbBulkHandle usbBulkHandle)
{
struct libusb_device_handle *handle = NULL;
T_DjiOsalHandler *osalHandler = DjiPlatform_GetOsalHandler();
if (usbBulkHandle == NULL) {
return DJI_ERROR_SYSTEM_MODULE_CODE_SYSTEM_ERROR;
}
handle = ((T_HalUsbBulkObj *) usbBulkHandle)->handle;
if (((T_HalUsbBulkObj *) usbBulkHandle)->usbBulkInfo.isUsbHost == true) {
#ifdef LIBUSB_INSTALLED
libusb_release_interface(handle, ((T_HalUsbBulkObj *) usbBulkHandle)->usbBulkInfo.channelInfo.interfaceNum);
osalHandler->TaskSleepMs(100);
libusb_exit(NULL);
#endif
} else {
close(((T_HalUsbBulkObj *) usbBulkHandle)->ep1);
close(((T_HalUsbBulkObj *) usbBulkHandle)->ep2);
}
free(usbBulkHandle);
return DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS;
}
T_DjiReturnCode HalUsbBulk_WriteData(T_DjiUsbBulkHandle usbBulkHandle, const uint8_t *buf, uint32_t len,
uint32_t *realLen)
{
int32_t ret;
int32_t actualLen;
struct libusb_device_handle *handle = NULL;
if (usbBulkHandle == NULL) {
return DJI_ERROR_SYSTEM_MODULE_CODE_SYSTEM_ERROR;
}
handle = ((T_HalUsbBulkObj *) usbBulkHandle)->handle;
if (((T_HalUsbBulkObj *) usbBulkHandle)->usbBulkInfo.isUsbHost == true) {
#ifdef LIBUSB_INSTALLED
ret = libusb_bulk_transfer(handle, ((T_HalUsbBulkObj *) usbBulkHandle)->usbBulkInfo.channelInfo.endPointOut,
(uint8_t *) buf, len, &actualLen, LINUX_USB_BULK_TRANSFER_TIMEOUT_MS);
if (ret < 0) {
USER_LOG_ERROR("Write usb bulk data failed, errno = %d", ret);
return DJI_ERROR_SYSTEM_MODULE_CODE_SYSTEM_ERROR;
}
*realLen = actualLen;
#endif
} else {
*realLen = write(((T_HalUsbBulkObj *) usbBulkHandle)->ep1, buf, len);
}
return DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS;
}
T_DjiReturnCode HalUsbBulk_ReadData(T_DjiUsbBulkHandle usbBulkHandle, uint8_t *buf, uint32_t len,
uint32_t *realLen)
{
int32_t ret;
struct libusb_device_handle *handle = NULL;
int32_t actualLen;
if (usbBulkHandle == NULL) {
return DJI_ERROR_SYSTEM_MODULE_CODE_SYSTEM_ERROR;
}
handle = ((T_HalUsbBulkObj *) usbBulkHandle)->handle;
if (((T_HalUsbBulkObj *) usbBulkHandle)->usbBulkInfo.isUsbHost == true) {
#ifdef LIBUSB_INSTALLED
ret = libusb_bulk_transfer(handle, ((T_HalUsbBulkObj *) usbBulkHandle)->usbBulkInfo.channelInfo.endPointIn,
buf, len, &actualLen, LINUX_USB_BULK_TRANSFER_WAIT_FOREVER);
if (ret < 0) {
USER_LOG_ERROR("Read usb bulk data failed, errno = %d", ret);
return DJI_ERROR_SYSTEM_MODULE_CODE_SYSTEM_ERROR;
}
*realLen = actualLen;
#endif
} else {
*realLen = read(((T_HalUsbBulkObj *) usbBulkHandle)->ep2, buf, len);
}
return DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS;
}
T_DjiReturnCode HalUsbBulk_GetDeviceInfo(T_DjiHalUsbBulkDeviceInfo *deviceInfo)
{
//attention: this interface only be called in usb device mode.
deviceInfo->vid = LINUX_USB_VID;
deviceInfo->pid = LINUX_USB_PID;
// This bulk channel is used to obtain DJI camera video stream and push 3rd-party camera video stream.
deviceInfo->channelInfo[DJI_HAL_USB_BULK_NUM_0].interfaceNum = LINUX_USB_BULK1_INTERFACE_NUM;
deviceInfo->channelInfo[DJI_HAL_USB_BULK_NUM_0].endPointIn = LINUX_USB_BULK1_END_POINT_IN;
deviceInfo->channelInfo[DJI_HAL_USB_BULK_NUM_0].endPointOut = LINUX_USB_BULK1_END_POINT_OUT;
// This bulk channel is used to obtain DJI perception image and download camera media file.
deviceInfo->channelInfo[DJI_HAL_USB_BULK_NUM_1].interfaceNum = LINUX_USB_BULK2_INTERFACE_NUM;
deviceInfo->channelInfo[DJI_HAL_USB_BULK_NUM_1].endPointIn = LINUX_USB_BULK2_END_POINT_IN;
deviceInfo->channelInfo[DJI_HAL_USB_BULK_NUM_1].endPointOut = LINUX_USB_BULK2_END_POINT_OUT;
return DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS;
}
/* Private functions definition-----------------------------------------------*/
/****************** (C) COPYRIGHT DJI Innovations *****END OF FILE****/

View File

@ -0,0 +1,92 @@
/**
********************************************************************
* @file hal_usb_bulk.h
* @brief This is the header file for "hal_usb_bulk.c", defining the structure and
* (exported) function prototypes.
*
* @copyright (c) 2021 DJI. All rights reserved.
*
* All information contained herein is, and remains, the property of DJI.
* The intellectual and technical concepts contained herein are proprietary
* to DJI and may be covered by U.S. and foreign patents, patents in process,
* and protected by trade secret or copyright law. Dissemination of this
* information, including but not limited to data and other proprietary
* material(s) incorporated within the information, in any form, is strictly
* prohibited without the express written consent of DJI.
*
* If you receive this source code without DJIs authorization, you may not
* further disseminate the information, and you must immediately remove the
* source code and notify DJI of its removal. DJI reserves the right to pursue
* legal actions against you for any loss(es) or damage(s) caused by your
* failure to do so.
*
*********************************************************************
*/
/* Define to prevent recursive inclusion -------------------------------------*/
#ifndef HAL_USB_BULK_H
#define HAL_USB_BULK_H
/* Includes ------------------------------------------------------------------*/
#include "stdint.h"
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <termios.h>
#include <unistd.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#ifdef LIBUSB_INSTALLED
#include <libusb-1.0/libusb.h>
#endif
#include "dji_platform.h"
#ifdef __cplusplus
extern "C" {
#endif
/* Exported constants --------------------------------------------------------*/
#define LINUX_USB_BULK1_EP_OUT_FD "/dev/usb-ffs/bulk1/ep1"
#define LINUX_USB_BULK1_EP_IN_FD "/dev/usb-ffs/bulk1/ep2"
#define LINUX_USB_BULK1_INTERFACE_NUM (7)
#define LINUX_USB_BULK1_END_POINT_IN (0x88)
#define LINUX_USB_BULK1_END_POINT_OUT (5)
#define LINUX_USB_BULK2_EP_OUT_FD "/dev/usb-ffs/bulk2/ep1"
#define LINUX_USB_BULK2_EP_IN_FD "/dev/usb-ffs/bulk2/ep2"
#define LINUX_USB_BULK2_INTERFACE_NUM (8)
#define LINUX_USB_BULK2_END_POINT_IN (0x89)
#define LINUX_USB_BULK2_END_POINT_OUT (6)
#ifdef PLATFORM_ARCH_x86_64
#define LINUX_USB_VID (0x0B95)
#define LINUX_USB_PID (0x1790)
#else
#define LINUX_USB_VID (0x0955)
#define LINUX_USB_PID (0x7020)
#endif
/* Exported types ------------------------------------------------------------*/
/* Exported functions --------------------------------------------------------*/
T_DjiReturnCode HalUsbBulk_Init(T_DjiHalUsbBulkInfo usbBulkInfo, T_DjiUsbBulkHandle *usbBulkHandle);
T_DjiReturnCode HalUsbBulk_DeInit(T_DjiUsbBulkHandle usbBulkHandle);
T_DjiReturnCode HalUsbBulk_WriteData(T_DjiUsbBulkHandle usbBulkHandle, const uint8_t *buf, uint32_t len,
uint32_t *realLen);
T_DjiReturnCode HalUsbBulk_ReadData(T_DjiUsbBulkHandle usbBulkHandle, uint8_t *buf, uint32_t len, uint32_t *realLen);
T_DjiReturnCode HalUsbBulk_GetDeviceInfo(T_DjiHalUsbBulkDeviceInfo *deviceInfo);
#ifdef __cplusplus
}
#endif
#endif // HAL_USB_BULK_H
/************************ (C) COPYRIGHT DJI Innovations *******END OF FILE******/

View File

@ -0,0 +1,262 @@
/**
********************************************************************
* @file dji_media_file_core.c
* @brief
*
* @copyright (c) 2021 DJI. All rights reserved.
*
* All information contained herein is, and remains, the property of DJI.
* The intellectual and technical concepts contained herein are proprietary
* to DJI and may be covered by U.S. and foreign patents, patents in process,
* and protected by trade secret or copyright law. Dissemination of this
* information, including but not limited to data and other proprietary
* material(s) incorporated within the information, in any form, is strictly
* prohibited without the express written consent of DJI.
*
* If you receive this source code without DJIs authorization, you may not
* further disseminate the information, and you must immediately remove the
* source code and notify DJI of its removal. DJI reserves the right to pursue
* legal actions against you for any loss(es) or damage(s) caused by your
* failure to do so.
*
*********************************************************************
*/
/* Includes ------------------------------------------------------------------*/
#include <string.h>
#include <dji_logger.h>
#include "dji_media_file_core.h"
#include "dji_media_file_jpg.h"
#include "dji_media_file_mp4.h"
#include "dji_platform.h"
/* Private constants ---------------------------------------------------------*/
/* Private types -------------------------------------------------------------*/
/* Private functions declaration ---------------------------------------------*/
/* Private values ------------------------------------------------------------*/
//@formatter:off
static const T_DjiMediaFileOptItem s_mediaFileOpt[] =
{
//JPEG File Operation Item
{
DJI_CAMERA_FILE_TYPE_JPEG ,
DjiMediaFile_IsSupported_JPG,
DjiMediaFile_GetAttrFunc_JPG,
DjiMediaFile_GetDataOrigin_JPG,
DjiMediaFile_GetFileSizeOrigin_JPG,
DjiMediaFile_CreateThumbNail_JPG,
DjiMediaFile_GetFileSizeThumbNail_JPG,
DjiMediaFile_GetDataThumbNail_JPG,
DjiMediaFile_DestroyThumbNail_JPG,
DjiMediaFile_CreateScreenNail_JPG,
DjiMediaFile_GetFileSizeScreenNail_JPG,
DjiMediaFile_GetDataScreenNail_JPG,
DjiMediaFile_DestroyScreenNail_JPG,
},
//MP4 File Operation Item
{
DJI_CAMERA_FILE_TYPE_MP4 ,
DjiMediaFile_IsSupported_MP4,
DjiMediaFile_GetAttrFunc_MP4,
DjiMediaFile_GetDataOrigin_MP4,
DjiMediaFile_GetFileSizeOrigin_MP4,
DjiMediaFile_CreateThumbNail_MP4,
DjiMediaFile_GetFileSizeThumbNail_MP4,
DjiMediaFile_GetDataThumbNail_MP4,
DjiMediaFile_DestroyThumbNail_MP4,
DjiMediaFile_CreateScreenNail_MP4,
DjiMediaFile_GetFileSizeScreenNail_MP4,
DjiMediaFile_GetDataScreenNail_MP4,
DjiMediaFile_DestroyScreenNail_MP4,
},
};
static const uint32_t s_mediaFileOptCount = sizeof (s_mediaFileOpt) / sizeof(T_DjiMediaFileOptItem);
//@formatter:on
/* Exported functions definition ---------------------------------------------*/
bool DjiMediaFile_IsSupported(const char *filePath)
{
int i;
for (i = 0; i < s_mediaFileOptCount; i++) {
if (s_mediaFileOpt[i].isSupportedFunc(filePath) == true) {
return true;
}
}
return false;
}
T_DjiReturnCode DjiMediaFile_CreateHandle(const char *filePath, T_DjiMediaFileHandle *pMediaFileHandle)
{
int optIndex;
T_DjiOsalHandler *osalHandler = DjiPlatform_GetOsalHandler();
for (optIndex = 0; optIndex < s_mediaFileOptCount; optIndex++) {
if (s_mediaFileOpt[optIndex].isSupportedFunc(filePath) == true) {
break;
}
}
if (optIndex == s_mediaFileOptCount) {
return DJI_ERROR_SYSTEM_MODULE_CODE_INVALID_PARAMETER;
}
*pMediaFileHandle = osalHandler->Malloc(sizeof(T_DjiMediaFile));
if (*pMediaFileHandle == NULL) {
return DJI_ERROR_SYSTEM_MODULE_CODE_MEMORY_ALLOC_FAILED;
}
(*pMediaFileHandle)->filePath = osalHandler->Malloc(strlen(filePath) + 1);
if ((*pMediaFileHandle)->filePath == NULL) {
return DJI_ERROR_SYSTEM_MODULE_CODE_MEMORY_ALLOC_FAILED;
}
(*pMediaFileHandle)->mediaFileOptItem = s_mediaFileOpt[optIndex];
(*pMediaFileHandle)->mediaFileThm.privThm = NULL;
(*pMediaFileHandle)->mediaFileScr.privScr = NULL;
strcpy((*pMediaFileHandle)->filePath, filePath);
return DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS;
}
T_DjiReturnCode DjiMediaFile_DestroyHandle(T_DjiMediaFileHandle mediaFileHandle)
{
T_DjiOsalHandler *osalHandler = DjiPlatform_GetOsalHandler();
osalHandler->Free(mediaFileHandle->filePath);
osalHandler->Free(mediaFileHandle);
return DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS;
}
T_DjiReturnCode DjiMediaFile_GetMediaFileType(T_DjiMediaFileHandle mediaFileHandle,
E_DjiCameraMediaFileType *mediaFileType)
{
*mediaFileType = mediaFileHandle->mediaFileOptItem.mediaFileType;
return DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS;
}
T_DjiReturnCode DjiMediaFile_GetMediaFileAttr(T_DjiMediaFileHandle mediaFileHandle,
T_DjiCameraMediaFileAttr *mediaFileAttr)
{
if (mediaFileHandle->mediaFileOptItem.getAttrFunc == NULL) {
USER_LOG_ERROR("Media file handle getAttrFunc null error");
return DJI_ERROR_SYSTEM_MODULE_CODE_INVALID_PARAMETER;
}
return mediaFileHandle->mediaFileOptItem.getAttrFunc(mediaFileHandle, mediaFileAttr);
}
T_DjiReturnCode DjiMediaFile_GetDataOrg(struct _DjiMediaFile *mediaFileHandle, uint32_t offset, uint16_t len,
uint8_t *data, uint32_t *realLen)
{
if (mediaFileHandle->mediaFileOptItem.getDataOrgFunc == NULL) {
USER_LOG_ERROR("Media file handle getDataOrgFunc null error");
return DJI_ERROR_SYSTEM_MODULE_CODE_INVALID_PARAMETER;
}
return mediaFileHandle->mediaFileOptItem.getDataOrgFunc(mediaFileHandle, offset, len, data, realLen);
}
T_DjiReturnCode DjiMediaFile_GetFileSizeOrg(struct _DjiMediaFile *mediaFileHandle, uint32_t *fileSize)
{
if (mediaFileHandle->mediaFileOptItem.getFileSizeOrgFunc == NULL) {
USER_LOG_ERROR("Media file handle getFileSizeOrgFunc null error");
return DJI_ERROR_SYSTEM_MODULE_CODE_INVALID_PARAMETER;
}
return mediaFileHandle->mediaFileOptItem.getFileSizeOrgFunc(mediaFileHandle, fileSize);
}
T_DjiReturnCode DjiMediaFile_CreateThm(T_DjiMediaFileHandle mediaFileHandle)
{
if (mediaFileHandle->mediaFileOptItem.createThmFunc == NULL) {
USER_LOG_ERROR("Media file handle createThmFunc null error");
return DJI_ERROR_SYSTEM_MODULE_CODE_INVALID_PARAMETER;
}
return mediaFileHandle->mediaFileOptItem.createThmFunc(mediaFileHandle);
}
T_DjiReturnCode DjiMediaFile_GetFileSizeThm(T_DjiMediaFileHandle mediaFileHandle, uint32_t *fileSize)
{
if (mediaFileHandle->mediaFileOptItem.getFileSizeThmFunc == NULL) {
USER_LOG_ERROR("Media file handle getFileSizeThmFunc null error");
return DJI_ERROR_SYSTEM_MODULE_CODE_INVALID_PARAMETER;
}
return mediaFileHandle->mediaFileOptItem.getFileSizeThmFunc(mediaFileHandle, fileSize);
}
T_DjiReturnCode DjiMediaFile_GetDataThm(T_DjiMediaFileHandle mediaFileHandle, uint32_t offset, uint16_t len,
uint8_t *data, uint16_t *realLen)
{
if (mediaFileHandle->mediaFileOptItem.getDataThmFunc == NULL) {
USER_LOG_ERROR("Media file handle getDataThmFunc null error");
return DJI_ERROR_SYSTEM_MODULE_CODE_INVALID_PARAMETER;
}
return mediaFileHandle->mediaFileOptItem.getDataThmFunc(mediaFileHandle, offset, len, data, realLen);
}
T_DjiReturnCode DjiMediaFile_DestoryThm(T_DjiMediaFileHandle mediaFileHandle)
{
if (mediaFileHandle->mediaFileOptItem.destroyThmFunc == NULL) {
USER_LOG_ERROR("Media file handle destroyThmFunc null error");
return DJI_ERROR_SYSTEM_MODULE_CODE_INVALID_PARAMETER;
}
return mediaFileHandle->mediaFileOptItem.destroyThmFunc(mediaFileHandle);
}
T_DjiReturnCode DjiMediaFile_CreateScr(T_DjiMediaFileHandle mediaFileHandle)
{
if (mediaFileHandle->mediaFileOptItem.creatScrFunc == NULL) {
USER_LOG_ERROR("Media file handle creatScrFunc null error");
return DJI_ERROR_SYSTEM_MODULE_CODE_INVALID_PARAMETER;
}
return mediaFileHandle->mediaFileOptItem.creatScrFunc(mediaFileHandle);
}
T_DjiReturnCode DjiMediaFile_GetFileSizeScr(T_DjiMediaFileHandle mediaFileHandle, uint32_t *fileSize)
{
if (mediaFileHandle->mediaFileOptItem.getFileSizeScrFunc == NULL) {
USER_LOG_ERROR("Media file handle getFileSizeScrFunc null error");
return DJI_ERROR_SYSTEM_MODULE_CODE_INVALID_PARAMETER;
}
return mediaFileHandle->mediaFileOptItem.getFileSizeScrFunc(mediaFileHandle, fileSize);
}
T_DjiReturnCode DjiMediaFile_GetDataScr(T_DjiMediaFileHandle mediaFileHandle, uint32_t offset, uint16_t len,
uint8_t *data, uint16_t *realLen)
{
if (mediaFileHandle->mediaFileOptItem.getDataScrFunc == NULL) {
USER_LOG_ERROR("Media file handle getDataScrFunc null error");
return DJI_ERROR_SYSTEM_MODULE_CODE_INVALID_PARAMETER;
}
return mediaFileHandle->mediaFileOptItem.getDataScrFunc(mediaFileHandle, offset, len, data, realLen);
}
T_DjiReturnCode DjiMediaFile_DestroyScr(T_DjiMediaFileHandle mediaFileHandle)
{
if (mediaFileHandle->mediaFileOptItem.destroyScrFunc == NULL) {
USER_LOG_ERROR("Media file handle destroyScrFunc null error");
return DJI_ERROR_SYSTEM_MODULE_CODE_INVALID_PARAMETER;
}
return mediaFileHandle->mediaFileOptItem.destroyScrFunc(mediaFileHandle);
}
/* Private functions definition-----------------------------------------------*/
/****************** (C) COPYRIGHT DJI Innovations *****END OF FILE****/

View File

@ -0,0 +1,115 @@
/**
********************************************************************
* @file dji_media_file_core.h
* @brief This is the header file for "dji_media_file_core.c", defining the structure and
* (exported) function prototypes.
*
* @copyright (c) 2021 DJI. All rights reserved.
*
* All information contained herein is, and remains, the property of DJI.
* The intellectual and technical concepts contained herein are proprietary
* to DJI and may be covered by U.S. and foreign patents, patents in process,
* and protected by trade secret or copyright law. Dissemination of this
* information, including but not limited to data and other proprietary
* material(s) incorporated within the information, in any form, is strictly
* prohibited without the express written consent of DJI.
*
* If you receive this source code without DJIs authorization, you may not
* further disseminate the information, and you must immediately remove the
* source code and notify DJI of its removal. DJI reserves the right to pursue
* legal actions against you for any loss(es) or damage(s) caused by your
* failure to do so.
*
*********************************************************************
*/
/* Define to prevent recursive inclusion -------------------------------------*/
#ifndef PSDK_MEDIA_FILE_CORE_H
#define PSDK_MEDIA_FILE_CORE_H
#ifdef __cplusplus
extern "C" {
#endif
/* Includes ------------------------------------------------------------------*/
#include <dji_typedef.h>
#include <dji_payload_camera.h>
/* Exported constants --------------------------------------------------------*/
#define PSDK_MEDIA_FILE_PATH_LEN_MAX 512 /*max file path len */
#define PSDK_MEDIA_DIR_PATH_LEN_MAX 256 /*max dir path len */
/* Exported types ------------------------------------------------------------*/
typedef struct {
void *privThm;
} T_DjiMediaFileThm;
typedef struct {
void *privScr;
} T_DjiMediaFileScr;
struct _DjiMediaFile;
typedef struct {
E_DjiCameraMediaFileType mediaFileType;
bool (*isSupportedFunc)(const char *filePath);
T_DjiReturnCode (*getAttrFunc)(struct _DjiMediaFile *mediaFileHandle, T_DjiCameraMediaFileAttr *mediaFileAttr);
T_DjiReturnCode (*getDataOrgFunc)(struct _DjiMediaFile *mediaFileHandle, uint32_t offset, uint16_t len,
uint8_t *data, uint32_t *realLen);
T_DjiReturnCode (*getFileSizeOrgFunc)(struct _DjiMediaFile *mediaFileHandle, uint32_t *fileSize);
T_DjiReturnCode (*createThmFunc)(struct _DjiMediaFile *mediaFileHandle);
T_DjiReturnCode (*getFileSizeThmFunc)(struct _DjiMediaFile *mediaFileHandle, uint32_t *fileSize);
T_DjiReturnCode (*getDataThmFunc)(struct _DjiMediaFile *mediaFileHandle, uint32_t offset, uint16_t len,
uint8_t *data, uint16_t *realLen);
T_DjiReturnCode (*destroyThmFunc)(struct _DjiMediaFile *mediaFileHandle);
T_DjiReturnCode (*creatScrFunc)(struct _DjiMediaFile *mediaFileHandle);
T_DjiReturnCode (*getFileSizeScrFunc)(struct _DjiMediaFile *mediaFileHandle, uint32_t *fileSize);
T_DjiReturnCode (*getDataScrFunc)(struct _DjiMediaFile *mediaFileHandle, uint32_t offset, uint16_t len,
uint8_t *data, uint16_t *realLen);
T_DjiReturnCode (*destroyScrFunc)(struct _DjiMediaFile *mediaFileHandle);
} T_DjiMediaFileOptItem;
typedef struct _DjiMediaFile {
char *filePath;
T_DjiMediaFileOptItem mediaFileOptItem;
T_DjiMediaFileThm mediaFileThm;
T_DjiMediaFileScr mediaFileScr;
} T_DjiMediaFile, *T_DjiMediaFileHandle;
/* Exported functions --------------------------------------------------------*/
bool DjiMediaFile_IsSupported(const char *filePath);
T_DjiReturnCode DjiMediaFile_CreateHandle(const char *filePath, T_DjiMediaFileHandle *pMediaFileHandle);
T_DjiReturnCode DjiMediaFile_DestroyHandle(T_DjiMediaFileHandle mediaFileHandle);
T_DjiReturnCode DjiMediaFile_GetMediaFileType(T_DjiMediaFileHandle mediaFileHandle,
E_DjiCameraMediaFileType *mediaFileType);
T_DjiReturnCode DjiMediaFile_GetMediaFileAttr(T_DjiMediaFileHandle mediaFileHandle,
T_DjiCameraMediaFileAttr *mediaFileAttr);
T_DjiReturnCode DjiMediaFile_GetDataOrg(struct _DjiMediaFile *mediaFileHandle, uint32_t offset, uint16_t len,
uint8_t *data, uint32_t *realLen);
T_DjiReturnCode DjiMediaFile_GetFileSizeOrg(struct _DjiMediaFile *mediaFileHandle, uint32_t *fileSize);
T_DjiReturnCode DjiMediaFile_CreateThm(T_DjiMediaFileHandle mediaFileHandle);
T_DjiReturnCode DjiMediaFile_GetFileSizeThm(T_DjiMediaFileHandle mediaFileHandle, uint32_t *fileSize);
T_DjiReturnCode DjiMediaFile_GetDataThm(T_DjiMediaFileHandle mediaFileHandle, uint32_t offset, uint16_t len,
uint8_t *data, uint16_t *realLen);
T_DjiReturnCode DjiMediaFile_DestoryThm(T_DjiMediaFileHandle mediaFileHandle);
T_DjiReturnCode DjiMediaFile_CreateScr(T_DjiMediaFileHandle mediaFileHandle);
T_DjiReturnCode DjiMediaFile_GetFileSizeScr(T_DjiMediaFileHandle mediaFileHandle, uint32_t *fileSize);
T_DjiReturnCode DjiMediaFile_GetDataScr(T_DjiMediaFileHandle mediaFileHandle, uint32_t offset, uint16_t len,
uint8_t *data, uint16_t *realLen);
T_DjiReturnCode DjiMediaFile_DestroyScr(T_DjiMediaFileHandle mediaFileHandle);
#ifdef __cplusplus
}
#endif
#endif // PSDK_MEDIA_FILE_CORE_H
/************************ (C) COPYRIGHT DJI Innovations *******END OF FILE******/

View File

@ -0,0 +1,228 @@
/**
********************************************************************
* @file dji_media_file_jpg.c
* @brief
*
* @copyright (c) 2021 DJI. All rights reserved.
*
* All information contained herein is, and remains, the property of DJI.
* The intellectual and technical concepts contained herein are proprietary
* to DJI and may be covered by U.S. and foreign patents, patents in process,
* and protected by trade secret or copyright law. Dissemination of this
* information, including but not limited to data and other proprietary
* material(s) incorporated within the information, in any form, is strictly
* prohibited without the express written consent of DJI.
*
* If you receive this source code without DJIs authorization, you may not
* further disseminate the information, and you must immediately remove the
* source code and notify DJI of its removal. DJI reserves the right to pursue
* legal actions against you for any loss(es) or damage(s) caused by your
* failure to do so.
*
*********************************************************************
*/
/* Includes ------------------------------------------------------------------*/
#include "dji_media_file_jpg.h"
#include "dji_media_file_core.h"
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <dji_logger.h>
#include <utils/util_misc.h>
#include "dji_platform.h"
#include "utils/util_time.h"
#include "utils/util_file.h"
/* Private constants ---------------------------------------------------------*/
#define JPG_FILE_SUFFIX ".jpg"
#define JPG_TEMP_FILE_TEMPLATE_STR "JPG_TEMP_XXXXXX.jpg"
#define JPG_TEMP_FILE_PATH_MAX_LEN 50
#define FFMPEG_CMD_BUF_SIZE 1024
#define JPG_THM_SCALE_CFG_STR "scale=100:-1"
#define JPG_SCR_SCALE_CFG_STR "scale=600:-1"
/* Private types -------------------------------------------------------------*/
typedef struct {
FILE *tempFile;
char tempfilePath[JPG_TEMP_FILE_PATH_MAX_LEN];
} T_DjiJPGTempFilePriv;
/* Private functions declaration ---------------------------------------------*/
static T_DjiReturnCode DjiMediaFile_CreateTempFilePriv_JPG(const char *srcFilePath, const char *scaleCfgStr,
T_DjiJPGTempFilePriv **pTempFilePrivHandle);
static T_DjiReturnCode DjiMediaFile_DestroyTempFilePriv_JPG(T_DjiJPGTempFilePriv *tempFilePrivHandle);
/* Exported functions definition ---------------------------------------------*/
bool DjiMediaFile_IsSupported_JPG(const char *filePath)
{
if (filePath == NULL) {
USER_LOG_ERROR("input parameter is null error");
return false;
}
if (strcmp(&filePath[strlen(filePath) - 4], JPG_FILE_SUFFIX) == 0) {
return true;
}
return false;
}
T_DjiReturnCode DjiMediaFile_GetAttrFunc_JPG(struct _DjiMediaFile *mediaFileHandle,
T_DjiCameraMediaFileAttr *mediaFileAttr)
{
USER_UTIL_UNUSED(mediaFileHandle);
mediaFileAttr->attrVideoDuration = 0;
return DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS;
}
T_DjiReturnCode DjiMediaFile_GetDataOrigin_JPG(struct _DjiMediaFile *mediaFileHandle, uint32_t offset, uint16_t len,
uint8_t *data, uint32_t *realLen)
{
return UtilFile_GetFileDataByPath(mediaFileHandle->filePath, offset, len, data, realLen);
}
T_DjiReturnCode DjiMediaFile_GetFileSizeOrigin_JPG(struct _DjiMediaFile *mediaFileHandle, uint32_t *fileSize)
{
return UtilFile_GetFileSizeByPath(mediaFileHandle->filePath, fileSize);
}
T_DjiReturnCode DjiMediaFile_CreateThumbNail_JPG(struct _DjiMediaFile *mediaFileHandle)
{
return DjiMediaFile_CreateTempFilePriv_JPG(mediaFileHandle->filePath, JPG_THM_SCALE_CFG_STR,
(T_DjiJPGTempFilePriv **) &mediaFileHandle->mediaFileThm.privThm);
}
T_DjiReturnCode DjiMediaFile_GetFileSizeThumbNail_JPG(struct _DjiMediaFile *mediaFileHandle, uint32_t *fileSize)
{
T_DjiJPGTempFilePriv *jpgFileThmPriv = (T_DjiJPGTempFilePriv *) mediaFileHandle->mediaFileThm.privThm;
return UtilFile_GetFileSize(jpgFileThmPriv->tempFile, fileSize);
}
T_DjiReturnCode
DjiMediaFile_GetDataThumbNail_JPG(struct _DjiMediaFile *mediaFileHandle, uint32_t offset, uint16_t len,
uint8_t *data, uint16_t *realLen)
{
T_DjiJPGTempFilePriv *jpgFileThmPriv = (T_DjiJPGTempFilePriv *) mediaFileHandle->mediaFileThm.privThm;
return UtilFile_GetFileData(jpgFileThmPriv->tempFile, offset, len, data, realLen);
}
T_DjiReturnCode DjiMediaFile_DestroyThumbNail_JPG(struct _DjiMediaFile *mediaFileHandle)
{
return DjiMediaFile_DestroyTempFilePriv_JPG(mediaFileHandle->mediaFileThm.privThm);
}
T_DjiReturnCode DjiMediaFile_CreateScreenNail_JPG(struct _DjiMediaFile *mediaFileHandle)
{
return DjiMediaFile_CreateTempFilePriv_JPG(mediaFileHandle->filePath, JPG_SCR_SCALE_CFG_STR,
(T_DjiJPGTempFilePriv **) &mediaFileHandle->mediaFileScr.privScr);
}
T_DjiReturnCode DjiMediaFile_GetFileSizeScreenNail_JPG(struct _DjiMediaFile *mediaFileHandle, uint32_t *fileSize)
{
T_DjiJPGTempFilePriv *jpgFileScrPriv = (T_DjiJPGTempFilePriv *) mediaFileHandle->mediaFileScr.privScr;
return UtilFile_GetFileSize(jpgFileScrPriv->tempFile, fileSize);
}
T_DjiReturnCode
DjiMediaFile_GetDataScreenNail_JPG(struct _DjiMediaFile *mediaFileHandle, uint32_t offset, uint16_t len,
uint8_t *data, uint16_t *realLen)
{
T_DjiJPGTempFilePriv *jpgFileScrPriv = (T_DjiJPGTempFilePriv *) mediaFileHandle->mediaFileScr.privScr;
return UtilFile_GetFileData(jpgFileScrPriv->tempFile, offset, len, data, realLen);
}
T_DjiReturnCode DjiMediaFile_DestroyScreenNail_JPG(struct _DjiMediaFile *mediaFileHandle)
{
return DjiMediaFile_DestroyTempFilePriv_JPG(mediaFileHandle->mediaFileScr.privScr);
}
/* Private functions definition-----------------------------------------------*/
static T_DjiReturnCode DjiMediaFile_CreateTempFilePriv_JPG(const char *srcFilePath, const char *scaleCfgStr,
T_DjiJPGTempFilePriv **pTempFilePrivHandle)
{
char ffmpeg_cmd[FFMPEG_CMD_BUF_SIZE];
int cmdRet;
T_DjiRunTimeStamps tiStart, tiEnd;
T_DjiJPGTempFilePriv *jpgTempFilePriv;
T_DjiReturnCode psdkStat;
int tempFd;
T_DjiOsalHandler *osalHandler = DjiPlatform_GetOsalHandler();
tiStart = DjiUtilTime_GetRunTimeStamps();
*pTempFilePrivHandle = osalHandler->Malloc(sizeof(T_DjiJPGTempFilePriv));
if (*pTempFilePrivHandle == NULL) {
return DJI_ERROR_SYSTEM_MODULE_CODE_MEMORY_ALLOC_FAILED;
}
jpgTempFilePriv = *pTempFilePrivHandle;
//get temp file name
strcpy(jpgTempFilePriv->tempfilePath, JPG_TEMP_FILE_TEMPLATE_STR);
tempFd = mkstemps(jpgTempFilePriv->tempfilePath, strlen(JPG_FILE_SUFFIX));
if (tempFd < 0) {
USER_LOG_ERROR("JPG Create Temp File Error, tempFd = %d\n", tempFd);
psdkStat = DJI_ERROR_SYSTEM_MODULE_CODE_SYSTEM_ERROR;
goto err_create_temp;
}
close(tempFd);
unlink(jpgTempFilePriv->tempfilePath);
//ffmpeg cmd send
snprintf(ffmpeg_cmd, FFMPEG_CMD_BUF_SIZE, "ffmpeg -i \"%s\" -vf %s %s 1>/dev/null 2>&1",
srcFilePath, scaleCfgStr, jpgTempFilePriv->tempfilePath);
cmdRet = system(ffmpeg_cmd);
tiEnd = DjiUtilTime_GetRunTimeStamps();
USER_LOG_DEBUG("JPG Create TempFile, RealTime = %ld us\n", tiEnd.realUsec - tiStart.realUsec);
if (cmdRet != 0) {
USER_LOG_ERROR("JPG ffmpeg cmd call error, ret = %d\n", cmdRet);
psdkStat = DJI_ERROR_SYSTEM_MODULE_CODE_SYSTEM_ERROR;
goto err_system_cmd;
}
//open temp file
jpgTempFilePriv->tempFile = fopen(jpgTempFilePriv->tempfilePath, "rb+");
if (jpgTempFilePriv->tempFile == NULL) {
psdkStat = DJI_ERROR_SYSTEM_MODULE_CODE_SYSTEM_ERROR;
goto err_file_open;
}
//unlink temp file
unlink(jpgTempFilePriv->tempfilePath);
return DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS;
err_file_open:
unlink(jpgTempFilePriv->tempfilePath);
err_system_cmd:
err_create_temp:
osalHandler->Free(*pTempFilePrivHandle);
return psdkStat;
}
static T_DjiReturnCode DjiMediaFile_DestroyTempFilePriv_JPG(T_DjiJPGTempFilePriv *tempFilePrivHandle)
{
T_DjiOsalHandler *osalHandler = DjiPlatform_GetOsalHandler();
fclose(tempFilePrivHandle->tempFile);
osalHandler->Free(tempFilePrivHandle);
return DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS;
}
/****************** (C) COPYRIGHT DJI Innovations *****END OF FILE****/

View File

@ -0,0 +1,75 @@
/**
********************************************************************
* @file dji_media_file_jpg.h
* @brief This is the header file for "dji_media_file_jpg.c", defining the structure and
* (exported) function prototypes.
*
* @copyright (c) 2021 DJI. All rights reserved.
*
* All information contained herein is, and remains, the property of DJI.
* The intellectual and technical concepts contained herein are proprietary
* to DJI and may be covered by U.S. and foreign patents, patents in process,
* and protected by trade secret or copyright law. Dissemination of this
* information, including but not limited to data and other proprietary
* material(s) incorporated within the information, in any form, is strictly
* prohibited without the express written consent of DJI.
*
* If you receive this source code without DJIs authorization, you may not
* further disseminate the information, and you must immediately remove the
* source code and notify DJI of its removal. DJI reserves the right to pursue
* legal actions against you for any loss(es) or damage(s) caused by your
* failure to do so.
*
*********************************************************************
*/
/* Define to prevent recursive inclusion -------------------------------------*/
#ifndef PSDK_MEDIA_FILE_JPG_H
#define PSDK_MEDIA_FILE_JPG_H
#ifdef __cplusplus
extern "C" {
#endif
/* Includes ------------------------------------------------------------------*/
#include <dji_payload_camera.h>
#include <dji_typedef.h>
#include "dji_media_file_core.h"
/* Exported constants --------------------------------------------------------*/
/* Exported types ------------------------------------------------------------*/
/* Exported functions --------------------------------------------------------*/
bool DjiMediaFile_IsSupported_JPG(const char *filePath);
T_DjiReturnCode DjiMediaFile_GetAttrFunc_JPG(struct _DjiMediaFile *mediaFileHandle,
T_DjiCameraMediaFileAttr *mediaFileAttr);
T_DjiReturnCode DjiMediaFile_GetDataOrigin_JPG(struct _DjiMediaFile *mediaFileHandle, uint32_t offset, uint16_t len,
uint8_t *data, uint32_t *realLen);
T_DjiReturnCode DjiMediaFile_GetFileSizeOrigin_JPG(struct _DjiMediaFile *mediaFileHandle, uint32_t *fileSize);
T_DjiReturnCode DjiMediaFile_CreateThumbNail_JPG(struct _DjiMediaFile *mediaFileHandle);
T_DjiReturnCode DjiMediaFile_GetFileSizeThumbNail_JPG(struct _DjiMediaFile *mediaFileHandle, uint32_t *fileSize);
T_DjiReturnCode
DjiMediaFile_GetDataThumbNail_JPG(struct _DjiMediaFile *mediaFileHandle, uint32_t offset, uint16_t len,
uint8_t *data, uint16_t *realLen);
T_DjiReturnCode DjiMediaFile_DestroyThumbNail_JPG(struct _DjiMediaFile *mediaFileHandle);
T_DjiReturnCode DjiMediaFile_CreateScreenNail_JPG(struct _DjiMediaFile *mediaFileHandle);
T_DjiReturnCode DjiMediaFile_GetFileSizeScreenNail_JPG(struct _DjiMediaFile *mediaFileHandle, uint32_t *fileSize);
T_DjiReturnCode
DjiMediaFile_GetDataScreenNail_JPG(struct _DjiMediaFile *mediaFileHandle, uint32_t offset, uint16_t len,
uint8_t *data, uint16_t *realLen);
T_DjiReturnCode DjiMediaFile_DestroyScreenNail_JPG(struct _DjiMediaFile *mediaFileHandle);
#ifdef __cplusplus
}
#endif
#endif // PSDK_MEIDA_FILE_JPG_H
/************************ (C) COPYRIGHT DJI Innovations *******END OF FILE******/

View File

@ -0,0 +1,262 @@
/**
********************************************************************
* @file dji_media_file_mp4.c
* @brief
*
* @copyright (c) 2021 DJI. All rights reserved.
*
* All information contained herein is, and remains, the property of DJI.
* The intellectual and technical concepts contained herein are proprietary
* to DJI and may be covered by U.S. and foreign patents, patents in process,
* and protected by trade secret or copyright law. Dissemination of this
* information, including but not limited to data and other proprietary
* material(s) incorporated within the information, in any form, is strictly
* prohibited without the express written consent of DJI.
*
* If you receive this source code without DJIs authorization, you may not
* further disseminate the information, and you must immediately remove the
* source code and notify DJI of its removal. DJI reserves the right to pursue
* legal actions against you for any loss(es) or damage(s) caused by your
* failure to do so.
*
*********************************************************************
*/
/* Includes ------------------------------------------------------------------*/
#include "dji_media_file_mp4.h"
#include "dji_media_file_core.h"
#include <string.h>
#include <unistd.h>
#include <stdio.h>
#include <dji_logger.h>
#include <stdlib.h>
#include "dji_platform.h"
#include "utils/util_time.h"
#include "utils/util_file.h"
/* Private constants ---------------------------------------------------------*/
#define MP4_FILE_SUFFIX ".mp4"
#define MP4_TEMP_FILE_TEMPLATE_STR "MP4_TEMP_XXXXXX.jpg"
#define MP4_TEMP_FILE_PATH_MAX_LEN 50
#define FFMPEG_CMD_BUF_SIZE (256 + 256)
#define MP4_THM_SCALE_CFG_STR "scale=100:-1"
#define MP4_SCR_SCALE_CFG_STR "scale=600:-1"
/* Private types -------------------------------------------------------------*/
typedef struct {
FILE *tempFile;
char tempfilePath[MP4_TEMP_FILE_PATH_MAX_LEN];
} T_DjiMP4TempPicPriv;
/* Private functions declaration ---------------------------------------------*/
static T_DjiReturnCode DjiMediaFile_CreateTempPicPriv_MP4(const char *srcFilePath, const char *scaleCfgStr,
T_DjiMP4TempPicPriv **pTempPicPrivHandle);
static T_DjiReturnCode DjiMediaFile_DestroyTempPicPriv_MP4(T_DjiMP4TempPicPriv *tempPicPrivHandle);
/* Private values ------------------------------------------------------------*/
/* Exported functions definition ---------------------------------------------*/
bool DjiMediaFile_IsSupported_MP4(const char *filePath)
{
if (filePath == NULL) {
USER_LOG_ERROR("input parameter is null error");
return false;
}
if (strcmp(&filePath[strlen(filePath) - 4], MP4_FILE_SUFFIX) == 0) {
return true;
}
return false;
}
T_DjiReturnCode DjiMediaFile_GetAttrFunc_MP4(struct _DjiMediaFile *mediaFileHandle,
T_DjiCameraMediaFileAttr *mediaFileAttr)
{
FILE *fp;
char ffmpegCmdStr[FFMPEG_CMD_BUF_SIZE];
float hour, minute, second;
char tempTailStr[128];
int ret;
T_DjiReturnCode psdkStat;
snprintf(ffmpegCmdStr, FFMPEG_CMD_BUF_SIZE, "ffmpeg -i \"%s\" 2>&1 | grep \"Duration\"", mediaFileHandle->filePath);
fp = popen(ffmpegCmdStr, "r");
if (fp == NULL) {
return DJI_ERROR_SYSTEM_MODULE_CODE_SYSTEM_ERROR;
}
ret = fscanf(fp, " Duration: %f:%f:%f,%127s", &hour, &minute, &second, tempTailStr);
if (ret <= 0) {
USER_LOG_ERROR("MP4 File Get Duration Error\n");
psdkStat = DJI_ERROR_SYSTEM_MODULE_CODE_SYSTEM_ERROR;
goto out;
}
mediaFileAttr->attrVideoDuration = (uint32_t) (hour * 3600 + minute * 60 + second + 0.5);
/*! The user needs to obtain the frame rate and resolution of the video file by ffmpeg tools.
* Also the frame rate and resolution of video need convert to enum E_DjiCameraVideoFrameRate or
* E_DjiCameraVideoResolution.
*/
mediaFileAttr->attrVideoFrameRate = DJI_CAMERA_VIDEO_FRAME_RATE_30_FPS;
mediaFileAttr->attrVideoResolution = DJI_CAMERA_VIDEO_RESOLUTION_1920x1080;
psdkStat = DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS;
out:
pclose(fp);
return psdkStat;
}
T_DjiReturnCode DjiMediaFile_GetDataOrigin_MP4(struct _DjiMediaFile *mediaFileHandle, uint32_t offset, uint16_t len,
uint8_t *data, uint32_t *realLen)
{
return UtilFile_GetFileDataByPath(mediaFileHandle->filePath, offset, len, data, realLen);
}
T_DjiReturnCode DjiMediaFile_GetFileSizeOrigin_MP4(struct _DjiMediaFile *mediaFileHandle, uint32_t *fileSize)
{
return UtilFile_GetFileSizeByPath(mediaFileHandle->filePath, fileSize);
}
T_DjiReturnCode DjiMediaFile_CreateThumbNail_MP4(struct _DjiMediaFile *mediaFileHandle)
{
return DjiMediaFile_CreateTempPicPriv_MP4(mediaFileHandle->filePath, MP4_THM_SCALE_CFG_STR,
(T_DjiMP4TempPicPriv **) &mediaFileHandle->mediaFileThm.privThm);
}
T_DjiReturnCode DjiMediaFile_GetFileSizeThumbNail_MP4(struct _DjiMediaFile *mediaFileHandle, uint32_t *fileSize)
{
T_DjiMP4TempPicPriv *jpgFileThmPriv = (T_DjiMP4TempPicPriv *) mediaFileHandle->mediaFileThm.privThm;
return UtilFile_GetFileSize(jpgFileThmPriv->tempFile, fileSize);
}
T_DjiReturnCode
DjiMediaFile_GetDataThumbNail_MP4(struct _DjiMediaFile *mediaFileHandle, uint32_t offset, uint16_t len,
uint8_t *data, uint16_t *realLen)
{
T_DjiMP4TempPicPriv *jpgFileThmPriv = (T_DjiMP4TempPicPriv *) mediaFileHandle->mediaFileThm.privThm;
return UtilFile_GetFileData(jpgFileThmPriv->tempFile, offset, len, data, realLen);
}
T_DjiReturnCode DjiMediaFile_DestroyThumbNail_MP4(struct _DjiMediaFile *MediaFileHandle)
{
return DjiMediaFile_DestroyTempPicPriv_MP4(MediaFileHandle->mediaFileThm.privThm);
}
T_DjiReturnCode DjiMediaFile_CreateScreenNail_MP4(struct _DjiMediaFile *mediaFileHandle)
{
return DjiMediaFile_CreateTempPicPriv_MP4(mediaFileHandle->filePath, MP4_SCR_SCALE_CFG_STR,
(T_DjiMP4TempPicPriv **) &mediaFileHandle->mediaFileScr.privScr);
}
T_DjiReturnCode DjiMediaFile_GetFileSizeScreenNail_MP4(struct _DjiMediaFile *mediaFileHandle, uint32_t *fileSize)
{
T_DjiMP4TempPicPriv *jpgFileScrPriv = (T_DjiMP4TempPicPriv *) mediaFileHandle->mediaFileScr.privScr;
return UtilFile_GetFileSize(jpgFileScrPriv->tempFile, fileSize);
}
T_DjiReturnCode
DjiMediaFile_GetDataScreenNail_MP4(struct _DjiMediaFile *mediaFileHandle, uint32_t offset, uint16_t len,
uint8_t *data, uint16_t *realLen)
{
T_DjiMP4TempPicPriv *jpgFileScrPriv = (T_DjiMP4TempPicPriv *) mediaFileHandle->mediaFileScr.privScr;
return UtilFile_GetFileData(jpgFileScrPriv->tempFile, offset, len, data, realLen);
}
T_DjiReturnCode DjiMediaFile_DestroyScreenNail_MP4(struct _DjiMediaFile *mediaFileHandle)
{
return DjiMediaFile_DestroyTempPicPriv_MP4(mediaFileHandle->mediaFileScr.privScr);
}
/* Private functions definition-----------------------------------------------*/
static T_DjiReturnCode DjiMediaFile_CreateTempPicPriv_MP4(const char *srcFilePath, const char *scaleCfgStr,
T_DjiMP4TempPicPriv **pTempPicPrivHandle)
{
char ffmpeg_cmd[FFMPEG_CMD_BUF_SIZE];
int cmdRet;
T_DjiRunTimeStamps tiStart, tiEnd;
T_DjiMP4TempPicPriv *mp4TempPicFile;
T_DjiReturnCode psdkStat;
int tempFd;
T_DjiOsalHandler *osalHandler = DjiPlatform_GetOsalHandler();
tiStart = DjiUtilTime_GetRunTimeStamps();
*pTempPicPrivHandle = osalHandler->Malloc(sizeof(T_DjiMP4TempPicPriv));
if (*pTempPicPrivHandle == NULL) {
return DJI_ERROR_SYSTEM_MODULE_CODE_MEMORY_ALLOC_FAILED;
}
mp4TempPicFile = *pTempPicPrivHandle;
//get temp file name
strcpy(mp4TempPicFile->tempfilePath, MP4_TEMP_FILE_TEMPLATE_STR);
tempFd = mkstemps(mp4TempPicFile->tempfilePath, strlen(MP4_FILE_SUFFIX));
if (tempFd < 0) {
USER_LOG_ERROR("JPG Create Temp File Error, tempFd = %d\n", tempFd);
psdkStat = DJI_ERROR_SYSTEM_MODULE_CODE_SYSTEM_ERROR;
goto err_create_temp;
}
close(tempFd);
unlink(mp4TempPicFile->tempfilePath);
//ffmpeg cmd send
snprintf(ffmpeg_cmd, FFMPEG_CMD_BUF_SIZE, "ffmpeg -i \"%s\" -vf %s -ss 00:00:00 -vframes 1 %s 1>/dev/null 2>&1",
srcFilePath, scaleCfgStr, mp4TempPicFile->tempfilePath);
cmdRet = system(ffmpeg_cmd);
tiEnd = DjiUtilTime_GetRunTimeStamps();
USER_LOG_DEBUG("JPG Create TempFile, RealTime = %ld us\n", tiEnd.realUsec - tiStart.realUsec);
if (cmdRet != 0) {
USER_LOG_ERROR("JPG ffmpeg cmd call error, ret = %d\n", cmdRet);
psdkStat = DJI_ERROR_SYSTEM_MODULE_CODE_SYSTEM_ERROR;
goto err_system_cmd;
}
//open temp file
mp4TempPicFile->tempFile = fopen(mp4TempPicFile->tempfilePath, "rb+");
if (mp4TempPicFile->tempFile == NULL) {
psdkStat = DJI_ERROR_SYSTEM_MODULE_CODE_SYSTEM_ERROR;
goto err_file_open;
}
//unlink temp file
unlink(mp4TempPicFile->tempfilePath);
return DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS;
err_file_open:
unlink(mp4TempPicFile->tempfilePath);
err_system_cmd:
err_create_temp:
osalHandler->Free(*pTempPicPrivHandle);
return psdkStat;
}
static T_DjiReturnCode DjiMediaFile_DestroyTempPicPriv_MP4(T_DjiMP4TempPicPriv *tempPicPrivHandle)
{
T_DjiOsalHandler *osalHandler = DjiPlatform_GetOsalHandler();
fclose(tempPicPrivHandle->tempFile);
osalHandler->Free(tempPicPrivHandle);
return DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS;
}
/****************** (C) COPYRIGHT DJI Innovations *****END OF FILE****/

View File

@ -0,0 +1,75 @@
/**
********************************************************************
* @file dji_media_file_mp4.h
* @brief This is the header file for "dji_media_file_mp4.c", defining the structure and
* (exported) function prototypes.
*
* @copyright (c) 2021 DJI. All rights reserved.
*
* All information contained herein is, and remains, the property of DJI.
* The intellectual and technical concepts contained herein are proprietary
* to DJI and may be covered by U.S. and foreign patents, patents in process,
* and protected by trade secret or copyright law. Dissemination of this
* information, including but not limited to data and other proprietary
* material(s) incorporated within the information, in any form, is strictly
* prohibited without the express written consent of DJI.
*
* If you receive this source code without DJIs authorization, you may not
* further disseminate the information, and you must immediately remove the
* source code and notify DJI of its removal. DJI reserves the right to pursue
* legal actions against you for any loss(es) or damage(s) caused by your
* failure to do so.
*
*********************************************************************
*/
/* Define to prevent recursive inclusion -------------------------------------*/
#ifndef PSDK_MEDIA_FILE_MP4_H
#define PSDK_MEDIA_FILE_MP4_H
#ifdef __cplusplus
extern "C" {
#endif
/* Includes ------------------------------------------------------------------*/
#include <dji_payload_camera.h>
#include <dji_typedef.h>
#include "dji_media_file_core.h"
/* Exported constants --------------------------------------------------------*/
/* Exported types ------------------------------------------------------------*/
/* Exported functions --------------------------------------------------------*/
bool DjiMediaFile_IsSupported_MP4(const char *filePath);
T_DjiReturnCode DjiMediaFile_GetAttrFunc_MP4(struct _DjiMediaFile *mediaFileHandle,
T_DjiCameraMediaFileAttr *mediaFileAttr);
T_DjiReturnCode DjiMediaFile_GetDataOrigin_MP4(struct _DjiMediaFile *mediaFileHandle, uint32_t offset, uint16_t len,
uint8_t *data, uint32_t *realLen);
T_DjiReturnCode DjiMediaFile_GetFileSizeOrigin_MP4(struct _DjiMediaFile *mediaFileHandle, uint32_t *fileSize);
T_DjiReturnCode DjiMediaFile_CreateThumbNail_MP4(struct _DjiMediaFile *mediaFileHandle);
T_DjiReturnCode DjiMediaFile_GetFileSizeThumbNail_MP4(struct _DjiMediaFile *mediaFileHandle, uint32_t *fileSize);
T_DjiReturnCode
DjiMediaFile_GetDataThumbNail_MP4(struct _DjiMediaFile *mediaFileHandle, uint32_t offset, uint16_t len,
uint8_t *data, uint16_t *realLen);
T_DjiReturnCode DjiMediaFile_DestroyThumbNail_MP4(struct _DjiMediaFile *MediaFileHandle);
T_DjiReturnCode DjiMediaFile_CreateScreenNail_MP4(struct _DjiMediaFile *mediaFileHandle);
T_DjiReturnCode DjiMediaFile_GetFileSizeScreenNail_MP4(struct _DjiMediaFile *mediaFileHandle, uint32_t *fileSize);
T_DjiReturnCode
DjiMediaFile_GetDataScreenNail_MP4(struct _DjiMediaFile *mediaFileHandle, uint32_t offset, uint16_t len,
uint8_t *data, uint16_t *realLen);
T_DjiReturnCode DjiMediaFile_DestroyScreenNail_MP4(struct _DjiMediaFile *mediaFileHandle);
#ifdef __cplusplus
}
#endif
#endif // PSDK_MEDIA_FILE_MP4_H
/************************ (C) COPYRIGHT DJI Innovations *******END OF FILE******/

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.1 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.4 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.0 MiB

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,55 @@
/**
********************************************************************
* @file test_payload_cam_emu_common.h
* @brief This is the header file for "test_payload_cam_emu.c", defining the structure and
* (exported) function prototypes.
*
* @copyright (c) 2021 DJI. All rights reserved.
*
* All information contained herein is, and remains, the property of DJI.
* The intellectual and technical concepts contained herein are proprietary
* to DJI and may be covered by U.S. and foreign patents, patents in process,
* and protected by trade secret or copyright law. Dissemination of this
* information, including but not limited to data and other proprietary
* material(s) incorporated within the information, in any form, is strictly
* prohibited without the express written consent of DJI.
*
* If you receive this source code without DJIs authorization, you may not
* further disseminate the information, and you must immediately remove the
* source code and notify DJI of its removal. DJI reserves the right to pursue
* legal actions against you for any loss(es) or damage(s) caused by your
* failure to do so.
*
*********************************************************************
*/
/* Define to prevent recursive inclusion -------------------------------------*/
#ifndef TEST_PAYLOAD_CAM_EMU_BASE_H
#define TEST_PAYLOAD_CAM_EMU_BASE_H
/* Includes ------------------------------------------------------------------*/
#include "dji_typedef.h"
#include "dji_payload_camera.h"
#ifdef __cplusplus
extern "C" {
#endif
/* Exported constants --------------------------------------------------------*/
/* Exported types ------------------------------------------------------------*/
/* Exported functions --------------------------------------------------------*/
T_DjiReturnCode DjiTest_CameraEmuBaseStartService(void);
T_DjiReturnCode DjiTest_CameraGetDigitalZoomFactor(dji_f32_t *factor);
T_DjiReturnCode DjiTest_CameraGetOpticalZoomFactor(dji_f32_t *factor);
T_DjiReturnCode DjiTest_CameraGetMode(E_DjiCameraMode *mode);
T_DjiReturnCode DjiTest_CameraGetVideoStreamType(E_DjiCameraVideoStreamType *type);
bool DjiTest_CameraIsInited(void);
#ifdef __cplusplus
}
#endif
#endif // TEST_PAYLOAD_CAM_EMU_BASE_H
/************************ (C) COPYRIGHT DJI Innovations *******END OF FILE******/

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,52 @@
/**
********************************************************************
* @file test_payload_cam_emu_media.h
* @brief This is the header file for "test_payload_cam_media.c", defining the structure and
* (exported) function prototypes.
*
* @copyright (c) 2021 DJI. All rights reserved.
*
* All information contained herein is, and remains, the property of DJI.
* The intellectual and technical concepts contained herein are proprietary
* to DJI and may be covered by U.S. and foreign patents, patents in process,
* and protected by trade secret or copyright law. Dissemination of this
* information, including but not limited to data and other proprietary
* material(s) incorporated within the information, in any form, is strictly
* prohibited without the express written consent of DJI.
*
* If you receive this source code without DJIs authorization, you may not
* further disseminate the information, and you must immediately remove the
* source code and notify DJI of its removal. DJI reserves the right to pursue
* legal actions against you for any loss(es) or damage(s) caused by your
* failure to do so.
*
*********************************************************************
*/
/* Define to prevent recursive inclusion -------------------------------------*/
#ifndef TEST_PAYLOAD_CAM_EMU_MEDIA_H
#define TEST_PAYLOAD_CAM_EMU_MEDIA_H
/* Includes ------------------------------------------------------------------*/
#include "dji_typedef.h"
#include "dji_payload_camera.h"
#ifdef __cplusplus
extern "C" {
#endif
/* Exported constants --------------------------------------------------------*/
/* Exported types ------------------------------------------------------------*/
/* Exported functions --------------------------------------------------------*/
T_DjiReturnCode DjiTest_CameraEmuMediaStartService(void);
T_DjiReturnCode DjiTest_CameraEmuSetMediaFilePath(const char *path);
T_DjiReturnCode DjiTest_CameraMediaGetFileInfo(const char *filePath, T_DjiCameraMediaFileInfo *fileInfo);
#ifdef __cplusplus
}
#endif
#endif // TEST_PAYLOAD_CAM_EMU_MEDIA_H
/************************ (C) COPYRIGHT DJI Innovations *******END OF FILE******/

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,274 @@
/**
********************************************************************
* @file test_camera_manager.h
* @brief This is the header file for "test_camera_manager.c", defining the structure and
* (exported) function prototypes.
*
* @copyright (c) 2021 DJI. All rights reserved.
*
* All information contained herein is, and remains, the property of DJI.
* The intellectual and technical concepts contained herein are proprietary
* to DJI and may be covered by U.S. and foreign patents, patents in process,
* and protected by trade secret or copyright law. Dissemination of this
* information, including but not limited to data and other proprietary
* material(s) incorporated within the information, in any form, is strictly
* prohibited without the express written consent of DJI.
*
* If you receive this source code without DJIs authorization, you may not
* further disseminate the information, and you must immediately remove the
* source code and notify DJI of its removal. DJI reserves the right to pursue
* legal actions against you for any loss(es) or damage(s) caused by your
* failure to do so.
*
*********************************************************************
*/
/* Define to prevent recursive inclusion -------------------------------------*/
#ifndef TEST_CAMERA_MANAGER_H
#define TEST_CAMERA_MANAGER_H
/* Includes ------------------------------------------------------------------*/
#include "dji_typedef.h"
#include "dji_camera_manager.h"
#ifdef __cplusplus
extern "C" {
#endif
/* Exported constants --------------------------------------------------------*/
/* Exported types ------------------------------------------------------------*/
typedef enum {
E_DJI_TEST_CAMERA_MANAGER_SAMPLE_SELECT_SET_CAMERA_SHUTTER_SPEED,
E_DJI_TEST_CAMERA_MANAGER_SAMPLE_SELECT_SET_CAMERA_APERTURE,
E_DJI_TEST_CAMERA_MANAGER_SAMPLE_SELECT_SET_CAMERA_EV,
E_DJI_TEST_CAMERA_MANAGER_SAMPLE_SELECT_SET_CAMERA_ISO,
E_DJI_TEST_CAMERA_MANAGER_SAMPLE_SELECT_SET_CAMERA_FOCUS_POINT,
E_DJI_TEST_CAMERA_MANAGER_SAMPLE_SELECT_SET_CAMERA_TAP_ZOOM_POINT,
E_DJI_TEST_CAMERA_MANAGER_SAMPLE_SELECT_SET_CAMERA_ZOOM_PARAM,
E_DJI_TEST_CAMERA_MANAGER_SAMPLE_SELECT_SHOOT_SINGLE_PHOTO,
E_DJI_TEST_CAMERA_MANAGER_SAMPLE_SELECT_SHOOT_BURST_PHOTO,
E_DJI_TEST_CAMERA_MANAGER_SAMPLE_SELECT_SHOOT_INTERVAL_PHOTO,
E_DJI_TEST_CAMERA_MANAGER_SAMPLE_SELECT_RECORD_VIDEO,
E_DJI_TEST_CAMERA_MANAGER_SAMPLE_SELECT_DOWNLOAD_AND_DELETE_MEDIA_FILE,
E_DJI_TEST_CAMERA_MANAGER_SAMPLE_SELECT_DOWNLOAD_FILE_LIST_BY_SLICES,
E_DJI_TEST_CAMERA_MANAGER_SAMPLE_SELECT_THERMOMETRY,
E_DJI_TEST_CAMERA_MANAGER_SAMPLE_SELECT_GET_LIDAR_RANGING_INFO,
E_DJI_TEST_CAMERA_MANAGER_SAMPLE_SELECT_IR_CAMERA_ZOOM_PARAM,
E_DJI_TEST_CAMERA_MANAGER_SAMPLE_SELECT_SET_NIGHT_SCENE_MODE,
E_DJI_TEST_CAMERA_MANAGER_SAMPLE_SELECT_SET_CAPTURE_RECORDING_STREAMS,
E_DJI_TEST_CAMERA_MANAGER_SAMPLE_SELECT_SHOW_STORAGE_INFO,
E_DJI_TEST_CAMERA_MANAGER_SAMPLE_SELECT_FORMAT_SD_CARD,
E_DJI_TEST_CAMERA_MANAGER_SAMPLE_SELECT_SET_LINK_ZOOM,
E_DJI_TEST_CAMERA_MANAGER_SAMPLE_SELECT_SET_USER_CUSTOM_DIR_FILE_NAME,
E_DJI_TEST_CAMERA_MANAGER_SAMPLE_SELECT_RESET_CAMERA_SETTINGS,
E_DJI_TEST_CAMERA_MANAGER_SAMPLE_SELECT_SET_AE_LOCK_MODE,
E_DJI_TEST_CAMERA_MANAGER_SAMPLE_SELECT_SET_FOCUS_RING_VALUE,
E_DJI_TEST_CAMERA_MANAGER_SAMPLE_SELECT_CONNECT_STATUS_TEST,
E_DJI_TEST_CAMERA_MANAGER_SAMPLE_SELECT_SET_GET_PHOTO_VIDEO_PARAM,
E_DJI_TEST_CAMERA_MANAGER_SAMPLE_SELECT_SET_METERING_MODE,
E_DJI_TEST_CAMERA_MANAGER_SAMPLE_SELECT_SET_METERING_POINT,
E_DJI_TEST_CAMERA_MANAGER_SAMPLE_SELECT_FFC_MODE_AND_TRRIGER,
E_DJI_TEST_CAMERA_MANAGER_SAMPLE_SELECT_SET_GAIN_MODE,
E_DJI_TEST_CAMERA_MANAGER_SAMPLE_SELECT_GET_CAMERA_STATUS,
E_DJI_TEST_CAMERA_MANAGER_SAMPLE_SELECT_SUBSCRIBE_POINT_CLOUD,
E_DJI_TEST_CAMERA_MANAGER_SAMPLE_SELECT_INDEX_MAX
} E_DjiTestCameraManagerSampleSelect;
/* Exported functions --------------------------------------------------------*/
/*! @brief Sample to set exposure compensation value for camera, using async
* api
*
* @note In this interface, exposure compensation value will be got then be
* set.
* @param index payload node index, input limit see enum
* DJI::OSDK::PayloadIndexType
* @param dataTarget the target exposure compensation value
* @return T_DjiReturnCode error code
*/
T_DjiReturnCode DjiTest_CameraManagerSetEV(E_DjiMountPosition position,
E_DjiCameraManagerExposureCompensation exposureCompensation);
/*! @brief Sample to set exposure mode for camera, using async api
*
* @note In this interface, exposure will be got then be set.
* @param index payload node index, input limit see enum
* DJI::OSDK::PayloadIndexType
* @param dataTarget the target exposure mode
* @return T_DjiReturnCode error code
*/
T_DjiReturnCode DjiTest_CameraManagerSetExposureMode(E_DjiMountPosition position,
E_DjiCameraManagerExposureMode exposureMode);
/*! @brief Sample to set ISO value for camera, using async api
*
* @note In this interface, ISO will be got then be set.
* @param index payload node index, input limit see enum
* DJI::OSDK::PayloadIndexType
* @param dataTarget the target ISO value
* @return T_DjiReturnCode error code
*/
T_DjiReturnCode DjiTest_CameraManagerSetISO(E_DjiMountPosition position,
E_DjiCameraManagerISO isoData);
/*! @brief Sample to set shutter speed for camera, using async api
*
* @note In this interface, shutter speed will be got then be set.
* @param index payload node index, input limit see enum
* DJI::OSDK::PayloadIndexType
* @param dataTarget the target shutter speed
* @return T_DjiReturnCode error code
*/
T_DjiReturnCode DjiTest_CameraManagerSetShutterSpeed(E_DjiMountPosition position,
E_DjiCameraManagerShutterSpeed shutterSpeed);
/*! @brief Sample to set shutter aperture value for camera, using async api
*
* @note In this interface, aperture value will be got then be set.
* @param index payload node index, input limit see enum
* DJI::OSDK::PayloadIndexType
* @param dataTarget the target aperture value
* @return T_DjiReturnCode error code
*/
T_DjiReturnCode DjiTest_CameraManagerSetAperture(E_DjiMountPosition position,
E_DjiCameraManagerAperture aperture);
/*! @brief Sample to set focus point for camera, using async api
*
* @note In this interface, focus mode will be set to be AUTO. Then the
* focus point will be set to be (x, y)
* @param index payload node index, input limit see enum
* DJI::OSDK::PayloadIndexType
* @param x the x value of target focus point, 0~1
* @param y the y value of target focus point, 0~1
* @return T_DjiReturnCode error code
*/
T_DjiReturnCode DjiTest_CameraManagerSetFocusPoint(E_DjiMountPosition position,
T_DjiCameraManagerFocusPosData tapFocusPos);
/*! @brief Sample to set tap-zoom point for camera, using async api
*
* @note In this interface, tap-zoom function will be enable and the
* multiplier will be set. Then the tap-zoom function will start with the
* target tap-zoom point (x, y)
* @param index payload node index, input limit see enum
* DJI::OSDK::PayloadIndexType
* @param multiplier the zoom multiplier of each tap zoom
* @param x the x value of target tap-zoom point, 0~1
* @param y the y value of target tap-zoom point, 0~1
* @return T_DjiReturnCode error code
*/
T_DjiReturnCode DjiTest_CameraManagerSetTapZoomPoint(E_DjiMountPosition position, uint8_t multiplier,
T_DjiCameraManagerTapZoomPosData tapZoomPosData);
/*! @brief Sample to execute continuous zoom on camera, using sync api
*
* @note It is only supported by X5, X5R and X5S camera on Osmo with lens
* Olympus M.Zuiko ED 14-42mm f/3.5-5.6 EZ, Z3 camera, Z30 camera.
* @note In this interface, the zoom will start with the designated direction
* and speed, and will stop after zoomTimeInSecond second(s).
* @param index payload node index, input limit see enum
* DJI::OSDK::PayloadIndexType
* @param direction the choice of zoom out or zoom in
* @param speed zooming speed
* @return T_DjiReturnCode error code
*/
T_DjiReturnCode DjiTest_CameraManagerStartContinuousZoom(E_DjiMountPosition position,
E_DjiCameraZoomDirection zoomDirection,
E_DjiCameraZoomSpeed zoomSpeed);
/*! @brief Sample to execute position zoom on camera, using sync api
*
* @note It is only supported by X5, X5R and X5S camera on Osmo with lens
* Olympus M.Zuiko ED 14-42mm f/3.5-5.6 EZ, Z3 camera, Z30 camera.
* @note In this interface, the zoom will set the zoom factor as the your
* target value.
* @param index payload node index, input limit see enum
* DJI::OSDK::PayloadIndexType
* @param factor target zoom factor
* @return T_DjiReturnCode error code
*/
T_DjiReturnCode DjiTest_CameraManagerOpticalZoom(E_DjiMountPosition position,
E_DjiCameraZoomDirection zoomDirection,
dji_f32_t factor);
/*! @brief Sample to stop continuous zoom on camera, using async api
*
* @note It is only supported by X5, X5R and X5S camera on Osmo with lens
* Olympus M.Zuiko ED 14-42mm f/3.5-5.6 EZ, Z3 camera, Z30 camera.
* @param index payload node index, input limit see enum
* DJI::OSDK::PayloadIndexType
* @return T_DjiReturnCode error code
*/
T_DjiReturnCode DjiTest_CameraManagerStopContinuousZoom(E_DjiMountPosition position);
/*! @brief Sample to shoot single photo, using async api
*
* @note In this interface, camera will be set to be the SHOOT_PHOTO mode
* then start to shoot a single photo.
* @param index payload node index, input limit see enum
* DJI::OSDK::PayloadIndexType
* @return T_DjiReturnCode error code
*/
T_DjiReturnCode DjiTest_CameraManagerStartShootSinglePhoto(E_DjiMountPosition position);
/*! @brief Sample to shoot burst photo, using async api
*
* @note In this interface, camera will be set to be the SHOOT_PHOTO mode
* then start to shoot a burst photo.
* @param index payload node index, input limit see enum
* DJI::OSDK::PayloadIndexType
* @param count The number of pictures in each burst shooting
* @return T_DjiReturnCode error code
*/
T_DjiReturnCode DjiTest_CameraManagerStartShootBurstPhoto(E_DjiMountPosition position,
E_DjiCameraBurstCount burstCount);
/*! @brief Sample to start shooting interval photo, using async api
*
* @note In this interface, camera will be set to be the SHOOT_PHOTO mode
* then start to shoot a interval photo.
* @param index payload node index, input limit see enum
* DJI::OSDK::PayloadIndexType
* @param intervalData the parameter of interval shooting
* @return T_DjiReturnCode error code
*/
T_DjiReturnCode DjiTest_CameraManagerStartShootIntervalPhoto(E_DjiMountPosition position,
T_DjiCameraPhotoTimeIntervalSettings intervalData);
/*! @brief Sample to stop shooting, using async api
*
* @note In this interface, camera will stop all the shooting action
* @param index payload node index, input limit see enum
* DJI::OSDK::PayloadIndexType
* @return T_DjiReturnCode error code
*/
T_DjiReturnCode DjiTest_CameraManagerStopShootPhoto(E_DjiMountPosition position);
/*! @brief Sample to start record video, using async api
*
* @note In this interface, camera will be set to be the RECORD_VIDEO mode
* then start to record video.
* @param index payload node index, input limit see enum
* DJI::OSDK::PayloadIndexType
* @return T_DjiReturnCode error code
*/
T_DjiReturnCode DjiTest_CameraManagerStartRecordVideo(E_DjiMountPosition position);
/*! @brief Sample to stop record video, using async api
*
* @note In this interface, camera will be set to be the RECORD_VIDEO mode
* then stop recording video.
* @param index payload node index, input limit see enum
* DJI::OSDK::PayloadIndexType
* @return T_DjiReturnCode error code
*/
T_DjiReturnCode DjiTest_CameraManagerStopRecordVideo(E_DjiMountPosition position);
T_DjiReturnCode DjiTest_CameraManagerRunSample(E_DjiMountPosition mountPosition,
E_DjiTestCameraManagerSampleSelect cameraManagerSampleSelect);
#ifdef __cplusplus
}
#endif
#endif // TEST_CAMERA_MANAGER_H
/************************ (C) COPYRIGHT DJI Innovations *******END OF FILE******/

View File

@ -0,0 +1,387 @@
/**
********************************************************************
* @file test_data_transmission.c
* @brief
*
* @copyright (c) 2021 DJI. All rights reserved.
*
* All information contained herein is, and remains, the property of DJI.
* The intellectual and technical concepts contained herein are proprietary
* to DJI and may be covered by U.S. and foreign patents, patents in process,
* and protected by trade secret or copyright law. Dissemination of this
* information, including but not limited to data and other proprietary
* material(s) incorporated within the information, in any form, is strictly
* prohibited without the express written consent of DJI.
*
* If you receive this source code without DJIs authorization, you may not
* further disseminate the information, and you must immediately remove the
* source code and notify DJI of its removal. DJI reserves the right to pursue
* legal actions against you for any loss(es) or damage(s) caused by your
* failure to do so.
*
*********************************************************************
*/
/* Includes ------------------------------------------------------------------*/
#include "test_data_transmission.h"
#include "dji_logger.h"
#include "dji_platform.h"
#include "utils/util_misc.h"
#include "dji_low_speed_data_channel.h"
#include "dji_high_speed_data_channel.h"
#include "dji_aircraft_info.h"
#include "widget_interaction_test/test_widget_interaction.h"
/* Private constants ---------------------------------------------------------*/
#define DATA_TRANSMISSION_TASK_FREQ (1)
#define DATA_TRANSMISSION_TASK_STACK_SIZE (2048)
/* Private types -------------------------------------------------------------*/
/* Private functions declaration ---------------------------------------------*/
static void *UserDataTransmission_Task(void *arg);
static T_DjiReturnCode ReceiveDataFromMobile(const uint8_t *data, uint16_t len);
static T_DjiReturnCode ReceiveDataFromCloud(const uint8_t *data, uint16_t len);
static T_DjiReturnCode ReceiveDataFromExtensionPort(const uint8_t *data, uint16_t len);
static T_DjiReturnCode ReceiveDataFromPayload(const uint8_t *data, uint16_t len);
static T_DjiReturnCode ReceiveDataFromPayload1(const uint8_t *data, uint16_t len);
static T_DjiReturnCode ReceiveDataFromPayload2(const uint8_t *data, uint16_t len);
static T_DjiReturnCode ReceiveDataFromPayload3(const uint8_t *data, uint16_t len);
/* Private variables ---------------------------------------------------------*/
static T_DjiTaskHandle s_userDataTransmissionThread;
static T_DjiAircraftInfoBaseInfo s_aircraftInfoBaseInfo;
/* Exported functions definition ---------------------------------------------*/
T_DjiReturnCode DjiTest_DataTransmissionStartService(void)
{
T_DjiReturnCode djiStat;
T_DjiOsalHandler *osalHandler = DjiPlatform_GetOsalHandler();
E_DjiChannelAddress channelAddress;
const T_DjiDataChannelBandwidthProportionOfHighspeedChannel bandwidthProportionOfHighspeedChannel =
{10, 60, 30};
char ipAddr[DJI_IP_ADDR_STR_SIZE_MAX];
uint16_t port;
djiStat = DjiLowSpeedDataChannel_Init();
if (djiStat != DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS) {
USER_LOG_ERROR("init data transmission module error.");
return DJI_ERROR_SYSTEM_MODULE_CODE_UNKNOWN;
}
djiStat = DjiAircraftInfo_GetBaseInfo(&s_aircraftInfoBaseInfo);
if (djiStat != DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS) {
USER_LOG_ERROR("get aircraft base info error");
return DJI_ERROR_SYSTEM_MODULE_CODE_SYSTEM_ERROR;
}
channelAddress = DJI_CHANNEL_ADDRESS_MASTER_RC_APP;
djiStat = DjiLowSpeedDataChannel_RegRecvDataCallback(channelAddress, ReceiveDataFromMobile);
if (djiStat != DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS) {
USER_LOG_ERROR("register receive data from mobile error.");
return DJI_ERROR_SYSTEM_MODULE_CODE_UNKNOWN;
}
if (s_aircraftInfoBaseInfo.aircraftType == DJI_AIRCRAFT_TYPE_M30 ||
s_aircraftInfoBaseInfo.aircraftType == DJI_AIRCRAFT_TYPE_M30T) {
channelAddress = DJI_CHANNEL_ADDRESS_CLOUD_API;
djiStat = DjiLowSpeedDataChannel_RegRecvDataCallback(channelAddress, ReceiveDataFromCloud);
if (djiStat != DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS) {
USER_LOG_ERROR("register receive data from cloud error.");
return DJI_ERROR_SYSTEM_MODULE_CODE_UNKNOWN;
}
}
if (s_aircraftInfoBaseInfo.mountPosition == DJI_MOUNT_POSITION_PAYLOAD_PORT_NO1 ||
s_aircraftInfoBaseInfo.mountPosition == DJI_MOUNT_POSITION_PAYLOAD_PORT_NO2 ||
s_aircraftInfoBaseInfo.mountPosition == DJI_MOUNT_POSITION_PAYLOAD_PORT_NO3) {
channelAddress = DJI_CHANNEL_ADDRESS_EXTENSION_PORT;
djiStat = DjiLowSpeedDataChannel_RegRecvDataCallback(channelAddress, ReceiveDataFromExtensionPort);
if (djiStat != DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS) {
USER_LOG_ERROR("register receive data from extension port error.");
return DJI_ERROR_SYSTEM_MODULE_CODE_UNKNOWN;
}
djiStat = DjiHighSpeedDataChannel_SetBandwidthProportion(bandwidthProportionOfHighspeedChannel);
if (djiStat != DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS) {
USER_LOG_ERROR("Set data channel bandwidth width proportion error.");
return DJI_ERROR_SYSTEM_MODULE_CODE_UNKNOWN;
}
djiStat = DjiHighSpeedDataChannel_GetDataStreamRemoteAddress(ipAddr, &port);
if (djiStat == DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS) {
USER_LOG_DEBUG("Get data stream remote address: %s, port: %d", ipAddr, port);
} else {
USER_LOG_ERROR("get data stream remote address error.");
}
} else if (s_aircraftInfoBaseInfo.mountPosition == DJI_MOUNT_POSITION_EXTENSION_PORT
|| DJI_MOUNT_POSITION_EXTENSION_LITE_PORT == s_aircraftInfoBaseInfo.mountPosition) {
channelAddress = DJI_CHANNEL_ADDRESS_PAYLOAD_PORT_NO1;
djiStat = DjiLowSpeedDataChannel_RegRecvDataCallback(channelAddress, ReceiveDataFromPayload1);
if (djiStat != DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS) {
USER_LOG_ERROR("register receive data from payload NO1 error.");
return DJI_ERROR_SYSTEM_MODULE_CODE_UNKNOWN;
}
channelAddress = DJI_CHANNEL_ADDRESS_PAYLOAD_PORT_NO2;
djiStat = DjiLowSpeedDataChannel_RegRecvDataCallback(channelAddress, ReceiveDataFromPayload2);
if (djiStat != DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS) {
USER_LOG_ERROR("register receive data from payload NO1 error.");
return DJI_ERROR_SYSTEM_MODULE_CODE_UNKNOWN;
}
channelAddress = DJI_CHANNEL_ADDRESS_PAYLOAD_PORT_NO3;
djiStat = DjiLowSpeedDataChannel_RegRecvDataCallback(channelAddress, ReceiveDataFromPayload3);
if (djiStat != DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS) {
USER_LOG_ERROR("register receive data from payload NO1 error.");
return DJI_ERROR_SYSTEM_MODULE_CODE_UNKNOWN;
}
} else {
return DJI_ERROR_SYSTEM_MODULE_CODE_NONSUPPORT;
}
if (osalHandler->TaskCreate("user_transmission_task", UserDataTransmission_Task,
DATA_TRANSMISSION_TASK_STACK_SIZE, NULL, &s_userDataTransmissionThread) !=
DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS) {
USER_LOG_ERROR("user data transmission task create error.");
return DJI_ERROR_SYSTEM_MODULE_CODE_UNKNOWN;
}
return DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS;
}
T_DjiReturnCode DjiTest_DataTransmissionStopService(void)
{
T_DjiOsalHandler *osalHandler = DjiPlatform_GetOsalHandler();
T_DjiReturnCode returnCode;
if (osalHandler->TaskDestroy(s_userDataTransmissionThread) != DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS) {
USER_LOG_ERROR("user data transmission task destroy error.");
return DJI_ERROR_SYSTEM_MODULE_CODE_UNKNOWN;
}
returnCode = DjiLowSpeedDataChannel_DeInit();
if (returnCode != DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS) {
USER_LOG_ERROR("deinit data transmission module error.");
return DJI_ERROR_SYSTEM_MODULE_CODE_UNKNOWN;
}
return DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS;
}
/* Private functions definition-----------------------------------------------*/
#ifndef __CC_ARM
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wmissing-noreturn"
#pragma GCC diagnostic ignored "-Wreturn-type"
#endif
static void *UserDataTransmission_Task(void *arg)
{
T_DjiReturnCode djiStat;
const uint8_t dataToBeSent[] = "DJI Data Transmission Test Data.";
T_DjiDataChannelState state = {0};
T_DjiOsalHandler *osalHandler = DjiPlatform_GetOsalHandler();
E_DjiChannelAddress channelAddress;
USER_UTIL_UNUSED(arg);
while (1) {
osalHandler->TaskSleepMs(1000 / DATA_TRANSMISSION_TASK_FREQ);
channelAddress = DJI_CHANNEL_ADDRESS_MASTER_RC_APP;
djiStat = DjiLowSpeedDataChannel_SendData(channelAddress, dataToBeSent, sizeof(dataToBeSent));
if (djiStat != DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS)
USER_LOG_ERROR("send data to mobile error.");
djiStat = DjiLowSpeedDataChannel_GetSendDataState(channelAddress, &state);
if (djiStat == DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS) {
USER_LOG_DEBUG(
"send to mobile state: realtimeBandwidthBeforeFlowController: %d, realtimeBandwidthAfterFlowController: %d, busyState: %d.",
state.realtimeBandwidthBeforeFlowController, state.realtimeBandwidthAfterFlowController,
state.busyState);
} else {
USER_LOG_ERROR("get send to mobile channel state error.");
}
if (s_aircraftInfoBaseInfo.aircraftType == DJI_AIRCRAFT_TYPE_M30 ||
s_aircraftInfoBaseInfo.aircraftType == DJI_AIRCRAFT_TYPE_M30T) {
channelAddress = DJI_CHANNEL_ADDRESS_CLOUD_API;
djiStat = DjiLowSpeedDataChannel_SendData(channelAddress, dataToBeSent, sizeof(dataToBeSent));
if (djiStat != DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS)
USER_LOG_ERROR("send data to cloud error.");
djiStat = DjiLowSpeedDataChannel_GetSendDataState(channelAddress, &state);
if (djiStat == DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS) {
USER_LOG_DEBUG(
"send to cloud state: realtimeBandwidthBeforeFlowController: %d, realtimeBandwidthAfterFlowController: %d, busyState: %d.",
state.realtimeBandwidthBeforeFlowController, state.realtimeBandwidthAfterFlowController,
state.busyState);
} else {
USER_LOG_ERROR("get send to cloud channel state error.");
}
}
if (s_aircraftInfoBaseInfo.mountPosition == DJI_MOUNT_POSITION_PAYLOAD_PORT_NO1 ||
s_aircraftInfoBaseInfo.mountPosition == DJI_MOUNT_POSITION_PAYLOAD_PORT_NO2 ||
s_aircraftInfoBaseInfo.mountPosition == DJI_MOUNT_POSITION_PAYLOAD_PORT_NO3) {
channelAddress = DJI_CHANNEL_ADDRESS_EXTENSION_PORT;
djiStat = DjiLowSpeedDataChannel_SendData(channelAddress, dataToBeSent, sizeof(dataToBeSent));
if (djiStat != DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS)
USER_LOG_ERROR("send data to extension port error.");
djiStat = DjiLowSpeedDataChannel_GetSendDataState(channelAddress, &state);
if (djiStat == DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS) {
USER_LOG_DEBUG(
"send to extension port state: realtimeBandwidthBeforeFlowController: %d, realtimeBandwidthAfterFlowController: %d, busyState: %d.",
state.realtimeBandwidthBeforeFlowController, state.realtimeBandwidthAfterFlowController,
state.busyState);
} else {
USER_LOG_ERROR("get send to extension port channel state error.");
}
if (DjiPlatform_GetSocketHandler() != NULL) {
#ifdef SYSTEM_ARCH_LINUX
djiStat = DjiHighSpeedDataChannel_SendDataStreamData(dataToBeSent, sizeof(dataToBeSent));
if (djiStat != DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS)
USER_LOG_ERROR("send data to data stream error.");
djiStat = DjiHighSpeedDataChannel_GetDataStreamState(&state);
if (djiStat == DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS) {
USER_LOG_DEBUG(
"data stream state: realtimeBandwidthLimit: %d, realtimeBandwidthBeforeFlowController: %d, busyState: %d.",
state.realtimeBandwidthLimit, state.realtimeBandwidthBeforeFlowController, state.busyState);
} else {
USER_LOG_ERROR("get data stream state error.");
}
#endif
}
} else if (s_aircraftInfoBaseInfo.mountPosition == DJI_MOUNT_POSITION_EXTENSION_PORT
|| DJI_MOUNT_POSITION_EXTENSION_LITE_PORT == s_aircraftInfoBaseInfo.mountPosition) {
channelAddress = DJI_CHANNEL_ADDRESS_PAYLOAD_PORT_NO1;
djiStat = DjiLowSpeedDataChannel_SendData(channelAddress, dataToBeSent, sizeof(dataToBeSent));
if (djiStat != DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS)
USER_LOG_ERROR("send data to extension port error.");
djiStat = DjiLowSpeedDataChannel_GetSendDataState(channelAddress, &state);
if (djiStat == DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS) {
USER_LOG_DEBUG(
"send to extension port state: realtimeBandwidthBeforeFlowController: %d, realtimeBandwidthAfterFlowController: %d, busyState: %d.",
state.realtimeBandwidthBeforeFlowController, state.realtimeBandwidthAfterFlowController,
state.busyState);
} else {
USER_LOG_ERROR("get send to extension port channel state error.");
}
}
}
}
#ifndef __CC_ARM
#pragma GCC diagnostic pop
#endif
static T_DjiReturnCode ReceiveDataFromMobile(const uint8_t *data, uint16_t len)
{
char *printData = NULL;
T_DjiOsalHandler *osalHandler = DjiPlatform_GetOsalHandler();
printData = osalHandler->Malloc(len + 1);
if (printData == NULL) {
USER_LOG_ERROR("malloc memory for printData fail.");
return DJI_ERROR_SYSTEM_MODULE_CODE_MEMORY_ALLOC_FAILED;
}
strncpy(printData, (const char *) data, len);
printData[len] = '\0';
USER_LOG_INFO("receive data from mobile: %s, len:%d.", printData, len);
DjiTest_WidgetLogAppend("receive data: %s, len:%d.", printData, len);
osalHandler->Free(printData);
return DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS;
}
static T_DjiReturnCode ReceiveDataFromCloud(const uint8_t *data, uint16_t len)
{
char *printData = NULL;
T_DjiOsalHandler *osalHandler = DjiPlatform_GetOsalHandler();
printData = osalHandler->Malloc(len + 1);
if (printData == NULL) {
USER_LOG_ERROR("malloc memory for printData fail.");
return DJI_ERROR_SYSTEM_MODULE_CODE_MEMORY_ALLOC_FAILED;
}
strncpy(printData, (const char *) data, len);
printData[len] = '\0';
USER_LOG_INFO("receive data from cloud: %s, len:%d.", printData, len);
DjiTest_WidgetLogAppend("receive data: %s, len:%d.", printData, len);
osalHandler->Free(printData);
return DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS;
}
static T_DjiReturnCode ReceiveDataFromExtensionPort(const uint8_t *data, uint16_t len)
{
char *printData = NULL;
T_DjiOsalHandler *osalHandler = DjiPlatform_GetOsalHandler();
printData = osalHandler->Malloc(len + 1);
if (printData == NULL) {
USER_LOG_ERROR("malloc memory for printData fail.");
return DJI_ERROR_SYSTEM_MODULE_CODE_MEMORY_ALLOC_FAILED;
}
strncpy(printData, (const char *) data, len);
printData[len] = '\0';
USER_LOG_INFO("receive data from extension port: %s, len:%d.", printData, len);
DjiTest_WidgetLogAppend("receive data: %s, len:%d.", printData, len);
osalHandler->Free(printData);
return DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS;
}
static T_DjiReturnCode ReceiveDataFromPayload(const uint8_t *data, uint16_t len)
{
char *printData = NULL;
T_DjiOsalHandler *osalHandler = DjiPlatform_GetOsalHandler();
printData = osalHandler->Malloc(len + 1);
if (printData == NULL) {
USER_LOG_ERROR("malloc memory for printData fail.");
return DJI_ERROR_SYSTEM_MODULE_CODE_MEMORY_ALLOC_FAILED;
}
strncpy(printData, (const char *) data, len);
printData[len] = '\0';
USER_LOG_INFO("receive data from payload port: %s, len:%d.", printData, len);
DjiTest_WidgetLogAppend("receive data: %s, len:%d.", printData, len);
osalHandler->Free(printData);
return DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS;
}
static T_DjiReturnCode ReceiveDataFromPayload1(const uint8_t *data, uint16_t len)
{
USER_LOG_INFO("Receive from payload on port 1");
return ReceiveDataFromPayload(data, len);
}
static T_DjiReturnCode ReceiveDataFromPayload2(const uint8_t *data, uint16_t len)
{
USER_LOG_INFO("Receive from payload on port 2");
return ReceiveDataFromPayload(data, len);
}
static T_DjiReturnCode ReceiveDataFromPayload3(const uint8_t *data, uint16_t len)
{
USER_LOG_INFO("Receive from payload on port 3");
return ReceiveDataFromPayload(data, len);
}
/****************** (C) COPYRIGHT DJI Innovations *****END OF FILE****/

View File

@ -0,0 +1,52 @@
/**
********************************************************************
* @file test_data_transmission.h
* @brief This is the header file for "test_data_transmission.c", defining the structure and
* (exported) function prototypes.
*
* @copyright (c) 2021 DJI. All rights reserved.
*
* All information contained herein is, and remains, the property of DJI.
* The intellectual and technical concepts contained herein are proprietary
* to DJI and may be covered by U.S. and foreign patents, patents in process,
* and protected by trade secret or copyright law. Dissemination of this
* information, including but not limited to data and other proprietary
* material(s) incorporated within the information, in any form, is strictly
* prohibited without the express written consent of DJI.
*
* If you receive this source code without DJIs authorization, you may not
* further disseminate the information, and you must immediately remove the
* source code and notify DJI of its removal. DJI reserves the right to pursue
* legal actions against you for any loss(es) or damage(s) caused by your
* failure to do so.
*
*********************************************************************
*/
/* Define to prevent recursive inclusion -------------------------------------*/
#ifndef TEST_DATA_TRANSMISSION_H
#define TEST_DATA_TRANSMISSION_H
/* Includes ------------------------------------------------------------------*/
#include "dji_typedef.h"
#ifdef __cplusplus
extern "C" {
#endif
/* Exported constants --------------------------------------------------------*/
/* Exported types ------------------------------------------------------------*/
/* Exported functions --------------------------------------------------------*/
T_DjiReturnCode DjiTest_DataTransmissionStartService(void);
T_DjiReturnCode DjiTest_DataTransmissionStopService(void);
#ifdef __cplusplus
}
#endif
#endif // TEST_DATA_TRANSMISSION_H
/************************ (C) COPYRIGHT DJI Innovations *******END OF FILE******/

View File

@ -0,0 +1,355 @@
/**
********************************************************************
* @file test_fc_subscription.c
* @brief
*
* @copyright (c) 2021 DJI. All rights reserved.
*
* All information contained herein is, and remains, the property of DJI.
* The intellectual and technical concepts contained herein are proprietary
* to DJI and may be covered by U.S. and foreign patents, patents in process,
* and protected by trade secret or copyright law. Dissemination of this
* information, including but not limited to data and other proprietary
* material(s) incorporated within the information, in any form, is strictly
* prohibited without the express written consent of DJI.
*
* If you receive this source code without DJIs authorization, you may not
* further disseminate the information, and you must immediately remove the
* source code and notify DJI of its removal. DJI reserves the right to pursue
* legal actions against you for any loss(es) or damage(s) caused by your
* failure to do so.
*
*********************************************************************
*/
/* Includes ------------------------------------------------------------------*/
#include <utils/util_misc.h>
#include <math.h>
#include "test_fc_subscription.h"
#include "dji_logger.h"
#include "dji_platform.h"
#include "widget_interaction_test/test_widget_interaction.h"
/* Private constants ---------------------------------------------------------*/
#define FC_SUBSCRIPTION_TASK_FREQ (1)
#define FC_SUBSCRIPTION_TASK_STACK_SIZE (1024)
/* Private types -------------------------------------------------------------*/
/* Private functions declaration ---------------------------------------------*/
static void *UserFcSubscription_Task(void *arg);
static T_DjiReturnCode DjiTest_FcSubscriptionReceiveQuaternionCallback(const uint8_t *data, uint16_t dataSize,
const T_DjiDataTimestamp *timestamp);
/* Private variables ---------------------------------------------------------*/
static T_DjiTaskHandle s_userFcSubscriptionThread;
static bool s_userFcSubscriptionDataShow = false;
static uint8_t s_totalSatelliteNumberUsed = 0;
static uint32_t s_userFcSubscriptionDataCnt = 0;
/* Exported functions definition ---------------------------------------------*/
T_DjiReturnCode DjiTest_FcSubscriptionStartService(void)
{
T_DjiReturnCode djiStat;
T_DjiOsalHandler *osalHandler = NULL;
osalHandler = DjiPlatform_GetOsalHandler();
djiStat = DjiFcSubscription_Init();
if (djiStat != DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS) {
USER_LOG_ERROR("init data subscription module error.");
return DJI_ERROR_SYSTEM_MODULE_CODE_UNKNOWN;
}
djiStat = DjiFcSubscription_SubscribeTopic(DJI_FC_SUBSCRIPTION_TOPIC_QUATERNION, DJI_DATA_SUBSCRIPTION_TOPIC_50_HZ,
DjiTest_FcSubscriptionReceiveQuaternionCallback);
if (djiStat != DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS) {
USER_LOG_ERROR("Subscribe topic quaternion error.");
return DJI_ERROR_SYSTEM_MODULE_CODE_UNKNOWN;
} else {
USER_LOG_DEBUG("Subscribe topic quaternion success.");
}
djiStat = DjiFcSubscription_SubscribeTopic(DJI_FC_SUBSCRIPTION_TOPIC_VELOCITY, DJI_DATA_SUBSCRIPTION_TOPIC_1_HZ,
NULL);
if (djiStat != DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS) {
USER_LOG_ERROR("Subscribe topic velocity error.");
return DJI_ERROR_SYSTEM_MODULE_CODE_UNKNOWN;
} else {
USER_LOG_DEBUG("Subscribe topic velocity success.");
}
djiStat = DjiFcSubscription_SubscribeTopic(DJI_FC_SUBSCRIPTION_TOPIC_GPS_POSITION, DJI_DATA_SUBSCRIPTION_TOPIC_1_HZ,
NULL);
if (djiStat != DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS) {
USER_LOG_ERROR("Subscribe topic gps position error.");
return DJI_ERROR_SYSTEM_MODULE_CODE_UNKNOWN;
} else {
USER_LOG_DEBUG("Subscribe topic gps position success.");
}
djiStat = DjiFcSubscription_SubscribeTopic(DJI_FC_SUBSCRIPTION_TOPIC_GPS_DETAILS, DJI_DATA_SUBSCRIPTION_TOPIC_1_HZ,
NULL);
if (djiStat != DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS) {
USER_LOG_ERROR("Subscribe topic gps details error.");
return DJI_ERROR_SYSTEM_MODULE_CODE_UNKNOWN;
} else {
USER_LOG_DEBUG("Subscribe topic gps details success.");
}
if (osalHandler->TaskCreate("user_subscription_task", UserFcSubscription_Task,
FC_SUBSCRIPTION_TASK_STACK_SIZE, NULL, &s_userFcSubscriptionThread) !=
DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS) {
USER_LOG_ERROR("user data subscription task create error.");
return DJI_ERROR_SYSTEM_MODULE_CODE_UNKNOWN;
}
return DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS;
}
T_DjiReturnCode DjiTest_FcSubscriptionRunSample(void)
{
T_DjiReturnCode djiStat;
T_DjiOsalHandler *osalHandler = DjiPlatform_GetOsalHandler();
T_DjiFcSubscriptionVelocity velocity = {0};
T_DjiDataTimestamp timestamp = {0};
T_DjiFcSubscriptionGpsPosition gpsPosition = {0};
T_DjiFcSubscriptionSingleBatteryInfo singleBatteryInfo = {0};
USER_LOG_INFO("Fc subscription sample start");
s_userFcSubscriptionDataShow = true;
USER_LOG_INFO("--> Step 1: Init fc subscription module");
djiStat = DjiFcSubscription_Init();
if (djiStat != DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS) {
USER_LOG_ERROR("init data subscription module error.");
return DJI_ERROR_SYSTEM_MODULE_CODE_UNKNOWN;
}
USER_LOG_INFO("--> Step 2: Subscribe the topics of quaternion, velocity and gps position");
djiStat = DjiFcSubscription_SubscribeTopic(DJI_FC_SUBSCRIPTION_TOPIC_QUATERNION, DJI_DATA_SUBSCRIPTION_TOPIC_50_HZ,
DjiTest_FcSubscriptionReceiveQuaternionCallback);
if (djiStat != DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS) {
USER_LOG_ERROR("Subscribe topic quaternion error.");
return DJI_ERROR_SYSTEM_MODULE_CODE_UNKNOWN;
}
djiStat = DjiFcSubscription_SubscribeTopic(DJI_FC_SUBSCRIPTION_TOPIC_VELOCITY, DJI_DATA_SUBSCRIPTION_TOPIC_1_HZ,
NULL);
if (djiStat != DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS) {
USER_LOG_ERROR("Subscribe topic velocity error.");
return DJI_ERROR_SYSTEM_MODULE_CODE_UNKNOWN;
}
djiStat = DjiFcSubscription_SubscribeTopic(DJI_FC_SUBSCRIPTION_TOPIC_GPS_POSITION, DJI_DATA_SUBSCRIPTION_TOPIC_1_HZ,
NULL);
if (djiStat != DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS) {
USER_LOG_ERROR("Subscribe topic gps position error.");
return DJI_ERROR_SYSTEM_MODULE_CODE_UNKNOWN;
}
USER_LOG_INFO("--> Step 3: Get latest value of the subscribed topics in the next 10 seconds\r\n");
for (int i = 0; i < 10; ++i) {
osalHandler->TaskSleepMs(1000 / FC_SUBSCRIPTION_TASK_FREQ);
djiStat = DjiFcSubscription_GetLatestValueOfTopic(DJI_FC_SUBSCRIPTION_TOPIC_VELOCITY,
(uint8_t *) &velocity,
sizeof(T_DjiFcSubscriptionVelocity),
&timestamp);
if (djiStat != DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS) {
USER_LOG_ERROR("get value of topic velocity error.");
} else {
USER_LOG_INFO("velocity: x = %f y = %f z = %f healthFlag = %d, timestamp ms = %d us = %d.", velocity.data.x,
velocity.data.y,
velocity.data.z, velocity.health, timestamp.millisecond, timestamp.microsecond);
}
djiStat = DjiFcSubscription_GetLatestValueOfTopic(DJI_FC_SUBSCRIPTION_TOPIC_GPS_POSITION,
(uint8_t *) &gpsPosition,
sizeof(T_DjiFcSubscriptionGpsPosition),
&timestamp);
if (djiStat != DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS) {
USER_LOG_ERROR("get value of topic gps position error.");
} else {
USER_LOG_INFO("gps position: x = %d y = %d z = %d.", gpsPosition.x, gpsPosition.y, gpsPosition.z);
}
//Attention: if you want to subscribe the single battery info on M300 RTK, you need connect USB cable to
//OSDK device or use topic DJI_FC_SUBSCRIPTION_TOPIC_BATTERY_INFO instead.
djiStat = DjiFcSubscription_GetLatestValueOfTopic(DJI_FC_SUBSCRIPTION_TOPIC_BATTERY_SINGLE_INFO_INDEX1,
(uint8_t *) &singleBatteryInfo,
sizeof(T_DjiFcSubscriptionSingleBatteryInfo),
&timestamp);
if (djiStat != DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS) {
USER_LOG_ERROR("get value of topic battery single info index1 error.");
} else {
USER_LOG_INFO(
"battery single info index1: capacity percent = %ld% voltage = %ldV temperature = %.2f degree.",
singleBatteryInfo.batteryCapacityPercent,
singleBatteryInfo.currentVoltage / 1000,
(dji_f32_t) singleBatteryInfo.batteryTemperature / 10);
}
djiStat = DjiFcSubscription_GetLatestValueOfTopic(DJI_FC_SUBSCRIPTION_TOPIC_BATTERY_SINGLE_INFO_INDEX2,
(uint8_t *) &singleBatteryInfo,
sizeof(T_DjiFcSubscriptionSingleBatteryInfo),
&timestamp);
if (djiStat != DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS) {
USER_LOG_ERROR("get value of topic battery single info index2 error.");
} else {
USER_LOG_INFO(
"battery single info index2: capacity percent = %ld% voltage = %ldV temperature = %.2f degree.\r\n",
singleBatteryInfo.batteryCapacityPercent,
singleBatteryInfo.currentVoltage / 1000,
(dji_f32_t) singleBatteryInfo.batteryTemperature / 10);
}
}
USER_LOG_INFO("--> Step 4: Unsubscribe the topics of quaternion, velocity and gps position");
djiStat = DjiFcSubscription_UnSubscribeTopic(DJI_FC_SUBSCRIPTION_TOPIC_QUATERNION);
if (djiStat != DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS) {
USER_LOG_ERROR("UnSubscribe topic quaternion error.");
return DJI_ERROR_SYSTEM_MODULE_CODE_UNKNOWN;
}
djiStat = DjiFcSubscription_UnSubscribeTopic(DJI_FC_SUBSCRIPTION_TOPIC_VELOCITY);
if (djiStat != DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS) {
USER_LOG_ERROR("UnSubscribe topic quaternion error.");
return DJI_ERROR_SYSTEM_MODULE_CODE_UNKNOWN;
}
djiStat = DjiFcSubscription_UnSubscribeTopic(DJI_FC_SUBSCRIPTION_TOPIC_GPS_POSITION);
if (djiStat != DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS) {
USER_LOG_ERROR("UnSubscribe topic quaternion error.");
return DJI_ERROR_SYSTEM_MODULE_CODE_UNKNOWN;
}
USER_LOG_INFO("--> Step 5: Deinit fc subscription module");
djiStat = DjiFcSubscription_DeInit();
if (djiStat != DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS) {
USER_LOG_ERROR("Deinit fc subscription error.");
return DJI_ERROR_SYSTEM_MODULE_CODE_UNKNOWN;
}
s_userFcSubscriptionDataShow = false;
USER_LOG_INFO("Fc subscription sample end");
return DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS;
}
T_DjiReturnCode DjiTest_FcSubscriptionDataShowTrigger(void)
{
s_userFcSubscriptionDataShow = !s_userFcSubscriptionDataShow;
return DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS;
}
T_DjiReturnCode DjiTest_FcSubscriptionGetTotalSatelliteNumber(uint8_t *number)
{
*number = s_totalSatelliteNumberUsed;
return DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS;
}
/* Private functions definition-----------------------------------------------*/
#ifndef __CC_ARM
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wmissing-noreturn"
#pragma GCC diagnostic ignored "-Wreturn-type"
#endif
static void *UserFcSubscription_Task(void *arg)
{
T_DjiReturnCode djiStat;
T_DjiFcSubscriptionVelocity velocity = {0};
T_DjiDataTimestamp timestamp = {0};
T_DjiFcSubscriptionGpsPosition gpsPosition = {0};
T_DjiFcSubscriptionGpsDetails gpsDetails = {0};
T_DjiOsalHandler *osalHandler = NULL;
USER_UTIL_UNUSED(arg);
osalHandler = DjiPlatform_GetOsalHandler();
while (1) {
osalHandler->TaskSleepMs(1000 / FC_SUBSCRIPTION_TASK_FREQ);
djiStat = DjiFcSubscription_GetLatestValueOfTopic(DJI_FC_SUBSCRIPTION_TOPIC_VELOCITY,
(uint8_t *) &velocity,
sizeof(T_DjiFcSubscriptionVelocity),
&timestamp);
if (djiStat != DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS) {
USER_LOG_ERROR("get value of topic velocity error.");
}
if (s_userFcSubscriptionDataShow == true) {
USER_LOG_INFO("velocity: x %f y %f z %f, healthFlag %d.", velocity.data.x, velocity.data.y,
velocity.data.z, velocity.health);
}
djiStat = DjiFcSubscription_GetLatestValueOfTopic(DJI_FC_SUBSCRIPTION_TOPIC_GPS_POSITION,
(uint8_t *) &gpsPosition,
sizeof(T_DjiFcSubscriptionGpsPosition),
&timestamp);
if (djiStat != DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS) {
USER_LOG_ERROR("get value of topic gps position error.");
}
if (s_userFcSubscriptionDataShow == true) {
USER_LOG_INFO("gps position: x %d y %d z %d.", gpsPosition.x, gpsPosition.y, gpsPosition.z);
}
djiStat = DjiFcSubscription_GetLatestValueOfTopic(DJI_FC_SUBSCRIPTION_TOPIC_GPS_DETAILS,
(uint8_t *) &gpsDetails,
sizeof(T_DjiFcSubscriptionGpsDetails),
&timestamp);
if (djiStat != DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS) {
USER_LOG_ERROR("get value of topic gps details error.");
}
if (s_userFcSubscriptionDataShow == true) {
USER_LOG_INFO("gps total satellite number used: %d %d %d.",
gpsDetails.gpsSatelliteNumberUsed,
gpsDetails.glonassSatelliteNumberUsed,
gpsDetails.totalSatelliteNumberUsed);
s_totalSatelliteNumberUsed = gpsDetails.totalSatelliteNumberUsed;
}
}
}
#ifndef __CC_ARM
#pragma GCC diagnostic pop
#endif
static T_DjiReturnCode DjiTest_FcSubscriptionReceiveQuaternionCallback(const uint8_t *data, uint16_t dataSize,
const T_DjiDataTimestamp *timestamp)
{
T_DjiFcSubscriptionQuaternion *quaternion = (T_DjiFcSubscriptionQuaternion *) data;
dji_f64_t pitch, yaw, roll;
USER_UTIL_UNUSED(dataSize);
pitch = (dji_f64_t) asinf(-2 * quaternion->q1 * quaternion->q3 + 2 * quaternion->q0 * quaternion->q2) * 57.3;
roll = (dji_f64_t) atan2f(2 * quaternion->q2 * quaternion->q3 + 2 * quaternion->q0 * quaternion->q1,
-2 * quaternion->q1 * quaternion->q1 - 2 * quaternion->q2 * quaternion->q2 + 1) * 57.3;
yaw = (dji_f64_t) atan2f(2 * quaternion->q1 * quaternion->q2 + 2 * quaternion->q0 * quaternion->q3,
-2 * quaternion->q2 * quaternion->q2 - 2 * quaternion->q3 * quaternion->q3 + 1) *
57.3;
if (s_userFcSubscriptionDataShow == true) {
if (s_userFcSubscriptionDataCnt++ % DJI_DATA_SUBSCRIPTION_TOPIC_50_HZ == 0) {
USER_LOG_INFO("receive quaternion data.");
USER_LOG_INFO("timestamp: millisecond %u microsecond %u.", timestamp->millisecond,
timestamp->microsecond);
USER_LOG_INFO("quaternion: %f %f %f %f.", quaternion->q0, quaternion->q1, quaternion->q2,
quaternion->q3);
USER_LOG_INFO("euler angles: pitch = %.2f roll = %.2f yaw = %.2f.\r\n", pitch, roll, yaw);
DjiTest_WidgetLogAppend("pitch = %.2f roll = %.2f yaw = %.2f.", pitch, roll, yaw);
}
}
return DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS;
}
/****************** (C) COPYRIGHT DJI Innovations *****END OF FILE****/

View File

@ -0,0 +1,55 @@
/**
********************************************************************
* @file test_fc_subscription.h
* @brief This is the header file for "test_fc_subscription.c", defining the structure and
* (exported) function prototypes.
*
* @copyright (c) 2021 DJI. All rights reserved.
*
* All information contained herein is, and remains, the property of DJI.
* The intellectual and technical concepts contained herein are proprietary
* to DJI and may be covered by U.S. and foreign patents, patents in process,
* and protected by trade secret or copyright law. Dissemination of this
* information, including but not limited to data and other proprietary
* material(s) incorporated within the information, in any form, is strictly
* prohibited without the express written consent of DJI.
*
* If you receive this source code without DJIs authorization, you may not
* further disseminate the information, and you must immediately remove the
* source code and notify DJI of its removal. DJI reserves the right to pursue
* legal actions against you for any loss(es) or damage(s) caused by your
* failure to do so.
*
*********************************************************************
*/
/* Define to prevent recursive inclusion -------------------------------------*/
#ifndef TEST_FC_SUBSCRIPTION_H
#define TEST_FC_SUBSCRIPTION_H
/* Includes ------------------------------------------------------------------*/
#include "dji_typedef.h"
#include "dji_fc_subscription.h"
#ifdef __cplusplus
extern "C" {
#endif
/* Exported constants --------------------------------------------------------*/
/* Exported types ------------------------------------------------------------*/
/* Exported functions --------------------------------------------------------*/
T_DjiReturnCode DjiTest_FcSubscriptionStartService(void);
T_DjiReturnCode DjiTest_FcSubscriptionRunSample(void);
T_DjiReturnCode DjiTest_FcSubscriptionDataShowTrigger(void);
T_DjiReturnCode DjiTest_FcSubscriptionGetTotalSatelliteNumber(uint8_t *number);
#ifdef __cplusplus
}
#endif
#endif // TEST_FC_SUBSCRIPTION_H
/************************ (C) COPYRIGHT DJI Innovations *******END OF FILE******/

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,68 @@
/**
********************************************************************
* @file test_flight_control.h
* @brief This is the header file for "test_flight_control.c", defining the structure and
* (exported) function prototypes.
*
* @copyright (c) 2021 DJI. All rights reserved.
*
* All information contained herein is, and remains, the property of DJI.
* The intellectual and technical concepts contained herein are proprietary
* to DJI and may be covered by U.S. and foreign patents, patents in process,
* and protected by trade secret or copyright law. Dissemination of this
* information, including but not limited to data and other proprietary
* material(s) incorporated within the information, in any form, is strictly
* prohibited without the express written consent of DJI.
*
* If you receive this source code without DJIs authorization, you may not
* further disseminate the information, and you must immediately remove the
* source code and notify DJI of its removal. DJI reserves the right to pursue
* legal actions against you for any loss(es) or damage(s) caused by your
* failure to do so.
*
*********************************************************************
*/
/* Define to prevent recursive inclusion -------------------------------------*/
#ifndef TEST_FLIGHT_CONTROL_H
#define TEST_FLIGHT_CONTROL_H
/* Includes ------------------------------------------------------------------*/
#include "dji_typedef.h"
#ifdef __cplusplus
extern "C" {
#endif
/* Exported constants --------------------------------------------------------*/
typedef enum {
E_DJI_TEST_FLIGHT_CTRL_SAMPLE_SELECT_TAKE_OFF_LANDING,
E_DJI_TEST_FLIGHT_CTRL_SAMPLE_SELECT_TAKE_OFF_POSITION_CTRL_LANDING,
E_DJI_TEST_FLIGHT_CTRL_SAMPLE_SELECT_TAKE_OFF_GO_HOME_FORCE_LANDING,
E_DJI_TEST_FLIGHT_CTRL_SAMPLE_SELECT_TAKE_OFF_VELOCITY_CTRL_LANDING,
E_DJI_TEST_FLIGHT_CTRL_SAMPLE_SELECT_ARREST_FLYING,
E_DJI_TEST_FLIGHT_CTRL_SAMPLE_SELECT_SET_GET_PARAM,
E_DJI_TEST_FLIGHT_CTRL_SAMPLE_SELECT_FTS_TRIGGER,
} E_DjiTestFlightCtrlSampleSelect;
#pragma pack(1)
typedef struct {
dji_f32_t x;
dji_f32_t y;
dji_f32_t z;
} T_DjiTestFlightControlVector3f; // pack(1)
#pragma pack()
/* Exported types ------------------------------------------------------------*/
/* Exported functions --------------------------------------------------------*/
T_DjiReturnCode DjiTest_FlightControlRunSample(E_DjiTestFlightCtrlSampleSelect flightCtrlSampleSelect);
void DjiTest_FlightControlVelocityAndYawRateCtrl(const T_DjiTestFlightControlVector3f offsetDesired, float yawRate,
uint32_t timeMs);
#ifdef __cplusplus
}
#endif
#endif // TEST_FLIGHT_CONTROL_H
/************************ (C) COPYRIGHT DJI Innovations *******END OF FILE******/

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,58 @@
/**
********************************************************************
* @file test_payload_gimbal_emu.h
* @brief This is the header file for "test_payload_gimbal_emu.c", defining the structure and
* (exported) function prototypes.
*
* @copyright (c) 2021 DJI. All rights reserved.
*
* All information contained herein is, and remains, the property of DJI.
* The intellectual and technical concepts contained herein are proprietary
* to DJI and may be covered by U.S. and foreign patents, patents in process,
* and protected by trade secret or copyright law. Dissemination of this
* information, including but not limited to data and other proprietary
* material(s) incorporated within the information, in any form, is strictly
* prohibited without the express written consent of DJI.
*
* If you receive this source code without DJIs authorization, you may not
* further disseminate the information, and you must immediately remove the
* source code and notify DJI of its removal. DJI reserves the right to pursue
* legal actions against you for any loss(es) or damage(s) caused by your
* failure to do so.
*
*********************************************************************
*/
/* Define to prevent recursive inclusion -------------------------------------*/
#ifndef TEST_PAYLOAD_GIMBAL_EMU_H
#define TEST_PAYLOAD_GIMBAL_EMU_H
/* Includes ------------------------------------------------------------------*/
#include "dji_typedef.h"
#include "dji_gimbal.h"
#ifdef __cplusplus
extern "C" {
#endif
/* Exported constants --------------------------------------------------------*/
/* Exported types ------------------------------------------------------------*/
/* Exported functions --------------------------------------------------------*/
T_DjiReturnCode DjiTest_GimbalStartService(void);
T_DjiReturnCode DjiTest_GimbalDeInit(void);
T_DjiReturnCode DjiTest_GimbalRotate(E_DjiGimbalRotationMode rotationMode,
T_DjiGimbalRotationProperty rotationProperty,
T_DjiAttitude3d rotationValue); // unit if angle control: 0.1 degree, unit if speed control: 0.1 degree/s
#ifdef __cplusplus
}
#endif
#endif // TEST_PAYLOAD_GIMBAL_EMU_H
/************************ (C) COPYRIGHT DJI Innovations *******END OF FILE******/

View File

@ -0,0 +1,189 @@
/**
********************************************************************
* @file test_gimbal_manager.c
* @brief
*
* @copyright (c) 2021 DJI. All rights reserved.
*
* All information contained herein is, and remains, the property of DJI.
* The intellectual and technical concepts contained herein are proprietary
* to DJI and may be covered by U.S. and foreign patents, patents in process,
* and protected by trade secret or copyright law. Dissemination of this
* information, including but not limited to data and other proprietary
* material(s) incorporated within the information, in any form, is strictly
* prohibited without the express written consent of DJI.
*
* If you receive this source code without DJIs authorization, you may not
* further disseminate the information, and you must immediately remove the
* source code and notify DJI of its removal. DJI reserves the right to pursue
* legal actions against you for any loss(es) or damage(s) caused by your
* failure to do so.
*
*********************************************************************
*/
/* Includes ------------------------------------------------------------------*/
#include <utils/util_misc.h>
#include <widget_interaction_test/test_widget_interaction.h>
#include "test_gimbal_manager.h"
#include "dji_platform.h"
#include "dji_logger.h"
#include "dji_gimbal_manager.h"
#include "dji_fc_subscription.h"
#include "dji_aircraft_info.h"
/* Private constants ---------------------------------------------------------*/
/* Private types -------------------------------------------------------------*/
typedef enum {
DJI_TEST_GIMBAL_ROTATION,
DJI_TEST_GIMBAL_RESET,
} E_DjiTestGimbalAction;
typedef struct {
E_DjiTestGimbalAction action;
T_DjiGimbalManagerRotation rotation;
} T_DjiTestGimbalActionList;
/* Private values -------------------------------------------------------------*/
static const T_DjiTestGimbalActionList s_rotationActionList[] =
{
{.action = DJI_TEST_GIMBAL_RESET},
{.action = DJI_TEST_GIMBAL_ROTATION, .rotation.rotationMode = DJI_GIMBAL_ROTATION_MODE_RELATIVE_ANGLE, 30, 0, 0, 0.2},
{.action = DJI_TEST_GIMBAL_ROTATION, .rotation.rotationMode = DJI_GIMBAL_ROTATION_MODE_RELATIVE_ANGLE, -30, 0, 0, 0.2},
{.action = DJI_TEST_GIMBAL_ROTATION, .rotation.rotationMode = DJI_GIMBAL_ROTATION_MODE_RELATIVE_ANGLE, -30, 0, 0, 0.2},
{.action = DJI_TEST_GIMBAL_ROTATION, .rotation.rotationMode = DJI_GIMBAL_ROTATION_MODE_RELATIVE_ANGLE, 30, 0, 0, 0.2},
{.action = DJI_TEST_GIMBAL_ROTATION, .rotation.rotationMode = DJI_GIMBAL_ROTATION_MODE_RELATIVE_ANGLE, 0, 30, 0, 0.2},
{.action = DJI_TEST_GIMBAL_ROTATION, .rotation.rotationMode = DJI_GIMBAL_ROTATION_MODE_RELATIVE_ANGLE, 0, -30, 0, 0.2},
{.action = DJI_TEST_GIMBAL_ROTATION, .rotation.rotationMode = DJI_GIMBAL_ROTATION_MODE_RELATIVE_ANGLE, 0, -30, 0, 0.2},
{.action = DJI_TEST_GIMBAL_ROTATION, .rotation.rotationMode = DJI_GIMBAL_ROTATION_MODE_RELATIVE_ANGLE, 0, 30, 0, 0.2},
{.action = DJI_TEST_GIMBAL_ROTATION, .rotation.rotationMode = DJI_GIMBAL_ROTATION_MODE_RELATIVE_ANGLE, 0, 0, 4, 0.2},
{.action = DJI_TEST_GIMBAL_ROTATION, .rotation.rotationMode = DJI_GIMBAL_ROTATION_MODE_RELATIVE_ANGLE, 0, 0, -4, 0.2},
{.action = DJI_TEST_GIMBAL_RESET},
{.action = DJI_TEST_GIMBAL_ROTATION, .rotation.rotationMode = DJI_GIMBAL_ROTATION_MODE_ABSOLUTE_ANGLE, 30, 0, 0, 0.2},
{.action = DJI_TEST_GIMBAL_ROTATION, .rotation.rotationMode = DJI_GIMBAL_ROTATION_MODE_ABSOLUTE_ANGLE, -90, 0, 0, 0.5},
{.action = DJI_TEST_GIMBAL_ROTATION, .rotation.rotationMode = DJI_GIMBAL_ROTATION_MODE_ABSOLUTE_ANGLE, -60, 0, 0, 0.5},
{.action = DJI_TEST_GIMBAL_ROTATION, .rotation.rotationMode = DJI_GIMBAL_ROTATION_MODE_ABSOLUTE_ANGLE, -30, 0, 0, 0.5},
{.action = DJI_TEST_GIMBAL_RESET},
};
/* Private functions declaration ---------------------------------------------*/
/* Exported functions definition ---------------------------------------------*/
T_DjiReturnCode DjiTest_GimbalManagerRunSample(E_DjiMountPosition mountPosition, E_DjiGimbalMode gimbalMode)
{
T_DjiOsalHandler *osalHandler = DjiPlatform_GetOsalHandler();
T_DjiReturnCode returnCode;
T_DjiGimbalManagerRotation rotation;
T_DjiAircraftInfoBaseInfo baseInfo;
E_DjiAircraftSeries aircraftSeries;
returnCode = DjiAircraftInfo_GetBaseInfo(&baseInfo);
if (returnCode != DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS) {
USER_LOG_ERROR("Failed to get aircraft base info, return code 0x%08X", returnCode);
goto out;
}
aircraftSeries = baseInfo.aircraftSeries;
USER_LOG_INFO("Gimbal manager sample start");
DjiTest_WidgetLogAppend("Gimbal manager sample start");
returnCode = DjiFcSubscription_SubscribeTopic(DJI_FC_SUBSCRIPTION_TOPIC_GIMBAL_ANGLES, DJI_DATA_SUBSCRIPTION_TOPIC_50_HZ, NULL);
if (returnCode != DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS) {
USER_LOG_ERROR("Failed to subscribe topic %d, 0x%08X", DJI_FC_SUBSCRIPTION_TOPIC_GIMBAL_ANGLES, returnCode);
goto out;
}
USER_LOG_INFO("--> Step 1: Init gimbal manager module");
DjiTest_WidgetLogAppend("--> Step 1: Init gimbal manager module");
returnCode = DjiGimbalManager_Init();
if (returnCode != DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS) {
USER_LOG_ERROR("Init gimbal manager failed, error code: 0x%08X", returnCode);
goto out;
}
if (gimbalMode == DJI_GIMBAL_MODE_FREE) {
USER_LOG_INFO("--> Step 2: Set gimbal to free mode");
DjiTest_WidgetLogAppend("--> Step 2: Set gimbal to free mode");
} else if (gimbalMode == DJI_GIMBAL_MODE_YAW_FOLLOW) {
USER_LOG_INFO("--> Step 2: Set gimbal to yaw follow mode");
DjiTest_WidgetLogAppend("--> Step 2: Set gimbal to yaw follow mode");
}
returnCode = DjiGimbalManager_SetMode(mountPosition, gimbalMode);
if (returnCode != DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS) {
USER_LOG_ERROR("Set gimbal mode failed, error code: 0x%08X", returnCode);
goto out;
}
USER_LOG_INFO("--> Step 3: Reset gimbal angles.\r\n");
returnCode = DjiGimbalManager_Reset(mountPosition, DJI_GIMBAL_RESET_MODE_PITCH_AND_YAW);
if (returnCode != DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS) {
USER_LOG_ERROR("Reset gimbal failed, error code: 0x%08X", returnCode);
}
USER_LOG_INFO("--> Step 4: Rotate gimbal to target angle by action list\r\n");
for (int i = 0; i < sizeof(s_rotationActionList) / sizeof(T_DjiTestGimbalActionList); ++i) {
if (s_rotationActionList[i].action == DJI_TEST_GIMBAL_RESET) {
USER_LOG_INFO("Target gimbal reset.\r\n");
returnCode = DjiGimbalManager_Reset(mountPosition, DJI_GIMBAL_RESET_MODE_PITCH_AND_YAW);
if (returnCode != DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS) {
USER_LOG_ERROR("Reset gimbal failed, error code: 0x%08X", returnCode);
}
osalHandler->TaskSleepMs(2000);
} else if (s_rotationActionList[i].action == DJI_TEST_GIMBAL_ROTATION) {
if (gimbalMode == DJI_GIMBAL_MODE_FREE &&
s_rotationActionList[i].rotation.rotationMode == DJI_GIMBAL_ROTATION_MODE_ABSOLUTE_ANGLE) {
continue;
}
rotation = s_rotationActionList[i].rotation;
if (aircraftSeries == DJI_AIRCRAFT_SERIES_M3 || aircraftSeries == DJI_AIRCRAFT_SERIES_M30
|| aircraftSeries == DJI_AIRCRAFT_SERIES_M3D) {
if (s_rotationActionList[i].rotation.rotationMode == DJI_GIMBAL_ROTATION_MODE_ABSOLUTE_ANGLE) {
T_DjiFcSubscriptionGimbalAngles gimbalAngles = {0};
T_DjiDataTimestamp timestamp = {0};
returnCode = DjiFcSubscription_GetLatestValueOfTopic(DJI_FC_SUBSCRIPTION_TOPIC_GIMBAL_ANGLES,
(uint8_t *) &gimbalAngles,
sizeof(T_DjiFcSubscriptionGimbalAngles),
&timestamp);
rotation.yaw = gimbalAngles.z;
}
}
USER_LOG_INFO("Target gimbal pry = (%.1f, %.1f, %.1f)", rotation.pitch, rotation.roll, rotation.yaw);
returnCode = DjiGimbalManager_Rotate(mountPosition, rotation);
if (returnCode != DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS) {
USER_LOG_ERROR("Target gimbal pry = (%.1f, %.1f, %.1f) failed, error code: 0x%08X",
s_rotationActionList[i].rotation.pitch, s_rotationActionList[i].rotation.roll,
s_rotationActionList[i].rotation.yaw,
returnCode);
}
osalHandler->TaskSleepMs(1000);
}
}
returnCode = DjiFcSubscription_UnSubscribeTopic(DJI_FC_SUBSCRIPTION_TOPIC_GIMBAL_ANGLES);
if (returnCode != DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS) {
USER_LOG_ERROR("Failed to unsubscribe topic %d, 0x%08X", DJI_FC_SUBSCRIPTION_TOPIC_GIMBAL_ANGLES, returnCode);
}
USER_LOG_INFO("--> Step 5: Deinit gimbal manager module");
DjiTest_WidgetLogAppend("--> Step 5: Deinit gimbal manager module");
returnCode = DjiGimbalManager_Deinit();
if (returnCode != DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS) {
USER_LOG_ERROR("Deinit gimbal manager failed, error code: 0x%08X", returnCode);
goto out;
}
out:
USER_LOG_INFO("Gimbal manager sample end");
return returnCode;
}
/* Private functions definition-----------------------------------------------*/
/****************** (C) COPYRIGHT DJI Innovations *****END OF FILE****/

View File

@ -0,0 +1,49 @@
/**
********************************************************************
* @file test_gimbal_manager.h
* @brief This is the header file for "test_gimbal_manager.c", defining the structure and
* (exported) function prototypes.
*
* @copyright (c) 2021 DJI. All rights reserved.
*
* All information contained herein is, and remains, the property of DJI.
* The intellectual and technical concepts contained herein are proprietary
* to DJI and may be covered by U.S. and foreign patents, patents in process,
* and protected by trade secret or copyright law. Dissemination of this
* information, including but not limited to data and other proprietary
* material(s) incorporated within the information, in any form, is strictly
* prohibited without the express written consent of DJI.
*
* If you receive this source code without DJIs authorization, you may not
* further disseminate the information, and you must immediately remove the
* source code and notify DJI of its removal. DJI reserves the right to pursue
* legal actions against you for any loss(es) or damage(s) caused by your
* failure to do so.
*
*********************************************************************
*/
/* Define to prevent recursive inclusion -------------------------------------*/
#ifndef TEST_GIMBAL_MANAGER_H
#define TEST_GIMBAL_MANAGER_H
/* Includes ------------------------------------------------------------------*/
#include "dji_typedef.h"
#ifdef __cplusplus
extern "C" {
#endif
/* Exported constants --------------------------------------------------------*/
/* Exported types ------------------------------------------------------------*/
/* Exported functions --------------------------------------------------------*/
T_DjiReturnCode DjiTest_GimbalManagerRunSample(E_DjiMountPosition mountPosition, E_DjiGimbalMode gimbalMode);
#ifdef __cplusplus
}
#endif
#endif // TEST_GIMBAL_MANAGER_H
/************************ (C) COPYRIGHT DJI Innovations *******END OF FILE******/

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,76 @@
{
"version": {
"major": 1,
"minor": 0
},
"hms_database": {
"hms_position_desc": "负载%position_index",
"hms_error_code_list": [
{
"hms_error_code": "0x1E020000",
"hms_interface": {
"message_title": "HMS测试文案: 我是错误码标题0",
"message_content": "HMS测试文案: 我是错误码内容0"
},
"fpv_interface": {
"message_on_the_ground": "HMS测试文案: 我在地面发生了错误0",
"is_keep_history_on_the_ground": false,
"message_in_the_sky": "HMS测试文案: 我在空中发生了错误0",
"is_keep_history_in_the_sky": false
}
},
{
"hms_error_code": "0x1E020001",
"hms_interface": {
"message_title": "HMS测试文案: 我是错误码标题1",
"message_content": "HMS测试文案: 我是错误码内容1"
},
"fpv_interface": {
"message_on_the_ground": "HMS测试文案: 我在地面发生了错误1",
"is_keep_history_on_the_ground": false,
"message_in_the_sky": "HMS测试文案: 我在空中发生了错误1",
"is_keep_history_in_the_sky": false
}
},
{
"hms_error_code": "0x1E020002",
"hms_interface": {
"message_title": "HMS测试文案: 我是错误码标题2",
"message_content": "HMS测试文案: 我是错误码内容2"
},
"fpv_interface": {
"message_on_the_ground": "HMS测试文案: 我在地面发生了错误2",
"is_keep_history_on_the_ground": true,
"message_in_the_sky": "HMS测试文案: 我在空中发生了错误2",
"is_keep_history_in_the_sky": true
}
},
{
"hms_error_code": "0x1E020003",
"hms_interface": {
"message_title": "HMS测试文案: 我是错误码标题3",
"message_content": "HMS测试文案: 我是错误码内容3"
},
"fpv_interface": {
"message_on_the_ground": "HMS测试文案: 我在地面发生了错误3",
"is_keep_history_on_the_ground": true,
"message_in_the_sky": "HMS测试文案: 我在空中发生了错误3",
"is_keep_history_in_the_sky": true
}
},
{
"hms_error_code": "0x1E020004",
"hms_interface": {
"message_title": "HMS测试文案: 我是错误码标题4",
"message_content": "HMS测试文案: 我是错误码内容4"
},
"fpv_interface": {
"message_on_the_ground": "HMS测试文案: 我在地面发生了错误4",
"is_keep_history_on_the_ground": true,
"message_in_the_sky": "HMS测试文案: 我在空中发生了错误4",
"is_keep_history_in_the_sky": true
}
}
]
}
}

View File

@ -0,0 +1,76 @@
{
"version": {
"major": 1,
"minor": 0
},
"hms_database": {
"hms_position_desc": "Payload %position_index",
"hms_error_code_list": [
{
"hms_error_code": "0x1E020000",
"hms_interface": {
"message_title": "HMS test text: I am error code Title 0",
"message_content": "HMS test text: I am error code Content 0"
},
"fpv_interface": {
"message_on_the_ground": "HMS test text: I got error on the ground 0",
"is_keep_history_on_the_ground": false,
"message_in_the_sky": "HMS test text: I got error in the sky 0",
"is_keep_history_in_the_sky": false
}
},
{
"hms_error_code": "0x1E020001",
"hms_interface": {
"message_title": "HMS test text: I am error code Title 1",
"message_content": "HMS test text: I am error code Content 1"
},
"fpv_interface": {
"message_on_the_ground": "HMS test text: I got error on the ground 1",
"is_keep_history_on_the_ground": false,
"message_in_the_sky": "HMS test text: I got error in the sky 1",
"is_keep_history_in_the_sky": false
}
},
{
"hms_error_code": "0x1E020002",
"hms_interface": {
"message_title": "HMS test text: I am error code Title 2",
"message_content": "HMS test text: I am error code Content 2"
},
"fpv_interface": {
"message_on_the_ground": "HMS test text: I got error on the ground 2",
"is_keep_history_on_the_ground": true,
"message_in_the_sky": "HMS test text: I got error in the sky 2",
"is_keep_history_in_the_sky": true
}
},
{
"hms_error_code": "0x1E020003",
"hms_interface": {
"message_title": "HMS test text: I am error code Title 3",
"message_content": "HMS test text: I am error code Content 3"
},
"fpv_interface": {
"message_on_the_ground": "HMS test text: I got error on the ground 3",
"is_keep_history_on_the_ground": true,
"message_in_the_sky": "HMS test text: I got error in the sky 3",
"is_keep_history_in_the_sky": true
}
},
{
"hms_error_code": "0x1E020004",
"hms_interface": {
"message_title": "HMS test text: I am error code Title 4",
"message_content": "HMS test text: I am error code Content 4"
},
"fpv_interface": {
"message_on_the_ground": "HMS test text: I got error on the ground 4",
"is_keep_history_on_the_ground": true,
"message_in_the_sky": "HMS test text: I got error in the sky 4",
"is_keep_history_in_the_sky": true
}
}
]
}
}

View File

@ -0,0 +1,188 @@
/* Generated by file2c, do not edit manually */
#ifndef __hms_text_config_json_h_included
#define __hms_text_config_json_h_included
#include <stdint.h>
/* Contents of file hms_text_config.json */
#define hms_text_config_json_fileName "hms_text_config.json"
#define hms_text_config_json_fileSize 2783
static const uint8_t hms_text_config_json_fileBinaryArray[2783] = {
0x7B, 0x0A, 0x20, 0x20, 0x22, 0x76, 0x65, 0x72, 0x73, 0x69, 0x6F, 0x6E, 0x22, 0x3A, 0x20, 0x7B,
0x0A, 0x20, 0x20, 0x20, 0x20, 0x22, 0x6D, 0x61, 0x6A, 0x6F, 0x72, 0x22, 0x3A, 0x20, 0x31, 0x2C,
0x0A, 0x20, 0x20, 0x20, 0x20, 0x22, 0x6D, 0x69, 0x6E, 0x6F, 0x72, 0x22, 0x3A, 0x20, 0x30, 0x0A,
0x20, 0x20, 0x7D, 0x2C, 0x0A, 0x20, 0x20, 0x22, 0x68, 0x6D, 0x73, 0x5F, 0x64, 0x61, 0x74, 0x61,
0x62, 0x61, 0x73, 0x65, 0x22, 0x3A, 0x20, 0x7B, 0x0A, 0x20, 0x20, 0x20, 0x20, 0x22, 0x68, 0x6D,
0x73, 0x5F, 0x70, 0x6F, 0x73, 0x69, 0x74, 0x69, 0x6F, 0x6E, 0x5F, 0x64, 0x65, 0x73, 0x63, 0x22,
0x3A, 0x20, 0x22, 0x50, 0x61, 0x79, 0x6C, 0x6F, 0x61, 0x64, 0x20, 0x25, 0x70, 0x6F, 0x73, 0x69,
0x74, 0x69, 0x6F, 0x6E, 0x5F, 0x69, 0x6E, 0x64, 0x65, 0x78, 0x22, 0x2C, 0x0A, 0x20, 0x20, 0x20,
0x20, 0x22, 0x68, 0x6D, 0x73, 0x5F, 0x65, 0x72, 0x72, 0x6F, 0x72, 0x5F, 0x63, 0x6F, 0x64, 0x65,
0x5F, 0x6C, 0x69, 0x73, 0x74, 0x22, 0x3A, 0x20, 0x5B, 0x0A, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x7B, 0x0A, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x22, 0x68, 0x6D, 0x73, 0x5F, 0x65,
0x72, 0x72, 0x6F, 0x72, 0x5F, 0x63, 0x6F, 0x64, 0x65, 0x22, 0x3A, 0x20, 0x22, 0x30, 0x78, 0x31,
0x45, 0x30, 0x32, 0x30, 0x30, 0x30, 0x30, 0x22, 0x2C, 0x0A, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x22, 0x68, 0x6D, 0x73, 0x5F, 0x69, 0x6E, 0x74, 0x65, 0x72, 0x66, 0x61, 0x63, 0x65,
0x22, 0x3A, 0x20, 0x7B, 0x0A, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x22,
0x6D, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x5F, 0x74, 0x69, 0x74, 0x6C, 0x65, 0x22, 0x3A, 0x20,
0x22, 0x48, 0x4D, 0x53, 0x20, 0x74, 0x65, 0x73, 0x74, 0x20, 0x74, 0x65, 0x78, 0x74, 0x3A, 0x20,
0x49, 0x20, 0x61, 0x6D, 0x20, 0x65, 0x72, 0x72, 0x6F, 0x72, 0x20, 0x63, 0x6F, 0x64, 0x65, 0x20,
0x54, 0x69, 0x74, 0x6C, 0x65, 0x20, 0x30, 0x22, 0x2C, 0x0A, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x22, 0x6D, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x5F, 0x63, 0x6F, 0x6E,
0x74, 0x65, 0x6E, 0x74, 0x22, 0x3A, 0x20, 0x22, 0x48, 0x4D, 0x53, 0x20, 0x74, 0x65, 0x73, 0x74,
0x20, 0x74, 0x65, 0x78, 0x74, 0x3A, 0x20, 0x49, 0x20, 0x61, 0x6D, 0x20, 0x65, 0x72, 0x72, 0x6F,
0x72, 0x20, 0x63, 0x6F, 0x64, 0x65, 0x20, 0x43, 0x6F, 0x6E, 0x74, 0x65, 0x6E, 0x74, 0x20, 0x30,
0x22, 0x0A, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x7D, 0x2C, 0x0A, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x22, 0x66, 0x70, 0x76, 0x5F, 0x69, 0x6E, 0x74, 0x65, 0x72, 0x66,
0x61, 0x63, 0x65, 0x22, 0x3A, 0x20, 0x7B, 0x0A, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x22, 0x6D, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x5F, 0x6F, 0x6E, 0x5F, 0x74, 0x68,
0x65, 0x5F, 0x67, 0x72, 0x6F, 0x75, 0x6E, 0x64, 0x22, 0x3A, 0x20, 0x22, 0x48, 0x4D, 0x53, 0x20,
0x74, 0x65, 0x73, 0x74, 0x20, 0x74, 0x65, 0x78, 0x74, 0x3A, 0x20, 0x49, 0x20, 0x67, 0x6F, 0x74,
0x20, 0x65, 0x72, 0x72, 0x6F, 0x72, 0x20, 0x6F, 0x6E, 0x20, 0x74, 0x68, 0x65, 0x20, 0x67, 0x72,
0x6F, 0x75, 0x6E, 0x64, 0x20, 0x30, 0x22, 0x2C, 0x0A, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x22, 0x69, 0x73, 0x5F, 0x6B, 0x65, 0x65, 0x70, 0x5F, 0x68, 0x69, 0x73, 0x74,
0x6F, 0x72, 0x79, 0x5F, 0x6F, 0x6E, 0x5F, 0x74, 0x68, 0x65, 0x5F, 0x67, 0x72, 0x6F, 0x75, 0x6E,
0x64, 0x22, 0x3A, 0x20, 0x66, 0x61, 0x6C, 0x73, 0x65, 0x2C, 0x0A, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x22, 0x6D, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x5F, 0x69, 0x6E,
0x5F, 0x74, 0x68, 0x65, 0x5F, 0x73, 0x6B, 0x79, 0x22, 0x3A, 0x20, 0x22, 0x48, 0x4D, 0x53, 0x20,
0x74, 0x65, 0x73, 0x74, 0x20, 0x74, 0x65, 0x78, 0x74, 0x3A, 0x20, 0x49, 0x20, 0x67, 0x6F, 0x74,
0x20, 0x65, 0x72, 0x72, 0x6F, 0x72, 0x20, 0x69, 0x6E, 0x20, 0x74, 0x68, 0x65, 0x20, 0x73, 0x6B,
0x79, 0x20, 0x30, 0x22, 0x2C, 0x0A, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x22, 0x69, 0x73, 0x5F, 0x6B, 0x65, 0x65, 0x70, 0x5F, 0x68, 0x69, 0x73, 0x74, 0x6F, 0x72, 0x79,
0x5F, 0x69, 0x6E, 0x5F, 0x74, 0x68, 0x65, 0x5F, 0x73, 0x6B, 0x79, 0x22, 0x3A, 0x20, 0x66, 0x61,
0x6C, 0x73, 0x65, 0x0A, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x7D, 0x0A, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x7D, 0x2C, 0x0A, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x7B, 0x0A, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x22, 0x68, 0x6D, 0x73, 0x5F, 0x65, 0x72, 0x72, 0x6F,
0x72, 0x5F, 0x63, 0x6F, 0x64, 0x65, 0x22, 0x3A, 0x20, 0x22, 0x30, 0x78, 0x31, 0x45, 0x30, 0x32,
0x30, 0x30, 0x30, 0x31, 0x22, 0x2C, 0x0A, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x22,
0x68, 0x6D, 0x73, 0x5F, 0x69, 0x6E, 0x74, 0x65, 0x72, 0x66, 0x61, 0x63, 0x65, 0x22, 0x3A, 0x20,
0x7B, 0x0A, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x22, 0x6D, 0x65, 0x73,
0x73, 0x61, 0x67, 0x65, 0x5F, 0x74, 0x69, 0x74, 0x6C, 0x65, 0x22, 0x3A, 0x20, 0x22, 0x48, 0x4D,
0x53, 0x20, 0x74, 0x65, 0x73, 0x74, 0x20, 0x74, 0x65, 0x78, 0x74, 0x3A, 0x20, 0x49, 0x20, 0x61,
0x6D, 0x20, 0x65, 0x72, 0x72, 0x6F, 0x72, 0x20, 0x63, 0x6F, 0x64, 0x65, 0x20, 0x54, 0x69, 0x74,
0x6C, 0x65, 0x20, 0x31, 0x22, 0x2C, 0x0A, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x22, 0x6D, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x5F, 0x63, 0x6F, 0x6E, 0x74, 0x65, 0x6E,
0x74, 0x22, 0x3A, 0x20, 0x22, 0x48, 0x4D, 0x53, 0x20, 0x74, 0x65, 0x73, 0x74, 0x20, 0x74, 0x65,
0x78, 0x74, 0x3A, 0x20, 0x49, 0x20, 0x61, 0x6D, 0x20, 0x65, 0x72, 0x72, 0x6F, 0x72, 0x20, 0x63,
0x6F, 0x64, 0x65, 0x20, 0x43, 0x6F, 0x6E, 0x74, 0x65, 0x6E, 0x74, 0x20, 0x31, 0x22, 0x0A, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x7D, 0x2C, 0x0A, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x22, 0x66, 0x70, 0x76, 0x5F, 0x69, 0x6E, 0x74, 0x65, 0x72, 0x66, 0x61, 0x63, 0x65,
0x22, 0x3A, 0x20, 0x7B, 0x0A, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x22,
0x6D, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x5F, 0x6F, 0x6E, 0x5F, 0x74, 0x68, 0x65, 0x5F, 0x67,
0x72, 0x6F, 0x75, 0x6E, 0x64, 0x22, 0x3A, 0x20, 0x22, 0x48, 0x4D, 0x53, 0x20, 0x74, 0x65, 0x73,
0x74, 0x20, 0x74, 0x65, 0x78, 0x74, 0x3A, 0x20, 0x49, 0x20, 0x67, 0x6F, 0x74, 0x20, 0x65, 0x72,
0x72, 0x6F, 0x72, 0x20, 0x6F, 0x6E, 0x20, 0x74, 0x68, 0x65, 0x20, 0x67, 0x72, 0x6F, 0x75, 0x6E,
0x64, 0x20, 0x31, 0x22, 0x2C, 0x0A, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x22, 0x69, 0x73, 0x5F, 0x6B, 0x65, 0x65, 0x70, 0x5F, 0x68, 0x69, 0x73, 0x74, 0x6F, 0x72, 0x79,
0x5F, 0x6F, 0x6E, 0x5F, 0x74, 0x68, 0x65, 0x5F, 0x67, 0x72, 0x6F, 0x75, 0x6E, 0x64, 0x22, 0x3A,
0x20, 0x66, 0x61, 0x6C, 0x73, 0x65, 0x2C, 0x0A, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x22, 0x6D, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x5F, 0x69, 0x6E, 0x5F, 0x74, 0x68,
0x65, 0x5F, 0x73, 0x6B, 0x79, 0x22, 0x3A, 0x20, 0x22, 0x48, 0x4D, 0x53, 0x20, 0x74, 0x65, 0x73,
0x74, 0x20, 0x74, 0x65, 0x78, 0x74, 0x3A, 0x20, 0x49, 0x20, 0x67, 0x6F, 0x74, 0x20, 0x65, 0x72,
0x72, 0x6F, 0x72, 0x20, 0x69, 0x6E, 0x20, 0x74, 0x68, 0x65, 0x20, 0x73, 0x6B, 0x79, 0x20, 0x31,
0x22, 0x2C, 0x0A, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x22, 0x69, 0x73,
0x5F, 0x6B, 0x65, 0x65, 0x70, 0x5F, 0x68, 0x69, 0x73, 0x74, 0x6F, 0x72, 0x79, 0x5F, 0x69, 0x6E,
0x5F, 0x74, 0x68, 0x65, 0x5F, 0x73, 0x6B, 0x79, 0x22, 0x3A, 0x20, 0x66, 0x61, 0x6C, 0x73, 0x65,
0x0A, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x7D, 0x0A, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x7D, 0x2C, 0x0A, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x7B, 0x0A, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x22, 0x68, 0x6D, 0x73, 0x5F, 0x65, 0x72, 0x72, 0x6F, 0x72, 0x5F, 0x63,
0x6F, 0x64, 0x65, 0x22, 0x3A, 0x20, 0x22, 0x30, 0x78, 0x31, 0x45, 0x30, 0x32, 0x30, 0x30, 0x30,
0x32, 0x22, 0x2C, 0x0A, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x22, 0x68, 0x6D, 0x73,
0x5F, 0x69, 0x6E, 0x74, 0x65, 0x72, 0x66, 0x61, 0x63, 0x65, 0x22, 0x3A, 0x20, 0x7B, 0x0A, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x22, 0x6D, 0x65, 0x73, 0x73, 0x61, 0x67,
0x65, 0x5F, 0x74, 0x69, 0x74, 0x6C, 0x65, 0x22, 0x3A, 0x20, 0x22, 0x48, 0x4D, 0x53, 0x20, 0x74,
0x65, 0x73, 0x74, 0x20, 0x74, 0x65, 0x78, 0x74, 0x3A, 0x20, 0x49, 0x20, 0x61, 0x6D, 0x20, 0x65,
0x72, 0x72, 0x6F, 0x72, 0x20, 0x63, 0x6F, 0x64, 0x65, 0x20, 0x54, 0x69, 0x74, 0x6C, 0x65, 0x20,
0x32, 0x22, 0x2C, 0x0A, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x22, 0x6D,
0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x5F, 0x63, 0x6F, 0x6E, 0x74, 0x65, 0x6E, 0x74, 0x22, 0x3A,
0x20, 0x22, 0x48, 0x4D, 0x53, 0x20, 0x74, 0x65, 0x73, 0x74, 0x20, 0x74, 0x65, 0x78, 0x74, 0x3A,
0x20, 0x49, 0x20, 0x61, 0x6D, 0x20, 0x65, 0x72, 0x72, 0x6F, 0x72, 0x20, 0x63, 0x6F, 0x64, 0x65,
0x20, 0x43, 0x6F, 0x6E, 0x74, 0x65, 0x6E, 0x74, 0x20, 0x32, 0x22, 0x0A, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x7D, 0x2C, 0x0A, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x22,
0x66, 0x70, 0x76, 0x5F, 0x69, 0x6E, 0x74, 0x65, 0x72, 0x66, 0x61, 0x63, 0x65, 0x22, 0x3A, 0x20,
0x7B, 0x0A, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x22, 0x6D, 0x65, 0x73,
0x73, 0x61, 0x67, 0x65, 0x5F, 0x6F, 0x6E, 0x5F, 0x74, 0x68, 0x65, 0x5F, 0x67, 0x72, 0x6F, 0x75,
0x6E, 0x64, 0x22, 0x3A, 0x20, 0x22, 0x48, 0x4D, 0x53, 0x20, 0x74, 0x65, 0x73, 0x74, 0x20, 0x74,
0x65, 0x78, 0x74, 0x3A, 0x20, 0x49, 0x20, 0x67, 0x6F, 0x74, 0x20, 0x65, 0x72, 0x72, 0x6F, 0x72,
0x20, 0x6F, 0x6E, 0x20, 0x74, 0x68, 0x65, 0x20, 0x67, 0x72, 0x6F, 0x75, 0x6E, 0x64, 0x20, 0x32,
0x22, 0x2C, 0x0A, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x22, 0x69, 0x73,
0x5F, 0x6B, 0x65, 0x65, 0x70, 0x5F, 0x68, 0x69, 0x73, 0x74, 0x6F, 0x72, 0x79, 0x5F, 0x6F, 0x6E,
0x5F, 0x74, 0x68, 0x65, 0x5F, 0x67, 0x72, 0x6F, 0x75, 0x6E, 0x64, 0x22, 0x3A, 0x20, 0x74, 0x72,
0x75, 0x65, 0x2C, 0x0A, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x22, 0x6D,
0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x5F, 0x69, 0x6E, 0x5F, 0x74, 0x68, 0x65, 0x5F, 0x73, 0x6B,
0x79, 0x22, 0x3A, 0x20, 0x22, 0x48, 0x4D, 0x53, 0x20, 0x74, 0x65, 0x73, 0x74, 0x20, 0x74, 0x65,
0x78, 0x74, 0x3A, 0x20, 0x49, 0x20, 0x67, 0x6F, 0x74, 0x20, 0x65, 0x72, 0x72, 0x6F, 0x72, 0x20,
0x69, 0x6E, 0x20, 0x74, 0x68, 0x65, 0x20, 0x73, 0x6B, 0x79, 0x20, 0x32, 0x22, 0x2C, 0x0A, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x22, 0x69, 0x73, 0x5F, 0x6B, 0x65, 0x65,
0x70, 0x5F, 0x68, 0x69, 0x73, 0x74, 0x6F, 0x72, 0x79, 0x5F, 0x69, 0x6E, 0x5F, 0x74, 0x68, 0x65,
0x5F, 0x73, 0x6B, 0x79, 0x22, 0x3A, 0x20, 0x74, 0x72, 0x75, 0x65, 0x0A, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x7D, 0x0A, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x7D, 0x2C, 0x0A, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x7B, 0x0A, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x22,
0x68, 0x6D, 0x73, 0x5F, 0x65, 0x72, 0x72, 0x6F, 0x72, 0x5F, 0x63, 0x6F, 0x64, 0x65, 0x22, 0x3A,
0x20, 0x22, 0x30, 0x78, 0x31, 0x45, 0x30, 0x32, 0x30, 0x30, 0x30, 0x33, 0x22, 0x2C, 0x0A, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x22, 0x68, 0x6D, 0x73, 0x5F, 0x69, 0x6E, 0x74, 0x65,
0x72, 0x66, 0x61, 0x63, 0x65, 0x22, 0x3A, 0x20, 0x7B, 0x0A, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x22, 0x6D, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x5F, 0x74, 0x69, 0x74,
0x6C, 0x65, 0x22, 0x3A, 0x20, 0x22, 0x48, 0x4D, 0x53, 0x20, 0x74, 0x65, 0x73, 0x74, 0x20, 0x74,
0x65, 0x78, 0x74, 0x3A, 0x20, 0x49, 0x20, 0x61, 0x6D, 0x20, 0x65, 0x72, 0x72, 0x6F, 0x72, 0x20,
0x63, 0x6F, 0x64, 0x65, 0x20, 0x54, 0x69, 0x74, 0x6C, 0x65, 0x20, 0x33, 0x22, 0x2C, 0x0A, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x22, 0x6D, 0x65, 0x73, 0x73, 0x61, 0x67,
0x65, 0x5F, 0x63, 0x6F, 0x6E, 0x74, 0x65, 0x6E, 0x74, 0x22, 0x3A, 0x20, 0x22, 0x48, 0x4D, 0x53,
0x20, 0x74, 0x65, 0x73, 0x74, 0x20, 0x74, 0x65, 0x78, 0x74, 0x3A, 0x20, 0x49, 0x20, 0x61, 0x6D,
0x20, 0x65, 0x72, 0x72, 0x6F, 0x72, 0x20, 0x63, 0x6F, 0x64, 0x65, 0x20, 0x43, 0x6F, 0x6E, 0x74,
0x65, 0x6E, 0x74, 0x20, 0x33, 0x22, 0x0A, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x7D,
0x2C, 0x0A, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x22, 0x66, 0x70, 0x76, 0x5F, 0x69,
0x6E, 0x74, 0x65, 0x72, 0x66, 0x61, 0x63, 0x65, 0x22, 0x3A, 0x20, 0x7B, 0x0A, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x22, 0x6D, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x5F,
0x6F, 0x6E, 0x5F, 0x74, 0x68, 0x65, 0x5F, 0x67, 0x72, 0x6F, 0x75, 0x6E, 0x64, 0x22, 0x3A, 0x20,
0x22, 0x48, 0x4D, 0x53, 0x20, 0x74, 0x65, 0x73, 0x74, 0x20, 0x74, 0x65, 0x78, 0x74, 0x3A, 0x20,
0x49, 0x20, 0x67, 0x6F, 0x74, 0x20, 0x65, 0x72, 0x72, 0x6F, 0x72, 0x20, 0x6F, 0x6E, 0x20, 0x74,
0x68, 0x65, 0x20, 0x67, 0x72, 0x6F, 0x75, 0x6E, 0x64, 0x20, 0x33, 0x22, 0x2C, 0x0A, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x22, 0x69, 0x73, 0x5F, 0x6B, 0x65, 0x65, 0x70,
0x5F, 0x68, 0x69, 0x73, 0x74, 0x6F, 0x72, 0x79, 0x5F, 0x6F, 0x6E, 0x5F, 0x74, 0x68, 0x65, 0x5F,
0x67, 0x72, 0x6F, 0x75, 0x6E, 0x64, 0x22, 0x3A, 0x20, 0x74, 0x72, 0x75, 0x65, 0x2C, 0x0A, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x22, 0x6D, 0x65, 0x73, 0x73, 0x61, 0x67,
0x65, 0x5F, 0x69, 0x6E, 0x5F, 0x74, 0x68, 0x65, 0x5F, 0x73, 0x6B, 0x79, 0x22, 0x3A, 0x20, 0x22,
0x48, 0x4D, 0x53, 0x20, 0x74, 0x65, 0x73, 0x74, 0x20, 0x74, 0x65, 0x78, 0x74, 0x3A, 0x20, 0x49,
0x20, 0x67, 0x6F, 0x74, 0x20, 0x65, 0x72, 0x72, 0x6F, 0x72, 0x20, 0x69, 0x6E, 0x20, 0x74, 0x68,
0x65, 0x20, 0x73, 0x6B, 0x79, 0x20, 0x33, 0x22, 0x2C, 0x0A, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x22, 0x69, 0x73, 0x5F, 0x6B, 0x65, 0x65, 0x70, 0x5F, 0x68, 0x69, 0x73,
0x74, 0x6F, 0x72, 0x79, 0x5F, 0x69, 0x6E, 0x5F, 0x74, 0x68, 0x65, 0x5F, 0x73, 0x6B, 0x79, 0x22,
0x3A, 0x20, 0x74, 0x72, 0x75, 0x65, 0x0A, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x7D,
0x0A, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x7D, 0x2C, 0x0A, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x7B, 0x0A, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x22, 0x68, 0x6D, 0x73, 0x5F, 0x65,
0x72, 0x72, 0x6F, 0x72, 0x5F, 0x63, 0x6F, 0x64, 0x65, 0x22, 0x3A, 0x20, 0x22, 0x30, 0x78, 0x31,
0x45, 0x30, 0x32, 0x30, 0x30, 0x30, 0x34, 0x22, 0x2C, 0x0A, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x22, 0x68, 0x6D, 0x73, 0x5F, 0x69, 0x6E, 0x74, 0x65, 0x72, 0x66, 0x61, 0x63, 0x65,
0x22, 0x3A, 0x20, 0x7B, 0x0A, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x22,
0x6D, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x5F, 0x74, 0x69, 0x74, 0x6C, 0x65, 0x22, 0x3A, 0x20,
0x22, 0x48, 0x4D, 0x53, 0x20, 0x74, 0x65, 0x73, 0x74, 0x20, 0x74, 0x65, 0x78, 0x74, 0x3A, 0x20,
0x49, 0x20, 0x61, 0x6D, 0x20, 0x65, 0x72, 0x72, 0x6F, 0x72, 0x20, 0x63, 0x6F, 0x64, 0x65, 0x20,
0x54, 0x69, 0x74, 0x6C, 0x65, 0x20, 0x34, 0x22, 0x2C, 0x0A, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x22, 0x6D, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x5F, 0x63, 0x6F, 0x6E,
0x74, 0x65, 0x6E, 0x74, 0x22, 0x3A, 0x20, 0x22, 0x48, 0x4D, 0x53, 0x20, 0x74, 0x65, 0x73, 0x74,
0x20, 0x74, 0x65, 0x78, 0x74, 0x3A, 0x20, 0x49, 0x20, 0x61, 0x6D, 0x20, 0x65, 0x72, 0x72, 0x6F,
0x72, 0x20, 0x63, 0x6F, 0x64, 0x65, 0x20, 0x43, 0x6F, 0x6E, 0x74, 0x65, 0x6E, 0x74, 0x20, 0x34,
0x22, 0x0A, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x7D, 0x2C, 0x0A, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x22, 0x66, 0x70, 0x76, 0x5F, 0x69, 0x6E, 0x74, 0x65, 0x72, 0x66,
0x61, 0x63, 0x65, 0x22, 0x3A, 0x20, 0x7B, 0x0A, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x22, 0x6D, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x5F, 0x6F, 0x6E, 0x5F, 0x74, 0x68,
0x65, 0x5F, 0x67, 0x72, 0x6F, 0x75, 0x6E, 0x64, 0x22, 0x3A, 0x20, 0x22, 0x48, 0x4D, 0x53, 0x20,
0x74, 0x65, 0x73, 0x74, 0x20, 0x74, 0x65, 0x78, 0x74, 0x3A, 0x20, 0x49, 0x20, 0x67, 0x6F, 0x74,
0x20, 0x65, 0x72, 0x72, 0x6F, 0x72, 0x20, 0x6F, 0x6E, 0x20, 0x74, 0x68, 0x65, 0x20, 0x67, 0x72,
0x6F, 0x75, 0x6E, 0x64, 0x20, 0x34, 0x22, 0x2C, 0x0A, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x22, 0x69, 0x73, 0x5F, 0x6B, 0x65, 0x65, 0x70, 0x5F, 0x68, 0x69, 0x73, 0x74,
0x6F, 0x72, 0x79, 0x5F, 0x6F, 0x6E, 0x5F, 0x74, 0x68, 0x65, 0x5F, 0x67, 0x72, 0x6F, 0x75, 0x6E,
0x64, 0x22, 0x3A, 0x20, 0x74, 0x72, 0x75, 0x65, 0x2C, 0x0A, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x22, 0x6D, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x5F, 0x69, 0x6E, 0x5F,
0x74, 0x68, 0x65, 0x5F, 0x73, 0x6B, 0x79, 0x22, 0x3A, 0x20, 0x22, 0x48, 0x4D, 0x53, 0x20, 0x74,
0x65, 0x73, 0x74, 0x20, 0x74, 0x65, 0x78, 0x74, 0x3A, 0x20, 0x49, 0x20, 0x67, 0x6F, 0x74, 0x20,
0x65, 0x72, 0x72, 0x6F, 0x72, 0x20, 0x69, 0x6E, 0x20, 0x74, 0x68, 0x65, 0x20, 0x73, 0x6B, 0x79,
0x20, 0x34, 0x22, 0x2C, 0x0A, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x22,
0x69, 0x73, 0x5F, 0x6B, 0x65, 0x65, 0x70, 0x5F, 0x68, 0x69, 0x73, 0x74, 0x6F, 0x72, 0x79, 0x5F,
0x69, 0x6E, 0x5F, 0x74, 0x68, 0x65, 0x5F, 0x73, 0x6B, 0x79, 0x22, 0x3A, 0x20, 0x74, 0x72, 0x75,
0x65, 0x0A, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x7D, 0x0A, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x7D, 0x0A, 0x20, 0x20, 0x20, 0x20, 0x5D, 0x0A, 0x20, 0x20, 0x7D, 0x0A, 0x7D
};
#endif /* __hms_text_config_json_h_included */

View File

@ -0,0 +1,431 @@
/**
********************************************************************
* @file test_hms.c
* @brief
*
* @copyright (c) 2021 DJI. All rights reserved.
*
* All information contained herein is, and remains, the property of DJI.
* The intellectual and technical concepts contained herein are proprietary
* to DJI and may be covered by U.S. and foreign patents, patents in process,
* and protected by trade secret or copyright law. Dissemination of this
* information, including but not limited to data and other proprietary
* material(s) incorporated within the information, in any form, is strictly
* prohibited without the express written consent of DJI.
*
* If you receive this source code without DJIs authorization, you may not
* further disseminate the information, and you must immediately remove the
* source code and notify DJI of its removal. DJI reserves the right to pursue
* legal actions against you for any loss(es) or damage(s) caused by your
* failure to do so.
*
*********************************************************************
*/
/* Includes ------------------------------------------------------------------*/
#include <widget_interaction_test/test_widget_interaction.h>
#include <utils/util_misc.h>
#include <utils/cJSON.h>
#include <utils/util_file.h>
#include "test_hms.h"
#include "dji_hms.h"
#include "dji_hms_info_table.h"
#include "dji_logger.h"
#include "dji_platform.h"
#include "dji_fc_subscription.h"
#include "hms_text_c/en/hms_text_config_json.h"
/* Private constants ---------------------------------------------------------*/
#define MAX_HMS_PRINT_COUNT (150)
#define MAX_BUFFER_LEN (256)
#define MIN_HMS_ERROR_LEVEL (0)
#define MID_HMS_ERROR_LEVEL (3)
#define MAX_HMS_ERROR_LEVEL (6)
#define HMS_DIR_PATH_LEN_MAX (256)
#define DJI_CUSTOM_HMS_CODE_INJECT_ON (0)
/* Private types -------------------------------------------------------------*/
/* Private values -------------------------------------------------------------*/
static const char *oldReplaceAlarmIdStr = "%alarmid";
static const char *oldReplaceIndexStr = "%index";
static const char *oldReplaceComponentIndexStr = "%component_index";
static T_DjiHmsFileBinaryArray s_EnHmsTextConfigFileBinaryArrayList[] = {
{hms_text_config_json_fileName, hms_text_config_json_fileSize, hms_text_config_json_fileBinaryArray},
};
static uint8_t *s_hmsJsonData = NULL;
static E_DjiMobileAppLanguage s_hmsLanguage = DJI_MOBILE_APP_LANGUAGE_ENGLISH;
/* Private functions declaration ---------------------------------------------*/
static T_DjiReturnCode DjiTest_HmsManagerInit(void);
static T_DjiReturnCode DjiTest_HmsManagerDeInit(void);
static T_DjiFcSubscriptionFlightStatus DjiTest_GetValueOfFlightStatus(void);
static bool DjiTest_ReplaceStr(char *buffer, uint32_t bufferMaxLen, const char *target, const char *dest);
static bool DjiTest_MarchErrCodeInfoTable(T_DjiHmsInfoTable hmsInfoTable);
static bool DjiTest_MarchErrCodeInfoTableByJson(T_DjiHmsInfoTable hmsInfoTable);
static T_DjiReturnCode DjiTest_HmsInfoCallback(T_DjiHmsInfoTable hmsInfoTable);
/* Exported functions definition ---------------------------------------------*/
T_DjiReturnCode DjiTest_HmsManagerRunSample(E_DjiMobileAppLanguage language)
{
T_DjiReturnCode returnCode;
T_DjiOsalHandler *osalHandler;
s_hmsLanguage = language;
USER_LOG_INFO("Hms Sample Start");
DjiTest_WidgetLogAppend("Hms Sample Start");
USER_LOG_INFO("--> Step 1: Init hms sample");
DjiTest_WidgetLogAppend("--> Step 1: Init hms sample");
returnCode = DjiTest_HmsManagerInit();
if (returnCode != DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS) {
USER_LOG_ERROR("Hms sample init error, error code:0x%08llX", returnCode);
goto out;
}
osalHandler = DjiPlatform_GetOsalHandler();
USER_LOG_INFO("--> Step 2: Register callback function of push HMS information");
DjiTest_WidgetLogAppend("--> Step 2: Register callback function of push HMS information");
returnCode = DjiHmsManager_RegHmsInfoCallback(DjiTest_HmsInfoCallback);
if (returnCode != DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS) {
USER_LOG_ERROR("Register callback function of push HMS information failed, error code:0x%08llX", returnCode);
goto out;
}
osalHandler->TaskSleepMs(10000);
out:
USER_LOG_INFO("--> Step 3: Deinit hms sample");
DjiTest_WidgetLogAppend("--> Step 3: Deinit hms sample");
returnCode = DjiTest_HmsManagerDeInit();
if (returnCode != DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS) {
USER_LOG_ERROR("Hms sample deinit error, error code:0x%08llX", returnCode);
}
USER_LOG_INFO("Hms Sample End");
DjiTest_WidgetLogAppend("Hms Sample End");
return returnCode;
}
T_DjiReturnCode DjiTest_HmsCustomizationStartService(void)
{
T_DjiReturnCode returnCode;
#ifdef SYSTEM_ARCH_LINUX
char curFileDirPath[HMS_DIR_PATH_LEN_MAX];
char tempPath[HMS_DIR_PATH_LEN_MAX];
#endif
returnCode = DjiHmsCustomization_Init();
if (returnCode != DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS) {
USER_LOG_ERROR("Hms init error, error code:0x%08llX", returnCode);
return returnCode;
}
#ifdef SYSTEM_ARCH_LINUX
//Step 2 : Set hms text Config (Linux environment)
returnCode = DjiUserUtil_GetCurrentFileDirPath(__FILE__, HMS_DIR_PATH_LEN_MAX, curFileDirPath);
if (returnCode != DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS) {
USER_LOG_ERROR("Get file current path error, stat = 0x%08llX", returnCode);
return returnCode;
}
snprintf(tempPath, HMS_DIR_PATH_LEN_MAX, "%shms_text/en", curFileDirPath);
//set default hms text config path
returnCode = DjiHmsCustomization_RegDefaultHmsTextConfigByDirPath(tempPath);
if (returnCode != DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS) {
USER_LOG_ERROR("Add default hms text config error, stat = 0x%08llX", returnCode);
return returnCode;
}
//set hms text config for English language
returnCode = DjiHmsCustomization_RegHmsTextConfigByDirPath(DJI_MOBILE_APP_LANGUAGE_ENGLISH,
tempPath);
if (returnCode != DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS) {
USER_LOG_ERROR("Add hms text config error, stat = 0x%08llX", returnCode);
return returnCode;
}
//set hms text config for Chinese language
snprintf(tempPath, HMS_DIR_PATH_LEN_MAX, "%shms_text/cn", curFileDirPath);
returnCode = DjiHmsCustomization_RegHmsTextConfigByDirPath(DJI_MOBILE_APP_LANGUAGE_CHINESE,
tempPath);
if (returnCode != DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS) {
USER_LOG_ERROR("Add hms text config error, stat = 0x%08llX", returnCode);
return returnCode;
}
#else
//Step 2 : Set hms text Config (RTOS environment)
T_DjiHmsBinaryArrayConfig enHmsTextBinaryArrayConfig = {
.binaryArrayCount = sizeof(s_EnHmsTextConfigFileBinaryArrayList) / sizeof(T_DjiHmsFileBinaryArray),
.fileBinaryArrayList = s_EnHmsTextConfigFileBinaryArrayList
};
//set default hms text config
returnCode = DjiHmsCustomization_RegDefaultHmsTextConfigByBinaryArray(&enHmsTextBinaryArrayConfig);
if (returnCode != DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS) {
USER_LOG_ERROR("Add default hms text config error, stat = 0x%08llX", returnCode);
return returnCode;
}
#endif
#if DJI_CUSTOM_HMS_CODE_INJECT_ON
DjiHmsCustomization_InjectHmsErrorCode(0x1E020000, DJI_HMS_ERROR_LEVEL_FATAL);
#endif
return returnCode;
}
/* Private functions definition-----------------------------------------------*/
static T_DjiReturnCode DjiTest_HmsManagerInit(void)
{
T_DjiReturnCode returnCode;
char curFileDirPath[HMS_DIR_PATH_LEN_MAX];
char tempFileDirPath[HMS_DIR_PATH_LEN_MAX];
uint32_t fileSize = 0;
uint32_t readRealSize = 0;
T_DjiOsalHandler *osalHandler = DjiPlatform_GetOsalHandler();
returnCode = DjiFcSubscription_Init();
if (returnCode != DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS) {
USER_LOG_ERROR("Hms sample init data subscription module failed, error code:0x%08llX", returnCode);
return returnCode;
}
/*! subscribe fc data */
returnCode = DjiFcSubscription_SubscribeTopic(DJI_FC_SUBSCRIPTION_TOPIC_STATUS_FLIGHT,
DJI_DATA_SUBSCRIPTION_TOPIC_10_HZ,
NULL);
if (returnCode != DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS) {
USER_LOG_ERROR("HMS sample subscribe topic flight status error, error code:0x%08llX", returnCode);
return returnCode;
}
#ifdef SYSTEM_ARCH_LINUX
returnCode = DjiUserUtil_GetCurrentFileDirPath(__FILE__, HMS_DIR_PATH_LEN_MAX, curFileDirPath);
if (returnCode != DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS) {
USER_LOG_ERROR("Get file current path error, stat = 0x%08llX", returnCode);
return returnCode;
}
snprintf(tempFileDirPath, HMS_DIR_PATH_LEN_MAX, "%s/data/hms.json", curFileDirPath);
returnCode = UtilFile_GetFileSizeByPath(tempFileDirPath, &fileSize);
if (returnCode != DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS) {
USER_LOG_ERROR("Get file size by path failed, stat = 0x%08llX", returnCode);
return returnCode;
}
USER_LOG_DEBUG("Hms json file size is %d", fileSize);
s_hmsJsonData = osalHandler->Malloc(fileSize);
if (s_hmsJsonData == NULL) {
USER_LOG_ERROR("Malloc failed.");
}
UtilFile_GetFileDataByPath(tempFileDirPath, 0, fileSize, s_hmsJsonData, &readRealSize);
#endif
return DjiHmsManager_Init();
}
static T_DjiReturnCode DjiTest_HmsManagerDeInit(void)
{
T_DjiReturnCode returnCode;
T_DjiOsalHandler *osalHandler = DjiPlatform_GetOsalHandler();
returnCode = DjiFcSubscription_DeInit();
if (returnCode != DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS) {
USER_LOG_ERROR("Deinit data subscription module failed, error code:0x%08llX",
returnCode);
return returnCode;
}
#ifdef SYSTEM_ARCH_LINUX
osalHandler->Free(s_hmsJsonData);
#endif
return DjiHmsManager_DeInit();
}
static T_DjiFcSubscriptionFlightStatus DjiTest_GetValueOfFlightStatus(void)
{
T_DjiReturnCode returnCode;
T_DjiFcSubscriptionFlightStatus flightStatus;
T_DjiDataTimestamp flightStatusTimestamp = {0};
returnCode = DjiFcSubscription_GetLatestValueOfTopic(DJI_FC_SUBSCRIPTION_TOPIC_STATUS_FLIGHT,
(uint8_t *) &flightStatus,
sizeof(T_DjiFcSubscriptionFlightStatus),
&flightStatusTimestamp);
if (returnCode != DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS) {
USER_LOG_ERROR("Get value of topic flight status failed, error code:0x%08llX", returnCode);
flightStatus = 0;
} else {
USER_LOG_DEBUG("Timestamp: millisecond %u microsecond %u.", flightStatusTimestamp.millisecond,
flightStatusTimestamp.microsecond);
USER_LOG_DEBUG("Flight status: %d.", flightStatus);
}
return flightStatus;
}
static bool DjiTest_ReplaceStr(char *buffer, uint32_t bufferMaxLen, const char *target, const char *dest)
{
char printBuffHeader[MAX_BUFFER_LEN] = {0};
uint32_t printBuffHeaderCpyCnt = 0;
char printBuffTail[MAX_BUFFER_LEN] = {0};
uint32_t printBuffTailCpyCnt = 0;
char *targetOffset = NULL;
targetOffset = strstr(buffer, target);
if (!targetOffset) {
return false;
}
printBuffHeaderCpyCnt = targetOffset - buffer;
if (printBuffHeaderCpyCnt > sizeof(printBuffHeader)) {
printBuffHeaderCpyCnt = sizeof(printBuffHeader);
}
memcpy(printBuffHeader, buffer, printBuffHeaderCpyCnt);
printBuffTailCpyCnt = strlen(targetOffset + strlen(target));
if (printBuffTailCpyCnt > sizeof(printBuffTail)) {
printBuffTailCpyCnt = sizeof(printBuffTail);
}
memcpy(printBuffTail, targetOffset + strlen(target), printBuffTailCpyCnt);
snprintf(buffer, bufferMaxLen, "%s%s%s", printBuffHeader, dest, printBuffTail);
return true;
}
static bool DjiTest_MarchErrCodeInfoTable(T_DjiHmsInfoTable hmsInfoTable)
{
char alarmIdStr[20] = {0};
char sensorIdStr[20] = {0};
char componentIdStr[20] = {0};
char printBuff[256] = {0};
const char *originalAlarmInfo = NULL;
uint8_t hmsCodeMatchFlag = 0;
if (!hmsInfoTable.hmsInfo) {
USER_LOG_ERROR("Hms info table is null");
return false;
}
for (int i = 0; i < hmsInfoTable.hmsInfoNum; i++) {
hmsCodeMatchFlag = 0;
for (int j = 0; j < sizeof(hmsErrCodeInfoTbl) / sizeof(T_DjiHmsErrCodeInfo); j++) {
if (hmsInfoTable.hmsInfo[i].errorCode == hmsErrCodeInfoTbl[j].alarmId) {
hmsCodeMatchFlag = 1;
snprintf(alarmIdStr, sizeof(alarmIdStr), "%u", hmsInfoTable.hmsInfo[i].errorCode);
//note:sensor_idx:[0,5].In order to be consistent with the display of pilot, add one.
snprintf(sensorIdStr, sizeof(sensorIdStr), "%d", hmsInfoTable.hmsInfo[i].componentIndex + 1);
snprintf(componentIdStr, sizeof(componentIdStr), "0x%02X", hmsInfoTable.hmsInfo[i].componentIndex + 1);
if (DjiTest_GetValueOfFlightStatus() == DJI_FC_SUBSCRIPTION_FLIGHT_STATUS_IN_AIR) {
originalAlarmInfo = hmsErrCodeInfoTbl[j].flyAlarmInfo;
} else {
originalAlarmInfo = hmsErrCodeInfoTbl[j].groundAlarmInfo;
}
originalAlarmInfo = hmsErrCodeInfoTbl[j].groundAlarmInfo;
if (strlen(originalAlarmInfo)) {
snprintf(printBuff, sizeof(printBuff), "%s", originalAlarmInfo);
DjiTest_ReplaceStr(printBuff, sizeof(printBuff), oldReplaceAlarmIdStr, alarmIdStr);
DjiTest_ReplaceStr(printBuff, sizeof(printBuff), oldReplaceIndexStr, sensorIdStr);
DjiTest_ReplaceStr(printBuff, sizeof(printBuff), oldReplaceComponentIndexStr, componentIdStr);
if (hmsInfoTable.hmsInfo[i].errorLevel > MIN_HMS_ERROR_LEVEL &&
hmsInfoTable.hmsInfo[i].errorLevel < MID_HMS_ERROR_LEVEL) {
USER_LOG_WARN("[ErrorCode:0x%2x] %s", hmsInfoTable.hmsInfo[i].errorCode, printBuff);
} else if (hmsInfoTable.hmsInfo[i].errorLevel >= MID_HMS_ERROR_LEVEL &&
hmsInfoTable.hmsInfo[i].errorLevel < MAX_HMS_ERROR_LEVEL) {
USER_LOG_ERROR("[ErrorCode:0x%2x] %s", hmsInfoTable.hmsInfo[i].errorCode, printBuff);
}
}
}
}
if (!hmsCodeMatchFlag) {
USER_LOG_WARN("[ErrorCode:0x%2x] There are no matching documents in the current hmsErrCodeInfoTbl for now.",
hmsInfoTable.hmsInfo[i].errorCode);
}
}
return true;
}
static bool DjiTest_MarchErrCodeInfoTableByJson(T_DjiHmsInfoTable hmsInfoTable)
{
cJSON *hmsJsonRoot = NULL;
cJSON *hmsErrorCode = NULL;
cJSON *hmsLanguage = NULL;
char hmsErrorCodeString[HMS_DIR_PATH_LEN_MAX] = {0};
hmsJsonRoot = cJSON_Parse((char *) s_hmsJsonData);
if (hmsJsonRoot == NULL) {
return 0;
}
for (int i = 0; i < hmsInfoTable.hmsInfoNum; i++) {
if (DjiTest_GetValueOfFlightStatus() == DJI_FC_SUBSCRIPTION_FLIGHT_STATUS_IN_AIR) {
sprintf(hmsErrorCodeString, "fpv_tip_0x%08X_in_the_sky", hmsInfoTable.hmsInfo[i].errorCode);
} else {
sprintf(hmsErrorCodeString, "fpv_tip_0x%08X", hmsInfoTable.hmsInfo[i].errorCode);
}
hmsErrorCode = cJSON_GetObjectItem(hmsJsonRoot, hmsErrorCodeString);
if (hmsErrorCode != NULL) {
if (s_hmsLanguage == DJI_MOBILE_APP_LANGUAGE_CHINESE) {
hmsLanguage = cJSON_GetObjectItem(hmsErrorCode, "zh");
} else if (s_hmsLanguage == DJI_MOBILE_APP_LANGUAGE_ENGLISH) {
hmsLanguage = cJSON_GetObjectItem(hmsErrorCode, "en");
} else if (s_hmsLanguage == DJI_MOBILE_APP_LANGUAGE_JAPANESE) {
hmsLanguage = cJSON_GetObjectItem(hmsErrorCode, "ja");
} else if (s_hmsLanguage == DJI_MOBILE_APP_LANGUAGE_FRENCH) {
hmsLanguage = cJSON_GetObjectItem(hmsErrorCode, "fr");
}
if (hmsLanguage != NULL) {
if (hmsInfoTable.hmsInfo[i].errorLevel > MIN_HMS_ERROR_LEVEL &&
hmsInfoTable.hmsInfo[i].errorLevel < MID_HMS_ERROR_LEVEL) {
USER_LOG_WARN("[ErrorCode: 0x%2x]: %s", hmsInfoTable.hmsInfo[i].errorCode,
hmsLanguage->valuestring);
} else if (hmsInfoTable.hmsInfo[i].errorLevel >= MID_HMS_ERROR_LEVEL &&
hmsInfoTable.hmsInfo[i].errorLevel < MAX_HMS_ERROR_LEVEL) {
USER_LOG_ERROR("[ErrorCode: 0x%2x]: %s", hmsInfoTable.hmsInfo[i].errorCode,
hmsLanguage->valuestring);
}
} else {
USER_LOG_WARN("[ErrorCode: 0x%2x] There are no matching documents for this language for now.",
hmsInfoTable.hmsInfo[i].errorCode);
}
} else {
USER_LOG_WARN("[ErrorCode: 0x%2x] There are no matching documents in the current json for now.",
hmsInfoTable.hmsInfo[i].errorCode);
}
}
cJSON_Delete(hmsJsonRoot);
}
static T_DjiReturnCode DjiTest_HmsInfoCallback(T_DjiHmsInfoTable hmsInfoTable)
{
#ifdef SYSTEM_ARCH_LINUX
DjiTest_MarchErrCodeInfoTableByJson(hmsInfoTable);
#else
if (!DjiTest_MarchErrCodeInfoTable(hmsInfoTable)) {
USER_LOG_ERROR("March HMS Information failed.");
return DJI_ERROR_SYSTEM_MODULE_CODE_UNKNOWN;
}
#endif
if (hmsInfoTable.hmsInfoNum == 0) {
USER_LOG_INFO("All systems of drone are running well now.");
}
return DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS;
}
/****************** (C) COPYRIGHT DJI Innovations *****END OF FILE****/

View File

@ -0,0 +1,50 @@
/**
********************************************************************
* @file test_hms.h
* @brief This is the header file for "test_hms.c", defining the structure and
* (exported) function prototypes.
*
* @copyright (c) 2021 DJI. All rights reserved.
*
* All information contained herein is, and remains, the property of DJI.
* The intellectual and technical concepts contained herein are proprietary
* to DJI and may be covered by U.S. and foreign patents, patents in process,
* and protected by trade secret or copyright law. Dissemination of this
* information, including but not limited to data and other proprietary
* material(s) incorporated within the information, in any form, is strictly
* prohibited without the express written consent of DJI.
*
* If you receive this source code without DJIs authorization, you may not
* further disseminate the information, and you must immediately remove the
* source code and notify DJI of its removal. DJI reserves the right to pursue
* legal actions against you for any loss(es) or damage(s) caused by your
* failure to do so.
*
*********************************************************************
*/
/* Define to prevent recursive inclusion -------------------------------------*/
#ifndef TEST_HMS_H
#define TEST_HMS_H
/* Includes ------------------------------------------------------------------*/
#include "dji_typedef.h"
#ifdef __cplusplus
extern "C" {
#endif
/* Exported constants --------------------------------------------------------*/
/* Exported types ------------------------------------------------------------*/
/* Exported functions --------------------------------------------------------*/
T_DjiReturnCode DjiTest_HmsManagerRunSample(E_DjiMobileAppLanguage language);
T_DjiReturnCode DjiTest_HmsCustomizationStartService(void);
#ifdef __cplusplus
}
#endif
#endif // TEST_HMS_H
/************************ (C) COPYRIGHT DJI Innovations *******END OF FILE******/

View File

@ -0,0 +1,131 @@
/**
********************************************************************
* @file test_interest_point.c
* @brief
*
* @copyright (c) 2018 DJI. All rights reserved.
*
* All information contained herein is, and remains, the property of DJI.
* The intellectual and technical concepts contained herein are proprietary
* to DJI and may be covered by U.S. and foreign patents, patents in process,
* and protected by trade secret or copyright law. Dissemination of this
* information, including but not limited to data and other proprietary
* material(s) incorporated within the information, in any form, is strictly
* prohibited without the express written consent of DJI.
*
* If you receive this source code without DJIs authorization, you may not
* further disseminate the information, and you must immediately remove the
* source code and notify DJI of its removal. DJI reserves the right to pursue
* legal actions against you for any loss(es) or damage(s) caused by your
* failure to do so.
*
*********************************************************************
*/
/* Includes ------------------------------------------------------------------*/
#include "test_interest_point.h"
#include "dji_interest_point.h"
#include "dji_logger.h"
#include "dji_flight_controller.h"
#include "flight_control/test_flight_control.h"
/* Private constants ---------------------------------------------------------*/
/* Private types -------------------------------------------------------------*/
/* Private values -------------------------------------------------------------*/
static T_DjiReturnCode DjiUser_InterestPointMissionStateCallback(T_DjiInterestPointMissionState missionState);
/* Private functions declaration ---------------------------------------------*/
/* Exported functions definition ---------------------------------------------*/
T_DjiReturnCode DjiTest_InterestPointRunSample(void)
{
T_DjiReturnCode returnCode;
T_DjiInterestPointSettings interestPointSettings = {0};
T_DjiOsalHandler *osalHandler = DjiPlatform_GetOsalHandler();
T_DjiFlightControllerRidInfo ridInfo = {0};
ridInfo.latitude = 22.542812;
ridInfo.longitude = 113.958902;
ridInfo.altitude = 10;
returnCode = DjiFlightController_Init(ridInfo);
if (returnCode != DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS) {
USER_LOG_ERROR("Flight control init failed, errno=%lld", returnCode);
return returnCode;
}
returnCode = DjiInterestPoint_Init();
if (returnCode != DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS) {
USER_LOG_ERROR("Point interest init failed, errno=%lld", returnCode);
return returnCode;
}
osalHandler->TaskSleepMs(1000);
DjiFlightController_ObtainJoystickCtrlAuthority();
osalHandler->TaskSleepMs(1000);
DjiFlightController_StartTakeoff();
osalHandler->TaskSleepMs(1000);
DjiTest_FlightControlVelocityAndYawRateCtrl((T_DjiTestFlightControlVector3f) {0, 0, 5}, 0, 10000);
osalHandler->TaskSleepMs(1000);
DjiTest_FlightControlVelocityAndYawRateCtrl((T_DjiTestFlightControlVector3f) {3, 0, 0}, 0, 5000);
interestPointSettings.latitude = 22.542812;
interestPointSettings.longitude = 113.958902;
returnCode = DjiInterestPoint_RegMissionStateCallback(DjiUser_InterestPointMissionStateCallback);
if (returnCode != DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS) {
USER_LOG_ERROR("Register mission state callback failed, errno=%lld", returnCode);
return returnCode;
}
returnCode = DjiInterestPoint_Start(interestPointSettings);
if (returnCode != DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS) {
USER_LOG_ERROR("Point interest start failed, errno=%lld", returnCode);
return returnCode;
}
DjiInterestPoint_SetSpeed(5.0f);
for (int i = 0; i < 60; ++i) {
USER_LOG_INFO("Interest point mission running %d.", i);
osalHandler->TaskSleepMs(1000);
}
returnCode = DjiInterestPoint_Stop();
if (returnCode != DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS) {
USER_LOG_ERROR("Point interest stop failed, errno=%lld", returnCode);
return returnCode;
}
DjiFlightController_StartForceLanding();
returnCode = DjiInterestPoint_DeInit();
if (returnCode != DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS) {
USER_LOG_ERROR("Point interest deinit failed, errno=%lld", returnCode);
return returnCode;
}
returnCode = DjiFlightController_DeInit();
if (returnCode != DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS) {
USER_LOG_ERROR("Flight control init failed, errno=%lld", returnCode);
return returnCode;
}
return DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS;
}
/* Private functions definition-----------------------------------------------*/
static T_DjiReturnCode DjiUser_InterestPointMissionStateCallback(T_DjiInterestPointMissionState missionState)
{
USER_LOG_INFO("Interest point state: %d, radius: %.2f m, speed: %.2f m/s", missionState.state, missionState.radius,
missionState.curSpeed);
return DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS;
}
/****************** (C) COPYRIGHT DJI Innovations *****END OF FILE****/

View File

@ -0,0 +1,49 @@
/**
********************************************************************
* @file test_interest_point.h
* @brief This is the header file for "test_interest_point.c", defining the structure and
* (exported) function prototypes.
*
* @copyright (c) 2018 DJI. All rights reserved.
*
* All information contained herein is, and remains, the property of DJI.
* The intellectual and technical concepts contained herein are proprietary
* to DJI and may be covered by U.S. and foreign patents, patents in process,
* and protected by trade secret or copyright law. Dissemination of this
* information, including but not limited to data and other proprietary
* material(s) incorporated within the information, in any form, is strictly
* prohibited without the express written consent of DJI.
*
* If you receive this source code without DJIs authorization, you may not
* further disseminate the information, and you must immediately remove the
* source code and notify DJI of its removal. DJI reserves the right to pursue
* legal actions against you for any loss(es) or damage(s) caused by your
* failure to do so.
*
*********************************************************************
*/
/* Define to prevent recursive inclusion -------------------------------------*/
#ifndef TEST_INTEREST_POINT_H
#define TEST_INTEREST_POINT_H
/* Includes ------------------------------------------------------------------*/
#include "dji_typedef.h"
#ifdef __cplusplus
extern "C" {
#endif
/* Exported constants --------------------------------------------------------*/
/* Exported types ------------------------------------------------------------*/
/* Exported functions --------------------------------------------------------*/
T_DjiReturnCode DjiTest_InterestPointRunSample(void);
#ifdef __cplusplus
}
#endif
#endif // TEST_INTEREST_POINT_H
/************************ (C) COPYRIGHT DJI Innovations *******END OF FILE******/

View File

@ -0,0 +1,240 @@
/**
********************************************************************
* @file test_liveview.c
* @brief
*
* @copyright (c) 2021 DJI. All rights reserved.
*
* All information contained herein is, and remains, the property of DJI.
* The intellectual and technical concepts contained herein are proprietary
* to DJI and may be covered by U.S. and foreign patents, patents in process,
* and protected by trade secret or copyright law. Dissemination of this
* information, including but not limited to data and other proprietary
* material(s) incorporated within the information, in any form, is strictly
* prohibited without the express written consent of DJI.
*
* If you receive this source code without DJIs authorization, you may not
* further disseminate the information, and you must immediately remove the
* source code and notify DJI of its removal. DJI reserves the right to pursue
* legal actions against you for any loss(es) or damage(s) caused by your
* failure to do so.
*
*********************************************************************
*/
/* Includes ------------------------------------------------------------------*/
#include <utils/util_misc.h>
#include <widget_interaction_test/test_widget_interaction.h>
#include "test_liveview.h"
#include "dji_liveview.h"
#include "dji_logger.h"
#include "dji_platform.h"
#include "dji_aircraft_info.h"
#include "time.h"
/* Private constants ---------------------------------------------------------*/
#define TEST_LIVEVIEW_STREAM_FILE_PATH_STR_MAX_SIZE 256
#define TEST_LIVEVIEW_STREAM_STROING_TIME_IN_SECONDS 20
#define TEST_LIVEVIEW_STREAM_REQUEST_I_FRAME_ON 1
#define TEST_LIVEVIEW_STREAM_REQUEST_I_FRAME_TICK_IN_SECONDS 5
/* Private types -------------------------------------------------------------*/
/* Private values -------------------------------------------------------------*/
static char s_fpvCameraStreamFilePath[TEST_LIVEVIEW_STREAM_FILE_PATH_STR_MAX_SIZE];
static char s_payloadCameraStreamFilePath[TEST_LIVEVIEW_STREAM_FILE_PATH_STR_MAX_SIZE];
/* Private functions declaration ---------------------------------------------*/
static void DjiTest_FpvCameraStreamCallback(E_DjiLiveViewCameraPosition position, const uint8_t *buf,
uint32_t bufLen);
static void DjiTest_PayloadCameraStreamCallback(E_DjiLiveViewCameraPosition position, const uint8_t *buf,
uint32_t bufLen);
/* Exported functions definition ---------------------------------------------*/
T_DjiReturnCode DjiTest_LiveviewRunSample(E_DjiMountPosition mountPosition)
{
T_DjiReturnCode returnCode;
T_DjiOsalHandler *osalHandler = DjiPlatform_GetOsalHandler();
time_t currentTime = time(NULL);
struct tm *localTime = NULL;
T_DjiAircraftInfoBaseInfo aircraftInfoBaseInfo = {0};
USER_LOG_INFO("Liveview sample start");
DjiTest_WidgetLogAppend("Liveview sample start");
returnCode = DjiAircraftInfo_GetBaseInfo(&aircraftInfoBaseInfo);
if (returnCode != DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS) {
USER_LOG_ERROR("get aircraft base info error");
return DJI_ERROR_SYSTEM_MODULE_CODE_SYSTEM_ERROR;
}
USER_LOG_INFO("--> Step 1: Init liveview module");
DjiTest_WidgetLogAppend("--> Step 1: Init liveview module");
returnCode = DjiLiveview_Init();
if (returnCode != DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS) {
USER_LOG_ERROR("Liveview init failed, error code: 0x%08X", returnCode);
goto out;
}
USER_LOG_INFO("--> Step 2: Start h264 stream of the fpv and selected payload\r\n");
DjiTest_WidgetLogAppend("--> Step 2: Start h264 stream of the fpv and selected payload\r\n");
if (aircraftInfoBaseInfo.aircraftSeries == DJI_AIRCRAFT_SERIES_M300 ||
aircraftInfoBaseInfo.aircraftSeries == DJI_AIRCRAFT_SERIES_M350 ||
aircraftInfoBaseInfo.aircraftSeries == DJI_AIRCRAFT_SERIES_M30) {
localTime = localtime(&currentTime);
sprintf(s_fpvCameraStreamFilePath, "fpv_stream_%04d%02d%02d_%02d-%02d-%02d.h264",
localTime->tm_year + 1900, localTime->tm_mon + 1, localTime->tm_mday,
localTime->tm_hour, localTime->tm_min, localTime->tm_sec);
returnCode = DjiLiveview_StartH264Stream(DJI_LIVEVIEW_CAMERA_POSITION_FPV, DJI_LIVEVIEW_CAMERA_SOURCE_DEFAULT,
DjiTest_FpvCameraStreamCallback);
if (returnCode != DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS) {
USER_LOG_ERROR("Request h264 of fpv failed, error code: 0x%08X", returnCode);
goto out;
}
}
localTime = localtime(&currentTime);
sprintf(s_payloadCameraStreamFilePath, "payload%d_vis_stream_%04d%02d%02d_%02d-%02d-%02d.h264",
mountPosition, localTime->tm_year + 1900, localTime->tm_mon + 1, localTime->tm_mday,
localTime->tm_hour, localTime->tm_min, localTime->tm_sec);
returnCode = DjiLiveview_StartH264Stream((E_DjiLiveViewCameraPosition) mountPosition,
DJI_LIVEVIEW_CAMERA_SOURCE_DEFAULT,
DjiTest_PayloadCameraStreamCallback);
if (returnCode != DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS) {
USER_LOG_ERROR("Request h264 of payload %d failed, error code: 0x%08X", mountPosition, returnCode);
}
for (int i = 0; i < TEST_LIVEVIEW_STREAM_STROING_TIME_IN_SECONDS; ++i) {
USER_LOG_INFO("Storing camera h264 stream, second: %d.", i + 1);
#if TEST_LIVEVIEW_STREAM_REQUEST_I_FRAME_ON
if (i % TEST_LIVEVIEW_STREAM_REQUEST_I_FRAME_TICK_IN_SECONDS == 0) {
returnCode = DjiLiveview_RequestIntraframeFrameData((E_DjiLiveViewCameraPosition) mountPosition,
DJI_LIVEVIEW_CAMERA_SOURCE_DEFAULT);
if (returnCode != DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS) {
USER_LOG_ERROR("Request stream I frame of payload %d failed, error code: 0x%08X", mountPosition,
returnCode);
}
}
#endif
osalHandler->TaskSleepMs(1000);
}
USER_LOG_INFO("--> Step 3: Stop h264 stream of the fpv and selected payload\r\n");
DjiTest_WidgetLogAppend("--> Step 3: Stop h264 stream of the fpv and selected payload");
if (aircraftInfoBaseInfo.aircraftSeries == DJI_AIRCRAFT_SERIES_M300 ||
aircraftInfoBaseInfo.aircraftSeries == DJI_AIRCRAFT_SERIES_M350 ||
aircraftInfoBaseInfo.aircraftSeries == DJI_AIRCRAFT_SERIES_M30) {
returnCode = DjiLiveview_StopH264Stream(DJI_LIVEVIEW_CAMERA_POSITION_FPV, DJI_LIVEVIEW_CAMERA_SOURCE_DEFAULT);
if (returnCode != DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS) {
USER_LOG_ERROR("Request to stop h264 of fpv failed, error code: 0x%08X", returnCode);
goto out;
}
}
returnCode = DjiLiveview_StopH264Stream((E_DjiLiveViewCameraPosition) mountPosition,
DJI_LIVEVIEW_CAMERA_SOURCE_DEFAULT);
if (returnCode != DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS) {
USER_LOG_ERROR("Request to stop h264 of payload %d failed, error code: 0x%08X", mountPosition, returnCode);
goto out;
}
USER_LOG_INFO("Fpv stream is saved to file: %s", s_fpvCameraStreamFilePath);
USER_LOG_INFO("Payload%d stream is saved to file: %s\r\n", mountPosition, s_payloadCameraStreamFilePath);
if (aircraftInfoBaseInfo.aircraftType == DJI_AIRCRAFT_TYPE_M3T ||
aircraftInfoBaseInfo.aircraftType == DJI_AIRCRAFT_TYPE_M3TD) {
USER_LOG_INFO("--> Start h264 stream of the fpv and selected payload\r\n");
localTime = localtime(&currentTime);
sprintf(s_payloadCameraStreamFilePath, "payload%d_ir_stream_%04d%02d%02d_%02d-%02d-%02d.h264",
mountPosition, localTime->tm_year + 1900, localTime->tm_mon + 1, localTime->tm_mday,
localTime->tm_hour, localTime->tm_min, localTime->tm_sec);
returnCode = DjiLiveview_StartH264Stream((E_DjiLiveViewCameraPosition) mountPosition,
DJI_LIVEVIEW_CAMERA_SOURCE_M3T_IR,
DjiTest_PayloadCameraStreamCallback);
if (returnCode != DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS) {
USER_LOG_ERROR("Request h264 of payload %d failed, error code: 0x%08X", mountPosition, returnCode);
}
for (int i = 0; i < TEST_LIVEVIEW_STREAM_STROING_TIME_IN_SECONDS; ++i) {
USER_LOG_INFO("Storing camera h264 stream, second: %d.", i + 1);
osalHandler->TaskSleepMs(1000);
}
returnCode = DjiLiveview_StopH264Stream((E_DjiLiveViewCameraPosition) mountPosition,
DJI_LIVEVIEW_CAMERA_SOURCE_M3T_IR);
if (returnCode != DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS) {
USER_LOG_ERROR("Request to stop h264 of payload %d failed, error code: 0x%08X", mountPosition, returnCode);
goto out;
}
}
USER_LOG_INFO("Fpv stream is saved to file: %s", s_fpvCameraStreamFilePath);
USER_LOG_INFO("Payload%d stream is saved to file: %s\r\n", mountPosition, s_payloadCameraStreamFilePath);
USER_LOG_INFO("--> Step 4: Deinit liveview module");
DjiTest_WidgetLogAppend("--> Step 4: Deinit liveview module");
returnCode = DjiLiveview_Deinit();
if (returnCode != DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS) {
USER_LOG_ERROR("Liveview deinit failed, error code: 0x%08X", returnCode);
goto out;
}
out:
USER_LOG_INFO("Liveview sample end");
return returnCode;
}
/* Private functions definition-----------------------------------------------*/
static void DjiTest_FpvCameraStreamCallback(E_DjiLiveViewCameraPosition position, const uint8_t *buf,
uint32_t bufLen)
{
FILE *fp = NULL;
size_t size;
fp = fopen(s_fpvCameraStreamFilePath, "ab+");
if (fp == NULL) {
printf("fopen failed!\n");
return;
}
size = fwrite(buf, 1, bufLen, fp);
if (size != bufLen) {
fclose(fp);
return;
}
fflush(fp);
fclose(fp);
}
static void DjiTest_PayloadCameraStreamCallback(E_DjiLiveViewCameraPosition position, const uint8_t *buf,
uint32_t bufLen)
{
FILE *fp = NULL;
size_t size;
fp = fopen(s_payloadCameraStreamFilePath, "ab+");
if (fp == NULL) {
printf("fopen failed!\n");
return;
}
size = fwrite(buf, 1, bufLen, fp);
if (size != bufLen) {
fclose(fp);
return;
}
fflush(fp);
fclose(fp);
}
/****************** (C) COPYRIGHT DJI Innovations *****END OF FILE****/

View File

@ -0,0 +1,49 @@
/**
********************************************************************
* @file test_liveview.h
* @brief This is the header file for "test_liveview.c", defining the structure and
* (exported) function prototypes.
*
* @copyright (c) 2021 DJI. All rights reserved.
*
* All information contained herein is, and remains, the property of DJI.
* The intellectual and technical concepts contained herein are proprietary
* to DJI and may be covered by U.S. and foreign patents, patents in process,
* and protected by trade secret or copyright law. Dissemination of this
* information, including but not limited to data and other proprietary
* material(s) incorporated within the information, in any form, is strictly
* prohibited without the express written consent of DJI.
*
* If you receive this source code without DJIs authorization, you may not
* further disseminate the information, and you must immediately remove the
* source code and notify DJI of its removal. DJI reserves the right to pursue
* legal actions against you for any loss(es) or damage(s) caused by your
* failure to do so.
*
*********************************************************************
*/
/* Define to prevent recursive inclusion -------------------------------------*/
#ifndef TEST_LIVEVIEW_H
#define TEST_LIVEVIEW_H
/* Includes ------------------------------------------------------------------*/
#include "dji_typedef.h"
#ifdef __cplusplus
extern "C" {
#endif
/* Exported constants --------------------------------------------------------*/
/* Exported types ------------------------------------------------------------*/
/* Exported functions --------------------------------------------------------*/
T_DjiReturnCode DjiTest_LiveviewRunSample(E_DjiMountPosition mountPosition);
#ifdef __cplusplus
}
#endif
#endif // TEST_LIVEVIEW_H
/************************ (C) COPYRIGHT DJI Innovations *******END OF FILE******/

View File

@ -0,0 +1,833 @@
/**
********************************************************************
* @file test_mop_channel.c
* @brief
*
* @copyright (c) 2021 DJI. All rights reserved.
*
* All information contained herein is, and remains, the property of DJI.
* The intellectual and technical concepts contained herein are proprietary
* to DJI and may be covered by U.S. and foreign patents, patents in process,
* and protected by trade secret or copyright law. Dissemination of this
* information, including but not limited to data and other proprietary
* material(s) incorporated within the information, in any form, is strictly
* prohibited without the express written consent of DJI.
*
* If you receive this source code without DJIs authorization, you may not
* further disseminate the information, and you must immediately remove the
* source code and notify DJI of its removal. DJI reserves the right to pursue
* legal actions against you for any loss(es) or damage(s) caused by your
* failure to do so.
*
*********************************************************************
*/
/* Includes ------------------------------------------------------------------*/
#include <utils/util_misc.h>
#include <stdio.h>
#include <utils/util_md5.h>
#include "dji_mop_channel.h"
#include "dji_logger.h"
#include "dji_platform.h"
#include "test_mop_channel.h"
/* Private constants ---------------------------------------------------------*/
#define DJI_MOP_CHANNEL_TASK_STACK_SIZE 2048
#define TEST_MOP_CHANNEL_INIT_TIMEMS (3 * 1000)
#define TEST_MOP_CHANNEL_RETRY_TIMEMS (3 * 1000)
#define TEST_MOP_CHANNEL_NORMAL_TRANSFOR_CHANNEL_ID 49152
#define TEST_MOP_CHANNEL_NORMAL_TRANSFOR_USING_RELIABLE_TRANS 0
#define TEST_MOP_CHANNEL_NORMAL_TRANSFOR_SEND_TASK_FREQ 1
#define TEST_MOP_CHANNEL_NORMAL_TRANSFOR_SEND_BUFFER (64 * 1024)
#define TEST_MOP_CHANNEL_NORMAL_TRANSFOR_RECV_BUFFER (100 * 1024)
#define TEST_MOP_CHANNEL_FILE_SERVICE_CHANNEL_ID 49153
#define TEST_MOP_CHANNEL_FILE_SERVICE_SEND_BUFFER (3 * 1024 * 1024)
#define TEST_MOP_CHANNEL_FILE_SERVICE_RECV_BUFFER (100 * 1024)
#define TEST_MOP_CHANNEL_FILE_SERVICE_CLIENT_MAX_SUPPORT_NUM 10
/* Private types -------------------------------------------------------------*/
typedef enum {
MOP_FILE_SERVICE_DOWNLOAD_IDEL = 0,
MOP_FILE_SERVICE_DOWNLOAD_REQUEST_START,
MOP_FILE_SERVICE_DOWNLOAD_FILE_INFO_SUCCESS,
MOP_FILE_SERVICE_DOWNLOAD_FILE_INFO_FAILED,
MOP_FILE_SERVICE_DOWNLOAD_DATA_SENDING,
MOP_FILE_SERVICE_DOWNLOAD_FINISHED_SUCCESS,
MOP_FILE_SERVICE_DOWNLOAD_FINISHED_FAILED,
MOP_FILE_SERVICE_DOWNLOAD_STOP,
} E_MopFileServiceDownloadState;
typedef enum {
MOP_FILE_SERVICE_UPLOAD_IDEL = 0,
MOP_FILE_SERVICE_UPLOAD_REQUEST_START,
MOP_FILE_SERVICE_UPLOAD_FILE_INFO_SUCCESS,
MOP_FILE_SERVICE_UPLOAD_FILE_INFO_FAILED,
MOP_FILE_SERVICE_UPLOAD_DATA_SENDING,
MOP_FILE_SERVICE_UPLOAD_FINISHED_SUCCESS,
MOP_FILE_SERVICE_UPLOAD_FINISHED_FAILED,
MOP_FILE_SERVICE_UPLOAD_STOP,
} E_MopFileServiceUploadState;
typedef struct {
uint8_t index;
T_DjiTaskHandle clientRecvTask;
T_DjiTaskHandle clientSendTask;
T_DjiMopChannelHandle clientHandle;
E_MopFileServiceDownloadState downloadState;
uint16_t downloadSeqNum;
E_MopFileServiceUploadState uploadState;
uint16_t uploadSeqNum;
} T_MopFileServiceClientContent;
/* Private values -------------------------------------------------------------*/
static T_DjiMopChannelHandle s_testMopChannelNormalHandle;
static T_DjiMopChannelHandle s_testMopChannelNormalOutHandle;
static T_DjiTaskHandle s_testMopChannelNormalSendTask;
static T_DjiTaskHandle s_testMopChannelNormalRecvTask;
static T_DjiSemaHandle s_testMopChannelReadySema;
static bool s_testMopChannelConnected = false;
static T_DjiTaskHandle s_fileServiceMopChannelAcceptTask;
static T_DjiMopChannelHandle s_fileServiceMopChannelHandle;
static T_MopFileServiceClientContent s_fileServiceContent[TEST_MOP_CHANNEL_FILE_SERVICE_CLIENT_MAX_SUPPORT_NUM];
/* Private functions declaration ---------------------------------------------*/
static void *DjiTest_MopChannelSendNormalTask(void *arg);
static void *DjiTest_MopChannelRecvNormalTask(void *arg);
static void *DjiTest_MopChannelFileServiceAcceptTask(void *arg);
static void *DjiTest_MopChannelFileServiceRecvTask(void *arg);
static void *DjiTest_MopChannelFileServiceSendTask(void *arg);
/* Exported functions definition ---------------------------------------------*/
T_DjiReturnCode DjiTest_MopChannelStartService(void)
{
T_DjiReturnCode returnCode;
T_DjiOsalHandler *osalHandler = DjiPlatform_GetOsalHandler();
returnCode = osalHandler->SemaphoreCreate(0, &s_testMopChannelReadySema);
if (returnCode != DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS) {
USER_LOG_ERROR("mop channel create msdk sema error, stat:0x%08llX.", returnCode);
return DJI_ERROR_SYSTEM_MODULE_CODE_UNKNOWN;
}
returnCode = DjiMopChannel_Init();
if (returnCode != DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS) {
USER_LOG_ERROR("mop channel init error, stat:0x%08llX.", returnCode);
return DJI_ERROR_SYSTEM_MODULE_CODE_UNKNOWN;
}
returnCode = osalHandler->TaskCreate("mop_msdk_send_task", DjiTest_MopChannelSendNormalTask,
DJI_MOP_CHANNEL_TASK_STACK_SIZE, NULL, &s_testMopChannelNormalSendTask);
if (returnCode != DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS) {
USER_LOG_ERROR("mop channel msdk send task create error, stat:0x%08llX.", returnCode);
return DJI_ERROR_SYSTEM_MODULE_CODE_UNKNOWN;
}
returnCode = osalHandler->TaskCreate("mop_msdk_recv_task", DjiTest_MopChannelRecvNormalTask,
DJI_MOP_CHANNEL_TASK_STACK_SIZE, NULL, &s_testMopChannelNormalRecvTask);
if (returnCode != DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS) {
USER_LOG_ERROR("mop channel msdk recv task create error, stat:0x%08llX.", returnCode);
return DJI_ERROR_SYSTEM_MODULE_CODE_UNKNOWN;
}
returnCode = osalHandler->TaskCreate("mop_msdk_accept_task", DjiTest_MopChannelFileServiceAcceptTask,
DJI_MOP_CHANNEL_TASK_STACK_SIZE, NULL, &s_fileServiceMopChannelAcceptTask);
if (returnCode != DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS) {
USER_LOG_ERROR("mop channel osdk recv task create error, stat:0x%08llX.", returnCode);
return DJI_ERROR_SYSTEM_MODULE_CODE_UNKNOWN;
}
return DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS;
}
/* Private functions definition-----------------------------------------------*/
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wmissing-noreturn"
#pragma GCC diagnostic ignored "-Wreturn-type"
static void *DjiTest_MopChannelSendNormalTask(void *arg)
{
uint8_t *sendBuf = NULL;
uint32_t realLen = 0;
T_DjiReturnCode returnCode;
uint32_t sendDataCount = 0;
T_DjiOsalHandler *osalHandler = DjiPlatform_GetOsalHandler();
USER_UTIL_UNUSED(arg);
osalHandler->TaskSleepMs(TEST_MOP_CHANNEL_INIT_TIMEMS);
sendBuf = osalHandler->Malloc(TEST_MOP_CHANNEL_NORMAL_TRANSFOR_SEND_BUFFER);
if (sendBuf == NULL) {
USER_LOG_ERROR("malloc send buffer error");
return NULL;
}
REWAIT:
returnCode = osalHandler->SemaphoreWait(s_testMopChannelReadySema);
if (returnCode != DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS) {
USER_LOG_ERROR("mop channel wait sema error, stat:0x%08llX.", returnCode);
return NULL;
}
while (1) {
if (s_testMopChannelConnected == false) {
sendDataCount = 0;
goto REWAIT;
}
sendDataCount++;
memset(sendBuf, sendDataCount, TEST_MOP_CHANNEL_NORMAL_TRANSFOR_SEND_BUFFER);
returnCode = DjiMopChannel_SendData(s_testMopChannelNormalOutHandle, sendBuf,
TEST_MOP_CHANNEL_NORMAL_TRANSFOR_SEND_BUFFER, &realLen);
if (returnCode != DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS) {
USER_LOG_ERROR("mop channel send data to channel error,stat:0x%08llX", returnCode);
} else {
USER_LOG_INFO("mop channel send data to channel length:%d count:%d", realLen, sendDataCount);
}
osalHandler->TaskSleepMs(1000 / TEST_MOP_CHANNEL_NORMAL_TRANSFOR_SEND_TASK_FREQ);
}
}
#pragma GCC diagnostic pop
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wmissing-noreturn"
#pragma GCC diagnostic ignored "-Wreturn-type"
static void *DjiTest_MopChannelRecvNormalTask(void *arg)
{
USER_UTIL_UNUSED(arg);
uint8_t *recvBuf = NULL;
uint32_t realLen;
T_DjiReturnCode returnCode;
uint32_t recvDataCount = 0;
T_DjiOsalHandler *osalHandler = DjiPlatform_GetOsalHandler();
osalHandler->TaskSleepMs(TEST_MOP_CHANNEL_INIT_TIMEMS);
#if TEST_MOP_CHANNEL_NORMAL_TRANSFOR_USING_RELIABLE_TRANS
returnCode = DjiMopChannel_Create(&s_testMopChannelNormalHandle, DJI_MOP_CHANNEL_TRANS_RELIABLE);
if (returnCode != DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS) {
USER_LOG_ERROR("mop channel create send handle error, stat:0x%08llX.", returnCode);
return NULL;
}
#else
returnCode = DjiMopChannel_Create(&s_testMopChannelNormalHandle, DJI_MOP_CHANNEL_TRANS_UNRELIABLE);
if (returnCode != DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS) {
USER_LOG_ERROR("mop channel create send handle error, stat:0x%08llX.", returnCode);
return NULL;
}
#endif
REBIND:
returnCode = DjiMopChannel_Bind(s_testMopChannelNormalHandle, TEST_MOP_CHANNEL_NORMAL_TRANSFOR_CHANNEL_ID);
if (returnCode != DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS) {
USER_LOG_ERROR("mop bind channel error :0x%08llX", returnCode);
osalHandler->TaskSleepMs(TEST_MOP_CHANNEL_RETRY_TIMEMS);
goto REBIND;
}
REACCEPT:
returnCode = DjiMopChannel_Accept(s_testMopChannelNormalHandle, &s_testMopChannelNormalOutHandle);
if (returnCode != DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS) {
USER_LOG_WARN("mop accept channel error :0x%08llX", returnCode);
osalHandler->TaskSleepMs(TEST_MOP_CHANNEL_RETRY_TIMEMS);
goto REACCEPT;
}
USER_LOG_INFO("mop channel is connected");
recvBuf = osalHandler->Malloc(TEST_MOP_CHANNEL_NORMAL_TRANSFOR_RECV_BUFFER);
if (recvBuf == NULL) {
USER_LOG_ERROR("malloc recv buffer error");
return NULL;
}
s_testMopChannelConnected = true;
returnCode = osalHandler->SemaphorePost(s_testMopChannelReadySema);
if (returnCode != DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS) {
USER_LOG_ERROR("mop channel post sema error, stat:0x%08llX.", returnCode);
return NULL;
}
while (1) {
memset(recvBuf, 0, TEST_MOP_CHANNEL_NORMAL_TRANSFOR_RECV_BUFFER);
returnCode = DjiMopChannel_RecvData(s_testMopChannelNormalOutHandle, recvBuf,
TEST_MOP_CHANNEL_NORMAL_TRANSFOR_RECV_BUFFER, &realLen);
if (returnCode != DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS) {
if (returnCode == DJI_ERROR_MOP_CHANNEL_MODULE_CODE_CONNECTION_CLOSE) {
USER_LOG_INFO("mop channel is disconnected");
s_testMopChannelConnected = false;
osalHandler->TaskSleepMs(TEST_MOP_CHANNEL_RETRY_TIMEMS);
DjiMopChannel_Close(s_testMopChannelNormalOutHandle);
DjiMopChannel_Destroy(s_testMopChannelNormalOutHandle);
goto REACCEPT;
}
} else {
USER_LOG_INFO("mop channel recv data from channel length:%d count:%d", realLen, recvDataCount++);
}
}
}
#pragma GCC diagnostic pop
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wmissing-noreturn"
#pragma GCC diagnostic ignored "-Wreturn-type"
static void *DjiTest_MopChannelFileServiceAcceptTask(void *arg)
{
T_DjiReturnCode returnCode;
uint8_t currentClientNum = 0;
T_DjiOsalHandler *osalHandler = DjiPlatform_GetOsalHandler();
USER_UTIL_UNUSED(arg);
USER_LOG_DEBUG("[File-Service] Start the file service.");
returnCode = DjiMopChannel_Create(&s_fileServiceMopChannelHandle, DJI_MOP_CHANNEL_TRANS_RELIABLE);
if (returnCode != DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS) {
USER_LOG_ERROR("[File-Service] mop channel create send handle error, stat:0x%08llX.", returnCode);
return NULL;
}
REBIND:
returnCode = DjiMopChannel_Bind(s_fileServiceMopChannelHandle, TEST_MOP_CHANNEL_FILE_SERVICE_CHANNEL_ID);
if (returnCode != DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS) {
USER_LOG_ERROR("[File-Service] mop bind channel error :0x%08llX", returnCode);
osalHandler->TaskSleepMs(TEST_MOP_CHANNEL_RETRY_TIMEMS);
goto REBIND;
}
while (1) {
REACCEPT:
returnCode = DjiMopChannel_Accept(s_fileServiceMopChannelHandle,
&s_fileServiceContent[currentClientNum].clientHandle);
if (returnCode != DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS) {
USER_LOG_WARN("[File-Service] mop accept channel error :0x%08llX", returnCode);
osalHandler->TaskSleepMs(TEST_MOP_CHANNEL_RETRY_TIMEMS);
goto REACCEPT;
}
USER_LOG_INFO("[File-Service] [Client:%d] mop channel is connected", currentClientNum);
s_fileServiceContent[currentClientNum].index = currentClientNum;
returnCode = osalHandler->TaskCreate("mop_file_service_recv_task",
DjiTest_MopChannelFileServiceRecvTask,
DJI_MOP_CHANNEL_TASK_STACK_SIZE,
&s_fileServiceContent[currentClientNum].index,
&s_fileServiceContent[currentClientNum].clientRecvTask);
if (returnCode != DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS) {
USER_LOG_ERROR("mop channel recv task create error, stat:0x%08llX.", returnCode);
return NULL;
}
returnCode = osalHandler->TaskCreate("mop_file_service_send_task",
DjiTest_MopChannelFileServiceSendTask,
DJI_MOP_CHANNEL_TASK_STACK_SIZE,
&s_fileServiceContent[currentClientNum].index,
&s_fileServiceContent[currentClientNum].clientSendTask);
if (returnCode != DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS) {
USER_LOG_ERROR("mop channel send task create error, stat:0x%08llX.", returnCode);
return NULL;
}
currentClientNum++;
if (currentClientNum > TEST_MOP_CHANNEL_FILE_SERVICE_CLIENT_MAX_SUPPORT_NUM) {
currentClientNum = 0;
}
}
}
#pragma GCC diagnostic pop
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wmissing-noreturn"
#pragma GCC diagnostic ignored "-Wreturn-type"
static void *DjiTest_MopChannelFileServiceSendTask(void *arg)
{
T_DjiReturnCode returnCode;
uint8_t clientNum = *(uint8_t *) arg;
uint32_t sendRealLen = 0;
uint8_t *sendBuf;
MD5_CTX downloadFileMd5Ctx;
FILE *downloadFile = NULL;
uint8_t downloadFileMd5[DJI_MD5_BUFFER_LEN] = {0};
uint64_t downloadFileTotalSize = 0;
uint64_t downloadWriteLen;
uint16_t downloadPackCount = 0;
T_DjiMopChannel_FileInfo downloadFileInfo = {0};
T_DjiMopChannel_FileTransfor transforAck = {0};
T_DjiMopChannel_FileTransfor fileData = {0};
T_DjiMopChannel_FileTransfor fileInfo = {0};
uint32_t downloadStartMs = 0;
uint32_t downloadEndMs = 0;
uint32_t downloadDurationMs;
dji_f32_t downloadRate;
T_DjiOsalHandler *osalHandler = DjiPlatform_GetOsalHandler();
char curFileDirPath[DJI_FILE_PATH_SIZE_MAX];
char tempPath[DJI_FILE_PATH_SIZE_MAX];
sendBuf = osalHandler->Malloc(TEST_MOP_CHANNEL_FILE_SERVICE_SEND_BUFFER);
if (sendBuf == NULL) {
USER_LOG_ERROR("[File-Service] [Client:%d] malloc send buffer error", clientNum);
return NULL;
}
while (1) {
switch (s_fileServiceContent[clientNum].uploadState) {
case MOP_FILE_SERVICE_UPLOAD_REQUEST_START:
transforAck.cmd = DJI_MOP_CHANNEL_FILE_TRANSFOR_CMD_ACK;
transforAck.subcmd = DJI_MOP_CHANNEL_FILE_TRANSFOR_SUBCMD_ACK_OK;
transforAck.seqNum = s_fileServiceContent[clientNum].uploadSeqNum;
transforAck.dataLen = 0;
DjiMopChannel_SendData(s_fileServiceContent[clientNum].clientHandle, (uint8_t * ) & transforAck,
UTIL_OFFSETOF(T_DjiMopChannel_FileTransfor, data),
&sendRealLen);
USER_LOG_DEBUG("[File-Service] [Client:%d] upload request ack", clientNum);
s_fileServiceContent[clientNum].uploadState = MOP_FILE_SERVICE_UPLOAD_IDEL;
break;
case MOP_FILE_SERVICE_UPLOAD_FILE_INFO_SUCCESS:
transforAck.cmd = DJI_MOP_CHANNEL_FILE_TRANSFOR_CMD_ACK;
transforAck.subcmd = DJI_MOP_CHANNEL_FILE_TRANSFOR_SUBCMD_ACK_OK;
transforAck.seqNum = s_fileServiceContent[clientNum].uploadSeqNum;
transforAck.dataLen = 0;
DjiMopChannel_SendData(s_fileServiceContent[clientNum].clientHandle, (uint8_t * ) & transforAck,
UTIL_OFFSETOF(T_DjiMopChannel_FileTransfor, data),
&sendRealLen);
USER_LOG_DEBUG("[File-Service] [Client:%d] upload file info success", clientNum);
s_fileServiceContent[clientNum].uploadState = MOP_FILE_SERVICE_UPLOAD_IDEL;
break;
case MOP_FILE_SERVICE_UPLOAD_FILE_INFO_FAILED:
transforAck.cmd = DJI_MOP_CHANNEL_FILE_TRANSFOR_CMD_ACK;
transforAck.subcmd = DJI_MOP_CHANNEL_FILE_TRANSFOR_SUBCMD_ACK_REJECTED;
transforAck.seqNum = s_fileServiceContent[clientNum].uploadSeqNum;
transforAck.dataLen = 0;
DjiMopChannel_SendData(s_fileServiceContent[clientNum].clientHandle, (uint8_t * ) & transforAck,
UTIL_OFFSETOF(T_DjiMopChannel_FileTransfor, data),
&sendRealLen);
USER_LOG_ERROR("[File-Service] [Client:%d] upload file info failed", clientNum);
s_fileServiceContent[clientNum].uploadState = MOP_FILE_SERVICE_UPLOAD_IDEL;
break;
case MOP_FILE_SERVICE_UPLOAD_FINISHED_SUCCESS:
transforAck.cmd = DJI_MOP_CHANNEL_FILE_TRANSFOR_CMD_RESULT;
transforAck.subcmd = DJI_MOP_CHANNEL_FILE_TRANSFOR_SUBCMD_RESULT_OK;
transforAck.seqNum = s_fileServiceContent[clientNum].uploadSeqNum++;
transforAck.dataLen = 0;
DjiMopChannel_SendData(s_fileServiceContent[clientNum].clientHandle,
(uint8_t * ) & transforAck,
UTIL_OFFSETOF(T_DjiMopChannel_FileTransfor, data),
&sendRealLen);
USER_LOG_DEBUG("[File-Service] [Client:%d] upload finished success", clientNum);
s_fileServiceContent[clientNum].uploadState = MOP_FILE_SERVICE_UPLOAD_IDEL;
break;
case MOP_FILE_SERVICE_UPLOAD_FINISHED_FAILED:
transforAck.cmd = DJI_MOP_CHANNEL_FILE_TRANSFOR_CMD_RESULT;
transforAck.subcmd = DJI_MOP_CHANNEL_FILE_TRANSFOR_SUBCMD_RESULT_FAILED;
transforAck.seqNum = s_fileServiceContent[clientNum].uploadSeqNum++;
transforAck.dataLen = 0;
DjiMopChannel_SendData(s_fileServiceContent[clientNum].clientHandle,
(uint8_t * ) & transforAck,
UTIL_OFFSETOF(T_DjiMopChannel_FileTransfor, data),
&sendRealLen);
USER_LOG_ERROR("[File-Service] [Client:%d] upload finished failed", clientNum);
s_fileServiceContent[clientNum].uploadState = MOP_FILE_SERVICE_UPLOAD_IDEL;
break;
case MOP_FILE_SERVICE_UPLOAD_STOP:
transforAck.cmd = DJI_MOP_CHANNEL_FILE_TRANSFOR_CMD_STOP_ACK;
transforAck.subcmd = DJI_MOP_CHANNEL_FILE_TRANSFOR_SUBCMD_STOP_UPLOAD;
transforAck.seqNum = s_fileServiceContent[clientNum].uploadSeqNum++;
transforAck.dataLen = 0;
DjiMopChannel_SendData(s_fileServiceContent[clientNum].clientHandle,
(uint8_t *) &transforAck,
UTIL_OFFSETOF(T_DjiMopChannel_FileTransfor, data),
&sendRealLen);
s_fileServiceContent[clientNum].uploadState = MOP_FILE_SERVICE_UPLOAD_IDEL;
break;
default:
break;
}
switch (s_fileServiceContent[clientNum].downloadState) {
case MOP_FILE_SERVICE_DOWNLOAD_REQUEST_START:
transforAck.cmd = DJI_MOP_CHANNEL_FILE_TRANSFOR_CMD_ACK;
transforAck.subcmd = DJI_MOP_CHANNEL_FILE_TRANSFOR_SUBCMD_ACK_OK;
transforAck.seqNum = s_fileServiceContent[clientNum].downloadSeqNum;
transforAck.dataLen = 0;
DjiMopChannel_SendData(s_fileServiceContent[clientNum].clientHandle, (uint8_t * ) & transforAck,
UTIL_OFFSETOF(T_DjiMopChannel_FileTransfor, data),
&sendRealLen);
USER_LOG_DEBUG("[File-Service] [Client:%d] download request ack", clientNum);
s_fileServiceContent[clientNum].downloadState = MOP_FILE_SERVICE_DOWNLOAD_IDEL;
break;
case MOP_FILE_SERVICE_DOWNLOAD_STOP:
transforAck.cmd = DJI_MOP_CHANNEL_FILE_TRANSFOR_CMD_STOP_ACK;
transforAck.subcmd = DJI_MOP_CHANNEL_FILE_TRANSFOR_SUBCMD_STOP_DOWNLOAD;
transforAck.seqNum = s_fileServiceContent[clientNum].uploadSeqNum++;
transforAck.dataLen = 0;
DjiMopChannel_SendData(s_fileServiceContent[clientNum].clientHandle,
(uint8_t *) &transforAck,
UTIL_OFFSETOF(T_DjiMopChannel_FileTransfor, data),
&sendRealLen);
s_fileServiceContent[clientNum].downloadState = MOP_FILE_SERVICE_DOWNLOAD_IDEL;
break;
case MOP_FILE_SERVICE_DOWNLOAD_FILE_INFO_SUCCESS:
UtilMd5_Init(&downloadFileMd5Ctx);
osalHandler->GetTimeMs(&downloadStartMs);
if (downloadFile != NULL) {
fclose(downloadFile);
}
returnCode = DjiUserUtil_GetCurrentFileDirPath(__FILE__, DJI_FILE_PATH_SIZE_MAX, curFileDirPath);
if (returnCode != DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS) {
USER_LOG_ERROR("Get file current path error, stat = 0x%08llX", returnCode);
exit(1);
}
snprintf(tempPath, DJI_FILE_PATH_SIZE_MAX, "%smop_channel_test_file/mop_send_test_file.mp4", curFileDirPath);
downloadFile = fopen(tempPath, "rb");
if (downloadFile == NULL) {
USER_LOG_ERROR("[File-Service] [Client:%d] download open file error",
clientNum);
return NULL;
}
downloadFileTotalSize = 0;
while (1) {
returnCode = fseek(downloadFile, downloadFileTotalSize, SEEK_SET);
if (returnCode != 0) {
USER_LOG_ERROR(
"[File-Service] [Client:%d] mop channel fseek file data fail.", clientNum);
}
downloadWriteLen = fread(sendBuf, 1, TEST_MOP_CHANNEL_FILE_SERVICE_SEND_BUFFER,
downloadFile);
if (downloadWriteLen > 0) {
downloadFileTotalSize += downloadWriteLen;
UtilMd5_Update(&downloadFileMd5Ctx, sendBuf, downloadWriteLen);
if (downloadWriteLen < TEST_MOP_CHANNEL_FILE_SERVICE_SEND_BUFFER) {
break;
}
}
}
UtilMd5_Final(&downloadFileMd5Ctx, downloadFileMd5);
fileInfo.cmd = DJI_MOP_CHANNEL_FILE_TRANSFOR_CMD_FILE_INFO;
fileInfo.subcmd = DJI_MOP_CHANNEL_FILE_TRANSFOR_SUBCMD_DOWNLOAD_REQUEST;
fileInfo.seqNum = s_fileServiceContent[clientNum].downloadSeqNum;
fileInfo.dataLen = sizeof(fileInfo) - UTIL_OFFSETOF(T_DjiMopChannel_FileTransfor, data);
fileInfo.data.fileInfo.isExist = true;
downloadFileInfo.fileLength = downloadFileTotalSize;
fileInfo.data.fileInfo.fileLength = downloadFileTotalSize;
strcpy(fileInfo.data.fileInfo.fileName, "test.mp4");
memcpy(&fileInfo.data.fileInfo.md5Buf, &downloadFileMd5, sizeof(downloadFileMd5));
DjiMopChannel_SendData(s_fileServiceContent[clientNum].clientHandle, (uint8_t *) &fileInfo,
sizeof(T_DjiMopChannel_FileTransfor),
&sendRealLen);
USER_LOG_DEBUG(
"[File-Service] [Client:%d] download ack file info exist:%d length:%d name:%s",
clientNum, fileInfo.data.fileInfo.isExist,
fileInfo.data.fileInfo.fileLength, fileInfo.data.fileInfo.fileName);
s_fileServiceContent[clientNum].downloadState = MOP_FILE_SERVICE_DOWNLOAD_DATA_SENDING;
downloadFileTotalSize = 0;
downloadPackCount = 0;
break;
case MOP_FILE_SERVICE_DOWNLOAD_DATA_SENDING:
if (downloadFile == NULL) {
USER_LOG_ERROR("[File-Service] [Client:%d] download file object is NULL.");
break;
}
returnCode = fseek(downloadFile, downloadFileTotalSize, SEEK_SET);
if (returnCode != 0) {
USER_LOG_ERROR("[File-Service] [Client:%d] download fseek file data fail.",
clientNum);
break;
}
downloadWriteLen = fread(&sendBuf[UTIL_OFFSETOF(T_DjiMopChannel_FileTransfor, data)],
1,
(TEST_MOP_CHANNEL_FILE_SERVICE_SEND_BUFFER -
UTIL_OFFSETOF(T_DjiMopChannel_FileTransfor, data)),
downloadFile);
if (downloadWriteLen > 0) {
downloadFileTotalSize += downloadWriteLen;
downloadPackCount++;
fileData.cmd = DJI_MOP_CHANNEL_FILE_TRANSFOR_CMD_FILE_DATA;
fileData.dataLen = downloadWriteLen;
fileData.seqNum++;
if (downloadWriteLen ==
(TEST_MOP_CHANNEL_FILE_SERVICE_SEND_BUFFER -
UTIL_OFFSETOF(T_DjiMopChannel_FileTransfor, data))) {
fileData.subcmd = DJI_MOP_CHANNEL_FILE_TRANSFOR_SUBCMD_FILE_DATA_NORMAL;
} else {
fileData.subcmd = DJI_MOP_CHANNEL_FILE_TRANSFOR_SUBCMD_FILE_DATA_END;
}
memcpy(sendBuf, &fileData, UTIL_OFFSETOF(T_DjiMopChannel_FileTransfor, data));
returnCode = DjiMopChannel_SendData(s_fileServiceContent[clientNum].clientHandle, sendBuf,
(downloadWriteLen +
UTIL_OFFSETOF(T_DjiMopChannel_FileTransfor, data)),
&sendRealLen);
if (returnCode != DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS) {
USER_LOG_ERROR(
"[File-Service] [Client:%d] download send file data error,stat:0x%08llX",
clientNum, returnCode);
if (returnCode == DJI_ERROR_MOP_CHANNEL_MODULE_CODE_CONNECTION_CLOSE) {
break;
}
} else {
USER_LOG_INFO(
"[File-Service] [Client:%d] download send file data length:%d count:%d total:%d percent: %.1f %%",
clientNum, sendRealLen, downloadPackCount, downloadFileTotalSize,
(dji_f32_t)(downloadFileTotalSize) * 100 / (dji_f32_t) downloadFileInfo.fileLength);
}
if (fileData.subcmd == DJI_MOP_CHANNEL_FILE_TRANSFOR_SUBCMD_FILE_DATA_END) {
osalHandler->GetTimeMs(&downloadEndMs);
downloadDurationMs = downloadEndMs - downloadStartMs;
if (downloadDurationMs != 0) {
downloadRate = (dji_f32_t) downloadFileInfo.fileLength * 1000 /
(dji_f32_t) (downloadDurationMs);
USER_LOG_INFO(
"[File-Service] [Client:%d] download finished totalTime:%d, rate:%.2f Byte/s",
clientNum, downloadDurationMs, downloadRate);
}
}
break;
default:
break;
}
}
}
}
#pragma GCC diagnostic pop
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wmissing-noreturn"
#pragma GCC diagnostic ignored "-Wreturn-type"
static void *DjiTest_MopChannelFileServiceRecvTask(void *arg)
{
T_DjiReturnCode returnCode;
uint8_t clientNum = *(uint8_t *) arg;
uint32_t recvRealLen;
uint8_t *recvBuf;
MD5_CTX uploadFileMd5Ctx;
FILE *uploadFile = NULL;
uint8_t uploadFileMd5[DJI_MD5_BUFFER_LEN] = {0};
uint32_t uploadFileTotalSize = 0;
int32_t uploadWriteLen;
T_DjiMopChannel_FileInfo uploadFileInfo = {0};
uint32_t uploadStartMs = 0;
uint32_t uploadEndMs = 0;
dji_f32_t uploadRate;
T_DjiOsalHandler *osalHandler = DjiPlatform_GetOsalHandler();
recvBuf = osalHandler->Malloc(TEST_MOP_CHANNEL_FILE_SERVICE_RECV_BUFFER);
if (recvBuf == NULL) {
USER_LOG_ERROR("[File-Service] [Client:%d] malloc recv buffer error", clientNum);
return NULL;
}
s_fileServiceContent[clientNum].uploadState = MOP_FILE_SERVICE_UPLOAD_IDEL;
s_fileServiceContent[clientNum].downloadState = MOP_FILE_SERVICE_DOWNLOAD_IDEL;
while (1) {
returnCode = DjiMopChannel_RecvData(s_fileServiceContent[clientNum].clientHandle, recvBuf,
TEST_MOP_CHANNEL_FILE_SERVICE_RECV_BUFFER, &recvRealLen);
if (returnCode != DJI_ERROR_SYSTEM_MODULE_CODE_SUCCESS) {
osalHandler->TaskSleepMs(1000);
if (returnCode == DJI_ERROR_MOP_CHANNEL_MODULE_CODE_CONNECTION_CLOSE) {
USER_LOG_INFO("[File-Service] [Client:%d] mop channel is disconnected", clientNum);
osalHandler->TaskDestroy(s_fileServiceContent[clientNum].clientRecvTask);
DjiMopChannel_Close(s_fileServiceContent[clientNum].clientHandle);
DjiMopChannel_Destroy(s_fileServiceContent[clientNum].clientHandle);
}
} else {
if (&recvRealLen > 0) {
T_DjiMopChannel_FileTransfor *fileTransfor = (T_DjiMopChannel_FileTransfor *) recvBuf;
switch (fileTransfor->cmd) {
case DJI_MOP_CHANNEL_FILE_TRANSFOR_CMD_REQUEST:
if (fileTransfor->subcmd == DJI_MOP_CHANNEL_FILE_TRANSFOR_SUBCMD_REQUEST_UPLOAD) {
s_fileServiceContent[clientNum].uploadState = MOP_FILE_SERVICE_UPLOAD_REQUEST_START;
s_fileServiceContent[clientNum].uploadSeqNum = fileTransfor->seqNum;
USER_LOG_DEBUG("[File-Service] [Client:%d] upload request is ok", clientNum);
UtilMd5_Init(&uploadFileMd5Ctx);
uploadFileTotalSize = 0;
osalHandler->GetTimeMs(&uploadStartMs);
} else if (fileTransfor->subcmd == DJI_MOP_CHANNEL_FILE_TRANSFOR_SUBCMD_REQUEST_DOWNLOAD) {
s_fileServiceContent[clientNum].downloadState = MOP_FILE_SERVICE_DOWNLOAD_REQUEST_START;
s_fileServiceContent[clientNum].downloadSeqNum = fileTransfor->seqNum;
USER_LOG_DEBUG("[File-Service] [Client:%d] download request is ok", clientNum);
}
break;
case DJI_MOP_CHANNEL_FILE_TRANSFOR_CMD_FILE_DOWNLOAD_REQ:
USER_LOG_DEBUG("[File-Service] [Client:%d] download request file name:%s", clientNum,
fileTransfor->data.dwonloadReq.fileName);
if (strcmp(fileTransfor->data.dwonloadReq.fileName, "test.mp4") == 0) {
s_fileServiceContent[clientNum].downloadState = MOP_FILE_SERVICE_DOWNLOAD_FILE_INFO_SUCCESS;
s_fileServiceContent[clientNum].downloadSeqNum = fileTransfor->seqNum;
} else {
s_fileServiceContent[clientNum].downloadState = MOP_FILE_SERVICE_DOWNLOAD_FILE_INFO_FAILED;
s_fileServiceContent[clientNum].downloadSeqNum = fileTransfor->seqNum;
}
break;
case DJI_MOP_CHANNEL_FILE_TRANSFOR_CMD_FILE_INFO:
USER_LOG_DEBUG(
"[File-Service] [Client:%d] upload file info length:%d exist:%d name:%s seq:%d", clientNum,
fileTransfor->data.fileInfo.fileLength,
fileTransfor->data.fileInfo.isExist,
fileTransfor->data.fileInfo.fileName, fileTransfor->seqNum);
uploadFileInfo.fileLength = fileTransfor->data.fileInfo.fileLength;
memcpy(uploadFileInfo.md5Buf, fileTransfor->data.fileInfo.md5Buf,
sizeof(uploadFileInfo.md5Buf));
if (uploadFile != NULL) {
fclose(uploadFile);
}
uploadFile = fopen(fileTransfor->data.fileInfo.fileName, "wb");
if (uploadFile == NULL) {
USER_LOG_ERROR("[File-Service] [Client:%d] open file error", clientNum);
return NULL;
}
s_fileServiceContent[clientNum].uploadState = MOP_FILE_SERVICE_UPLOAD_FILE_INFO_SUCCESS;
s_fileServiceContent[clientNum].uploadSeqNum = fileTransfor->seqNum;
break;
case DJI_MOP_CHANNEL_FILE_TRANSFOR_CMD_FILE_DATA:
if (uploadFile == NULL) {
USER_LOG_ERROR("[File-Service] [Client:%d] open file error", clientNum);
return NULL;
}
if (fileTransfor->subcmd == DJI_MOP_CHANNEL_FILE_TRANSFOR_SUBCMD_FILE_DATA_NORMAL) {
s_fileServiceContent[clientNum].uploadState = MOP_FILE_SERVICE_UPLOAD_DATA_SENDING;
s_fileServiceContent[clientNum].uploadSeqNum = fileTransfor->seqNum;
uploadWriteLen = fwrite(&recvBuf[UTIL_OFFSETOF(T_DjiMopChannel_FileTransfor, data)], 1,
fileTransfor->dataLen, uploadFile);
if (uploadWriteLen < 0) {
USER_LOG_ERROR(
"[File-Service] [Client:%d] upload write normal data to file error, stat:%d.",
clientNum,
uploadWriteLen);
} else {
uploadFileTotalSize += uploadWriteLen;
UtilMd5_Update(&uploadFileMd5Ctx,
&recvBuf[UTIL_OFFSETOF(T_DjiMopChannel_FileTransfor, data)],
fileTransfor->dataLen);
if (uploadFileInfo.fileLength != 0) {
USER_LOG_INFO(
"[File-Service] [Client:%d] upload write data to file success, len:%d percent:%.1f %%",
clientNum, uploadWriteLen,
(dji_f32_t)(uploadFileTotalSize * 100) /
(dji_f32_t) uploadFileInfo.fileLength);
}
}
} else if (fileTransfor->subcmd == DJI_MOP_CHANNEL_FILE_TRANSFOR_SUBCMD_FILE_DATA_END) {
s_fileServiceContent[clientNum].uploadState = MOP_FILE_SERVICE_UPLOAD_DATA_SENDING;
s_fileServiceContent[clientNum].uploadSeqNum = fileTransfor->seqNum;
uploadWriteLen = fwrite(&recvBuf[UTIL_OFFSETOF(T_DjiMopChannel_FileTransfor, data)], 1,
fileTransfor->dataLen, uploadFile);
if (uploadWriteLen < 0) {
USER_LOG_ERROR(
"[File-Service] [Client:%d] upload write end data to file error, stat:%d.",
clientNum,
uploadWriteLen);
} else {
uploadFileTotalSize += uploadWriteLen;
UtilMd5_Update(&uploadFileMd5Ctx,
&recvBuf[UTIL_OFFSETOF(T_DjiMopChannel_FileTransfor, data)],
fileTransfor->dataLen);
UtilMd5_Final(&uploadFileMd5Ctx, uploadFileMd5);
osalHandler->GetTimeMs(&uploadEndMs);
if (uploadEndMs - uploadStartMs > 0) {
uploadRate = (dji_f32_t) uploadFileTotalSize * 1000 /
(dji_f32_t) (uploadEndMs - uploadStartMs);
USER_LOG_INFO(
"[File-Service] [Client:%d] upload write data to file success, len:%d percent:%.1f %%",
clientNum, uploadWriteLen,
(dji_f32_t)(uploadFileTotalSize * 100) /
(dji_f32_t) uploadFileInfo.fileLength);
USER_LOG_INFO(
"[File-Service] [Client:%d] upload file finished, totalTime:%d ms rate:%.2f Byte/s",
clientNum, (uploadEndMs - uploadStartMs), uploadRate);
}
fclose(uploadFile);
uploadFile = NULL;
if (uploadFileInfo.fileLength == uploadFileTotalSize) {
if (memcmp(uploadFileInfo.md5Buf, uploadFileMd5, sizeof(uploadFileMd5)) == 0) {
USER_LOG_DEBUG(
"[File-Service] [Client:%d] upload file md5 check success", clientNum);
s_fileServiceContent[clientNum].uploadState = MOP_FILE_SERVICE_UPLOAD_FINISHED_SUCCESS;
s_fileServiceContent[clientNum].uploadSeqNum = fileTransfor->seqNum;
} else {
USER_LOG_ERROR(
"[File-Service] [Client:%d] upload file md5 check failed", clientNum);
s_fileServiceContent[clientNum].uploadState = MOP_FILE_SERVICE_UPLOAD_FINISHED_FAILED;
s_fileServiceContent[clientNum].uploadSeqNum = fileTransfor->seqNum;
}
} else {
USER_LOG_ERROR(
"[File-Service] [Client:%d] upload file check file length error", clientNum);
s_fileServiceContent[clientNum].uploadState = MOP_FILE_SERVICE_UPLOAD_FINISHED_FAILED;
s_fileServiceContent[clientNum].uploadSeqNum = fileTransfor->seqNum;
}
}
}
break;
case DJI_MOP_CHANNEL_FILE_TRANSFOR_CMD_RESULT:
if (fileTransfor->subcmd == DJI_MOP_CHANNEL_FILE_TRANSFOR_SUBCMD_RESULT_OK) {
s_fileServiceContent[clientNum].downloadState = MOP_FILE_SERVICE_DOWNLOAD_FINISHED_SUCCESS;
USER_LOG_DEBUG("[File-Service] [Client:%d] download file result notify success",
clientNum);
} else {
s_fileServiceContent[clientNum].downloadState = MOP_FILE_SERVICE_DOWNLOAD_FINISHED_FAILED;
USER_LOG_ERROR("[File-Service] [Client:%d] download file result notify failed",
clientNum);
}
break;
case DJI_MOP_CHANNEL_FILE_TRANSFOR_CMD_STOP_REQUEST:
if (fileTransfor->subcmd == DJI_MOP_CHANNEL_FILE_TRANSFOR_SUBCMD_STOP_UPLOAD) {
s_fileServiceContent[clientNum].uploadState = MOP_FILE_SERVICE_UPLOAD_STOP;
USER_LOG_DEBUG("[File-Service] [Client:%d] upload file stop", clientNum);
} else if (fileTransfor->subcmd == DJI_MOP_CHANNEL_FILE_TRANSFOR_SUBCMD_STOP_DOWNLOAD) {
s_fileServiceContent[clientNum].downloadState = MOP_FILE_SERVICE_DOWNLOAD_STOP;
USER_LOG_DEBUG("[File-Service] [Client:%d] download file stop", clientNum);
}
break;
default:
USER_LOG_WARN("[File-Service] [Client:%d] recv the unknown command0x%02X",
clientNum, fileTransfor->cmd);
break;
}
}
}
}
}
#pragma GCC diagnostic pop
/****************** (C) COPYRIGHT DJI Innovations *****END OF FILE****/

View File

@ -0,0 +1,119 @@
/**
********************************************************************
* @file test_mop_channel.h
* @brief This is the header file for "test_mop_channel.c", defining the structure and
* (exported) function prototypes.
*
* @copyright (c) 2021 DJI. All rights reserved.
*
* All information contained herein is, and remains, the property of DJI.
* The intellectual and technical concepts contained herein are proprietary
* to DJI and may be covered by U.S. and foreign patents, patents in process,
* and protected by trade secret or copyright law. Dissemination of this
* information, including but not limited to data and other proprietary
* material(s) incorporated within the information, in any form, is strictly
* prohibited without the express written consent of DJI.
*
* If you receive this source code without DJIs authorization, you may not
* further disseminate the information, and you must immediately remove the
* source code and notify DJI of its removal. DJI reserves the right to pursue
* legal actions against you for any loss(es) or damage(s) caused by your
* failure to do so.
*
*********************************************************************
*/
/* Define to prevent recursive inclusion -------------------------------------*/
#ifndef TEST_MOP_CHANNEL_H
#define TEST_MOP_CHANNEL_H
/* Includes ------------------------------------------------------------------*/
#include "dji_typedef.h"
#ifdef __cplusplus
extern "C" {
#endif
/* Exported constants --------------------------------------------------------*/
/* Exported types ------------------------------------------------------------*/
typedef enum {
DJI_MOP_CHANNEL_FILE_TRANSFOR_CMD_REQUEST = 0x50,
DJI_MOP_CHANNEL_FILE_TRANSFOR_CMD_ACK = 0x51,
DJI_MOP_CHANNEL_FILE_TRANSFOR_CMD_RESULT = 0x52,
DJI_MOP_CHANNEL_FILE_TRANSFOR_CMD_FILE_INFO = 0x60,
DJI_MOP_CHANNEL_FILE_TRANSFOR_CMD_FILE_DOWNLOAD_REQ = 0x61,
DJI_MOP_CHANNEL_FILE_TRANSFOR_CMD_FILE_DATA = 0x62,
DJI_MOP_CHANNEL_FILE_TRANSFOR_CMD_STOP_REQUEST = 0x63,
DJI_MOP_CHANNEL_FILE_TRANSFOR_CMD_STOP_ACK = 0x64,
} E_DjiMopChannel_FileTransforCmd;
typedef enum {
DJI_MOP_CHANNEL_FILE_TRANSFOR_SUBCMD_REQUEST_UPLOAD = 0x00,
DJI_MOP_CHANNEL_FILE_TRANSFOR_SUBCMD_REQUEST_DOWNLOAD = 0x01,
} E_DjiMopChannel_FileTransforRequestSubCmd;
typedef enum {
DJI_MOP_CHANNEL_FILE_TRANSFOR_SUBCMD_ACK_OK = 0x00,
DJI_MOP_CHANNEL_FILE_TRANSFOR_SUBCMD_ACK_REJECTED = 0x01,
} E_DjiMopChannel_FileTransforAckSubCmd;
typedef enum {
DJI_MOP_CHANNEL_FILE_TRANSFOR_SUBCMD_RESULT_OK = 0x00,
DJI_MOP_CHANNEL_FILE_TRANSFOR_SUBCMD_RESULT_FAILED = 0x01,
} E_DjiMopChannel_FileTransforResultSubCmd;
typedef enum {
DJI_MOP_CHANNEL_FILE_TRANSFOR_SUBCMD_FILE_INFO_DEFAULT = 0xFF,
} E_DjiMopChannel_FileTransforFileInfoSubCmd;
typedef enum {
DJI_MOP_CHANNEL_FILE_TRANSFOR_SUBCMD_DOWNLOAD_REQUEST = 0xFF,
} E_DjiMopChannel_FileTransforFileDownloadRequestSubCmd;
typedef enum {
DJI_MOP_CHANNEL_FILE_TRANSFOR_SUBCMD_FILE_DATA_NORMAL = 0x00,
DJI_MOP_CHANNEL_FILE_TRANSFOR_SUBCMD_FILE_DATA_END = 0x01,
} E_DjiMopChannel_FileTransforFileDataSubCmd;
typedef enum {
DJI_MOP_CHANNEL_FILE_TRANSFOR_SUBCMD_STOP_UPLOAD = 0x00,
DJI_MOP_CHANNEL_FILE_TRANSFOR_SUBCMD_STOP_DOWNLOAD = 0x01,
} E_DjiMopChannel_FileTransforStopSubCmd;
#pragma pack(1)
typedef struct {
bool isExist;
uint32_t fileLength;
char fileName[32];
uint8_t md5Buf[16];
} T_DjiMopChannel_FileInfo;
typedef struct {
char fileName[32];
} T_DjiMopChannel_DwonloadReq;
typedef struct {
uint8_t cmd;
uint8_t subcmd;
uint16_t seqNum;
uint32_t dataLen;
union dataType {
T_DjiMopChannel_FileInfo fileInfo;
T_DjiMopChannel_DwonloadReq dwonloadReq;
uint8_t fileData[0];
} data;
} T_DjiMopChannel_FileTransfor;
#pragma pack()
/* Exported functions --------------------------------------------------------*/
T_DjiReturnCode DjiTest_MopChannelStartService(void);
#ifdef __cplusplus
}
#endif
#endif // TEST_MOP_CHANNEL_H
/************************ (C) COPYRIGHT DJI Innovations *******END OF FILE******/

Some files were not shown because too many files have changed in this diff Show More