Merge branch 'master-develop' of gitee.com:shenzhen-jiuyilian/ipc into master-develop

This commit is contained in:
Fancy code 2024-04-17 13:21:10 +08:00
commit 1e42c00ae2
68 changed files with 3131 additions and 324 deletions

View File

@ -22,7 +22,7 @@ void TestMissionState::GoInState()
{ {
MissionState::GoInState(); MissionState::GoInState();
LogInfo(" ========== TestMissionState::GoInState.\n"); 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); IAppManager::GetInstance()->Init(mAppParam);
std::shared_ptr<VAppMonitor> monitor = std::shared_ptr<VAppMonitor> monitor =
std::dynamic_pointer_cast<TestMissionState>(MissionState::shared_from_this()); std::dynamic_pointer_cast<TestMissionState>(MissionState::shared_from_this());

View File

@ -68,7 +68,8 @@ set(CURL_SHARED_LIBS_PATH "/mnt/mmc")
# ------------ build curl + openssl ------------ end # ------------ build curl + openssl ------------ end
# ------------ build AppManager ------------ # # ------------ build AppManager ------------ #
# set(APP_MANAGER_HTTP_SERVER_IP "localhost") set(APP_MANAGER_DEVICE_IP "localhost")
set(APP_MANAGER_HTTP_SERVER_IP "192.168.1.29") # set(APP_MANAGER_DEVICE_IP "192.168.1.29")
set(APP_MANAGER_HTTP_SERVER_PORT "8080") set(APP_MANAGER_HTTP_SERVER_PORT "8080")
set(APP_MANAGER_TCP_SERVER_PORT "9876")
# ------------ build AppManager end ------------ # # ------------ build AppManager end ------------ #

View File

@ -99,8 +99,8 @@ set(SRCDIR src)
set(LIBDIR lib) set(LIBDIR lib)
set(BINDIR bin) set(BINDIR bin)
# ================== added by xiao ================== # # ================== added by xiao ================== #
set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${LIBS_OUTPUT_PATH}) set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${EXTERNAL_LIBS_OUTPUT_PATH})
set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${LIBS_OUTPUT_PATH}) set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${EXTERNAL_LIBS_OUTPUT_PATH})
# ================== added by xiao ================== # # ================== added by xiao ================== #
set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/${BINDIR}) set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/${BINDIR})
message(STATUS "CMAKE_LIBRARY_OUTPUT_DIRECTORY=${CMAKE_LIBRARY_OUTPUT_DIRECTORY}") message(STATUS "CMAKE_LIBRARY_OUTPUT_DIRECTORY=${CMAKE_LIBRARY_OUTPUT_DIRECTORY}")

View File

@ -11,6 +11,7 @@ include_directories(
${UTILS_SOURCE_PATH}/Log/include ${UTILS_SOURCE_PATH}/Log/include
${UTILS_SOURCE_PATH}/FxHttpServer/include ${UTILS_SOURCE_PATH}/FxHttpServer/include
${UTILS_SOURCE_PATH}/WebServer/include ${UTILS_SOURCE_PATH}/WebServer/include
${UTILS_SOURCE_PATH}/TcpModule/include
${HAL_SOURCE_PATH}/include ${HAL_SOURCE_PATH}/include
${EXTERNAL_SOURCE_PATH}/cJSON-1.7.17 ${EXTERNAL_SOURCE_PATH}/cJSON-1.7.17
) )
@ -24,7 +25,7 @@ aux_source_directory(./src/Protocol/SixFrame SRC_FILES)
set(TARGET_NAME AppManager) set(TARGET_NAME AppManager)
add_library(${TARGET_NAME} STATIC ${SRC_FILES}) 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") if ("${COMPILE_IMPROVE_SUPPORT}" MATCHES "true")
add_custom_target( add_custom_target(

View File

@ -1,8 +1,8 @@
if (NOT DEFINED APP_MANAGER_HTTP_SERVER_IP) if (NOT DEFINED APP_MANAGER_DEVICE_IP)
set(APP_MANAGER_HTTP_SERVER_IP "localhost") set(APP_MANAGER_DEVICE_IP "localhost")
endif() 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) if (NOT DEFINED APP_MANAGER_HTTP_SERVER_PORT)
message(FATAL_ERROR "You should set http listen 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") Refer to:${IPC_SDK_PATH}/builde/cmake/toolchain/linux.toolchain.cmake")
endif() endif()
add_definitions(-DAPP_MANAGER_HTTP_SERVER_PORT=${APP_MANAGER_HTTP_SERVER_PORT}) 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})

View File

