diff --git a/application/MissionManager/src/TestMissionState.cpp b/application/MissionManager/src/TestMissionState.cpp index 5460ff41..cfb1f806 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 2f4a1748..5efb0d27 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/external/libhv/libhv-1.3.2/CMakeLists.txt b/external/libhv/libhv-1.3.2/CMakeLists.txt index 4a29432c..a79d2eb4 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/middleware/AppManager/CMakeLists.txt b/middleware/AppManager/CMakeLists.txt index aa933a30..fb405201 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 0f3fd41e..7e7bd084 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 5cd7a7e7..cfaefcfd 100644 --- a/middleware/AppManager/include/IAppManager.h +++ b/middleware/AppManager/include/IAppManager.h @@ -151,11 +151,27 @@ 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() - { - } + app_get_product_info(); std::string mModel; std::string mCompany; std::string mSoc; @@ -163,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; @@ -178,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; @@ -246,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; @@ -261,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; @@ -288,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; @@ -311,22 +274,36 @@ 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: + 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,15 +326,8 @@ 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) - { - } - const char *mIP; - const int mPort; -} AppParam; class IAppManager { public: diff --git a/middleware/AppManager/src/AppClient.cpp b/middleware/AppManager/src/AppClient.cpp new file mode 100644 index 00000000..acc4186d --- /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 00000000..de51b091 --- /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 56175e53..55b16305 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) { @@ -33,26 +33,53 @@ const StatusCode AppManager::Init(const AppParam ¶m) } LogInfo("ssssssssssssssssssssssssssssssssssssssssssssssssss\n"); 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) { @@ -64,7 +91,6 @@ void AppManager::HttpServerStart(const AppParam ¶m) } void AppManager::HttpServerStop(void) { - // FxHttpServerExit(); WebServerExit(); if (mHttpSever.joinable()) { mHttpSever.join(); @@ -82,9 +108,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 fa3e3dbf..308a08da 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 d01955dc..e115ef40 100644 --- a/middleware/AppManager/src/IAppManager.cpp +++ b/middleware/AppManager/src/IAppManager.cpp @@ -14,6 +14,104 @@ */ #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) +{ +} +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 +180,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 00000000..7c435ff4 --- /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 4cd04d43..5e8d8e1f 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 91f1d3e2..aa51ada8 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"; @@ -44,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(); @@ -67,7 +86,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 +100,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 +699,116 @@ 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 = nullptr; + CjsonAutoFree autoJson(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) +{ + 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) +{ + 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) +{ + 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) +{ + 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) +{ + 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) { const char *RESPONSE_RESULT = "result"; @@ -711,6 +858,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 edc900e2..be3b0b18 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/middleware/IpcConfig/CMakeLists.txt b/middleware/IpcConfig/CMakeLists.txt index 9e378f0c..9a987b5f 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 4f72be3e..5a84893e 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 @@ -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 422240af..c83c10c4 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 cc456386..b673908e 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 7add2c57..9de09a46 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/middleware/McuManager/src/McuDevice.cpp b/middleware/McuManager/src/McuDevice.cpp index ae736e1e..624efc96 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 7cda7925..6a44dc69 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/GtestUsing.h b/test/GtestUsing.h index 7378611b..e829a58e 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 ea317d85..d75f030b 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/middleware/AppManager/src/AppManager_Test.cpp b/test/middleware/AppManager/src/AppManager_Test.cpp index 518b206e..bf15ed62 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,10 @@ 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(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_Demo @@ -255,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/CMakeLists.txt b/test/middleware/AppManager/tool/CMakeLists.txt index 8e77f9b6..c335eb0f 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 f110eabd..92c821ef 100644 --- a/test/middleware/AppManager/tool/include/AppManagerTestTool.h +++ b/test/middleware/AppManager/tool/include/AppManagerTestTool.h @@ -44,6 +44,15 @@ protected: void MockAppPlayback(void); void MockMonitorSetFileList(std::vector &files); +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); void AppMonitorInit(std::shared_ptr &vMock); @@ -51,6 +60,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 ec721bdb..925214d5 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 a2ba6db0..7d5816da 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,84 @@ 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::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); @@ -268,5 +350,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 bdca5528..d969edad 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 4d19508e..fc2225b9 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 0de6e88d..ccc90ba0 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 +#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 00000000..cf89f72b --- /dev/null +++ b/test/utils/TcpModule/src/TcpModule_Test.cpp @@ -0,0 +1,74 @@ +/* + * 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 +#include +namespace TcpModuleTest +{ +// ../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_EXAMPLE_AUTO_IllegalObject) +{ + TcpServerParam tcpServerparam = { + .mIp = "127.0.0.1", + .mPort = 9876, + .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 = { + .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; + }, + .mClosedFunc = [](const void *object) -> void { + LogInfo("tcp client closed.\n"); + }, + }; + CreateLogModule(); + ILogInit(LOG_INSTANCE_TYPE_END); + 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, "client send data.", strlen("client send data.")); + std::this_thread::sleep_for(std::chrono::milliseconds(1000)); + if (nullptr != tcpClient) { + FreeTcpClient(tcpClient); + } + if (nullptr != tcpServer) { + FreeTcpServer(tcpServer); + } + ILogUnInit(); +} +} // namespace TcpModuleTest \ No newline at end of file diff --git a/test/utils/UartDevice/CMakeLists.txt b/test/utils/UartDevice/CMakeLists.txt index 0527aa06..3d633483 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/CMakeLists.txt b/utils/CMakeLists.txt index 76078822..bd0ba166 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 0d04847f..f6f1e999 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 00000000..8fb72427 --- /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 00000000..09434ee2 --- /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 00000000..0f2a330a --- /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 00000000..b15ec75f --- /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(IConfigBaseHeader))) != 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(IConfigBaseHeader)); // 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 00000000..c6dac5a5 --- /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 00000000..4b070a1d --- /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 00000000..aad87606 --- /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 00000000..de3c9a29 --- /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 00000000..51a26bcc --- /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 00000000..8a98c18e --- /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 diff --git a/utils/McuProtocol/include/McuProtocol.h b/utils/McuProtocol/include/McuProtocol.h index 6ed055d5..08b7ea87 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/CMakeLists.txt b/utils/TcpModule/CMakeLists.txt index 2b6dd884..a3d94d2e 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,7 +18,7 @@ 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") add_custom_target( diff --git a/utils/TcpModule/include/TcpModule.h b/utils/TcpModule/include/TcpModule.h index e3d9d09f..f3a57c5f 100644 --- a/utils/TcpModule/include/TcpModule.h +++ b/utils/TcpModule/include/TcpModule.h @@ -14,22 +14,41 @@ */ #ifndef TCP_MODULE_H #define TCP_MODULE_H +#include +#include +#define TCP_MODULE_WRITE_ERROR -1; #ifdef __cplusplus extern "C" { #endif -typedef void (*TcpReadFunction)(void *, const int, void *); +typedef void (*TcpReadFunction)(const void *, const ssize_t, const void *); +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; + const TcpAcceptClientFunction mAcceptClientFunc; + const ClientAcceptParam mClientAcceptParam; +} TcpServerParam; 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); + const SocketClosedFunction mClosedFunc; +} TcpClientParam; +void *CreateTcpServer(const TcpServerParam param); +void FreeTcpServer(void *object); +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); #ifdef __cplusplus } #endif diff --git a/utils/TcpModule/src/ITcpClient.cpp b/utils/TcpModule/src/ITcpClient.cpp new file mode 100644 index 00000000..256ab402 --- /dev/null +++ b/utils/TcpModule/src/ITcpClient.cpp @@ -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. + */ +#include "ITcpClient.h" +#include "ILog.h" +#include "TcpModule.h" +#include +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 TCP_MODULE_WRITE_ERROR; +} +void ITcpClient::Closed(void) +{ +} +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 00000000..8948a45d --- /dev/null +++ b/utils/TcpModule/src/ITcpClient.h @@ -0,0 +1,40 @@ +/* + * 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 +class ITcpClient +{ +public: + ITcpClient() = default; + 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 +{ + 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/ITcpServer.cpp b/utils/TcpModule/src/ITcpServer.cpp new file mode 100644 index 00000000..a26c05c7 --- /dev/null +++ b/utils/TcpModule/src/ITcpServer.cpp @@ -0,0 +1,59 @@ +/* + * 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 "ITcpServer.h" +#include "ILog.h" +#include "TcpModule.h" +#include +void ITcpClientAccept::Close(void) +{ +} +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) +{ +} +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; +} +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 new file mode 100644 index 00000000..098ad0b0 --- /dev/null +++ b/utils/TcpModule/src/ITcpServer.h @@ -0,0 +1,55 @@ +/* + * 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 "TcpModule.h" +#include +class ITcpClientAccept +{ +public: + ITcpClientAccept() = default; + virtual ~ITcpClientAccept() = default; + 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); +}; +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); +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 new file mode 100644 index 00000000..5d76d64e --- /dev/null +++ b/utils/TcpModule/src/TcpClientImpl.cpp @@ -0,0 +1,128 @@ +/* + * 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 +static void on_message(hio_t *io, void *buf, int len) +{ + LogInfo("onmessage: %.*s\n", len, (char *)buf); + 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)); + 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 *tcpClient = (TcpClientImpl *)hevent_userdata(io); + tcpClient->Closed(); +} +TcpClientImpl::TcpClientImpl(const TcpClientParam ¶m, const void *object) : mParam(param), mObjectThis(object) +{ +} +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 != mIo) { + LogInfo("Close io.\n"); + hio_close(mIo); + mIo = nullptr; + } + if (mTcpClientThread.joinable()) { + mTcpClientThread.join(); + } +} +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) +{ + std::lock_guard locker(mMutex); + if (nullptr == mIo) { + LogError("mIo is nullptr.\n"); + return TCP_MODULE_WRITE_ERROR; + } + return hio_write(mIo, buf, bufLenght); +} +void TcpClientImpl::Closed(void) +{ + std::lock_guard locker(mMutex); + mIo = nullptr; + if (nullptr != mParam.mClosedFunc) { + mParam.mClosedFunc(mObjectThis); + } + if (nullptr != mLoop) { + LogInfo("Stop loop.\n"); + hloop_stop(mLoop); + } +} +void TcpClientImpl::Loop(void) +{ + if (nullptr == mLoop) { + LogError("mLoop is null\n"); + return; + } + hloop_run(mLoop); + hloop_free(&mLoop); + mLoop = nullptr; +} +std::shared_ptr *NewTcpClient(const TcpClientParam ¶m) +{ + 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(); + 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 new file mode 100644 index 00000000..4e0a3379 --- /dev/null +++ b/utils/TcpModule/src/TcpClientImpl.h @@ -0,0 +1,46 @@ +/* + * 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 +#include +class TcpClientImpl : public ITcpClient, public std::enable_shared_from_this +{ +public: + 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: + std::mutex mMutex; + hloop_t *mLoop; + hio_t *mIo; + const TcpClientParam mParam; + std::thread mTcpClientThread; + const void *mObjectThis; +}; +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 544800d0..9401ee7b 100644 --- a/utils/TcpModule/src/TcpModule.cpp +++ b/utils/TcpModule/src/TcpModule.cpp @@ -13,9 +13,84 @@ * 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 TcpServerParam 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? + } +} +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 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); + 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 8d96ffe3..08e20a87 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 TcpClientParam &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 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 e1430261..3320ea42 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 uart_device_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 TcpClientParam &uatrInfo); +// virtual ~TcpModuleImpl() = default; -private: - const StatusCode SetConfig(void); +// private: +// const StatusCode SetConfig(void); -private: - const TcpPram mUatrInfo; - int mFd; -}; +// private: +// const TcpClientParam 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 TcpClientParam &tcpParam); +// void *NewTcpServer(const TcpClientParam &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/TcpModuleMakePtr.cpp b/utils/TcpModule/src/TcpModuleMakePtr.cpp new file mode 100644 index 00000000..975d350f --- /dev/null +++ b/utils/TcpModule/src/TcpModuleMakePtr.cpp @@ -0,0 +1,34 @@ +/* + * 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 "TcpModuleMakePtr.h" +#include "ILog.h" +#include "TcpClientImpl.h" +#include "TcpServerImpl.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 TcpServerParam ¶m) +{ + return NewTcpServer(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 new file mode 100644 index 00000000..f381029b --- /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 "ITcpClient.h" +#include "ITcpServer.h" +#include "StatusCode.h" +#include "TcpModule.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 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/TcpServerHandle.cpp b/utils/TcpModule/src/TcpServerHandle.cpp new file mode 100644 index 00000000..3006dc0f --- /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/TcpServerHandle.h b/utils/TcpModule/src/TcpServerHandle.h new file mode 100644 index 00000000..8413bec6 --- /dev/null +++ b/utils/TcpModule/src/TcpServerHandle.h @@ -0,0 +1,32 @@ +/* + * 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_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 00000000..231a1c26 --- /dev/null +++ b/utils/TcpModule/src/TcpServerImpl.cpp @@ -0,0 +1,248 @@ +/* + * 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 void on_close(hio_t *io) +{ + LogInfo("on_close fd=%d error=%d\n", hio_fd(io), hio_error(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); + 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); + 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) +{ + 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); + server->AddClient(io); + hio_read_start(io); +} +TcpClientAcceptImpl::TcpClientAcceptImpl(const hio_t *io, const void *object, const ClientAcceptParam ¶m) + : mIo(io), mObjectThis(object), mParam(param) +{ +} +void TcpClientAcceptImpl::Close(void) +{ + if (nullptr != mIo) { + hio_t *io = (hio_t *)mIo; + hio_close(io); + } +} +void TcpClientAcceptImpl::Readed(const void *data, size_t length) +{ + if (nullptr != mParam.mReadFunc) { + mParam.mReadFunc(data, length, mObjectThis); + return; + } + LogWarning("mParam.mClosedFunc is null\n"); +} +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) +{ + 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; +} +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; + 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) { + tcpServer->Loop(); + }; + mTcpServerThread = std::thread(recvThread, impl); +} +void TcpServerImpl::UnInit(void) +{ + LogInfo("UnInit TcpServerImpl\n"); + FreeClients(); + if (nullptr != mIo) { + hio_close(mIo); + mIo = nullptr; + } + if (mTcpServerThread.joinable()) { + mTcpServerThread.join(); + } +} +void TcpServerImpl::Loop(void) +{ + if (nullptr == mLoop) { + LogError("mLoop is null\n"); + return; + } + hloop_run(mLoop); + hloop_free(&mLoop); + mLoop = nullptr; +} +void TcpServerImpl::AddClient(hio_t *io) +{ + 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)); + std::shared_ptr *addClient = NewTcpClientAccept(io, mParam.mClientAcceptParam); + mClients[hio_fd(io)] = addClient; + if (mParam.mAcceptClientFunc) { + 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) +{ + 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) { + void *object = (void *)client.second; + if (TcpClientAcceptObjectCheck(object) == true) { + (*(std::shared_ptr *)object)->Closed(); + (*(std::shared_ptr *)object).reset(); + free(((char *)object) - sizeof(ITcpServerHeader)); + } + } + } + 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"); + 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, const ClientAcceptParam ¶m) +{ + 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(); + std::shared_ptr *objectThis = + (std::shared_ptr *)(((char *)impl) + sizeof(ITcpServerHeader)); + 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 new file mode 100644 index 00000000..007f63fb --- /dev/null +++ b/utils/TcpModule/src/TcpServerImpl.h @@ -0,0 +1,64 @@ +/* + * 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 +#include +class TcpClientAcceptImpl : public ITcpClientAccept, public std::enable_shared_from_this +{ +public: + TcpClientAcceptImpl(const hio_t *io, const void *object, const ClientAcceptParam ¶m); + virtual ~TcpClientAcceptImpl() = default; + 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; + +private: + const hio_t *mIo; + const void *mObjectThis; + const ClientAcceptParam mParam; +}; +class TcpServerImpl : public ITcpServer, public std::enable_shared_from_this +{ +public: + TcpServerImpl(const TcpServerParam param); + virtual ~TcpServerImpl() = default; + void Init(void) override; + void UnInit(void) override; + void Loop(void); + void AddClient(hio_t *io); + std::shared_ptr *GetClient(hio_t *io); + void RemoveClient(hio_t *io); + void FreeClients(void); + void Closed(void); + +private: + std::mutex mMutex; + hloop_t *mLoop; + hio_t *mIo; + const TcpServerParam mParam; + std::thread mTcpServerThread; + std::map *> mClients; +}; +std::shared_ptr *NewTcpServer(const TcpServerParam ¶m); +std::shared_ptr *NewTcpClientAccept(const hio_t *io, const ClientAcceptParam ¶m); +#endif \ No newline at end of file