From b8cd52e849309cebd63e5cf82fc5a5c8ba14cec3 Mon Sep 17 00:00:00 2001 From: Fancy code <258828110.@qq.com> Date: Sun, 7 Apr 2024 19:26:15 +0800 Subject: [PATCH 01/10] Improve:ConfigBase module. --- middleware/IpcConfig/CMakeLists.txt | 2 +- middleware/IpcConfig/include/IIpcConfig.h | 105 ++----- middleware/IpcConfig/src/IIpcConfig.cpp | 82 ++++++ middleware/IpcConfig/src/IpcConfig.cpp | 45 ++- middleware/IpcConfig/src/IpcConfig.h | 4 +- test/middleware/IpcConfig/CMakeLists.txt | 4 - utils/CMakeLists.txt | 2 +- utils/Config/CMakeLists.txt | 2 - utils/ConfigBase/CMakeLists.txt | 79 +++++ utils/ConfigBase/build/config_base.cmake | 12 + utils/ConfigBase/include/ConfigBase.h | 52 ++++ utils/ConfigBase/src/ConfigBase.cpp | 178 ++++++++++++ utils/ConfigBase/src/ConfigBaseCode.c | 53 ++++ utils/ConfigBase/src/ConfigBaseCode.h | 29 ++ utils/ConfigBase/src/ConfigBaseImpl.cpp | 339 ++++++++++++++++++++++ utils/ConfigBase/src/ConfigBaseImpl.h | 50 ++++ utils/ConfigBase/src/IConfigBase.cpp | 119 ++++++++ utils/ConfigBase/src/IConfigBase.h | 57 ++++ 18 files changed, 1107 insertions(+), 107 deletions(-) create mode 100644 utils/ConfigBase/CMakeLists.txt create mode 100644 utils/ConfigBase/build/config_base.cmake create mode 100644 utils/ConfigBase/include/ConfigBase.h create mode 100644 utils/ConfigBase/src/ConfigBase.cpp create mode 100644 utils/ConfigBase/src/ConfigBaseCode.c create mode 100644 utils/ConfigBase/src/ConfigBaseCode.h create mode 100644 utils/ConfigBase/src/ConfigBaseImpl.cpp create mode 100644 utils/ConfigBase/src/ConfigBaseImpl.h create mode 100644 utils/ConfigBase/src/IConfigBase.cpp create mode 100644 utils/ConfigBase/src/IConfigBase.h diff --git a/middleware/IpcConfig/CMakeLists.txt b/middleware/IpcConfig/CMakeLists.txt index 9e378f0..9a987b5 100644 --- a/middleware/IpcConfig/CMakeLists.txt +++ b/middleware/IpcConfig/CMakeLists.txt @@ -8,7 +8,7 @@ include_directories( ./include ${UTILS_SOURCE_PATH}/StatusCode/include ${UTILS_SOURCE_PATH}/Log/include - ${UTILS_SOURCE_PATH}/Config/include + ${UTILS_SOURCE_PATH}/ConfigBase/include ) #do not rely on any other library #link_directories( diff --git a/middleware/IpcConfig/include/IIpcConfig.h b/middleware/IpcConfig/include/IIpcConfig.h index 4f72be3..732f1b3 100644 --- a/middleware/IpcConfig/include/IIpcConfig.h +++ b/middleware/IpcConfig/include/IIpcConfig.h @@ -96,89 +96,30 @@ class IIpcConfig public: IIpcConfig() = default; virtual ~IIpcConfig() = default; - virtual const StatusCode ConfigFileSave(void) - { - return CreateStatusCode(STATUS_CODE_OK); - } static std::shared_ptr &GetInstance(std::shared_ptr *impl = nullptr); - virtual const StatusCode Init(void) - { - return CreateStatusCode(STATUS_CODE_OK); - } - virtual const StatusCode UnInit(void) - { - return CreateStatusCode(STATUS_CODE_OK); - } - virtual const int GetInt(const IpcConfigKey &key) - { - return -1; - } - virtual void SetInt(const IpcConfigKey &key, const int &value) - { - } - virtual const short GetShort(const IpcConfigKey &key) - { - return -1; - } - virtual void SetShort(const IpcConfigKey &key, const short &value) - { - } - virtual const long GetLong(const IpcConfigKey &key) - { - return -1; - } - virtual void SetLong(const IpcConfigKey &key, const long &value) - { - } - virtual const long long GetLLong(const IpcConfigKey &key) - { - return -1; - } - virtual void SetLLong(const IpcConfigKey &key, const long long &value) - { - } - virtual const char GetChar(const IpcConfigKey &key) - { - return '\0'; - } - virtual void SetChar(const IpcConfigKey &key, const char &value) - { - } - virtual const float GetFloat(const IpcConfigKey &key) - { - return -1.0; - } - virtual void SetFloat(const IpcConfigKey &key, const float &value) - { - } - virtual const double GetDouble(const IpcConfigKey &key) - { - return -1.0; - } - virtual void SetDouble(const IpcConfigKey &key, const double &value) - { - } - virtual const long double GetLongDouble(const IpcConfigKey &key) - { - return -1.0; - } - virtual void SetLongDouble(const IpcConfigKey &key, const long double &value) - { - } - virtual const bool GetBool(const IpcConfigKey &key) - { - return true; - } - virtual void SetBool(const IpcConfigKey &key, const bool &value) - { - } - virtual const std::string GetString(const IpcConfigKey &key) - { - return "undefine"; - } - virtual void SetString(const IpcConfigKey &key, const std::string string) - { - } + virtual const StatusCode ConfigFileSave(void); + virtual const StatusCode Init(void); + virtual const StatusCode UnInit(void); + virtual const int GetInt(const IpcConfigKey &key); + virtual void SetInt(const IpcConfigKey &key, const int &value); + virtual const short GetShort(const IpcConfigKey &key); + virtual void SetShort(const IpcConfigKey &key, const short &value); + virtual const long GetLong(const IpcConfigKey &key); + virtual void SetLong(const IpcConfigKey &key, const long &value); + virtual const long long GetLLong(const IpcConfigKey &key); + virtual void SetLLong(const IpcConfigKey &key, const long long &value); + virtual const char GetChar(const IpcConfigKey &key); + virtual void SetChar(const IpcConfigKey &key, const char &value); + virtual const float GetFloat(const IpcConfigKey &key); + virtual void SetFloat(const IpcConfigKey &key, const float &value); + virtual const double GetDouble(const IpcConfigKey &key); + virtual void SetDouble(const IpcConfigKey &key, const double &value); + virtual const long double GetLongDouble(const IpcConfigKey &key); + virtual void SetLongDouble(const IpcConfigKey &key, const long double &value); + virtual const bool GetBool(const IpcConfigKey &key); + virtual void SetBool(const IpcConfigKey &key, const bool &value); + virtual const std::string GetString(const IpcConfigKey &key); + virtual void SetString(const IpcConfigKey &key, const std::string string); }; bool CreateIpcConfig(void); #endif \ No newline at end of file diff --git a/middleware/IpcConfig/src/IIpcConfig.cpp b/middleware/IpcConfig/src/IIpcConfig.cpp index 422240a..c83c10c 100644 --- a/middleware/IpcConfig/src/IIpcConfig.cpp +++ b/middleware/IpcConfig/src/IIpcConfig.cpp @@ -27,4 +27,86 @@ std::shared_ptr &IIpcConfig::GetInstance(std::shared_ptr } } return instance; +} +const StatusCode IIpcConfig::ConfigFileSave(void) +{ + return CreateStatusCode(STATUS_CODE_OK); +} +const StatusCode IIpcConfig::Init(void) +{ + return CreateStatusCode(STATUS_CODE_OK); +} +const StatusCode IIpcConfig::UnInit(void) +{ + return CreateStatusCode(STATUS_CODE_OK); +} +const int IIpcConfig::GetInt(const IpcConfigKey &key) +{ + return -1; +} +void IIpcConfig::SetInt(const IpcConfigKey &key, const int &value) +{ +} +const short IIpcConfig::GetShort(const IpcConfigKey &key) +{ + return -1; +} +void IIpcConfig::SetShort(const IpcConfigKey &key, const short &value) +{ +} +const long IIpcConfig::GetLong(const IpcConfigKey &key) +{ + return -1; +} +void IIpcConfig::SetLong(const IpcConfigKey &key, const long &value) +{ +} +const long long IIpcConfig::GetLLong(const IpcConfigKey &key) +{ + return -1; +} +void IIpcConfig::SetLLong(const IpcConfigKey &key, const long long &value) +{ +} +const char IIpcConfig::GetChar(const IpcConfigKey &key) +{ + return '\0'; +} +void IIpcConfig::SetChar(const IpcConfigKey &key, const char &value) +{ +} +const float IIpcConfig::GetFloat(const IpcConfigKey &key) +{ + return -1.0; +} +void IIpcConfig::SetFloat(const IpcConfigKey &key, const float &value) +{ +} +const double IIpcConfig::GetDouble(const IpcConfigKey &key) +{ + return -1.0; +} +void IIpcConfig::SetDouble(const IpcConfigKey &key, const double &value) +{ +} +const long double IIpcConfig::GetLongDouble(const IpcConfigKey &key) +{ + return -1.0; +} +void IIpcConfig::SetLongDouble(const IpcConfigKey &key, const long double &value) +{ +} +const bool IIpcConfig::GetBool(const IpcConfigKey &key) +{ + return true; +} +void IIpcConfig::SetBool(const IpcConfigKey &key, const bool &value) +{ +} +const std::string IIpcConfig::GetString(const IpcConfigKey &key) +{ + return "undefine"; +} +void IIpcConfig::SetString(const IpcConfigKey &key, const std::string string) +{ } \ No newline at end of file diff --git a/middleware/IpcConfig/src/IpcConfig.cpp b/middleware/IpcConfig/src/IpcConfig.cpp index cc45638..b673908 100644 --- a/middleware/IpcConfig/src/IpcConfig.cpp +++ b/middleware/IpcConfig/src/IpcConfig.cpp @@ -143,7 +143,7 @@ void IpcConfig::SetInt(const IpcConfigKey &key, const int &value) iter = mCfgMapInt.find(key); if (iter != mCfgMapInt.end() && CHECK_MAP(iter->second)) { iter->second.begin()->second.get() = value; - const char *name = iter->second.begin()->first.c_str(); // const std::strinbg --> const char * + const char *name = iter->second.begin()->first.c_str(); ConfigSetInt(mCfg, name, iter->second.begin()->second); mCfgChanged = CONFIG_HAS_CHANGED; } @@ -168,7 +168,7 @@ void IpcConfig::SetShort(const IpcConfigKey &key, const short &value) iter = mCfgMapShort.find(key); if (iter != mCfgMapShort.end() && CHECK_MAP(iter->second)) { iter->second.begin()->second.get() = value; - const char *name = iter->second.begin()->first.c_str(); // const std::strinbg --> const char * + const char *name = iter->second.begin()->first.c_str(); ConfigSetShort(mCfg, name, iter->second.begin()->second); mCfgChanged = CONFIG_HAS_CHANGED; } @@ -193,7 +193,7 @@ void IpcConfig::SetLong(const IpcConfigKey &key, const long &value) iter = mCfgMapLong.find(key); if (iter != mCfgMapLong.end() && CHECK_MAP(iter->second)) { iter->second.begin()->second.get() = value; - const char *name = iter->second.begin()->first.c_str(); // const std::strinbg --> const char * + const char *name = iter->second.begin()->first.c_str(); ConfigSetLong(mCfg, name, iter->second.begin()->second); mCfgChanged = CONFIG_HAS_CHANGED; } @@ -218,7 +218,7 @@ void IpcConfig::SetLLong(const IpcConfigKey &key, const long long &value) iter = mCfgMapLLong.find(key); if (iter != mCfgMapLLong.end() && CHECK_MAP(iter->second)) { iter->second.begin()->second.get() = value; - const char *name = iter->second.begin()->first.c_str(); // const std::strinbg --> const char * + const char *name = iter->second.begin()->first.c_str(); ConfigSetLLong(mCfg, name, iter->second.begin()->second); mCfgChanged = CONFIG_HAS_CHANGED; } @@ -243,7 +243,7 @@ void IpcConfig::SetChar(const IpcConfigKey &key, const char &character) iter = mCfgMapChar.find(key); if (iter != mCfgMapChar.end() && CHECK_MAP(iter->second)) { iter->second.begin()->second.get() = character; - const char *name = iter->second.begin()->first.c_str(); // const std::strinbg --> const char * + const char *name = iter->second.begin()->first.c_str(); ConfigSetChar(mCfg, name, iter->second.begin()->second); mCfgChanged = CONFIG_HAS_CHANGED; } @@ -268,7 +268,7 @@ void IpcConfig::SetFloat(const IpcConfigKey &key, const float &value) iter = mCfgMapFloat.find(key); if (iter != mCfgMapFloat.end() && CHECK_MAP(iter->second)) { iter->second.begin()->second.get() = value; - const char *name = iter->second.begin()->first.c_str(); // const std::strinbg --> const char * + const char *name = iter->second.begin()->first.c_str(); ConfigSetFloat(mCfg, name, iter->second.begin()->second); mCfgChanged = CONFIG_HAS_CHANGED; } @@ -293,7 +293,7 @@ void IpcConfig::SetDouble(const IpcConfigKey &key, const double &value) iter = mCfgMapDouble.find(key); if (iter != mCfgMapDouble.end() && CHECK_MAP(iter->second)) { iter->second.begin()->second.get() = value; - const char *name = iter->second.begin()->first.c_str(); // const std::strinbg --> const char * + const char *name = iter->second.begin()->first.c_str(); ConfigSetDouble(mCfg, name, iter->second.begin()->second); mCfgChanged = CONFIG_HAS_CHANGED; } @@ -341,7 +341,7 @@ void IpcConfig::SetBool(const IpcConfigKey &key, const bool &value) iter = mCfgMapBool.find(key); if (iter != mCfgMapBool.end() && CHECK_MAP(iter->second)) { iter->second.begin()->second.get() = value; - const char *name = iter->second.begin()->first.c_str(); // const std::strinbg --> const char * + const char *name = iter->second.begin()->first.c_str(); ConfigSetBool(mCfg, name, iter->second.begin()->second); mCfgChanged = CONFIG_HAS_CHANGED; } @@ -367,7 +367,7 @@ void IpcConfig::SetString(const IpcConfigKey &key, const std::string string) iter = mCfgMapString.find(key); if (iter != mCfgMapString.end() && CHECK_MAP(iter->second)) { strncpy(iter->second.begin()->second, string.c_str(), sizeof(CHAR_STRING)); // const std::strinbg --> char[] - const char *name = iter->second.begin()->first.c_str(); // const std::strinbg --> const char * + const char *name = iter->second.begin()->first.c_str(); ConfigSetString(mCfg, name, iter->second.begin()->second); mCfgChanged = CONFIG_HAS_CHANGED; } @@ -402,7 +402,7 @@ void IpcConfig::ReadAllConfigParameters(void) ConfigSetInt(mCfg, "burst_photo_interval", mAllData.burstPhotoInterval); } - const char *imageSizeString = NULL; + const char *imageSizeString = nullptr; StatusCode imageSizeCode = ConfigGetString(mCfg, "image_size", &(imageSizeString)); if (StatusCodeEqual(imageSizeCode, "CONFIG_CODE_PARAM_NOT_EXIST")) { LogWarning("image_size doesn't exist, will make it as default.\n"); @@ -412,7 +412,12 @@ void IpcConfig::ReadAllConfigParameters(void) ConfigSetString(mCfg, "image_size", mAllData.imageSize); } else { - strncpy(mAllData.imageSize, imageSizeString, sizeof(mAllData.imageSize)); + if (nullptr != imageSizeString) { + strncpy(mAllData.imageSize, imageSizeString, sizeof(mAllData.imageSize)); + } + else { + LogError("image_size get failed.\n"); + } } StatusCode videoSizeCode = ConfigGetInt(mCfg, "video_size", &(mAllData.videoSize)); @@ -474,7 +479,7 @@ void IpcConfig::ReadAllConfigParameters(void) ConfigSetBool(mCfg, "formatting_SD_card", mAllData.formattingSDCard); } - const char *darkModeString = NULL; + const char *darkModeString = nullptr; StatusCode darkModeCode = ConfigGetString(mCfg, "dark_mode", &(darkModeString)); if (StatusCodeEqual(darkModeCode, "CONFIG_CODE_PARAM_NOT_EXIST")) { LogWarning("dark_mode doesn't exist, will make it as default.\n"); @@ -484,10 +489,15 @@ void IpcConfig::ReadAllConfigParameters(void) ConfigSetString(mCfg, "dark_mode", mAllData.darkMode); } else { - strncpy(mAllData.darkMode, darkModeString, sizeof(mAllData.darkMode)); + if (nullptr != darkModeString) { + strncpy(mAllData.darkMode, darkModeString, sizeof(mAllData.darkMode)); + } + else { + LogError("dark_mode get failed.\n"); + } } - const char *workIntervalString = NULL; + const char *workIntervalString = nullptr; StatusCode workIntervalCode = ConfigGetString(mCfg, "work_interval", &(workIntervalString)); if (StatusCodeEqual(workIntervalCode, "CONFIG_CODE_PARAM_NOT_EXIST")) { LogWarning("work_interval doesn't exist, will make it as default.\n"); @@ -497,7 +507,12 @@ void IpcConfig::ReadAllConfigParameters(void) ConfigSetString(mCfg, "work_interval", mAllData.workingInterval); } else { - strncpy(mAllData.workingInterval, workIntervalString, sizeof(mAllData.workingInterval)); + if (nullptr != workIntervalString) { + strncpy(mAllData.workingInterval, workIntervalString, sizeof(mAllData.workingInterval)); + } + else { + LogError("work_interval get failed.\n"); + } } StatusCode shortCode = ConfigGetShort(mCfg, "test_short", &(mAllData.testShort)); diff --git a/middleware/IpcConfig/src/IpcConfig.h b/middleware/IpcConfig/src/IpcConfig.h index 7add2c5..9de09a4 100644 --- a/middleware/IpcConfig/src/IpcConfig.h +++ b/middleware/IpcConfig/src/IpcConfig.h @@ -14,7 +14,7 @@ */ #ifndef IPCCONFIG_H #define IPCCONFIG_H -#include "Config.h" +#include "ConfigBase.h" #include "IIpcConfig.h" #include "StatusCode.h" #include @@ -84,7 +84,7 @@ private: private: bool mCfgChanged; - VConfig *mCfg; + void *mCfg; Config_s mAllData; std::map>> mCfgMapInt; std::map>> mCfgMapShort; diff --git a/test/middleware/IpcConfig/CMakeLists.txt b/test/middleware/IpcConfig/CMakeLists.txt index 5712a80..888acfb 100644 --- a/test/middleware/IpcConfig/CMakeLists.txt +++ b/test/middleware/IpcConfig/CMakeLists.txt @@ -18,10 +18,6 @@ link_directories( ${EXTERNAL_LIBS_OUTPUT_PATH} ) - - - - aux_source_directory(. SRC_FILES_MAIN) aux_source_directory(./src SRC_FILES) diff --git a/utils/CMakeLists.txt b/utils/CMakeLists.txt index 7607882..bd0ba16 100644 --- a/utils/CMakeLists.txt +++ b/utils/CMakeLists.txt @@ -1,6 +1,6 @@ # cmake_minimum_required(VERSION 2.8.0) -add_subdirectory(Config) +add_subdirectory(ConfigBase) add_subdirectory(StatusCode) add_subdirectory(Log) add_subdirectory(SharedData) diff --git a/utils/Config/CMakeLists.txt b/utils/Config/CMakeLists.txt index 0d04847..f6f1e99 100644 --- a/utils/Config/CMakeLists.txt +++ b/utils/Config/CMakeLists.txt @@ -14,8 +14,6 @@ include_directories( # ${EXTERNAL_SOURCE_PATH}/libconfig/libconfig-1.7.3/lib/.libs # ) - - aux_source_directory(./src SRC_FILES) set(TARGET_NAME ConfigBase) diff --git a/utils/ConfigBase/CMakeLists.txt b/utils/ConfigBase/CMakeLists.txt new file mode 100644 index 0000000..8fb7242 --- /dev/null +++ b/utils/ConfigBase/CMakeLists.txt @@ -0,0 +1,79 @@ + +include(${CMAKE_SOURCE_DIR_IPCSDK}/build/global_config.cmake) +include(build/config_base.cmake) +set(EXECUTABLE_OUTPUT_PATH ${EXEC_OUTPUT_PATH}) +set(LIBRARY_OUTPUT_PATH ${LIBS_OUTPUT_PATH}) + +include_directories( + ./src + ./include + ${UTILS_SOURCE_PATH}/StatusCode/include + ${UTILS_SOURCE_PATH}/Log/include + ${EXTERNAL_SOURCE_PATH}/libconfig/libconfig-1.7.3/lib +) +# link_directories( +# ${EXTERNAL_SOURCE_PATH}/libconfig/libconfig-1.7.3/lib/.libs +# ) + +aux_source_directory(./src SRC_FILES) + +set(TARGET_NAME ConfigBase) +add_library(${TARGET_NAME} STATIC ${SRC_FILES}) +target_link_libraries(${TARGET_NAME} StatusCode Log libconfig.a) + +if ("${COMPILE_IMPROVE_SUPPORT}" MATCHES "true") +add_custom_target( + ConfigBase_code_check + COMMAND ${CLANG_TIDY_EXE} + -checks='${CLANG_TIDY_CHECKS}' + --header-filter=.* + --system-headers=false + ${SRC_FILES} + ${CLANG_TIDY_CONFIG} + -p ${PLATFORM_PATH}/cmake-shell + WORKING_DIRECTORY ${UTILS_SOURCE_PATH}/ConfigBase +) +add_custom_command( + TARGET ${TARGET_NAME} + PRE_BUILD + COMMAND make ConfigBase_code_check + WORKING_DIRECTORY ${PLATFORM_PATH}/cmake-shell/ +) +file(GLOB_RECURSE HEADER_FILES *.h) +add_custom_target( + ConfigBase_code_format + COMMAND ${CLANG_FORMAT_EXE} + -style=file + -i ${SRC_FILES} ${HEADER_FILES} + WORKING_DIRECTORY ${UTILS_SOURCE_PATH}/ConfigBase +) +add_custom_command( + TARGET ${TARGET_NAME} + PRE_BUILD + COMMAND make ConfigBase_code_check + COMMAND make ConfigBase_code_format + WORKING_DIRECTORY ${PLATFORM_PATH}/cmake-shell/ +) +endif() + +# build libconfig before make libConfigBase.a +add_custom_command( + # OUTPUT ${EXTERNAL_SOURCE_PATH}/libconfig/libconfig-1.7.3/lib/.libs/libconfig.a + OUTPUT ${EXTERNAL_LIBS_OUTPUT_PATH}/libconfig.a + COMMAND echo "Build libconfig-1.7.3. COMPILE_HOST = ${COMPILE_HOST}" + # COMMAND tar zxvf libconfig-1.7.3.tar.gz + COMMAND sh build_libconfig.sh ${TARGET_PLATFORM} ${COMPILE_HOST} + COMMAND mv ${EXTERNAL_SOURCE_PATH}/libconfig/libconfig-1.7.3/lib/.libs/libconfig.a ${EXTERNAL_LIBS_OUTPUT_PATH}/libconfig.a + WORKING_DIRECTORY ${EXTERNAL_SOURCE_PATH}/libconfig/ +) +add_custom_target( + libconfig.a + # DEPENDS ${EXTERNAL_SOURCE_PATH}/libconfig/libconfig-1.7.3/lib/.libs/libconfig.a + DEPENDS ${EXTERNAL_LIBS_OUTPUT_PATH}/libconfig.a +) + +define_file_name(${TARGET_NAME}) +config_owner(${TARGET_NAME}) + +file(GLOB_RECURSE INSTALL_HEADER_FILES include/*.h) +install(FILES ${INSTALL_HEADER_FILES} DESTINATION include) \ No newline at end of file diff --git a/utils/ConfigBase/build/config_base.cmake b/utils/ConfigBase/build/config_base.cmake new file mode 100644 index 0000000..09434ee --- /dev/null +++ b/utils/ConfigBase/build/config_base.cmake @@ -0,0 +1,12 @@ +function(config_owner target) + get_target_property(source_files "${target}" SOURCES) + foreach(source_file ${source_files}) + get_property(defs SOURCE "${source_file}" + PROPERTY COMPILE_DEFINITIONS) + get_filename_component(file_name "${source_file}" NAME) + list(APPEND defs "CONFIG_OWNER") + set_property( + SOURCE "${source_file}" + PROPERTY COMPILE_DEFINITIONS ${defs}) + endforeach() +endfunction() \ No newline at end of file diff --git a/utils/ConfigBase/include/ConfigBase.h b/utils/ConfigBase/include/ConfigBase.h new file mode 100644 index 0000000..0f2a330 --- /dev/null +++ b/utils/ConfigBase/include/ConfigBase.h @@ -0,0 +1,52 @@ +/* + * Copyright (c) 2023 Fancy Code. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef CONFIG_BASE_H +#define CONFIG_BASE_H +#include "StatusCode.h" +#ifdef __cplusplus +extern "C" { +#endif +enum CONFIG_CODE +{ + CONFIG_CODE_PARAM_NOT_EXIST = STATUS_CODE_END, + CONFIG_CODE_END +}; +// StatusCode ConfigInit(void); +// StatusCode ConfigUnInit(void); +void *OpenConfigFile(const char *fileName); +StatusCode ConfigSaveFile(void *object); +void CloseConfigFile(void *object); +StatusCode ConfigGetInt(void *object, const char *name, int *value); +StatusCode ConfigSetInt(void *object, const char *name, const int value); +StatusCode ConfigGetShort(void *object, const char *name, short *value); +StatusCode ConfigSetShort(void *object, const char *name, const short value); +StatusCode ConfigGetLong(void *object, const char *name, long *value); +StatusCode ConfigSetLong(void *object, const char *name, const long value); +StatusCode ConfigGetLLong(void *object, const char *name, long long *value); +StatusCode ConfigSetLLong(void *object, const char *name, const long long value); +StatusCode ConfigGetChar(void *object, const char *name, char *value); +StatusCode ConfigSetChar(void *object, const char *name, const char value); +StatusCode ConfigGetBool(void *object, const char *name, bool *value); +StatusCode ConfigSetBool(void *object, const char *name, const bool value); +StatusCode ConfigGetFloat(void *object, const char *name, float *value); +StatusCode ConfigSetFloat(void *object, const char *name, const float value); +StatusCode ConfigGetDouble(void *object, const char *name, double *value); +StatusCode ConfigSetDouble(void *object, const char *name, const double value); +StatusCode ConfigGetString(void *object, const char *name, const char **value); +StatusCode ConfigSetString(void *object, const char *name, const char *value); +#ifdef __cplusplus +} +#endif +#endif \ No newline at end of file diff --git a/utils/ConfigBase/src/ConfigBase.cpp b/utils/ConfigBase/src/ConfigBase.cpp new file mode 100644 index 0000000..4a4bfbb --- /dev/null +++ b/utils/ConfigBase/src/ConfigBase.cpp @@ -0,0 +1,178 @@ +/* + * Copyright (c) 2023 Fancy Code. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include "ConfigBase.h" +#include "IConfigBase.h" +#include "ILog.h" +static bool ObjectCheck(void *object) +{ + if (nullptr == object) { + LogError("nullptr object!\n"); + return false; + } + if (*((const char **)(((char *)object) - sizeof(IConfigBase))) != GetConfigBaseModuleName()) { + LogError("Illegal object!\n"); + return false; + } + return true; +} +void *OpenConfigFile(const char *fileName) +{ + std::shared_ptr *configObject = NewConfigBase(fileName); + if (nullptr != configObject) { + (*configObject)->OpenConfigFile(); + } + return configObject; +} +StatusCode ConfigSaveFile(void *object) +{ + if (ObjectCheck(object) == true) { + return (*(std::shared_ptr *)object)->ConfigSaveFile(); + } + return CreateStatusCode(STATUS_CODE_INVALID_PARAMENTER); +} +void CloseConfigFile(void *object) +{ + if (ObjectCheck(object) == true) { + (*(std::shared_ptr *)object)->CloseConfigFile(); + (*(std::shared_ptr *)object).reset(); + free(((char *)object) - sizeof(IConfigBase)); // TODO: bug? + } +} +StatusCode ConfigGetInt(void *object, const char *name, int *value) +{ + if (ObjectCheck(object) == true) { + return (*(std::shared_ptr *)object)->ConfigGetInt(name, value); + } + return CreateStatusCode(STATUS_CODE_INVALID_PARAMENTER); +} +StatusCode ConfigSetInt(void *object, const char *name, const int value) +{ + if (ObjectCheck(object) == true) { + return (*(std::shared_ptr *)object)->ConfigSetInt(name, value); + } + return CreateStatusCode(STATUS_CODE_INVALID_PARAMENTER); +} +StatusCode ConfigGetShort(void *object, const char *name, short *value) +{ + if (ObjectCheck(object) == true) { + return (*(std::shared_ptr *)object)->ConfigGetShort(name, value); + } + return CreateStatusCode(STATUS_CODE_INVALID_PARAMENTER); +} +StatusCode ConfigSetShort(void *object, const char *name, const short value) +{ + if (ObjectCheck(object) == true) { + return (*(std::shared_ptr *)object)->ConfigSetShort(name, value); + } + return CreateStatusCode(STATUS_CODE_INVALID_PARAMENTER); +} +StatusCode ConfigGetLong(void *object, const char *name, long *value) +{ + if (ObjectCheck(object) == true) { + return (*(std::shared_ptr *)object)->ConfigGetLong(name, value); + } + return CreateStatusCode(STATUS_CODE_INVALID_PARAMENTER); +} +StatusCode ConfigSetLong(void *object, const char *name, const long value) +{ + if (ObjectCheck(object) == true) { + return (*(std::shared_ptr *)object)->ConfigSetLong(name, value); + } + return CreateStatusCode(STATUS_CODE_INVALID_PARAMENTER); +} +StatusCode ConfigGetLLong(void *object, const char *name, long long *value) +{ + if (ObjectCheck(object) == true) { + return (*(std::shared_ptr *)object)->ConfigGetLLong(name, value); + } + return CreateStatusCode(STATUS_CODE_INVALID_PARAMENTER); +} +StatusCode ConfigSetLLong(void *object, const char *name, const long long value) +{ + if (ObjectCheck(object) == true) { + return (*(std::shared_ptr *)object)->ConfigSetLLong(name, value); + } + return CreateStatusCode(STATUS_CODE_INVALID_PARAMENTER); +} +StatusCode ConfigGetChar(void *object, const char *name, char *value) +{ + if (ObjectCheck(object) == true) { + return (*(std::shared_ptr *)object)->ConfigGetChar(name, value); + } + return CreateStatusCode(STATUS_CODE_INVALID_PARAMENTER); +} +StatusCode ConfigSetChar(void *object, const char *name, const char value) +{ + if (ObjectCheck(object) == true) { + return (*(std::shared_ptr *)object)->ConfigSetChar(name, value); + } + return CreateStatusCode(STATUS_CODE_INVALID_PARAMENTER); +} +StatusCode ConfigGetBool(void *object, const char *name, bool *value) +{ + if (ObjectCheck(object) == true) { + return (*(std::shared_ptr *)object)->ConfigGetBool(name, value); + } + return CreateStatusCode(STATUS_CODE_INVALID_PARAMENTER); +} +StatusCode ConfigSetBool(void *object, const char *name, const bool value) +{ + if (ObjectCheck(object) == true) { + return (*(std::shared_ptr *)object)->ConfigSetBool(name, value); + } + return CreateStatusCode(STATUS_CODE_INVALID_PARAMENTER); +} +StatusCode ConfigGetFloat(void *object, const char *name, float *value) +{ + if (ObjectCheck(object) == true) { + return (*(std::shared_ptr *)object)->ConfigGetFloat(name, value); + } + return CreateStatusCode(STATUS_CODE_INVALID_PARAMENTER); +} +StatusCode ConfigSetFloat(void *object, const char *name, const float value) +{ + if (ObjectCheck(object) == true) { + return (*(std::shared_ptr *)object)->ConfigSetFloat(name, value); + } + return CreateStatusCode(STATUS_CODE_INVALID_PARAMENTER); +} +StatusCode ConfigGetDouble(void *object, const char *name, double *value) +{ + if (ObjectCheck(object) == true) { + return (*(std::shared_ptr *)object)->ConfigGetDouble(name, value); + } + return CreateStatusCode(STATUS_CODE_INVALID_PARAMENTER); +} +StatusCode ConfigSetDouble(void *object, const char *name, const double value) +{ + if (ObjectCheck(object) == true) { + return (*(std::shared_ptr *)object)->ConfigSetDouble(name, value); + } + return CreateStatusCode(STATUS_CODE_INVALID_PARAMENTER); +} +StatusCode ConfigGetString(void *object, const char *name, const char **value) +{ + if (ObjectCheck(object) == true) { + return (*(std::shared_ptr *)object)->ConfigGetString(name, value); + } + return CreateStatusCode(STATUS_CODE_INVALID_PARAMENTER); +} +StatusCode ConfigSetString(void *object, const char *name, const char *value) +{ + if (ObjectCheck(object) == true) { + return (*(std::shared_ptr *)object)->ConfigSetString(name, value); + } + return CreateStatusCode(STATUS_CODE_INVALID_PARAMENTER); +} \ No newline at end of file diff --git a/utils/ConfigBase/src/ConfigBaseCode.c b/utils/ConfigBase/src/ConfigBaseCode.c new file mode 100644 index 0000000..c6dac5a --- /dev/null +++ b/utils/ConfigBase/src/ConfigBaseCode.c @@ -0,0 +1,53 @@ +/* + * Copyright (c) 2023 Fancy Code. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include "ConfigBaseCode.h" +#include "ILog.h" +#include +static const char *ConfigCodeString[CONFIG_CODE_END - STATUS_CODE_END + 1] = {"CONFIG_CODE_PARAM_NOT_EXIST", + "CONFIG_CODE_END"}; +static const char *PrintStringConfigCode(const StatusCode this) +{ + const int CODE_INDEX = this.mStatusCode - STATUS_CODE_END; + if (STATUS_CODE_END <= this.mStatusCode && this.mStatusCode <= CONFIG_CODE_END) { + LogInfo("Config code = [ %s ]\n", ConfigCodeString[CODE_INDEX]); + return ConfigCodeString[CODE_INDEX]; + } + LogError("Config code undefine.\n"); + return "Config code undefine.\n"; +} +static const bool CodeEqual(const StatusCode code, const char *value) +{ + if (memcmp(value, ConfigCodeString[code.mStatusCode - STATUS_CODE_END], strlen(value)) == 0) { + return true; + } + return false; +} +static StatusCode NewConfigCode(const long int code) +{ + StatusCode result = {PrintStringConfigCode, CodeEqual, code}; + return result; +} +const StatusCode CreateConfigCode(const long int code) +{ + // if (STATUS_CODE_OK <= code && code < STATUS_CODE_END) + // { + // return CreateStatusCode(code); + // } + if (STATUS_CODE_END <= code && code < CONFIG_CODE_END) { + return NewConfigCode(code); + } + LogError("undefined code.\n"); + return CreateStatusCode(STATUS_CODE_END); +} \ No newline at end of file diff --git a/utils/ConfigBase/src/ConfigBaseCode.h b/utils/ConfigBase/src/ConfigBaseCode.h new file mode 100644 index 0000000..4b070a1 --- /dev/null +++ b/utils/ConfigBase/src/ConfigBaseCode.h @@ -0,0 +1,29 @@ +/* + * Copyright (c) 2023 Fancy Code. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef CONFIG_BASE_CODE_H +#define CONFIG_BASE_CODE_H +#include "ConfigBase.h" +#include "StatusCode.h" +#ifdef __cplusplus +extern "C" { +#endif +#ifndef CONFIG_OWNER + #error This is internal file, never include it. +#endif +const StatusCode CreateConfigCode(const long int code); +#ifdef __cplusplus +} +#endif +#endif \ No newline at end of file diff --git a/utils/ConfigBase/src/ConfigBaseImpl.cpp b/utils/ConfigBase/src/ConfigBaseImpl.cpp new file mode 100644 index 0000000..aad8760 --- /dev/null +++ b/utils/ConfigBase/src/ConfigBaseImpl.cpp @@ -0,0 +1,339 @@ +/* + * Copyright (c) 2023 Fancy Code. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include "ConfigBaseImpl.h" +#include "ConfigBaseCode.h" +#include "ILog.h" +#include +#include +#include + +constexpr int INVALID_RESULT = -1; +#define CHECK_SHORT_LIMIT(value) (value > SHRT_MAX ? false : (value < SHRT_MIN ? false : true)) +#define CHECK_LONG_LIMIT(value) (value > LONG_MAX ? false : (value < LONG_MIN ? false : true)) +#define CHECK_CHAR_LIMIT(value) (value > CHAR_MAX ? false : (value < CHAR_MIN ? false : true)) +#define CHECK_FLOAT_LIMIT(value) (fabs(value - ((float)value)) < 0.000001 ? false : true) + +ConfigBaseImpl::ConfigBaseImpl(const std::string &fileName) : mFileName(fileName) +{ +} +void ConfigBaseImpl::OpenConfigFile(void) +{ + config_init(&cfg); + config_set_options(&cfg, + (CONFIG_OPTION_FSYNC | CONFIG_OPTION_SEMICOLON_SEPARATORS | + CONFIG_OPTION_COLON_ASSIGNMENT_FOR_GROUPS | CONFIG_OPTION_OPEN_BRACE_ON_SEPARATE_LINE)); + constexpr int FIEL_EXIST = 0; + if (FIEL_EXIST == access(mFileName.c_str(), F_OK)) { + if (!config_read_file(&cfg, mFileName.c_str())) { + LogError("Read file failed[%s].\n", mFileName.c_str()); + fprintf(stderr, "%s:%d - %s\n", config_error_file(&cfg), config_error_line(&cfg), config_error_text(&cfg)); + return; + } + } + else { + LogInfo("Config file doesn't exist.\n"); + /* Write out the new configuration. */ + if (!config_write_file(&cfg, mFileName.c_str())) { + fprintf(stderr, "Error while writing file.\n"); + return; + } + } +} +void ConfigBaseImpl::CloseConfigFile(void) +{ + config_destroy(&cfg); +} +StatusCode ConfigBaseImpl::ConfigSaveFile(void) +{ + LogInfo("Save file[%s].\n", mFileName.c_str()); + if (!config_write_file(&cfg, mFileName.c_str())) { + LogError("Save config failed.\n"); + return CreateStatusCode(STATUS_CODE_NOT_OK); + } + return CreateStatusCode(STATUS_CODE_OK); +} +StatusCode ConfigBaseImpl::ConfigGetInt(const char *name, int *value) +{ + int result = INVALID_RESULT; + result = config_lookup_int(&cfg, name, value); + if (CONFIG_FALSE == result) { + return CreateConfigCode(CONFIG_CODE_PARAM_NOT_EXIST); + } + return CreateStatusCode(STATUS_CODE_OK); +} +StatusCode ConfigBaseImpl::ConfigSetInt(const char *name, const int value) +{ + config_setting_t *root = nullptr; + config_setting_t *setting = nullptr; + root = config_root_setting(&cfg); + if (nullptr == root) { + LogError("Config function failed.\n"); + return CreateConfigCode(STATUS_CODE_NOT_OK); + } + setting = config_setting_get_member(root, name); + if (nullptr == setting) { + setting = config_setting_add(root, name, CONFIG_TYPE_INT); + } + if (nullptr == setting) { + LogError("Config function failed.\n"); + return CreateConfigCode(STATUS_CODE_NOT_OK); + } + config_setting_set_int(setting, value); + return CreateStatusCode(STATUS_CODE_OK); +} +StatusCode ConfigBaseImpl::ConfigGetShort(const char *name, short *value) +{ + int intValue = 0; + int result = 0; + result = config_lookup_int(&cfg, name, &intValue); + if (CONFIG_FALSE == result || CHECK_SHORT_LIMIT(intValue)) { + return CreateConfigCode(CONFIG_CODE_PARAM_NOT_EXIST); + } + *value = (short)intValue; + return CreateStatusCode(STATUS_CODE_OK); +} +StatusCode ConfigBaseImpl::ConfigSetShort(const char *name, const short value) +{ + config_setting_t *root = nullptr; + config_setting_t *setting = nullptr; + root = config_root_setting(&cfg); + if (nullptr == root) { + LogError("Config function failed.\n"); + return CreateConfigCode(STATUS_CODE_NOT_OK); + } + setting = config_setting_get_member(root, name); + if (nullptr == setting) { + setting = config_setting_add(root, name, CONFIG_TYPE_INT); + } + if (nullptr == setting) { + LogError("Config function failed.\n"); + return CreateConfigCode(STATUS_CODE_NOT_OK); + } + int intValue = value; + config_setting_set_int(setting, intValue); + return CreateStatusCode(STATUS_CODE_OK); +} +StatusCode ConfigBaseImpl::ConfigGetLong(const char *name, long *value) +{ + long long llongValue = 0; + int result = 0; + result = config_lookup_int64(&cfg, name, &llongValue); + if (CONFIG_FALSE == result || CHECK_LONG_LIMIT(llongValue)) { + return CreateConfigCode(CONFIG_CODE_PARAM_NOT_EXIST); + } + *value = (long)llongValue; + return CreateStatusCode(STATUS_CODE_OK); +} +StatusCode ConfigBaseImpl::ConfigSetLong(const char *name, const long value) +{ + config_setting_t *root = nullptr; + config_setting_t *setting = nullptr; + root = config_root_setting(&cfg); + if (nullptr == root) { + LogError("Config function failed.\n"); + return CreateConfigCode(STATUS_CODE_NOT_OK); + } + setting = config_setting_get_member(root, name); + if (nullptr == setting) { + setting = config_setting_add(root, name, CONFIG_TYPE_INT64); + } + if (nullptr == setting) { + LogError("Config function failed.\n"); + return CreateConfigCode(STATUS_CODE_NOT_OK); + } + long long llongValue = value; + config_setting_set_int64(setting, llongValue); + return CreateStatusCode(STATUS_CODE_OK); +} +StatusCode ConfigBaseImpl::ConfigGetLLong(const char *name, long long *value) +{ + int result = 0; + result = config_lookup_int64(&cfg, name, value); + if (CONFIG_FALSE == result) { + return CreateConfigCode(CONFIG_CODE_PARAM_NOT_EXIST); + } + return CreateStatusCode(STATUS_CODE_OK); +} +StatusCode ConfigBaseImpl::ConfigSetLLong(const char *name, const long long value) +{ + config_setting_t *root = nullptr; + config_setting_t *setting = nullptr; + root = config_root_setting(&cfg); + if (nullptr == root) { + LogError("Config function failed.\n"); + return CreateConfigCode(STATUS_CODE_NOT_OK); + } + setting = config_setting_get_member(root, name); + if (nullptr == setting) { + setting = config_setting_add(root, name, CONFIG_TYPE_INT64); + } + if (nullptr == setting) { + LogError("Config function failed.\n"); + return CreateConfigCode(STATUS_CODE_NOT_OK); + } + config_setting_set_int64(setting, value); + return CreateStatusCode(STATUS_CODE_OK); +} +StatusCode ConfigBaseImpl::ConfigGetChar(const char *name, char *value) +{ + int charValue = 0; + int result = 0; + result = config_lookup_int(&cfg, name, &charValue); + if (CONFIG_FALSE == result && CHECK_CHAR_LIMIT(charValue)) { + return CreateConfigCode(CONFIG_CODE_PARAM_NOT_EXIST); + } + *value = (char)charValue; + return CreateStatusCode(STATUS_CODE_OK); +} +StatusCode ConfigBaseImpl::ConfigSetChar(const char *name, const char value) +{ + config_setting_t *root = nullptr; + config_setting_t *setting = nullptr; + root = config_root_setting(&cfg); + if (nullptr == root) { + LogError("Config function failed.\n"); + return CreateConfigCode(STATUS_CODE_NOT_OK); + } + setting = config_setting_get_member(root, name); + if (nullptr == setting) { + setting = config_setting_add(root, name, CONFIG_TYPE_INT); + } + if (nullptr == setting) { + LogError("Config function failed.\n"); + return CreateConfigCode(STATUS_CODE_NOT_OK); + } + int charValue = (int)value; + config_setting_set_int(setting, charValue); + return CreateStatusCode(STATUS_CODE_OK); +} +StatusCode ConfigBaseImpl::ConfigGetBool(const char *name, bool *value) +{ + int result = 0; + result = config_lookup_bool(&cfg, name, (int *)value); + if (CONFIG_FALSE == result) { + return CreateConfigCode(CONFIG_CODE_PARAM_NOT_EXIST); + } + return CreateStatusCode(STATUS_CODE_OK); +} +StatusCode ConfigBaseImpl::ConfigSetBool(const char *name, const bool value) +{ + config_setting_t *root = nullptr; + config_setting_t *setting = nullptr; + root = config_root_setting(&cfg); + if (nullptr == root) { + LogError("Config function failed.\n"); + return CreateConfigCode(STATUS_CODE_NOT_OK); + } + setting = config_setting_get_member(root, name); + if (nullptr == setting) { + setting = config_setting_add(root, name, CONFIG_TYPE_BOOL); + } + if (nullptr == setting) { + LogError("Config function failed.\n"); + return CreateConfigCode(STATUS_CODE_NOT_OK); + } + config_setting_set_bool(setting, (int)value); + return CreateStatusCode(STATUS_CODE_OK); +} +StatusCode ConfigBaseImpl::ConfigGetFloat(const char *name, float *value) +{ + double dValue = 0; + int result = 0; + result = config_lookup_float(&cfg, name, &dValue); + if (CONFIG_FALSE == result || CHECK_FLOAT_LIMIT(dValue)) { + return CreateConfigCode(CONFIG_CODE_PARAM_NOT_EXIST); + } + *value = (float)dValue; + return CreateStatusCode(STATUS_CODE_OK); +} +StatusCode ConfigBaseImpl::ConfigSetFloat(const char *name, const float value) +{ + config_setting_t *root = nullptr; + config_setting_t *setting = nullptr; + root = config_root_setting(&cfg); + if (nullptr == root) { + LogError("Config function failed.\n"); + return CreateConfigCode(STATUS_CODE_NOT_OK); + } + setting = config_setting_get_member(root, name); + if (nullptr == setting) { + setting = config_setting_add(root, name, CONFIG_TYPE_FLOAT); + } + if (nullptr == setting) { + LogError("Config function failed.\n"); + return CreateConfigCode(STATUS_CODE_NOT_OK); + } + double dValue = value; + config_setting_set_float(setting, dValue); + return CreateStatusCode(STATUS_CODE_OK); +} +StatusCode ConfigBaseImpl::ConfigGetDouble(const char *name, double *value) +{ + int result = 0; + result = config_lookup_float(&cfg, name, value); + if (CONFIG_FALSE == result) { + return CreateConfigCode(CONFIG_CODE_PARAM_NOT_EXIST); + } + return CreateStatusCode(STATUS_CODE_OK); +} +StatusCode ConfigBaseImpl::ConfigSetDouble(const char *name, const double value) +{ + config_setting_t *root = nullptr; + config_setting_t *setting = nullptr; + root = config_root_setting(&cfg); + if (nullptr == root) { + LogError("Config function failed.\n"); + return CreateConfigCode(STATUS_CODE_NOT_OK); + } + setting = config_setting_get_member(root, name); + if (nullptr == setting) { + setting = config_setting_add(root, name, CONFIG_TYPE_FLOAT); + } + if (nullptr == setting) { + LogError("Config function failed.\n"); + return CreateConfigCode(STATUS_CODE_NOT_OK); + } + config_setting_set_float(setting, value); + return CreateStatusCode(STATUS_CODE_OK); +} +StatusCode ConfigBaseImpl::ConfigGetString(const char *name, const char **value) +{ + int result = 0; + result = config_lookup_string(&cfg, name, value); + if (CONFIG_FALSE == result) { + return CreateConfigCode(CONFIG_CODE_PARAM_NOT_EXIST); + } + return CreateStatusCode(STATUS_CODE_OK); +} +StatusCode ConfigBaseImpl::ConfigSetString(const char *name, const char *value) +{ + config_setting_t *root = nullptr; + config_setting_t *setting = nullptr; + root = config_root_setting(&cfg); + if (nullptr == root) { + LogError("Config function failed.\n"); + return CreateConfigCode(STATUS_CODE_NOT_OK); + } + setting = config_setting_get_member(root, name); + if (!setting) { + setting = config_setting_add(root, name, CONFIG_TYPE_STRING); + } + if (nullptr == setting) { + LogError("Config function failed.\n"); + return CreateConfigCode(STATUS_CODE_NOT_OK); + } + config_setting_set_string(setting, value); + return CreateStatusCode(STATUS_CODE_OK); +} \ No newline at end of file diff --git a/utils/ConfigBase/src/ConfigBaseImpl.h b/utils/ConfigBase/src/ConfigBaseImpl.h new file mode 100644 index 0000000..de3c9a2 --- /dev/null +++ b/utils/ConfigBase/src/ConfigBaseImpl.h @@ -0,0 +1,50 @@ +/* + * Copyright (c) 2023 Fancy Code. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef CONFIG_BASE_IMPL_H +#define CONFIG_BASE_IMPL_H +#include "IConfigBase.h" +#include +class ConfigBaseImpl : public IConfigBase +{ +public: + ConfigBaseImpl(const std::string &fileName); + virtual ~ConfigBaseImpl() = default; + void OpenConfigFile(void) override; + void CloseConfigFile(void) override; + StatusCode ConfigSaveFile(void) override; + StatusCode ConfigGetInt(const char *name, int *value) override; + StatusCode ConfigSetInt(const char *name, const int value) override; + StatusCode ConfigGetShort(const char *name, short *value) override; + StatusCode ConfigSetShort(const char *name, const short value) override; + StatusCode ConfigGetLong(const char *name, long *value) override; + StatusCode ConfigSetLong(const char *name, const long value) override; + StatusCode ConfigGetLLong(const char *name, long long *value) override; + StatusCode ConfigSetLLong(const char *name, const long long value) override; + StatusCode ConfigGetChar(const char *name, char *value) override; + StatusCode ConfigSetChar(const char *name, const char value) override; + StatusCode ConfigGetBool(const char *name, bool *value) override; + StatusCode ConfigSetBool(const char *name, const bool value) override; + StatusCode ConfigGetFloat(const char *name, float *value) override; + StatusCode ConfigSetFloat(const char *name, const float value) override; + StatusCode ConfigGetDouble(const char *name, double *value) override; + StatusCode ConfigSetDouble(const char *name, const double value) override; + StatusCode ConfigGetString(const char *name, const char **value) override; + StatusCode ConfigSetString(const char *name, const char *value) override; + +private: + const std::string mFileName; + config_t cfg; +}; +#endif \ No newline at end of file diff --git a/utils/ConfigBase/src/IConfigBase.cpp b/utils/ConfigBase/src/IConfigBase.cpp new file mode 100644 index 0000000..51a26bc --- /dev/null +++ b/utils/ConfigBase/src/IConfigBase.cpp @@ -0,0 +1,119 @@ +/* + * Copyright (c) 2023 Fancy Code. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include "IConfigBase.h" +#include "ConfigBaseImpl.h" +#include "ILog.h" +#include +void IConfigBase::OpenConfigFile(void) +{ +} +void IConfigBase::CloseConfigFile(void) +{ +} +StatusCode IConfigBase::ConfigSaveFile(void) +{ + return CreateStatusCode(STATUS_CODE_VIRTUAL_FUNCTION); +} +StatusCode IConfigBase::ConfigGetInt(const char *name, int *value) +{ + return CreateStatusCode(STATUS_CODE_VIRTUAL_FUNCTION); +} +StatusCode IConfigBase::ConfigSetInt(const char *name, const int value) +{ + return CreateStatusCode(STATUS_CODE_VIRTUAL_FUNCTION); +} +StatusCode IConfigBase::ConfigGetShort(const char *name, short *value) +{ + return CreateStatusCode(STATUS_CODE_VIRTUAL_FUNCTION); +} +StatusCode IConfigBase::ConfigSetShort(const char *name, const short value) +{ + return CreateStatusCode(STATUS_CODE_VIRTUAL_FUNCTION); +} +StatusCode IConfigBase::ConfigGetLong(const char *name, long *value) +{ + return CreateStatusCode(STATUS_CODE_VIRTUAL_FUNCTION); +} +StatusCode IConfigBase::ConfigSetLong(const char *name, const long value) +{ + return CreateStatusCode(STATUS_CODE_VIRTUAL_FUNCTION); +} +StatusCode IConfigBase::ConfigGetLLong(const char *name, long long *value) +{ + return CreateStatusCode(STATUS_CODE_VIRTUAL_FUNCTION); +} +StatusCode IConfigBase::ConfigSetLLong(const char *name, const long long value) +{ + return CreateStatusCode(STATUS_CODE_VIRTUAL_FUNCTION); +} +StatusCode IConfigBase::ConfigGetChar(const char *name, char *value) +{ + return CreateStatusCode(STATUS_CODE_VIRTUAL_FUNCTION); +} +StatusCode IConfigBase::ConfigSetChar(const char *name, const char value) +{ + return CreateStatusCode(STATUS_CODE_VIRTUAL_FUNCTION); +} +StatusCode IConfigBase::ConfigGetBool(const char *name, bool *value) +{ + return CreateStatusCode(STATUS_CODE_VIRTUAL_FUNCTION); +} +StatusCode IConfigBase::ConfigSetBool(const char *name, const bool value) +{ + return CreateStatusCode(STATUS_CODE_VIRTUAL_FUNCTION); +} +StatusCode IConfigBase::ConfigGetFloat(const char *name, float *value) +{ + return CreateStatusCode(STATUS_CODE_VIRTUAL_FUNCTION); +} +StatusCode IConfigBase::ConfigSetFloat(const char *name, const float value) +{ + return CreateStatusCode(STATUS_CODE_VIRTUAL_FUNCTION); +} +StatusCode IConfigBase::ConfigGetDouble(const char *name, double *value) +{ + return CreateStatusCode(STATUS_CODE_VIRTUAL_FUNCTION); +} +StatusCode IConfigBase::ConfigSetDouble(const char *name, const double value) +{ + return CreateStatusCode(STATUS_CODE_VIRTUAL_FUNCTION); +} +StatusCode IConfigBase::ConfigGetString(const char *name, const char **value) +{ + return CreateStatusCode(STATUS_CODE_VIRTUAL_FUNCTION); +} +StatusCode IConfigBase::ConfigSetString(const char *name, const char *value) +{ + return CreateStatusCode(STATUS_CODE_VIRTUAL_FUNCTION); +} +static const char *CONFIG_BASE_NAME = "config_base"; +const char *GetConfigBaseModuleName(void) +{ + return CONFIG_BASE_NAME; +} +std::shared_ptr *NewConfigBase(const char *fileName) +{ + LogInfo("Create the uart device object.\n"); + ConfigBase *impl = (ConfigBase *)malloc(sizeof(ConfigBase)); + if (nullptr == impl) { + LogError("NewConfigBase::malloc failed.\n"); + return nullptr; + } + ConfigBase tmp; + memcpy((void *)impl, (void *)&tmp, sizeof(ConfigBase)); + impl->mHeader.mCheckName = CONFIG_BASE_NAME; + impl->mIConfigBase = std::make_shared(fileName); + return (std::shared_ptr *)(((char *)impl) + sizeof(IConfigBaseHeader)); +} \ No newline at end of file diff --git a/utils/ConfigBase/src/IConfigBase.h b/utils/ConfigBase/src/IConfigBase.h new file mode 100644 index 0000000..8a98c18 --- /dev/null +++ b/utils/ConfigBase/src/IConfigBase.h @@ -0,0 +1,57 @@ +/* + * Copyright (c) 2023 Fancy Code. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef I_CONFIG_BASE_H +#define I_CONFIG_BASE_H +#include "StatusCode.h" +#include +class IConfigBase +{ +public: + IConfigBase() = default; + virtual ~IConfigBase() = default; + virtual void OpenConfigFile(void); + virtual void CloseConfigFile(void); + virtual StatusCode ConfigSaveFile(void); + virtual StatusCode ConfigGetInt(const char *name, int *value); + virtual StatusCode ConfigSetInt(const char *name, const int value); + virtual StatusCode ConfigGetShort(const char *name, short *value); + virtual StatusCode ConfigSetShort(const char *name, const short value); + virtual StatusCode ConfigGetLong(const char *name, long *value); + virtual StatusCode ConfigSetLong(const char *name, const long value); + virtual StatusCode ConfigGetLLong(const char *name, long long *value); + virtual StatusCode ConfigSetLLong(const char *name, const long long value); + virtual StatusCode ConfigGetChar(const char *name, char *value); + virtual StatusCode ConfigSetChar(const char *name, const char value); + virtual StatusCode ConfigGetBool(const char *name, bool *value); + virtual StatusCode ConfigSetBool(const char *name, const bool value); + virtual StatusCode ConfigGetFloat(const char *name, float *value); + virtual StatusCode ConfigSetFloat(const char *name, const float value); + virtual StatusCode ConfigGetDouble(const char *name, double *value); + virtual StatusCode ConfigSetDouble(const char *name, const double value); + virtual StatusCode ConfigGetString(const char *name, const char **value); + virtual StatusCode ConfigSetString(const char *name, const char *value); +}; +typedef struct i_config_base_header +{ + const char *mCheckName; +} IConfigBaseHeader; +typedef struct config_base +{ + IConfigBaseHeader mHeader; + std::shared_ptr mIConfigBase; +} ConfigBase; +const char *GetConfigBaseModuleName(void); +std::shared_ptr *NewConfigBase(const char *fileName); +#endif \ No newline at end of file From 0b976c4619e533a4b8c5f25a22b3d3a953b27242 Mon Sep 17 00:00:00 2001 From: xiaojiazhu <258828110.@qq.com> Date: Sun, 7 Apr 2024 08:00:41 -0700 Subject: [PATCH 02/10] Add:TCP server module. --- external/libhv/libhv-1.3.2/CMakeLists.txt | 4 +- test/utils/CMakeLists.txt | 3 +- test/utils/TcpModule/CMakeLists.txt | 68 +++++++++++++++++++++ test/utils/TcpModule/mainTest.cpp | 23 +++++++ test/utils/TcpModule/src/TcpModule_Test.cpp | 31 ++++++++++ test/utils/UartDevice/CMakeLists.txt | 2 - utils/TcpModule/CMakeLists.txt | 4 +- utils/TcpModule/src/TcpClient.cpp | 14 +++++ utils/TcpModule/src/TcpClient.h | 14 +++++ utils/TcpModule/src/TcpModuleImpl.h | 2 +- utils/TcpModule/src/TcpServer.cpp | 14 +++++ utils/TcpModule/src/TcpServer.h | 14 +++++ 12 files changed, 184 insertions(+), 9 deletions(-) create mode 100644 test/utils/TcpModule/CMakeLists.txt create mode 100644 test/utils/TcpModule/mainTest.cpp create mode 100644 test/utils/TcpModule/src/TcpModule_Test.cpp create mode 100644 utils/TcpModule/src/TcpClient.cpp create mode 100644 utils/TcpModule/src/TcpClient.h create mode 100644 utils/TcpModule/src/TcpServer.cpp create mode 100644 utils/TcpModule/src/TcpServer.h diff --git a/external/libhv/libhv-1.3.2/CMakeLists.txt b/external/libhv/libhv-1.3.2/CMakeLists.txt index 4a29432..a79d2eb 100644 --- a/external/libhv/libhv-1.3.2/CMakeLists.txt +++ b/external/libhv/libhv-1.3.2/CMakeLists.txt @@ -99,8 +99,8 @@ set(SRCDIR src) set(LIBDIR lib) set(BINDIR bin) # ================== added by xiao ================== # -set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${LIBS_OUTPUT_PATH}) -set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${LIBS_OUTPUT_PATH}) +set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${EXTERNAL_LIBS_OUTPUT_PATH}) +set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${EXTERNAL_LIBS_OUTPUT_PATH}) # ================== added by xiao ================== # set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/${BINDIR}) message(STATUS "CMAKE_LIBRARY_OUTPUT_DIRECTORY=${CMAKE_LIBRARY_OUTPUT_DIRECTORY}") diff --git a/test/utils/CMakeLists.txt b/test/utils/CMakeLists.txt index d79f2dd..251acc6 100644 --- a/test/utils/CMakeLists.txt +++ b/test/utils/CMakeLists.txt @@ -8,5 +8,4 @@ add_subdirectory(LinuxApiMock) add_subdirectory(McuProtocol) add_subdirectory(FxHttpServer) add_subdirectory(TestManager) - - +add_subdirectory(TcpModule) \ No newline at end of file diff --git a/test/utils/TcpModule/CMakeLists.txt b/test/utils/TcpModule/CMakeLists.txt new file mode 100644 index 0000000..72dce6d --- /dev/null +++ b/test/utils/TcpModule/CMakeLists.txt @@ -0,0 +1,68 @@ +# include(${CMAKE_SOURCE_DIR}/build/independent_source.cmake) +include(${CMAKE_SOURCE_DIR_IPCSDK}/build/global_config.cmake) +set(EXECUTABLE_OUTPUT_PATH ${TEST_OUTPUT_PATH}/bin) + +include_directories( + ./tool/include + ${UTILS_SOURCE_PATH}/StatusCode/include + ${UTILS_SOURCE_PATH}/Log/include + ${UTILS_SOURCE_PATH}/TcpModule/include + ${TEST_SOURCE_PATH}/utils/LinuxApiMock/include + ${EXTERNAL_SOURCE_PATH}/gtest/googletest-release-1.11.0/googletest/include + ${EXTERNAL_SOURCE_PATH}/gtest/googletest-release-1.11.0/googlemock/include +) + +link_directories( + ${LIBS_OUTPUT_PATH} + ${EXTERNAL_LIBS_OUTPUT_PATH} +) + +aux_source_directory(. SRC_FILES) +aux_source_directory(./src SRC_FILES) +if(${TARGET_PLATFORM} MATCHES ${DEFINE_LINUX}) + aux_source_directory(./src_mock SRC_FILES) +endif() + +set(TARGET_NAME TcpModuleTest) +add_executable(${TARGET_NAME} ${SRC_FILES}) +target_link_libraries(${TARGET_NAME} TcpModule gtest gmock pthread Log) +if(${TEST_COVERAGE} MATCHES "true") + target_link_libraries(${TARGET_NAME} gcov) +endif() +if(${TARGET_PLATFORM} MATCHES ${DEFINE_LINUX}) + target_link_libraries(${TARGET_NAME} LinuxApiMock) +endif() +# if ("${COMPILE_IMPROVE_SUPPORT}" MATCHES "true") +add_custom_target( + TcpModuleTest_code_check + COMMAND ${CLANG_TIDY_EXE} + -checks='${CLANG_TIDY_CHECKS}' + --header-filter=.* + --system-headers=false + ${SRC_FILES} + ${CLANG_TIDY_CONFIG} + # --line-filter='[{\"name\":\"${EXTERNAL_SOURCE_PATH}/gtest/googletest-release-1.11.0/googletest/include/getest/gtest.h\"}]' + --line-filter='[{\"name\":\"${EXTERNAL_SOURCE_PATH}/gtest/googletest-release-1.11.0/googletest/include/getest/*.h\"}]' + -p ${PLATFORM_PATH}/cmake-shell + WORKING_DIRECTORY ${TEST_SOURCE_PATH}/utils/TcpModule +) +file(GLOB_RECURSE HEADER_FILES *.h) +add_custom_target( + TcpModuleTest_code_format + COMMAND ${CLANG_FORMAT_EXE} + -style=file + -i ${SRC_FILES} ${HEADER_FILES} + WORKING_DIRECTORY ${TEST_SOURCE_PATH}/utils/TcpModule +) +add_custom_command( + TARGET ${TARGET_NAME} + PRE_BUILD + COMMAND make TcpModuleTest_code_check + COMMAND make TcpModuleTest_code_format + WORKING_DIRECTORY ${PLATFORM_PATH}/cmake-shell/ +) +# endif() + +define_file_name(${TARGET_NAME}) + +# add_subdirectory(tool) \ No newline at end of file diff --git a/test/utils/TcpModule/mainTest.cpp b/test/utils/TcpModule/mainTest.cpp new file mode 100644 index 0000000..475ceee --- /dev/null +++ b/test/utils/TcpModule/mainTest.cpp @@ -0,0 +1,23 @@ +/* + * Copyright (c) 2023 Fancy Code. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include +#include +#include +#include +int main(int argc, char *argv[]) +{ + testing::InitGoogleTest(&argc, argv); + return RUN_ALL_TESTS(); +} \ No newline at end of file diff --git a/test/utils/TcpModule/src/TcpModule_Test.cpp b/test/utils/TcpModule/src/TcpModule_Test.cpp new file mode 100644 index 0000000..a493ca4 --- /dev/null +++ b/test/utils/TcpModule/src/TcpModule_Test.cpp @@ -0,0 +1,31 @@ +/* + * Copyright (c) 2023 Fancy Code. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include "ILog.h" +#include "TcpModule.h" +#include +#include +namespace TcpModuleTest +{ +// ../output_files/test/bin/TcpModuleTest --gtest_filter=TcpModuleTest.UNIT_TcpModule_AUTO_IllegalObject +/** + * TcpModule module api will not crash when object is illegal. + */ +TEST(TcpModuleTest, UNIT_TcpModule_AUTO_IllegalObject) +{ + CreateLogModule(); + ILogInit(LOG_INSTANCE_TYPE_END); + ILogUnInit(); +} +} // namespace TcpModuleTest \ No newline at end of file diff --git a/test/utils/UartDevice/CMakeLists.txt b/test/utils/UartDevice/CMakeLists.txt index 0527aa0..3d63348 100644 --- a/test/utils/UartDevice/CMakeLists.txt +++ b/test/utils/UartDevice/CMakeLists.txt @@ -17,8 +17,6 @@ link_directories( ${EXTERNAL_LIBS_OUTPUT_PATH} ) - - aux_source_directory(. SRC_FILES) aux_source_directory(./src SRC_FILES) if(${TARGET_PLATFORM} MATCHES ${DEFINE_LINUX}) diff --git a/utils/TcpModule/CMakeLists.txt b/utils/TcpModule/CMakeLists.txt index 2b6dd88..732bd8f 100644 --- a/utils/TcpModule/CMakeLists.txt +++ b/utils/TcpModule/CMakeLists.txt @@ -19,7 +19,7 @@ set(TARGET_NAME TcpModule) add_library(${TARGET_NAME} STATIC ${SRC_FILES}) target_link_libraries(${TARGET_NAME} LinuxApi StatusCode Log) -if ("${COMPILE_IMPROVE_SUPPORT}" MATCHES "true") +# if ("${COMPILE_IMPROVE_SUPPORT}" MATCHES "true") add_custom_target( TcpModule_code_check COMMAND ${CLANG_TIDY_EXE} @@ -46,7 +46,7 @@ add_custom_command( COMMAND make TcpModule_code_format WORKING_DIRECTORY ${PLATFORM_PATH}/cmake-shell/ ) -endif() +# endif() define_file_name(${TARGET_NAME}) diff --git a/utils/TcpModule/src/TcpClient.cpp b/utils/TcpModule/src/TcpClient.cpp new file mode 100644 index 0000000..f297c00 --- /dev/null +++ b/utils/TcpModule/src/TcpClient.cpp @@ -0,0 +1,14 @@ +/* + * Copyright (c) 2023 Fancy Code. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ \ No newline at end of file diff --git a/utils/TcpModule/src/TcpClient.h b/utils/TcpModule/src/TcpClient.h new file mode 100644 index 0000000..f297c00 --- /dev/null +++ b/utils/TcpModule/src/TcpClient.h @@ -0,0 +1,14 @@ +/* + * Copyright (c) 2023 Fancy Code. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ \ No newline at end of file diff --git a/utils/TcpModule/src/TcpModuleImpl.h b/utils/TcpModule/src/TcpModuleImpl.h index e143026..138441a 100644 --- a/utils/TcpModule/src/TcpModuleImpl.h +++ b/utils/TcpModule/src/TcpModuleImpl.h @@ -18,7 +18,7 @@ #include "TcpModule.h" #include #define TCP_MODULE_INIT_NAME "UART" -typedef struct uart_device_header +typedef struct tcp_module_header { const char *mCheckName; } TcpModuleHeader; diff --git a/utils/TcpModule/src/TcpServer.cpp b/utils/TcpModule/src/TcpServer.cpp new file mode 100644 index 0000000..f297c00 --- /dev/null +++ b/utils/TcpModule/src/TcpServer.cpp @@ -0,0 +1,14 @@ +/* + * Copyright (c) 2023 Fancy Code. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ \ No newline at end of file diff --git a/utils/TcpModule/src/TcpServer.h b/utils/TcpModule/src/TcpServer.h new file mode 100644 index 0000000..f297c00 --- /dev/null +++ b/utils/TcpModule/src/TcpServer.h @@ -0,0 +1,14 @@ +/* + * Copyright (c) 2023 Fancy Code. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ \ No newline at end of file From 6f6e8eb7cd00c1c3591367954d187497df5bebf3 Mon Sep 17 00:00:00 2001 From: Fancy code <258828110.@qq.com> Date: Wed, 10 Apr 2024 22:08:56 +0800 Subject: [PATCH 03/10] Backup:TcpModule. --- middleware/IpcConfig/include/IIpcConfig.h | 4 +- test/GtestUsing.h | 6 +- test/all/CMakeLists.txt | 4 - test/utils/TcpModule/CMakeLists.txt | 4 +- test/utils/TcpModule/src/TcpModule_Test.cpp | 26 ++ utils/ConfigBase/src/ConfigBase.cpp | 4 +- utils/TcpModule/CMakeLists.txt | 7 +- utils/TcpModule/include/TcpModule.h | 23 +- .../src/{TcpClient.cpp => ITcpClient.cpp} | 20 +- utils/TcpModule/src/ITcpClient.h | 39 +++ .../src/{TcpClient.h => ITcpServer.cpp} | 24 +- utils/TcpModule/src/ITcpServer.h | 50 ++++ utils/TcpModule/src/TcpClientImpl.cpp | 117 +++++++++ utils/TcpModule/src/TcpClientImpl.h | 41 +++ utils/TcpModule/src/TcpModule.cpp | 68 ++++- utils/TcpModule/src/TcpModuleImpl.cpp | 46 ++-- utils/TcpModule/src/TcpModuleImpl.h | 58 ++--- .../src/{TcpServer.h => TcpModuleMakePtr.cpp} | 22 +- utils/TcpModule/src/TcpModuleMakePtr.h | 31 +++ utils/TcpModule/src/TcpServerHandle.cpp | 45 ++++ .../src/{TcpServer.cpp => TcpServerHandle.h} | 20 +- utils/TcpModule/src/TcpServerImpl.cpp | 233 ++++++++++++++++++ utils/TcpModule/src/TcpServerImpl.h | 57 +++++ 23 files changed, 865 insertions(+), 84 deletions(-) rename utils/TcpModule/src/{TcpClient.cpp => ITcpClient.cpp} (62%) create mode 100644 utils/TcpModule/src/ITcpClient.h rename utils/TcpModule/src/{TcpClient.h => ITcpServer.cpp} (55%) create mode 100644 utils/TcpModule/src/ITcpServer.h create mode 100644 utils/TcpModule/src/TcpClientImpl.cpp create mode 100644 utils/TcpModule/src/TcpClientImpl.h rename utils/TcpModule/src/{TcpServer.h => TcpModuleMakePtr.cpp} (50%) create mode 100644 utils/TcpModule/src/TcpModuleMakePtr.h create mode 100644 utils/TcpModule/src/TcpServerHandle.cpp rename utils/TcpModule/src/{TcpServer.cpp => TcpServerHandle.h} (52%) create mode 100644 utils/TcpModule/src/TcpServerImpl.cpp create mode 100644 utils/TcpModule/src/TcpServerImpl.h diff --git a/middleware/IpcConfig/include/IIpcConfig.h b/middleware/IpcConfig/include/IIpcConfig.h index 732f1b3..5a84893 100644 --- a/middleware/IpcConfig/include/IIpcConfig.h +++ b/middleware/IpcConfig/include/IIpcConfig.h @@ -12,8 +12,8 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -#ifndef IIPCCONFIG_H -#define IIPCCONFIG_H +#ifndef I_IPC_CONFIG_H +#define I_IPC_CONFIG_H #include "StatusCode.h" #include #include diff --git a/test/GtestUsing.h b/test/GtestUsing.h index 7378611..e829a58 100644 --- a/test/GtestUsing.h +++ b/test/GtestUsing.h @@ -12,8 +12,8 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -#ifndef GTESTUSING_H -#define GTESTUSING_H +#ifndef GTEST_USING_H +#define GTEST_USING_H #include #include using ::testing::_; @@ -41,11 +41,11 @@ using ::testing::ReturnRefOfCopy; using ::testing::ReturnRoundRobin; using ::testing::SaveArg; using ::testing::SetArgPointee; +using ::testing::SetArgReferee; using ::testing::SetArgumentPointee; using ::testing::Unused; using ::testing::WithArgs; using ::testing::internal::BuiltInDefaultValue; -using ::testing::SetArgReferee; // using ::testing::Mock::VerifyAndClearExpectations; using ::testing::Mock; #endif \ No newline at end of file diff --git a/test/all/CMakeLists.txt b/test/all/CMakeLists.txt index ea317d8..d75f030 100644 --- a/test/all/CMakeLists.txt +++ b/test/all/CMakeLists.txt @@ -18,10 +18,6 @@ link_directories( ${EXTERNAL_LIBS_OUTPUT_PATH} ) - - - - aux_source_directory(. SRC_FILES) aux_source_directory(${TEST_SOURCE_PATH}/middleware/IpcConfig/src SRC_FILES) set(TARGET_NAME AllTest) diff --git a/test/utils/TcpModule/CMakeLists.txt b/test/utils/TcpModule/CMakeLists.txt index 72dce6d..f51ec8c 100644 --- a/test/utils/TcpModule/CMakeLists.txt +++ b/test/utils/TcpModule/CMakeLists.txt @@ -32,7 +32,7 @@ endif() if(${TARGET_PLATFORM} MATCHES ${DEFINE_LINUX}) target_link_libraries(${TARGET_NAME} LinuxApiMock) endif() -# if ("${COMPILE_IMPROVE_SUPPORT}" MATCHES "true") +if ("${COMPILE_IMPROVE_SUPPORT}" MATCHES "true") add_custom_target( TcpModuleTest_code_check COMMAND ${CLANG_TIDY_EXE} @@ -61,7 +61,7 @@ add_custom_command( COMMAND make TcpModuleTest_code_format WORKING_DIRECTORY ${PLATFORM_PATH}/cmake-shell/ ) -# endif() +endif() define_file_name(${TARGET_NAME}) diff --git a/test/utils/TcpModule/src/TcpModule_Test.cpp b/test/utils/TcpModule/src/TcpModule_Test.cpp index a493ca4..39a4ea3 100644 --- a/test/utils/TcpModule/src/TcpModule_Test.cpp +++ b/test/utils/TcpModule/src/TcpModule_Test.cpp @@ -16,6 +16,7 @@ #include "TcpModule.h" #include #include +#include namespace TcpModuleTest { // ../output_files/test/bin/TcpModuleTest --gtest_filter=TcpModuleTest.UNIT_TcpModule_AUTO_IllegalObject @@ -24,8 +25,33 @@ namespace TcpModuleTest */ TEST(TcpModuleTest, UNIT_TcpModule_AUTO_IllegalObject) { + static void *tcpClientAccept = nullptr; + TcpParam param = { + .mIp = "127.0.0.1", + .mPort = 9876, + .mReadFunc = [](const void *p, const size_t len, void *context) -> void { + return; + }, + .mAcceptClientFunc = [](void *object, const char *ip) -> void { + LogInfo("accept client, peer ip: %s", ip); + tcpClientAccept = object; + return; + }, + }; CreateLogModule(); ILogInit(LOG_INSTANCE_TYPE_END); + void *tcpServer = CreateTcpServer(param); + std::this_thread::sleep_for(std::chrono::milliseconds(500)); + void *tcpClient = CreateTcpClient(param); + std::this_thread::sleep_for(std::chrono::milliseconds(100)); + TcpClientWrite(tcpClient, "123456789", strlen("123456789")); + std::this_thread::sleep_for(std::chrono::milliseconds(3000)); + if (nullptr != tcpClient) { + FreeTcpClient(tcpClient); + } + if (nullptr != tcpServer) { + FreeTcpServer(tcpServer); + } ILogUnInit(); } } // namespace TcpModuleTest \ No newline at end of file diff --git a/utils/ConfigBase/src/ConfigBase.cpp b/utils/ConfigBase/src/ConfigBase.cpp index 4a4bfbb..b15ec75 100644 --- a/utils/ConfigBase/src/ConfigBase.cpp +++ b/utils/ConfigBase/src/ConfigBase.cpp @@ -21,7 +21,7 @@ static bool ObjectCheck(void *object) LogError("nullptr object!\n"); return false; } - if (*((const char **)(((char *)object) - sizeof(IConfigBase))) != GetConfigBaseModuleName()) { + if (*((const char **)(((char *)object) - sizeof(IConfigBaseHeader))) != GetConfigBaseModuleName()) { LogError("Illegal object!\n"); return false; } @@ -47,7 +47,7 @@ void CloseConfigFile(void *object) if (ObjectCheck(object) == true) { (*(std::shared_ptr *)object)->CloseConfigFile(); (*(std::shared_ptr *)object).reset(); - free(((char *)object) - sizeof(IConfigBase)); // TODO: bug? + free(((char *)object) - sizeof(IConfigBaseHeader)); // TODO: bug? } } StatusCode ConfigGetInt(void *object, const char *name, int *value) diff --git a/utils/TcpModule/CMakeLists.txt b/utils/TcpModule/CMakeLists.txt index 732bd8f..a3d94d2 100644 --- a/utils/TcpModule/CMakeLists.txt +++ b/utils/TcpModule/CMakeLists.txt @@ -8,6 +8,7 @@ include_directories( ${UTILS_SOURCE_PATH}/LinuxApi/include ${UTILS_SOURCE_PATH}/StatusCode/include ${UTILS_SOURCE_PATH}/Log/include + ${EXTERNAL_SOURCE_PATH}/libhv/libhv-1.3.2/include/hv ) # link_directories( # ${EXTERNAL_SOURCE_PATH}/libconfig/libconfig-1.7.3/lib/.libs @@ -17,9 +18,9 @@ aux_source_directory(./src SRC_FILES) set(TARGET_NAME TcpModule) add_library(${TARGET_NAME} STATIC ${SRC_FILES}) -target_link_libraries(${TARGET_NAME} LinuxApi StatusCode Log) +target_link_libraries(${TARGET_NAME} LinuxApi hv_static StatusCode Log) -# if ("${COMPILE_IMPROVE_SUPPORT}" MATCHES "true") +if ("${COMPILE_IMPROVE_SUPPORT}" MATCHES "true") add_custom_target( TcpModule_code_check COMMAND ${CLANG_TIDY_EXE} @@ -46,7 +47,7 @@ add_custom_command( COMMAND make TcpModule_code_format WORKING_DIRECTORY ${PLATFORM_PATH}/cmake-shell/ ) -# endif() +endif() define_file_name(${TARGET_NAME}) diff --git a/utils/TcpModule/include/TcpModule.h b/utils/TcpModule/include/TcpModule.h index e3d9d09..2044b24 100644 --- a/utils/TcpModule/include/TcpModule.h +++ b/utils/TcpModule/include/TcpModule.h @@ -14,22 +14,27 @@ */ #ifndef TCP_MODULE_H #define TCP_MODULE_H +#include +#include #ifdef __cplusplus extern "C" { #endif -typedef void (*TcpReadFunction)(void *, const int, void *); +typedef void (*TcpReadFunction)(const void *, const size_t, void *); +typedef void (*TcpAcceptClientFunction)(void *, const char *); typedef struct tcp_parm { const char *mIp; const int mPort; - const TcpReadFunction mReadFunc; -} TcpPram; -void *CreateTcpServer(const TcpPram param); -void FreeTcpServer(void *pointer); -int TcpServerWrite(void *object, void *buf, const int bufLenght); -void *CreateTcpClient(const TcpPram param); -void FreeTcpClient(void *pointer); -int TcpClientWrite(void *object, void *buf, const int bufLenght); + TcpReadFunction mReadFunc; // TODO: delete this memeber + TcpAcceptClientFunction mAcceptClientFunc; +} TcpParam; +void *CreateTcpServer(const TcpParam param); +void FreeTcpServer(void *object); +int AcceptClientSetReadFunc(void *object, TcpReadFunction readFunc); +int AcceptClientWrite(void *object, void *buf, const size_t bufLenght); +void *CreateTcpClient(const TcpParam param); +void FreeTcpClient(void *object); +ssize_t TcpClientWrite(void *object, const void *buf, const size_t bufLenght); #ifdef __cplusplus } #endif diff --git a/utils/TcpModule/src/TcpClient.cpp b/utils/TcpModule/src/ITcpClient.cpp similarity index 62% rename from utils/TcpModule/src/TcpClient.cpp rename to utils/TcpModule/src/ITcpClient.cpp index f297c00..0e0ca32 100644 --- a/utils/TcpModule/src/TcpClient.cpp +++ b/utils/TcpModule/src/ITcpClient.cpp @@ -11,4 +11,22 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - */ \ No newline at end of file + */ +#include "ITcpClient.h" +#include "ILog.h" +#include +void ITcpClient::Init(void) +{ +} +void ITcpClient::UnInit(void) +{ +} +ssize_t ITcpClient::Write(const void *buf, const size_t bufLenght) +{ + return WRITE_ERROR; +} +static const char *TCP_CLIENT_NAME = "tcp_client"; +const char *GetTcpClientModuleName(void) +{ + return TCP_CLIENT_NAME; +} \ No newline at end of file diff --git a/utils/TcpModule/src/ITcpClient.h b/utils/TcpModule/src/ITcpClient.h new file mode 100644 index 0000000..992174b --- /dev/null +++ b/utils/TcpModule/src/ITcpClient.h @@ -0,0 +1,39 @@ +/* + * Copyright (c) 2023 Fancy Code. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef I_TCP_CLIENT_H +#define I_TCP_CLIENT_H +#include "StatusCode.h" +#include +constexpr int WRITE_ERROR = -1; +class ITcpClient +{ +public: + ITcpClient() = default; + virtual ~ITcpClient() = default; + virtual void Init(void); + virtual void UnInit(void); + virtual ssize_t Write(const void *buf, const size_t bufLenght); +}; +typedef struct i_tcp_client_header +{ + const char *mCheckName; +} ITcpClientHeader; +typedef struct tcp_client +{ + ITcpClientHeader mHeader; + std::shared_ptr mTcpClient; +} TcpClient; +const char *GetTcpClientModuleName(void); +#endif \ No newline at end of file diff --git a/utils/TcpModule/src/TcpClient.h b/utils/TcpModule/src/ITcpServer.cpp similarity index 55% rename from utils/TcpModule/src/TcpClient.h rename to utils/TcpModule/src/ITcpServer.cpp index f297c00..4c8c0e2 100644 --- a/utils/TcpModule/src/TcpClient.h +++ b/utils/TcpModule/src/ITcpServer.cpp @@ -11,4 +11,26 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - */ \ No newline at end of file + */ +#include "ITcpServer.h" +#include "ILog.h" +#include +void ITcpClientAccept::Readed(const void *data, size_t length) +{ +} +void ITcpServer::Init(void) +{ +} +void ITcpServer::UnInit(void) +{ +} +static const char *TCP_SERVER_NAME = "tcp_server"; +static const char *TCP_CLIENT_ACCEPT_NAME = "tcp_client_accept"; +const char *GetTcpServerModuleName(void) +{ + return TCP_SERVER_NAME; +} +const char *GetTcpClientAcceptName(void) +{ + return TCP_CLIENT_ACCEPT_NAME; +} \ No newline at end of file diff --git a/utils/TcpModule/src/ITcpServer.h b/utils/TcpModule/src/ITcpServer.h new file mode 100644 index 0000000..34a4cc7 --- /dev/null +++ b/utils/TcpModule/src/ITcpServer.h @@ -0,0 +1,50 @@ +/* + * Copyright (c) 2023 Fancy Code. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef I_TCP_SERVER_H +#define I_TCP_SERVER_H +#include "StatusCode.h" +#include +class ITcpClientAccept +{ +public: + ITcpClientAccept() = default; + virtual ~ITcpClientAccept() = default; + virtual void Readed(const void *data, size_t length); +}; +class ITcpServer +{ +public: + ITcpServer() = default; + virtual ~ITcpServer() = default; + virtual void Init(void); + virtual void UnInit(void); +}; +typedef struct i_tcp_server_header +{ + const char *mCheckName; +} ITcpServerHeader; +typedef struct tcp_server +{ + ITcpServerHeader mHeader; + std::shared_ptr mTcpServer; +} TcpServer; +typedef struct tcp_client_accept +{ + ITcpServerHeader mHeader; + std::shared_ptr mTcpClientAccept; +} TcpClientAccept; +const char *GetTcpServerModuleName(void); +const char *GetTcpClientAcceptName(void); +#endif \ No newline at end of file diff --git a/utils/TcpModule/src/TcpClientImpl.cpp b/utils/TcpModule/src/TcpClientImpl.cpp new file mode 100644 index 0000000..532ad74 --- /dev/null +++ b/utils/TcpModule/src/TcpClientImpl.cpp @@ -0,0 +1,117 @@ +/* + * Copyright (c) 2023 Fancy Code. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include "TcpClientImpl.h" +#include "ILog.h" +#include +TcpClientImpl::TcpClientImpl(const TcpParam param) : mParam(param) +{ +} +static void on_message(hio_t *io, void *buf, int len) +{ + LogInfo("onmessage: %.*s\n", len, (char *)buf); + TcpClientImpl *cli = (TcpClientImpl *)hevent_userdata(io); + // ... +} +static void on_connect(hio_t *io) +{ + LogInfo("onconnect: connfd=%d\n", hio_fd(io)); + TcpClientImpl *cli = (TcpClientImpl *)hevent_userdata(io); + // cli->connected = 1; + + // hio_write(io, "hello\r\n", 7); + + hio_setcb_read(io, on_message); + hio_read(io); +} +static void on_close(hio_t *io) +{ + LogInfo("onclose: connfd=%d error=%d\n", hio_fd(io), hio_error(io)); + TcpClientImpl *cli = (TcpClientImpl *)hevent_userdata(io); + // cli->connected = 0; + // reconnect + // if (cli->reconn_setting && reconn_setting_can_retry(cli->reconn_setting)) { + // uint32_t delay = reconn_setting_calc_delay(cli->reconn_setting); + // LogInfo("reconnect cnt=%d, delay=%d ...\n", cli->reconn_setting->cur_retry_cnt, + // cli->reconn_setting->cur_delay); cli->reconn_timer = htimer_add(cli->mLoop, reconnect_timer_cb, delay, 1); + // hevent_set_userdata(cli->reconn_timer, cli); + // } +} +void TcpClientImpl::Init(void) +{ + constexpr int NO_FALGS = 0; + mLoop = hloop_new(NO_FALGS); + if (nullptr == mLoop) { + LogError("TcpClientImpl::Init hloop_new failed.\n"); + return; + } + hio_t *io = hio_create_socket(mLoop, mParam.mIp, mParam.mPort, HIO_TYPE_TCP, HIO_CLIENT_SIDE); + if (nullptr == io) { + LogError("TcpClientImpl::Init hio_create_socket failed.\n"); + return; + } + hevent_set_userdata(io, this); + hio_setcb_connect(io, on_connect); + hio_setcb_close(io, on_close); + hio_connect(io); + mIo = io; + std::shared_ptr impl = std::dynamic_pointer_cast(shared_from_this()); + auto recvThread = [](std::shared_ptr tcpClient) { + tcpClient->Loop(); + }; + mTcpClientThread = std::thread(recvThread, impl); +} +void TcpClientImpl::UnInit(void) +{ + if (nullptr != mLoop) { + LogInfo("Stop loop.\n"); + hloop_stop(mLoop); + } + if (mTcpClientThread.joinable()) { + mTcpClientThread.join(); + } + hloop_free(&mLoop); + mLoop = nullptr; + mIo = nullptr; +} +ssize_t TcpClientImpl::Write(const void *buf, const size_t bufLenght) +{ + if (nullptr == mIo) { + LogError("mIo is nullptr.\n"); + return WRITE_ERROR; + } + return hio_write(mIo, buf, bufLenght); +} +void TcpClientImpl::Loop(void) +{ + if (nullptr == mLoop) { + LogError("mLoop is null\n"); + return; + } + hloop_run(mLoop); +} +std::shared_ptr *NewTcpClient(const TcpParam param) +{ + LogInfo("Create tcp server object.\n"); + TcpClient *impl = (TcpClient *)malloc(sizeof(TcpClient)); + if (nullptr == impl) { + LogError("NewTcpServer::malloc failed.\n"); + return nullptr; + } + TcpClient tmp; + memcpy((void *)impl, (void *)&tmp, sizeof(TcpClient)); + impl->mHeader.mCheckName = GetTcpClientModuleName(); + impl->mTcpClient = std::make_shared(param); + return (std::shared_ptr *)(((char *)impl) + sizeof(ITcpClientHeader)); +} \ No newline at end of file diff --git a/utils/TcpModule/src/TcpClientImpl.h b/utils/TcpModule/src/TcpClientImpl.h new file mode 100644 index 0000000..9404a89 --- /dev/null +++ b/utils/TcpModule/src/TcpClientImpl.h @@ -0,0 +1,41 @@ +/* + * Copyright (c) 2023 Fancy Code. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef TCP_CLIENT_IMPL_H +#define TCP_CLIENT_IMPL_H +#include "ITcpClient.h" +#include "TcpModule.h" +#include "hloop.h" +#include "hsocket.h" +#include "hssl.h" +#include +#include +class TcpClientImpl : public ITcpClient, public std::enable_shared_from_this +{ +public: + TcpClientImpl(const TcpParam param); + virtual ~TcpClientImpl() = default; + void Init(void) override; + void UnInit(void) override; + ssize_t Write(const void *buf, const size_t bufLenght) override; + void Loop(void); + +private: + hloop_t* mLoop; + hio_t *mIo; + const TcpParam mParam; + std::thread mTcpClientThread; +}; +std::shared_ptr *NewTcpClient(const TcpParam param); +#endif \ No newline at end of file diff --git a/utils/TcpModule/src/TcpModule.cpp b/utils/TcpModule/src/TcpModule.cpp index 544800d..939c2a4 100644 --- a/utils/TcpModule/src/TcpModule.cpp +++ b/utils/TcpModule/src/TcpModule.cpp @@ -13,9 +13,71 @@ * limitations under the License. */ #include "TcpModule.h" +#include "ILog.h" +#include "ITcpServer.h" +#include "TcpClientImpl.h" #include "TcpModuleImpl.h" -void *CreateTcpServer(const TcpPram param) +#include "TcpModuleMakePtr.h" +static bool TcpServerObjectCheck(void *object) { - // - return NewTcpServer(param); + if (nullptr == object) { + LogError("nullptr object!\n"); + return false; + } + if (*((const char **)(((char *)object) - sizeof(ITcpServerHeader))) != GetTcpServerModuleName()) { + LogError("Illegal object!\n"); + return false; + } + return true; +} +static bool TcpClientObjectCheck(void *object) +{ + if (nullptr == object) { + LogError("nullptr object!\n"); + return false; + } + if (*((const char **)(((char *)object) - sizeof(ITcpClientHeader))) != GetTcpClientModuleName()) { + LogError("Illegal object!\n"); + return false; + } + return true; +} +void *CreateTcpServer(const TcpParam param) +{ + std::shared_ptr *server = TcpModuleMakePtr::GetInstance()->CreateTcpServer(param); + if (nullptr != *server) { + (*server)->Init(); + } + return server; +} +void FreeTcpServer(void *object) +{ + if (TcpServerObjectCheck(object) == true) { + (*(std::shared_ptr *)object)->UnInit(); + (*(std::shared_ptr *)object).reset(); + free(((char *)object) - sizeof(ITcpServerHeader)); // TODO: bug? + } +} +void *CreateTcpClient(const TcpParam param) +{ + std::shared_ptr *client = TcpModuleMakePtr::GetInstance()->CreateTcpClient(param); + if (nullptr != *client) { + (*client)->Init(); + } + return client; +} +void FreeTcpClient(void *object) +{ + if (TcpClientObjectCheck(object) == true) { + (*(std::shared_ptr *)object)->UnInit(); + (*(std::shared_ptr *)object).reset(); + free(((char *)object) - sizeof(ITcpClientHeader)); // TODO: bug? + } +} +ssize_t TcpClientWrite(void *object, const void *buf, const size_t bufLenght) +{ + if (TcpClientObjectCheck(object) == true) { + return (*(std::shared_ptr *)object)->Write(buf, bufLenght); + } + return -1; } \ No newline at end of file diff --git a/utils/TcpModule/src/TcpModuleImpl.cpp b/utils/TcpModule/src/TcpModuleImpl.cpp index 8d96ffe..85e5619 100644 --- a/utils/TcpModule/src/TcpModuleImpl.cpp +++ b/utils/TcpModule/src/TcpModuleImpl.cpp @@ -15,26 +15,26 @@ #include "TcpModuleImpl.h" #include "ILog.h" #include -static const char *TCP_MODULE_NAME = "tcp_module"; -const char *GetTcpModuleName(void) -{ - return TCP_MODULE_NAME; -} -void *NewTcpModuleImpl(const TcpPram &tcpParam) -{ - if (nullptr == tcpParam.mIp) { - LogError("Parament error, nullptr == tcpParam.mIp\n"); - return nullptr; - } - LogInfo("Create the tcp module object.\n"); - TcpServer *impl = (TcpServer *)malloc(sizeof(TcpServer)); - TcpServer tmp; - memcpy((void *)impl, (void *)&tmp, sizeof(TcpServer)); - impl->mHeader.mCheckName = TCP_MODULE_NAME; - impl->mTcpImpl = std::make_shared(tcpParam); - return (void *)(((char *)impl) + sizeof(TcpModuleHeader)); -} -void *NewTcpServer(const TcpPram &tcpParam) -{ - return nullptr; -} \ No newline at end of file +// static const char *TCP_MODULE_NAME = "tcp_module"; +// const char *GetTcpModuleName(void) +// { +// return TCP_MODULE_NAME; +// } +// void *NewTcpModuleImpl(const TcpParam &tcpParam) +// { +// if (nullptr == tcpParam.mIp) { +// LogError("Parament error, nullptr == tcpParam.mIp\n"); +// return nullptr; +// } +// LogInfo("Create the tcp module object.\n"); +// TcpServer *impl = (TcpServer *)malloc(sizeof(TcpServer)); +// TcpServer tmp; +// memcpy((void *)impl, (void *)&tmp, sizeof(TcpServer)); +// impl->mHeader.mCheckName = TCP_MODULE_NAME; +// impl->mTcpImpl = std::make_shared(tcpParam); +// return (void *)(((char *)impl) + sizeof(TcpModuleHeader)); +// } +// void *NewTcpServer(const TcpParam &tcpParam) +// { +// return nullptr; +// } \ No newline at end of file diff --git a/utils/TcpModule/src/TcpModuleImpl.h b/utils/TcpModule/src/TcpModuleImpl.h index 138441a..6b58fa6 100644 --- a/utils/TcpModule/src/TcpModuleImpl.h +++ b/utils/TcpModule/src/TcpModuleImpl.h @@ -17,36 +17,36 @@ #include "StatusCode.h" #include "TcpModule.h" #include -#define TCP_MODULE_INIT_NAME "UART" -typedef struct tcp_module_header -{ - const char *mCheckName; -} TcpModuleHeader; -class TcpModuleImpl -{ -public: - TcpModuleImpl(const TcpPram &uatrInfo); - virtual ~TcpModuleImpl() = default; +// #define TCP_MODULE_INIT_NAME "UART" +// typedef struct tcp_module_header +// { +// const char *mCheckName; +// } TcpModuleHeader; +// class TcpModuleImpl +// { +// public: +// TcpModuleImpl(const TcpParam &uatrInfo); +// virtual ~TcpModuleImpl() = default; -private: - const StatusCode SetConfig(void); +// private: +// const StatusCode SetConfig(void); -private: - const TcpPram mUatrInfo; - int mFd; -}; +// private: +// const TcpParam mUatrInfo; +// int mFd; +// }; // TODO: There may be a CPU byte alignment bug. -typedef struct tcp_server TcpServer; -typedef struct tcp_server -{ - TcpModuleHeader mHeader; - std::shared_ptr mTcpImpl; -} TcpServer; -void *NewTcpModuleImpl(const TcpPram &tcpParam); -void *NewTcpServer(const TcpPram &tcpParam); -static inline TcpServer *TcpModuleImplConvert(void *object) -{ - return ((TcpServer *)(((char *)object) - sizeof(TcpModuleHeader))); -} -const char *GetTcpModuleName(void); +// typedef struct tcp_server TcpServer; +// typedef struct tcp_server +// { +// TcpModuleHeader mHeader; +// std::shared_ptr mTcpImpl; +// } TcpServer; +// void *NewTcpModuleImpl(const TcpParam &tcpParam); +// void *NewTcpServer(const TcpParam &tcpParam); +// static inline TcpServer *TcpModuleImplConvert(void *object) +// { +// return ((TcpServer *)(((char *)object) - sizeof(TcpModuleHeader))); +// } +// const char *GetTcpModuleName(void); #endif \ No newline at end of file diff --git a/utils/TcpModule/src/TcpServer.h b/utils/TcpModule/src/TcpModuleMakePtr.cpp similarity index 50% rename from utils/TcpModule/src/TcpServer.h rename to utils/TcpModule/src/TcpModuleMakePtr.cpp index f297c00..0c0d2f5 100644 --- a/utils/TcpModule/src/TcpServer.h +++ b/utils/TcpModule/src/TcpModuleMakePtr.cpp @@ -11,4 +11,24 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - */ \ No newline at end of file + */ +#include "TcpModuleMakePtr.h" +#include "ILog.h" +#include "TcpServerImpl.h" +#include "TcpClientImpl.h" +std::shared_ptr &TcpModuleMakePtr::GetInstance(std::shared_ptr *impl) +{ + static auto instance = std::make_shared(); + if (impl) { + instance = *impl; + } + return instance; +} +std::shared_ptr *TcpModuleMakePtr::CreateTcpServer(const TcpParam param) +{ + return NewTcpServer(param); +} +std::shared_ptr *TcpModuleMakePtr::CreateTcpClient(const TcpParam param) +{ + return NewTcpClient(param); +} \ No newline at end of file diff --git a/utils/TcpModule/src/TcpModuleMakePtr.h b/utils/TcpModule/src/TcpModuleMakePtr.h new file mode 100644 index 0000000..78f31bf --- /dev/null +++ b/utils/TcpModule/src/TcpModuleMakePtr.h @@ -0,0 +1,31 @@ +/* + * Copyright (c) 2023 Fancy Code. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef TCP_MODULE_MAKE_PTR_H +#define TCP_MODULE_MAKE_PTR_H +#include "StatusCode.h" +#include "TcpModule.h" +#include "ITcpServer.h" +#include "ITcpClient.h" +#include +class TcpModuleMakePtr +{ +public: + TcpModuleMakePtr() = default; + virtual ~TcpModuleMakePtr() = default; + static std::shared_ptr &GetInstance(std::shared_ptr *impl = nullptr); + virtual std::shared_ptr *CreateTcpServer(const TcpParam param); + virtual std::shared_ptr *CreateTcpClient(const TcpParam param); +}; +#endif // !TCP_MODULE_MAKE_PTR_H \ No newline at end of file diff --git a/utils/TcpModule/src/TcpServerHandle.cpp b/utils/TcpModule/src/TcpServerHandle.cpp new file mode 100644 index 0000000..3006dc0 --- /dev/null +++ b/utils/TcpModule/src/TcpServerHandle.cpp @@ -0,0 +1,45 @@ +/* + * Copyright (c) 2023 Fancy Code. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include "TcpServerHandle.h" +#include "ILog.h" +std::shared_ptr &TcpServerHandle::GetInstance(std::shared_ptr *impl) +{ + static auto instance = std::make_shared(); + if (impl) { + if (instance.use_count() == 1) { + LogInfo("Instance changed succeed.\n"); + instance = *impl; + } + else { + LogError("Can't changing the instance becase of using by some one.\n"); + } + } + return instance; +} +void TcpServerHandle::AddServer(const int &fd, const std::shared_ptr &server) +{ + LogInfo("AddServer fd = %d\n", fd); + mFd[fd] = server; +} +bool TcpServerHandle::GetServer(const int &fd, std::shared_ptr &server) +{ + auto it = mFd.find(fd); + if (it != mFd.end()) { + server = it->second; + return true; + } + LogError("There no ITcpServer fd = %d\n", fd); + return false; +} \ No newline at end of file diff --git a/utils/TcpModule/src/TcpServer.cpp b/utils/TcpModule/src/TcpServerHandle.h similarity index 52% rename from utils/TcpModule/src/TcpServer.cpp rename to utils/TcpModule/src/TcpServerHandle.h index f297c00..8413bec 100644 --- a/utils/TcpModule/src/TcpServer.cpp +++ b/utils/TcpModule/src/TcpServerHandle.h @@ -11,4 +11,22 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - */ \ No newline at end of file + */ +#ifndef TCP_SERVER_HANDLE_H +#define TCP_SERVER_HANDLE_H +#include "ITcpServer.h" +#include +#include +class TcpServerHandle +{ +public: + TcpServerHandle() = default; + ~TcpServerHandle() = default; + static std::shared_ptr &GetInstance(std::shared_ptr *impl = nullptr); + void AddServer(const int &fd, const std::shared_ptr &server); + bool GetServer(const int &fd, std::shared_ptr &server); + +private: + std::map> mFd; +}; +#endif \ No newline at end of file diff --git a/utils/TcpModule/src/TcpServerImpl.cpp b/utils/TcpModule/src/TcpServerImpl.cpp new file mode 100644 index 0000000..5a24d54 --- /dev/null +++ b/utils/TcpModule/src/TcpServerImpl.cpp @@ -0,0 +1,233 @@ +/* + * Copyright (c) 2023 Fancy Code. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include "TcpServerImpl.h" +#include "ILog.h" +#include "TcpServerHandle.h" +static bool TcpClientAcceptObjectCheck(void *object) +{ + if (nullptr == object) { + LogError("nullptr object!\n"); + return false; + } + if (*((const char **)(((char *)object) - sizeof(ITcpServerHeader))) != GetTcpClientAcceptName()) { + LogError("Illegal object!\n"); + return false; + } + return true; +} +static void on_close(hio_t *io) +{ + LogInfo("on_close fd=%d error=%d\n", hio_fd(io), hio_error(io)); + // std::shared_ptr server; + // if (TcpServerHandle::GetInstance()->GetServer(hio_fd(io), server) == true) { + // std::shared_ptr impl = std::dynamic_pointer_cast(server); + // if (impl != nullptr) { + // impl->ClosedEvent(); + // } + // } +} +static void on_recv(hio_t *io, void *buf, int readbytes) +{ + LogInfo("on_recv fd=%d readbytes=%d\n", hio_fd(io), readbytes); + char localaddrstr[SOCKADDR_STRLEN] = {0}; + char peeraddrstr[SOCKADDR_STRLEN] = {0}; + LogInfo( + "[%s] <=> [%s]\n", SOCKADDR_STR(hio_localaddr(io), localaddrstr), SOCKADDR_STR(hio_peeraddr(io), peeraddrstr)); + LogInfo("< %.*s", readbytes, (char *)buf); + ITcpClientAccept *client = (ITcpClientAccept *)hevent_userdata(io); + client->Readed((const char *)buf, readbytes); + // server->RemoveClient(hio_fd(io)); + // std::shared_ptr server; + // if (TcpServerHandle::GetInstance()->GetServer(hio_fd(io), server) == true) { + // std::shared_ptr impl = std::dynamic_pointer_cast(server); + // if (impl != nullptr) { + // impl->TcpServerReaded(buf, readbytes); + // } + // } + // echo + // LogInfo("> %.*s", readbytes, (char *)buf); + // hio_write(io, buf, readbytes); +} +static void on_accept(hio_t *io) +{ + LogInfo("on_accept connfd=%d\n", hio_fd(io)); + char localaddrstr[SOCKADDR_STRLEN] = {0}; + char peeraddrstr[SOCKADDR_STRLEN] = {0}; + LogInfo("accept connfd=%d [%s] <= [%s]\n", + hio_fd(io), + SOCKADDR_STR(hio_localaddr(io), localaddrstr), + SOCKADDR_STR(hio_peeraddr(io), peeraddrstr)); + + hio_setcb_close(io, on_close); + hio_setcb_read(io, on_recv); + std::shared_ptr *client = NewTcpClientAccept(io); + TcpServerImpl *server = (TcpServerImpl *)hevent_userdata(io); + // std::shared_ptr server; + // if (TcpServerHandle::GetInstance()->GetServer(hio_fd(io), server) == true) { + // std::shared_ptr impl = std::dynamic_pointer_cast(server); + // if (impl != nullptr) { + // impl->SetIo(io); + // } + // } + server->AddClient(io, client); + hevent_set_userdata(io, (*client).get()); + hio_read_start(io); +} +TcpClientAcceptImpl::TcpClientAcceptImpl(const hio_t *io) : mIo(io) +{ +} +void TcpClientAcceptImpl::Readed(const void *data, size_t length) +{ + LogInfo("TcpClientAcceptImpl::Readed\n"); +} +TcpServerImpl::TcpServerImpl(const TcpParam param) : mParam(param) +{ + mLoop = nullptr; + mIo = nullptr; +} +void TcpServerImpl::Init(void) +{ + constexpr int NO_FALGS = 0; + mLoop = hloop_new(NO_FALGS); + if (nullptr == mLoop) { + LogError("hloop_new failed\n"); + return; + } + hio_t *listenio = hloop_create_tcp_server(mLoop, mParam.mIp, mParam.mPort, on_accept); + if (nullptr == listenio) { + LogError("hloop_create_tcp_server failed\n"); + return; + } + LogInfo("listenfd=%d\n", hio_fd(listenio)); + hevent_set_userdata(listenio, this); + mIo = listenio; + std::shared_ptr server = shared_from_this(); + // TcpServerHandle::GetInstance()->AddServer(hio_fd(listenio), server); + std::shared_ptr impl = std::dynamic_pointer_cast(server); + auto recvThread = [](std::shared_ptr tcpServer) { + tcpServer->Loop(); + }; + mTcpServerThread = std::thread(recvThread, impl); +} +void TcpServerImpl::UnInit(void) +{ + LogInfo("UnInit TcpServerImpl\n"); + FreeClients(); + if (nullptr != mLoop) { + LogInfo("Stop loop.\n"); + hloop_stop(mLoop); + } + if (mTcpServerThread.joinable()) { + mTcpServerThread.join(); + } + hloop_free(&mLoop); + mLoop = nullptr; + mIo = nullptr; +} +void TcpServerImpl::TcpServerReaded(const void *buf, size_t length) +{ +} +void TcpServerImpl::TcpServerWrite(const void *buf, size_t length) +{ + if (mIo) { + hio_write(mIo, buf, length); + return; + } + LogError("mIo is null\n"); +} +void TcpServerImpl::ClosedEvent(void) +{ + mLoop = nullptr; + mIo = nullptr; +} +void TcpServerImpl::Loop(void) +{ + if (nullptr == mLoop) { + LogError("mLoop is null\n"); + return; + } + hloop_run(mLoop); +} +void TcpServerImpl::AddClient(hio_t *io, std::shared_ptr *client) +{ + char localaddrstr[SOCKADDR_STRLEN] = {0}; + char peeraddrstr[SOCKADDR_STRLEN] = {0}; + LogInfo("accept connfd=%d [%s] <= [%s]\n", + hio_fd(io), + SOCKADDR_STR(hio_localaddr(io), localaddrstr), + SOCKADDR_STR(hio_peeraddr(io), peeraddrstr)); + mClients[hio_fd(io)] = client; + if (mParam.mAcceptClientFunc) { + mParam.mAcceptClientFunc(client, peeraddrstr); + } +} +void TcpServerImpl::FreeClients(void) +{ + for (auto &client : mClients) { + if (nullptr != client.second) { + // delete client.second; + // client.second = nullptr; + void *object = (void *)client.second; + if (TcpClientAcceptObjectCheck(object) == true) { + // (*(std::shared_ptr *)object)->UnInit(); + (*(std::shared_ptr *)object).reset(); + free(((char *)object) - sizeof(ITcpServerHeader)); // TODO: bug? + } + } + } + // for (auto it = mClients.begin(); it != mClients.end();) { + // // 检查指针是否为空 + // if (it->second != nullptr) { + // // 释放 shared_ptr,这将减少引用计数 + // it->second->reset(); + // // 删除指针 + // delete it->second; + // // 从 map 中删除条目 + // it = mClients.erase(it); + // } + // else { + // // 指针为空,继续迭代 + // ++it; + // } + // } +} +std::shared_ptr *NewTcpServer(const TcpParam param) +{ + LogInfo("Create tcp server object.\n"); + TcpServer *impl = (TcpServer *)malloc(sizeof(TcpServer)); + if (nullptr == impl) { + LogError("NewTcpServer::malloc failed.\n"); + return nullptr; + } + TcpServer tmp; + memcpy((void *)impl, (void *)&tmp, sizeof(TcpServer)); + impl->mHeader.mCheckName = GetTcpServerModuleName(); + impl->mTcpServer = std::make_shared(param); + return (std::shared_ptr *)(((char *)impl) + sizeof(ITcpServerHeader)); +} +std::shared_ptr *NewTcpClientAccept(const hio_t *io) +{ + LogInfo("Create tcp server object.\n"); + TcpClientAccept *impl = (TcpClientAccept *)malloc(sizeof(TcpClientAccept)); + if (nullptr == impl) { + LogError("NewTcpServer::malloc failed.\n"); + return nullptr; + } + TcpClientAccept tmp; + memcpy((void *)impl, (void *)&tmp, sizeof(TcpClientAccept)); + impl->mHeader.mCheckName = GetTcpClientAcceptName(); + impl->mTcpClientAccept = std::make_shared(io); + return (std::shared_ptr *)(((char *)impl) + sizeof(ITcpServerHeader)); +} \ No newline at end of file diff --git a/utils/TcpModule/src/TcpServerImpl.h b/utils/TcpModule/src/TcpServerImpl.h new file mode 100644 index 0000000..3db698c --- /dev/null +++ b/utils/TcpModule/src/TcpServerImpl.h @@ -0,0 +1,57 @@ +/* + * Copyright (c) 2023 Fancy Code. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef TCP_SERVER_IMPL_H +#define TCP_SERVER_IMPL_H +#include "ITcpServer.h" +#include "TcpModule.h" +#include "hloop.h" +#include "hsocket.h" +#include "hssl.h" +#include +#include +class TcpClientAcceptImpl : public ITcpClientAccept +{ +public: + TcpClientAcceptImpl(const hio_t *io); + virtual ~TcpClientAcceptImpl() = default; + void Readed(const void *data, size_t length) override; + +private: + const hio_t *mIo; +}; +class TcpServerImpl : public ITcpServer, public std::enable_shared_from_this +{ +public: + TcpServerImpl(const TcpParam param); + virtual ~TcpServerImpl() = default; + void Init(void) override; + void UnInit(void) override; + void TcpServerReaded(const void *buf, size_t length); + void TcpServerWrite(const void *buf, size_t length); + void ClosedEvent(void); + void Loop(void); + void AddClient(hio_t *io, std::shared_ptr *client); + void FreeClients(void); + +private: + hloop_t *mLoop; + hio_t *mIo; + const TcpParam mParam; + std::thread mTcpServerThread; + std::map *> mClients; +}; +std::shared_ptr *NewTcpServer(const TcpParam param); +std::shared_ptr *NewTcpClientAccept(const hio_t *io); +#endif \ No newline at end of file From a7fc63285c5f06fe9abdd8da4658405a196793d0 Mon Sep 17 00:00:00 2001 From: Fancy code <258828110.@qq.com> Date: Thu, 11 Apr 2024 15:57:49 +0800 Subject: [PATCH 04/10] Backup:TcpModule. --- middleware/McuManager/src/McuDevice.cpp | 4 +- middleware/McuManager/src/McuDevice.h | 4 +- test/utils/TcpModule/src/TcpModule_Test.cpp | 25 ++- utils/McuProtocol/include/McuProtocol.h | 4 +- utils/TcpModule/include/TcpModule.h | 29 +++- utils/TcpModule/src/ITcpClient.cpp | 9 +- utils/TcpModule/src/ITcpClient.h | 3 +- utils/TcpModule/src/ITcpServer.cpp | 23 +++ utils/TcpModule/src/ITcpServer.h | 5 + utils/TcpModule/src/TcpClientImpl.cpp | 52 ++++--- utils/TcpModule/src/TcpClientImpl.h | 11 +- utils/TcpModule/src/TcpModule.cpp | 17 ++- utils/TcpModule/src/TcpModuleImpl.cpp | 4 +- utils/TcpModule/src/TcpModuleImpl.h | 8 +- utils/TcpModule/src/TcpModuleMakePtr.cpp | 6 +- utils/TcpModule/src/TcpModuleMakePtr.h | 8 +- utils/TcpModule/src/TcpServerImpl.cpp | 159 ++++++++++---------- utils/TcpModule/src/TcpServerImpl.h | 23 ++- 18 files changed, 238 insertions(+), 156 deletions(-) diff --git a/middleware/McuManager/src/McuDevice.cpp b/middleware/McuManager/src/McuDevice.cpp index ae736e1..624efc9 100644 --- a/middleware/McuManager/src/McuDevice.cpp +++ b/middleware/McuManager/src/McuDevice.cpp @@ -79,8 +79,8 @@ const StatusCode McuDevice::UnInit(void) DeleteAllAsk(); return CreateStatusCode(STATUS_CODE_OK); } -size_t McuDevice::WriteData(const void *buff, const size_t buffLength, std::shared_ptr &context, - const unsigned int &serialNumber) +ssize_t McuDevice::WriteData(const void *buff, const size_t buffLength, std::shared_ptr &context, + const unsigned int &serialNumber) { constexpr size_t WRITE_ERROR = -1; size_t length = WRITE_ERROR; diff --git a/middleware/McuManager/src/McuDevice.h b/middleware/McuManager/src/McuDevice.h index 7cda792..6a44dc6 100644 --- a/middleware/McuManager/src/McuDevice.h +++ b/middleware/McuManager/src/McuDevice.h @@ -29,8 +29,8 @@ public: const StatusCode UnInit(void) override; public: - size_t WriteData(const void *buff, const size_t buffLength, std::shared_ptr &context, - const unsigned int &serialNumber) override; + ssize_t WriteData(const void *buff, const size_t buffLength, std::shared_ptr &context, + const unsigned int &serialNumber) override; public: void GetIpcMissionReply(const unsigned int &serialNumber, const unsigned char &mission) override; diff --git a/test/utils/TcpModule/src/TcpModule_Test.cpp b/test/utils/TcpModule/src/TcpModule_Test.cpp index 39a4ea3..99db5eb 100644 --- a/test/utils/TcpModule/src/TcpModule_Test.cpp +++ b/test/utils/TcpModule/src/TcpModule_Test.cpp @@ -19,33 +19,42 @@ #include namespace TcpModuleTest { -// ../output_files/test/bin/TcpModuleTest --gtest_filter=TcpModuleTest.UNIT_TcpModule_AUTO_IllegalObject +// ../output_files/test/bin/TcpModuleTest --gtest_filter=TcpModuleTest.UNIT_TcpModule_EXAMPLE_AUTO_IllegalObject /** * TcpModule module api will not crash when object is illegal. */ -TEST(TcpModuleTest, UNIT_TcpModule_AUTO_IllegalObject) +TEST(TcpModuleTest, UNIT_TcpModule_EXAMPLE_AUTO_IllegalObject) { static void *tcpClientAccept = nullptr; - TcpParam param = { + TcpServerParam tcpServerparam = { .mIp = "127.0.0.1", .mPort = 9876, - .mReadFunc = [](const void *p, const size_t len, void *context) -> void { - return; - }, .mAcceptClientFunc = [](void *object, const char *ip) -> void { LogInfo("accept client, peer ip: %s", ip); tcpClientAccept = object; return; }, }; + TcpClientParam param = { + .mIp = "127.0.0.1", + .mPort = 9876, + .mReadFunc = [](const void *data, const ssize_t len, const void *context) -> void { + LogInfo("read data: %s", (char *)data); + return; + }, + }; CreateLogModule(); ILogInit(LOG_INSTANCE_TYPE_END); - void *tcpServer = CreateTcpServer(param); + void *tcpServer = CreateTcpServer(tcpServerparam); std::this_thread::sleep_for(std::chrono::milliseconds(500)); void *tcpClient = CreateTcpClient(param); std::this_thread::sleep_for(std::chrono::milliseconds(100)); TcpClientWrite(tcpClient, "123456789", strlen("123456789")); - std::this_thread::sleep_for(std::chrono::milliseconds(3000)); + std::this_thread::sleep_for(std::chrono::milliseconds(100)); + if (nullptr != tcpClientAccept) { + AcceptClientWrite(tcpClientAccept, "9876543210", strlen("9876543210")); + } + std::this_thread::sleep_for(std::chrono::milliseconds(1000)); if (nullptr != tcpClient) { FreeTcpClient(tcpClient); } diff --git a/utils/McuProtocol/include/McuProtocol.h b/utils/McuProtocol/include/McuProtocol.h index 6ed055d..08b7ea8 100644 --- a/utils/McuProtocol/include/McuProtocol.h +++ b/utils/McuProtocol/include/McuProtocol.h @@ -68,8 +68,8 @@ protected: { return std::make_shared(); } - virtual size_t WriteData(const void *buff, const size_t buffLength, std::shared_ptr &context, - const unsigned int &serialNumber) + virtual ssize_t WriteData(const void *buff, const size_t buffLength, std::shared_ptr &context, + const unsigned int &serialNumber) { return 0; } diff --git a/utils/TcpModule/include/TcpModule.h b/utils/TcpModule/include/TcpModule.h index 2044b24..a8b605d 100644 --- a/utils/TcpModule/include/TcpModule.h +++ b/utils/TcpModule/include/TcpModule.h @@ -16,23 +16,36 @@ #define TCP_MODULE_H #include #include +#define TCP_MODULE_WRITE_ERROR -1; #ifdef __cplusplus extern "C" { #endif -typedef void (*TcpReadFunction)(const void *, const size_t, void *); +typedef void (*TcpReadFunction)(const void *, const ssize_t, const void *); typedef void (*TcpAcceptClientFunction)(void *, const char *); +typedef void (*SocketClosedFunction)(const void *); +typedef struct tcp_server_parm +{ + const char *mIp; + const int mPort; + TcpAcceptClientFunction mAcceptClientFunc; +} TcpServerParam; typedef struct tcp_parm { const char *mIp; const int mPort; - TcpReadFunction mReadFunc; // TODO: delete this memeber - TcpAcceptClientFunction mAcceptClientFunc; -} TcpParam; -void *CreateTcpServer(const TcpParam param); + TcpReadFunction mReadFunc; + SocketClosedFunction mClosedFunc; +} TcpClientParam; +typedef struct client_accept_parm +{ + TcpReadFunction mReadFunc; + SocketClosedFunction mClosedFunc; +} ClientAcceptParam; +void *CreateTcpServer(const TcpServerParam param); void FreeTcpServer(void *object); -int AcceptClientSetReadFunc(void *object, TcpReadFunction readFunc); -int AcceptClientWrite(void *object, void *buf, const size_t bufLenght); -void *CreateTcpClient(const TcpParam param); +void AcceptClientSetParam(void *object, const ClientAcceptParam param); +ssize_t AcceptClientWrite(void *object, const void *buf, const size_t bufLenght); +void *CreateTcpClient(const TcpClientParam param); void FreeTcpClient(void *object); ssize_t TcpClientWrite(void *object, const void *buf, const size_t bufLenght); #ifdef __cplusplus diff --git a/utils/TcpModule/src/ITcpClient.cpp b/utils/TcpModule/src/ITcpClient.cpp index 0e0ca32..256ab40 100644 --- a/utils/TcpModule/src/ITcpClient.cpp +++ b/utils/TcpModule/src/ITcpClient.cpp @@ -14,6 +14,7 @@ */ #include "ITcpClient.h" #include "ILog.h" +#include "TcpModule.h" #include void ITcpClient::Init(void) { @@ -21,9 +22,15 @@ void ITcpClient::Init(void) void ITcpClient::UnInit(void) { } +void ITcpClient::Readed(const void *data, size_t length) +{ +} ssize_t ITcpClient::Write(const void *buf, const size_t bufLenght) { - return WRITE_ERROR; + return TCP_MODULE_WRITE_ERROR; +} +void ITcpClient::Closed(void) +{ } static const char *TCP_CLIENT_NAME = "tcp_client"; const char *GetTcpClientModuleName(void) diff --git a/utils/TcpModule/src/ITcpClient.h b/utils/TcpModule/src/ITcpClient.h index 992174b..8948a45 100644 --- a/utils/TcpModule/src/ITcpClient.h +++ b/utils/TcpModule/src/ITcpClient.h @@ -16,7 +16,6 @@ #define I_TCP_CLIENT_H #include "StatusCode.h" #include -constexpr int WRITE_ERROR = -1; class ITcpClient { public: @@ -24,7 +23,9 @@ public: virtual ~ITcpClient() = default; virtual void Init(void); virtual void UnInit(void); + virtual void Readed(const void *data, size_t length); virtual ssize_t Write(const void *buf, const size_t bufLenght); + virtual void Closed(void); }; typedef struct i_tcp_client_header { diff --git a/utils/TcpModule/src/ITcpServer.cpp b/utils/TcpModule/src/ITcpServer.cpp index 4c8c0e2..f61b8c4 100644 --- a/utils/TcpModule/src/ITcpServer.cpp +++ b/utils/TcpModule/src/ITcpServer.cpp @@ -14,10 +14,21 @@ */ #include "ITcpServer.h" #include "ILog.h" +#include "TcpModule.h" #include +void ITcpClientAccept::SetParam(const ClientAcceptParam ¶m) +{ +} void ITcpClientAccept::Readed(const void *data, size_t length) { } +ssize_t ITcpClientAccept::Write(const void *data, size_t length) +{ + return TCP_MODULE_WRITE_ERROR; +} +void ITcpClientAccept::Closed(void) +{ +} void ITcpServer::Init(void) { } @@ -33,4 +44,16 @@ const char *GetTcpServerModuleName(void) const char *GetTcpClientAcceptName(void) { return TCP_CLIENT_ACCEPT_NAME; +} +bool TcpClientAcceptObjectCheck(void *object) +{ + if (nullptr == object) { + LogError("nullptr object!\n"); + return false; + } + if (*((const char **)(((char *)object) - sizeof(ITcpServerHeader))) != GetTcpClientAcceptName()) { + LogError("Illegal object!\n"); + return false; + } + return true; } \ No newline at end of file diff --git a/utils/TcpModule/src/ITcpServer.h b/utils/TcpModule/src/ITcpServer.h index 34a4cc7..5f72f50 100644 --- a/utils/TcpModule/src/ITcpServer.h +++ b/utils/TcpModule/src/ITcpServer.h @@ -15,13 +15,17 @@ #ifndef I_TCP_SERVER_H #define I_TCP_SERVER_H #include "StatusCode.h" +#include "TcpModule.h" #include class ITcpClientAccept { public: ITcpClientAccept() = default; virtual ~ITcpClientAccept() = default; + virtual void SetParam(const ClientAcceptParam ¶m); virtual void Readed(const void *data, size_t length); + virtual ssize_t Write(const void *data, size_t length); + virtual void Closed(void); }; class ITcpServer { @@ -47,4 +51,5 @@ typedef struct tcp_client_accept } TcpClientAccept; const char *GetTcpServerModuleName(void); const char *GetTcpClientAcceptName(void); +bool TcpClientAcceptObjectCheck(void *object); #endif \ No newline at end of file diff --git a/utils/TcpModule/src/TcpClientImpl.cpp b/utils/TcpModule/src/TcpClientImpl.cpp index 532ad74..a7c2b6f 100644 --- a/utils/TcpModule/src/TcpClientImpl.cpp +++ b/utils/TcpModule/src/TcpClientImpl.cpp @@ -15,38 +15,26 @@ #include "TcpClientImpl.h" #include "ILog.h" #include -TcpClientImpl::TcpClientImpl(const TcpParam param) : mParam(param) -{ -} static void on_message(hio_t *io, void *buf, int len) { LogInfo("onmessage: %.*s\n", len, (char *)buf); - TcpClientImpl *cli = (TcpClientImpl *)hevent_userdata(io); - // ... + TcpClientImpl *tcpClient = (TcpClientImpl *)hevent_userdata(io); + tcpClient->Readed(buf, len); } static void on_connect(hio_t *io) { LogInfo("onconnect: connfd=%d\n", hio_fd(io)); - TcpClientImpl *cli = (TcpClientImpl *)hevent_userdata(io); - // cli->connected = 1; - - // hio_write(io, "hello\r\n", 7); - hio_setcb_read(io, on_message); hio_read(io); } static void on_close(hio_t *io) { LogInfo("onclose: connfd=%d error=%d\n", hio_fd(io), hio_error(io)); - TcpClientImpl *cli = (TcpClientImpl *)hevent_userdata(io); - // cli->connected = 0; - // reconnect - // if (cli->reconn_setting && reconn_setting_can_retry(cli->reconn_setting)) { - // uint32_t delay = reconn_setting_calc_delay(cli->reconn_setting); - // LogInfo("reconnect cnt=%d, delay=%d ...\n", cli->reconn_setting->cur_retry_cnt, - // cli->reconn_setting->cur_delay); cli->reconn_timer = htimer_add(cli->mLoop, reconnect_timer_cb, delay, 1); - // hevent_set_userdata(cli->reconn_timer, cli); - // } + TcpClientImpl *tcpClient = (TcpClientImpl *)hevent_userdata(io); + tcpClient->Closed(); +} +TcpClientImpl::TcpClientImpl(const TcpClientParam ¶m, const void *object) : mParam(param), mObjectThis(object) +{ } void TcpClientImpl::Init(void) { @@ -85,14 +73,30 @@ void TcpClientImpl::UnInit(void) mLoop = nullptr; mIo = nullptr; } +void TcpClientImpl::Readed(const void *data, size_t length) +{ + if (nullptr != mParam.mReadFunc) { + mParam.mReadFunc(data, length, nullptr); + return; + } + LogError("mParam.mReadFunc is nullptr.\n"); +} ssize_t TcpClientImpl::Write(const void *buf, const size_t bufLenght) { if (nullptr == mIo) { LogError("mIo is nullptr.\n"); - return WRITE_ERROR; + return TCP_MODULE_WRITE_ERROR; } return hio_write(mIo, buf, bufLenght); } +void TcpClientImpl::Closed(void) +{ + if (nullptr != mParam.mClosedFunc) { + mParam.mClosedFunc(mObjectThis); + return; + } + LogWarning("mParam.mClosedFunc is null\n"); +} void TcpClientImpl::Loop(void) { if (nullptr == mLoop) { @@ -101,7 +105,7 @@ void TcpClientImpl::Loop(void) } hloop_run(mLoop); } -std::shared_ptr *NewTcpClient(const TcpParam param) +std::shared_ptr *NewTcpClient(const TcpClientParam ¶m) { LogInfo("Create tcp server object.\n"); TcpClient *impl = (TcpClient *)malloc(sizeof(TcpClient)); @@ -112,6 +116,8 @@ std::shared_ptr *NewTcpClient(const TcpParam param) TcpClient tmp; memcpy((void *)impl, (void *)&tmp, sizeof(TcpClient)); impl->mHeader.mCheckName = GetTcpClientModuleName(); - impl->mTcpClient = std::make_shared(param); - return (std::shared_ptr *)(((char *)impl) + sizeof(ITcpClientHeader)); + std::shared_ptr *objectThis = + (std::shared_ptr *)(((char *)impl) + sizeof(ITcpClientHeader)); + impl->mTcpClient = std::make_shared(param, objectThis); + return objectThis; } \ No newline at end of file diff --git a/utils/TcpModule/src/TcpClientImpl.h b/utils/TcpModule/src/TcpClientImpl.h index 9404a89..c84cde9 100644 --- a/utils/TcpModule/src/TcpClientImpl.h +++ b/utils/TcpModule/src/TcpClientImpl.h @@ -24,18 +24,21 @@ class TcpClientImpl : public ITcpClient, public std::enable_shared_from_this { public: - TcpClientImpl(const TcpParam param); + TcpClientImpl(const TcpClientParam ¶m, const void *object); virtual ~TcpClientImpl() = default; void Init(void) override; void UnInit(void) override; + void Readed(const void *data, size_t length) override; ssize_t Write(const void *buf, const size_t bufLenght) override; + void Closed(void) override; void Loop(void); private: - hloop_t* mLoop; + hloop_t *mLoop; hio_t *mIo; - const TcpParam mParam; + const TcpClientParam mParam; std::thread mTcpClientThread; + const void *mObjectThis; }; -std::shared_ptr *NewTcpClient(const TcpParam param); +std::shared_ptr *NewTcpClient(const TcpClientParam ¶m); #endif \ No newline at end of file diff --git a/utils/TcpModule/src/TcpModule.cpp b/utils/TcpModule/src/TcpModule.cpp index 939c2a4..ab28bc9 100644 --- a/utils/TcpModule/src/TcpModule.cpp +++ b/utils/TcpModule/src/TcpModule.cpp @@ -42,7 +42,7 @@ static bool TcpClientObjectCheck(void *object) } return true; } -void *CreateTcpServer(const TcpParam param) +void *CreateTcpServer(const TcpServerParam param) { std::shared_ptr *server = TcpModuleMakePtr::GetInstance()->CreateTcpServer(param); if (nullptr != *server) { @@ -58,7 +58,20 @@ void FreeTcpServer(void *object) free(((char *)object) - sizeof(ITcpServerHeader)); // TODO: bug? } } -void *CreateTcpClient(const TcpParam param) +void AcceptClientSetParam(void *object, const ClientAcceptParam param) +{ + if (TcpClientAcceptObjectCheck(object) == true) { + (*(std::shared_ptr *)object)->SetParam(param); + } +} +ssize_t AcceptClientWrite(void *object, const void *buf, const size_t bufLenght) +{ + if (TcpClientAcceptObjectCheck(object) == true) { + return (*(std::shared_ptr *)object)->Write(buf, bufLenght); + } + return TCP_MODULE_WRITE_ERROR; +} +void *CreateTcpClient(const TcpClientParam param) { std::shared_ptr *client = TcpModuleMakePtr::GetInstance()->CreateTcpClient(param); if (nullptr != *client) { diff --git a/utils/TcpModule/src/TcpModuleImpl.cpp b/utils/TcpModule/src/TcpModuleImpl.cpp index 85e5619..08e20a8 100644 --- a/utils/TcpModule/src/TcpModuleImpl.cpp +++ b/utils/TcpModule/src/TcpModuleImpl.cpp @@ -20,7 +20,7 @@ // { // return TCP_MODULE_NAME; // } -// void *NewTcpModuleImpl(const TcpParam &tcpParam) +// void *NewTcpModuleImpl(const TcpClientParam &tcpParam) // { // if (nullptr == tcpParam.mIp) { // LogError("Parament error, nullptr == tcpParam.mIp\n"); @@ -34,7 +34,7 @@ // impl->mTcpImpl = std::make_shared(tcpParam); // return (void *)(((char *)impl) + sizeof(TcpModuleHeader)); // } -// void *NewTcpServer(const TcpParam &tcpParam) +// void *NewTcpServer(const TcpClientParam &tcpParam) // { // return nullptr; // } \ No newline at end of file diff --git a/utils/TcpModule/src/TcpModuleImpl.h b/utils/TcpModule/src/TcpModuleImpl.h index 6b58fa6..3320ea4 100644 --- a/utils/TcpModule/src/TcpModuleImpl.h +++ b/utils/TcpModule/src/TcpModuleImpl.h @@ -25,14 +25,14 @@ // class TcpModuleImpl // { // public: -// TcpModuleImpl(const TcpParam &uatrInfo); +// TcpModuleImpl(const TcpClientParam &uatrInfo); // virtual ~TcpModuleImpl() = default; // private: // const StatusCode SetConfig(void); // private: -// const TcpParam mUatrInfo; +// const TcpClientParam mUatrInfo; // int mFd; // }; // TODO: There may be a CPU byte alignment bug. @@ -42,8 +42,8 @@ // TcpModuleHeader mHeader; // std::shared_ptr mTcpImpl; // } TcpServer; -// void *NewTcpModuleImpl(const TcpParam &tcpParam); -// void *NewTcpServer(const TcpParam &tcpParam); +// void *NewTcpModuleImpl(const TcpClientParam &tcpParam); +// void *NewTcpServer(const TcpClientParam &tcpParam); // static inline TcpServer *TcpModuleImplConvert(void *object) // { // return ((TcpServer *)(((char *)object) - sizeof(TcpModuleHeader))); diff --git a/utils/TcpModule/src/TcpModuleMakePtr.cpp b/utils/TcpModule/src/TcpModuleMakePtr.cpp index 0c0d2f5..975d350 100644 --- a/utils/TcpModule/src/TcpModuleMakePtr.cpp +++ b/utils/TcpModule/src/TcpModuleMakePtr.cpp @@ -14,8 +14,8 @@ */ #include "TcpModuleMakePtr.h" #include "ILog.h" -#include "TcpServerImpl.h" #include "TcpClientImpl.h" +#include "TcpServerImpl.h" std::shared_ptr &TcpModuleMakePtr::GetInstance(std::shared_ptr *impl) { static auto instance = std::make_shared(); @@ -24,11 +24,11 @@ std::shared_ptr &TcpModuleMakePtr::GetInstance(std::shared_ptr } return instance; } -std::shared_ptr *TcpModuleMakePtr::CreateTcpServer(const TcpParam param) +std::shared_ptr *TcpModuleMakePtr::CreateTcpServer(const TcpServerParam ¶m) { return NewTcpServer(param); } -std::shared_ptr *TcpModuleMakePtr::CreateTcpClient(const TcpParam param) +std::shared_ptr *TcpModuleMakePtr::CreateTcpClient(const TcpClientParam ¶m) { return NewTcpClient(param); } \ No newline at end of file diff --git a/utils/TcpModule/src/TcpModuleMakePtr.h b/utils/TcpModule/src/TcpModuleMakePtr.h index 78f31bf..f381029 100644 --- a/utils/TcpModule/src/TcpModuleMakePtr.h +++ b/utils/TcpModule/src/TcpModuleMakePtr.h @@ -14,10 +14,10 @@ */ #ifndef TCP_MODULE_MAKE_PTR_H #define TCP_MODULE_MAKE_PTR_H +#include "ITcpClient.h" +#include "ITcpServer.h" #include "StatusCode.h" #include "TcpModule.h" -#include "ITcpServer.h" -#include "ITcpClient.h" #include class TcpModuleMakePtr { @@ -25,7 +25,7 @@ public: TcpModuleMakePtr() = default; virtual ~TcpModuleMakePtr() = default; static std::shared_ptr &GetInstance(std::shared_ptr *impl = nullptr); - virtual std::shared_ptr *CreateTcpServer(const TcpParam param); - virtual std::shared_ptr *CreateTcpClient(const TcpParam param); + virtual std::shared_ptr *CreateTcpServer(const TcpServerParam ¶m); + virtual std::shared_ptr *CreateTcpClient(const TcpClientParam ¶m); }; #endif // !TCP_MODULE_MAKE_PTR_H \ No newline at end of file diff --git a/utils/TcpModule/src/TcpServerImpl.cpp b/utils/TcpModule/src/TcpServerImpl.cpp index 5a24d54..dee7329 100644 --- a/utils/TcpModule/src/TcpServerImpl.cpp +++ b/utils/TcpModule/src/TcpServerImpl.cpp @@ -15,28 +15,11 @@ #include "TcpServerImpl.h" #include "ILog.h" #include "TcpServerHandle.h" -static bool TcpClientAcceptObjectCheck(void *object) -{ - if (nullptr == object) { - LogError("nullptr object!\n"); - return false; - } - if (*((const char **)(((char *)object) - sizeof(ITcpServerHeader))) != GetTcpClientAcceptName()) { - LogError("Illegal object!\n"); - return false; - } - return true; -} static void on_close(hio_t *io) { LogInfo("on_close fd=%d error=%d\n", hio_fd(io), hio_error(io)); - // std::shared_ptr server; - // if (TcpServerHandle::GetInstance()->GetServer(hio_fd(io), server) == true) { - // std::shared_ptr impl = std::dynamic_pointer_cast(server); - // if (impl != nullptr) { - // impl->ClosedEvent(); - // } - // } + TcpServerImpl *server = (TcpServerImpl *)hevent_userdata(io); + server->RemoveClient(io); } static void on_recv(hio_t *io, void *buf, int readbytes) { @@ -46,19 +29,9 @@ static void on_recv(hio_t *io, void *buf, int readbytes) LogInfo( "[%s] <=> [%s]\n", SOCKADDR_STR(hio_localaddr(io), localaddrstr), SOCKADDR_STR(hio_peeraddr(io), peeraddrstr)); LogInfo("< %.*s", readbytes, (char *)buf); - ITcpClientAccept *client = (ITcpClientAccept *)hevent_userdata(io); - client->Readed((const char *)buf, readbytes); - // server->RemoveClient(hio_fd(io)); - // std::shared_ptr server; - // if (TcpServerHandle::GetInstance()->GetServer(hio_fd(io), server) == true) { - // std::shared_ptr impl = std::dynamic_pointer_cast(server); - // if (impl != nullptr) { - // impl->TcpServerReaded(buf, readbytes); - // } - // } - // echo - // LogInfo("> %.*s", readbytes, (char *)buf); - // hio_write(io, buf, readbytes); + TcpServerImpl *server = (TcpServerImpl *)hevent_userdata(io); + std::shared_ptr *client = server->GetClient(io); + (*client)->Readed((const char *)buf, readbytes); } static void on_accept(hio_t *io) { @@ -74,25 +47,47 @@ static void on_accept(hio_t *io) hio_setcb_read(io, on_recv); std::shared_ptr *client = NewTcpClientAccept(io); TcpServerImpl *server = (TcpServerImpl *)hevent_userdata(io); - // std::shared_ptr server; - // if (TcpServerHandle::GetInstance()->GetServer(hio_fd(io), server) == true) { - // std::shared_ptr impl = std::dynamic_pointer_cast(server); - // if (impl != nullptr) { - // impl->SetIo(io); - // } - // } server->AddClient(io, client); - hevent_set_userdata(io, (*client).get()); hio_read_start(io); } -TcpClientAcceptImpl::TcpClientAcceptImpl(const hio_t *io) : mIo(io) +TcpClientAcceptImpl::TcpClientAcceptImpl(const hio_t *io, const void *object) : mIo(io), mObjectThis(object) { + mParam.mReadFunc = nullptr; + mParam.mClosedFunc = nullptr; +} +void TcpClientAcceptImpl::SetParam(const ClientAcceptParam ¶m) +{ + std::lock_guard locker(mMutex); + mParam = param; } void TcpClientAcceptImpl::Readed(const void *data, size_t length) { - LogInfo("TcpClientAcceptImpl::Readed\n"); + std::lock_guard locker(mMutex); + if (nullptr != mParam.mReadFunc) { + mParam.mReadFunc(data, length, mObjectThis); + return; + } + LogWarning("mParam.mClosedFunc is null\n"); } -TcpServerImpl::TcpServerImpl(const TcpParam param) : mParam(param) +ssize_t TcpClientAcceptImpl::Write(const void *data, size_t length) +{ + if (mIo) { + hio_t *io = (hio_t *)mIo; + return hio_write(io, data, length); + } + LogError("mIo is null\n"); + return TCP_MODULE_WRITE_ERROR; +} +void TcpClientAcceptImpl::Closed(void) +{ + std::lock_guard locker(mMutex); + if (nullptr != mParam.mClosedFunc) { + mParam.mClosedFunc(mObjectThis); + return; + } + LogWarning("mParam.mClosedFunc is null\n"); +} +TcpServerImpl::TcpServerImpl(const TcpServerParam param) : mParam(param) { mLoop = nullptr; mIo = nullptr; @@ -114,7 +109,6 @@ void TcpServerImpl::Init(void) hevent_set_userdata(listenio, this); mIo = listenio; std::shared_ptr server = shared_from_this(); - // TcpServerHandle::GetInstance()->AddServer(hio_fd(listenio), server); std::shared_ptr impl = std::dynamic_pointer_cast(server); auto recvThread = [](std::shared_ptr tcpServer) { tcpServer->Loop(); @@ -136,22 +130,6 @@ void TcpServerImpl::UnInit(void) mLoop = nullptr; mIo = nullptr; } -void TcpServerImpl::TcpServerReaded(const void *buf, size_t length) -{ -} -void TcpServerImpl::TcpServerWrite(const void *buf, size_t length) -{ - if (mIo) { - hio_write(mIo, buf, length); - return; - } - LogError("mIo is null\n"); -} -void TcpServerImpl::ClosedEvent(void) -{ - mLoop = nullptr; - mIo = nullptr; -} void TcpServerImpl::Loop(void) { if (nullptr == mLoop) { @@ -162,6 +140,7 @@ void TcpServerImpl::Loop(void) } void TcpServerImpl::AddClient(hio_t *io, std::shared_ptr *client) { + std::lock_guard locker(mMutex); char localaddrstr[SOCKADDR_STRLEN] = {0}; char peeraddrstr[SOCKADDR_STRLEN] = {0}; LogInfo("accept connfd=%d [%s] <= [%s]\n", @@ -173,37 +152,51 @@ void TcpServerImpl::AddClient(hio_t *io, std::shared_ptr *clie mParam.mAcceptClientFunc(client, peeraddrstr); } } +std::shared_ptr *TcpServerImpl::GetClient(hio_t *io) +{ + std::lock_guard locker(mMutex); + auto it = mClients.find(hio_fd(io)); + if (it != mClients.end()) { + return it->second; + } + else { + LogError("GetClient failed, client not exit.\n"); + return nullptr; + } +} +void TcpServerImpl::RemoveClient(hio_t *io) +{ + std::lock_guard locker(mMutex); + auto it = mClients.find(hio_fd(io)); + if (it != mClients.end()) { + void *object = (void *)it->second; + if (TcpClientAcceptObjectCheck(object) == true) { + (*(std::shared_ptr *)object)->Closed(); + (*(std::shared_ptr *)object).reset(); + free(((char *)object) - sizeof(ITcpServerHeader)); + } + mClients.erase(it); + } + else { + LogError("RemoveClient failed, client not exit.\n"); + } +} void TcpServerImpl::FreeClients(void) { + std::lock_guard locker(mMutex); for (auto &client : mClients) { if (nullptr != client.second) { - // delete client.second; - // client.second = nullptr; void *object = (void *)client.second; if (TcpClientAcceptObjectCheck(object) == true) { - // (*(std::shared_ptr *)object)->UnInit(); + (*(std::shared_ptr *)object)->Closed(); (*(std::shared_ptr *)object).reset(); - free(((char *)object) - sizeof(ITcpServerHeader)); // TODO: bug? + free(((char *)object) - sizeof(ITcpServerHeader)); } } } - // for (auto it = mClients.begin(); it != mClients.end();) { - // // 检查指针是否为空 - // if (it->second != nullptr) { - // // 释放 shared_ptr,这将减少引用计数 - // it->second->reset(); - // // 删除指针 - // delete it->second; - // // 从 map 中删除条目 - // it = mClients.erase(it); - // } - // else { - // // 指针为空,继续迭代 - // ++it; - // } - // } + mClients.clear(); } -std::shared_ptr *NewTcpServer(const TcpParam param) +std::shared_ptr *NewTcpServer(const TcpServerParam ¶m) { LogInfo("Create tcp server object.\n"); TcpServer *impl = (TcpServer *)malloc(sizeof(TcpServer)); @@ -228,6 +221,8 @@ std::shared_ptr *NewTcpClientAccept(const hio_t *io) TcpClientAccept tmp; memcpy((void *)impl, (void *)&tmp, sizeof(TcpClientAccept)); impl->mHeader.mCheckName = GetTcpClientAcceptName(); - impl->mTcpClientAccept = std::make_shared(io); - return (std::shared_ptr *)(((char *)impl) + sizeof(ITcpServerHeader)); + std::shared_ptr *objectThis = + (std::shared_ptr *)(((char *)impl) + sizeof(ITcpServerHeader)); + impl->mTcpClientAccept = std::make_shared(io, objectThis); + return objectThis; } \ No newline at end of file diff --git a/utils/TcpModule/src/TcpServerImpl.h b/utils/TcpModule/src/TcpServerImpl.h index 3db698c..5e92655 100644 --- a/utils/TcpModule/src/TcpServerImpl.h +++ b/utils/TcpModule/src/TcpServerImpl.h @@ -20,38 +20,45 @@ #include "hsocket.h" #include "hssl.h" #include +#include #include -class TcpClientAcceptImpl : public ITcpClientAccept +class TcpClientAcceptImpl : public ITcpClientAccept, public std::enable_shared_from_this { public: - TcpClientAcceptImpl(const hio_t *io); + TcpClientAcceptImpl(const hio_t *io, const void *object); virtual ~TcpClientAcceptImpl() = default; + void SetParam(const ClientAcceptParam ¶m) override; void Readed(const void *data, size_t length) override; + ssize_t Write(const void *data, size_t length) override; + void Closed(void) override; private: + std::mutex mMutex; const hio_t *mIo; + ClientAcceptParam mParam; + const void *mObjectThis; }; class TcpServerImpl : public ITcpServer, public std::enable_shared_from_this { public: - TcpServerImpl(const TcpParam param); + TcpServerImpl(const TcpServerParam param); virtual ~TcpServerImpl() = default; void Init(void) override; void UnInit(void) override; - void TcpServerReaded(const void *buf, size_t length); - void TcpServerWrite(const void *buf, size_t length); - void ClosedEvent(void); void Loop(void); void AddClient(hio_t *io, std::shared_ptr *client); + std::shared_ptr *GetClient(hio_t *io); + void RemoveClient(hio_t *io); void FreeClients(void); private: + std::mutex mMutex; hloop_t *mLoop; hio_t *mIo; - const TcpParam mParam; + const TcpServerParam mParam; std::thread mTcpServerThread; std::map *> mClients; }; -std::shared_ptr *NewTcpServer(const TcpParam param); +std::shared_ptr *NewTcpServer(const TcpServerParam ¶m); std::shared_ptr *NewTcpClientAccept(const hio_t *io); #endif \ No newline at end of file From 7ebd2e3aa7f069e2c6130a61455c74db82104ce5 Mon Sep 17 00:00:00 2001 From: Fancy code <258828110.@qq.com> Date: Thu, 11 Apr 2024 18:49:05 +0800 Subject: [PATCH 05/10] Improve:TcpModule. --- test/utils/TcpModule/src/TcpModule_Test.cpp | 28 +++++++++++------ utils/TcpModule/include/TcpModule.h | 19 ++++++------ utils/TcpModule/src/TcpServerImpl.cpp | 34 ++++++++++++--------- utils/TcpModule/src/TcpServerImpl.h | 9 +++--- 4 files changed, 51 insertions(+), 39 deletions(-) diff --git a/test/utils/TcpModule/src/TcpModule_Test.cpp b/test/utils/TcpModule/src/TcpModule_Test.cpp index 99db5eb..cf89f72 100644 --- a/test/utils/TcpModule/src/TcpModule_Test.cpp +++ b/test/utils/TcpModule/src/TcpModule_Test.cpp @@ -25,14 +25,23 @@ namespace TcpModuleTest */ TEST(TcpModuleTest, UNIT_TcpModule_EXAMPLE_AUTO_IllegalObject) { - static void *tcpClientAccept = nullptr; TcpServerParam tcpServerparam = { .mIp = "127.0.0.1", .mPort = 9876, - .mAcceptClientFunc = [](void *object, const char *ip) -> void { - LogInfo("accept client, peer ip: %s", ip); - tcpClientAccept = object; - return; + .mAcceptClientFunc = [](void *object, const char *ip) -> bool { + LogInfo("accept client, peer ip: %s\n", ip); + if (nullptr != object) { + AcceptClientWrite(object, "client accept send data.", strlen("client accept send data.")); + } + return true; + }, + .mClientAcceptParam = { + .mReadFunc = [](const void *data, const ssize_t len, const void *object) -> void { + LogInfo("client accept read data: %s\n", (char *)data); + }, + .mClosedFunc = [](const void *object) -> void { + LogInfo("client accept closed.\n"); + }, }, }; TcpClientParam param = { @@ -42,6 +51,9 @@ TEST(TcpModuleTest, UNIT_TcpModule_EXAMPLE_AUTO_IllegalObject) LogInfo("read data: %s", (char *)data); return; }, + .mClosedFunc = [](const void *object) -> void { + LogInfo("tcp client closed.\n"); + }, }; CreateLogModule(); ILogInit(LOG_INSTANCE_TYPE_END); @@ -49,11 +61,7 @@ TEST(TcpModuleTest, UNIT_TcpModule_EXAMPLE_AUTO_IllegalObject) std::this_thread::sleep_for(std::chrono::milliseconds(500)); void *tcpClient = CreateTcpClient(param); std::this_thread::sleep_for(std::chrono::milliseconds(100)); - TcpClientWrite(tcpClient, "123456789", strlen("123456789")); - std::this_thread::sleep_for(std::chrono::milliseconds(100)); - if (nullptr != tcpClientAccept) { - AcceptClientWrite(tcpClientAccept, "9876543210", strlen("9876543210")); - } + TcpClientWrite(tcpClient, "client send data.", strlen("client send data.")); std::this_thread::sleep_for(std::chrono::milliseconds(1000)); if (nullptr != tcpClient) { FreeTcpClient(tcpClient); diff --git a/utils/TcpModule/include/TcpModule.h b/utils/TcpModule/include/TcpModule.h index a8b605d..21de5c8 100644 --- a/utils/TcpModule/include/TcpModule.h +++ b/utils/TcpModule/include/TcpModule.h @@ -21,26 +21,27 @@ extern "C" { #endif typedef void (*TcpReadFunction)(const void *, const ssize_t, const void *); -typedef void (*TcpAcceptClientFunction)(void *, const char *); +typedef bool (*TcpAcceptClientFunction)(void *, const char *); typedef void (*SocketClosedFunction)(const void *); +typedef struct client_accept_parm +{ + const TcpReadFunction mReadFunc; + const SocketClosedFunction mClosedFunc; +} ClientAcceptParam; typedef struct tcp_server_parm { const char *mIp; const int mPort; - TcpAcceptClientFunction mAcceptClientFunc; + const TcpAcceptClientFunction mAcceptClientFunc; + const ClientAcceptParam mClientAcceptParam; } TcpServerParam; typedef struct tcp_parm { const char *mIp; const int mPort; - TcpReadFunction mReadFunc; - SocketClosedFunction mClosedFunc; + const TcpReadFunction mReadFunc; + const SocketClosedFunction mClosedFunc; } TcpClientParam; -typedef struct client_accept_parm -{ - TcpReadFunction mReadFunc; - SocketClosedFunction mClosedFunc; -} ClientAcceptParam; void *CreateTcpServer(const TcpServerParam param); void FreeTcpServer(void *object); void AcceptClientSetParam(void *object, const ClientAcceptParam param); diff --git a/utils/TcpModule/src/TcpServerImpl.cpp b/utils/TcpModule/src/TcpServerImpl.cpp index dee7329..9212f48 100644 --- a/utils/TcpModule/src/TcpServerImpl.cpp +++ b/utils/TcpModule/src/TcpServerImpl.cpp @@ -45,24 +45,21 @@ static void on_accept(hio_t *io) hio_setcb_close(io, on_close); hio_setcb_read(io, on_recv); - std::shared_ptr *client = NewTcpClientAccept(io); + // std::shared_ptr *client = NewTcpClientAccept(io); TcpServerImpl *server = (TcpServerImpl *)hevent_userdata(io); - server->AddClient(io, client); + server->AddClient(io); hio_read_start(io); } -TcpClientAcceptImpl::TcpClientAcceptImpl(const hio_t *io, const void *object) : mIo(io), mObjectThis(object) +TcpClientAcceptImpl::TcpClientAcceptImpl(const hio_t *io, const void *object, const ClientAcceptParam ¶m) + : mIo(io), mObjectThis(object), mParam(param) { - mParam.mReadFunc = nullptr; - mParam.mClosedFunc = nullptr; } void TcpClientAcceptImpl::SetParam(const ClientAcceptParam ¶m) { - std::lock_guard locker(mMutex); - mParam = param; + // mParam = param; } void TcpClientAcceptImpl::Readed(const void *data, size_t length) { - std::lock_guard locker(mMutex); if (nullptr != mParam.mReadFunc) { mParam.mReadFunc(data, length, mObjectThis); return; @@ -80,7 +77,6 @@ ssize_t TcpClientAcceptImpl::Write(const void *data, size_t length) } void TcpClientAcceptImpl::Closed(void) { - std::lock_guard locker(mMutex); if (nullptr != mParam.mClosedFunc) { mParam.mClosedFunc(mObjectThis); return; @@ -138,19 +134,27 @@ void TcpServerImpl::Loop(void) } hloop_run(mLoop); } -void TcpServerImpl::AddClient(hio_t *io, std::shared_ptr *client) +void TcpServerImpl::AddClient(hio_t *io) { - std::lock_guard locker(mMutex); + mMutex.lock(); char localaddrstr[SOCKADDR_STRLEN] = {0}; char peeraddrstr[SOCKADDR_STRLEN] = {0}; LogInfo("accept connfd=%d [%s] <= [%s]\n", hio_fd(io), SOCKADDR_STR(hio_localaddr(io), localaddrstr), SOCKADDR_STR(hio_peeraddr(io), peeraddrstr)); - mClients[hio_fd(io)] = client; + std::shared_ptr *addClient = NewTcpClientAccept(io, mParam.mClientAcceptParam); + mClients[hio_fd(io)] = addClient; if (mParam.mAcceptClientFunc) { - mParam.mAcceptClientFunc(client, peeraddrstr); + if (mParam.mAcceptClientFunc(addClient, peeraddrstr) == true) { + mMutex.unlock(); + return; + } + LogWarning("User did not accept client.\n"); } + mMutex.unlock(); + hio_close(io); + LogWarning("AddClient failed.\n"); } std::shared_ptr *TcpServerImpl::GetClient(hio_t *io) { @@ -210,7 +214,7 @@ std::shared_ptr *NewTcpServer(const TcpServerParam ¶m) impl->mTcpServer = std::make_shared(param); return (std::shared_ptr *)(((char *)impl) + sizeof(ITcpServerHeader)); } -std::shared_ptr *NewTcpClientAccept(const hio_t *io) +std::shared_ptr *NewTcpClientAccept(const hio_t *io, const ClientAcceptParam ¶m) { LogInfo("Create tcp server object.\n"); TcpClientAccept *impl = (TcpClientAccept *)malloc(sizeof(TcpClientAccept)); @@ -223,6 +227,6 @@ std::shared_ptr *NewTcpClientAccept(const hio_t *io) impl->mHeader.mCheckName = GetTcpClientAcceptName(); std::shared_ptr *objectThis = (std::shared_ptr *)(((char *)impl) + sizeof(ITcpServerHeader)); - impl->mTcpClientAccept = std::make_shared(io, objectThis); + impl->mTcpClientAccept = std::make_shared(io, objectThis, param); return objectThis; } \ No newline at end of file diff --git a/utils/TcpModule/src/TcpServerImpl.h b/utils/TcpModule/src/TcpServerImpl.h index 5e92655..c5e1a3c 100644 --- a/utils/TcpModule/src/TcpServerImpl.h +++ b/utils/TcpModule/src/TcpServerImpl.h @@ -25,7 +25,7 @@ class TcpClientAcceptImpl : public ITcpClientAccept, public std::enable_shared_from_this { public: - TcpClientAcceptImpl(const hio_t *io, const void *object); + TcpClientAcceptImpl(const hio_t *io, const void *object, const ClientAcceptParam ¶m); virtual ~TcpClientAcceptImpl() = default; void SetParam(const ClientAcceptParam ¶m) override; void Readed(const void *data, size_t length) override; @@ -33,10 +33,9 @@ public: void Closed(void) override; private: - std::mutex mMutex; const hio_t *mIo; - ClientAcceptParam mParam; const void *mObjectThis; + const ClientAcceptParam mParam; }; class TcpServerImpl : public ITcpServer, public std::enable_shared_from_this { @@ -46,7 +45,7 @@ public: void Init(void) override; void UnInit(void) override; void Loop(void); - void AddClient(hio_t *io, std::shared_ptr *client); + void AddClient(hio_t *io); std::shared_ptr *GetClient(hio_t *io); void RemoveClient(hio_t *io); void FreeClients(void); @@ -60,5 +59,5 @@ private: std::map *> mClients; }; std::shared_ptr *NewTcpServer(const TcpServerParam ¶m); -std::shared_ptr *NewTcpClientAccept(const hio_t *io); +std::shared_ptr *NewTcpClientAccept(const hio_t *io, const ClientAcceptParam ¶m); #endif \ No newline at end of file From 7fd6c72864c5b894329bb1724376f2aa5be20e7a Mon Sep 17 00:00:00 2001 From: Fancy code <258828110.@qq.com> Date: Thu, 11 Apr 2024 20:25:49 +0800 Subject: [PATCH 06/10] Fixed:TcpModule. --- utils/TcpModule/src/TcpClientImpl.cpp | 18 ++++++++++-------- utils/TcpModule/src/TcpServerImpl.cpp | 25 +++++++++++++++++++------ utils/TcpModule/src/TcpServerImpl.h | 1 + 3 files changed, 30 insertions(+), 14 deletions(-) diff --git a/utils/TcpModule/src/TcpClientImpl.cpp b/utils/TcpModule/src/TcpClientImpl.cpp index a7c2b6f..a210ddf 100644 --- a/utils/TcpModule/src/TcpClientImpl.cpp +++ b/utils/TcpModule/src/TcpClientImpl.cpp @@ -62,16 +62,14 @@ void TcpClientImpl::Init(void) } void TcpClientImpl::UnInit(void) { - if (nullptr != mLoop) { - LogInfo("Stop loop.\n"); - hloop_stop(mLoop); + if (nullptr != mIo) { + LogInfo("Close io.\n"); + hio_close(mIo); + mIo = nullptr; } if (mTcpClientThread.joinable()) { mTcpClientThread.join(); } - hloop_free(&mLoop); - mLoop = nullptr; - mIo = nullptr; } void TcpClientImpl::Readed(const void *data, size_t length) { @@ -93,9 +91,11 @@ void TcpClientImpl::Closed(void) { if (nullptr != mParam.mClosedFunc) { mParam.mClosedFunc(mObjectThis); - return; } - LogWarning("mParam.mClosedFunc is null\n"); + if (nullptr != mLoop) { + LogInfo("Stop loop.\n"); + hloop_stop(mLoop); + } } void TcpClientImpl::Loop(void) { @@ -104,6 +104,8 @@ void TcpClientImpl::Loop(void) return; } hloop_run(mLoop); + hloop_free(&mLoop); + mLoop = nullptr; } std::shared_ptr *NewTcpClient(const TcpClientParam ¶m) { diff --git a/utils/TcpModule/src/TcpServerImpl.cpp b/utils/TcpModule/src/TcpServerImpl.cpp index 9212f48..b67b561 100644 --- a/utils/TcpModule/src/TcpServerImpl.cpp +++ b/utils/TcpModule/src/TcpServerImpl.cpp @@ -21,6 +21,12 @@ static void on_close(hio_t *io) TcpServerImpl *server = (TcpServerImpl *)hevent_userdata(io); server->RemoveClient(io); } +static void server_on_close(hio_t *io) +{ + LogInfo("server_on_close fd=%d error=%d\n", hio_fd(io), hio_error(io)); + TcpServerImpl *server = (TcpServerImpl *)hevent_userdata(io); + server->Closed(); +} static void on_recv(hio_t *io, void *buf, int readbytes) { LogInfo("on_recv fd=%d readbytes=%d\n", hio_fd(io), readbytes); @@ -104,6 +110,7 @@ void TcpServerImpl::Init(void) LogInfo("listenfd=%d\n", hio_fd(listenio)); hevent_set_userdata(listenio, this); mIo = listenio; + hio_setcb_close(mIo, server_on_close); std::shared_ptr server = shared_from_this(); std::shared_ptr impl = std::dynamic_pointer_cast(server); auto recvThread = [](std::shared_ptr tcpServer) { @@ -115,16 +122,13 @@ void TcpServerImpl::UnInit(void) { LogInfo("UnInit TcpServerImpl\n"); FreeClients(); - if (nullptr != mLoop) { - LogInfo("Stop loop.\n"); - hloop_stop(mLoop); + if (nullptr != mIo) { + hio_close(mIo); + mIo = nullptr; } if (mTcpServerThread.joinable()) { mTcpServerThread.join(); } - hloop_free(&mLoop); - mLoop = nullptr; - mIo = nullptr; } void TcpServerImpl::Loop(void) { @@ -133,6 +137,8 @@ void TcpServerImpl::Loop(void) return; } hloop_run(mLoop); + hloop_free(&mLoop); + mLoop = nullptr; } void TcpServerImpl::AddClient(hio_t *io) { @@ -200,6 +206,13 @@ void TcpServerImpl::FreeClients(void) } mClients.clear(); } +void TcpServerImpl::Closed(void) +{ + if (nullptr != mLoop) { + LogInfo("Stop loop.\n"); + hloop_stop(mLoop); + } +} std::shared_ptr *NewTcpServer(const TcpServerParam ¶m) { LogInfo("Create tcp server object.\n"); diff --git a/utils/TcpModule/src/TcpServerImpl.h b/utils/TcpModule/src/TcpServerImpl.h index c5e1a3c..68e85ac 100644 --- a/utils/TcpModule/src/TcpServerImpl.h +++ b/utils/TcpModule/src/TcpServerImpl.h @@ -49,6 +49,7 @@ public: std::shared_ptr *GetClient(hio_t *io); void RemoveClient(hio_t *io); void FreeClients(void); + void Closed(void); private: std::mutex mMutex; From 2f6678c7eb59fa1253d8294ab3b9d805886b0635 Mon Sep 17 00:00:00 2001 From: Fancy code <258828110.@qq.com> Date: Thu, 11 Apr 2024 20:46:26 +0800 Subject: [PATCH 07/10] Improve:TcpModule. --- utils/TcpModule/include/TcpModule.h | 3 ++- utils/TcpModule/src/ITcpServer.cpp | 2 +- utils/TcpModule/src/ITcpServer.h | 2 +- utils/TcpModule/src/TcpModule.cpp | 18 ++++++++++++------ utils/TcpModule/src/TcpServerImpl.cpp | 7 +++++-- utils/TcpModule/src/TcpServerImpl.h | 2 +- 6 files changed, 22 insertions(+), 12 deletions(-) diff --git a/utils/TcpModule/include/TcpModule.h b/utils/TcpModule/include/TcpModule.h index 21de5c8..3f2156f 100644 --- a/utils/TcpModule/include/TcpModule.h +++ b/utils/TcpModule/include/TcpModule.h @@ -44,8 +44,9 @@ typedef struct tcp_parm } TcpClientParam; void *CreateTcpServer(const TcpServerParam param); void FreeTcpServer(void *object); -void AcceptClientSetParam(void *object, const ClientAcceptParam param); +// void AcceptClientSetParam(void *object, const ClientAcceptParam param); ssize_t AcceptClientWrite(void *object, const void *buf, const size_t bufLenght); +void AcceptClientClose(void *object); void *CreateTcpClient(const TcpClientParam param); void FreeTcpClient(void *object); ssize_t TcpClientWrite(void *object, const void *buf, const size_t bufLenght); diff --git a/utils/TcpModule/src/ITcpServer.cpp b/utils/TcpModule/src/ITcpServer.cpp index f61b8c4..a26c05c 100644 --- a/utils/TcpModule/src/ITcpServer.cpp +++ b/utils/TcpModule/src/ITcpServer.cpp @@ -16,7 +16,7 @@ #include "ILog.h" #include "TcpModule.h" #include -void ITcpClientAccept::SetParam(const ClientAcceptParam ¶m) +void ITcpClientAccept::Close(void) { } void ITcpClientAccept::Readed(const void *data, size_t length) diff --git a/utils/TcpModule/src/ITcpServer.h b/utils/TcpModule/src/ITcpServer.h index 5f72f50..098ad0b 100644 --- a/utils/TcpModule/src/ITcpServer.h +++ b/utils/TcpModule/src/ITcpServer.h @@ -22,7 +22,7 @@ class ITcpClientAccept public: ITcpClientAccept() = default; virtual ~ITcpClientAccept() = default; - virtual void SetParam(const ClientAcceptParam ¶m); + virtual void Close(void); virtual void Readed(const void *data, size_t length); virtual ssize_t Write(const void *data, size_t length); virtual void Closed(void); diff --git a/utils/TcpModule/src/TcpModule.cpp b/utils/TcpModule/src/TcpModule.cpp index ab28bc9..4101b25 100644 --- a/utils/TcpModule/src/TcpModule.cpp +++ b/utils/TcpModule/src/TcpModule.cpp @@ -58,12 +58,12 @@ void FreeTcpServer(void *object) free(((char *)object) - sizeof(ITcpServerHeader)); // TODO: bug? } } -void AcceptClientSetParam(void *object, const ClientAcceptParam param) -{ - if (TcpClientAcceptObjectCheck(object) == true) { - (*(std::shared_ptr *)object)->SetParam(param); - } -} +// void AcceptClientSetParam(void *object, const ClientAcceptParam param) +// { +// if (TcpClientAcceptObjectCheck(object) == true) { +// (*(std::shared_ptr *)object)->SetParam(param); +// } +// } ssize_t AcceptClientWrite(void *object, const void *buf, const size_t bufLenght) { if (TcpClientAcceptObjectCheck(object) == true) { @@ -71,6 +71,12 @@ ssize_t AcceptClientWrite(void *object, const void *buf, const size_t bufLenght) } return TCP_MODULE_WRITE_ERROR; } +void AcceptClientClose(void *object) +{ + if (TcpClientAcceptObjectCheck(object) == true) { + return (*(std::shared_ptr *)object)->Close(); + } +} void *CreateTcpClient(const TcpClientParam param) { std::shared_ptr *client = TcpModuleMakePtr::GetInstance()->CreateTcpClient(param); diff --git a/utils/TcpModule/src/TcpServerImpl.cpp b/utils/TcpModule/src/TcpServerImpl.cpp index b67b561..231a1c2 100644 --- a/utils/TcpModule/src/TcpServerImpl.cpp +++ b/utils/TcpModule/src/TcpServerImpl.cpp @@ -60,9 +60,12 @@ TcpClientAcceptImpl::TcpClientAcceptImpl(const hio_t *io, const void *object, co : mIo(io), mObjectThis(object), mParam(param) { } -void TcpClientAcceptImpl::SetParam(const ClientAcceptParam ¶m) +void TcpClientAcceptImpl::Close(void) { - // mParam = param; + if (nullptr != mIo) { + hio_t *io = (hio_t *)mIo; + hio_close(io); + } } void TcpClientAcceptImpl::Readed(const void *data, size_t length) { diff --git a/utils/TcpModule/src/TcpServerImpl.h b/utils/TcpModule/src/TcpServerImpl.h index 68e85ac..007f63f 100644 --- a/utils/TcpModule/src/TcpServerImpl.h +++ b/utils/TcpModule/src/TcpServerImpl.h @@ -27,7 +27,7 @@ class TcpClientAcceptImpl : public ITcpClientAccept, public std::enable_shared_f public: TcpClientAcceptImpl(const hio_t *io, const void *object, const ClientAcceptParam ¶m); virtual ~TcpClientAcceptImpl() = default; - void SetParam(const ClientAcceptParam ¶m) override; + void Close(void) override; void Readed(const void *data, size_t length) override; ssize_t Write(const void *data, size_t length) override; void Closed(void) override; From bb0180882ce747cc3f0cd343fd3483e4900380de Mon Sep 17 00:00:00 2001 From: Fancy code <258828110.@qq.com> Date: Fri, 12 Apr 2024 20:10:13 +0800 Subject: [PATCH 08/10] Improve:AppManager tcp function. --- .../MissionManager/src/TestMissionState.cpp | 2 +- build/cmake/toolchain/linux.toolchain.cmake | 5 +- middleware/AppManager/CMakeLists.txt | 3 +- middleware/AppManager/build/app_manager.cmake | 12 ++- middleware/AppManager/include/IAppManager.h | 36 ++++++- middleware/AppManager/src/AppClient.cpp | 51 ++++++++++ middleware/AppManager/src/AppClient.h | 33 +++++++ middleware/AppManager/src/AppManager.cpp | 94 ++++++++++++++++--- middleware/AppManager/src/AppManager.h | 13 ++- middleware/AppManager/src/IAppManager.cpp | 22 +++++ .../AppManager/src/IAppProtocolHandle.cpp | 81 ++++++++++++++++ .../AppManager/src/IAppProtocolHandle.h | 40 +++++--- .../src/Protocol/SixFrame/SixFrameHandle.cpp | 89 +++++++++++++++++- .../src/Protocol/SixFrame/SixFrameHandle.h | 16 +++- .../AppManager/src/AppManager_Test.cpp | 5 +- .../middleware/AppManager/tool/CMakeLists.txt | 1 + .../tool/include/AppManagerTestTool.h | 5 + .../AppManager/tool/src/AppManagerMock.cpp | 12 +-- .../tool/src/AppManagerTestTool.cpp | 38 ++++++++ .../AppManager/tool/src/AppMonitorMock.cpp | 28 ++++++ .../AppManager/tool/src/AppMonitorMock.h | 6 ++ .../AppManager/tool/src/ServersMock.cpp | 2 +- utils/TcpModule/include/TcpModule.h | 1 - utils/TcpModule/src/TcpClientImpl.cpp | 3 + utils/TcpModule/src/TcpClientImpl.h | 2 + utils/TcpModule/src/TcpModule.cpp | 6 -- 26 files changed, 547 insertions(+), 59 deletions(-) create mode 100644 middleware/AppManager/src/AppClient.cpp create mode 100644 middleware/AppManager/src/AppClient.h create mode 100644 middleware/AppManager/src/IAppProtocolHandle.cpp diff --git a/application/MissionManager/src/TestMissionState.cpp b/application/MissionManager/src/TestMissionState.cpp index 5460ff4..cfb1f80 100644 --- a/application/MissionManager/src/TestMissionState.cpp +++ b/application/MissionManager/src/TestMissionState.cpp @@ -22,7 +22,7 @@ void TestMissionState::GoInState() { MissionState::GoInState(); LogInfo(" ========== TestMissionState::GoInState.\n"); - AppParam mAppParam(APP_MANAGER_HTTP_SERVER_IP, APP_MANAGER_HTTP_SERVER_PORT); // TODO: + AppParam mAppParam(APP_MANAGER_DEVICE_IP, APP_MANAGER_HTTP_SERVER_PORT, APP_MANAGER_TCP_SERVER_PORT); // TODO: IAppManager::GetInstance()->Init(mAppParam); std::shared_ptr monitor = std::dynamic_pointer_cast(MissionState::shared_from_this()); diff --git a/build/cmake/toolchain/linux.toolchain.cmake b/build/cmake/toolchain/linux.toolchain.cmake index 2f4a174..5efb0d2 100755 --- a/build/cmake/toolchain/linux.toolchain.cmake +++ b/build/cmake/toolchain/linux.toolchain.cmake @@ -68,7 +68,8 @@ set(CURL_SHARED_LIBS_PATH "/mnt/mmc") # ------------ build curl + openssl ------------ end # ------------ build AppManager ------------ # -# set(APP_MANAGER_HTTP_SERVER_IP "localhost") -set(APP_MANAGER_HTTP_SERVER_IP "192.168.1.29") +set(APP_MANAGER_DEVICE_IP "localhost") +# set(APP_MANAGER_DEVICE_IP "192.168.1.29") set(APP_MANAGER_HTTP_SERVER_PORT "8080") +set(APP_MANAGER_TCP_SERVER_PORT "9876") # ------------ build AppManager end ------------ # \ No newline at end of file diff --git a/middleware/AppManager/CMakeLists.txt b/middleware/AppManager/CMakeLists.txt index aa933a3..fb40520 100644 --- a/middleware/AppManager/CMakeLists.txt +++ b/middleware/AppManager/CMakeLists.txt @@ -11,6 +11,7 @@ include_directories( ${UTILS_SOURCE_PATH}/Log/include ${UTILS_SOURCE_PATH}/FxHttpServer/include ${UTILS_SOURCE_PATH}/WebServer/include + ${UTILS_SOURCE_PATH}/TcpModule/include ${HAL_SOURCE_PATH}/include ${EXTERNAL_SOURCE_PATH}/cJSON-1.7.17 ) @@ -24,7 +25,7 @@ aux_source_directory(./src/Protocol/SixFrame SRC_FILES) set(TARGET_NAME AppManager) add_library(${TARGET_NAME} STATIC ${SRC_FILES}) -target_link_libraries(${TARGET_NAME} WebServer Hal cjson-static StatusCode Log) +target_link_libraries(${TARGET_NAME} WebServer TcpModule Hal cjson-static StatusCode Log) if ("${COMPILE_IMPROVE_SUPPORT}" MATCHES "true") add_custom_target( diff --git a/middleware/AppManager/build/app_manager.cmake b/middleware/AppManager/build/app_manager.cmake index 0f3fd41..7e7bd08 100644 --- a/middleware/AppManager/build/app_manager.cmake +++ b/middleware/AppManager/build/app_manager.cmake @@ -1,8 +1,8 @@ -if (NOT DEFINED APP_MANAGER_HTTP_SERVER_IP) - set(APP_MANAGER_HTTP_SERVER_IP "localhost") +if (NOT DEFINED APP_MANAGER_DEVICE_IP) + set(APP_MANAGER_DEVICE_IP "localhost") endif() -add_definitions(-DAPP_MANAGER_HTTP_SERVER_IP=\"${APP_MANAGER_HTTP_SERVER_IP}\") +add_definitions(-DAPP_MANAGER_DEVICE_IP=\"${APP_MANAGER_DEVICE_IP}\") if (NOT DEFINED APP_MANAGER_HTTP_SERVER_PORT) message(FATAL_ERROR "You should set http listen port. @@ -10,3 +10,9 @@ if (NOT DEFINED APP_MANAGER_HTTP_SERVER_PORT) Refer to:${IPC_SDK_PATH}/builde/cmake/toolchain/linux.toolchain.cmake") endif() add_definitions(-DAPP_MANAGER_HTTP_SERVER_PORT=${APP_MANAGER_HTTP_SERVER_PORT}) +if (NOT DEFINED APP_MANAGER_TCP_SERVER_PORT) + message(FATAL_ERROR "You should set TCP listen port. + Example: set(APP_MANAGER_TCP_SERVER_PORT \"8888\") + Refer to:${IPC_SDK_PATH}/builde/cmake/toolchain/linux.toolchain.cmake") +endif() +add_definitions(-DAPP_MANAGER_TCP_SERVER_PORT=${APP_MANAGER_TCP_SERVER_PORT}) diff --git a/middleware/AppManager/include/IAppManager.h b/middleware/AppManager/include/IAppManager.h index 5cd7a7e..98e7133 100644 --- a/middleware/AppManager/include/IAppManager.h +++ b/middleware/AppManager/include/IAppManager.h @@ -151,6 +151,24 @@ enum class FileCopy SUPPORT_COPY, END }; +enum class RecordingStatus +{ + RECORDING_STOP = 0, + RECORDING_START, + END +}; +enum class MicrophoneStatus +{ + OFF = 0, + ON, + END +}; +enum class BatteryStatus +{ + CHARGING = 0, + NOT_CHARGING, + END +}; typedef struct app_get_product_info { app_get_product_info() @@ -327,6 +345,18 @@ typedef struct app_get_thumbnail const std::string mFile; std::string mThumbnail; } AppGetThumbnail; +class VAppClient +{ +public: + VAppClient() = default; + virtual ~VAppClient() = default; + virtual void SetRecordingStatus(const RecordingStatus &status); + virtual void SetMicrophoneStatus(const MicrophoneStatus &status); + virtual void SetBatteryStatus(const BatteryStatus &status, const int &batteryCapacity); + virtual void SetSdCardStatus(const SdCardStatus &status); + virtual void DeletedFileMessage(const std::string &file, const StorageFileType &type); + virtual void CreatedFileMessage(const std::string &file, const StorageFileType &type); +}; class VAppMonitor { public: @@ -349,14 +379,16 @@ public: virtual StatusCode AppPlayback(const PlayBackEvent &event); virtual StatusCode UploadFile(AppUploadFile ¶m); virtual StatusCode GetThumbnail(AppGetThumbnail ¶m); + virtual StatusCode AppClientConnected(std::shared_ptr &client); }; typedef struct app_param { - app_param(const char *ip, const int port) : mIP(ip), mPort(port) + app_param(const char *ip, const int &httpPort, const int &tcpPort) : mIP(ip), mHttpPort(httpPort), mTcpPort(tcpPort) { } const char *mIP; - const int mPort; + const int mHttpPort; + const int mTcpPort; } AppParam; class IAppManager { diff --git a/middleware/AppManager/src/AppClient.cpp b/middleware/AppManager/src/AppClient.cpp new file mode 100644 index 0000000..acc4186 --- /dev/null +++ b/middleware/AppManager/src/AppClient.cpp @@ -0,0 +1,51 @@ +/* + * Copyright (c) 2023 Fancy Code. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include "AppClient.h" +#include "IAppProtocolHandle.h" +#include "TcpModule.h" +AppClient::AppClient(const void *clientObject) : mClientObject(clientObject) +{ +} +void AppClient::SetRecordingStatus(const RecordingStatus &status) +{ + std::shared_ptr packet = IAppProtocolHandle::GetInstance()->SetRecordingStatus(status); + AcceptClientWrite((void *)mClientObject, packet->mData, packet->mDataLength); +} +void AppClient::SetMicrophoneStatus(const MicrophoneStatus &status) +{ + std::shared_ptr packet = IAppProtocolHandle::GetInstance()->SetMicrophoneStatus(status); + AcceptClientWrite((void *)mClientObject, packet->mData, packet->mDataLength); +} +void AppClient::SetBatteryStatus(const BatteryStatus &status, const int &batteryCapacity) +{ + std::shared_ptr packet = + IAppProtocolHandle::GetInstance()->SetBatteryStatus(status, batteryCapacity); + AcceptClientWrite((void *)mClientObject, packet->mData, packet->mDataLength); +} +void AppClient::SetSdCardStatus(const SdCardStatus &status) +{ + std::shared_ptr packet = IAppProtocolHandle::GetInstance()->SetSdCardStatus(status); + AcceptClientWrite((void *)mClientObject, packet->mData, packet->mDataLength); +} +void AppClient::DeletedFileMessage(const std::string &file, const StorageFileType &type) +{ + std::shared_ptr packet = IAppProtocolHandle::GetInstance()->DeletedFileMessage(file, type); + AcceptClientWrite((void *)mClientObject, packet->mData, packet->mDataLength); +} +void AppClient::CreatedFileMessage(const std::string &file, const StorageFileType &type) +{ + std::shared_ptr packet = IAppProtocolHandle::GetInstance()->CreatedFileMessage(file, type); + AcceptClientWrite((void *)mClientObject, packet->mData, packet->mDataLength); +} \ No newline at end of file diff --git a/middleware/AppManager/src/AppClient.h b/middleware/AppManager/src/AppClient.h new file mode 100644 index 0000000..de51b09 --- /dev/null +++ b/middleware/AppManager/src/AppClient.h @@ -0,0 +1,33 @@ +/* + * Copyright (c) 2023 Fancy Code. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef APP_CLIENT_H +#define APP_CLIENT_H +#include "IAppManager.h" +class AppClient : public VAppClient +{ +public: + AppClient(const void *clientObject); + virtual ~AppClient() = default; + void SetRecordingStatus(const RecordingStatus &status) override; + void SetMicrophoneStatus(const MicrophoneStatus &status) override; + void SetBatteryStatus(const BatteryStatus &status, const int &batteryCapacity) override; + void SetSdCardStatus(const SdCardStatus &status) override; + void DeletedFileMessage(const std::string &file, const StorageFileType &type) override; + void CreatedFileMessage(const std::string &file, const StorageFileType &type) override; + +private: + const void *mClientObject; +}; +#endif \ No newline at end of file diff --git a/middleware/AppManager/src/AppManager.cpp b/middleware/AppManager/src/AppManager.cpp index 6736920..508dc0c 100644 --- a/middleware/AppManager/src/AppManager.cpp +++ b/middleware/AppManager/src/AppManager.cpp @@ -13,15 +13,15 @@ * limitations under the License. */ #include "AppManager.h" +#include "AppClient.h" #include "AppManagerMakePtr.h" -// #include "FxHttpServer.h" #include "IHalCpp.h" #include "ILog.h" +#include "TcpModule.h" #include "WebServer.h" AppManager::AppManager() { - // mHttpServerRuning = false; - mProtocolHandle = std::make_shared(); + mTcpServer = nullptr; } const StatusCode AppManager::Init(const AppParam ¶m) { @@ -32,26 +32,53 @@ const StatusCode AppManager::Init(const AppParam ¶m) return CreateStatusCode(STATUS_CODE_NOT_OK); } wifi->OpenApMode(); - AppManagerMakePtr::GetInstance()->CreateProtocolHandle(mProtocolHandle); + std::shared_ptr protocolHandle; + AppManagerMakePtr::GetInstance()->CreateProtocolHandle(protocolHandle); + IAppProtocolHandle::GetInstance(&protocolHandle); HttpServerStart(param); + TcpServerStart(param); return CreateStatusCode(STATUS_CODE_OK); } const StatusCode AppManager::UnInit(void) { HttpServerStop(); - mProtocolHandle.reset(); + TcpServerStop(); + std::shared_ptr protocolHandle = std::make_shared(); + IAppProtocolHandle::GetInstance(&protocolHandle); + mAppMonitor.reset(); return CreateStatusCode(STATUS_CODE_OK); } const StatusCode AppManager::SetAppMonitor(std::shared_ptr &monitor) { - mProtocolHandle->SetAppMonitor(monitor); + IAppProtocolHandle::GetInstance()->SetAppMonitor(monitor); + mAppMonitor = monitor; return CreateStatusCode(STATUS_CODE_OK); } void AppManager::AppRequestHandle(const char *url, const unsigned int urlLength, ResponseHandle responseHandle, void *context) { - // - mProtocolHandle->RequestHandle(url, urlLength, responseHandle, context); + IAppProtocolHandle::GetInstance()->RequestHandle(url, urlLength, responseHandle, context); +} +void AppManager::AppRequestHandleTcp(const char *data, const unsigned int dataLength, ResponseHandle responseHandle, + void *context) +{ +} +void AppManager::AppClientConnected(const void *client, const char *ip) +{ + void *object = (void *)client; + mAppClients[object] = std::make_shared(client); + mAppMonitor->AppClientConnected(mAppClients[object]); +} +void AppManager::AppClientClosed(const void *client) +{ + void *object = (void *)client; + auto it = mAppClients.find(object); + if (it != mAppClients.end()) { + mAppClients.erase(it); + } + else { + LogError("App client not exit.\n"); + } } void AppManager::HttpServerStart(const AppParam ¶m) { @@ -63,7 +90,6 @@ void AppManager::HttpServerStart(const AppParam ¶m) } void AppManager::HttpServerStop(void) { - // FxHttpServerExit(); WebServerExit(); if (mHttpSever.joinable()) { mHttpSever.join(); @@ -81,9 +107,53 @@ void AppManager::HttpServerThread(const AppParam ¶m) appImpl->AppRequestHandle(url, urlLength, responseHandle, context); } }; - // FxHttpServerInit(httpHandle, 8080); - // FxHttpServerUnInit(); - WebServerParam web = {.mIp = param.mIP, .mPort = param.mPort, .mHttpRequestHandle = httpHandle}; + WebServerParam web = {.mIp = param.mIP, .mPort = param.mHttpPort, .mHttpRequestHandle = httpHandle}; WebServerInit(web); WebServerUnInit(); +} +void AppManager::TcpServerStart(const AppParam ¶m) +{ + auto acceptClientFunc = [](void *object, const char *ip) -> bool { + LogInfo("accept client, peer ip: %s\n", ip); + if (nullptr != object) { + std::shared_ptr app = IAppManager::GetInstance(); + std::shared_ptr appImpl = std::dynamic_pointer_cast(app); + if (appImpl) { + appImpl->AppClientConnected(object, ip); + } + return true; + } + return false; + }; + auto readFunc = [](const void *data, const ssize_t len, const void *object) -> void { + LogInfo("read data: %s\n", (char *)data); + }; + auto closedFunc = [](const void *object) -> void { + LogInfo("closed.\n"); + std::shared_ptr app = IAppManager::GetInstance(); + std::shared_ptr appImpl = std::dynamic_pointer_cast(app); + if (appImpl) { + appImpl->AppClientClosed(object); + } + }; + TcpServerParam tcpServerparam = { + .mIp = param.mIP, + .mPort = param.mTcpPort, + .mAcceptClientFunc = acceptClientFunc, + .mClientAcceptParam = + { + .mReadFunc = readFunc, + .mClosedFunc = closedFunc, + }, + }; + mTcpServer = CreateTcpServer(tcpServerparam); + if (nullptr == mTcpServer) { + LogError("Create tcp server failed.\n"); + } +} +void AppManager::TcpServerStop(void) +{ + if (nullptr != mTcpServer) { + FreeTcpServer(mTcpServer); + } } \ No newline at end of file diff --git a/middleware/AppManager/src/AppManager.h b/middleware/AppManager/src/AppManager.h index fa3e3db..308a08d 100644 --- a/middleware/AppManager/src/AppManager.h +++ b/middleware/AppManager/src/AppManager.h @@ -16,6 +16,7 @@ #define APP_MANAGER_H #include "IAppManager.h" #include "IAppProtocolHandle.h" +#include #include class AppManager : public IAppManager, public std::enable_shared_from_this { @@ -26,6 +27,10 @@ public: const StatusCode UnInit(void) override; const StatusCode SetAppMonitor(std::shared_ptr &monitor) override; void AppRequestHandle(const char *url, const unsigned int urlLength, ResponseHandle responseHandle, void *context); + void AppRequestHandleTcp(const char *data, const unsigned int dataLength, ResponseHandle responseHandle, + void *context); + void AppClientConnected(const void *client, const char *ip); + void AppClientClosed(const void *client); private: void HttpServerStart(const AppParam ¶m); @@ -33,9 +38,15 @@ private: void HttpServerThread(const AppParam ¶m); private: - // bool mHttpServerRuning; + void TcpServerStart(const AppParam ¶m); + void TcpServerStop(void); + +private: std::thread mHttpSever; std::shared_ptr mProtocolHandle; + void *mTcpServer; + std::shared_ptr mAppMonitor; + std::map> mAppClients; }; #endif diff --git a/middleware/AppManager/src/IAppManager.cpp b/middleware/AppManager/src/IAppManager.cpp index d01955d..cf76be5 100644 --- a/middleware/AppManager/src/IAppManager.cpp +++ b/middleware/AppManager/src/IAppManager.cpp @@ -14,6 +14,24 @@ */ #include "IAppManager.h" #include "ILog.h" +void VAppClient::SetRecordingStatus(const RecordingStatus &status) +{ +} +void VAppClient::SetMicrophoneStatus(const MicrophoneStatus &status) +{ +} +void VAppClient::SetBatteryStatus(const BatteryStatus &status, const int &batteryCapacity) +{ +} +void VAppClient::SetSdCardStatus(const SdCardStatus &status) +{ +} +void VAppClient::DeletedFileMessage(const std::string &file, const StorageFileType &type) +{ +} +void VAppClient::CreatedFileMessage(const std::string &file, const StorageFileType &type) +{ +} StatusCode VAppMonitor::GetProductInfo(AppGetProductInfo ¶m) { return CreateStatusCode(STATUS_CODE_VIRTUAL_FUNCTION); @@ -82,6 +100,10 @@ StatusCode VAppMonitor::GetThumbnail(AppGetThumbnail ¶m) { return CreateStatusCode(STATUS_CODE_VIRTUAL_FUNCTION); } +StatusCode VAppMonitor::AppClientConnected(std::shared_ptr &client) +{ + return CreateStatusCode(STATUS_CODE_VIRTUAL_FUNCTION); +} std::shared_ptr &IAppManager::GetInstance(std::shared_ptr *impl) { static auto instance = std::make_shared(); diff --git a/middleware/AppManager/src/IAppProtocolHandle.cpp b/middleware/AppManager/src/IAppProtocolHandle.cpp new file mode 100644 index 0000000..7c435ff --- /dev/null +++ b/middleware/AppManager/src/IAppProtocolHandle.cpp @@ -0,0 +1,81 @@ +/* + * Copyright (c) 2023 Fancy Code. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include "IAppProtocolHandle.h" +#include "ILog.h" +protocol_packet::~protocol_packet() +{ + if (nullptr != mData) { + free(mData); + mData = nullptr; + } +} +std::shared_ptr &IAppProtocolHandle::GetInstance(std::shared_ptr *impl) +{ + static auto instance = std::make_shared(); + if (impl) { + if (instance.use_count() == 1) { + LogInfo("Instance changed succeed.\n"); + instance = *impl; + } + else { + LogError("Can't changing the instance becase of using by some one.\n"); + } + } + return instance; +} +void IAppProtocolHandle::Init(void) +{ +} +void IAppProtocolHandle::UnInit(void) +{ +} +void IAppProtocolHandle::RequestHandle(const char *url, const unsigned int &urlLength, ResponseHandle responseHandle, + void *context) +{ +} +void IAppProtocolHandle::RequestHandleTcp(const char *data, const unsigned int &dataLength, + ResponseHandle responseHandle, void *context) +{ +} +void IAppProtocolHandle::SetAppMonitor(std::shared_ptr &monitor) +{ +} +std::shared_ptr IAppProtocolHandle::SetRecordingStatus(const RecordingStatus &status) +{ + return std::make_shared(); +} +std::shared_ptr IAppProtocolHandle::SetMicrophoneStatus(const MicrophoneStatus &status) +{ + return std::make_shared(); +} +std::shared_ptr IAppProtocolHandle::SetBatteryStatus(const BatteryStatus &status, + const int &batteryCapacity) +{ + return std::make_shared(); +} +std::shared_ptr IAppProtocolHandle::SetSdCardStatus(const SdCardStatus &status) +{ + return std::make_shared(); +} +std::shared_ptr IAppProtocolHandle::DeletedFileMessage(const std::string &file, + const StorageFileType &type) +{ + return std::make_shared(); +} +std::shared_ptr IAppProtocolHandle::CreatedFileMessage(const std::string &file, + const StorageFileType &type) +{ + return std::make_shared(); +} \ No newline at end of file diff --git a/middleware/AppManager/src/IAppProtocolHandle.h b/middleware/AppManager/src/IAppProtocolHandle.h index 4cd04d4..5e8d8e1 100644 --- a/middleware/AppManager/src/IAppProtocolHandle.h +++ b/middleware/AppManager/src/IAppProtocolHandle.h @@ -14,11 +14,24 @@ */ #ifndef I_APP_PROTOCOL_HANDLE_H #define I_APP_PROTOCOL_HANDLE_H +#include "IAppManager.h" #include "StatusCode.h" #include "WebServer.h" #include #include #include +typedef struct protocol_packet +{ + protocol_packet() : mData(nullptr), mDataLength(0) + { + } + protocol_packet(void *data, const size_t &size) : mData(data), mDataLength(size) + { + } + ~protocol_packet(); + void *mData; + size_t mDataLength; +} ProtocolPacket; class VAppDataPacket { public: @@ -30,18 +43,19 @@ class IAppProtocolHandle public: IAppProtocolHandle() = default; virtual ~IAppProtocolHandle() = default; - virtual void Init(void) - { - } - virtual void UnInit(void) - { - } - virtual void RequestHandle(const char *url, const unsigned int urlLength, ResponseHandle responseHandle, - void *context) - { - } - virtual void SetAppMonitor(std::shared_ptr &monitor) - { - } + static std::shared_ptr &GetInstance(std::shared_ptr *impl = nullptr); + virtual void Init(void); + virtual void UnInit(void); + virtual void RequestHandle(const char *url, const unsigned int &urlLength, ResponseHandle responseHandle, + void *context); + virtual void RequestHandleTcp(const char *data, const unsigned int &dataLength, ResponseHandle responseHandle, + void *context); + virtual void SetAppMonitor(std::shared_ptr &monitor); + virtual std::shared_ptr SetRecordingStatus(const RecordingStatus &status); + virtual std::shared_ptr SetMicrophoneStatus(const MicrophoneStatus &status); + virtual std::shared_ptr SetBatteryStatus(const BatteryStatus &status, const int &batteryCapacity); + virtual std::shared_ptr SetSdCardStatus(const SdCardStatus &status); + virtual std::shared_ptr DeletedFileMessage(const std::string &file, const StorageFileType &type); + virtual std::shared_ptr CreatedFileMessage(const std::string &file, const StorageFileType &type); }; #endif \ No newline at end of file diff --git a/middleware/AppManager/src/Protocol/SixFrame/SixFrameHandle.cpp b/middleware/AppManager/src/Protocol/SixFrame/SixFrameHandle.cpp index 91f1d3e..5fc2983 100644 --- a/middleware/AppManager/src/Protocol/SixFrame/SixFrameHandle.cpp +++ b/middleware/AppManager/src/Protocol/SixFrame/SixFrameHandle.cpp @@ -14,13 +14,16 @@ */ #include "SixFrameHandle.h" #include "ILog.h" +#include #include #include +#include using std::placeholders::_1; using std::placeholders::_2; using std::placeholders::_3; // using std::placeholders::_4; // clang-format off +const char *TCP_RESULT_MSGID = "msgid"; const char *CJSON_INFO_STRING = "info"; const char *CJSON_FILES_STRING = "files"; const char *APP_GET_PRODUCT_INFO = "/app/getproductinfo"; @@ -67,7 +70,7 @@ SixFrameHandle::SixFrameHandle() mResquesHandleFunc[APP_GET_THUMBNAIL] = std::bind(&SixFrameHandle::RequestGetThumbnail, this, _1, _2, _3); // mResquesHandleFunc["favicon.ico"] = std::bind(&SixFrameHandle::DoNothing, this, _1, _2, _); } -void SixFrameHandle::RequestHandle(const char *url, const unsigned int urlLength, ResponseHandle responseHandle, +void SixFrameHandle::RequestHandle(const char *url, const unsigned int &urlLength, ResponseHandle responseHandle, void *context) { const std::string urlStr2 = url; @@ -81,9 +84,27 @@ void SixFrameHandle::RequestHandle(const char *url, const unsigned int urlLength command = urlStr2.substr(0, urlStr2.length()); } LogInfo("command = %s\n", command.c_str()); - // ExtractParamsFromUrl(urlStr2, paramsMap); RequestHandle2(command, urlStr2, responseHandle, context); } +void SixFrameHandle::RequestHandleTcp(const char *data, const unsigned int &dataLength, ResponseHandle responseHandle, + void *context) +{ + cJSON *parsed = nullptr; + std::string command = ""; + parsed = cJSON_Parse(data); + if (nullptr == parsed) { + LogError("cJSON_Parse failed.\n"); + responseHandle("Device run out of memory.", context); + return; + } + cJSON *msgid = cJSON_GetObjectItem(parsed, "msgid"); + if (cJSON_IsString(msgid)) { + command = cJSON_GetStringValue(msgid); + } + LogInfo("command = %s\n", command.c_str()); + RequestTcpHandle2(command, parsed, responseHandle, context); + cJSON_Delete(parsed); +} void SixFrameHandle::ExtractParamsFromUrl(const std::string &url, ParseUrlResultFunc resultHandle, std::shared_ptr &context) { @@ -662,6 +683,47 @@ void SixFrameHandle::RequestGetThumbnail(const std::string &url, ResponseHandle // respon.mThumbnail = "./34a396526922a33e97906920dbfef2a5.jpg"; responseHandle(respon.mThumbnail.c_str(), context); } +void SixFrameHandle::RequestTcpHandle2(const std::string command, const cJSON *const data, + ResponseHandle responseHandle, void *context) +{ +} +std::shared_ptr SixFrameHandle::SetRecordingStatus(const RecordingStatus &status) +{ + cJSON *resultCJSON = cJSON_CreateObject(); + if (nullptr == resultCJSON) { + LogError("cJSON_CreateObject failed.\n"); + return std::make_shared(); + } + cJSON_AddStringToObject(resultCJSON, TCP_RESULT_MSGID, "rec"); + cJSON *info = cJSON_CreateObject(); + if (nullptr != info) { + cJSON_AddNumberToObject(info, "value", static_cast(status)); + cJSON_AddItemToObject(resultCJSON, CJSON_INFO_STRING, info); + } + AddTimestamp(resultCJSON); + return MakePacket(resultCJSON); +} +std::shared_ptr SixFrameHandle::SetMicrophoneStatus(const MicrophoneStatus &status) +{ + return std::make_shared(); +} +std::shared_ptr SixFrameHandle::SetBatteryStatus(const BatteryStatus &status, + const int &batteryCapacity) +{ + return std::make_shared(); +} +std::shared_ptr SixFrameHandle::SetSdCardStatus(const SdCardStatus &status) +{ + return std::make_shared(); +} +std::shared_ptr SixFrameHandle::DeletedFileMessage(const std::string &file, const StorageFileType &type) +{ + return std::make_shared(); +} +std::shared_ptr SixFrameHandle::CreatedFileMessage(const std::string &file, const StorageFileType &type) +{ + return std::make_shared(); +} cJSON *SixFrameHandle::MakeResponseResult(const ResposeResult result, const bool requestSet) { const char *RESPONSE_RESULT = "result"; @@ -711,6 +773,29 @@ const char *SixFrameHandle::PrintfFileEvent(const AppGetFileInfo &fileInfo) } return "unknown event"; } +void SixFrameHandle::AddTimestamp(cJSON *json) +{ + time_t current_time; + current_time = time(nullptr); + + if (current_time == -1) { + LogError("Error getting the time\n"); + return; + } + cJSON_AddNumberToObject(json, "time", current_time); +} +std::shared_ptr SixFrameHandle::MakePacket(const cJSON *json) +{ + char *resultStr = nullptr; + resultStr = cJSON_Print(json); + if (nullptr != resultStr) { + return std::make_shared(resultStr, strlen(resultStr)); + } + else { + LogError("MakePacket failed.\n"); + return std::make_shared(); + } +} void SixFrameHandle::SetAppMonitor(std::shared_ptr &monitor) { if (monitor) { diff --git a/middleware/AppManager/src/Protocol/SixFrame/SixFrameHandle.h b/middleware/AppManager/src/Protocol/SixFrame/SixFrameHandle.h index edc900e..be3b0b1 100644 --- a/middleware/AppManager/src/Protocol/SixFrame/SixFrameHandle.h +++ b/middleware/AppManager/src/Protocol/SixFrame/SixFrameHandle.h @@ -51,8 +51,10 @@ public: virtual ~SixFrameHandle() = default; // virtual void Init(void) {} // virtual void UnInit(void) {} - void RequestHandle(const char *url, const unsigned int urlLength, ResponseHandle responseHandle, + void RequestHandle(const char *url, const unsigned int &urlLength, ResponseHandle responseHandle, void *context) override; + void RequestHandleTcp(const char *data, const unsigned int &dataLength, ResponseHandle responseHandle, + void *context) override; private: void ExtractParamsFromUrl(const std::string &url, ParseUrlResultFunc resultHandle, @@ -95,10 +97,22 @@ private: std::string RequestGetThumbnailParse(const std::string &url); void RequestGetThumbnail(const std::string &url, ResponseHandle responseHandle, void *context); +private: + void RequestTcpHandle2(const std::string command, const cJSON *const data, ResponseHandle responseHandle, + void *context); // TODO: delete + std::shared_ptr SetRecordingStatus(const RecordingStatus &status) override; + std::shared_ptr SetMicrophoneStatus(const MicrophoneStatus &status) override; + std::shared_ptr SetBatteryStatus(const BatteryStatus &status, const int &batteryCapacity) override; + std::shared_ptr SetSdCardStatus(const SdCardStatus &status) override; + std::shared_ptr DeletedFileMessage(const std::string &file, const StorageFileType &type) override; + std::shared_ptr CreatedFileMessage(const std::string &file, const StorageFileType &type) override; + private: cJSON *MakeResponseResult(const ResposeResult result, const bool requestSet = false); void ResponseJsonString(cJSON *json, ResponseHandle responseHandle, void *context); const char *PrintfFileEvent(const AppGetFileInfo &fileInfo); + void AddTimestamp(cJSON *json); + std::shared_ptr MakePacket(const cJSON *json); protected: void SetAppMonitor(std::shared_ptr &monitor) override; diff --git a/test/middleware/AppManager/src/AppManager_Test.cpp b/test/middleware/AppManager/src/AppManager_Test.cpp index 518b206..69daca1 100644 --- a/test/middleware/AppManager/src/AppManager_Test.cpp +++ b/test/middleware/AppManager/src/AppManager_Test.cpp @@ -24,7 +24,7 @@ namespace AppManagerTest class AppManagerTest : public testing::Test, public AppManagerTestTool, public HalTestTool { public: - AppManagerTest() : mAppParam(APP_MANAGER_HTTP_SERVER_IP, APP_MANAGER_HTTP_SERVER_PORT) + AppManagerTest() : mAppParam(APP_MANAGER_DEVICE_IP, APP_MANAGER_HTTP_SERVER_PORT, APP_MANAGER_TCP_SERVER_PORT) { } virtual ~AppManagerTest() @@ -64,7 +64,8 @@ TEST_F(AppManagerTest, INTEGRATION_AppManager_EXAMPLE_Demo0) IAppManager::GetInstance()->Init(mAppParam); IAppManager::GetInstance()->SetAppMonitor(monitor); std::this_thread::sleep_for(std::chrono::milliseconds(100)); - std::this_thread::sleep_for(std::chrono::milliseconds(200000)); + MockAppClientConnect(); + std::this_thread::sleep_for(std::chrono::milliseconds(2000)); IAppManager::GetInstance()->UnInit(); } // ../output_files/test/bin/AppManagerTest --gtest_filter=AppManagerTest.INTEGRATION_AppManager_EXAMPLE_Demo diff --git a/test/middleware/AppManager/tool/CMakeLists.txt b/test/middleware/AppManager/tool/CMakeLists.txt index 8e77f9b..c335eb0 100644 --- a/test/middleware/AppManager/tool/CMakeLists.txt +++ b/test/middleware/AppManager/tool/CMakeLists.txt @@ -9,6 +9,7 @@ include_directories( ${UTILS_SOURCE_PATH}/StatusCode/include ${UTILS_SOURCE_PATH}/Log/include ${UTILS_SOURCE_PATH}/Servers/include + ${UTILS_SOURCE_PATH}/TcpModule/include ${MIDDLEWARE_SOURCE_PATH}/AppManager/src ${MIDDLEWARE_SOURCE_PATH}/AppManager/src/Protocol/SixFrame ${TEST_SOURCE_PATH} diff --git a/test/middleware/AppManager/tool/include/AppManagerTestTool.h b/test/middleware/AppManager/tool/include/AppManagerTestTool.h index f110eab..0913a46 100644 --- a/test/middleware/AppManager/tool/include/AppManagerTestTool.h +++ b/test/middleware/AppManager/tool/include/AppManagerTestTool.h @@ -44,6 +44,9 @@ protected: void MockAppPlayback(void); void MockMonitorSetFileList(std::vector &files); +protected: + void MockAppClientConnect(void); + private: void AppManagerMockInit(std::shared_ptr &vMock); void AppMonitorInit(std::shared_ptr &vMock); @@ -51,6 +54,8 @@ private: private: std::shared_ptr mAppManagerMock; std::shared_ptr mAppMonitorMock; + void *mAppClientTool; + std::shared_ptr mAppClient; public: static std::shared_ptr MakeMonitorMock(void); diff --git a/test/middleware/AppManager/tool/src/AppManagerMock.cpp b/test/middleware/AppManager/tool/src/AppManagerMock.cpp index ec721bd..925214d 100644 --- a/test/middleware/AppManager/tool/src/AppManagerMock.cpp +++ b/test/middleware/AppManager/tool/src/AppManagerMock.cpp @@ -27,14 +27,4 @@ const StatusCode AppManagerTest::SetAppMonitorTrace(std::shared_ptr { LogInfo("AppManagerTest::SetAppMonitorTrace\n"); return CreateStatusCode(STATUS_CODE_VIRTUAL_FUNCTION); -} -// StatusCode AppManagerTest::GetAllLedsTrace(std::map> &allLeds) -// { -// LogInfo("AppManagerTest::GetAllLedsTrace\n"); -// return CreateStatusCode(STATUS_CODE_VIRTUAL_FUNCTION); -// } -// StatusCode AppManagerTest::GetAllKeysTrace(std::map> &allKeys) -// { -// LogInfo("AppManagerTest::GetAllKeysTrace\n"); -// return CreateStatusCode(STATUS_CODE_VIRTUAL_FUNCTION); -// } \ No newline at end of file +} \ No newline at end of file diff --git a/test/middleware/AppManager/tool/src/AppManagerTestTool.cpp b/test/middleware/AppManager/tool/src/AppManagerTestTool.cpp index a2ba6db..f9a301c 100644 --- a/test/middleware/AppManager/tool/src/AppManagerTestTool.cpp +++ b/test/middleware/AppManager/tool/src/AppManagerTestTool.cpp @@ -18,6 +18,7 @@ #include "AppMonitorMock.h" #include "ILog.h" #include "ServersMock.h" +#include "TcpModule.h" constexpr int ONLY_BE_CALLED_ONCE = 1; void AppManagerTestTool::Init(void) { @@ -33,6 +34,9 @@ void AppManagerTestTool::UnInit(void) mAppManagerMock.reset(); mAppMonitorMock.reset(); CancelOverrideAppManagerMakePtrObject(); + if (nullptr != mAppClientTool) { + FreeTcpClient(mAppClientTool); + } } void AppManagerTestTool::MockGetProductInfo(void) { @@ -205,6 +209,36 @@ void AppManagerTestTool::MockMonitorSetFileList(std::vector &fil LogError("MockMonitorSetFileList failed, mAppMonitorMock isn't mock object.\n"); } } +void AppManagerTestTool::MockAppClientConnect(void) +{ + std::shared_ptr mock = std::dynamic_pointer_cast(mAppMonitorMock); + if (mock) { + auto appClientConnected = [=](std::shared_ptr &cliient) { + LogInfo("appClientConnected.\n"); + mAppClient = cliient; + }; + EXPECT_CALL(*mock.get(), AppClientConnectedTrace(_)) + .Times(ONLY_BE_CALLED_ONCE) + .WillOnce( + DoAll(WithArgs<0>(Invoke(appClientConnected)), Return(CreateStatusCode(STATUS_CODE_VIRTUAL_FUNCTION)))); + } + auto readFunc = [](const void *data, const ssize_t len, const void *context) -> void { + LogInfo("read data: %s", (char *)data); + }; + auto closedFunc = [](const void *object) -> void { + LogInfo("tcp client closed.\n"); + }; + TcpClientParam param = { + .mIp = APP_MANAGER_DEVICE_IP, + .mPort = APP_MANAGER_TCP_SERVER_PORT, + .mReadFunc = readFunc, + .mClosedFunc = closedFunc, + }; + mAppClientTool = CreateTcpClient(param); + if (nullptr == mAppClientTool) { + LogError("CreateTcpClient failed.\n"); + } +} void AppManagerTestTool::AppManagerMockInit(std::shared_ptr &vMock) { std::shared_ptr mock = std::dynamic_pointer_cast(vMock); @@ -268,5 +302,9 @@ void AppManagerTestTool::AppMonitorInit(std::shared_ptr &vMock) .WillRepeatedly(DoAll(Return(CreateStatusCode(STATUS_CODE_VIRTUAL_FUNCTION)))); EXPECT_CALL(*mock.get(), UploadFileTrace(_)) .WillRepeatedly(DoAll(Return(CreateStatusCode(STATUS_CODE_VIRTUAL_FUNCTION)))); + EXPECT_CALL(*mock.get(), GetThumbnailTrace(_)) + .WillRepeatedly(DoAll(Return(CreateStatusCode(STATUS_CODE_VIRTUAL_FUNCTION)))); + EXPECT_CALL(*mock.get(), AppClientConnectedTrace(_)) + .WillRepeatedly(DoAll(Return(CreateStatusCode(STATUS_CODE_VIRTUAL_FUNCTION)))); } } \ No newline at end of file diff --git a/test/middleware/AppManager/tool/src/AppMonitorMock.cpp b/test/middleware/AppManager/tool/src/AppMonitorMock.cpp index bdca552..d969eda 100644 --- a/test/middleware/AppManager/tool/src/AppMonitorMock.cpp +++ b/test/middleware/AppManager/tool/src/AppMonitorMock.cpp @@ -243,4 +243,32 @@ StatusCode AppMonitorTrace::UploadFileTrace(AppUploadFile ¶m) { LogInfo("AppMonitorTrace::UploadFileTrace\n"); return CreateStatusCode(STATUS_CODE_VIRTUAL_FUNCTION); +} +StatusCode AppMonitorTest::GetThumbnail(AppGetThumbnail ¶m) +{ + LogInfo("AppMonitorTest::GetThumbnail\n"); + StatusCode code = GetThumbnailTrace(param); + if (StatusCodeEqual(code, "STATUS_CODE_VIRTUAL_FUNCTION")) { + return VAppMonitor::GetThumbnail(param); + } + return code; +} +StatusCode AppMonitorTrace::GetThumbnailTrace(AppGetThumbnail ¶m) +{ + LogInfo("AppMonitorTrace::UploadFileTrace\n"); + return CreateStatusCode(STATUS_CODE_VIRTUAL_FUNCTION); +} +StatusCode AppMonitorTest::AppClientConnected(std::shared_ptr &client) +{ + LogInfo("AppMonitorTest::AppClientConnected\n"); + StatusCode code = AppClientConnectedTrace(client); + if (StatusCodeEqual(code, "STATUS_CODE_VIRTUAL_FUNCTION")) { + return VAppMonitor::AppClientConnected(client); + } + return code; +} +StatusCode AppMonitorTrace::AppClientConnectedTrace(std::shared_ptr &client) +{ + LogInfo("AppMonitorTrace::AppClientConnected\n"); + return CreateStatusCode(STATUS_CODE_VIRTUAL_FUNCTION); } \ No newline at end of file diff --git a/test/middleware/AppManager/tool/src/AppMonitorMock.h b/test/middleware/AppManager/tool/src/AppMonitorMock.h index 4d19508..fc2225b 100644 --- a/test/middleware/AppManager/tool/src/AppMonitorMock.h +++ b/test/middleware/AppManager/tool/src/AppMonitorMock.h @@ -39,6 +39,8 @@ protected: virtual StatusCode EnterRecorderTrace(void); virtual StatusCode AppPlaybackTrace(const PlayBackEvent &event); virtual StatusCode UploadFileTrace(AppUploadFile ¶m); + virtual StatusCode GetThumbnailTrace(AppGetThumbnail ¶m); + virtual StatusCode AppClientConnectedTrace(std::shared_ptr &client); }; class AppMonitorTest : public VAppMonitor, virtual public AppMonitorTrace { @@ -61,6 +63,8 @@ public: StatusCode EnterRecorder(void) override; StatusCode AppPlayback(const PlayBackEvent &event) override; StatusCode UploadFile(AppUploadFile ¶m) override; + StatusCode GetThumbnail(AppGetThumbnail ¶m) override; + StatusCode AppClientConnected(std::shared_ptr &client) override; }; class AppMonitorMock : virtual public AppMonitorTrace { @@ -83,5 +87,7 @@ public: MOCK_METHOD0(EnterRecorderTrace, StatusCode(void)); MOCK_METHOD1(AppPlaybackTrace, StatusCode(const PlayBackEvent &)); MOCK_METHOD1(UploadFileTrace, StatusCode(AppUploadFile &)); + MOCK_METHOD1(GetThumbnailTrace, StatusCode(AppGetThumbnail &)); + MOCK_METHOD1(AppClientConnectedTrace, StatusCode(std::shared_ptr &)); }; #endif \ No newline at end of file diff --git a/test/middleware/AppManager/tool/src/ServersMock.cpp b/test/middleware/AppManager/tool/src/ServersMock.cpp index 0de6e88..ccc90ba 100644 --- a/test/middleware/AppManager/tool/src/ServersMock.cpp +++ b/test/middleware/AppManager/tool/src/ServersMock.cpp @@ -49,7 +49,7 @@ std::shared_ptr &ServersMock::GetInstance(std::shared_ptr locker(mMutex); if (nullptr == mIo) { LogError("mIo is nullptr.\n"); return TCP_MODULE_WRITE_ERROR; @@ -89,6 +90,8 @@ ssize_t TcpClientImpl::Write(const void *buf, const size_t bufLenght) } void TcpClientImpl::Closed(void) { + std::lock_guard locker(mMutex); + mIo = nullptr; if (nullptr != mParam.mClosedFunc) { mParam.mClosedFunc(mObjectThis); } diff --git a/utils/TcpModule/src/TcpClientImpl.h b/utils/TcpModule/src/TcpClientImpl.h index c84cde9..4e0a337 100644 --- a/utils/TcpModule/src/TcpClientImpl.h +++ b/utils/TcpModule/src/TcpClientImpl.h @@ -20,6 +20,7 @@ #include "hsocket.h" #include "hssl.h" #include +#include #include class TcpClientImpl : public ITcpClient, public std::enable_shared_from_this { @@ -34,6 +35,7 @@ public: void Loop(void); private: + std::mutex mMutex; hloop_t *mLoop; hio_t *mIo; const TcpClientParam mParam; diff --git a/utils/TcpModule/src/TcpModule.cpp b/utils/TcpModule/src/TcpModule.cpp index 4101b25..9401ee7 100644 --- a/utils/TcpModule/src/TcpModule.cpp +++ b/utils/TcpModule/src/TcpModule.cpp @@ -58,12 +58,6 @@ void FreeTcpServer(void *object) free(((char *)object) - sizeof(ITcpServerHeader)); // TODO: bug? } } -// void AcceptClientSetParam(void *object, const ClientAcceptParam param) -// { -// if (TcpClientAcceptObjectCheck(object) == true) { -// (*(std::shared_ptr *)object)->SetParam(param); -// } -// } ssize_t AcceptClientWrite(void *object, const void *buf, const size_t bufLenght) { if (TcpClientAcceptObjectCheck(object) == true) { From 3ba9078ef95d9a285c7c0a52f851fea8cb1ba0a3 Mon Sep 17 00:00:00 2001 From: Fancy code <258828110.@qq.com> Date: Sat, 13 Apr 2024 10:52:20 +0800 Subject: [PATCH 09/10] Improve:SixFrame tcp protocol. --- .../src/Protocol/SixFrame/SixFrameHandle.cpp | 97 +++++++++++++++++-- .../AppManager/src/AppManager_Test.cpp | 86 ++++++++++++++++ .../tool/include/AppManagerTestTool.h | 6 ++ .../tool/src/AppManagerTestTool.cpp | 48 +++++++++ 4 files changed, 231 insertions(+), 6 deletions(-) diff --git a/middleware/AppManager/src/Protocol/SixFrame/SixFrameHandle.cpp b/middleware/AppManager/src/Protocol/SixFrame/SixFrameHandle.cpp index 5fc2983..aa51ada 100644 --- a/middleware/AppManager/src/Protocol/SixFrame/SixFrameHandle.cpp +++ b/middleware/AppManager/src/Protocol/SixFrame/SixFrameHandle.cpp @@ -47,6 +47,22 @@ const char *APP_GET_THUMBNAIL = "/app/getthumbnail"; // /app/exitrecorder // clang-format on constexpr bool SET_REQUEST_RESPONSE = true; +class CjsonAutoFree +{ +public: + CjsonAutoFree(cJSON *json) : mJson(json) + { + } + ~CjsonAutoFree() + { + if (mJson != nullptr) { + cJSON_Delete(mJson); + } + } + +private: + cJSON *mJson; +}; SixFrameHandle::SixFrameHandle() { mAppMonitor = std::make_shared(); @@ -689,7 +705,8 @@ void SixFrameHandle::RequestTcpHandle2(const std::string command, const cJSON *c } std::shared_ptr SixFrameHandle::SetRecordingStatus(const RecordingStatus &status) { - cJSON *resultCJSON = cJSON_CreateObject(); + cJSON *resultCJSON = nullptr; + CjsonAutoFree autoJson(resultCJSON = cJSON_CreateObject()); if (nullptr == resultCJSON) { LogError("cJSON_CreateObject failed.\n"); return std::make_shared(); @@ -705,24 +722,92 @@ std::shared_ptr SixFrameHandle::SetRecordingStatus(const Recordi } std::shared_ptr SixFrameHandle::SetMicrophoneStatus(const MicrophoneStatus &status) { - return std::make_shared(); + cJSON *resultCJSON = nullptr; + CjsonAutoFree autoJson(resultCJSON = cJSON_CreateObject()); + if (nullptr == resultCJSON) { + LogError("cJSON_CreateObject failed.\n"); + return std::make_shared(); + } + cJSON_AddStringToObject(resultCJSON, TCP_RESULT_MSGID, "mic"); + cJSON *info = cJSON_CreateObject(); + if (nullptr != info) { + cJSON_AddNumberToObject(info, "value", static_cast(status)); + cJSON_AddItemToObject(resultCJSON, CJSON_INFO_STRING, info); + } + AddTimestamp(resultCJSON); + return MakePacket(resultCJSON); } std::shared_ptr SixFrameHandle::SetBatteryStatus(const BatteryStatus &status, const int &batteryCapacity) { - return std::make_shared(); + cJSON *resultCJSON = nullptr; + CjsonAutoFree autoJson(resultCJSON = cJSON_CreateObject()); + if (nullptr == resultCJSON) { + LogError("cJSON_CreateObject failed.\n"); + return std::make_shared(); + } + cJSON_AddStringToObject(resultCJSON, TCP_RESULT_MSGID, "battery"); + cJSON *info = cJSON_CreateObject(); + if (nullptr != info) { + cJSON_AddNumberToObject(info, "charge", static_cast(status)); + cJSON_AddNumberToObject(info, "capacity", batteryCapacity); + cJSON_AddItemToObject(resultCJSON, CJSON_INFO_STRING, info); + } + AddTimestamp(resultCJSON); + return MakePacket(resultCJSON); } std::shared_ptr SixFrameHandle::SetSdCardStatus(const SdCardStatus &status) { - return std::make_shared(); + cJSON *resultCJSON = nullptr; + CjsonAutoFree autoJson(resultCJSON = cJSON_CreateObject()); + if (nullptr == resultCJSON) { + LogError("cJSON_CreateObject failed.\n"); + return std::make_shared(); + } + cJSON_AddStringToObject(resultCJSON, TCP_RESULT_MSGID, "sd"); + cJSON *info = cJSON_CreateObject(); + if (nullptr != info) { + cJSON_AddNumberToObject(info, "status", static_cast(status)); + cJSON_AddItemToObject(resultCJSON, CJSON_INFO_STRING, info); + } + AddTimestamp(resultCJSON); + return MakePacket(resultCJSON); } std::shared_ptr SixFrameHandle::DeletedFileMessage(const std::string &file, const StorageFileType &type) { - return std::make_shared(); + cJSON *resultCJSON = nullptr; + CjsonAutoFree autoJson(resultCJSON = cJSON_CreateObject()); + if (nullptr == resultCJSON) { + LogError("cJSON_CreateObject failed.\n"); + return std::make_shared(); + } + cJSON_AddStringToObject(resultCJSON, TCP_RESULT_MSGID, "file_del"); + cJSON *info = cJSON_CreateObject(); + if (nullptr != info) { + cJSON_AddStringToObject(info, "name", file.c_str()); + cJSON_AddNumberToObject(info, "type", static_cast(type)); + cJSON_AddItemToObject(resultCJSON, CJSON_INFO_STRING, info); + } + AddTimestamp(resultCJSON); + return MakePacket(resultCJSON); } std::shared_ptr SixFrameHandle::CreatedFileMessage(const std::string &file, const StorageFileType &type) { - return std::make_shared(); + cJSON *resultCJSON = nullptr; + CjsonAutoFree autoJson(resultCJSON = cJSON_CreateObject()); + if (nullptr == resultCJSON) { + LogError("cJSON_CreateObject failed.\n"); + return std::make_shared(); + } + cJSON_AddStringToObject(resultCJSON, TCP_RESULT_MSGID, "file_add"); + cJSON *info = cJSON_CreateObject(); + if (nullptr != info) { + cJSON_AddStringToObject(info, "name", file.c_str()); + cJSON_AddNumberToObject(info, "type", static_cast(type)); + cJSON_AddItemToObject(resultCJSON, CJSON_INFO_STRING, info); + } + AddTimestamp(resultCJSON); + return MakePacket(resultCJSON); } cJSON *SixFrameHandle::MakeResponseResult(const ResposeResult result, const bool requestSet) { diff --git a/test/middleware/AppManager/src/AppManager_Test.cpp b/test/middleware/AppManager/src/AppManager_Test.cpp index 69daca1..bf15ed6 100644 --- a/test/middleware/AppManager/src/AppManager_Test.cpp +++ b/test/middleware/AppManager/src/AppManager_Test.cpp @@ -65,6 +65,8 @@ TEST_F(AppManagerTest, INTEGRATION_AppManager_EXAMPLE_Demo0) IAppManager::GetInstance()->SetAppMonitor(monitor); std::this_thread::sleep_for(std::chrono::milliseconds(100)); MockAppClientConnect(); + std::this_thread::sleep_for(std::chrono::milliseconds(100)); + MockSetRecordingStatus(RecordingStatus::RECORDING_START); std::this_thread::sleep_for(std::chrono::milliseconds(2000)); IAppManager::GetInstance()->UnInit(); } @@ -256,4 +258,88 @@ TEST_F(AppManagerTest, INTEGRATION_AppManager_EXAMPLE_AUTO_AppPlayback) std::this_thread::sleep_for(std::chrono::milliseconds(1000)); IAppManager::GetInstance()->UnInit(); } +// ../output_files/test/bin/AppManagerTest +// --gtest_filter=AppManagerTest.INTEGRATION_AppManager_EXAMPLE_AUTO_SetRecordingStatus +TEST_F(AppManagerTest, INTEGRATION_AppManager_EXAMPLE_AUTO_SetRecordingStatus) +{ + std::shared_ptr monitor = AppManagerTestTool::MakeMonitorMock(); + IAppManager::GetInstance()->Init(mAppParam); + IAppManager::GetInstance()->SetAppMonitor(monitor); + std::this_thread::sleep_for(std::chrono::milliseconds(100)); + MockAppClientConnect(); + std::this_thread::sleep_for(std::chrono::milliseconds(100)); + MockSetRecordingStatus(RecordingStatus::RECORDING_START); + std::this_thread::sleep_for(std::chrono::milliseconds(2000)); + IAppManager::GetInstance()->UnInit(); +} +// ../output_files/test/bin/AppManagerTest +// --gtest_filter=AppManagerTest.INTEGRATION_AppManager_EXAMPLE_AUTO_SetMicrophoneStatus +TEST_F(AppManagerTest, INTEGRATION_AppManager_EXAMPLE_AUTO_SetMicrophoneStatus) +{ + std::shared_ptr monitor = AppManagerTestTool::MakeMonitorMock(); + IAppManager::GetInstance()->Init(mAppParam); + IAppManager::GetInstance()->SetAppMonitor(monitor); + std::this_thread::sleep_for(std::chrono::milliseconds(100)); + MockAppClientConnect(); + std::this_thread::sleep_for(std::chrono::milliseconds(100)); + MockSetMicrophoneStatus(MicrophoneStatus::ON); + std::this_thread::sleep_for(std::chrono::milliseconds(2000)); + IAppManager::GetInstance()->UnInit(); +} +// ../output_files/test/bin/AppManagerTest +// --gtest_filter=AppManagerTest.INTEGRATION_AppManager_EXAMPLE_AUTO_SetBatteryStatus +TEST_F(AppManagerTest, INTEGRATION_AppManager_EXAMPLE_AUTO_SetBatteryStatus) +{ + std::shared_ptr monitor = AppManagerTestTool::MakeMonitorMock(); + IAppManager::GetInstance()->Init(mAppParam); + IAppManager::GetInstance()->SetAppMonitor(monitor); + std::this_thread::sleep_for(std::chrono::milliseconds(100)); + MockAppClientConnect(); + std::this_thread::sleep_for(std::chrono::milliseconds(100)); + MockSetBatteryStatus(BatteryStatus::CHARGING, 20); + std::this_thread::sleep_for(std::chrono::milliseconds(2000)); + IAppManager::GetInstance()->UnInit(); +} +// ../output_files/test/bin/AppManagerTest +// --gtest_filter=AppManagerTest.INTEGRATION_AppManager_EXAMPLE_AUTO_SetSdCardStatus +TEST_F(AppManagerTest, INTEGRATION_AppManager_EXAMPLE_AUTO_SetSdCardStatus) +{ + std::shared_ptr monitor = AppManagerTestTool::MakeMonitorMock(); + IAppManager::GetInstance()->Init(mAppParam); + IAppManager::GetInstance()->SetAppMonitor(monitor); + std::this_thread::sleep_for(std::chrono::milliseconds(100)); + MockAppClientConnect(); + std::this_thread::sleep_for(std::chrono::milliseconds(100)); + MockSetSdCardStatus(SdCardStatus::NOT_INSERTED); + std::this_thread::sleep_for(std::chrono::milliseconds(2000)); + IAppManager::GetInstance()->UnInit(); +} +// ../output_files/test/bin/AppManagerTest +// --gtest_filter=AppManagerTest.INTEGRATION_AppManager_EXAMPLE_AUTO_DeletedFileMessage +TEST_F(AppManagerTest, INTEGRATION_AppManager_EXAMPLE_AUTO_DeletedFileMessage) +{ + std::shared_ptr monitor = AppManagerTestTool::MakeMonitorMock(); + IAppManager::GetInstance()->Init(mAppParam); + IAppManager::GetInstance()->SetAppMonitor(monitor); + std::this_thread::sleep_for(std::chrono::milliseconds(100)); + MockAppClientConnect(); + std::this_thread::sleep_for(std::chrono::milliseconds(100)); + MockDeletedFileMessage("file_name", StorageFileType::VIDEO); + std::this_thread::sleep_for(std::chrono::milliseconds(2000)); + IAppManager::GetInstance()->UnInit(); +} +// ../output_files/test/bin/AppManagerTest +// --gtest_filter=AppManagerTest.INTEGRATION_AppManager_EXAMPLE_AUTO_CreatedFileMessage +TEST_F(AppManagerTest, INTEGRATION_AppManager_EXAMPLE_AUTO_CreatedFileMessage) +{ + std::shared_ptr monitor = AppManagerTestTool::MakeMonitorMock(); + IAppManager::GetInstance()->Init(mAppParam); + IAppManager::GetInstance()->SetAppMonitor(monitor); + std::this_thread::sleep_for(std::chrono::milliseconds(100)); + MockAppClientConnect(); + std::this_thread::sleep_for(std::chrono::milliseconds(100)); + MockCreatedFileMessage("file_name", StorageFileType::VIDEO); + std::this_thread::sleep_for(std::chrono::milliseconds(2000)); + IAppManager::GetInstance()->UnInit(); +} } // namespace AppManagerTest \ No newline at end of file diff --git a/test/middleware/AppManager/tool/include/AppManagerTestTool.h b/test/middleware/AppManager/tool/include/AppManagerTestTool.h index 0913a46..92c821e 100644 --- a/test/middleware/AppManager/tool/include/AppManagerTestTool.h +++ b/test/middleware/AppManager/tool/include/AppManagerTestTool.h @@ -46,6 +46,12 @@ protected: protected: void MockAppClientConnect(void); + void MockSetRecordingStatus(const RecordingStatus &status); + void MockSetMicrophoneStatus(const MicrophoneStatus &status); + void MockSetBatteryStatus(const BatteryStatus &status, const int &batteryCapacity); + void MockSetSdCardStatus(const SdCardStatus &status); + void MockDeletedFileMessage(const std::string &file, const StorageFileType &type); + void MockCreatedFileMessage(const std::string &file, const StorageFileType &type); private: void AppManagerMockInit(std::shared_ptr &vMock); diff --git a/test/middleware/AppManager/tool/src/AppManagerTestTool.cpp b/test/middleware/AppManager/tool/src/AppManagerTestTool.cpp index f9a301c..7d5816d 100644 --- a/test/middleware/AppManager/tool/src/AppManagerTestTool.cpp +++ b/test/middleware/AppManager/tool/src/AppManagerTestTool.cpp @@ -239,6 +239,54 @@ void AppManagerTestTool::MockAppClientConnect(void) LogError("CreateTcpClient failed.\n"); } } +void AppManagerTestTool::MockSetRecordingStatus(const RecordingStatus &status) +{ + if (mAppClient) { + mAppClient->SetRecordingStatus(status); + return; + } + LogWarning("mAppClient is nullptr.\n"); +} +void AppManagerTestTool::MockSetMicrophoneStatus(const MicrophoneStatus &status) +{ + if (mAppClient) { + mAppClient->SetMicrophoneStatus(status); + return; + } + LogWarning("mAppClient is nullptr.\n"); +} +void AppManagerTestTool::MockSetBatteryStatus(const BatteryStatus &status, const int &batteryCapacity) +{ + if (mAppClient) { + mAppClient->SetBatteryStatus(status, batteryCapacity); + return; + } + LogWarning("mAppClient is nullptr.\n"); +} +void AppManagerTestTool::MockSetSdCardStatus(const SdCardStatus &status) +{ + if (mAppClient) { + mAppClient->SetSdCardStatus(status); + return; + } + LogWarning("mAppClient is nullptr.\n"); +} +void AppManagerTestTool::MockDeletedFileMessage(const std::string &file, const StorageFileType &type) +{ + if (mAppClient) { + mAppClient->DeletedFileMessage(file, type); + return; + } + LogWarning("mAppClient is nullptr.\n"); +} +void AppManagerTestTool::MockCreatedFileMessage(const std::string &file, const StorageFileType &type) +{ + if (mAppClient) { + mAppClient->CreatedFileMessage(file, type); + return; + } + LogWarning("mAppClient is nullptr.\n"); +} void AppManagerTestTool::AppManagerMockInit(std::shared_ptr &vMock) { std::shared_ptr mock = std::dynamic_pointer_cast(vMock); From 2f89bc86817ddc9fce76b37c3436ea0e9e32bb0d Mon Sep 17 00:00:00 2001 From: Fancy code <258828110.@qq.com> Date: Sat, 13 Apr 2024 11:39:34 +0800 Subject: [PATCH 10/10] Backup. --- middleware/AppManager/include/IAppManager.h | 104 ++++---------------- middleware/AppManager/src/IAppManager.cpp | 80 +++++++++++++++ 2 files changed, 101 insertions(+), 83 deletions(-) diff --git a/middleware/AppManager/include/IAppManager.h b/middleware/AppManager/include/IAppManager.h index 98e7133..cfaefcf 100644 --- a/middleware/AppManager/include/IAppManager.h +++ b/middleware/AppManager/include/IAppManager.h @@ -171,9 +171,7 @@ enum class BatteryStatus }; typedef struct app_get_product_info { - app_get_product_info() - { - } + app_get_product_info(); std::string mModel; std::string mCompany; std::string mSoc; @@ -181,9 +179,7 @@ typedef struct app_get_product_info } AppGetProductInfo; typedef struct app_get_device_attr { - app_get_device_attr() - { - } + app_get_device_attr(); std::string mUUID; std::string mSoftVersion; std::string mOtaVersion; @@ -196,61 +192,33 @@ typedef struct app_get_device_attr } AppGetDeviceAttr; typedef struct app_get_media_info { - app_get_media_info() - { - mPort = -1; - } + app_get_media_info(); std::string mRtspUrl; std::string mTransport; int mPort; } AppGetMeidaInfo; typedef struct app_get_sd_card_info { - app_get_sd_card_info() - { - mStatus = SdCardStatus::END; - mFree = 0; - mTotal = 0; - } + app_get_sd_card_info(); SdCardStatus mStatus; int mFree; int mTotal; } AppGetSdCardInfo; typedef struct app_get_battery_info { - app_get_battery_info() - { - mCapacity = 0; - mChargeStatus = ChargeStatus::END; - } + app_get_battery_info(); int mCapacity; ChargeStatus mChargeStatus; } AppGetBatteryInfo; typedef struct app_get_param_value { - app_get_param_value() - { - mRec = SwitchStatus::END; - mMicStatus = SwitchStatus::END; - } + app_get_param_value(); SwitchStatus mMicStatus; SwitchStatus mRec; } AppParamValue; typedef struct app_get_capability { - app_get_capability() - { - mGpsCapability = GpsCapability::END; - mDeviceType = DeviceType::END; - mAlbum = DashAlbum::END; - mAppLock = AppLock::END; - mDeleteLock = DeleteLock::END; - mDeviceMode = DeviceMode::END; - mPlaybackType = PlaybackType::END; - mPhotographCapability = PhotographCapability::END; - mWifiCapability = WifiCapability::END; - mFileCopy = FileCopy::END; - } + app_get_capability(); GpsCapability mGpsCapability; DeviceType mDeviceType; DashAlbum mAlbum; @@ -264,13 +232,7 @@ typedef struct app_get_capability } AppGetCapability; typedef struct app_get_storage_info { - app_get_storage_info() - { - mIndex = -1; - mType = StorageType::END; - mFree = 0; - mTotal = 0; - } + app_get_storage_info(); int mIndex; StorageType mType; std::string mName; @@ -279,25 +241,14 @@ typedef struct app_get_storage_info } AppGetStorageInfo; typedef struct app_get_file_info { - app_get_file_info() - { - mStartIndex = 0; - mStopIndex = 0; - mEvent = StorageFileEvent::END; - } + app_get_file_info(); int mStartIndex; int mStopIndex; StorageFileEvent mEvent; } AppGetFileInfo; typedef struct app_get_file_list { - app_get_file_list() - { - mDuration = 0; - mSize = 0; - mCreateTime_s = 0; - mType = StorageFileType::END; - } + app_get_file_list(); std::string mName; int mDuration; int mSize; @@ -306,20 +257,14 @@ typedef struct app_get_file_list } AppGetFileList; typedef struct app_set_param_value { - app_set_param_value() - { - mValue = -1; - } + app_set_param_value(); std::string mName; int mValue; } AppSetParamValue; typedef struct app_set_date_time { app_set_date_time(const unsigned int year, const unsigned int month, const unsigned int day, - const unsigned int hour, const unsigned int minute, const unsigned int second) - : mYear(year), mMonth(month), mDay(day), mHour(hour), mMinute(minute), mSecond(second) - { - } + const unsigned int hour, const unsigned int minute, const unsigned int second); const unsigned int mYear; const unsigned int mMonth; const unsigned int mDay; @@ -329,22 +274,24 @@ typedef struct app_set_date_time } AppSetDateTime; typedef struct app_upload_file { - app_upload_file(const std::string filePath, const UploadCommand command) : mFilePath(filePath), mCommand(command) - { - mResult = ResposeResult::END; - } + app_upload_file(const std::string filePath, const UploadCommand command); const std::string mFilePath; const UploadCommand mCommand; ResposeResult mResult; } AppUploadFile; typedef struct app_get_thumbnail { - app_get_thumbnail(const std::string file) : mFile(file) - { - } + app_get_thumbnail(const std::string file); const std::string mFile; std::string mThumbnail; } AppGetThumbnail; +typedef struct app_param +{ + app_param(const char *ip, const int &httpPort, const int &tcpPort); + const char *mIP; + const int mHttpPort; + const int mTcpPort; +} AppParam; class VAppClient { public: @@ -381,15 +328,6 @@ public: virtual StatusCode GetThumbnail(AppGetThumbnail ¶m); virtual StatusCode AppClientConnected(std::shared_ptr &client); }; -typedef struct app_param -{ - app_param(const char *ip, const int &httpPort, const int &tcpPort) : mIP(ip), mHttpPort(httpPort), mTcpPort(tcpPort) - { - } - const char *mIP; - const int mHttpPort; - const int mTcpPort; -} AppParam; class IAppManager { public: diff --git a/middleware/AppManager/src/IAppManager.cpp b/middleware/AppManager/src/IAppManager.cpp index cf76be5..e115ef4 100644 --- a/middleware/AppManager/src/IAppManager.cpp +++ b/middleware/AppManager/src/IAppManager.cpp @@ -14,6 +14,86 @@ */ #include "IAppManager.h" #include "ILog.h" +app_get_product_info::app_get_product_info() +{ +} +app_get_device_attr::app_get_device_attr() +{ +} +app_get_media_info::app_get_media_info() +{ + mPort = -1; +} +app_get_sd_card_info::app_get_sd_card_info() +{ + mStatus = SdCardStatus::END; + mFree = 0; + mTotal = 0; +} +app_get_battery_info::app_get_battery_info() +{ + mCapacity = 0; + mChargeStatus = ChargeStatus::END; +} +app_get_param_value::app_get_param_value() +{ + mRec = SwitchStatus::END; + mMicStatus = SwitchStatus::END; +} +app_get_capability::app_get_capability() +{ + mGpsCapability = GpsCapability::END; + mDeviceType = DeviceType::END; + mAlbum = DashAlbum::END; + mAppLock = AppLock::END; + mDeleteLock = DeleteLock::END; + mDeviceMode = DeviceMode::END; + mPlaybackType = PlaybackType::END; + mPhotographCapability = PhotographCapability::END; + mWifiCapability = WifiCapability::END; + mFileCopy = FileCopy::END; +} +app_get_storage_info::app_get_storage_info() +{ + mIndex = -1; + mType = StorageType::END; + mFree = 0; + mTotal = 0; +} +app_get_file_info::app_get_file_info() +{ + mStartIndex = 0; + mStopIndex = 0; + mEvent = StorageFileEvent::END; +} +app_get_file_list::app_get_file_list() +{ + mDuration = 0; + mSize = 0; + mCreateTime_s = 0; + mType = StorageFileType::END; +} +app_set_param_value::app_set_param_value() +{ + mValue = -1; +} +app_set_date_time::app_set_date_time(const unsigned int year, const unsigned int month, const unsigned int day, + const unsigned int hour, const unsigned int minute, const unsigned int second) + : mYear(year), mMonth(month), mDay(day), mHour(hour), mMinute(minute), mSecond(second) +{ +} +app_upload_file::app_upload_file(const std::string filePath, const UploadCommand command) + : mFilePath(filePath), mCommand(command) +{ + mResult = ResposeResult::END; +} +app_get_thumbnail::app_get_thumbnail(const std::string file) : mFile(file) +{ +} +app_param::app_param(const char *ip, const int &httpPort, const int &tcpPort) + : mIP(ip), mHttpPort(httpPort), mTcpPort(tcpPort) +{ +} void VAppClient::SetRecordingStatus(const RecordingStatus &status) { }