@ -151,11 +151,27 @@ enum class FileCopy
SUPPORT_COPY, SUPPORT_COPY,
END 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 typedef struct app_get_product_info
{ {
app_get_product_info() app_get_product_info();
{
}
std::string mModel; std::string mModel;
std::string mCompany; std::string mCompany;
std::string mSoc; std::string mSoc;
@ -163,9 +179,7 @@ typedef struct app_get_product_info
} AppGetProductInfo; } AppGetProductInfo;
typedef struct app_get_device_attr typedef struct app_get_device_attr
{ {
app_get_device_attr() app_get_device_attr();
{
}
std::string mUUID; std::string mUUID;
std::string mSoftVersion; std::string mSoftVersion;
std::string mOtaVersion; std::string mOtaVersion;
@ -178,61 +192,33 @@ typedef struct app_get_device_attr
} AppGetDeviceAttr; } AppGetDeviceAttr;
typedef struct app_get_media_info typedef struct app_get_media_info
{ {
app_get_media_info() app_get_media_info();
{
mPort = -1;
}
std::string mRtspUrl; std::string mRtspUrl;
std::string mTransport; std::string mTransport;
int mPort; int mPort;
} AppGetMeidaInfo; } AppGetMeidaInfo;
typedef struct app_get_sd_card_info typedef struct app_get_sd_card_info
{ {
app_get_sd_card_info() app_get_sd_card_info();
{
mStatus = SdCardStatus::END;
mFree = 0;
mTotal = 0;
}
SdCardStatus mStatus; SdCardStatus mStatus;
int mFree; int mFree;
int mTotal; int mTotal;
} AppGetSdCardInfo; } AppGetSdCardInfo;
typedef struct app_get_battery_info typedef struct app_get_battery_info
{ {
app_get_battery_info() app_get_battery_info();
{
mCapacity = 0;
mChargeStatus = ChargeStatus::END;
}
int mCapacity; int mCapacity;
ChargeStatus mChargeStatus; ChargeStatus mChargeStatus;
} AppGetBatteryInfo; } AppGetBatteryInfo;
typedef struct app_get_param_value typedef struct app_get_param_value
{ {
app_get_param_value() app_get_param_value();
{
mRec = SwitchStatus::END;
mMicStatus = SwitchStatus::END;
}
SwitchStatus mMicStatus; SwitchStatus mMicStatus;
SwitchStatus mRec; SwitchStatus mRec;
} AppParamValue; } AppParamValue;
typedef struct app_get_capability typedef struct app_get_capability
{ {
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;
}
GpsCapability mGpsCapability; GpsCapability mGpsCapability;
DeviceType mDeviceType; DeviceType mDeviceType;
DashAlbum mAlbum; DashAlbum mAlbum;
@ -246,13 +232,7 @@ typedef struct app_get_capability
} AppGetCapability; } AppGetCapability;
typedef struct app_get_storage_info typedef struct app_get_storage_info
{ {
app_get_storage_info() app_get_storage_info();
{
mIndex = -1;
mType = StorageType::END;
mFree = 0;
mTotal = 0;
}
int mIndex; int mIndex;
StorageType mType; StorageType mType;
std::string mName; std::string mName;
@ -261,25 +241,14 @@ typedef struct app_get_storage_info
} AppGetStorageInfo; } AppGetStorageInfo;
typedef struct app_get_file_info typedef struct app_get_file_info
{ {
app_get_file_info() app_get_file_info();
{
mStartIndex = 0;
mStopIndex = 0;
mEvent = StorageFileEvent::END;
}
int mStartIndex; int mStartIndex;
int mStopIndex; int mStopIndex;
StorageFileEvent mEvent; StorageFileEvent mEvent;
} AppGetFileInfo; } AppGetFileInfo;
typedef struct app_get_file_list typedef struct app_get_file_list
{ {
app_get_file_list() app_get_file_list();
{
mDuration = 0;
mSize = 0;
mCreateTime_s = 0;
mType = StorageFileType::END;
}
std::string mName; std::string mName;
int mDuration; int mDuration;
int mSize; int mSize;
@ -288,20 +257,14 @@ typedef struct app_get_file_list
} AppGetFileList; } AppGetFileList;
typedef struct app_set_param_value typedef struct app_set_param_value
{ {
app_set_param_value() app_set_param_value();
{
mValue = -1;
}
std::string mName; std::string mName;
int mValue; int mValue;
} AppSetParamValue; } AppSetParamValue;
typedef struct app_set_date_time typedef struct app_set_date_time
{ {
app_set_date_time(const unsigned int year, const unsigned int month, const unsigned int day, 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) 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 mYear; const unsigned int mYear;
const unsigned int mMonth; const unsigned int mMonth;
const unsigned int mDay; const unsigned int mDay;
@ -311,22 +274,36 @@ typedef struct app_set_date_time
} AppSetDateTime; } AppSetDateTime;
typedef struct app_upload_file typedef struct app_upload_file
{ {
app_upload_file(const std::string filePath, const UploadCommand command) : mFilePath(filePath), mCommand(command) app_upload_file(const std::string filePath, const UploadCommand command);
{
mResult = ResposeResult::END;
}
const std::string mFilePath; const std::string mFilePath;
const UploadCommand mCommand; const UploadCommand mCommand;
ResposeResult mResult; ResposeResult mResult;
} AppUploadFile; } AppUploadFile;
typedef struct app_get_thumbnail 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; const std::string mFile;
std::string mThumbnail; std::string mThumbnail;
} AppGetThumbnail; } 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 class VAppMonitor
{ {
public: public:
@ -349,15 +326,8 @@ public:
virtual StatusCode AppPlayback(const PlayBackEvent &event); virtual StatusCode AppPlayback(const PlayBackEvent &event);
virtual StatusCode UploadFile(AppUploadFile &param); virtual StatusCode UploadFile(AppUploadFile &param);
virtual StatusCode GetThumbnail(AppGetThumbnail &param); virtual StatusCode GetThumbnail(AppGetThumbnail &param);
virtual StatusCode AppClientConnected(std::shared_ptr<VAppClient> &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 class IAppManager
{ {
public: public:

View File

@ -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<ProtocolPacket> packet = IAppProtocolHandle::GetInstance()->SetRecordingStatus(status);
AcceptClientWrite((void *)mClientObject, packet->mData, packet->mDataLength);
}
void AppClient::SetMicrophoneStatus(const MicrophoneStatus &status)
{
std::shared_ptr<ProtocolPacket> packet = IAppProtocolHandle::GetInstance()->SetMicrophoneStatus(status);
AcceptClientWrite((void *)mClientObject, packet->mData, packet->mDataLength);
}
void AppClient::SetBatteryStatus(const BatteryStatus &status, const int &batteryCapacity)
{
std::shared_ptr<ProtocolPacket> packet =
IAppProtocolHandle::GetInstance()->SetBatteryStatus(status, batteryCapacity);
AcceptClientWrite((void *)mClientObject, packet->mData, packet->mDataLength);
}
void AppClient::SetSdCardStatus(const SdCardStatus &status)
{
std::shared_ptr<ProtocolPacket> 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<ProtocolPacket> 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<ProtocolPacket> packet = IAppProtocolHandle::GetInstance()->CreatedFileMessage(file, type);
AcceptClientWrite((void *)mClientObject, packet->mData, packet->mDataLength);
}

View File

@ -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

View File

@ -13,15 +13,15 @@
* limitations under the License. * limitations under the License.
*/ */
#include "AppManager.h" #include "AppManager.h"
#include "AppClient.h"
#include "AppManagerMakePtr.h" #include "AppManagerMakePtr.h"
// #include "FxHttpServer.h"
#include "IHalCpp.h" #include "IHalCpp.h"
#include "ILog.h" #include "ILog.h"
#include "TcpModule.h"
#include "WebServer.h" #include "WebServer.h"
AppManager::AppManager() AppManager::AppManager()
{ {
// mHttpServerRuning = false; mTcpServer = nullptr;
mProtocolHandle = std::make_shared<IAppProtocolHandle>();
} }
const StatusCode AppManager::Init(const AppParam &param) const StatusCode AppManager::Init(const AppParam &param)
{ {
@ -33,26 +33,53 @@ const StatusCode AppManager::Init(const AppParam &param)
} }
LogInfo("ssssssssssssssssssssssssssssssssssssssssssssssssss\n"); LogInfo("ssssssssssssssssssssssssssssssssssssssssssssssssss\n");
wifi->OpenApMode(); wifi->OpenApMode();
AppManagerMakePtr::GetInstance()->CreateProtocolHandle(mProtocolHandle); std::shared_ptr<IAppProtocolHandle> protocolHandle;
AppManagerMakePtr::GetInstance()->CreateProtocolHandle(protocolHandle);
IAppProtocolHandle::GetInstance(&protocolHandle);
HttpServerStart(param); HttpServerStart(param);
TcpServerStart(param);
return CreateStatusCode(STATUS_CODE_OK); return CreateStatusCode(STATUS_CODE_OK);
} }
const StatusCode AppManager::UnInit(void) const StatusCode AppManager::UnInit(void)
{ {
HttpServerStop(); HttpServerStop();
mProtocolHandle.reset(); TcpServerStop();
std::shared_ptr<IAppProtocolHandle> protocolHandle = std::make_shared<IAppProtocolHandle>();
IAppProtocolHandle::GetInstance(&protocolHandle);
mAppMonitor.reset();
return CreateStatusCode(STATUS_CODE_OK); return CreateStatusCode(STATUS_CODE_OK);
} }
const StatusCode AppManager::SetAppMonitor(std::shared_ptr<VAppMonitor> &monitor) const StatusCode AppManager::SetAppMonitor(std::shared_ptr<VAppMonitor> &monitor)
{ {
mProtocolHandle->SetAppMonitor(monitor); IAppProtocolHandle::GetInstance()->SetAppMonitor(monitor);
mAppMonitor = monitor;
return CreateStatusCode(STATUS_CODE_OK); return CreateStatusCode(STATUS_CODE_OK);
} }
void AppManager::AppRequestHandle(const char *url, const unsigned int urlLength, ResponseHandle responseHandle, void AppManager::AppRequestHandle(const char *url, const unsigned int urlLength, ResponseHandle responseHandle,
void *context) void *context)
{ {
// IAppProtocolHandle::GetInstance()->RequestHandle(url, urlLength, responseHandle, context);
mProtocolHandle->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<AppClient>(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 &param) void AppManager::HttpServerStart(const AppParam &param)
{ {
@ -64,7 +91,6 @@ void AppManager::HttpServerStart(const AppParam &param)
} }
void AppManager::HttpServerStop(void) void AppManager::HttpServerStop(void)
{ {
// FxHttpServerExit();
WebServerExit(); WebServerExit();
if (mHttpSever.joinable()) { if (mHttpSever.joinable()) {
mHttpSever.join(); mHttpSever.join();
@ -82,9 +108,53 @@ void AppManager::HttpServerThread(const AppParam &param)
appImpl->AppRequestHandle(url, urlLength, responseHandle, context); appImpl->AppRequestHandle(url, urlLength, responseHandle, context);
} }
}; };
// FxHttpServerInit(httpHandle, 8080); WebServerParam web = {.mIp = param.mIP, .mPort = param.mHttpPort, .mHttpRequestHandle = httpHandle};
// FxHttpServerUnInit();
WebServerParam web = {.mIp = param.mIP, .mPort = param.mPort, .mHttpRequestHandle = httpHandle};
WebServerInit(web); WebServerInit(web);
WebServerUnInit(); WebServerUnInit();
}
void AppManager::TcpServerStart(const AppParam &param)
{
auto acceptClientFunc = [](void *object, const char *ip) -> bool {
LogInfo("accept client, peer ip: %s\n", ip);
if (nullptr != object) {
std::shared_ptr<IAppManager> app = IAppManager::GetInstance();
std::shared_ptr<AppManager> appImpl = std::dynamic_pointer_cast<AppManager>(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<IAppManager> app = IAppManager::GetInstance();
std::shared_ptr<AppManager> appImpl = std::dynamic_pointer_cast<AppManager>(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);
}
} }

View File

@ -16,6 +16,7 @@
#define APP_MANAGER_H #define APP_MANAGER_H
#include "IAppManager.h" #include "IAppManager.h"
#include "IAppProtocolHandle.h" #include "IAppProtocolHandle.h"
#include <map>
#include <thread> #include <thread>
class AppManager : public IAppManager, public std::enable_shared_from_this<AppManager> class AppManager : public IAppManager, public std::enable_shared_from_this<AppManager>
{ {
@ -26,6 +27,10 @@ public:
const StatusCode UnInit(void) override; const StatusCode UnInit(void) override;
const StatusCode SetAppMonitor(std::shared_ptr<VAppMonitor> &monitor) override; const StatusCode SetAppMonitor(std::shared_ptr<VAppMonitor> &monitor) override;
void AppRequestHandle(const char *url, const unsigned int urlLength, ResponseHandle responseHandle, void *context); 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: private:
void HttpServerStart(const AppParam &param); void HttpServerStart(const AppParam &param);
@ -33,9 +38,15 @@ private:
void HttpServerThread(const AppParam &param); void HttpServerThread(const AppParam &param);
private: private:
// bool mHttpServerRuning; void TcpServerStart(const AppParam &param);
void TcpServerStop(void);
private:
std::thread mHttpSever; std::thread mHttpSever;
std::shared_ptr<IAppProtocolHandle> mProtocolHandle; std::shared_ptr<IAppProtocolHandle> mProtocolHandle;
void *mTcpServer;
std::shared_ptr<VAppMonitor> mAppMonitor;
std::map<void *, std::shared_ptr<VAppClient>> mAppClients;
}; };
#endif #endif

View File

@ -14,6 +14,104 @@
*/ */
#include "IAppManager.h" #include "IAppManager.h"
#include "ILog.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 &param) StatusCode VAppMonitor::GetProductInfo(AppGetProductInfo &param)
{ {
return CreateStatusCode(STATUS_CODE_VIRTUAL_FUNCTION); return CreateStatusCode(STATUS_CODE_VIRTUAL_FUNCTION);
@ -82,6 +180,10 @@ StatusCode VAppMonitor::GetThumbnail(AppGetThumbnail &param)
{ {
return CreateStatusCode(STATUS_CODE_VIRTUAL_FUNCTION); return CreateStatusCode(STATUS_CODE_VIRTUAL_FUNCTION);
} }
StatusCode VAppMonitor::AppClientConnected(std::shared_ptr<VAppClient> &client)
{
return CreateStatusCode(STATUS_CODE_VIRTUAL_FUNCTION);
}
std::shared_ptr<IAppManager> &IAppManager::GetInstance(std::shared_ptr<IAppManager> *impl) std::shared_ptr<IAppManager> &IAppManager::GetInstance(std::shared_ptr<IAppManager> *impl)
{ {
static auto instance = std::make_shared<IAppManager>(); static auto instance = std::make_shared<IAppManager>();

View File

@ -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> &IAppProtocolHandle::GetInstance(std::shared_ptr<IAppProtocolHandle> *impl)
{
static auto instance = std::make_shared<IAppProtocolHandle>();
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<VAppMonitor> &monitor)
{
}
std::shared_ptr<ProtocolPacket> IAppProtocolHandle::SetRecordingStatus(const RecordingStatus &status)
{
return std::make_shared<ProtocolPacket>();
}
std::shared_ptr<ProtocolPacket> IAppProtocolHandle::SetMicrophoneStatus(const MicrophoneStatus &status)
{
return std::make_shared<ProtocolPacket>();
}
std::shared_ptr<ProtocolPacket> IAppProtocolHandle::SetBatteryStatus(const BatteryStatus &status,
const int &batteryCapacity)
{
return std::make_shared<ProtocolPacket>();
}
std::shared_ptr<ProtocolPacket> IAppProtocolHandle::SetSdCardStatus(const SdCardStatus &status)
{
return std::make_shared<ProtocolPacket>();
}
std::shared_ptr<ProtocolPacket> IAppProtocolHandle::DeletedFileMessage(const std::string &file,
const StorageFileType &type)
{
return std::make_shared<ProtocolPacket>();
}
std::shared_ptr<ProtocolPacket> IAppProtocolHandle::CreatedFileMessage(const std::string &file,
const StorageFileType &type)
{
return std::make_shared<ProtocolPacket>();
}

View File

@ -14,11 +14,24 @@
*/ */
#ifndef I_APP_PROTOCOL_HANDLE_H #ifndef I_APP_PROTOCOL_HANDLE_H
#define I_APP_PROTOCOL_HANDLE_H #define I_APP_PROTOCOL_HANDLE_H
#include "IAppManager.h"
#include "StatusCode.h" #include "StatusCode.h"
#include "WebServer.h" #include "WebServer.h"
#include <iostream> #include <iostream>
#include <memory> #include <memory>
#include <vector> #include <vector>
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 class VAppDataPacket
{ {
public: public:
@ -30,18 +43,19 @@ class IAppProtocolHandle
public: public:
IAppProtocolHandle() = default; IAppProtocolHandle() = default;
virtual ~IAppProtocolHandle() = default; virtual ~IAppProtocolHandle() = default;
virtual void Init(void) static std::shared_ptr<IAppProtocolHandle> &GetInstance(std::shared_ptr<IAppProtocolHandle> *impl = nullptr);
{ virtual void Init(void);
} virtual void UnInit(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,
virtual void RequestHandle(const char *url, const unsigned int urlLength, ResponseHandle responseHandle, void *context);
void *context) virtual void SetAppMonitor(std::shared_ptr<VAppMonitor> &monitor);
{ virtual std::shared_ptr<ProtocolPacket> SetRecordingStatus(const RecordingStatus &status);
} virtual std::shared_ptr<ProtocolPacket> SetMicrophoneStatus(const MicrophoneStatus &status);
virtual void SetAppMonitor(std::shared_ptr<VAppMonitor> &monitor) virtual std::shared_ptr<ProtocolPacket> SetBatteryStatus(const BatteryStatus &status, const int &batteryCapacity);
{ virtual std::shared_ptr<ProtocolPacket> SetSdCardStatus(const SdCardStatus &status);
} virtual std::shared_ptr<ProtocolPacket> DeletedFileMessage(const std::string &file, const StorageFileType &type);
virtual std::shared_ptr<ProtocolPacket> CreatedFileMessage(const std::string &file, const StorageFileType &type);
}; };
#endif #endif

View File

@ -14,13 +14,16 @@
*/ */
#include "SixFrameHandle.h" #include "SixFrameHandle.h"
#include "ILog.h" #include "ILog.h"
#include <cstring>
#include <sstream> #include <sstream>
#include <stdio.h> #include <stdio.h>
#include <time.h>
using std::placeholders::_1; using std::placeholders::_1;
using std::placeholders::_2; using std::placeholders::_2;
using std::placeholders::_3; using std::placeholders::_3;
// using std::placeholders::_4; // using std::placeholders::_4;
// clang-format off // clang-format off
const char *TCP_RESULT_MSGID = "msgid";
const char *CJSON_INFO_STRING = "info"; const char *CJSON_INFO_STRING = "info";
const char *CJSON_FILES_STRING = "files"; const char *CJSON_FILES_STRING = "files";
const char *APP_GET_PRODUCT_INFO = "/app/getproductinfo"; const char *APP_GET_PRODUCT_INFO = "/app/getproductinfo";
@ -44,6 +47,22 @@ const char *APP_GET_THUMBNAIL = "/app/getthumbnail";
// /app/exitrecorder // /app/exitrecorder
// clang-format on // clang-format on
constexpr bool SET_REQUEST_RESPONSE = true; 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() SixFrameHandle::SixFrameHandle()
{ {
mAppMonitor = std::make_shared<VAppMonitor>(); mAppMonitor = std::make_shared<VAppMonitor>();
@ -67,7 +86,7 @@ SixFrameHandle::SixFrameHandle()
mResquesHandleFunc[APP_GET_THUMBNAIL] = std::bind(&SixFrameHandle::RequestGetThumbnail, this, _1, _2, _3); mResquesHandleFunc[APP_GET_THUMBNAIL] = std::bind(&SixFrameHandle::RequestGetThumbnail, this, _1, _2, _3);
// mResquesHandleFunc["favicon.ico"] = std::bind(&SixFrameHandle::DoNothing, this, _1, _2, _); // 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) void *context)
{ {
const std::string urlStr2 = url; 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()); command = urlStr2.substr(0, urlStr2.length());
} }
LogInfo("command = %s\n", command.c_str()); LogInfo("command = %s\n", command.c_str());
// ExtractParamsFromUrl(urlStr2, paramsMap);
RequestHandle2(command, urlStr2, responseHandle, context); 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, void SixFrameHandle::ExtractParamsFromUrl(const std::string &url, ParseUrlResultFunc resultHandle,
std::shared_ptr<VParseUrl> &context) std::shared_ptr<VParseUrl> &context)
{ {
@ -662,6 +699,116 @@ void SixFrameHandle::RequestGetThumbnail(const std::string &url, ResponseHandle
// respon.mThumbnail = "./34a396526922a33e97906920dbfef2a5.jpg"; // respon.mThumbnail = "./34a396526922a33e97906920dbfef2a5.jpg";
responseHandle(respon.mThumbnail.c_str(), context); responseHandle(respon.mThumbnail.c_str(), context);
} }
void SixFrameHandle::RequestTcpHandle2(const std::string command, const cJSON *const data,
ResponseHandle responseHandle, void *context)
{
}
std::shared_ptr<ProtocolPacket> 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<ProtocolPacket>();
}
cJSON_AddStringToObject(resultCJSON, TCP_RESULT_MSGID, "rec");
cJSON *info = cJSON_CreateObject();
if (nullptr != info) {
cJSON_AddNumberToObject(info, "value", static_cast<int>(status));
cJSON_AddItemToObject(resultCJSON, CJSON_INFO_STRING, info);
}
AddTimestamp(resultCJSON);
return MakePacket(resultCJSON);
}
std::shared_ptr<ProtocolPacket> 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<ProtocolPacket>();
}
cJSON_AddStringToObject(resultCJSON, TCP_RESULT_MSGID, "mic");
cJSON *info = cJSON_CreateObject();
if (nullptr != info) {
cJSON_AddNumberToObject(info, "value", static_cast<int>(status));
cJSON_AddItemToObject(resultCJSON, CJSON_INFO_STRING, info);
}
AddTimestamp(resultCJSON);
return MakePacket(resultCJSON);
}
std::shared_ptr<ProtocolPacket> 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<ProtocolPacket>();
}
cJSON_AddStringToObject(resultCJSON, TCP_RESULT_MSGID, "battery");
cJSON *info = cJSON_CreateObject();
if (nullptr != info) {
cJSON_AddNumberToObject(info, "charge", static_cast<int>(status));
cJSON_AddNumberToObject(info, "capacity", batteryCapacity);
cJSON_AddItemToObject(resultCJSON, CJSON_INFO_STRING, info);
}
AddTimestamp(resultCJSON);
return MakePacket(resultCJSON);
}
std::shared_ptr<ProtocolPacket> 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<ProtocolPacket>();
}
cJSON_AddStringToObject(resultCJSON, TCP_RESULT_MSGID, "sd");
cJSON *info = cJSON_CreateObject();
if (nullptr != info) {
cJSON_AddNumberToObject(info, "status", static_cast<int>(status));
cJSON_AddItemToObject(resultCJSON, CJSON_INFO_STRING, info);
}
AddTimestamp(resultCJSON);
return MakePacket(resultCJSON);
}
std::shared_ptr<ProtocolPacket> 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<ProtocolPacket>();
}
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<int>(type));
cJSON_AddItemToObject(resultCJSON, CJSON_INFO_STRING, info);
}
AddTimestamp(resultCJSON);
return MakePacket(resultCJSON);
}
std::shared_ptr<ProtocolPacket> 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<ProtocolPacket>();
}
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<int>(type));
cJSON_AddItemToObject(resultCJSON, CJSON_INFO_STRING, info);
}
AddTimestamp(resultCJSON);
return MakePacket(resultCJSON);
}
cJSON *SixFrameHandle::MakeResponseResult(const ResposeResult result, const bool requestSet) cJSON *SixFrameHandle::MakeResponseResult(const ResposeResult result, const bool requestSet)
{ {
const char *RESPONSE_RESULT = "result"; const char *RESPONSE_RESULT = "result";
@ -711,6 +858,29 @@ const char *SixFrameHandle::PrintfFileEvent(const AppGetFileInfo &fileInfo)
} }
return "unknown event"; 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<ProtocolPacket> SixFrameHandle::MakePacket(const cJSON *json)
{
char *resultStr = nullptr;
resultStr = cJSON_Print(json);
if (nullptr != resultStr) {
return std::make_shared<ProtocolPacket>(resultStr, strlen(resultStr));
}
else {
LogError("MakePacket failed.\n");
return std::make_shared<ProtocolPacket>();
}
}
void SixFrameHandle::SetAppMonitor(std::shared_ptr<VAppMonitor> &monitor) void SixFrameHandle::SetAppMonitor(std::shared_ptr<VAppMonitor> &monitor)
{ {
if (monitor) { if (monitor) {

View File

@ -51,8 +51,10 @@ public:
virtual ~SixFrameHandle() = default; virtual ~SixFrameHandle() = default;
// virtual void Init(void) {} // virtual void Init(void) {}
// virtual void UnInit(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 *context) override;
void RequestHandleTcp(const char *data, const unsigned int &dataLength, ResponseHandle responseHandle,
void *context) override;
private: private:
void ExtractParamsFromUrl(const std::string &url, ParseUrlResultFunc resultHandle, void ExtractParamsFromUrl(const std::string &url, ParseUrlResultFunc resultHandle,
@ -95,10 +97,22 @@ private:
std::string RequestGetThumbnailParse(const std::string &url); std::string RequestGetThumbnailParse(const std::string &url);
void RequestGetThumbnail(const std::string &url, ResponseHandle responseHandle, void *context); 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<ProtocolPacket> SetRecordingStatus(const RecordingStatus &status) override;
std::shared_ptr<ProtocolPacket> SetMicrophoneStatus(const MicrophoneStatus &status) override;
std::shared_ptr<ProtocolPacket> SetBatteryStatus(const BatteryStatus &status, const int &batteryCapacity) override;
std::shared_ptr<ProtocolPacket> SetSdCardStatus(const SdCardStatus &status) override;
std::shared_ptr<ProtocolPacket> DeletedFileMessage(const std::string &file, const StorageFileType &type) override;
std::shared_ptr<ProtocolPacket> CreatedFileMessage(const std::string &file, const StorageFileType &type) override;
private: private:
cJSON *MakeResponseResult(const ResposeResult result, const bool requestSet = false); cJSON *MakeResponseResult(const ResposeResult result, const bool requestSet = false);
void ResponseJsonString(cJSON *json, ResponseHandle responseHandle, void *context); void ResponseJsonString(cJSON *json, ResponseHandle responseHandle, void *context);
const char *PrintfFileEvent(const AppGetFileInfo &fileInfo); const char *PrintfFileEvent(const AppGetFileInfo &fileInfo);
void AddTimestamp(cJSON *json);
std::shared_ptr<ProtocolPacket> MakePacket(const cJSON *json);
protected: protected:
void SetAppMonitor(std::shared_ptr<VAppMonitor> &monitor) override; void SetAppMonitor(std::shared_ptr<VAppMonitor> &monitor) override;

View File

@ -8,7 +8,7 @@ include_directories(
./include ./include
${UTILS_SOURCE_PATH}/StatusCode/include ${UTILS_SOURCE_PATH}/StatusCode/include
${UTILS_SOURCE_PATH}/Log/include ${UTILS_SOURCE_PATH}/Log/include
${UTILS_SOURCE_PATH}/Config/include ${UTILS_SOURCE_PATH}/ConfigBase/include
) )
#do not rely on any other library #do not rely on any other library
#link_directories( #link_directories(

View File

@ -12,8 +12,8 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
#ifndef IIPCCONFIG_H #ifndef I_IPC_CONFIG_H
#define IIPCCONFIG_H #define I_IPC_CONFIG_H
#include "StatusCode.h" #include "StatusCode.h"
#include <iostream> #include <iostream>
#include <memory> #include <memory>
@ -96,89 +96,30 @@ class IIpcConfig
public: public:
IIpcConfig() = default; IIpcConfig() = default;
virtual ~IIpcConfig() = default; virtual ~IIpcConfig() = default;
virtual const StatusCode ConfigFileSave(void)
{
return CreateStatusCode(STATUS_CODE_OK);
}
static std::shared_ptr<IIpcConfig> &GetInstance(std::shared_ptr<IIpcConfig> *impl = nullptr); static std::shared_ptr<IIpcConfig> &GetInstance(std::shared_ptr<IIpcConfig> *impl = nullptr);
virtual const StatusCode Init(void) virtual const StatusCode ConfigFileSave(void);
{ virtual const StatusCode Init(void);
return CreateStatusCode(STATUS_CODE_OK); virtual const StatusCode UnInit(void);
} virtual const int GetInt(const IpcConfigKey &key);
virtual const StatusCode UnInit(void) virtual void SetInt(const IpcConfigKey &key, const int &value);
{ virtual const short GetShort(const IpcConfigKey &key);
return CreateStatusCode(STATUS_CODE_OK); virtual void SetShort(const IpcConfigKey &key, const short &value);
} virtual const long GetLong(const IpcConfigKey &key);
virtual const int GetInt(const IpcConfigKey &key) 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);
virtual void SetInt(const IpcConfigKey &key, const int &value) 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 short GetShort(const IpcConfigKey &key) virtual const double GetDouble(const IpcConfigKey &key);
{ virtual void SetDouble(const IpcConfigKey &key, const double &value);
return -1; virtual const long double GetLongDouble(const IpcConfigKey &key);
} virtual void SetLongDouble(const IpcConfigKey &key, const long double &value);
virtual void SetShort(const IpcConfigKey &key, const short &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 const long GetLong(const IpcConfigKey &key) virtual void SetString(const IpcConfigKey &key, const std::string string);
{
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)
{
}
}; };
bool CreateIpcConfig(void); bool CreateIpcConfig(void);
#endif #endif

View File

@ -27,4 +27,86 @@ std::shared_ptr<IIpcConfig> &IIpcConfig::GetInstance(std::shared_ptr<IIpcConfig>
} }
} }
return instance; 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)
{
} }

View File

@ -143,7 +143,7 @@ void IpcConfig::SetInt(const IpcConfigKey &key, const int &value)
iter = mCfgMapInt.find(key); iter = mCfgMapInt.find(key);
if (iter != mCfgMapInt.end() && CHECK_MAP(iter->second)) { if (iter != mCfgMapInt.end() && CHECK_MAP(iter->second)) {
iter->second.begin()->second.get() = value; 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); ConfigSetInt(mCfg, name, iter->second.begin()->second);
mCfgChanged = CONFIG_HAS_CHANGED; mCfgChanged = CONFIG_HAS_CHANGED;
} }
@ -168,7 +168,7 @@ void IpcConfig::SetShort(const IpcConfigKey &key, const short &value)
iter = mCfgMapShort.find(key); iter = mCfgMapShort.find(key);
if (iter != mCfgMapShort.end() && CHECK_MAP(iter->second)) { if (iter != mCfgMapShort.end() && CHECK_MAP(iter->second)) {
iter->second.begin()->second.get() = value; 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); ConfigSetShort(mCfg, name, iter->second.begin()->second);
mCfgChanged = CONFIG_HAS_CHANGED; mCfgChanged = CONFIG_HAS_CHANGED;
} }
@ -193,7 +193,7 @@ void IpcConfig::SetLong(const IpcConfigKey &key, const long &value)
iter = mCfgMapLong.find(key); iter = mCfgMapLong.find(key);
if (iter != mCfgMapLong.end() && CHECK_MAP(iter->second)) { if (iter != mCfgMapLong.end() && CHECK_MAP(iter->second)) {
iter->second.begin()->second.get() = value; 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); ConfigSetLong(mCfg, name, iter->second.begin()->second);
mCfgChanged = CONFIG_HAS_CHANGED; mCfgChanged = CONFIG_HAS_CHANGED;
} }
@ -218,7 +218,7 @@ void IpcConfig::SetLLong(const IpcConfigKey &key, const long long &value)
iter = mCfgMapLLong.find(key); iter = mCfgMapLLong.find(key);
if (iter != mCfgMapLLong.end() && CHECK_MAP(iter->second)) { if (iter != mCfgMapLLong.end() && CHECK_MAP(iter->second)) {
iter->second.begin()->second.get() = value; 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); ConfigSetLLong(mCfg, name, iter->second.begin()->second);
mCfgChanged = CONFIG_HAS_CHANGED; mCfgChanged = CONFIG_HAS_CHANGED;
} }
@ -243,7 +243,7 @@ void IpcConfig::SetChar(const IpcConfigKey &key, const char &character)
iter = mCfgMapChar.find(key); iter = mCfgMapChar.find(key);
if (iter != mCfgMapChar.end() && CHECK_MAP(iter->second)) { if (iter != mCfgMapChar.end() && CHECK_MAP(iter->second)) {
iter->second.begin()->second.get() = character; 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); ConfigSetChar(mCfg, name, iter->second.begin()->second);
mCfgChanged = CONFIG_HAS_CHANGED; mCfgChanged = CONFIG_HAS_CHANGED;
} }
@ -268,7 +268,7 @@ void IpcConfig::SetFloat(const IpcConfigKey &key, const float &value)
iter = mCfgMapFloat.find(key); iter = mCfgMapFloat.find(key);
if (iter != mCfgMapFloat.end() && CHECK_MAP(iter->second)) { if (iter != mCfgMapFloat.end() && CHECK_MAP(iter->second)) {
iter->second.begin()->second.get() = value; 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); ConfigSetFloat(mCfg, name, iter->second.begin()->second);
mCfgChanged = CONFIG_HAS_CHANGED; mCfgChanged = CONFIG_HAS_CHANGED;
} }
@ -293,7 +293,7 @@ void IpcConfig::SetDouble(const IpcConfigKey &key, const double &value)
iter = mCfgMapDouble.find(key); iter = mCfgMapDouble.find(key);
if (iter != mCfgMapDouble.end() && CHECK_MAP(iter->second)) { if (iter != mCfgMapDouble.end() && CHECK_MAP(iter->second)) {
iter->second.begin()->second.get() = value; 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); ConfigSetDouble(mCfg, name, iter->second.begin()->second);
mCfgChanged = CONFIG_HAS_CHANGED; mCfgChanged = CONFIG_HAS_CHANGED;
} }
@ -341,7 +341,7 @@ void IpcConfig::SetBool(const IpcConfigKey &key, const bool &value)
iter = mCfgMapBool.find(key); iter = mCfgMapBool.find(key);
if (iter != mCfgMapBool.end() && CHECK_MAP(iter->second)) { if (iter != mCfgMapBool.end() && CHECK_MAP(iter->second)) {
iter->second.begin()->second.get() = value; 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); ConfigSetBool(mCfg, name, iter->second.begin()->second);
mCfgChanged = CONFIG_HAS_CHANGED; mCfgChanged = CONFIG_HAS_CHANGED;
} }
@ -367,7 +367,7 @@ void IpcConfig::SetString(const IpcConfigKey &key, const std::string string)
iter = mCfgMapString.find(key); iter = mCfgMapString.find(key);
if (iter != mCfgMapString.end() && CHECK_MAP(iter->second)) { if (iter != mCfgMapString.end() && CHECK_MAP(iter->second)) {
strncpy(iter->second.begin()->second, string.c_str(), sizeof(CHAR_STRING)); // const std::strinbg --> char[] 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); ConfigSetString(mCfg, name, iter->second.begin()->second);
mCfgChanged = CONFIG_HAS_CHANGED; mCfgChanged = CONFIG_HAS_CHANGED;
} }
@ -402,7 +402,7 @@ void IpcConfig::ReadAllConfigParameters(void)
ConfigSetInt(mCfg, "burst_photo_interval", mAllData.burstPhotoInterval); ConfigSetInt(mCfg, "burst_photo_interval", mAllData.burstPhotoInterval);
} }
const char *imageSizeString = NULL; const char *imageSizeString = nullptr;
StatusCode imageSizeCode = ConfigGetString(mCfg, "image_size", &(imageSizeString)); StatusCode imageSizeCode = ConfigGetString(mCfg, "image_size", &(imageSizeString));
if (StatusCodeEqual(imageSizeCode, "CONFIG_CODE_PARAM_NOT_EXIST")) { if (StatusCodeEqual(imageSizeCode, "CONFIG_CODE_PARAM_NOT_EXIST")) {
LogWarning("image_size doesn't exist, will make it as default.\n"); 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); ConfigSetString(mCfg, "image_size", mAllData.imageSize);
} }
else { 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)); StatusCode videoSizeCode = ConfigGetInt(mCfg, "video_size", &(mAllData.videoSize));
@ -474,7 +479,7 @@ void IpcConfig::ReadAllConfigParameters(void)
ConfigSetBool(mCfg, "formatting_SD_card", mAllData.formattingSDCard); ConfigSetBool(mCfg, "formatting_SD_card", mAllData.formattingSDCard);
} }
const char *darkModeString = NULL; const char *darkModeString = nullptr;
StatusCode darkModeCode = ConfigGetString(mCfg, "dark_mode", &(darkModeString)); StatusCode darkModeCode = ConfigGetString(mCfg, "dark_mode", &(darkModeString));
if (StatusCodeEqual(darkModeCode, "CONFIG_CODE_PARAM_NOT_EXIST")) { if (StatusCodeEqual(darkModeCode, "CONFIG_CODE_PARAM_NOT_EXIST")) {
LogWarning("dark_mode doesn't exist, will make it as default.\n"); 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); ConfigSetString(mCfg, "dark_mode", mAllData.darkMode);
} }
else { 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)); StatusCode workIntervalCode = ConfigGetString(mCfg, "work_interval", &(workIntervalString));
if (StatusCodeEqual(workIntervalCode, "CONFIG_CODE_PARAM_NOT_EXIST")) { if (StatusCodeEqual(workIntervalCode, "CONFIG_CODE_PARAM_NOT_EXIST")) {
LogWarning("work_interval doesn't exist, will make it as default.\n"); 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); ConfigSetString(mCfg, "work_interval", mAllData.workingInterval);
} }
else { 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)); StatusCode shortCode = ConfigGetShort(mCfg, "test_short", &(mAllData.testShort));

View File

@ -14,7 +14,7 @@
*/ */
#ifndef IPCCONFIG_H #ifndef IPCCONFIG_H
#define IPCCONFIG_H #define IPCCONFIG_H
#include "Config.h" #include "ConfigBase.h"
#include "IIpcConfig.h" #include "IIpcConfig.h"
#include "StatusCode.h" #include "StatusCode.h"
#include <map> #include <map>
@ -84,7 +84,7 @@ private:
private: private:
bool mCfgChanged; bool mCfgChanged;
VConfig *mCfg; void *mCfg;
Config_s mAllData; Config_s mAllData;
std::map<IpcConfigKey, std::map<std::string, std::reference_wrapper<int>>> mCfgMapInt; std::map<IpcConfigKey, std::map<std::string, std::reference_wrapper<int>>> mCfgMapInt;
std::map<IpcConfigKey, std::map<std::string, std::reference_wrapper<short>>> mCfgMapShort; std::map<IpcConfigKey, std::map<std::string, std::reference_wrapper<short>>> mCfgMapShort;

View File

@ -79,8 +79,8 @@ const StatusCode McuDevice::UnInit(void)
DeleteAllAsk(); DeleteAllAsk();
return CreateStatusCode(STATUS_CODE_OK); return CreateStatusCode(STATUS_CODE_OK);
} }
size_t McuDevice::WriteData(const void *buff, const size_t buffLength, std::shared_ptr<VProtocolContext> &context, ssize_t McuDevice::WriteData(const void *buff, const size_t buffLength, std::shared_ptr<VProtocolContext> &context,
const unsigned int &serialNumber) const unsigned int &serialNumber)
{ {
constexpr size_t WRITE_ERROR = -1; constexpr size_t WRITE_ERROR = -1;
size_t length = WRITE_ERROR; size_t length = WRITE_ERROR;

View File

@ -29,8 +29,8 @@ public:
const StatusCode UnInit(void) override; const StatusCode UnInit(void) override;
public: public:
size_t WriteData(const void *buff, const size_t buffLength, std::shared_ptr<VProtocolContext> &context, ssize_t WriteData(const void *buff, const size_t buffLength, std::shared_ptr<VProtocolContext> &context,
const unsigned int &serialNumber) override; const unsigned int &serialNumber) override;
public: public:
void GetIpcMissionReply(const unsigned int &serialNumber, const unsigned char &mission) override; void GetIpcMissionReply(const unsigned int &serialNumber, const unsigned char &mission) override;

View File

@ -12,8 +12,8 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
#ifndef GTESTUSING_H #ifndef GTEST_USING_H
#define GTESTUSING_H #define GTEST_USING_H
#include <gmock/gmock.h> #include <gmock/gmock.h>
#include <gtest/gtest.h> #include <gtest/gtest.h>
using ::testing::_; using ::testing::_;
@ -41,11 +41,11 @@ using ::testing::ReturnRefOfCopy;
using ::testing::ReturnRoundRobin; using ::testing::ReturnRoundRobin;
using ::testing::SaveArg; using ::testing::SaveArg;
using ::testing::SetArgPointee; using ::testing::SetArgPointee;
using ::testing::SetArgReferee;
using ::testing::SetArgumentPointee; using ::testing::SetArgumentPointee;
using ::testing::Unused; using ::testing::Unused;
using ::testing::WithArgs; using ::testing::WithArgs;
using ::testing::internal::BuiltInDefaultValue; using ::testing::internal::BuiltInDefaultValue;
using ::testing::SetArgReferee;
// using ::testing::Mock::VerifyAndClearExpectations; // using ::testing::Mock::VerifyAndClearExpectations;
using ::testing::Mock; using ::testing::Mock;
#endif #endif

View File

@ -18,10 +18,6 @@ link_directories(
${EXTERNAL_LIBS_OUTPUT_PATH} ${EXTERNAL_LIBS_OUTPUT_PATH}
) )
aux_source_directory(. SRC_FILES) aux_source_directory(. SRC_FILES)
aux_source_directory(${TEST_SOURCE_PATH}/middleware/IpcConfig/src SRC_FILES) aux_source_directory(${TEST_SOURCE_PATH}/middleware/IpcConfig/src SRC_FILES)
set(TARGET_NAME AllTest) set(TARGET_NAME AllTest)

View File

@ -24,7 +24,7 @@ namespace AppManagerTest
class AppManagerTest : public testing::Test, public AppManagerTestTool, public HalTestTool class AppManagerTest : public testing::Test, public AppManagerTestTool, public HalTestTool
{ {
public: 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() virtual ~AppManagerTest()
@ -64,7 +64,10 @@ TEST_F(AppManagerTest, INTEGRATION_AppManager_EXAMPLE_Demo0)
IAppManager::GetInstance()->Init(mAppParam); IAppManager::GetInstance()->Init(mAppParam);
IAppManager::GetInstance()->SetAppMonitor(monitor); IAppManager::GetInstance()->SetAppMonitor(monitor);
std::this_thread::sleep_for(std::chrono::milliseconds(100)); 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(); IAppManager::GetInstance()->UnInit();
} }
// ../output_files/test/bin/AppManagerTest --gtest_filter=AppManagerTest.INTEGRATION_AppManager_EXAMPLE_Demo // ../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)); std::this_thread::sleep_for(std::chrono::milliseconds(1000));
IAppManager::GetInstance()->UnInit(); 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<VAppMonitor> 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<VAppMonitor> 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<VAppMonitor> 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<VAppMonitor> 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<VAppMonitor> 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<VAppMonitor> 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 } // namespace AppManagerTest

View File

@ -9,6 +9,7 @@ include_directories(
${UTILS_SOURCE_PATH}/StatusCode/include ${UTILS_SOURCE_PATH}/StatusCode/include
${UTILS_SOURCE_PATH}/Log/include ${UTILS_SOURCE_PATH}/Log/include
${UTILS_SOURCE_PATH}/Servers/include ${UTILS_SOURCE_PATH}/Servers/include
${UTILS_SOURCE_PATH}/TcpModule/include
${MIDDLEWARE_SOURCE_PATH}/AppManager/src ${MIDDLEWARE_SOURCE_PATH}/AppManager/src
${MIDDLEWARE_SOURCE_PATH}/AppManager/src/Protocol/SixFrame ${MIDDLEWARE_SOURCE_PATH}/AppManager/src/Protocol/SixFrame
${TEST_SOURCE_PATH} ${TEST_SOURCE_PATH}

View File

@ -44,6 +44,15 @@ protected:
void MockAppPlayback(void); void MockAppPlayback(void);
void MockMonitorSetFileList(std::vector<AppGetFileList> &files); void MockMonitorSetFileList(std::vector<AppGetFileList> &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: private:
void AppManagerMockInit(std::shared_ptr<IAppManager> &vMock); void AppManagerMockInit(std::shared_ptr<IAppManager> &vMock);
void AppMonitorInit(std::shared_ptr<VAppMonitor> &vMock); void AppMonitorInit(std::shared_ptr<VAppMonitor> &vMock);
@ -51,6 +60,8 @@ private:
private: private:
std::shared_ptr<IAppManager> mAppManagerMock; std::shared_ptr<IAppManager> mAppManagerMock;
std::shared_ptr<VAppMonitor> mAppMonitorMock; std::shared_ptr<VAppMonitor> mAppMonitorMock;
void *mAppClientTool;
std::shared_ptr<VAppClient> mAppClient;
public: public:
static std::shared_ptr<VAppMonitor> MakeMonitorMock(void); static std::shared_ptr<VAppMonitor> MakeMonitorMock(void);

View File

@ -27,14 +27,4 @@ const StatusCode AppManagerTest::SetAppMonitorTrace(std::shared_ptr<VAppMonitor>
{ {
LogInfo("AppManagerTest::SetAppMonitorTrace\n"); LogInfo("AppManagerTest::SetAppMonitorTrace\n");
return CreateStatusCode(STATUS_CODE_VIRTUAL_FUNCTION); return CreateStatusCode(STATUS_CODE_VIRTUAL_FUNCTION);
} }
// StatusCode AppManagerTest::GetAllLedsTrace(std::map<std::string, std::shared_ptr<VLedHal>> &allLeds)
// {
// LogInfo("AppManagerTest::GetAllLedsTrace\n");
// return CreateStatusCode(STATUS_CODE_VIRTUAL_FUNCTION);
// }
// StatusCode AppManagerTest::GetAllKeysTrace(std::map<std::string, std::shared_ptr<VKeyHal>> &allKeys)
// {
// LogInfo("AppManagerTest::GetAllKeysTrace\n");
// return CreateStatusCode(STATUS_CODE_VIRTUAL_FUNCTION);
// }

View File

@ -18,6 +18,7 @@
#include "AppMonitorMock.h" #include "AppMonitorMock.h"
#include "ILog.h" #include "ILog.h"
#include "ServersMock.h" #include "ServersMock.h"
#include "TcpModule.h"
constexpr int ONLY_BE_CALLED_ONCE = 1; constexpr int ONLY_BE_CALLED_ONCE = 1;
void AppManagerTestTool::Init(void) void AppManagerTestTool::Init(void)
{ {
@ -33,6 +34,9 @@ void AppManagerTestTool::UnInit(void)
mAppManagerMock.reset(); mAppManagerMock.reset();
mAppMonitorMock.reset(); mAppMonitorMock.reset();
CancelOverrideAppManagerMakePtrObject(); CancelOverrideAppManagerMakePtrObject();
if (nullptr != mAppClientTool) {
FreeTcpClient(mAppClientTool);
}
} }
void AppManagerTestTool::MockGetProductInfo(void) void AppManagerTestTool::MockGetProductInfo(void)
{ {
@ -205,6 +209,84 @@ void AppManagerTestTool::MockMonitorSetFileList(std::vector<AppGetFileList> &fil
LogError("MockMonitorSetFileList failed, mAppMonitorMock isn't mock object.\n"); LogError("MockMonitorSetFileList failed, mAppMonitorMock isn't mock object.\n");
} }
} }
void AppManagerTestTool::MockAppClientConnect(void)
{
std::shared_ptr<AppMonitorMock> mock = std::dynamic_pointer_cast<AppMonitorMock>(mAppMonitorMock);
if (mock) {
auto appClientConnected = [=](std::shared_ptr<VAppClient> &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<IAppManager> &vMock) void AppManagerTestTool::AppManagerMockInit(std::shared_ptr<IAppManager> &vMock)
{ {
std::shared_ptr<AppManagerMock> mock = std::dynamic_pointer_cast<AppManagerMock>(vMock); std::shared_ptr<AppManagerMock> mock = std::dynamic_pointer_cast<AppManagerMock>(vMock);
@ -268,5 +350,9 @@ void AppManagerTestTool::AppMonitorInit(std::shared_ptr<VAppMonitor> &vMock)
.WillRepeatedly(DoAll(Return(CreateStatusCode(STATUS_CODE_VIRTUAL_FUNCTION)))); .WillRepeatedly(DoAll(Return(CreateStatusCode(STATUS_CODE_VIRTUAL_FUNCTION))));
EXPECT_CALL(*mock.get(), UploadFileTrace(_)) EXPECT_CALL(*mock.get(), UploadFileTrace(_))
.WillRepeatedly(DoAll(Return(CreateStatusCode(STATUS_CODE_VIRTUAL_FUNCTION)))); .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))));
} }
} }

View File

@ -243,4 +243,32 @@ StatusCode AppMonitorTrace::UploadFileTrace(AppUploadFile &param)
{ {
LogInfo("AppMonitorTrace::UploadFileTrace\n"); LogInfo("AppMonitorTrace::UploadFileTrace\n");
return CreateStatusCode(STATUS_CODE_VIRTUAL_FUNCTION); return CreateStatusCode(STATUS_CODE_VIRTUAL_FUNCTION);
}
StatusCode AppMonitorTest::GetThumbnail(AppGetThumbnail &param)
{
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 &param)
{
LogInfo("AppMonitorTrace::UploadFileTrace\n");
return CreateStatusCode(STATUS_CODE_VIRTUAL_FUNCTION);
}
StatusCode AppMonitorTest::AppClientConnected(std::shared_ptr<VAppClient> &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<VAppClient> &client)
{
LogInfo("AppMonitorTrace::AppClientConnected\n");
return CreateStatusCode(STATUS_CODE_VIRTUAL_FUNCTION);
} }

View File

@ -39,6 +39,8 @@ protected:
virtual StatusCode EnterRecorderTrace(void); virtual StatusCode EnterRecorderTrace(void);
virtual StatusCode AppPlaybackTrace(const PlayBackEvent &event); virtual StatusCode AppPlaybackTrace(const PlayBackEvent &event);
virtual StatusCode UploadFileTrace(AppUploadFile &param); virtual StatusCode UploadFileTrace(AppUploadFile &param);
virtual StatusCode GetThumbnailTrace(AppGetThumbnail &param);
virtual StatusCode AppClientConnectedTrace(std::shared_ptr<VAppClient> &client);
}; };
class AppMonitorTest : public VAppMonitor, virtual public AppMonitorTrace class AppMonitorTest : public VAppMonitor, virtual public AppMonitorTrace
{ {
@ -61,6 +63,8 @@ public:
StatusCode EnterRecorder(void) override; StatusCode EnterRecorder(void) override;
StatusCode AppPlayback(const PlayBackEvent &event) override; StatusCode AppPlayback(const PlayBackEvent &event) override;
StatusCode UploadFile(AppUploadFile &param) override; StatusCode UploadFile(AppUploadFile &param) override;
StatusCode GetThumbnail(AppGetThumbnail &param) override;
StatusCode AppClientConnected(std::shared_ptr<VAppClient> &client) override;
}; };
class AppMonitorMock : virtual public AppMonitorTrace class AppMonitorMock : virtual public AppMonitorTrace
{ {
@ -83,5 +87,7 @@ public:
MOCK_METHOD0(EnterRecorderTrace, StatusCode(void)); MOCK_METHOD0(EnterRecorderTrace, StatusCode(void));
MOCK_METHOD1(AppPlaybackTrace, StatusCode(const PlayBackEvent &)); MOCK_METHOD1(AppPlaybackTrace, StatusCode(const PlayBackEvent &));
MOCK_METHOD1(UploadFileTrace, StatusCode(AppUploadFile &)); MOCK_METHOD1(UploadFileTrace, StatusCode(AppUploadFile &));
MOCK_METHOD1(GetThumbnailTrace, StatusCode(AppGetThumbnail &));
MOCK_METHOD1(AppClientConnectedTrace, StatusCode(std::shared_ptr<VAppClient> &));
}; };
#endif #endif

View File

@ -49,7 +49,7 @@ std::shared_ptr<ServersMock> &ServersMock::GetInstance(std::shared_ptr<ServersMo
ServersMock::ServersMock() ServersMock::ServersMock()
{ {
// //
mServerUrl = APP_MANAGER_HTTP_SERVER_IP ":" + std::to_string(APP_MANAGER_HTTP_SERVER_PORT); mServerUrl = APP_MANAGER_DEVICE_IP ":" + std::to_string(APP_MANAGER_HTTP_SERVER_PORT);
} }
void ServersMock::Init(void) void ServersMock::Init(void)
{ {

View File

@ -18,10 +18,6 @@ link_directories(
${EXTERNAL_LIBS_OUTPUT_PATH} ${EXTERNAL_LIBS_OUTPUT_PATH}
) )
aux_source_directory(. SRC_FILES_MAIN) aux_source_directory(. SRC_FILES_MAIN)
aux_source_directory(./src SRC_FILES) aux_source_directory(./src SRC_FILES)

View File

@ -8,5 +8,4 @@ add_subdirectory(LinuxApiMock)
add_subdirectory(McuProtocol) add_subdirectory(McuProtocol)
add_subdirectory(FxHttpServer) add_subdirectory(FxHttpServer)
add_subdirectory(TestManager) add_subdirectory(TestManager)
add_subdirectory(TcpModule)

View File

@ -0,0 +1,68 @@
# include(${CMAKE_SOURCE_DIR}/build/independent_source.cmake)
include(${CMAKE_SOURCE_DIR_IPCSDK}/build/global_config.cmake)
set(EXECUTABLE_OUTPUT_PATH ${TEST_OUTPUT_PATH}/bin)
include_directories(
./tool/include
${UTILS_SOURCE_PATH}/StatusCode/include
${UTILS_SOURCE_PATH}/Log/include
${UTILS_SOURCE_PATH}/TcpModule/include
${TEST_SOURCE_PATH}/utils/LinuxApiMock/include
${EXTERNAL_SOURCE_PATH}/gtest/googletest-release-1.11.0/googletest/include
${EXTERNAL_SOURCE_PATH}/gtest/googletest-release-1.11.0/googlemock/include
)
link_directories(
${LIBS_OUTPUT_PATH}
${EXTERNAL_LIBS_OUTPUT_PATH}
)
aux_source_directory(. SRC_FILES)
aux_source_directory(./src SRC_FILES)
if(${TARGET_PLATFORM} MATCHES ${DEFINE_LINUX})
aux_source_directory(./src_mock SRC_FILES)
endif()
set(TARGET_NAME TcpModuleTest)
add_executable(${TARGET_NAME} ${SRC_FILES})
target_link_libraries(${TARGET_NAME} TcpModule gtest gmock pthread Log)
if(${TEST_COVERAGE} MATCHES "true")
target_link_libraries(${TARGET_NAME} gcov)
endif()
if(${TARGET_PLATFORM} MATCHES ${DEFINE_LINUX})
target_link_libraries(${TARGET_NAME} LinuxApiMock)
endif()
if ("${COMPILE_IMPROVE_SUPPORT}" MATCHES "true")
add_custom_target(
TcpModuleTest_code_check
COMMAND ${CLANG_TIDY_EXE}
-checks='${CLANG_TIDY_CHECKS}'
--header-filter=.*
--system-headers=false
${SRC_FILES}
${CLANG_TIDY_CONFIG}
# --line-filter='[{\"name\":\"${EXTERNAL_SOURCE_PATH}/gtest/googletest-release-1.11.0/googletest/include/getest/gtest.h\"}]'
--line-filter='[{\"name\":\"${EXTERNAL_SOURCE_PATH}/gtest/googletest-release-1.11.0/googletest/include/getest/*.h\"}]'
-p ${PLATFORM_PATH}/cmake-shell
WORKING_DIRECTORY ${TEST_SOURCE_PATH}/utils/TcpModule
)
file(GLOB_RECURSE HEADER_FILES *.h)
add_custom_target(
TcpModuleTest_code_format
COMMAND ${CLANG_FORMAT_EXE}
-style=file
-i ${SRC_FILES} ${HEADER_FILES}
WORKING_DIRECTORY ${TEST_SOURCE_PATH}/utils/TcpModule
)
add_custom_command(
TARGET ${TARGET_NAME}
PRE_BUILD
COMMAND make TcpModuleTest_code_check
COMMAND make TcpModuleTest_code_format
WORKING_DIRECTORY ${PLATFORM_PATH}/cmake-shell/
)
endif()
define_file_name(${TARGET_NAME})
# add_subdirectory(tool)

View File

@ -0,0 +1,23 @@
/*
* Copyright (c) 2023 Fancy Code.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include <thread>
#include <unistd.h>
int main(int argc, char *argv[])
{
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}

View File

@ -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 <gmock/gmock.h>
#include <gtest/gtest.h>
#include <thread>
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

View File

@ -17,8 +17,6 @@ link_directories(
${EXTERNAL_LIBS_OUTPUT_PATH} ${EXTERNAL_LIBS_OUTPUT_PATH}
) )
aux_source_directory(. SRC_FILES) aux_source_directory(. SRC_FILES)
aux_source_directory(./src SRC_FILES) aux_source_directory(./src SRC_FILES)
if(${TARGET_PLATFORM} MATCHES ${DEFINE_LINUX}) if(${TARGET_PLATFORM} MATCHES ${DEFINE_LINUX})

View File

@ -1,6 +1,6 @@
# cmake_minimum_required(VERSION 2.8.0) # cmake_minimum_required(VERSION 2.8.0)
add_subdirectory(Config) add_subdirectory(ConfigBase)
add_subdirectory(StatusCode) add_subdirectory(StatusCode)
add_subdirectory(Log) add_subdirectory(Log)
add_subdirectory(SharedData) add_subdirectory(SharedData)

View File

@ -14,8 +14,6 @@ include_directories(
# ${EXTERNAL_SOURCE_PATH}/libconfig/libconfig-1.7.3/lib/.libs # ${EXTERNAL_SOURCE_PATH}/libconfig/libconfig-1.7.3/lib/.libs
# ) # )
aux_source_directory(./src SRC_FILES) aux_source_directory(./src SRC_FILES)
set(TARGET_NAME ConfigBase) set(TARGET_NAME ConfigBase)

View File

@ -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)

View File

@ -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()

View File

@ -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

View File

@ -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<IConfigBase> *configObject = NewConfigBase(fileName);
if (nullptr != configObject) {
(*configObject)->OpenConfigFile();
}
return configObject;
}
StatusCode ConfigSaveFile(void *object)
{
if (ObjectCheck(object) == true) {
return (*(std::shared_ptr<IConfigBase> *)object)->ConfigSaveFile();
}
return CreateStatusCode(STATUS_CODE_INVALID_PARAMENTER);
}
void CloseConfigFile(void *object)
{
if (ObjectCheck(object) == true) {
(*(std::shared_ptr<IConfigBase> *)object)->CloseConfigFile();
(*(std::shared_ptr<IConfigBase> *)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<IConfigBase> *)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<IConfigBase> *)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<IConfigBase> *)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<IConfigBase> *)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<IConfigBase> *)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<IConfigBase> *)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<IConfigBase> *)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<IConfigBase> *)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<IConfigBase> *)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<IConfigBase> *)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<IConfigBase> *)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<IConfigBase> *)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<IConfigBase> *)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<IConfigBase> *)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<IConfigBase> *)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<IConfigBase> *)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<IConfigBase> *)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<IConfigBase> *)object)->ConfigSetString(name, value);
}
return CreateStatusCode(STATUS_CODE_INVALID_PARAMENTER);
}

View File

@ -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 <string.h>
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);
}

View File

@ -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

View File

@ -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 <limits.h>
#include <math.h>
#include <unistd.h>
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);
}

View File

@ -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 <libconfig.h>
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

View File

@ -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 <cstring>
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<IConfigBase> *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<ConfigBaseImpl>(fileName);
return (std::shared_ptr<IConfigBase> *)(((char *)impl) + sizeof(IConfigBaseHeader));
}

View File

@ -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 <memory>
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<IConfigBase> mIConfigBase;
} ConfigBase;
const char *GetConfigBaseModuleName(void);
std::shared_ptr<IConfigBase> *NewConfigBase(const char *fileName);
#endif

View File

@ -68,8 +68,8 @@ protected:
{ {
return std::make_shared<VProtocolBase>(); return std::make_shared<VProtocolBase>();
} }
virtual size_t WriteData(const void *buff, const size_t buffLength, std::shared_ptr<VProtocolContext> &context, virtual ssize_t WriteData(const void *buff, const size_t buffLength, std::shared_ptr<VProtocolContext> &context,
const unsigned int &serialNumber) const unsigned int &serialNumber)
{ {
return 0; return 0;
} }

View File

@ -8,6 +8,7 @@ include_directories(
${UTILS_SOURCE_PATH}/LinuxApi/include ${UTILS_SOURCE_PATH}/LinuxApi/include
${UTILS_SOURCE_PATH}/StatusCode/include ${UTILS_SOURCE_PATH}/StatusCode/include
${UTILS_SOURCE_PATH}/Log/include ${UTILS_SOURCE_PATH}/Log/include
${EXTERNAL_SOURCE_PATH}/libhv/libhv-1.3.2/include/hv
) )
# link_directories( # link_directories(
# ${EXTERNAL_SOURCE_PATH}/libconfig/libconfig-1.7.3/lib/.libs # ${EXTERNAL_SOURCE_PATH}/libconfig/libconfig-1.7.3/lib/.libs
@ -17,7 +18,7 @@ aux_source_directory(./src SRC_FILES)
set(TARGET_NAME TcpModule) set(TARGET_NAME TcpModule)
add_library(${TARGET_NAME} STATIC ${SRC_FILES}) add_library(${TARGET_NAME} STATIC ${SRC_FILES})
target_link_libraries(${TARGET_NAME} LinuxApi StatusCode Log) target_link_libraries(${TARGET_NAME} LinuxApi hv_static StatusCode Log)
if ("${COMPILE_IMPROVE_SUPPORT}" MATCHES "true") if ("${COMPILE_IMPROVE_SUPPORT}" MATCHES "true")
add_custom_target( add_custom_target(

View File

@ -14,22 +14,41 @@
*/ */
#ifndef TCP_MODULE_H #ifndef TCP_MODULE_H
#define TCP_MODULE_H #define TCP_MODULE_H
#include <stddef.h>
#include <sys/types.h>
#define TCP_MODULE_WRITE_ERROR -1;
#ifdef __cplusplus #ifdef __cplusplus
extern "C" { extern "C" {
#endif #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 typedef struct tcp_parm
{ {
const char *mIp; const char *mIp;
const int mPort; const int mPort;
const TcpReadFunction mReadFunc; const TcpReadFunction mReadFunc;
} TcpPram; const SocketClosedFunction mClosedFunc;
void *CreateTcpServer(const TcpPram param); } TcpClientParam;
void FreeTcpServer(void *pointer); void *CreateTcpServer(const TcpServerParam param);
int TcpServerWrite(void *object, void *buf, const int bufLenght); void FreeTcpServer(void *object);
void *CreateTcpClient(const TcpPram param); ssize_t AcceptClientWrite(void *object, const void *buf, const size_t bufLenght);
void FreeTcpClient(void *pointer); void AcceptClientClose(void *object);
int TcpClientWrite(void *object, void *buf, const int bufLenght); void *CreateTcpClient(const TcpClientParam param);
void FreeTcpClient(void *object);
ssize_t TcpClientWrite(void *object, const void *buf, const size_t bufLenght);
#ifdef __cplusplus #ifdef __cplusplus
} }
#endif #endif

View File

@ -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 <cstring>
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;
}

View File

@ -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 <memory>
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<ITcpClient> mTcpClient;
} TcpClient;
const char *GetTcpClientModuleName(void);
#endif

View File

@ -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 <cstring>
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;
}

View File

@ -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 <memory>
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<ITcpServer> mTcpServer;
} TcpServer;
typedef struct tcp_client_accept
{
ITcpServerHeader mHeader;
std::shared_ptr<ITcpClientAccept> mTcpClientAccept;
} TcpClientAccept;
const char *GetTcpServerModuleName(void);
const char *GetTcpClientAcceptName(void);
bool TcpClientAcceptObjectCheck(void *object);
#endif

View File

@ -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 <cstring>
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 &param, 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<TcpClientImpl> impl = std::dynamic_pointer_cast<TcpClientImpl>(shared_from_this());
auto recvThread = [](std::shared_ptr<TcpClientImpl> 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<std::mutex> 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<std::mutex> 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<ITcpClient> *NewTcpClient(const TcpClientParam &param)
{
LogInfo("Create tcp server object.\n");
TcpClient *impl = (TcpClient *)malloc(sizeof(TcpClient));
if (nullptr == impl) {
LogError("NewTcpServer::malloc failed.\n");
return nullptr;
}
TcpClient tmp;
memcpy((void *)impl, (void *)&tmp, sizeof(TcpClient));
impl->mHeader.mCheckName = GetTcpClientModuleName();
std::shared_ptr<ITcpClient> *objectThis =
(std::shared_ptr<ITcpClient> *)(((char *)impl) + sizeof(ITcpClientHeader));
impl->mTcpClient = std::make_shared<TcpClientImpl>(param, objectThis);
return objectThis;
}

View File

@ -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 <memory>
#include <mutex>
#include <thread>
class TcpClientImpl : public ITcpClient, public std::enable_shared_from_this<TcpClientImpl>
{
public:
TcpClientImpl(const TcpClientParam &param, 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<ITcpClient> *NewTcpClient(const TcpClientParam &param);
#endif

View File

@ -13,9 +13,84 @@
* limitations under the License. * limitations under the License.
*/ */
#include "TcpModule.h" #include "TcpModule.h"
#include "ILog.h"
#include "ITcpServer.h"
#include "TcpClientImpl.h"
#include "TcpModuleImpl.h" #include "TcpModuleImpl.h"
void *CreateTcpServer(const TcpPram param) #include "TcpModuleMakePtr.h"
static bool TcpServerObjectCheck(void *object)
{ {
// if (nullptr == object) {
return NewTcpServer(param); 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<ITcpServer> *server = TcpModuleMakePtr::GetInstance()->CreateTcpServer(param);
if (nullptr != *server) {
(*server)->Init();
}
return server;
}
void FreeTcpServer(void *object)
{
if (TcpServerObjectCheck(object) == true) {
(*(std::shared_ptr<ITcpServer> *)object)->UnInit();
(*(std::shared_ptr<ITcpServer> *)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<ITcpClientAccept> *)object)->Write(buf, bufLenght);
}
return TCP_MODULE_WRITE_ERROR;
}
void AcceptClientClose(void *object)
{
if (TcpClientAcceptObjectCheck(object) == true) {
return (*(std::shared_ptr<ITcpClientAccept> *)object)->Close();
}
}
void *CreateTcpClient(const TcpClientParam param)
{
std::shared_ptr<ITcpClient> *client = TcpModuleMakePtr::GetInstance()->CreateTcpClient(param);
if (nullptr != *client) {
(*client)->Init();
}
return client;
}
void FreeTcpClient(void *object)
{
if (TcpClientObjectCheck(object) == true) {
(*(std::shared_ptr<ITcpClient> *)object)->UnInit();
(*(std::shared_ptr<ITcpClient> *)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<ITcpClient> *)object)->Write(buf, bufLenght);
}
return -1;
} }

View File

@ -15,26 +15,26 @@
#include "TcpModuleImpl.h" #include "TcpModuleImpl.h"
#include "ILog.h" #include "ILog.h"
#include <cstring> #include <cstring>
static const char *TCP_MODULE_NAME = "tcp_module"; // static const char *TCP_MODULE_NAME = "tcp_module";
const char *GetTcpModuleName(void) // const char *GetTcpModuleName(void)
{ // {
return TCP_MODULE_NAME; // return TCP_MODULE_NAME;
} // }
void *NewTcpModuleImpl(const TcpPram &tcpParam) // void *NewTcpModuleImpl(const TcpClientParam &tcpParam)
{ // {
if (nullptr == tcpParam.mIp) { // if (nullptr == tcpParam.mIp) {
LogError("Parament error, nullptr == tcpParam.mIp\n"); // LogError("Parament error, nullptr == tcpParam.mIp\n");
return nullptr; // return nullptr;
} // }
LogInfo("Create the tcp module object.\n"); // LogInfo("Create the tcp module object.\n");
TcpServer *impl = (TcpServer *)malloc(sizeof(TcpServer)); // TcpServer *impl = (TcpServer *)malloc(sizeof(TcpServer));
TcpServer tmp; // TcpServer tmp;
memcpy((void *)impl, (void *)&tmp, sizeof(TcpServer)); // memcpy((void *)impl, (void *)&tmp, sizeof(TcpServer));
impl->mHeader.mCheckName = TCP_MODULE_NAME; // impl->mHeader.mCheckName = TCP_MODULE_NAME;
impl->mTcpImpl = std::make_shared<TcpModuleImpl>(tcpParam); // impl->mTcpImpl = std::make_shared<TcpModuleImpl>(tcpParam);
return (void *)(((char *)impl) + sizeof(TcpModuleHeader)); // return (void *)(((char *)impl) + sizeof(TcpModuleHeader));
} // }
void *NewTcpServer(const TcpPram &tcpParam) // void *NewTcpServer(const TcpClientParam &tcpParam)
{ // {
return nullptr; // return nullptr;
} // }

View File

@ -17,36 +17,36 @@
#include "StatusCode.h" #include "StatusCode.h"
#include "TcpModule.h" #include "TcpModule.h"
#include <memory> #include <memory>
#define TCP_MODULE_INIT_NAME "UART" // #define TCP_MODULE_INIT_NAME "UART"
typedef struct uart_device_header // typedef struct tcp_module_header
{ // {
const char *mCheckName; // const char *mCheckName;
} TcpModuleHeader; // } TcpModuleHeader;
class TcpModuleImpl // class TcpModuleImpl
{ // {
public: // public:
TcpModuleImpl(const TcpPram &uatrInfo); // TcpModuleImpl(const TcpClientParam &uatrInfo);
virtual ~TcpModuleImpl() = default; // virtual ~TcpModuleImpl() = default;
private: // private:
const StatusCode SetConfig(void); // const StatusCode SetConfig(void);
private: // private:
const TcpPram mUatrInfo; // const TcpClientParam mUatrInfo;
int mFd; // int mFd;
}; // };
// TODO: There may be a CPU byte alignment bug. // TODO: There may be a CPU byte alignment bug.
typedef struct tcp_server TcpServer; // typedef struct tcp_server TcpServer;
typedef struct tcp_server // typedef struct tcp_server
{ // {
TcpModuleHeader mHeader; // TcpModuleHeader mHeader;
std::shared_ptr<TcpModuleImpl> mTcpImpl; // std::shared_ptr<TcpModuleImpl> mTcpImpl;
} TcpServer; // } TcpServer;
void *NewTcpModuleImpl(const TcpPram &tcpParam); // void *NewTcpModuleImpl(const TcpClientParam &tcpParam);
void *NewTcpServer(const TcpPram &tcpParam); // void *NewTcpServer(const TcpClientParam &tcpParam);
static inline TcpServer *TcpModuleImplConvert(void *object) // static inline TcpServer *TcpModuleImplConvert(void *object)
{ // {
return ((TcpServer *)(((char *)object) - sizeof(TcpModuleHeader))); // return ((TcpServer *)(((char *)object) - sizeof(TcpModuleHeader)));
} // }
const char *GetTcpModuleName(void); // const char *GetTcpModuleName(void);
#endif #endif

View File

@ -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> &TcpModuleMakePtr::GetInstance(std::shared_ptr<TcpModuleMakePtr> *impl)
{
static auto instance = std::make_shared<TcpModuleMakePtr>();
if (impl) {
instance = *impl;
}
return instance;
}
std::shared_ptr<ITcpServer> *TcpModuleMakePtr::CreateTcpServer(const TcpServerParam &param)
{
return NewTcpServer(param);
}
std::shared_ptr<ITcpClient> *TcpModuleMakePtr::CreateTcpClient(const TcpClientParam &param)
{
return NewTcpClient(param);
}

View File

@ -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 <memory>
class TcpModuleMakePtr
{
public:
TcpModuleMakePtr() = default;
virtual ~TcpModuleMakePtr() = default;
static std::shared_ptr<TcpModuleMakePtr> &GetInstance(std::shared_ptr<TcpModuleMakePtr> *impl = nullptr);
virtual std::shared_ptr<ITcpServer> *CreateTcpServer(const TcpServerParam &param);
virtual std::shared_ptr<ITcpClient> *CreateTcpClient(const TcpClientParam &param);
};
#endif // !TCP_MODULE_MAKE_PTR_H

View File

@ -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> &TcpServerHandle::GetInstance(std::shared_ptr<TcpServerHandle> *impl)
{
static auto instance = std::make_shared<TcpServerHandle>();
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<ITcpServer> &server)
{
LogInfo("AddServer fd = %d\n", fd);
mFd[fd] = server;
}
bool TcpServerHandle::GetServer(const int &fd, std::shared_ptr<ITcpServer> &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;
}

View File

@ -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 <map>
#include <memory>
class TcpServerHandle
{
public:
TcpServerHandle() = default;
~TcpServerHandle() = default;
static std::shared_ptr<TcpServerHandle> &GetInstance(std::shared_ptr<TcpServerHandle> *impl = nullptr);
void AddServer(const int &fd, const std::shared_ptr<ITcpServer> &server);
bool GetServer(const int &fd, std::shared_ptr<ITcpServer> &server);
private:
std::map<int, std::shared_ptr<ITcpServer>> mFd;
};
#endif

View File

@ -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<ITcpClientAccept> *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<ITcpClientAccept> *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 &param)
: 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<ITcpServer> server = shared_from_this();
std::shared_ptr<TcpServerImpl> impl = std::dynamic_pointer_cast<TcpServerImpl>(server);
auto recvThread = [](std::shared_ptr<TcpServerImpl> 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<ITcpClientAccept> *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<ITcpClientAccept> *TcpServerImpl::GetClient(hio_t *io)
{
std::lock_guard<std::mutex> 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<std::mutex> 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<ITcpClientAccept> *)object)->Closed();
(*(std::shared_ptr<ITcpClientAccept> *)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<std::mutex> locker(mMutex);
for (auto &client : mClients) {
if (nullptr != client.second) {
void *object = (void *)client.second;
if (TcpClientAcceptObjectCheck(object) == true) {
(*(std::shared_ptr<ITcpClientAccept> *)object)->Closed();
(*(std::shared_ptr<ITcpClientAccept> *)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<ITcpServer> *NewTcpServer(const TcpServerParam &param)
{
LogInfo("Create tcp server object.\n");
TcpServer *impl = (TcpServer *)malloc(sizeof(TcpServer));
if (nullptr == impl) {
LogError("NewTcpServer::malloc failed.\n");
return nullptr;
}
TcpServer tmp;
memcpy((void *)impl, (void *)&tmp, sizeof(TcpServer));
impl->mHeader.mCheckName = GetTcpServerModuleName();
impl->mTcpServer = std::make_shared<TcpServerImpl>(param);
return (std::shared_ptr<ITcpServer> *)(((char *)impl) + sizeof(ITcpServerHeader));
}
std::shared_ptr<ITcpClientAccept> *NewTcpClientAccept(const hio_t *io, const ClientAcceptParam &param)
{
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<ITcpClientAccept> *objectThis =
(std::shared_ptr<ITcpClientAccept> *)(((char *)impl) + sizeof(ITcpServerHeader));
impl->mTcpClientAccept = std::make_shared<TcpClientAcceptImpl>(io, objectThis, param);
return objectThis;
}

View File

@ -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 <map>
#include <mutex>
#include <thread>
class TcpClientAcceptImpl : public ITcpClientAccept, public std::enable_shared_from_this<TcpClientAcceptImpl>
{
public:
TcpClientAcceptImpl(const hio_t *io, const void *object, const ClientAcceptParam &param);
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<TcpServerImpl>
{
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<ITcpClientAccept> *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<int, std::shared_ptr<ITcpClientAccept> *> mClients;
};
std::shared_ptr<ITcpServer> *NewTcpServer(const TcpServerParam &param);
std::shared_ptr<ITcpClientAccept> *NewTcpClientAccept(const hio_t *io, const ClientAcceptParam &param);
#endif