From 75d4d06ac9c0cad7e7ad64bcd8844e697f5ef8b2 Mon Sep 17 00:00:00 2001 From: Max Qian <64824374+AstroAir@users.noreply.github.com> Date: Fri, 20 Oct 2023 08:25:21 +0000 Subject: [PATCH] update big problem!!!! --- src/App.cpp | 2 +- src/LithiumApp.cpp | 13 +- src/client/ascom/ascom_device.cpp | 12 +- src/client/astap.cpp | 22 +- src/client/phd2client.cpp | 22 +- src/core/deviceio.cpp | 12 +- src/core/shared_memory.hpp | 8 +- src/modules/config/configor.cpp | 69 ++-- src/modules/device/device_manager.cpp | 258 ++++++------- src/modules/device/device_manager.hpp | 17 +- src/modules/device/indi_device.cpp | 2 +- src/modules/device/indidevice_manager.cpp | 8 +- src/modules/deviceloader/client_info.cpp | 4 +- src/modules/deviceloader/driver_info.cpp | 2 +- src/modules/deviceloader/hydrogen_server.cpp | 4 +- src/modules/deviceloader/local_driver.cpp | 24 +- src/modules/deviceloader/message.cpp | 8 +- src/modules/deviceloader/message_queue.cpp | 28 +- src/modules/deviceloader/remote_driver.cpp | 6 +- src/modules/deviceloader/serialize.cpp | 2 +- src/modules/deviceloader/tcp_server.cpp | 28 +- src/modules/error/error_stack.cpp | 2 +- src/modules/io/compress.cpp | 57 +-- src/modules/io/file.cpp | 38 +- src/modules/io/io.cpp | 24 +- src/modules/module/compiler.cpp | 26 +- src/modules/module/modloader.cpp | 50 +-- src/modules/module/modloader.hpp | 8 +- src/modules/plugin/exe_plugin.cpp | 6 +- src/modules/plugin/plugin_manager.cpp | 10 +- src/modules/plugin/script_plugin.cpp | 6 +- src/modules/script/script_manager.cpp | 10 +- src/modules/script/script_manager.hpp | 4 +- src/modules/server/message_bus.hpp | 381 ++++++++++--------- src/modules/system/pid.cpp | 6 +- src/modules/system/pidw.cpp | 10 +- src/modules/system/process.cpp | 30 +- src/modules/task/task_generator.cpp | 24 +- src/modules/task/task_manager.cpp | 28 +- src/modules/thread/thread.cpp | 14 +- src/modules/utils/string.cpp | 71 ++++ src/modules/utils/string.hpp | 12 + src/modules/web/downloader.cpp | 20 +- src/modules/web/httpclient.cpp | 18 +- src/modules/web/utils.cpp | 12 +- src/websocket/WebSocketServer.cpp | 32 +- src/websocket/WsDeviceComponent.cpp | 56 +-- src/websocket/WsProcessComponent.cpp | 28 +- src/websocket/WsScriptComponent.cpp | 24 +- src/websocket/WsTaskComponent.cpp | 36 +- src/websocket/device/WsDeviceHub.cpp | 32 +- src/websocket/device/WsDeviceHub.hpp | 32 +- src/websocket/device/WsDeviceInstance.cpp | 118 +++++- src/websocket/device/WsDeviceInstance.hpp | 131 ++++--- src/websocket/device/WsDeviceServer.cpp | 30 ++ src/websocket/device/WsDeviceServer.hpp | 30 ++ 56 files changed, 1146 insertions(+), 821 deletions(-) create mode 100644 src/modules/utils/string.cpp create mode 100644 src/modules/utils/string.hpp diff --git a/src/App.cpp b/src/App.cpp index c61b67a6..67a122e0 100644 --- a/src/App.cpp +++ b/src/App.cpp @@ -236,7 +236,7 @@ int main(int argc, char *argv[]) } catch (const std::runtime_error &e) { - DLOG_F(ERROR, _("Failed to parser command line : %s"), e.what()); + LOG_F(ERROR, _("Failed to parser command line : %s"), e.what()); std::exit(1); } diff --git a/src/LithiumApp.cpp b/src/LithiumApp.cpp index 395da9e3..654316b8 100644 --- a/src/LithiumApp.cpp +++ b/src/LithiumApp.cpp @@ -33,6 +33,9 @@ Description: Lithium App Enter #include "config.h" #include "loguru/loguru.hpp" +#include "nlohmann/json.hpp" + +using json = nlohmann::json; namespace Lithium { @@ -64,7 +67,7 @@ namespace Lithium } catch (const std::exception &e) { - DLOG_F(ERROR, _("Failed to load Lithium App , error : {}"), e.what()); + LOG_F(ERROR, _("Failed to load Lithium App , error : {}"), e.what()); throw std::runtime_error("Failed to load Lithium App"); } } @@ -269,7 +272,7 @@ namespace Lithium } else { - DLOG_F(ERROR, _("Failed to run chai command : {}"), command); + LOG_F(ERROR, _("Failed to run chai command : {}"), command); } return false; } @@ -287,7 +290,7 @@ namespace Lithium { result += str + "\n"; } - DLOG_F(ERROR, _("Failed to run chai multi command {}"), result); + LOG_F(ERROR, _("Failed to run chai multi command {}"), result); } return true; } @@ -300,7 +303,7 @@ namespace Lithium } else { - DLOG_F(ERROR, _("Failed to load chaiscript file {}"), filename); + LOG_F(ERROR, _("Failed to load chaiscript file {}"), filename); return false; } } @@ -313,7 +316,7 @@ namespace Lithium } else { - DLOG_F(ERROR, _("Failed to run chai script {}"), filename); + LOG_F(ERROR, _("Failed to run chai script {}"), filename); return false; } } diff --git a/src/client/ascom/ascom_device.cpp b/src/client/ascom/ascom_device.cpp index 18108af1..f309a186 100644 --- a/src/client/ascom/ascom_device.cpp +++ b/src/client/ascom/ascom_device.cpp @@ -71,7 +71,7 @@ bool ASCOMDevice::connect(const IParams ¶ms) setConnected(true); if (!getConnected()) { - //DLOG_F(ERROR, "Failed to establish connection with %s", name.c_str()); + //LOG_F(ERROR, "Failed to establish connection with %s", name.c_str()); return false; } //DLOG_F(INFO, "Connected to %s", name.c_str()); @@ -88,7 +88,7 @@ bool ASCOMDevice::disconnect(const IParams ¶ms) setConnected(false); if (getConnected()) { - DLOG_F(ERROR, "Failed to disconnect with %s", getDeviceName()); + LOG_F(ERROR, "Failed to disconnect with %s", getDeviceName()); return false; } return true; @@ -98,11 +98,11 @@ bool ASCOMDevice::reconnect(const IParams ¶ms) { if (!disconnect(params)) { - DLOG_F(ERROR, "Failed to reconnect with %s, falied when trying to disconnect with", getDeviceName()); + LOG_F(ERROR, "Failed to reconnect with %s, falied when trying to disconnect with", getDeviceName()); } if (!connect(params)) { - DLOG_F(ERROR, "Failed to reconnect %s, falied when trying to connect to", getDeviceName()); + LOG_F(ERROR, "Failed to reconnect %s, falied when trying to connect to", getDeviceName()); } return true; } @@ -202,7 +202,7 @@ const std::string ASCOMDevice::get(const std::string &attribute, const json &dat } catch (const std::exception &e) { - DLOG_F(ERROR, "Exception occurred during GET request: %s", e.what()); + LOG_F(ERROR, "Exception occurred during GET request: %s", e.what()); throw; } } @@ -232,7 +232,7 @@ const std::string ASCOMDevice::put(const std::string &attribute, const json &dat } catch (const std::exception &e) { - DLOG_F(ERROR, "Exception occurred during PUT request: %s", e.what()); + LOG_F(ERROR, "Exception occurred during PUT request: %s", e.what()); throw; } } diff --git a/src/client/astap.cpp b/src/client/astap.cpp index ab9dd2b2..229a7cd6 100644 --- a/src/client/astap.cpp +++ b/src/client/astap.cpp @@ -122,7 +122,7 @@ namespace Lithium::API::ASTAP FILE *pipe = popen(command.c_str(), "r"); if (!pipe) { - DLOG_F(ERROR, "Error: failed to run command '%s'.", command.c_str()); + LOG_F(ERROR, "Error: failed to run command '%s'.", command.c_str()); return ""; } std::string output = ""; @@ -141,7 +141,7 @@ namespace Lithium::API::ASTAP if (attempts_left < 1) { - DLOG_F(ERROR, "Exceeded maximum attempts"); + LOG_F(ERROR, "Exceeded maximum attempts"); throw std::runtime_error("Exceeded maximum attempts"); } @@ -153,7 +153,7 @@ namespace Lithium::API::ASTAP { if (attempts_left == 1) { - DLOG_F(ERROR, "Failed to execute function after multiple attempts"); + LOG_F(ERROR, "Failed to execute function after multiple attempts"); throw; } else @@ -171,17 +171,17 @@ namespace Lithium::API::ASTAP // 输入参数合法性检查 if (ra < 0.0 || ra > 360.0) { - DLOG_F(ERROR, "RA should be within [0, 360]"); + LOG_F(ERROR, "RA should be within [0, 360]"); return ""; } if (dec < -90.0 || dec > 90.0) { - DLOG_F(ERROR, "DEC should be within [-90, 90]"); + LOG_F(ERROR, "DEC should be within [-90, 90]"); return ""; } if (fov <= 0.0 || fov > 180.0) { - DLOG_F(ERROR, "FOV should be within (0, 180]"); + LOG_F(ERROR, "FOV should be within (0, 180]"); return ""; } if (!image.empty()) @@ -190,7 +190,7 @@ namespace Lithium::API::ASTAP file.open(image, std::ios::in | std::ios::out); if (!file.good()) { - DLOG_F(ERROR, "Error: image file '%s' is not accessible.", image.c_str()); + LOG_F(ERROR, "Error: image file '%s' is not accessible.", image.c_str()); return ""; } file.close(); @@ -231,7 +231,7 @@ namespace Lithium::API::ASTAP auto elapsed_time = std::chrono::duration_cast(std::chrono::system_clock::now() - start_time).count(); if (elapsed_time > timeout) { - DLOG_F(ERROR, "Error: command timed out after %s seconds.", std::to_string(timeout).c_str()); + LOG_F(ERROR, "Error: command timed out after %s seconds.", std::to_string(timeout).c_str()); return ""; } } @@ -265,7 +265,7 @@ namespace Lithium::API::ASTAP if (status != 0) { ret_struct["message"] = "Error: cannot open FITS file '" + image + "'."; - DLOG_F(ERROR, "%s", ret_struct["message"].c_str()); + LOG_F(ERROR, "%s", ret_struct["message"].c_str()); return ret_struct; } @@ -300,7 +300,7 @@ namespace Lithium::API::ASTAP if (status != 0) { ret_struct["message"] = "Error: failed to close FITS file '" + image + "'."; - DLOG_F(ERROR, "%s", ret_struct["message"].c_str()); + LOG_F(ERROR, "%s", ret_struct["message"].c_str()); return ret_struct; } @@ -362,7 +362,7 @@ namespace Lithium::API::ASTAP } else { - DLOG_F(ERROR, "Failed to solve the image"); + LOG_F(ERROR, "Failed to solve the image"); ret_struct["message"] = "Failed to solve the image"; } diff --git a/src/client/phd2client.cpp b/src/client/phd2client.cpp index 0962beef..cc0d4579 100644 --- a/src/client/phd2client.cpp +++ b/src/client/phd2client.cpp @@ -21,7 +21,7 @@ SocketClient::SocketClient() WSADATA wsaData; if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0) { - DLOG_F(ERROR, "Failed to initialize Winsock"); + LOG_F(ERROR, "Failed to initialize Winsock"); throw std::runtime_error("Failed to initialize Winsock"); } #endif @@ -41,7 +41,7 @@ bool SocketClient::Connect(const std::string &serverIP, int serverPort) #endif if (socket_ == INVALID_SOCKET) { - DLOG_F(ERROR, "Failed to create socket"); + LOG_F(ERROR, "Failed to create socket"); #ifdef _WIN32 WSACleanup(); #endif @@ -55,7 +55,7 @@ bool SocketClient::Connect(const std::string &serverIP, int serverPort) #ifdef _WIN32 if (InetPton(AF_INET, serverIP.c_str(), &(serverAddress.sin_addr)) <= 0) { - DLOG_F(ERROR, "Invalid server IP address"); + LOG_F(ERROR, "Invalid server IP address"); closesocket(socket_); WSACleanup(); throw std::runtime_error("Invalid server IP address"); @@ -63,14 +63,14 @@ bool SocketClient::Connect(const std::string &serverIP, int serverPort) #else if (inet_pton(AF_INET, serverIP.c_str(), &(serverAddress.sin_addr)) <= 0) { - DLOG_F(ERROR, "Invalid server IP address"); + LOG_F(ERROR, "Invalid server IP address"); throw std::runtime_error("Invalid server IP address"); } #endif if (connect(socket_, (struct sockaddr *)&serverAddress, sizeof(serverAddress)) < 0) { - DLOG_F(ERROR, "Failed to connect to server"); + LOG_F(ERROR, "Failed to connect to server"); throw std::runtime_error("Failed to connect to server"); } @@ -107,13 +107,13 @@ void SocketClient::Send(const std::string &message) { if (socket_ == INVALID_SOCKET) { - DLOG_F(ERROR, "Not connected to server"); + LOG_F(ERROR, "Not connected to server"); return; } if (send(socket_, message.c_str(), message.length(), 0) < 0) { - DLOG_F(ERROR, "Failed to send data"); + LOG_F(ERROR, "Failed to send data"); throw std::runtime_error("Failed to send data"); } } @@ -152,7 +152,7 @@ void SocketClient::ReceiveThread() { if (bytesRead < 0) { - DLOG_F(ERROR, "Failed to receive data: %d", bytesRead); + LOG_F(ERROR, "Failed to receive data: %d", bytesRead); } else { @@ -461,7 +461,7 @@ void PHD2Client::_star_lost(const json &message) _starlost_status["avg_dist"] = message["AvgDist"]; _starlost_error = message["Status"]; - DLOG_F(ERROR, "Star Lost, SNR: {}, StarMass: {}, AvgDist: {}", + LOG_F(ERROR, "Star Lost, SNR: {}, StarMass: {}, AvgDist: {}", _starlost_status["snr"], _starlost_status["star_mass"], _starlost_status["avg_dist"]); _is_guiding = false; @@ -532,13 +532,13 @@ void PHD2Client::_guiding_dithered(const json &message) void PHD2Client::_lock_position_lost(const json &message) { _is_star_locked = true; - DLOG_F(ERROR, "Star Lock Position Lost"); + LOG_F(ERROR, "Star Lock Position Lost"); } void PHD2Client::_alert(const json &message) { _last_error = message["Msg"]; - DLOG_F(ERROR, "Alert: %s", _last_error.c_str()); + LOG_F(ERROR, "Alert: %s", _last_error.c_str()); } void PHD2Client::_guide_param_change(const json &message) diff --git a/src/core/deviceio.cpp b/src/core/deviceio.cpp index 3e69e0a3..04a3a846 100644 --- a/src/core/deviceio.cpp +++ b/src/core/deviceio.cpp @@ -52,7 +52,7 @@ void SocketServer::start() WSADATA wsaData; if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0) { - DLOG_F(ERROR, "Failed to initialize Winsock"); + LOG_F(ERROR, "Failed to initialize Winsock"); return; } #endif @@ -60,7 +60,7 @@ void SocketServer::start() serverSocket = socket(AF_INET, SOCK_STREAM, 0); // 修改 IPPROTO_TCP 为 0 if (serverSocket == INVALID_SOCKET) { - DLOG_F(ERROR, "Failed to create socket"); + LOG_F(ERROR, "Failed to create socket"); #ifdef _WIN32 WSACleanup(); #endif @@ -74,7 +74,7 @@ void SocketServer::start() if (bind(serverSocket, (sockaddr *)&serverAddress, sizeof(serverAddress)) == SOCKET_ERROR) { - DLOG_F(ERROR, "Failed to bind socket"); + LOG_F(ERROR, "Failed to bind socket"); closesocket(serverSocket); #ifdef _WIN32 WSACleanup(); @@ -84,7 +84,7 @@ void SocketServer::start() if (listen(serverSocket, 5) == SOCKET_ERROR) { - DLOG_F(ERROR, "Failed to listen on socket"); + LOG_F(ERROR, "Failed to listen on socket"); closesocket(serverSocket); #ifdef _WIN32 WSACleanup(); @@ -139,7 +139,7 @@ void SocketServer::acceptClientConnection() SOCKET clientSocket = accept(serverSocket, (sockaddr *)&clientAddress, &clientAddressLength); if (clientSocket == INVALID_SOCKET) { - DLOG_F(ERROR, "Failed to accept client connection"); + LOG_F(ERROR, "Failed to accept client connection"); return; } @@ -154,7 +154,7 @@ void SocketServer::handleClientMessage(SOCKET clientSocket) int bytesRead = recv(clientSocket, buffer, sizeof(buffer), 0); if (bytesRead == SOCKET_ERROR) { - DLOG_F(ERROR, "Failed to read from client socket"); + LOG_F(ERROR, "Failed to read from client socket"); } else if (bytesRead == 0) { diff --git a/src/core/shared_memory.hpp b/src/core/shared_memory.hpp index 69610253..1a5f0805 100644 --- a/src/core/shared_memory.hpp +++ b/src/core/shared_memory.hpp @@ -25,7 +25,7 @@ class SharedMemory handle_ = CreateFileMappingA(INVALID_HANDLE_VALUE, nullptr, PAGE_READWRITE, 0, sizeof(T) + sizeof(bool), name.c_str()); if (handle_ == nullptr) { - DLOG_F(ERROR, "Failed to create file mapping."); + LOG_F(ERROR, "Failed to create file mapping."); throw std::runtime_error("Failed to create file mapping."); } @@ -33,14 +33,14 @@ class SharedMemory if (buffer_ == nullptr) { CloseHandle(handle_); - DLOG_F(ERROR, "Failed to map view of file."); + LOG_F(ERROR, "Failed to map view of file."); throw std::runtime_error("Failed to map view of file."); } #else // Unix-like fd_ = shm_open(name.c_str(), O_CREAT | O_RDWR, S_IRUSR | S_IWUSR); if (fd_ == -1) { - DLOG_F(ERROR, "Failed to create shared memory."); + LOG_F(ERROR, "Failed to create shared memory."); throw std::runtime_error("Failed to create shared memory."); } @@ -51,7 +51,7 @@ class SharedMemory if (buffer_ == MAP_FAILED) { shm_unlink(name.c_str()); - DLOG_F(ERROR, "Failed to map shared memory."); + LOG_F(ERROR, "Failed to map shared memory."); throw std::runtime_error("Failed to map shared memory."); } #endif diff --git a/src/modules/config/configor.cpp b/src/modules/config/configor.cpp index 5093bf89..02424854 100644 --- a/src/modules/config/configor.cpp +++ b/src/modules/config/configor.cpp @@ -72,7 +72,7 @@ namespace Lithium::Config std::ifstream ifs(path); if (!ifs.is_open()) { - DLOG_F(ERROR, "Failed to open file: {}", path); + LOG_F(ERROR, "Failed to open file: {}", path); return false; } json j; @@ -88,9 +88,13 @@ namespace Lithium::Config } catch (const json::exception &e) { - DLOG_F(ERROR, "Failed to parse file: {}, error message: {}", path, e.what()); - return false; + LOG_F(ERROR, "Failed to parse file: {}, error message: {}", path, e.what()); } + catch (const std::exception &e) + { + LOG_F(ERROR, "Failed to load config file: {}, error message: {}", path, e.what()); + } + return false; } bool ConfigManager::loadFromDir(const std::string &dir_path, bool recursive) @@ -120,11 +124,11 @@ namespace Lithium::Config } catch (const json::exception &e) { - DLOG_F(ERROR, "Failed to parse file: {}, error message: {}", config_file_path, e.what()); + LOG_F(ERROR, "Failed to parse file: {}, error message: {}", config_file_path, e.what()); } catch (const std::exception &e) { - DLOG_F(ERROR, "Failed to open file {}", config_file_path); + LOG_F(ERROR, "Failed to open file {}", config_file_path); } } loadFromDir(subdir_path, true); @@ -135,35 +139,37 @@ namespace Lithium::Config void ConfigManager::setValue(const std::string &key_path, const json &value) { - // std::shared_lock lock(rw_mutex_); - std::vector keys = split(key_path, "/"); - json *p = &config_; - - for (const auto &key : keys) + try { - if (!p->is_object()) - { - DLOG_F(ERROR, "Invalid key path: {}", key_path); - return; - } - - if (p->contains(key)) - { - p = &(*p)[key]; - } - else + std::vector keys = split(key_path, "/"); + json *p = &config_; + for (const auto &key : keys) { - (*p)[key] = json::object(); - p = &(*p)[key]; + if (!p->is_object()) + { + LOG_F(ERROR, "Invalid key path: {}", key_path); + return; + } + if (p->contains(key)) + { + p = &(*p)[key]; + } + else + { + (*p)[key] = json::object(); + p = &(*p)[key]; + } } + *p = value; + } + catch (const std::exception &e) + { + LOG_F(ERROR, "Failed to set key: {} with {}", key_path, e.what()); } - - *p = value; } json ConfigManager::getValue(const std::string &key_path) const { - // std::shared_lock lock(rw_mutex_); try { std::vector keys = split(key_path, "/"); @@ -176,7 +182,7 @@ namespace Lithium::Config } else { - DLOG_F(ERROR, "Key not found: {}", key_path); + LOG_F(ERROR, "Key not found: {}", key_path); return nullptr; } } @@ -184,7 +190,7 @@ namespace Lithium::Config } catch (const std::exception &e) { - DLOG_F(ERROR, "Failed to get value: {} {}", key_path, e.what()); + LOG_F(ERROR, "Failed to get value: {} {}", key_path, e.what()); return nullptr; } } @@ -198,14 +204,14 @@ namespace Lithium::Config { if (!p->is_object()) { - DLOG_F(ERROR, "Invalid key path: {}", key_path); + LOG_F(ERROR, "Invalid key path: {}", key_path); return; } p = &(*p)[key]; } if (p->is_null()) { - DLOG_F(ERROR, "Key not found: {}", key_path); + LOG_F(ERROR, "Key not found: {}", key_path); return; } p->clear(); @@ -274,11 +280,12 @@ namespace Lithium::Config std::ofstream ofs(file_path); if (!ofs.is_open()) { - DLOG_F(ERROR, "Failed to open file: {}", file_path); + LOG_F(ERROR, "Failed to open file: {}", file_path); return false; } ofs << config_.dump(4); ofs.close(); + DLOG_F(INFO, "Save config to file: {}", file_path); return true; } diff --git a/src/modules/device/device_manager.cpp b/src/modules/device/device_manager.cpp index 1f025a77..60b31f4c 100644 --- a/src/modules/device/device_manager.cpp +++ b/src/modules/device/device_manager.cpp @@ -30,6 +30,10 @@ Description: Device Manager **************************************************/ #include "device_manager.hpp" +#include "config/configor.hpp" +#include "module/modloader.hpp" +#include "server/message_bus.hpp" +#include "thread/thread.hpp" #include "core/device_exception.hpp" @@ -60,45 +64,42 @@ Description: Device Manager #include "config.h" -#ifndef _WIN32 -#include "deviceloader/hydrogen_server.hpp" -#endif // For DEVICE_FUNC -#define CHECK_DEVICE(device) \ - do \ - { \ - if (!(device)) \ - { \ - DLOG_F(ERROR, "Main {} not specified on calling {}", \ - #device, __func__); \ - return DeviceError::NotSpecific; \ - } \ +#define CHECK_DEVICE(device) \ + do \ + { \ + if (!(device)) \ + { \ + LOG_F(ERROR, "Main {} not specified on calling {}", \ + #device, __func__); \ + return DeviceError::NotSpecific; \ + } \ } while (false) // For DEVICE_FUNC_J -#define CHECK_DEVICE_J(device, error_message) \ - do \ - { \ - if (!(device)) \ - { \ - DLOG_F(ERROR, "Main {} not specified on calling {}", \ - #device, __func__); \ - return {{"error", error_message}}; \ - } \ +#define CHECK_DEVICE_J(device, error_message) \ + do \ + { \ + if (!(device)) \ + { \ + LOG_F(ERROR, "Main {} not specified on calling {}", \ + #device, __func__); \ + return {{"error", error_message}}; \ + } \ } while (false) -#define CHECK_CONNECTED(device) \ - do \ - { \ - if (!(device)->isConnected()) \ - { \ - DLOG_F(ERROR, "{} is not connected when call {}", \ - (device)->getDeviceName(), __func__); \ - return DeviceError::NotConnected; \ - } \ +#define CHECK_CONNECTED(device) \ + do \ + { \ + if (!(device)->isConnected()) \ + { \ + LOG_F(ERROR, "{} is not connected when call {}", \ + (device)->getDeviceName(), __func__); \ + return DeviceError::NotConnected; \ + } \ } while (false) namespace Lithium @@ -160,7 +161,7 @@ namespace Lithium } if (findDeviceByName(name)) { - DLOG_F(ERROR, _("A device with name {} already exists, please choose a different name"), name); + LOG_F(ERROR, _("A device with name {} already exists, please choose a different name"), name); return false; } std::string newName = name; @@ -183,103 +184,55 @@ namespace Lithium { if (lib_name.empty()) { - switch (type) - { - case DeviceType::Camera: - { - DLOG_F(INFO, _("Trying to add a new camera instance : {}"), newName); - m_devices[static_cast(type)].emplace_back(std::make_shared(newName)); - DLOG_F(INFO, _("Added new camera {} instance successfully"), newName); - break; - } - case DeviceType::Telescope: - { - DLOG_F(INFO, _("Trying to add a new telescope instance : {}"), newName); - m_devices[static_cast(type)].emplace_back(std::make_shared(newName)); - DLOG_F(INFO, _("Added new telescope instance successfully")); - break; - } - case DeviceType::Focuser: - { - DLOG_F(INFO, _("Trying to add a new Focuser instance : {}"), newName); - m_devices[static_cast(type)].emplace_back(std::make_shared(newName)); - DLOG_F(INFO, _("Added new focuser instance successfully")); - break; - } - case DeviceType::FilterWheel: - { - DLOG_F(INFO, "Trying to add a new filterwheel instance : {}", newName); - m_devices[static_cast(type)].emplace_back(std::make_shared(newName)); - DLOG_F(INFO, "Added new filterwheel instance successfully"); - break; - } - case DeviceType::Solver: - // m_devices[static_cast(type)].emplace_back(std::make_shared(newName)); - break; - case DeviceType::Guider: - // m_devices[static_cast(type)].emplace_back(std::make_shared(newName)); - break; - default: - { - DLOG_F(ERROR, "Invalid device type"); - throw InvalidDeviceType("Invalid device type"); - break; - } - } + LOG_F(ERROR, "Please specific a device library when you want to create a new instance"); + return false; } else { nlohmann::json params; params["name"] = newName; + std::string logMsg; + switch (type) { case DeviceType::Camera: - { - DLOG_F(INFO, "Trying to add a new camera instance : {} from {}", newName, lib_name); + logMsg = fmt::format("Trying to add a new camera instance : {} from {}", newName, lib_name); m_devices[static_cast(type)].emplace_back(m_ModuleLoader->GetInstance(lib_name, params, "GetInstance")); - DLOG_F(INFO, "Added new camera {} instance successfully", newName); break; - } case DeviceType::Telescope: - { - DLOG_F(INFO, "Trying to add a new telescope instance : {}", newName); + logMsg = fmt::format("Trying to add a new telescope instance : {}", newName); m_devices[static_cast(type)].emplace_back(std::make_shared(newName)); - DLOG_F(INFO, "Added new telescope instance successfully"); break; - } case DeviceType::Focuser: - { - DLOG_F(INFO, "Trying to add a new Focuser instance : {}", newName); + logMsg = fmt::format("Trying to add a new Focuser instance : {}", newName); m_devices[static_cast(type)].emplace_back(std::make_shared(newName)); - DLOG_F(INFO, "Added new focuser instance successfully"); break; - } case DeviceType::FilterWheel: - { - DLOG_F(INFO, "Trying to add a new filterwheel instance : {}", newName); + logMsg = fmt::format("Trying to add a new filterwheel instance : {}", newName); m_devices[static_cast(type)].emplace_back(std::make_shared(newName)); - DLOG_F(INFO, "Added new filterwheel instance successfully"); break; - } case DeviceType::Solver: - { - DLOG_F(INFO, "Trying to add a new solver instance : {} from {}", newName, lib_name); + logMsg = fmt::format("Trying to add a new solver instance : {} from {}", newName, lib_name); // m_devices[static_cast(type)].emplace_back(std::make_shared(newName)); break; - } case DeviceType::Guider: // m_devices[static_cast(type)].emplace_back(std::make_shared(newName)); break; default: - DLOG_F(ERROR, "Invalid device type"); + LOG_F(ERROR, "Invalid device type"); throw InvalidDeviceType("Invalid device type"); - break; } + + if (!logMsg.empty()) + { + DLOG_F(INFO, logMsg); + } + DLOG_F(INFO, "Added new {} instance successfully", DeviceTypeToString(type)); } } catch (const std::exception &e) { - DLOG_F(ERROR, "Failed to add device {} , error : {}", newName, e.what()); + LOG_F(ERROR, "Failed to add device {} , error : {}", newName, e.what()); return false; } if (m_ConfigManager) @@ -287,11 +240,12 @@ namespace Lithium #ifdef __cpp_lib_format m_ConfigManager->setValue(std::format("driver/{}/name", newName), newName); #else + m_ConfigManager->setValue(fmt::format("driver/{}/name", newName), newName); #endif } else { - DLOG_F(ERROR, "Config manager not initialized"); + LOG_F(ERROR, "Config manager not initialized"); } return true; } @@ -300,12 +254,12 @@ namespace Lithium { if (lib_path.empty() || lib_name.empty()) { - DLOG_F(ERROR, "Library path and name is required!"); + LOG_F(ERROR, "Library path and name is required!"); return false; } if (!m_ModuleLoader->LoadModule(lib_path, lib_name)) { - DLOG_F(ERROR, "Failed to load device library : {} in {}", lib_name, lib_path); + LOG_F(ERROR, "Failed to load device library : {} in {}", lib_name, lib_path); return false; } return true; @@ -340,12 +294,12 @@ namespace Lithium } else { - DLOG_F(ERROR,"Unknown property type!"); + LOG_F(ERROR,"Unknown property type!"); } } catch(const std::bad_any_cast &e) { - DLOG_F(ERROR,"Failed to cast property {}",e.what()); + LOG_F(ERROR,"Failed to cast property {}",e.what()); } } }); DLOG_F(INFO, "Add device {} observer successfully", name); @@ -353,7 +307,7 @@ namespace Lithium return true; } } - DLOG_F(ERROR, "Could not find device {} of type %d", name, static_cast(type)); + LOG_F(ERROR, "Could not find device {} of type %d", name, static_cast(type)); return false; } @@ -379,12 +333,12 @@ namespace Lithium } else { - DLOG_F(ERROR, "Config manager not initialized"); + LOG_F(ERROR, "Config manager not initialized"); } return true; } } - DLOG_F(ERROR, "Could not find device {} of type %d", name, static_cast(type)); + LOG_F(ERROR, "Could not find device {} of type %d", name, static_cast(type)); return false; } @@ -409,7 +363,7 @@ namespace Lithium } else { - DLOG_F(ERROR, "Config manager not initialized"); + LOG_F(ERROR, "Config manager not initialized"); } return true; } @@ -418,12 +372,12 @@ namespace Lithium { if (lib_name.empty()) { - DLOG_F(ERROR, "Library name is required"); + LOG_F(ERROR, "Library name is required"); return false; } if (!m_ModuleLoader->UnloadModule(lib_name)) { - DLOG_F(ERROR, "Failed to remove device library : {} with unload error", lib_name); + LOG_F(ERROR, "Failed to remove device library : {} with unload error", lib_name); return false; } return true; @@ -516,7 +470,7 @@ namespace Lithium break; } default: - DLOG_F(ERROR, "Invalid device type"); + LOG_F(ERROR, "Invalid device type"); break; } } @@ -535,7 +489,7 @@ namespace Lithium } if (!m_ConfigManager) { - DLOG_F(ERROR, "Config manager not initialized"); + LOG_F(ERROR, "Config manager not initialized"); } else { @@ -558,7 +512,7 @@ namespace Lithium } if (!m_ConfigManager) { - DLOG_F(ERROR, "Config manager not initialized"); + LOG_F(ERROR, "Config manager not initialized"); } else { @@ -578,7 +532,7 @@ namespace Lithium } if (!m_ConfigManager) { - DLOG_F(ERROR, "Config manager not initialized"); + LOG_F(ERROR, "Config manager not initialized"); } else { @@ -597,7 +551,7 @@ namespace Lithium auto device = getDevice(type, name); if (!device) { - DLOG_F(ERROR, "{} not found",name); + LOG_F(ERROR, "{} not found",name); return; } try @@ -606,7 +560,7 @@ namespace Lithium } catch (const std::bad_any_cast &e) { - DLOG_F(ERROR, "Failed to convert {} of {} with {}", value_name, name, e.what()); + LOG_F(ERROR, "Failed to convert {} of {} with {}", value_name, name, e.what()); } }, m_ThreadManager->generateRandomString(16)); return true; @@ -619,7 +573,7 @@ namespace Lithium auto device = findDeviceByName(name); if (!device) { - DLOG_F(ERROR, "{} not found",name); + LOG_F(ERROR, "{} not found",name); return; } try @@ -628,7 +582,7 @@ namespace Lithium } catch (const std::bad_any_cast &e) { - DLOG_F(ERROR, "Failed to convert {} of {} with {}", value_name, name, e.what()); + LOG_F(ERROR, "Failed to convert {} of {} with {}", value_name, name, e.what()); } }, m_ThreadManager->generateRandomString(16)); return true; @@ -646,7 +600,7 @@ namespace Lithium } catch (const std::bad_alloc &e) { - DLOG_F(ERROR, "Failed to set main camera to: {} with {}", name, e.what()); + LOG_F(ERROR, "Failed to set main camera to: {} with {}", name, e.what()); return false; } } @@ -665,7 +619,7 @@ namespace Lithium } catch (const std::bad_alloc &e) { - DLOG_F(ERROR, "Failed to set main camera to: {} with {}", name, e.what()); + LOG_F(ERROR, "Failed to set main camera to: {} with {}", name, e.what()); return false; } } @@ -684,7 +638,7 @@ namespace Lithium } catch (const std::bad_alloc &e) { - DLOG_F(ERROR, "Failed to set telescope to: {} with {}", name, e.what()); + LOG_F(ERROR, "Failed to set telescope to: {} with {}", name, e.what()); return false; } } @@ -703,7 +657,7 @@ namespace Lithium } catch (const std::bad_alloc &e) { - DLOG_F(ERROR, "Failed to set focuser to: {} with {}", name, e.what()); + LOG_F(ERROR, "Failed to set focuser to: {} with {}", name, e.what()); return false; } } @@ -722,7 +676,7 @@ namespace Lithium } catch (const std::bad_alloc &e) { - DLOG_F(ERROR, "Failed to set filterwheel to: {} with {}", name, e.what()); + LOG_F(ERROR, "Failed to set filterwheel to: {} with {}", name, e.what()); return false; } } @@ -741,7 +695,7 @@ namespace Lithium } catch (const std::bad_alloc &e) { - DLOG_F(ERROR, "Failed to set guider to: {} with {}", name, e.what()); + LOG_F(ERROR, "Failed to set guider to: {} with {}", name, e.what()); return false; } } @@ -758,7 +712,7 @@ namespace Lithium } if (!m_params.contains("exposure")) { - DLOG_F(ERROR, "Missing exposure time."); + LOG_F(ERROR, "Missing exposure time."); return DeviceError::MissingValue; } // 必须先指定是提前设置才会触发,不然所有功能均在startExposure中完成 @@ -782,7 +736,7 @@ namespace Lithium } if (!m_main_camera->startExposure(m_params)) { - DLOG_F(ERROR, "{} failed to start exposure", m_main_camera->getDeviceName()); + LOG_F(ERROR, "{} failed to start exposure", m_main_camera->getDeviceName()); return DeviceError::ExposureError; } return DeviceError::None; @@ -800,7 +754,7 @@ namespace Lithium { if (!m_main_camera->abortExposure(m_params)) { - DLOG_F(ERROR, "{} failed to stop exposure", m_main_camera->getDeviceName()); + LOG_F(ERROR, "{} failed to stop exposure", m_main_camera->getDeviceName()); return DeviceError::ExposureError; } DLOG_F(INFO, "{} is aborted successfully", m_main_camera->getDeviceName()); @@ -813,13 +767,13 @@ namespace Lithium CHECK_DEVICE(m_main_camera); if (!m_main_camera->isCoolingAvailable()) { - DLOG_F(ERROR, "{} did not support cooling mode", m_main_camera->getDeviceName()); + LOG_F(ERROR, "{} did not support cooling mode", m_main_camera->getDeviceName()); return DeviceError::NotSupported; } // TODO: 这里是否需要一个温度的检查,或者说是在启动制冷时是否需要指定问温度 if (!m_main_camera->startCooling(m_params)) { - DLOG_F(ERROR, "{} failed to start cooling mode", m_main_camera->getDeviceName()); + LOG_F(ERROR, "{} failed to start cooling mode", m_main_camera->getDeviceName()); return DeviceError::CoolingError; } return DeviceError::None; @@ -830,12 +784,12 @@ namespace Lithium CHECK_DEVICE(m_main_camera); if (!m_main_camera->isCoolingAvailable()) { - DLOG_F(ERROR, "{} did not support cooling mode", m_main_camera->getDeviceName()); + LOG_F(ERROR, "{} did not support cooling mode", m_main_camera->getDeviceName()); return DeviceError::NotSupported; } if (!m_main_camera->stopCooling(m_params)) { - DLOG_F(ERROR, "{} failed to stop cooling mode", m_main_camera->getDeviceName()); + LOG_F(ERROR, "{} failed to stop cooling mode", m_main_camera->getDeviceName()); return DeviceError::CoolingError; } return DeviceError::None; @@ -846,7 +800,7 @@ namespace Lithium CHECK_DEVICE(m_main_camera); if (!m_params.contains("gain")) { - DLOG_F(ERROR, "Failed to set gain: No gain value provided"); + LOG_F(ERROR, "Failed to set gain: No gain value provided"); return DeviceError::MissingValue; } else @@ -861,14 +815,14 @@ namespace Lithium int value = m_params["gain"].get(); if (value < 0 || value > 100) { - DLOG_F(ERROR, "Invalid gain value {}, would not set", value); + LOG_F(ERROR, "Invalid gain value {}, would not set", value); return DeviceError::InvalidValue; } else { if (!m_main_camera->setGain({"gain", value})) { - DLOG_F(ERROR, "Failed to set gain of main camera {}", m_main_camera->getDeviceName()); + LOG_F(ERROR, "Failed to set gain of main camera {}", m_main_camera->getDeviceName()); return DeviceError::GainError; } } @@ -882,7 +836,7 @@ namespace Lithium CHECK_DEVICE(m_main_camera); if (!m_params.contains("offset")) { - DLOG_F(ERROR, "Failed to set offset: No offset value provided"); + LOG_F(ERROR, "Failed to set offset: No offset value provided"); return DeviceError::MissingValue; } else @@ -897,14 +851,14 @@ namespace Lithium int value = m_params["offset"].get(); if (value < 0 || value > 255) { - DLOG_F(ERROR, "Invalid offset value {}, would not set", value); + LOG_F(ERROR, "Invalid offset value {}, would not set", value); return DeviceError::InvalidValue; } else { if (!m_main_camera->setOffset({"offset", value})) { - DLOG_F(ERROR, "Failed to set offset of main camera {}", m_main_camera->getDeviceName()); + LOG_F(ERROR, "Failed to set offset of main camera {}", m_main_camera->getDeviceName()); return DeviceError::OffsetError; } } @@ -918,7 +872,7 @@ namespace Lithium CHECK_DEVICE(m_main_camera); if (!m_params.contains("iso")) { - DLOG_F(ERROR, "Failed to set iso: No iso value provided"); + LOG_F(ERROR, "Failed to set iso: No iso value provided"); return DeviceError::MissingValue; } else @@ -934,7 +888,7 @@ namespace Lithium // TODO: There needs a ISO value check if (!m_main_camera->setISO({"iso", value})) { - DLOG_F(ERROR, "Failed to set iso of main camera {}", m_main_camera->getDeviceName()); + LOG_F(ERROR, "Failed to set iso of main camera {}", m_main_camera->getDeviceName()); return DeviceError::ISOError; } } @@ -1011,19 +965,19 @@ namespace Lithium CHECK_DEVICE(m_telescope); if (m_telescope->isAtPark({})) { - DLOG_F(ERROR, "{} had already parked, please unpark before {}", m_telescope->getDeviceName(), __func__); + LOG_F(ERROR, "{} had already parked, please unpark before {}", m_telescope->getDeviceName(), __func__); return DeviceError::ParkedError; } if (!m_params.contains("ra") || !m_params.contains("dec")) { - DLOG_F(ERROR, "{} failed to goto: Missing RA or DEC value", m_telescope->getDeviceName()); + LOG_F(ERROR, "{} failed to goto: Missing RA or DEC value", m_telescope->getDeviceName()); return DeviceError::MissingValue; } std::string ra = m_params["ra"]; std::string dec = m_params["dec"]; if (ra.empty() || dec.empty()) { - DLOG_F(ERROR, "RA or DEC value is missing"); + LOG_F(ERROR, "RA or DEC value is missing"); return DeviceError::MissingValue; } try @@ -1034,7 +988,7 @@ namespace Lithium } if (!checkTimeFormat(ra)) { - DLOG_F(ERROR, "Error Format of RA value {}", ra); + LOG_F(ERROR, "Error Format of RA value {}", ra); return DeviceError::InvalidValue; } if (checkDigits(dec)) @@ -1043,18 +997,18 @@ namespace Lithium } if (!checkTimeFormat(dec)) { - DLOG_F(ERROR, "Error Format of DEC value {}", ra); + LOG_F(ERROR, "Error Format of DEC value {}", ra); return DeviceError::InvalidValue; } } catch (const std::out_of_range &e) { - DLOG_F(ERROR, "Failed to check RA and DEC value: {}", e.what()); + LOG_F(ERROR, "Failed to check RA and DEC value: {}", e.what()); return DeviceError::InvalidValue; } if (!m_telescope->SlewTo(m_params)) { - DLOG_F(ERROR, "{} failed to slew to {} {}", m_telescope->getDeviceName(), ra, dec); + LOG_F(ERROR, "{} failed to slew to {} {}", m_telescope->getDeviceName(), ra, dec); return DeviceError::GotoError; } return DeviceError::None; @@ -1065,7 +1019,7 @@ namespace Lithium CHECK_DEVICE(m_telescope); if (!m_telescope->isParkAvailable(m_params)) { - DLOG_F(ERROR, "{} is not support park function", m_telescope->getDeviceName()); + LOG_F(ERROR, "{} is not support park function", m_telescope->getDeviceName()); return DeviceError::NotSupported; } if (m_telescope->isAtPark(m_params)) @@ -1075,7 +1029,7 @@ namespace Lithium } if (m_telescope->Park(m_params)) { - DLOG_F(ERROR, "{} failed to park", m_telescope->getDeviceName()); + LOG_F(ERROR, "{} failed to park", m_telescope->getDeviceName()); return DeviceError::ParkError; } DLOG_F(INFO, "{} parked successfully", m_telescope->getDeviceName()); @@ -1087,7 +1041,7 @@ namespace Lithium CHECK_DEVICE(m_telescope); if (!m_telescope->isParkAvailable(m_params)) { - DLOG_F(ERROR, "{} is not support park function", m_telescope->getDeviceName()); + LOG_F(ERROR, "{} is not support park function", m_telescope->getDeviceName()); return DeviceError::NotSupported; } if (!m_telescope->isAtPark(m_params)) @@ -1097,7 +1051,7 @@ namespace Lithium } if (m_telescope->Unpark(m_params)) { - DLOG_F(ERROR, "{} failed to unpark", m_telescope->getDeviceName()); + LOG_F(ERROR, "{} failed to unpark", m_telescope->getDeviceName()); return DeviceError::ParkError; } DLOG_F(INFO, "{} parked successfully", m_telescope->getDeviceName()); @@ -1109,22 +1063,22 @@ namespace Lithium CHECK_DEVICE(m_telescope); if (!m_telescope->isConnected()) { - DLOG_F(ERROR, "{} is not connected when call {}", m_telescope->getDeviceName(), __func__); + LOG_F(ERROR, "{} is not connected when call {}", m_telescope->getDeviceName(), __func__); return DeviceError::NotConnected; } if (!m_telescope->isHomeAvailable({})) { - DLOG_F(ERROR, "{} is not support home", m_telescope->getDeviceName()); + LOG_F(ERROR, "{} is not support home", m_telescope->getDeviceName()); return DeviceError::NotSupported; } if (m_telescope->isAtPark({})) { - DLOG_F(ERROR, "{} had already parked, please unpark before {}", m_telescope->getDeviceName(), __func__); + LOG_F(ERROR, "{} had already parked, please unpark before {}", m_telescope->getDeviceName(), __func__); return DeviceError::ParkedError; } if (!m_telescope->Home(m_params)) { - DLOG_F(ERROR, "{} Failed to go home position"); + LOG_F(ERROR, "{} Failed to go home position"); return DeviceError::HomeError; } DLOG_F(INFO, "{} go home position successfully!", m_telescope->getDeviceName()); @@ -1300,7 +1254,7 @@ namespace Lithium { if (!m_indimanager->is_running()) { - DLOG_F(ERROR, "INDI server is not started(not by lithium server)"); + LOG_F(ERROR, "INDI server is not started(not by lithium server)"); return false; } return true; diff --git a/src/modules/device/device_manager.hpp b/src/modules/device/device_manager.hpp index cc16a60f..65513d09 100644 --- a/src/modules/device/device_manager.hpp +++ b/src/modules/device/device_manager.hpp @@ -38,10 +38,6 @@ Description: Device Manager #include #include "core/device.hpp" -#include "config/configor.hpp" -#include "module/modloader.hpp" -#include "server/message_bus.hpp" -#include "thread/thread.hpp" #include "error/error_code.hpp" @@ -74,6 +70,19 @@ namespace Lithium Guider, NumDeviceTypes }; + + class ModuleLoader; + class MessageBus; + + namespace Thread + { + class ThreadManager; + } + + namespace Config + { + class ConfigManager; + } /** * @class DeviceManager diff --git a/src/modules/device/indi_device.cpp b/src/modules/device/indi_device.cpp index ca19b1e5..8be20433 100644 --- a/src/modules/device/indi_device.cpp +++ b/src/modules/device/indi_device.cpp @@ -75,7 +75,7 @@ void INDIDriverCollection::parseDrivers() pugi::xml_document doc; if (!doc.load_file(fname.c_str())) { - DLOG_F(ERROR, "Error loading file {}", fname); + LOG_F(ERROR, "Error loading file {}", fname); continue; } diff --git a/src/modules/device/indidevice_manager.cpp b/src/modules/device/indidevice_manager.cpp index 7b81a1eb..0d59bf7d 100644 --- a/src/modules/device/indidevice_manager.cpp +++ b/src/modules/device/indidevice_manager.cpp @@ -112,7 +112,7 @@ void INDIManager::stop_server() } else { - DLOG_F(ERROR, "Failed to terminate indiserver, error code is {}", res); + LOG_F(ERROR, "Failed to terminate indiserver, error code is {}", res); } } @@ -189,7 +189,7 @@ void INDIManager::start_driver(std::shared_ptr driver) } else { - DLOG_F(ERROR, "Failed to start driver: {}", driver->name); + LOG_F(ERROR, "Failed to start driver: {}", driver->name); } #else int res = system(full_cmd.c_str()); @@ -223,7 +223,7 @@ void INDIManager::stop_driver(std::shared_ptr driver) } else { - DLOG_F(ERROR, "Failed to stop driver: {}", driver->label); + LOG_F(ERROR, "Failed to stop driver: {}", driver->label); } #else int res = system(full_cmd.c_str()); @@ -263,7 +263,7 @@ void INDIManager::set_prop(const std::string &dev, const std::string &prop, cons int result = system(cmd.c_str()); if (result != 0) { - DLOG_F(ERROR, _("Failed to run command: {}"), cmd); + LOG_F(ERROR, _("Failed to run command: {}"), cmd); } } diff --git a/src/modules/deviceloader/client_info.cpp b/src/modules/deviceloader/client_info.cpp index 4a99ed5c..baca3947 100644 --- a/src/modules/deviceloader/client_info.cpp +++ b/src/modules/deviceloader/client_info.cpp @@ -76,7 +76,7 @@ void ClInfo::onMessage(XMLEle *root, std::list &sharedBuffers) Msg *mp = Msg::fromXml(this, root, sharedBuffers); if (!mp) { - DLOG_F(ERROR, "Closing after malformed message\n"); + LOG_F(ERROR, "Closing after malformed message\n"); close(); return; } @@ -103,7 +103,7 @@ void ClInfo::onMessage(XMLEle *root, std::list &sharedBuffers) void ClInfo::close() { if (verbose > 0) - DLOG_F(ERROR, "shut down complete - bye!\n"); + LOG_F(ERROR, "shut down complete - bye!\n"); delete (this); diff --git a/src/modules/deviceloader/driver_info.cpp b/src/modules/deviceloader/driver_info.cpp index 602ca314..ee380919 100644 --- a/src/modules/deviceloader/driver_info.cpp +++ b/src/modules/deviceloader/driver_info.cpp @@ -32,7 +32,7 @@ void DvrInfo::onMessage(XMLEle *root, std::list &sharedBuffers) traceMsg("read ", root); else if (verbose > 1) { - DLOG_F(ERROR, "read <{} device='{}' name='{}'>\n", tagXMLEle(root), findXMLAttValu(root, "device"), findXMLAttValu(root, "name")); + LOG_F(ERROR, "read <{} device='{}' name='{}'>\n", tagXMLEle(root), findXMLAttValu(root, "device"), findXMLAttValu(root, "name")); } /* that's all if driver is just registering a snoop */ diff --git a/src/modules/deviceloader/hydrogen_server.cpp b/src/modules/deviceloader/hydrogen_server.cpp index 3065ac04..29f508ff 100644 --- a/src/modules/deviceloader/hydrogen_server.cpp +++ b/src/modules/deviceloader/hydrogen_server.cpp @@ -357,7 +357,7 @@ int main(int ac, char *av[]) #endif /* will not happen unless no more listener left ! */ - DLOG_F(ERROR, "unexpected return from event loop"); + LOG_F(ERROR, "unexpected return from event loop"); return (1); } @@ -389,7 +389,7 @@ void run_hydrogen_server(std::unordered_map m_params) loop.loop(); #endif /* will not happen unless no more listener left ! */ - DLOG_F(ERROR, "unexpected return from event loop"); + LOG_F(ERROR, "unexpected return from event loop"); } void start_hydrogen_driver(const std::string &driver_binary,const std::string &driver_skeleton) diff --git a/src/modules/deviceloader/local_driver.cpp b/src/modules/deviceloader/local_driver.cpp index 2e760226..c91a7f9e 100644 --- a/src/modules/deviceloader/local_driver.cpp +++ b/src/modules/deviceloader/local_driver.cpp @@ -397,7 +397,7 @@ void LocalDvrInfo::onEfdEvent(uv_poll_t *handle, int status, int events) { // 处理错误情况 const char *error = uv_strerror(status); - DLOG_F(ERROR, "Error on stderr: {}", error); + LOG_F(ERROR, "Error on stderr: {}", error); closeEfd(); return; } @@ -415,10 +415,10 @@ void LocalDvrInfo::onEfdEvent(uv_poll_t *handle, int status, int events) if (errno == EAGAIN || errno == EWOULDBLOCK) return; - DLOG_F(ERROR, "stderr {}", strerror(errno)); + LOG_F(ERROR, "stderr {}", strerror(errno)); } else - DLOG_F(ERROR, "stderr EOF"); + LOG_F(ERROR, "stderr EOF"); closeEfd(); return; } @@ -428,7 +428,7 @@ void LocalDvrInfo::onEfdEvent(uv_poll_t *handle, int status, int events) { if (errbuff[i] == '\n') { - DLOG_F(ERROR, "{}{}", (int)i, errbuff); + LOG_F(ERROR, "{}{}", (int)i, errbuff); i++; /* count including nl */ errbuffpos -= i; /* remove from nexbuf */ memmove(errbuff, errbuff + i, errbuffpos); /* slide remaining to front */ @@ -449,12 +449,12 @@ void LocalDvrInfo::onPidEvent(uv_process_t *handle, int exit_status, int term_si { if (WIFEXITED(pidwatcher.signum)) { - DLOG_F(ERROR, "process {} exited with status {}", pid, WEXITSTATUS(pidwatcher.signum)); + LOG_F(ERROR, "process {} exited with status {}", pid, WEXITSTATUS(pidwatcher.signum)); } else if (WIFSIGNALED(pidwatcher.signum)) { int exit_status = WTERMSIG(pidwatcher.signum); - DLOG_F(ERROR, "process {} killed with signal {} - {}", pid, exit_status, strsignal(exit_status)); + LOG_F(ERROR, "process {} killed with signal {} - {}", pid, exit_status, strsignal(exit_status)); } pid = 0; uv_signal_stop(&pidwatcher); @@ -469,7 +469,7 @@ void LocalDvrInfo::onEfdEvent(ev::io &, int revents) int sockErrno = readFdError(this->efd); if (sockErrno) { - DLOG_F(ERROR, "Error on stderr: {}", strerror(sockErrno)); + LOG_F(ERROR, "Error on stderr: {}", strerror(sockErrno)); closeEfd(); } return; @@ -488,10 +488,10 @@ void LocalDvrInfo::onEfdEvent(ev::io &, int revents) if (errno == EAGAIN || errno == EWOULDBLOCK) return; - DLOG_F(ERROR, "stderr {}", strerror(errno)); + LOG_F(ERROR, "stderr {}", strerror(errno)); } else - DLOG_F(ERROR, "stderr EOF"); + LOG_F(ERROR, "stderr EOF"); closeEfd(); return; } @@ -501,7 +501,7 @@ void LocalDvrInfo::onEfdEvent(ev::io &, int revents) { if (errbuff[i] == '\n') { - DLOG_F(ERROR, "{}{}", (int)i, errbuff); + LOG_F(ERROR, "{}{}", (int)i, errbuff); i++; /* count including nl */ errbuffpos -= i; /* remove from nexbuf */ memmove(errbuff, errbuff + i, errbuffpos); /* slide remaining to front */ @@ -521,12 +521,12 @@ void LocalDvrInfo::onPidEvent(ev::child &, int revents) { if (WIFEXITED(pidwatcher.rstatus)) { - DLOG_F(ERROR, "process {} exited with status {}", pid, WEXITSTATUS(pidwatcher.rstatus)); + LOG_F(ERROR, "process {} exited with status {}", pid, WEXITSTATUS(pidwatcher.rstatus)); } else if (WIFSIGNALED(pidwatcher.rstatus)) { int exit_status = WTERMSIG(pidwatcher.rstatus); - DLOG_F(ERROR, "process {} killed with signal {} - {}", pid, exit_status, strsignal(exit_status)); + LOG_F(ERROR, "process {} killed with signal {} - {}", pid, exit_status, strsignal(exit_status)); } pid = 0; this->pidwatcher.stop(); diff --git a/src/modules/deviceloader/message.cpp b/src/modules/deviceloader/message.cpp index 8ef9e9b1..777188f6 100644 --- a/src/modules/deviceloader/message.cpp +++ b/src/modules/deviceloader/message.cpp @@ -167,7 +167,7 @@ bool parseBlobSize(XMLEle *blobWithAttachedBuffer, ssize_t &size) size = std::stoll(sizeStr, &pos, 10); if (pos != sizeStr.size()) { - DLOG_F(ERROR, "Invalid size attribute value %s", sizeStr.c_str()); + LOG_F(ERROR, "Invalid size attribute value %s", sizeStr.c_str()); return false; } return true; @@ -182,7 +182,7 @@ bool Msg::fetchBlobs(std::list &incomingSharedBuffers) ssize_t blobSize; if (!parseBlobSize(blobContent, blobSize)) { - DLOG_F(ERROR, "Attached blob misses the size attribute"); + LOG_F(ERROR, "Attached blob misses the size attribute"); return false; } @@ -191,12 +191,12 @@ bool Msg::fetchBlobs(std::list &incomingSharedBuffers) { if (incomingSharedBuffers.empty()) { - DLOG_F(ERROR, "Missing shared buffer...\n"); + LOG_F(ERROR, "Missing shared buffer...\n"); return false; } queueSize += blobSize; - // DLOG_F(ERROR,"Found one fd !\n"); + // LOG_F(ERROR,"Found one fd !\n"); int fd = *incomingSharedBuffers.begin(); incomingSharedBuffers.pop_front(); diff --git a/src/modules/deviceloader/message_queue.cpp b/src/modules/deviceloader/message_queue.cpp index 61a5fa0f..e8e27469 100644 --- a/src/modules/deviceloader/message_queue.cpp +++ b/src/modules/deviceloader/message_queue.cpp @@ -82,7 +82,7 @@ void MsgQueue::closeWritePart() { if (errno != ENOTCONN) { - DLOG_F(ERROR, "socket shutdown failed: %s\n", strerror(errno)); + LOG_F(ERROR, "socket shutdown failed: %s\n", strerror(errno)); close(); } } @@ -556,9 +556,9 @@ void MsgQueue::readFromFd() return; if (nr < 0) - DLOG_F(ERROR, "read: %s\n", strerror(errno)); + LOG_F(ERROR, "read: %s\n", strerror(errno)); else if (verbose > 0) - DLOG_F(ERROR, "read EOF\n"); + LOG_F(ERROR, "read EOF\n"); close(); return; } @@ -616,7 +616,7 @@ void MsgQueue::writeToFd() auto mp = headMsg(); if (mp == nullptr) { - DLOG_F(ERROR, "Unexpected write notification"); + LOG_F(ERROR, "Unexpected write notification"); return; } @@ -659,7 +659,7 @@ void MsgQueue::writeToFd() { if (fdCount > MAXFD_PER_MESSAGE) { - DLOG_F(ERROR, "attempt to send too many FD\n"); + LOG_F(ERROR, "attempt to send too many FD\n"); close(); return; } @@ -707,7 +707,7 @@ void MsgQueue::writeToFd() if (nw == 0) DLOG_F(INFO, "write returned 0\n"); else - DLOG_F(ERROR, "write: %s\n", strerror(errno)); + LOG_F(ERROR, "write: %s\n", strerror(errno)); // 保持读取部分打开 closeWritePart(); @@ -732,7 +732,7 @@ void MsgQueue::writeToFd() auto mp = headMsg(); if (mp == nullptr) { - DLOG_F(ERROR, "Unexpected write notification"); + LOG_F(ERROR, "Unexpected write notification"); return; } @@ -779,7 +779,7 @@ void MsgQueue::writeToFd() { if (fdCount > MAXFD_PER_MESSAGE) { - DLOG_F(ERROR, "attempt to send too many FD\n"); + LOG_F(ERROR, "attempt to send too many FD\n"); close(); return; } @@ -828,7 +828,7 @@ void MsgQueue::writeToFd() if (nw == 0) DLOG_F(INFO, "write returned 0\n"); else - DLOG_F(ERROR, "write: %s\n", strerror(errno)); + LOG_F(ERROR, "write: %s\n", strerror(errno)); // Keep the read part open closeWritePart(); @@ -876,25 +876,25 @@ void MsgQueue::traceMsg(const std::string &logMsg, XMLEle *root) /* print tag header */ // fprintf(stderr, "%s %s %s %s", tagXMLEle(root), findXMLAttValu(root, "device"), findXMLAttValu(root, "name"), // findXMLAttValu(root, "state")); - DLOG_F(ERROR, "{} {} {} {}", tagXMLEle(root), findXMLAttValu(root, "device"), findXMLAttValu(root, "name"), + LOG_F(ERROR, "{} {} {} {}", tagXMLEle(root), findXMLAttValu(root, "device"), findXMLAttValu(root, "name"), findXMLAttValu(root, "state")); pcd = pcdataXMLEle(root); if (pcd[0]) // fprintf(stderr, " %s", pcd); - DLOG_F(ERROR, "{}", pcd); + LOG_F(ERROR, "{}", pcd); perm = findXMLAttValu(root, "perm"); if (perm[0]) // fprintf(stderr, " %s", perm); - DLOG_F(ERROR, "{}", perm); + LOG_F(ERROR, "{}", perm); msg = findXMLAttValu(root, "message"); if (msg[0]) // fprintf(stderr, " '%s'", msg); - DLOG_F(ERROR, "{}", msg); + LOG_F(ERROR, "{}", msg); /* print each array value */ for (e = nextXMLEle(root, 1); e; e = nextXMLEle(root, 0)) for (i = 0; i < sizeof(prtags) / sizeof(prtags[0]); i++) if (strcmp(prtags[i], tagXMLEle(e)) == 0) // fprintf(stderr, "\n %10s='%s'", findXMLAttValu(e, "name"), pcdataXMLEle(e)); - DLOG_F(ERROR, "{:<10}='{}'", findXMLAttValu(e, "name"), pcdataXMLEle(e)); + LOG_F(ERROR, "{:<10}='{}'", findXMLAttValu(e, "name"), pcdataXMLEle(e)); } \ No newline at end of file diff --git a/src/modules/deviceloader/remote_driver.cpp b/src/modules/deviceloader/remote_driver.cpp index 828c5695..f156a9fa 100644 --- a/src/modules/deviceloader/remote_driver.cpp +++ b/src/modules/deviceloader/remote_driver.cpp @@ -145,7 +145,7 @@ int RemoteDvrInfo::openHYDROGENServer() hp = gethostbyname(host.c_str()); if (!hp) { - DLOG_F(ERROR, "gethostbyname({}): {}", host.c_str(), strerror(errno)); + LOG_F(ERROR, "gethostbyname({}): {}", host.c_str(), strerror(errno)); // Bye(); } @@ -156,14 +156,14 @@ int RemoteDvrInfo::openHYDROGENServer() serv_addr.sin_port = htons(port); if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0) { - DLOG_F(ERROR, "socket({},{}): {}", host.c_str(), port, strerror(errno)); + LOG_F(ERROR, "socket({},{}): {}", host.c_str(), port, strerror(errno)); // Bye(); } /* connect */ if (connect(sockfd, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0) { - DLOG_F(ERROR, "connect({},{}): {}", host.c_str(), port, strerror(errno)); + LOG_F(ERROR, "connect({},{}): {}", host.c_str(), port, strerror(errno)); // Bye(); } diff --git a/src/modules/deviceloader/serialize.cpp b/src/modules/deviceloader/serialize.cpp index b5d1c3f6..87aab889 100644 --- a/src/modules/deviceloader/serialize.cpp +++ b/src/modules/deviceloader/serialize.cpp @@ -536,7 +536,7 @@ void SerializedMsgWithSharedBuffer::generateContent() void *blob = IDSharedBlobAlloc(size); if (blob == nullptr) { - DLOG_F(ERROR, "Unable to allocate shared buffer of size %ld : %s\n", size, strerror(errno)); + LOG_F(ERROR, "Unable to allocate shared buffer of size %ld : %s\n", size, strerror(errno)); ::exit(1); } DLOG_F(INFO, "Blob allocated at %p\n", blob); diff --git a/src/modules/deviceloader/tcp_server.cpp b/src/modules/deviceloader/tcp_server.cpp index 6d081a58..3686b9cd 100644 --- a/src/modules/deviceloader/tcp_server.cpp +++ b/src/modules/deviceloader/tcp_server.cpp @@ -30,7 +30,7 @@ void TcpServer::ioCb(uv_poll_t *watcher, int status, int revents) { if (status < 0) { - DLOG_F(ERROR, "Error on tcp server socket: {}", uv_strerror(status)); + LOG_F(ERROR, "Error on tcp server socket: {}", uv_strerror(status)); // Bye(); } else if (revents & UV_READABLE) @@ -47,7 +47,7 @@ void TcpServer::listen() /* make socket endpoint */ if ((sfd = socket(AF_INET, SOCK_STREAM, 0)) < 0) { - DLOG_F(ERROR, "socket: %s\n", strerror(errno)); + LOG_F(ERROR, "socket: %s\n", strerror(errno)); // Bye(); } @@ -63,7 +63,7 @@ void TcpServer::listen() #ifdef _WIN32 if (setsockopt(sfd, SOL_SOCKET, SO_RCVTIMEO, (const char *)&reuse, sizeof(reuse)) < 0) { - DLOG_F(ERROR, "Failed to set receive timeout."); + LOG_F(ERROR, "Failed to set receive timeout."); close(sfd); sfd = -1; return; @@ -71,20 +71,20 @@ void TcpServer::listen() #else if (setsockopt(sfd, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse)) < 0) { - DLOG_F(ERROR, "setsockopt: %s\n", strerror(errno)); + LOG_F(ERROR, "setsockopt: %s\n", strerror(errno)); // Bye(); } #endif if (bind(sfd, (struct sockaddr *)&serv_socket, sizeof(serv_socket)) < 0) { - DLOG_F(ERROR, "bind: %s\n", strerror(errno)); + LOG_F(ERROR, "bind: %s\n", strerror(errno)); // Bye(); } /* willing to accept connections with a backlog of 5 pending */ if (::listen(sfd, 5) < 0) { - DLOG_F(ERROR, "listen: %s\n", strerror(errno)); + LOG_F(ERROR, "listen: %s\n", strerror(errno)); // Bye(); } @@ -122,7 +122,7 @@ void TcpServer::accept() if (errno == EAGAIN || errno == EWOULDBLOCK) return; - DLOG_F(ERROR, "accept: %s\n", strerror(errno)); + LOG_F(ERROR, "accept: %s\n", strerror(errno)); // Bye(); } @@ -146,7 +146,7 @@ void TcpServer::ioCb(ev::io &, int revents) int sockErrno = readFdError(this->sfd); if (sockErrno) { - DLOG_F(ERROR, "Error on tcp server socket: %s\n", strerror(sockErrno)); + LOG_F(ERROR, "Error on tcp server socket: %s\n", strerror(sockErrno)); // Bye(); } } @@ -164,7 +164,7 @@ void TcpServer::listen() /* make socket endpoint */ if ((sfd = socket(AF_INET, SOCK_STREAM, 0)) < 0) { - DLOG_F(ERROR, "socket: %s\n", strerror(errno)); + LOG_F(ERROR, "socket: %s\n", strerror(errno)); // Bye(); } @@ -180,7 +180,7 @@ void TcpServer::listen() #ifdef _WIN32 if (setsockopt(sfd, SOL_SOCKET, SO_RCVTIMEO, (const char *)&reuse, sizeof(reuse)) < 0) { - DLOG_F(ERROR, "Failed to set receive timeout."); + LOG_F(ERROR, "Failed to set receive timeout."); close(sfd); sfd = -1; return; @@ -188,20 +188,20 @@ void TcpServer::listen() #else if (setsockopt(sfd, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse)) < 0) { - DLOG_F(ERROR, "setsockopt: %s\n", strerror(errno)); + LOG_F(ERROR, "setsockopt: %s\n", strerror(errno)); // Bye(); } #endif if (bind(sfd, (struct sockaddr *)&serv_socket, sizeof(serv_socket)) < 0) { - DLOG_F(ERROR, "bind: %s\n", strerror(errno)); + LOG_F(ERROR, "bind: %s\n", strerror(errno)); // Bye(); } /* willing to accept connections with a backlog of 5 pending */ if (::listen(sfd, 5) < 0) { - DLOG_F(ERROR, "listen: %s\n", strerror(errno)); + LOG_F(ERROR, "listen: %s\n", strerror(errno)); // Bye(); } @@ -232,7 +232,7 @@ void TcpServer::accept() if (errno == EAGAIN || errno == EWOULDBLOCK) return; - DLOG_F(ERROR, "accept: %s\n", strerror(errno)); + LOG_F(ERROR, "accept: %s\n", strerror(errno)); // Bye(); } diff --git a/src/modules/error/error_stack.cpp b/src/modules/error/error_stack.cpp index fa1992d5..0d220211 100644 --- a/src/modules/error/error_stack.cpp +++ b/src/modules/error/error_stack.cpp @@ -83,7 +83,7 @@ void ErrorStack::PrintFilteredErrorStack() const { if (std::find(filteredModules.begin(), filteredModules.end(), error.moduleName) == filteredModules.end()) { - DLOG_F(ERROR, "%s", error.errorMessage.c_str()); + LOG_F(ERROR, "%s", error.errorMessage.c_str()); } } } diff --git a/src/modules/io/compress.cpp b/src/modules/io/compress.cpp index 0d73c057..faf24190 100644 --- a/src/modules/io/compress.cpp +++ b/src/modules/io/compress.cpp @@ -85,7 +85,7 @@ namespace Lithium::File std::filesystem::path input_path(file_name); if (!std::filesystem::exists(input_path)) { - DLOG_F(ERROR, "Input file {} does not exist.", file_name); + LOG_F(ERROR, "Input file {} does not exist.", file_name); return false; } @@ -93,14 +93,14 @@ namespace Lithium::File gzFile out = gzopen(output_path.string().c_str(), "wb"); if (!out) { - DLOG_F(ERROR, "Failed to create compressed file {}", output_path.string()); + LOG_F(ERROR, "Failed to create compressed file {}", output_path.string()); return false; } std::ifstream in(file_name, std::ios::binary); if (!in) { - DLOG_F(ERROR, "Failed to open input file {}", file_name); + LOG_F(ERROR, "Failed to open input file {}", file_name); gzclose(out); return false; } @@ -113,7 +113,7 @@ namespace Lithium::File if (gzwrite(out, buf, bytesRead) != bytesRead) { - DLOG_F(ERROR, "Failed to compress file {}", file_name); + LOG_F(ERROR, "Failed to compress file {}", file_name); in.close(); gzclose(out); return false; @@ -131,7 +131,7 @@ namespace Lithium::File std::filesystem::path input_path(file_name); if (!std::filesystem::exists(input_path)) { - DLOG_F(ERROR, "Input file {} does not exist.", file_name); + LOG_F(ERROR, "Input file {} does not exist.", file_name); return false; } @@ -139,14 +139,14 @@ namespace Lithium::File FILE *out = fopen(output_path.string().c_str(), "wb"); if (!out) { - DLOG_F(ERROR, "Failed to create decompressed file {}", output_path.string()); + LOG_F(ERROR, "Failed to create decompressed file {}", output_path.string()); return false; } gzFile in = gzopen(file_name.c_str(), "rb"); if (!in) { - DLOG_F(ERROR, "Failed to open compressed file {}", file_name); + LOG_F(ERROR, "Failed to open compressed file {}", file_name); fclose(out); return false; } @@ -157,7 +157,7 @@ namespace Lithium::File { if (fwrite(buf, 1, bytesRead, out) != static_cast(bytesRead)) { - DLOG_F(ERROR, "Failed to decompress file {}", file_name); + LOG_F(ERROR, "Failed to decompress file {}", file_name); fclose(out); gzclose(in); return false; @@ -172,13 +172,16 @@ namespace Lithium::File bool compress_folder(const char *folder_name) { - // Size of the read/write buffer - char outfile_name[256]; - sprintf(outfile_name, "{}.gz", folder_name); - gzFile out = gzopen(outfile_name, "wb"); +// Size of the read/write buffer +#ifdef __cpp_lib_format + std::string outfile_name = std::format("{}.gz", folder_name); +#else + std::string outfile_name = fmt::format("{}.gz", folder_name); +#endif + gzFile out = gzopen(outfile_name.c_str(), "wb"); if (!out) { - DLOG_F(ERROR, "Failed to create compressed file {}", outfile_name); + LOG_F(ERROR, "Failed to create compressed file {}", outfile_name); return false; } #ifdef _WIN32 @@ -190,7 +193,7 @@ namespace Lithium::File hFind = FindFirstFileA(searchPath, &findData); if (hFind == INVALID_HANDLE_VALUE) { - DLOG_F(ERROR, "Failed to open folder {}", folder_name); + LOG_F(ERROR, "Failed to open folder {}", folder_name); gzclose(out); return false; } @@ -234,7 +237,7 @@ namespace Lithium::File { fclose(in); gzclose(out); - DLOG_F(ERROR, "Failed to create compressed file {}", outfile_name); + LOG_F(ERROR, "Failed to create compressed file {}", outfile_name); return false; } } @@ -247,7 +250,7 @@ namespace Lithium::File dir = opendir(folder_name); if (!dir) { - DLOG_F(ERROR, "Failed to open folder {}", folder_name); + LOG_F(ERROR, "Failed to open folder {}", folder_name); gzclose(out); return false; } @@ -256,10 +259,10 @@ namespace Lithium::File if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) continue; char file_name[512]; - int ret = snprintf(file_name, sizeof(file_name), "{}/{}", folder_name, entry->d_name); + int ret = snprintf(file_name, sizeof(file_name), "%s/%s", folder_name, entry->d_name); if (ret < 0 || ret >= sizeof(file_name)) { - DLOG_F(ERROR, "Failed to compress file {} because the output was truncated or an error occurred in snprintf()", entry->d_name); + LOG_F(ERROR, "Failed to compress file {} because the output was truncated or an error occurred in snprintf()", entry->d_name); closedir(dir); gzclose(out); return false; @@ -296,7 +299,7 @@ namespace Lithium::File { fclose(in); gzclose(out); - DLOG_F(ERROR, "Failed to compress file {}", file_name); + LOG_F(ERROR, "Failed to compress file {}", file_name); return false; } } @@ -314,7 +317,7 @@ namespace Lithium::File std::ifstream file(zip_file, std::ios::binary); if (!file) { - DLOG_F(ERROR, "Failed to open ZIP file: {}", zip_file); + LOG_F(ERROR, "Failed to open ZIP file: {}", zip_file); return false; } file.close(); @@ -324,7 +327,7 @@ namespace Lithium::File const std::string &strerror, int zip_error_code, int system_error_code) - { DLOG_F(ERROR, "Exract zip file failed : {} {}", message, strerror); }); + { LOG_F(ERROR, "Exract zip file failed : {} {}", message, strerror); }); zip.open(ZipArchive::ReadOnly); ProgressListener pl; zip.addProgressListener(&pl); @@ -337,7 +340,7 @@ namespace Lithium::File { std::string name = entry.getName(); int size = entry.getSize(); - DLOG_F(ERROR, "Extracting file: {}, size: %d", name, size); + LOG_F(ERROR, "Extracting file: {}, size: %d", name, size); std::string textData = entry.readAsText(); std::filesystem::path file_path = std::filesystem::path(destination_folder) / name; std::ofstream file(file_path); @@ -345,11 +348,11 @@ namespace Lithium::File { file << textData; file.close(); - DLOG_F(INFO, "File extracted: {}", file_path); + DLOG_F(INFO, "File extracted: {}", file_path.string()); } else { - DLOG_F(ERROR, "Failed to create file: {}", file_path); + LOG_F(ERROR, "Failed to create file: {}", file_path.string()); } } zip.close(); @@ -358,7 +361,7 @@ namespace Lithium::File } catch (const std::exception &e) { - DLOG_F(ERROR, "Failed to extract ZIP file: {}", e.what()); + LOG_F(ERROR, "Failed to extract ZIP file: {}", e.what()); return false; } } @@ -372,7 +375,7 @@ namespace Lithium::File const std::string &strerror, int zip_error_code, int system_error_code) - { DLOG_F(ERROR, "Create zip file failed : {} {}", message, strerror); }); + { LOG_F(ERROR, "Create zip file failed : {} {}", message, strerror); }); zip.open(ZipArchive::Write); ProgressListener pl; @@ -398,7 +401,7 @@ namespace Lithium::File } catch (const std::exception &e) { - DLOG_F(ERROR, "Failed to create ZIP file: {}", e.what()); + LOG_F(ERROR, "Failed to create ZIP file: {}", e.what()); return false; } } diff --git a/src/modules/io/file.cpp b/src/modules/io/file.cpp index 773e232f..5b54926e 100644 --- a/src/modules/io/file.cpp +++ b/src/modules/io/file.cpp @@ -57,13 +57,13 @@ namespace Lithium::File { if (fileExists(filename)) { - DLOG_F(ERROR, "File \"{}\" already exists!", filename); + LOG_F(ERROR, "File \"{}\" already exists!", filename); return false; } std::ofstream outfile(filename); if (!outfile) { - DLOG_F(ERROR, "Error creating file \"{}\"!", filename); + LOG_F(ERROR, "Error creating file \"{}\"!", filename); return false; } outfile.close(); @@ -76,14 +76,14 @@ namespace Lithium::File { if (!fileExists(filename)) { - DLOG_F(ERROR, "File \"{}\" does not exist!", filename); + LOG_F(ERROR, "File \"{}\" does not exist!", filename); return false; } m_filename = filename; m_file.open(filename, std::ios::in | std::ios::out); if (!m_file) { - DLOG_F(ERROR, "Could not open file \"{}\"!", filename); + LOG_F(ERROR, "Could not open file \"{}\"!", filename); return false; } DLOG_F(INFO, "Opened file \"{}\"", filename); @@ -94,7 +94,7 @@ namespace Lithium::File { if (!m_file.is_open()) { - DLOG_F(ERROR, "No file is currently open!"); + LOG_F(ERROR, "No file is currently open!"); return false; } std::stringstream buffer; @@ -108,7 +108,7 @@ namespace Lithium::File { if (!m_file.is_open()) { - DLOG_F(ERROR, "No file is currently open!"); + LOG_F(ERROR, "No file is currently open!"); return false; } m_file << contents; @@ -120,18 +120,18 @@ namespace Lithium::File { if (!fileExists(oldFilename)) { - DLOG_F(ERROR, "File \"{}\" does not exist!", oldFilename); + LOG_F(ERROR, "File \"{}\" does not exist!", oldFilename); return false; } if (fileExists(newFilename)) { - DLOG_F(ERROR, "File \"{}\" already exists!", newFilename); + LOG_F(ERROR, "File \"{}\" already exists!", newFilename); return false; } int result = std::rename(oldFilename.c_str(), newFilename.c_str()); if (result != 0) { - DLOG_F(ERROR, "Could not move file from \"{}\" to \"{}\"!", oldFilename, newFilename); + LOG_F(ERROR, "Could not move file from \"{}\" to \"{}\"!", oldFilename, newFilename); return false; } DLOG_F(INFO, "Moved file from \"{}\" to \"{}\"", oldFilename, newFilename); @@ -142,12 +142,12 @@ namespace Lithium::File { if (!fileExists(filename)) { - DLOG_F(ERROR, "File \"{}\" does not exist!", filename); + LOG_F(ERROR, "File \"{}\" does not exist!", filename); return false; } if (std::remove(filename.c_str()) != 0) { - DLOG_F(ERROR, "Could not delete file \"{}\"!", filename); + LOG_F(ERROR, "Could not delete file \"{}\"!", filename); return false; } DLOG_F(INFO, "Deleted file \"{}\"", filename); @@ -158,7 +158,7 @@ namespace Lithium::File { if (!m_file.is_open()) { - DLOG_F(ERROR, "No file is currently open!"); + LOG_F(ERROR, "No file is currently open!"); return -1; } m_file.seekg(0, m_file.end); @@ -166,7 +166,7 @@ namespace Lithium::File m_file.seekg(0, m_file.beg); if (fileSize == -1) { - DLOG_F(ERROR, "Could not get file size of \"{}\"!", m_filename); + LOG_F(ERROR, "Could not get file size of \"{}\"!", m_filename); } else { @@ -179,20 +179,20 @@ namespace Lithium::File { if (!m_file.is_open()) { - DLOG_F(ERROR, "No file is currently open!"); + LOG_F(ERROR, "No file is currently open!"); return ""; } EVP_MD_CTX *mdContext = EVP_MD_CTX_new(); if (mdContext == nullptr) { - DLOG_F(ERROR, "Failed to create EVP_MD_CTX"); + LOG_F(ERROR, "Failed to create EVP_MD_CTX"); return ""; } if (EVP_DigestInit_ex(mdContext, EVP_sha256(), nullptr) != 1) { - DLOG_F(ERROR, "Failed to initialize EVP_MD_CTX"); + LOG_F(ERROR, "Failed to initialize EVP_MD_CTX"); EVP_MD_CTX_free(mdContext); return ""; } @@ -202,7 +202,7 @@ namespace Lithium::File { if (EVP_DigestUpdate(mdContext, buffer, sizeof(buffer)) != 1) { - DLOG_F(ERROR, "Failed to update EVP_MD_CTX"); + LOG_F(ERROR, "Failed to update EVP_MD_CTX"); EVP_MD_CTX_free(mdContext); return ""; } @@ -212,7 +212,7 @@ namespace Lithium::File unsigned int hashLength = 0; if (EVP_DigestFinal_ex(mdContext, hash, &hashLength) != 1) { - DLOG_F(ERROR, "Failed to finalize EVP_MD_CTX"); + LOG_F(ERROR, "Failed to finalize EVP_MD_CTX"); EVP_MD_CTX_free(mdContext); return ""; } @@ -235,7 +235,7 @@ namespace Lithium::File size_t pos = filename.find_last_of("/\\"); if (pos == std::string::npos) { - DLOG_F(ERROR, "Could not get directory of file \"{}\"", filename); + LOG_F(ERROR, "Could not get directory of file \"{}\"", filename); return ""; } else diff --git a/src/modules/io/io.cpp b/src/modules/io/io.cpp index 4617e72f..26780d65 100644 --- a/src/modules/io/io.cpp +++ b/src/modules/io/io.cpp @@ -64,7 +64,7 @@ namespace Lithium::File } catch (const std::exception &ex) { - DLOG_F(ERROR, "Failed to create directory {}: {}", path, ex.what()); + LOG_F(ERROR, "Failed to create directory {}: {}", path, ex.what()); } return false; } @@ -79,7 +79,7 @@ namespace Lithium::File } catch (const std::exception &ex) { - DLOG_F(ERROR, "Failed to remove directory {}: {}", path, ex.what()); + LOG_F(ERROR, "Failed to remove directory {}: {}", path, ex.what()); } return false; } @@ -94,7 +94,7 @@ namespace Lithium::File } catch (const std::exception &ex) { - DLOG_F(ERROR, "Failed to rename directory from {} to {}: {}", old_path, new_path, ex.what()); + LOG_F(ERROR, "Failed to rename directory from {} to {}: {}", old_path, new_path, ex.what()); } return false; } @@ -109,7 +109,7 @@ namespace Lithium::File } catch (const std::exception &ex) { - DLOG_F(ERROR, "Failed to move directory from {} to {}: {}", old_path, new_path, ex.what()); + LOG_F(ERROR, "Failed to move directory from {} to {}: {}", old_path, new_path, ex.what()); } return false; } @@ -124,7 +124,7 @@ namespace Lithium::File } catch (const std::exception &ex) { - DLOG_F(ERROR, "Failed to copy file from {} to {}: {}", src_path, dst_path, ex.what()); + LOG_F(ERROR, "Failed to copy file from {} to {}: {}", src_path, dst_path, ex.what()); } return false; } @@ -139,7 +139,7 @@ namespace Lithium::File } catch (const std::exception &ex) { - DLOG_F(ERROR, "Failed to move file from {} to {}: {}", src_path, dst_path, ex.what()); + LOG_F(ERROR, "Failed to move file from {} to {}: {}", src_path, dst_path, ex.what()); } return false; } @@ -154,7 +154,7 @@ namespace Lithium::File } catch (const std::exception &ex) { - DLOG_F(ERROR, "Failed to rename file from {} to {}: {}", old_path, new_path, ex.what()); + LOG_F(ERROR, "Failed to rename file from {} to {}: {}", old_path, new_path, ex.what()); } return false; } @@ -169,7 +169,7 @@ namespace Lithium::File } catch (const std::exception &ex) { - DLOG_F(ERROR, "Failed to remove file {}: {}", path, ex.what()); + LOG_F(ERROR, "Failed to remove file {}: {}", path, ex.what()); } return false; } @@ -184,7 +184,7 @@ namespace Lithium::File } catch (const std::exception &ex) { - DLOG_F(ERROR, "Failed to create symlink from {} to {}: {}", target_path, symlink_path, ex.what()); + LOG_F(ERROR, "Failed to create symlink from {} to {}: {}", target_path, symlink_path, ex.what()); } return false; } @@ -199,7 +199,7 @@ namespace Lithium::File } catch (const std::exception &ex) { - DLOG_F(ERROR, "Failed to remove symlink {}: {}", path, ex.what()); + LOG_F(ERROR, "Failed to remove symlink {}: {}", path, ex.what()); } return false; } @@ -212,7 +212,7 @@ namespace Lithium::File } catch (const std::exception &ex) { - DLOG_F(ERROR, "Failed to get file size of {}: {}", path, ex.what()); + LOG_F(ERROR, "Failed to get file size of {}: {}", path, ex.what()); return 0; } } @@ -235,7 +235,7 @@ namespace Lithium::File } catch (const std::exception &ex) { - DLOG_F(ERROR, "Failed to traverse directory {}: {}", path, ex.what()); + LOG_F(ERROR, "Failed to traverse directory {}: {}", path, ex.what()); } } diff --git a/src/modules/module/compiler.cpp b/src/modules/module/compiler.cpp index 996a5e6f..2aa4e500 100644 --- a/src/modules/module/compiler.cpp +++ b/src/modules/module/compiler.cpp @@ -65,7 +65,7 @@ namespace Lithium // 参数校验 if (code.empty() || moduleName.empty() || functionName.empty()) { - DLOG_F(ERROR, "Invalid parameters."); + LOG_F(ERROR, "Invalid parameters."); return false; } @@ -88,7 +88,7 @@ namespace Lithium } catch (const std::exception &e) { - DLOG_F(ERROR, "Failed to create output directory: {}", e.what()); + LOG_F(ERROR, "Failed to create output directory: {}", e.what()); return false; } } @@ -110,13 +110,13 @@ namespace Lithium } else { - DLOG_F(ERROR, "Invalid format in compile_options.json."); + LOG_F(ERROR, "Invalid format in compile_options.json."); return false; } } catch (const std::exception &e) { - DLOG_F(ERROR, "Error reading compile_options.json: {}", e.what()); + LOG_F(ERROR, "Error reading compile_options.json: {}", e.what()); return false; } } @@ -130,7 +130,7 @@ namespace Lithium std::string syntaxCheckOutput; if (RunShellCommand(syntaxCheckCmd.str(), code, syntaxCheckOutput) != 0) { - DLOG_F(ERROR, "Syntax error in C++ code: {}", syntaxCheckOutput); + LOG_F(ERROR, "Syntax error in C++ code: {}", syntaxCheckOutput); return false; } @@ -142,7 +142,7 @@ namespace Lithium int exitCode = RunShellCommand(cmd, code, compilationOutput); if (exitCode != 0) { - DLOG_F(ERROR, "Failed to compile C++ code: {}", compilationOutput); + LOG_F(ERROR, "Failed to compile C++ code: {}", compilationOutput); return false; } @@ -155,7 +155,7 @@ namespace Lithium LOG_S(INFO) << "Module " << moduleName << "::" << functionName << " compiled successfully."; return true; } else { - DLOG_F(ERROR, "Failed to load the compiled module: {}", output); + LOG_F(ERROR, "Failed to load the compiled module: {}", output); return false; } */ @@ -197,17 +197,17 @@ namespace Lithium sa.bInheritHandle = TRUE; if (!CreatePipe(&hStdinRead, &hStdoutWrite, &sa, 0)) { - DLOG_F(ERROR, "Failed to create input pipe for shell command: {}", command); + LOG_F(ERROR, "Failed to create input pipe for shell command: {}", command); return exitCode; } if (!SetHandleInformation(hStdoutWrite, HANDLE_FLAG_INHERIT, 0)) { - DLOG_F(ERROR, "Failed to set input handle information for shell command: {}", command); + LOG_F(ERROR, "Failed to set input handle information for shell command: {}", command); return exitCode; } if (!SetHandleInformation(hStdoutRead, HANDLE_FLAG_INHERIT, 0)) { - DLOG_F(ERROR, "Failed to set output handle information for shell command: {}", command); + LOG_F(ERROR, "Failed to set output handle information for shell command: {}", command); return exitCode; } si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES; @@ -221,7 +221,7 @@ namespace Lithium if (!CreateProcess(NULL, &commandBuffer[0], NULL, NULL, TRUE, 0, NULL, NULL, &si, &pi)) { - DLOG_F(ERROR, "Failed to launch shell command: {}", command); + LOG_F(ERROR, "Failed to launch shell command: {}", command); CloseHandle(hStdinRead); CloseHandle(hStdoutWrite); CloseHandle(hStdoutRead); @@ -245,7 +245,7 @@ namespace Lithium DWORD bytesWritten; if (!WriteFile(hStdoutWrite, input, input.size(), &bytesWritten, NULL)) { - DLOG_F(ERROR, "Failed to write input for shell command: {}", command); + LOG_F(ERROR, "Failed to write input for shell command: {}", command); return exitCode; } CloseHandle(hStdoutWrite); @@ -264,7 +264,7 @@ namespace Lithium FILE *pipe = popen(command.c_str(), "w"); if (!pipe) { - DLOG_F(ERROR, "Failed to popen shell command: {}", command); + LOG_F(ERROR, "Failed to popen shell command: {}", command); return exitCode; } diff --git a/src/modules/module/modloader.cpp b/src/modules/module/modloader.cpp index aa3e1adf..804d1e7f 100644 --- a/src/modules/module/modloader.cpp +++ b/src/modules/module/modloader.cpp @@ -72,7 +72,7 @@ namespace Lithium std::ifstream file_stream(file_path); if (!file_stream.is_open()) { - DLOG_F(ERROR, "Failed to open config file {}", file_path); + LOG_F(ERROR, "Failed to open config file {}", file_path); return {{"error", "Failed to open config file"}}; } @@ -85,7 +85,7 @@ namespace Lithium } catch (const std::exception &e) { - DLOG_F(ERROR, "Failed to read config file {}: {}", file_path, e.what()); + LOG_F(ERROR, "Failed to read config file {}: {}", file_path, e.what()); return {{"error", "Failed to read config file"}}; } } @@ -94,7 +94,7 @@ namespace Lithium { if (dir_name == "") { - DLOG_F(ERROR, "DIR name should not be null"); + LOG_F(ERROR, "DIR name should not be null"); return {{"error", "dir name should not be null"}}; } // Define the modules directory path @@ -111,7 +111,7 @@ namespace Lithium } catch (const std::exception &e) { - DLOG_F(ERROR, "Failed to create modules directory: {}", e.what()); + LOG_F(ERROR, "Failed to create modules directory: {}", e.what()); return {{"error", "Failed to create modules directory"}}; } @@ -149,7 +149,7 @@ namespace Lithium } catch (const std::exception &e) { - DLOG_F(ERROR, "Failed to iterate modules directory: {}", e.what()); + LOG_F(ERROR, "Failed to iterate modules directory: {}", e.what()); return {{"error", "Failed to iterate modules directory"}}; } if (config.empty()) @@ -167,13 +167,13 @@ namespace Lithium { m_ThreadManager->addThread([this]() { if(!LoadOnInit("modules")){ - DLOG_F(ERROR,"Failed to load modules on init"); + LOG_F(ERROR,"Failed to load modules on init"); } }, "LoadOnInit"); } else { - DLOG_F(ERROR, "Failed to initialize thread manager in module loader"); + LOG_F(ERROR, "Failed to initialize thread manager in module loader"); } } @@ -185,13 +185,13 @@ namespace Lithium { m_ThreadManager->addThread([this]() { if(!LoadOnInit("modules")){ - DLOG_F(ERROR,"Failed to load modules on init"); + LOG_F(ERROR,"Failed to load modules on init"); } }, "LoadOnInit"); } else { - DLOG_F(ERROR, "Failed to initialize thread manager in module loader"); + LOG_F(ERROR, "Failed to initialize thread manager in module loader"); } } @@ -203,13 +203,13 @@ namespace Lithium { m_ThreadManager->addThread([this, dir_name]() { if(!LoadOnInit(dir_name)){ - DLOG_F(ERROR,"Failed to load modules on init"); + LOG_F(ERROR,"Failed to load modules on init"); } }, "LoadOnInit"); } else { - DLOG_F(ERROR, "Failed to initialize thread manager in module loader"); + LOG_F(ERROR, "Failed to initialize thread manager in module loader"); } } @@ -221,13 +221,13 @@ namespace Lithium { m_ThreadManager->addThread([this, dir_name]() { if(!LoadOnInit(dir_name)){ - DLOG_F(ERROR,"Failed to load modules on init"); + LOG_F(ERROR,"Failed to load modules on init"); } }, "LoadOnInit"); } else { - DLOG_F(ERROR, "Failed to initialize thread manager in module loader"); + LOG_F(ERROR, "Failed to initialize thread manager in module loader"); } } @@ -265,7 +265,7 @@ namespace Lithium { if (dir_name.empty()) { - DLOG_F(ERROR, "Directory name is empty"); + LOG_F(ERROR, "Directory name is empty"); return false; } const json dir_info = iterator_modules_dir(dir_name); @@ -295,7 +295,7 @@ namespace Lithium // Check if the library file exists if (!std::filesystem::exists(path)) { - DLOG_F(ERROR, "Library {} does not exist", path); + LOG_F(ERROR, "Library {} does not exist", path); return false; } @@ -303,7 +303,7 @@ namespace Lithium void *handle = LOAD_LIBRARY(path.c_str()); if (!handle) { - DLOG_F(ERROR, "Failed to load library {}: {}", path, LOAD_ERROR()); + LOG_F(ERROR, "Failed to load library {}: {}", path, LOAD_ERROR()); return false; } @@ -342,7 +342,7 @@ namespace Lithium } catch (const std::exception &e) { - DLOG_F(ERROR, "Failed to load library {}: {}", path, e.what()); + LOG_F(ERROR, "Failed to load library {}: {}", path, e.what()); return false; } } @@ -355,13 +355,13 @@ namespace Lithium auto it = handles_.find(filename); if (it == handles_.end()) { - DLOG_F(ERROR, "Module {} is not loaded", filename); + LOG_F(ERROR, "Module {} is not loaded", filename); return false; } if (!it->second) { - DLOG_F(ERROR, "Module {}'s handle is null", filename); + LOG_F(ERROR, "Module {}'s handle is null", filename); return false; } @@ -375,13 +375,13 @@ namespace Lithium } else { - DLOG_F(ERROR, "Failed to unload module {}", filename); + LOG_F(ERROR, "Failed to unload module {}", filename); return false; } } catch (const std::exception &e) { - DLOG_F(ERROR, "{}", e.what()); + LOG_F(ERROR, "{}", e.what()); return false; } } @@ -391,7 +391,7 @@ namespace Lithium void *handle = LOAD_LIBRARY(name.c_str()); if (handle == nullptr) { - DLOG_F(ERROR, "Module {} does not exist.", name); + LOG_F(ERROR, "Module {} does not exist.", name); return false; } DLOG_F(INFO, "Module {} is existing.", name); @@ -436,7 +436,7 @@ namespace Lithium } else { - DLOG_F(ERROR, "Enabled file not found for module {}", module_name); + LOG_F(ERROR, "Enabled file not found for module {}", module_name); return false; } } @@ -452,7 +452,7 @@ namespace Lithium std::string module_path = GetModulePath(module_name); if (module_path.empty()) { - DLOG_F(ERROR, "Module path not found for module {}", module_name); + LOG_F(ERROR, "Module path not found for module {}", module_name); return false; } std::string disabled_file = module_path + ".disabled"; @@ -464,7 +464,7 @@ namespace Lithium } else { - DLOG_F(ERROR, "Failed to disable module {}", module_name); + LOG_F(ERROR, "Failed to disable module {}", module_name); return false; } } diff --git a/src/modules/module/modloader.hpp b/src/modules/module/modloader.hpp index 43f44906..89981338 100644 --- a/src/modules/module/modloader.hpp +++ b/src/modules/module/modloader.hpp @@ -227,7 +227,7 @@ namespace Lithium auto handle_it = handles_.find(module_name); if (handle_it == handles_.end()) { - DLOG_F(ERROR, "Failed to find module %s", module_name.c_str()); + LOG_F(ERROR, "Failed to find module %s", module_name.c_str()); return nullptr; } @@ -235,7 +235,7 @@ namespace Lithium if (!func_ptr) { - DLOG_F(ERROR, "Failed to get symbol %s from module %s: %s", function_name.c_str(), module_name.c_str(), dlerror()); + LOG_F(ERROR, "Failed to get symbol %s from module %s: %s", function_name.c_str(), module_name.c_str(), dlerror()); return nullptr; } @@ -258,14 +258,14 @@ namespace Lithium auto handle_it = handles_.find(module_name); if (handle_it == handles_.end()) { - DLOG_F(ERROR, "Failed to find module %s", module_name.c_str()); + LOG_F(ERROR, "Failed to find module %s", module_name.c_str()); return nullptr; } auto get_instance_func = GetFunction (*)(const json &)>(module_name, symbol_name); if (!get_instance_func) { - DLOG_F(ERROR, "Failed to get symbol %s from module %s: %s", symbol_name.c_str(), module_name.c_str(), dlerror()); + LOG_F(ERROR, "Failed to get symbol %s from module %s: %s", symbol_name.c_str(), module_name.c_str(), dlerror()); return nullptr; } diff --git a/src/modules/plugin/exe_plugin.cpp b/src/modules/plugin/exe_plugin.cpp index 8663842d..1332484e 100644 --- a/src/modules/plugin/exe_plugin.cpp +++ b/src/modules/plugin/exe_plugin.cpp @@ -56,15 +56,15 @@ void ExecutablePlugin::Execute(const std::vector &args) const { if (!m_ProcessManager->createProcess(command, GetPath())) { - DLOG_F(ERROR, "Failed to run executable plugin : %s", command.c_str()); + LOG_F(ERROR, "Failed to run executable plugin : %s", command.c_str()); } else { - DLOG_F(ERROR, "Started %s successfully", command.c_str()); + LOG_F(ERROR, "Started %s successfully", command.c_str()); } } else { - DLOG_F(ERROR, "Process manager is not initialized"); + LOG_F(ERROR, "Process manager is not initialized"); } } diff --git a/src/modules/plugin/plugin_manager.cpp b/src/modules/plugin/plugin_manager.cpp index ef474db0..6e795f64 100644 --- a/src/modules/plugin/plugin_manager.cpp +++ b/src/modules/plugin/plugin_manager.cpp @@ -56,7 +56,7 @@ namespace Lithium if (plugins_.count(pluginName)) { - DLOG_F(ERROR, "Error: Plugin '%s' already exists.", pluginName.c_str()); + LOG_F(ERROR, "Error: Plugin '%s' already exists.", pluginName.c_str()); throw std::runtime_error("Error: Plugin '" + pluginName + "' already exists."); } @@ -72,7 +72,7 @@ namespace Lithium } else { - DLOG_F(ERROR, "Error: Unknown plugin type '%s'.", type.c_str()); + LOG_F(ERROR, "Error: Unknown plugin type '%s'.", type.c_str()); throw std::runtime_error("Error: Unknown plugin type '" + type + "'."); } @@ -93,7 +93,7 @@ namespace Lithium } else { - DLOG_F(ERROR, "Error: Plugin '%s' does not exist.", pluginName.c_str()); + LOG_F(ERROR, "Error: Plugin '%s' does not exist.", pluginName.c_str()); throw std::runtime_error("Error: Plugin '" + pluginName + "' does not exist."); } } @@ -117,7 +117,7 @@ namespace Lithium } else { - DLOG_F(ERROR, "Error: Plugin '%s' does not exist.", pluginName.c_str()); + LOG_F(ERROR, "Error: Plugin '%s' does not exist.", pluginName.c_str()); throw std::runtime_error("Error: Plugin '" + pluginName + "' does not exist."); } } @@ -157,7 +157,7 @@ namespace Lithium } else { - DLOG_F(ERROR, "Error: Plugin '%s' does not exist.", pluginName.c_str()); + LOG_F(ERROR, "Error: Plugin '%s' does not exist.", pluginName.c_str()); throw std::runtime_error("Error: Plugin '" + pluginName + "' does not exist."); } } diff --git a/src/modules/plugin/script_plugin.cpp b/src/modules/plugin/script_plugin.cpp index 3c09f313..8272dbbc 100644 --- a/src/modules/plugin/script_plugin.cpp +++ b/src/modules/plugin/script_plugin.cpp @@ -53,15 +53,15 @@ void ScriptPlugin::Execute(const std::vector &args) const { if (!m_ProcessManager->runScript(script, GetPath())) { - DLOG_F(ERROR, "Failed to run executable plugin : %s", script.c_str()); + LOG_F(ERROR, "Failed to run executable plugin : %s", script.c_str()); } else { - DLOG_F(ERROR, "Started %s successfully", script.c_str()); + LOG_F(ERROR, "Started %s successfully", script.c_str()); } } else { - DLOG_F(ERROR, "Process manager is not initialized"); + LOG_F(ERROR, "Process manager is not initialized"); } } diff --git a/src/modules/script/script_manager.cpp b/src/modules/script/script_manager.cpp index 1bb98065..55552951 100644 --- a/src/modules/script/script_manager.cpp +++ b/src/modules/script/script_manager.cpp @@ -66,7 +66,7 @@ namespace Lithium { } - std::shared_ptr ChaiScriptManager::createShared(std::shared_ptr messageBus) + std::shared_ptr ChaiScriptManager::createShared(std::shared_ptr messageBus) { return std::make_shared(messageBus); } @@ -172,7 +172,7 @@ namespace Lithium } else { - DLOG_F(ERROR, "Failed to open script file: {}", filename); + LOG_F(ERROR, "Failed to open script file: {}", filename); return false; } return true; @@ -186,7 +186,7 @@ namespace Lithium } catch (chaiscript::exception::eval_error &e) { - DLOG_F(ERROR, "Failed to eval {} : {}", e.filename, e.what()); + LOG_F(ERROR, "Failed to eval {} : {}", e.filename, e.what()); return false; }; return true; @@ -200,7 +200,7 @@ namespace Lithium } catch (chaiscript::exception::eval_error &e) { - DLOG_F(ERROR, "Failed to run {} : {}", e.filename, e.what()); + LOG_F(ERROR, "Failed to run {} : {}", e.filename, e.what()); return false; } return true; @@ -216,7 +216,7 @@ namespace Lithium } catch (chaiscript::exception::eval_error &e) { - DLOG_F(ERROR, "Failed to run: {}", e.what()); + LOG_F(ERROR, "Failed to run: {}", e.what()); return false; } } diff --git a/src/modules/script/script_manager.hpp b/src/modules/script/script_manager.hpp index 8ef22312..fd6de34b 100644 --- a/src/modules/script/script_manager.hpp +++ b/src/modules/script/script_manager.hpp @@ -41,10 +41,10 @@ namespace chaiscript class ChaiScript; } -class MessageBus; - namespace Lithium { + class MessageBus; + class ChaiScriptManager { public: diff --git a/src/modules/server/message_bus.hpp b/src/modules/server/message_bus.hpp index 777ed01f..af9d5a75 100644 --- a/src/modules/server/message_bus.hpp +++ b/src/modules/server/message_bus.hpp @@ -33,14 +33,8 @@ Description: Main Message Bus #define HAS_MESSAGE_BUS -#include #include #include -#if ENABLE_FASTHASH -#include "emhash/hash_table8.hpp" -#else -#include -#endif #include #include #include @@ -51,221 +45,230 @@ Description: Main Message Bus #include #include +#if ENABLE_FASTHASH +#include "emhash/hash_table8.hpp" +#else +#include +#endif + #include "loguru/loguru.hpp" -class MessageBus +namespace Lithium { -public: - template - void Subscribe(const std::string &topic, std::function callback, int priority = 0, const std::string &namespace_ = "") + class MessageBus { - std::string fullTopic = namespace_.empty() ? topic : (namespace_ + "::" + topic); - - subscribersLock_.lock(); - subscribers_[fullTopic].push_back({priority, std::any(callback)}); - std::sort(subscribers_[fullTopic].begin(), subscribers_[fullTopic].end(), - [](const auto &a, const auto &b) - { - return a.first > b.first; - }); - subscribersLock_.unlock(); - - DLOG_F(INFO, "Subscribed to topic: %s", fullTopic.c_str()); - } - - template - void SubscribeToNamespace(const std::string &namespaceName, std::function callback, int priority = 0) - { - std::string topic = namespaceName + ".*"; - Subscribe(topic, callback, priority, namespaceName); - } + public: + template + void Subscribe(const std::string &topic, std::function callback, int priority = 0, const std::string &namespace_ = "") + { + std::string fullTopic = namespace_.empty() ? topic : (namespace_ + "::" + topic); - template - void Unsubscribe(const std::string &topic, std::function callback, const std::string &namespace_ = "") - { - std::string fullTopic = namespace_.empty() ? topic : (namespace_ + "::" + topic); + subscribersLock_.lock(); + subscribers_[fullTopic].push_back({priority, std::any(callback)}); + std::sort(subscribers_[fullTopic].begin(), subscribers_[fullTopic].end(), + [](const auto &a, const auto &b) + { + return a.first > b.first; + }); + subscribersLock_.unlock(); + + DLOG_F(INFO, "Subscribed to topic: %s", fullTopic.c_str()); + } - subscribersLock_.lock(); - auto it = subscribers_.find(fullTopic); - if (it != subscribers_.end()) + template + void SubscribeToNamespace(const std::string &namespaceName, std::function callback, int priority = 0) { - auto &topicSubscribers = it->second; - topicSubscribers.erase( - std::remove_if( - topicSubscribers.begin(), topicSubscribers.end(), - [&](const auto &subscriber) - { - return subscriber.second.type() == typeid(callback); - }), - topicSubscribers.end()); + std::string topic = namespaceName + ".*"; + Subscribe(topic, callback, priority, namespaceName); + } - DLOG_F(INFO, "Unsubscribed from topic: %s", fullTopic.c_str()); + template + void Unsubscribe(const std::string &topic, std::function callback, const std::string &namespace_ = "") + { + std::string fullTopic = namespace_.empty() ? topic : (namespace_ + "::" + topic); + + subscribersLock_.lock(); + auto it = subscribers_.find(fullTopic); + if (it != subscribers_.end()) + { + auto &topicSubscribers = it->second; + topicSubscribers.erase( + std::remove_if( + topicSubscribers.begin(), topicSubscribers.end(), + [&](const auto &subscriber) + { + return subscriber.second.type() == typeid(callback); + }), + topicSubscribers.end()); + + DLOG_F(INFO, "Unsubscribed from topic: %s", fullTopic.c_str()); + } + subscribersLock_.unlock(); } - subscribersLock_.unlock(); - } - template - void Publish(const std::string &topic, const T &message, const std::string &namespace_ = "") - { - std::string fullTopic = namespace_.empty() ? topic : (namespace_ + "::" + topic); + template + void Publish(const std::string &topic, const T &message, const std::string &namespace_ = "") + { + std::string fullTopic = namespace_.empty() ? topic : (namespace_ + "::" + topic); - messageQueueLock_.lock(); - messageQueue_.push({fullTopic, std::any(message)}); - messageQueueLock_.unlock(); - messageAvailableFlag_.notify_one(); + messageQueueLock_.lock(); + messageQueue_.push({fullTopic, std::any(message)}); + messageQueueLock_.unlock(); + messageAvailableFlag_.notify_one(); - DLOG_F(INFO, "Published message to topic: %s", fullTopic.c_str()); - } + DLOG_F(INFO, "Published message to topic: %s", fullTopic.c_str()); + } - template - void GlobalSubscribe(std::function callback) - { - globalSubscribersLock_.lock(); - globalSubscribers_.push_back({std::any(callback)}); - globalSubscribersLock_.unlock(); - } + template + void GlobalSubscribe(std::function callback) + { + globalSubscribersLock_.lock(); + globalSubscribers_.push_back({std::any(callback)}); + globalSubscribersLock_.unlock(); + } - template - void GlobalUnsubscribe(std::function callback) - { - globalSubscribersLock_.lock(); - globalSubscribers_.erase( - std::remove_if( - globalSubscribers_.begin(), globalSubscribers_.end(), - [&](const auto &subscriber) - { - return subscriber.type() == typeid(callback); - }), - globalSubscribers_.end()); - globalSubscribersLock_.unlock(); - } - - template - void StartProcessingThread() - { - std::type_index typeIndex = typeid(T); -#if __cplusplus >= 202002L - processingThreads_.emplace(typeIndex, std::jthread([&]() - { -#else - processingThreads_.emplace(typeIndex, std::thread([&]() - { -#endif - while (isRunning_.load()) { - std::pair message; - bool hasMessage = false; + template + void GlobalUnsubscribe(std::function callback) + { + globalSubscribersLock_.lock(); + globalSubscribers_.erase( + std::remove_if( + globalSubscribers_.begin(), globalSubscribers_.end(), + [&](const auto &subscriber) + { + return subscriber.type() == typeid(callback); + }), + globalSubscribers_.end()); + globalSubscribersLock_.unlock(); + } + template + void StartProcessingThread() + { + std::type_index typeIndex = typeid(T); + #if __cplusplus >= 202002L + processingThreads_.emplace(typeIndex, std::jthread([&]() + { + #else + processingThreads_.emplace(typeIndex, std::thread([&]() + { + #endif while (isRunning_.load()) { - messageQueueLock_.lock(); - if (!messageQueue_.empty()) { - message = std::move(messageQueue_.front()); - messageQueue_.pop(); - hasMessage = true; - } - messageQueueLock_.unlock(); + std::pair message; + bool hasMessage = false; + + while (isRunning_.load()) { + messageQueueLock_.lock(); + if (!messageQueue_.empty()) { + message = std::move(messageQueue_.front()); + messageQueue_.pop(); + hasMessage = true; + } + messageQueueLock_.unlock(); - if (hasMessage) { - break; - } + if (hasMessage) { + break; + } - std::unique_lock lock(waitingMutex_); - messageAvailableFlag_.wait(lock); - } + std::unique_lock lock(waitingMutex_); + messageAvailableFlag_.wait(lock); + } - if (hasMessage) { - const std::string& topic = message.first; - const std::any& data = message.second; + if (hasMessage) { + const std::string& topic = message.first; + const std::any& data = message.second; + + subscribersLock_.lock(); + auto it = subscribers_.find(topic); + if (it != subscribers_.end()) { + try { + for (const auto& subscriber : it->second) { + if (subscriber.second.type() == typeid(std::function)) { + std::any_cast>(subscriber.second)(std::any_cast(data)); + } + } + } catch (const std::bad_any_cast& e) { + LOG_F(ERROR, "Message type mismatch: %s", e.what()); + } catch (...) { + LOG_F(ERROR, "Unknown error occurred during message processing"); + } + } + subscribersLock_.unlock(); - subscribersLock_.lock(); - auto it = subscribers_.find(topic); - if (it != subscribers_.end()) { + globalSubscribersLock_.lock(); try { - for (const auto& subscriber : it->second) { - if (subscriber.second.type() == typeid(std::function)) { - std::any_cast>(subscriber.second)(std::any_cast(data)); + for (const auto& subscriber : globalSubscribers_) { + if (subscriber.type() == typeid(std::function)) { + std::any_cast>(subscriber)(std::any_cast(data)); } } } catch (const std::bad_any_cast& e) { - DLOG_F(ERROR, "Message type mismatch: %s", e.what()); + LOG_F(ERROR, "Global message type mismatch: %s", e.what()); } catch (...) { - DLOG_F(ERROR, "Unknown error occurred during message processing"); + LOG_F(ERROR, "Unknown error occurred during global message processing"); } - } - subscribersLock_.unlock(); + globalSubscribersLock_.unlock(); - globalSubscribersLock_.lock(); - try { - for (const auto& subscriber : globalSubscribers_) { - if (subscriber.type() == typeid(std::function)) { - std::any_cast>(subscriber)(std::any_cast(data)); - } - } - } catch (const std::bad_any_cast& e) { - DLOG_F(ERROR, "Global message type mismatch: %s", e.what()); - } catch (...) { - DLOG_F(ERROR, "Unknown error occurred during global message processing"); + DLOG_F(INFO, "Processed message on topic: %s", topic.c_str()); } - globalSubscribersLock_.unlock(); - - DLOG_F(INFO, "Processed message on topic: %s", topic.c_str()); - } - } })); - } + } })); + } - template - void StopProcessingThread() - { - std::type_index typeIndex = typeid(T); - auto it = processingThreads_.find(typeIndex); - if (it != processingThreads_.end()) + template + void StopProcessingThread() { -#if __cplusplus >= 202002L - it->second.request_stop(); -#endif - it->second.join(); - processingThreads_.erase(it); - DLOG_F(INFO, "Processing thread for type %s stopped", typeid(T).name()); + std::type_index typeIndex = typeid(T); + auto it = processingThreads_.find(typeIndex); + if (it != processingThreads_.end()) + { + #if __cplusplus >= 202002L + it->second.request_stop(); + #endif + it->second.join(); + processingThreads_.erase(it); + DLOG_F(INFO, "Processing thread for type %s stopped", typeid(T).name()); + } } - } - void StopAllProcessingThreads() - { - isRunning_.store(false); - messageAvailableFlag_.notify_one(); - for (auto &thread : processingThreads_) + void StopAllProcessingThreads() { -#if __cplusplus >= 202002L - thread.second.request_stop(); -#endif - thread.second.join(); + isRunning_.store(false); + messageAvailableFlag_.notify_one(); + for (auto &thread : processingThreads_) + { + #if __cplusplus >= 202002L + thread.second.request_stop(); + #endif + thread.second.join(); + } + processingThreads_.clear(); + DLOG_F(INFO, "All processing threads stopped"); } - processingThreads_.clear(); - DLOG_F(INFO, "All processing threads stopped"); - } - -private: - std::unordered_map>> subscribers_; - std::mutex subscribersLock_; - std::queue> messageQueue_; - std::mutex messageQueueLock_; - std::condition_variable messageAvailableFlag_; - std::mutex waitingMutex_; -#if __cplusplus >= 202002L -#if ENABLE_FASTHASH - emhash8::HashMap processingThreads_; -#else - std::unordered_map processingThreads_; -#endif -#else -#if ENABLE_FASTHASH - emhash8::HashMap processingThreads_; -#else - std::unordered_map processingThreads_; -#endif - -#endif - std::atomic isRunning_{true}; - std::vector globalSubscribers_; - std::mutex globalSubscribersLock_; -}; \ No newline at end of file + private: + std::unordered_map>> subscribers_; + std::mutex subscribersLock_; + std::queue> messageQueue_; + std::mutex messageQueueLock_; + std::condition_variable messageAvailableFlag_; + std::mutex waitingMutex_; + #if __cplusplus >= 202002L + #if ENABLE_FASTHASH + emhash8::HashMap processingThreads_; + #else + std::unordered_map processingThreads_; + #endif + #else + #if ENABLE_FASTHASH + emhash8::HashMap processingThreads_; + #else + std::unordered_map processingThreads_; + #endif + + #endif + std::atomic isRunning_{true}; + + std::vector globalSubscribers_; + std::mutex globalSubscribersLock_; + }; +} diff --git a/src/modules/system/pid.cpp b/src/modules/system/pid.cpp index 54455f8d..d1f89a7a 100644 --- a/src/modules/system/pid.cpp +++ b/src/modules/system/pid.cpp @@ -91,7 +91,7 @@ void PIDWatcher::watch() HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); if (snapshot == INVALID_HANDLE_VALUE) { - DLOG_F(ERROR, _("CreateToolhelp32Snapshot failed.")); + LOG_F(ERROR, _("CreateToolhelp32Snapshot failed.")); return; } @@ -130,7 +130,7 @@ void PIDWatcher::watch() } else { - DLOG_F(ERROR, _("GetExitCodeProcess failed.")); + LOG_F(ERROR, _("GetExitCodeProcess failed.")); } CloseHandle(process); stop(); @@ -140,7 +140,7 @@ void PIDWatcher::watch() } else { - DLOG_F(ERROR, _("OpenProcess failed.")); + LOG_F(ERROR, _("OpenProcess failed.")); } break; diff --git a/src/modules/system/pidw.cpp b/src/modules/system/pidw.cpp index 914aeef6..dd64ae47 100644 --- a/src/modules/system/pidw.cpp +++ b/src/modules/system/pidw.cpp @@ -145,7 +145,7 @@ void PidWWatcher::MonitorThread() DWORD aProcesses[1024], cbNeeded, cProcesses; if (!EnumProcesses(aProcesses, sizeof(aProcesses), &cbNeeded)) { - DLOG_F(ERROR, "Failed to enumerate processes!"); + LOG_F(ERROR, "Failed to enumerate processes!"); return; } @@ -179,7 +179,7 @@ void PidWWatcher::MonitorThread() if (pid_ == 0) { - DLOG_F(ERROR, "Failed to find process!"); + LOG_F(ERROR, "Failed to find process!"); return; } #else @@ -187,7 +187,7 @@ void PidWWatcher::MonitorThread() std::ifstream file("/proc/self/stat"); if (!file) { - DLOG_F(ERROR, "Failed to read /proc/self/stat"); + LOG_F(ERROR, "Failed to read /proc/self/stat"); return; } @@ -201,7 +201,7 @@ void PidWWatcher::MonitorThread() DIR *procDir = opendir("/proc"); if (procDir == nullptr) { - DLOG_F(ERROR, "Failed to open /proc"); + LOG_F(ERROR, "Failed to open /proc"); return; } @@ -247,7 +247,7 @@ void PidWWatcher::MonitorThread() if (pid_ == 0) { - DLOG_F(ERROR, "Failed to find process!"); + LOG_F(ERROR, "Failed to find process!"); return; } #endif diff --git a/src/modules/system/process.cpp b/src/modules/system/process.cpp index 87fc3a01..261a4e1a 100644 --- a/src/modules/system/process.cpp +++ b/src/modules/system/process.cpp @@ -72,7 +72,7 @@ namespace Lithium::Process std::string cmd = "powershell.exe -Command \"" + command + "\""; if (!CreateProcess(NULL, (LPSTR)cmd.c_str(), NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi)) { - DLOG_F(ERROR, _("Failed to create PowerShell process")); + LOG_F(ERROR, _("Failed to create PowerShell process")); return false; } pid = pi.dwProcessId; @@ -95,7 +95,7 @@ namespace Lithium::Process else if (pid < 0) { // Error handling - DLOG_F(ERROR, _("Failed to create process")); + LOG_F(ERROR, _("Failed to create process")); return false; } #endif @@ -119,7 +119,7 @@ namespace Lithium::Process PROCESS_INFORMATION pi{}; if (!CreateProcess(NULL, (LPSTR)cmd.c_str(), NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi)) { - DLOG_F(ERROR, _("Failed to create process")); + LOG_F(ERROR, _("Failed to create process")); return false; } pid = pi.dwProcessId; @@ -140,7 +140,7 @@ namespace Lithium::Process else if (pid < 0) { // Error handling - DLOG_F(ERROR, _("Failed to create process")); + LOG_F(ERROR, _("Failed to create process")); return false; } #endif @@ -171,7 +171,7 @@ namespace Lithium::Process } else { - DLOG_F(ERROR, _("Failed to terminate process")); + LOG_F(ERROR, _("Failed to terminate process")); return false; } #else @@ -187,7 +187,7 @@ namespace Lithium::Process } else { - DLOG_F(ERROR, _("Process not found")); + LOG_F(ERROR, _("Process not found")); return false; } return true; @@ -202,7 +202,7 @@ namespace Lithium::Process { return terminateProcess(it->pid, signal); } - DLOG_F(ERROR, _("Process not found by name: {}"), name); + LOG_F(ERROR, _("Process not found by name: {}"), name); return false; } @@ -243,7 +243,7 @@ namespace Lithium::Process } else { - DLOG_F(ERROR, _("Process not found")); + LOG_F(ERROR, _("Process not found")); return std::vector(); } } @@ -262,7 +262,7 @@ namespace Lithium::Process } else { - DLOG_F(ERROR, _("Failed to wait for process completion")); + LOG_F(ERROR, _("Failed to wait for process completion")); } #else int status; @@ -284,7 +284,7 @@ namespace Lithium::Process HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); if (snapshot == INVALID_HANDLE_VALUE) { - DLOG_F(ERROR, _("Failed to create process snapshot")); + LOG_F(ERROR, _("Failed to create process snapshot")); return processes; } @@ -325,7 +325,7 @@ namespace Lithium::Process DIR *procDir = opendir("/proc"); if (!procDir) { - DLOG_F(ERROR, _("Failed to open /proc directory")); + LOG_F(ERROR, _("Failed to open /proc directory")); return processes; } @@ -354,7 +354,7 @@ namespace Lithium::Process char pathbuf[PROC_PIDPATHINFO_MAXSIZE]; if (proc_pidpath(pid, pathbuf, sizeof(pathbuf)) <= 0) { - DLOG_F(ERROR, _("Failed to get process path")); + LOG_F(ERROR, _("Failed to get process path")); return ""; } std::string path(pathbuf); @@ -375,20 +375,20 @@ namespace Lithium::Process if (sysctl(mib, 4, nullptr, &length, nullptr, 0) == -1) { - DLOG_F(ERROR, _("Failed to get process info length")); + LOG_F(ERROR, _("Failed to get process info length")); return processes; } struct kinfo_proc *procBuf = (struct kinfo_proc *)malloc(length); if (!procBuf) { - DLOG_F(ERROR, _("Failed to allocate memory")); + LOG_F(ERROR, _("Failed to allocate memory")); return processes; } if (sysctl(mib, 4, procBuf, &length, nullptr, 0) == -1) { - DLOG_F(ERROR, _("Failed to get process info")); + LOG_F(ERROR, _("Failed to get process info")); free(procBuf); return processes; } diff --git a/src/modules/task/task_generator.cpp b/src/modules/task/task_generator.cpp index 01e96900..67347222 100644 --- a/src/modules/task/task_generator.cpp +++ b/src/modules/task/task_generator.cpp @@ -53,7 +53,7 @@ namespace Lithium { if (!fs::exists(macroFileName)) { - DLOG_F(ERROR, "Macro file not found : {}", macroFileName); + LOG_F(ERROR, "Macro file not found : {}", macroFileName); return false; } try @@ -64,13 +64,13 @@ namespace Lithium } catch (const std::exception &e) { - DLOG_F(ERROR, "Failed to parse file {} , error : {}", macroFileName, e.what()); + LOG_F(ERROR, "Failed to parse file {} , error : {}", macroFileName, e.what()); return false; } } catch (const std::exception &e) { - DLOG_F(ERROR, "Error while loading macro file: {}", e.what()); + LOG_F(ERROR, "Error while loading macro file: {}", e.what()); return false; } @@ -83,7 +83,7 @@ namespace Lithium { if (!fs::is_directory(folderPath)) { - DLOG_F(ERROR, "Invalid folder path: {}", folderPath); + LOG_F(ERROR, "Invalid folder path: {}", folderPath); return false; } @@ -96,7 +96,7 @@ namespace Lithium std::ifstream file(filePath); if (!file) { - DLOG_F(ERROR, "Failed to open macro file: {}", filePath); + LOG_F(ERROR, "Failed to open macro file: {}", filePath.string()); continue; } @@ -107,7 +107,7 @@ namespace Lithium } catch (const std::exception &e) { - DLOG_F(ERROR, "Failed to parse macro file: {}, error: {}", filePath, e.what()); + LOG_F(ERROR, "Failed to parse macro file: {}, error: {}", filePath.string(), e.what()); continue; } @@ -123,7 +123,7 @@ namespace Lithium } else { - DLOG_F(ERROR, "Invalid macro file format: {}", filePath); + LOG_F(ERROR, "Invalid macro file format: {}", filePath.string()); continue; } } @@ -131,7 +131,7 @@ namespace Lithium } catch (const std::exception &e) { - DLOG_F(ERROR, "Error while loading macros from folder: {}", e.what()); + LOG_F(ERROR, "Error while loading macros from folder: {}", e.what()); return false; } @@ -187,14 +187,14 @@ namespace Lithium std::ifstream file(jsonFileName); if (!file) { - DLOG_F(ERROR, "Failed to open JSON file: {}", jsonFileName); + LOG_F(ERROR, "Failed to open JSON file: {}", jsonFileName); return false; } file >> jsonTasks; } catch (const std::exception &e) { - DLOG_F(ERROR, "Error while parsing JSON file: {}", e.what()); + LOG_F(ERROR, "Error while parsing JSON file: {}", e.what()); return false; } @@ -208,14 +208,14 @@ namespace Lithium std::ofstream jsonFile(jsonFileName); if (!jsonFile) { - DLOG_F(ERROR, "Failed to open JSON file: {}", jsonFileName); + LOG_F(ERROR, "Failed to open JSON file: {}", jsonFileName); return; } jsonFile << jsonTasks.dump(4); // 使用四个空格缩进 } catch (const std::exception &e) { - DLOG_F(ERROR, "Error while saving JSON file: {}", e.what()); + LOG_F(ERROR, "Error while saving JSON file: {}", e.what()); return; } } diff --git a/src/modules/task/task_manager.cpp b/src/modules/task/task_manager.cpp index d6f24997..76c0fbac 100644 --- a/src/modules/task/task_manager.cpp +++ b/src/modules/task/task_manager.cpp @@ -43,7 +43,7 @@ namespace Lithium::Task { if (!task) { - DLOG_F(ERROR, "Invalid task!"); + LOG_F(ERROR, "Invalid task!"); return false; } m_TaskList.push_back(task); @@ -56,13 +56,13 @@ namespace Lithium::Task { if (!task) { - DLOG_F(ERROR, "Error: Invalid task!"); + LOG_F(ERROR, "Error: Invalid task!"); return false; } if (position < 0 || position >= m_TaskList.size()) { - DLOG_F(ERROR, "Error: Invalid position!"); + LOG_F(ERROR, "Error: Invalid position!"); return false; } @@ -93,12 +93,12 @@ namespace Lithium::Task } catch (const std::exception &ex) { - DLOG_F(ERROR, "Error: Failed to execute task {} - {}", task->get_name(), ex.what()); + LOG_F(ERROR, "Error: Failed to execute task {} - {}", task->get_name(), ex.what()); ++it; } catch (...) { - DLOG_F(ERROR, "Error: Failed to execute task {}", task->get_name()); + LOG_F(ERROR, "Error: Failed to execute task {}", task->get_name()); ++it; } } @@ -128,22 +128,22 @@ namespace Lithium::Task } else { - DLOG_F(ERROR, "Error: Failed to execute task {}", it->second->get_name()); + LOG_F(ERROR, "Error: Failed to execute task {}", it->second->get_name()); } return true; } catch (const std::exception &ex) { - DLOG_F(ERROR, "Error: Failed to execute task {} - {}", it->second->get_name(), ex.what()); + LOG_F(ERROR, "Error: Failed to execute task {} - {}", it->second->get_name(), ex.what()); } catch (...) { - DLOG_F(ERROR, "Error: Failed to execute task {}", it->second->get_name()); + LOG_F(ERROR, "Error: Failed to execute task {}", it->second->get_name()); } } else { - DLOG_F(ERROR, "Error: Task not found or invalid!"); + LOG_F(ERROR, "Error: Task not found or invalid!"); } return false; } @@ -152,13 +152,13 @@ namespace Lithium::Task { if (!task) { - DLOG_F(ERROR, "Error: Invalid task!"); + LOG_F(ERROR, "Error: Invalid task!"); return false; } if (index < 0 || index >= m_TaskList.size()) { - DLOG_F(ERROR, "Error: Invalid index!"); + LOG_F(ERROR, "Error: Invalid index!"); return false; } @@ -183,7 +183,7 @@ namespace Lithium::Task { if (index < 0 || index >= m_TaskList.size()) { - DLOG_F(ERROR, "Error: Invalid index!"); + LOG_F(ERROR, "Error: Invalid index!"); return false; } @@ -205,7 +205,7 @@ namespace Lithium::Task DLOG_F(INFO, "Task deleted: {}", task->get_name()); return true; } - DLOG_F(ERROR, "Error: Task not found!"); + LOG_F(ERROR, "Error: Task not found!"); return false; } @@ -247,7 +247,7 @@ namespace Lithium::Task std::ofstream outputFile(m_FileName); if (!outputFile.is_open()) { - DLOG_F(ERROR, "Error: Failed to open file for writing!"); + LOG_F(ERROR, "Error: Failed to open file for writing!"); return false; } diff --git a/src/modules/thread/thread.cpp b/src/modules/thread/thread.cpp index 0ae475cc..61bdfde2 100644 --- a/src/modules/thread/thread.cpp +++ b/src/modules/thread/thread.cpp @@ -60,7 +60,7 @@ namespace Lithium::Thread } catch (const std::exception &e) { - DLOG_F(ERROR, _("Failed to destroy ThreadManager: {}"), e.what()); + LOG_F(ERROR, _("Failed to destroy ThreadManager: {}"), e.what()); } } @@ -97,7 +97,7 @@ namespace Lithium::Thread } catch (const std::exception &e) { - DLOG_F(ERROR, _("Unhandled exception in thread: {}"), e.what()); + LOG_F(ERROR, _("Unhandled exception in thread: {}"), e.what()); } }), name, false); @@ -119,7 +119,7 @@ namespace Lithium::Thread } catch (const std::exception &e) { - DLOG_F(ERROR, _("Unhandled exception in thread: {}"), e.what()); + LOG_F(ERROR, _("Unhandled exception in thread: {}"), e.what()); } }), generateRandomString(16), false); @@ -130,7 +130,7 @@ namespace Lithium::Thread } catch (const std::exception &e) { - DLOG_F(ERROR, _("Failed to add thread {}: {}"), name, e.what()); + LOG_F(ERROR, _("Failed to add thread {}: {}"), name, e.what()); } } @@ -150,7 +150,7 @@ namespace Lithium::Thread } catch (const std::exception &e) { - DLOG_F(ERROR, _("Failed to join all threads: {}"), e.what()); + LOG_F(ERROR, _("Failed to join all threads: {}"), e.what()); } } @@ -181,7 +181,7 @@ namespace Lithium::Thread } catch (const std::exception &e) { - DLOG_F(ERROR, _("Failed to join thread {}: {}"), name, e.what()); + LOG_F(ERROR, _("Failed to join thread {}: {}"), name, e.what()); } } @@ -207,7 +207,7 @@ namespace Lithium::Thread } catch (const std::exception &e) { - DLOG_F(ERROR, _("Failed to check if thread {} is running: {}"), name, e.what()); + LOG_F(ERROR, _("Failed to check if thread {} is running: {}"), name, e.what()); return false; } } diff --git a/src/modules/utils/string.cpp b/src/modules/utils/string.cpp new file mode 100644 index 00000000..47bf756d --- /dev/null +++ b/src/modules/utils/string.cpp @@ -0,0 +1,71 @@ +#include "string.hpp" +#include + +bool HasUppercase(const std::string& str) +{ + return std::any_of(str.begin(), str.end(), [](char ch) { return std::isupper(ch); }); +} + +std::string ToUnderscore(const std::string& str) +{ + std::string result; + for (char ch : str) + { + if (std::isupper(ch)) + { + result += '_'; + result += std::tolower(ch); + } + else + { + result += ch; + } + } + return result; +} + +std::string ToCamelCase(const std::string& str) +{ + std::string result; + bool capitalize = false; + + for (char ch : str) + { + if (ch == '_') + { + capitalize = true; + } + else + { + if (capitalize) + { + result += std::toupper(ch); + capitalize = false; + } + else + { + result += ch; + } + } + } + return result; +} + +std::string ConvertToUnderscore(const std::string& str) +{ + return HasUppercase(str) ? ToUnderscore(str) : str; +} + +std::string ConvertToCamelCase(const std::string& str) +{ + if (str.find('_') != std::string::npos) + { + return ToCamelCase(str); + } + else + { + std::string result = str; + result[0] = std::tolower(result[0]); + return result; + } +} diff --git a/src/modules/utils/string.hpp b/src/modules/utils/string.hpp new file mode 100644 index 00000000..99fd74e3 --- /dev/null +++ b/src/modules/utils/string.hpp @@ -0,0 +1,12 @@ +#ifndef UNDERSCORE_H +#define UNDERSCORE_H + +#include + +bool HasUppercase(const std::string& str); +std::string ToUnderscore(const std::string& str); +std::string ToCamelCase(const std::string& str); +std::string ConvertToUnderscore(const std::string& str); +std::string ConvertToCamelCase(const std::string& str); + +#endif // UNDERSCORE_H diff --git a/src/modules/web/downloader.cpp b/src/modules/web/downloader.cpp index e11f5c4c..df048561 100644 --- a/src/modules/web/downloader.cpp +++ b/src/modules/web/downloader.cpp @@ -46,7 +46,7 @@ DownloadManager::DownloadManager(const std::string &task_file) : task_file_(task std::ifstream infile(task_file_); if (!infile) { - DLOG_F(ERROR, "Failed to open task file {}", task_file_); + LOG_F(ERROR, "Failed to open task file {}", task_file_); throw std::runtime_error("Failed to open task file."); } while (infile >> std::ws && !infile.eof()) @@ -62,7 +62,7 @@ DownloadManager::DownloadManager(const std::string &task_file) : task_file_(task } catch (const std::exception &e) { - DLOG_F(ERROR, "Error: {}", e.what()); + LOG_F(ERROR, "Error: {}", e.what()); throw; } } @@ -79,7 +79,7 @@ void DownloadManager::add_task(const std::string &url, const std::string &filepa std::ofstream outfile(task_file_, std::ios_base::app); if (!outfile) { - DLOG_F(ERROR, "Failed to open task file {}", task_file_); + LOG_F(ERROR, "Failed to open task file {}", task_file_); throw std::runtime_error("Failed to open task file."); } outfile << url << " " << filepath << std::endl; @@ -87,7 +87,7 @@ void DownloadManager::add_task(const std::string &url, const std::string &filepa } catch (const std::exception &e) { - DLOG_F(ERROR, "Error: {}", e.what()); + LOG_F(ERROR, "Error: {}", e.what()); throw; } tasks_.push_back({url, filepath, false, false, 0, priority}); @@ -121,7 +121,7 @@ void DownloadManager::pause_task(size_t index) { if (index >= tasks_.size()) { - DLOG_F(ERROR, "Index out of bounds!"); + LOG_F(ERROR, "Index out of bounds!"); return; } @@ -133,7 +133,7 @@ void DownloadManager::resume_task(size_t index) { if (index >= tasks_.size()) { - DLOG_F(ERROR, "Index out of bounds!"); + LOG_F(ERROR, "Index out of bounds!"); return; } @@ -150,7 +150,7 @@ size_t DownloadManager::get_downloaded_bytes(size_t index) { if (index >= tasks_.size()) { - DLOG_F(ERROR, "Index out of bounds!"); + LOG_F(ERROR, "Index out of bounds!"); return 0; } @@ -214,14 +214,14 @@ void DownloadManager::download_task(DownloadTask &task, size_t download_speed) auto res = cli.Get("/"); if (!res || res->status != 200) { - DLOG_F(ERROR, "Failed to download {}", task.url); + LOG_F(ERROR, "Failed to download {}", task.url); return; } std::ofstream outfile(task.filepath, std::ofstream::binary | std::ofstream::app); if (!outfile) { - DLOG_F(ERROR, "Failed to open file {}", task.filepath); + LOG_F(ERROR, "Failed to open file {}", task.filepath); return; } @@ -299,7 +299,7 @@ void DownloadManager::save_task_list_to_file() } catch (const std::exception &e) { - DLOG_F(ERROR, "Error: {}", e.what()); + LOG_F(ERROR, "Error: {}", e.what()); throw; } } \ No newline at end of file diff --git a/src/modules/web/httpclient.cpp b/src/modules/web/httpclient.cpp index 4f09afee..b84d6c19 100644 --- a/src/modules/web/httpclient.cpp +++ b/src/modules/web/httpclient.cpp @@ -64,7 +64,7 @@ bool HttpClient::SendGetRequest(const std::string &path, const std::mapstatus != 200) { err = res ? res->body : "Unknown error"; - DLOG_F(ERROR, "Failed to send GET request to {}{}. Error message: {}", host_, path, err); + LOG_F(ERROR, "Failed to send GET request to {}{}. Error message: {}", host_, path, err); return false; } @@ -75,7 +75,7 @@ bool HttpClient::SendGetRequest(const std::string &path, const std::mapstatus != 200) { err = res ? res->body : "Unknown error"; - DLOG_F(ERROR, "Failed to send POST request to {}{}, data {}. Error message: {}", host_, path, data.dump(), err); + LOG_F(ERROR, "Failed to send POST request to {}{}, data {}. Error message: {}", host_, path, data.dump(), err); return false; } @@ -110,7 +110,7 @@ bool HttpClient::SendPostRequest(const std::string &path, const std::mapstatus != 200) { err = res ? res->body : "Unknown error"; - DLOG_F(ERROR, "Failed to send PUT request to {}{}, data {}. Error message: {}", host_, path, data.dump(), err); + LOG_F(ERROR, "Failed to send PUT request to {}{}, data {}. Error message: {}", host_, path, data.dump(), err); return false; } @@ -145,7 +145,7 @@ bool HttpClient::SendPutRequest(const std::string &path, const std::mapstatus != 200) { err = res ? res->body : "Unknown error"; - DLOG_F(ERROR, "Failed to send DELETE request to {}{}, data {}. Error message: {}", host_, path, res->body, err); + LOG_F(ERROR, "Failed to send DELETE request to {}{}, data {}. Error message: {}", host_, path, res->body, err); return false; } @@ -180,7 +180,7 @@ bool HttpClient::SendDeleteRequest(const std::string &path, const std::mapstatus != 200) { status = res ? std::to_string(res->status) : "Unknown error"; - DLOG_F(ERROR, "Failed to check server status on {}:%d with error message: {}", host_, port_, status); + LOG_F(ERROR, "Failed to check server status on {}:%d with error message: {}", host_, port_, status); return false; } diff --git a/src/modules/web/utils.cpp b/src/modules/web/utils.cpp index 55d07976..48e516ca 100644 --- a/src/modules/web/utils.cpp +++ b/src/modules/web/utils.cpp @@ -178,7 +178,7 @@ bool CheckAndKillProgramOnPort(int port) int ret = WSAStartup(MAKEWORD(2, 2), &wsaData); if (ret != 0) { - DLOG_F(ERROR, "Failed to initialize Windows Socket API: %d", ret); + LOG_F(ERROR, "Failed to initialize Windows Socket API: %d", ret); return false; } #endif @@ -187,7 +187,7 @@ bool CheckAndKillProgramOnPort(int port) int sockfd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if (sockfd < 0) { - DLOG_F(ERROR, "Failed to create socket: {}", strerror(errno)); + LOG_F(ERROR, "Failed to create socket: {}", strerror(errno)); #ifdef _WIN32 WSACleanup(); #endif @@ -225,7 +225,7 @@ bool CheckAndKillProgramOnPort(int port) FILE *fp = popen(cmd.c_str(), "r"); if (fp == nullptr) { - DLOG_F(ERROR, "Failed to execute command: {}", cmd); + LOG_F(ERROR, "Failed to execute command: {}", cmd); close(sockfd); #ifdef _WIN32 WSACleanup(); @@ -263,7 +263,7 @@ bool CheckAndKillProgramOnPort(int port) if (ret != 0) { - DLOG_F(ERROR, "Failed to kill the process: {}", pid_str); + LOG_F(ERROR, "Failed to kill the process: {}", pid_str); close(sockfd); #ifdef _WIN32 WSACleanup(); @@ -275,7 +275,7 @@ bool CheckAndKillProgramOnPort(int port) } else { - DLOG_F(ERROR, "Failed to get process ID on port(%d)", port); + LOG_F(ERROR, "Failed to get process ID on port(%d)", port); close(sockfd); #ifdef _WIN32 WSACleanup(); @@ -285,7 +285,7 @@ bool CheckAndKillProgramOnPort(int port) } else { - DLOG_F(ERROR, "Failed to bind socket: {}", strerror(errno)); + LOG_F(ERROR, "Failed to bind socket: {}", strerror(errno)); close(sockfd); #ifdef _WIN32 WSACleanup(); diff --git a/src/websocket/WebSocketServer.cpp b/src/websocket/WebSocketServer.cpp index f8c00db9..01ad8b70 100644 --- a/src/websocket/WebSocketServer.cpp +++ b/src/websocket/WebSocketServer.cpp @@ -113,7 +113,7 @@ oatpp::async::CoroutineStarter WebSocketServer::readMessage(const std::shared_pt // DLOG_F(INFO, "onMessage message='%s'", wholeMessage->c_str()); if (!nlohmann::json::accept(wholeMessage->c_str())) { - DLOG_F(ERROR, "Message is not in JSON format"); + LOG_F(ERROR, "Message is not in JSON format"); reply_data["error"] = "Invalid Format"; reply_data["message"] = "Message is not in JSON format"; return socket->sendOneFrameTextAsync(reply_data.dump()); @@ -125,7 +125,7 @@ oatpp::async::CoroutineStarter WebSocketServer::readMessage(const std::shared_pt { if (jdata.empty()) { - DLOG_F(ERROR, "WebSocketServer::processMessage() data is empty"); + LOG_F(ERROR, "WebSocketServer::processMessage() data is empty"); reply_data["error"] = "Invalid Parameters"; reply_data["message"] = "Data is empty"; return socket->sendOneFrameTextAsync(reply_data.dump()); @@ -138,7 +138,7 @@ oatpp::async::CoroutineStarter WebSocketServer::readMessage(const std::shared_pt json res = m_CommandDispatcher->Dispatch(name, jdata["params"].get()); if (res.contains("error")) { - DLOG_F(ERROR, "Failed to run command %s , error : %s", name.c_str(), res.dump().c_str()); + LOG_F(ERROR, "Failed to run command %s , error : %s", name.c_str(), res.dump().c_str()); reply_data["error"] = res["error"]; } else @@ -150,24 +150,24 @@ oatpp::async::CoroutineStarter WebSocketServer::readMessage(const std::shared_pt } else { - DLOG_F(ERROR, "[ASYNC MODE] WebSocketServer::readMessage() missing parameter: name or params"); + LOG_F(ERROR, "[ASYNC MODE] WebSocketServer::readMessage() missing parameter: name or params"); reply_data = {{"error", "Invalid Parameters"}, {"message", "Missing parameter: name or params"}}; } } catch (const std::exception &e) { - DLOG_F(ERROR, "WebSocketServer::readMessage() run command failed: %s", e.what()); + LOG_F(ERROR, "WebSocketServer::readMessage() run command failed: %s", e.what()); reply_data = {{"error", "Running Error"}, {"message", e.what()}}; } } catch (const nlohmann::detail::parse_error &e) { - DLOG_F(ERROR, "[ASYNC MODE] WebSocketServer::readMessage() json exception: %s", e.what()); + LOG_F(ERROR, "[ASYNC MODE] WebSocketServer::readMessage() json exception: %s", e.what()); reply_data = {{"errro", "Invalid Format"}, {"message", e.what()}}; } catch (const std::exception &e) { - DLOG_F(ERROR, "[ASYNC MODE] WebSocketServer::readMessage() exception: %s", e.what()); + LOG_F(ERROR, "[ASYNC MODE] WebSocketServer::readMessage() exception: %s", e.what()); reply_data = {{"errro", "Unknown Error"}, {"message", e.what()}}; } return socket->sendOneFrameTextAsync(reply_data.dump()); @@ -206,7 +206,7 @@ void WebSocketServer::readMessage(const WebSocket &socket, v_uint8 opcode, p_cha DLOG_F(INFO, "onMessage message='%s'", wholeMessage->c_str()); if (!nlohmann::json::accept(wholeMessage->c_str())) { - DLOG_F(ERROR, "Message is not in JSON format"); + LOG_F(ERROR, "Message is not in JSON format"); return; } try @@ -223,11 +223,11 @@ void WebSocketServer::readMessage(const WebSocket &socket, v_uint8 opcode, p_cha } catch (const nlohmann::detail::parse_error &e) { - DLOG_F(ERROR, "Failed to parser JSON message : %s", e.what()); + LOG_F(ERROR, "Failed to parser JSON message : %s", e.what()); } catch (const std::exception &e) { - DLOG_F(ERROR, "Unknown error happened in WebsocketServer : %s", e.what()); + LOG_F(ERROR, "Unknown error happened in WebsocketServer : %s", e.what()); } } else if (size > 0) @@ -287,7 +287,7 @@ void WebSocketServer::ProcessMessage(const WebSocket &socket, const nlohmann::js { if (data.empty()) { - DLOG_F(ERROR, "WebSocketServer::processMessage() data is empty"); + LOG_F(ERROR, "WebSocketServer::processMessage() data is empty"); return; } nlohmann::json reply_data; @@ -301,7 +301,7 @@ void WebSocketServer::ProcessMessage(const WebSocket &socket, const nlohmann::js json res = m_CommandDispatcher->Dispatch(name, data["params"].get()); if (res.contains("error")) { - DLOG_F(ERROR, "Failed to run command %s , error : %s", name.c_str(), res.dump().c_str()); + LOG_F(ERROR, "Failed to run command %s , error : %s", name.c_str(), res.dump().c_str()); reply_data["error"] = res["error"]; } else @@ -313,25 +313,25 @@ void WebSocketServer::ProcessMessage(const WebSocket &socket, const nlohmann::js } else { - DLOG_F(ERROR, "WebSocketServer::processMessage() missing parameter: name or params"); + LOG_F(ERROR, "WebSocketServer::processMessage() missing parameter: name or params"); reply_data = {{"error", "Missing parameter: name or params"}}; } } catch (const nlohmann::json::exception &e) { - DLOG_F(ERROR, "WebSocketServer::processMessage() json exception: %s", e.what()); + LOG_F(ERROR, "WebSocketServer::processMessage() json exception: %s", e.what()); reply_data = {{"error", e.what()}}; } catch (const std::exception &e) { - DLOG_F(ERROR, "WebSocketServer::processMessage() exception: %s", e.what()); + LOG_F(ERROR, "WebSocketServer::processMessage() exception: %s", e.what()); reply_data = {{"error", e.what()}}; } socket.sendOneFrameText(reply_data.dump()); } catch (const std::exception &e) { - DLOG_F(ERROR, "WebSocketServer::onMessage() parse json failed: %s", e.what()); + LOG_F(ERROR, "WebSocketServer::onMessage() parse json failed: %s", e.what()); } } #endif diff --git a/src/websocket/WsDeviceComponent.cpp b/src/websocket/WsDeviceComponent.cpp index c18854ba..ff3a258a 100644 --- a/src/websocket/WsDeviceComponent.cpp +++ b/src/websocket/WsDeviceComponent.cpp @@ -43,7 +43,7 @@ const nlohmann::json WebSocketServer::GetDeviceList(const nlohmann::json &m_para res["command"] = "GetDeviceList"; if (!m_params.contains("device_type")) { - DLOG_F(ERROR, "GetDeviceList() : Device type is required"); + LOG_F(ERROR, "GetDeviceList() : Device type is required"); res["error"] = "Device type is required"; return res; } @@ -52,7 +52,7 @@ const nlohmann::json WebSocketServer::GetDeviceList(const nlohmann::json &m_para if (it == DeviceTypeMap.end()) { res["error"] = "Unsupport device type"; - DLOG_F(ERROR, "Unsupport device type, GetDeviceList() : %s", res.dump().c_str()); + LOG_F(ERROR, "Unsupport device type, GetDeviceList() : %s", res.dump().c_str()); return res; } device_type = it->second; @@ -64,7 +64,7 @@ const nlohmann::json WebSocketServer::GetDeviceList(const nlohmann::json &m_para } catch (const std::exception &e) { - DLOG_F(ERROR, "Error occurred in GetDeviceList: %s", e.what()); + LOG_F(ERROR, "Error occurred in GetDeviceList: %s", e.what()); return {{"error", "Error occurred in GetDeviceList"}, {"message", e.what()}}; } } @@ -77,7 +77,7 @@ const nlohmann::json WebSocketServer::AddDevice(const nlohmann::json &m_params) { if (!m_params.contains("device_type") || !m_params.contains("device_name")) { - DLOG_F(ERROR, "GetDeviceList() : Device type and name are required"); + LOG_F(ERROR, "GetDeviceList() : Device type and name are required"); res["error"] = "Device type and name are required"; return res; } @@ -86,7 +86,7 @@ const nlohmann::json WebSocketServer::AddDevice(const nlohmann::json &m_params) if (it == DeviceTypeMap.end()) { res["error"] = "Unsupport device type"; - DLOG_F(ERROR, "Unsupport device type, AddDevice() : %s", res.dump().c_str()); + LOG_F(ERROR, "Unsupport device type, AddDevice() : %s", res.dump().c_str()); return res; } device_type = it->second; @@ -102,12 +102,12 @@ const nlohmann::json WebSocketServer::AddDevice(const nlohmann::json &m_params) } catch (const nlohmann::json::exception &e) { - DLOG_F(ERROR, "WebSocketServer::AddDevice() json exception: %s", e.what()); + LOG_F(ERROR, "WebSocketServer::AddDevice() json exception: %s", e.what()); res["error"] = "Invalid parameters"; } catch (const std::exception &e) { - DLOG_F(ERROR, "Error occurred in AddDevice: %s", e.what()); + LOG_F(ERROR, "Error occurred in AddDevice: %s", e.what()); res["error"] = "Error occurred in AddDevice"; res["message"] = e.what(); } @@ -120,7 +120,7 @@ const nlohmann::json WebSocketServer::AddDeviceLibrary(const nlohmann::json &m_p res["command"] = "AddDeviceLibrary"; if (!m_params.contains("lib_path") || !m_params.contains("lib_name")) { - DLOG_F(ERROR, "WebSocketServer::AddDevice() : Device library path and name are required"); + LOG_F(ERROR, "WebSocketServer::AddDevice() : Device library path and name are required"); res["error"] = "Invalid parameters"; res["message"] = "Device library path and name are required"; return res; @@ -136,7 +136,7 @@ const nlohmann::json WebSocketServer::AddDeviceLibrary(const nlohmann::json &m_p } catch (const nlohmann::json::exception &e) { - DLOG_F(ERROR, "WebSocketServer::AddDeviceLibrary() json exception: %s", e.what()); + LOG_F(ERROR, "WebSocketServer::AddDeviceLibrary() json exception: %s", e.what()); res["error"] = "Invalid parameters"; res["message"] = e.what(); } @@ -144,7 +144,7 @@ const nlohmann::json WebSocketServer::AddDeviceLibrary(const nlohmann::json &m_p { res["error"] = "Error occurred in WebSocketServer::AddDeviceLibrary"; res["message"] = e.what(); - DLOG_F(ERROR, "WebSocketServer::AddDeviceLibrary: %s", e.what()); + LOG_F(ERROR, "WebSocketServer::AddDeviceLibrary: %s", e.what()); } return res; } @@ -155,7 +155,7 @@ const nlohmann::json WebSocketServer::RemoveDevice(const nlohmann::json &m_param res["command"] = "RemoveDevice"; if (!m_params.contains("device_type") || !m_params.contains("device_name")) { - DLOG_F(ERROR, "WebSocketServer::RemoveDevice() : Device type and name are required"); + LOG_F(ERROR, "WebSocketServer::RemoveDevice() : Device type and name are required"); res["error"] = "Invalid parameters"; res["message"] = "Device type and name are required"; return res; @@ -167,7 +167,7 @@ const nlohmann::json WebSocketServer::RemoveDevice(const nlohmann::json &m_param if (it == DeviceTypeMap.end()) { res["error"] = "Unsupport device type"; - DLOG_F(ERROR, "WebSocketServer::RemoveDevice() : Unsupport device type %s", res.dump().c_str()); + LOG_F(ERROR, "WebSocketServer::RemoveDevice() : Unsupport device type %s", res.dump().c_str()); return res; } device_type = it->second; @@ -181,7 +181,7 @@ const nlohmann::json WebSocketServer::RemoveDevice(const nlohmann::json &m_param } catch (const nlohmann::json::exception &e) { - DLOG_F(ERROR, "WebSocketServer::RemoveDevice() json exception: %s", e.what()); + LOG_F(ERROR, "WebSocketServer::RemoveDevice() json exception: %s", e.what()); res["error"] = "Invalid parameters"; res["message"] = e.what(); } @@ -189,7 +189,7 @@ const nlohmann::json WebSocketServer::RemoveDevice(const nlohmann::json &m_param { res["error"] = "Error occurred in WebSocketServer::RemoveDevice"; res["message"] = e.what(); - DLOG_F(ERROR, "WebSocketServer::RemoveDevice(): %s", e.what()); + LOG_F(ERROR, "WebSocketServer::RemoveDevice(): %s", e.what()); } return res; } @@ -200,7 +200,7 @@ const nlohmann::json WebSocketServer::RemoveDevicesByName(const nlohmann::json & res["command"] = "RemoveDeviceByName"; if (!m_params.contains("device_name")) { - DLOG_F(ERROR, "WebSocketServer::RemoveDevice() : Device name is required"); + LOG_F(ERROR, "WebSocketServer::RemoveDevice() : Device name is required"); res["error"] = "Invalid parameters"; res["message"] = "Device name is required"; return res; @@ -216,7 +216,7 @@ const nlohmann::json WebSocketServer::RemoveDevicesByName(const nlohmann::json & } catch (const nlohmann::json::exception &e) { - DLOG_F(ERROR, "WebSocketServer::RemoveDeviceByName() json exception: %s", e.what()); + LOG_F(ERROR, "WebSocketServer::RemoveDeviceByName() json exception: %s", e.what()); res["error"] = "Invalid parameters"; res["message"] = e.what(); } @@ -224,7 +224,7 @@ const nlohmann::json WebSocketServer::RemoveDevicesByName(const nlohmann::json & { res["error"] = "Error occurred in WebSocketServer::RemoveDeviceByName"; res["message"] = e.what(); - DLOG_F(ERROR, "WebSocketServer::RemoveDeviceByName(): %s", e.what()); + LOG_F(ERROR, "WebSocketServer::RemoveDeviceByName(): %s", e.what()); } return res; } @@ -235,7 +235,7 @@ const nlohmann::json WebSocketServer::RemoveDeviceLibrary(const nlohmann::json & res["command"] = "RemoveDeviceLibrary"; if (!m_params.contains("lib_name")) { - DLOG_F(ERROR, "WebSocketServer::RemoveDeviceLibrary() : Device name is required"); + LOG_F(ERROR, "WebSocketServer::RemoveDeviceLibrary() : Device name is required"); res["error"] = "Invalid parameters"; res["message"] = "Device library name is required"; return res; @@ -251,7 +251,7 @@ const nlohmann::json WebSocketServer::RemoveDeviceLibrary(const nlohmann::json & } catch (const nlohmann::json::exception &e) { - DLOG_F(ERROR, "WebSocketServer::RemoveDeviceLibrary() json exception: %s", e.what()); + LOG_F(ERROR, "WebSocketServer::RemoveDeviceLibrary() json exception: %s", e.what()); res["error"] = "Invalid parameters"; res["message"] = e.what(); } @@ -259,7 +259,7 @@ const nlohmann::json WebSocketServer::RemoveDeviceLibrary(const nlohmann::json & { res["error"] = "Error occurred in WebSocketServer::RemoveDeviceLibrary"; res["message"] = e.what(); - DLOG_F(ERROR, "WebSocketServer::RemoveDeviceLibrary(): %s", e.what()); + LOG_F(ERROR, "WebSocketServer::RemoveDeviceLibrary(): %s", e.what()); } return res; } @@ -275,7 +275,7 @@ const nlohmann::json WebSocketServer::RunDeviceTask(const nlohmann::json &m_para if (!(m_params.contains("device_name") || m_params.contains("device_uuid")) || !m_params.contains("device_type")) { res["error"] = "Device name or uuid is required"; - DLOG_F(ERROR, "WebSocketServer::RunDeviceTask() : %s", res.dump().c_str()); + LOG_F(ERROR, "WebSocketServer::RunDeviceTask() : %s", res.dump().c_str()); return res; } @@ -285,7 +285,7 @@ const nlohmann::json WebSocketServer::RunDeviceTask(const nlohmann::json &m_para if (it == DeviceTypeMap.end()) { res["error"] = "Device type not supported"; - DLOG_F(ERROR, "WebSocketServer::RunDeviceTask() : %s", res.dump().c_str()); + LOG_F(ERROR, "WebSocketServer::RunDeviceTask() : %s", res.dump().c_str()); return res; } device_type = it->second; @@ -294,7 +294,7 @@ const nlohmann::json WebSocketServer::RunDeviceTask(const nlohmann::json &m_para if (!m_params.contains("task_name")) { res["error"] = "Task name is required"; - DLOG_F(ERROR, "WebSocketServer::RunDeviceTask() : %s", res.dump().c_str()); + LOG_F(ERROR, "WebSocketServer::RunDeviceTask() : %s", res.dump().c_str()); return res; } std::string task_name = m_params["task_name"]; @@ -304,7 +304,7 @@ const nlohmann::json WebSocketServer::RunDeviceTask(const nlohmann::json &m_para if (task == nullptr) { res["error"] = "Failed to get task"; - DLOG_F(ERROR, "WebSocketServer::RunDeviceTask() : Failed to get task %s ,error %s", task_name.c_str(), res.dump().c_str()); + LOG_F(ERROR, "WebSocketServer::RunDeviceTask() : Failed to get task %s ,error %s", task_name.c_str(), res.dump().c_str()); return res; } task->Execute(); @@ -314,7 +314,7 @@ const nlohmann::json WebSocketServer::RunDeviceTask(const nlohmann::json &m_para if (result.contains("error")) { res["error"] = result["error"]; - DLOG_F(ERROR, "WebSocketServer::RunDeviceTask() : Error happened in task %s - %s", task_name.c_str(), result.dump().c_str()); + LOG_F(ERROR, "WebSocketServer::RunDeviceTask() : Error happened in task %s - %s", task_name.c_str(), result.dump().c_str()); } res["result"] = result; return res; @@ -329,7 +329,7 @@ const nlohmann::json WebSocketServer::GetDeviceInfo(const nlohmann::json &m_para if (!m_params.contains("device_name") && !m_params.contains("device_uuid")) { res["error"] = "Device name or uuid is required"; - DLOG_F(ERROR, "WebSocketServer::GetDeviceInfo() : %s", res.dump().c_str()); + LOG_F(ERROR, "WebSocketServer::GetDeviceInfo() : %s", res.dump().c_str()); return res; } @@ -356,7 +356,7 @@ const nlohmann::json WebSocketServer::GetDeviceInfo(const nlohmann::json &m_para } catch (const nlohmann::json::exception &e) { - DLOG_F(ERROR, "WebSocketServer::GetDeviceInfo() json exception: %s", e.what()); + LOG_F(ERROR, "WebSocketServer::GetDeviceInfo() json exception: %s", e.what()); res["error"] = "Invalid parameters"; res["message"] = e.what(); } @@ -364,7 +364,7 @@ const nlohmann::json WebSocketServer::GetDeviceInfo(const nlohmann::json &m_para { res["error"] = "Error occurred in WebSocketServer::GetDeviceInfo"; res["message"] = e.what(); - DLOG_F(ERROR, "WebSocketServer::GetDeviceInfo(): %s", e.what()); + LOG_F(ERROR, "WebSocketServer::GetDeviceInfo(): %s", e.what()); } return res; } \ No newline at end of file diff --git a/src/websocket/WsProcessComponent.cpp b/src/websocket/WsProcessComponent.cpp index ceae78c0..37f2b811 100644 --- a/src/websocket/WsProcessComponent.cpp +++ b/src/websocket/WsProcessComponent.cpp @@ -43,7 +43,7 @@ const nlohmann::json WebSocketServer::CreateProcessLi(const nlohmann::json &m_pa { if (!m_params.contains("command") || !m_params.contains("cmd_id")) { - DLOG_F(ERROR, "CreateProcess() : Command and ID are required"); + LOG_F(ERROR, "CreateProcess() : Command and ID are required"); res["error"] = "Command and ID are required"; return res; } @@ -57,13 +57,13 @@ const nlohmann::json WebSocketServer::CreateProcessLi(const nlohmann::json &m_pa } catch (const nlohmann::json::exception &e) { - DLOG_F(ERROR, "WebSocketServer::CreateProcess() json exception: %s", e.what()); + LOG_F(ERROR, "WebSocketServer::CreateProcess() json exception: %s", e.what()); res["error"] = "Invalid parameters"; res["message"] = e.what(); } catch (const std::exception &e) { - DLOG_F(ERROR, "Error occurred in CreateProcess: %s", e.what()); + LOG_F(ERROR, "Error occurred in CreateProcess: %s", e.what()); res["error"] = "Error occurred in CreateProcess"; res["message"] = e.what(); } @@ -78,7 +78,7 @@ const nlohmann::json WebSocketServer::RunScript(const nlohmann::json &m_params) { if (!m_params.contains("script_name") || !m_params.contains("script_id")) { - DLOG_F(ERROR, "RunScript() : Script name and ID are required"); + LOG_F(ERROR, "RunScript() : Script name and ID are required"); res["error"] = "Script name and ID are required"; return res; } @@ -92,13 +92,13 @@ const nlohmann::json WebSocketServer::RunScript(const nlohmann::json &m_params) } catch (const nlohmann::json::exception &e) { - DLOG_F(ERROR, "WebSocketServer::RunScript() json exception: %s", e.what()); + LOG_F(ERROR, "WebSocketServer::RunScript() json exception: %s", e.what()); res["error"] = "Invalid parameters"; res["message"] = e.what(); } catch (const std::exception &e) { - DLOG_F(ERROR, "Error occurred in RunScript: %s", e.what()); + LOG_F(ERROR, "Error occurred in RunScript: %s", e.what()); res["error"] = "Error occurred in RunScript"; res["message"] = e.what(); } @@ -113,7 +113,7 @@ const nlohmann::json WebSocketServer::TerminateProcessByName(const nlohmann::jso { if (!m_params.contains("process_name")) { - DLOG_F(ERROR, "TerminateProcessByName() : Process name is required"); + LOG_F(ERROR, "TerminateProcessByName() : Process name is required"); res["error"] = "Process name is required"; return res; } @@ -126,13 +126,13 @@ const nlohmann::json WebSocketServer::TerminateProcessByName(const nlohmann::jso } catch (const nlohmann::json::exception &e) { - DLOG_F(ERROR, "WebSocketServer::TerminateProcessByName() json exception: %s", e.what()); + LOG_F(ERROR, "WebSocketServer::TerminateProcessByName() json exception: %s", e.what()); res["error"] = "Invalid parameters"; res["message"] = e.what(); } catch (const std::exception &e) { - DLOG_F(ERROR, "Error occurred in TerminateProcessByName: %s", e.what()); + LOG_F(ERROR, "Error occurred in TerminateProcessByName: %s", e.what()); res["error"] = "Error occurred in TerminateProcessByName"; res["message"] = e.what(); } @@ -154,13 +154,13 @@ const nlohmann::json WebSocketServer::GetRunningProcesses(const nlohmann::json & } catch (const nlohmann::json::exception &e) { - DLOG_F(ERROR, "WebSocketServer::GetRunningProcesses() json exception: %s", e.what()); + LOG_F(ERROR, "WebSocketServer::GetRunningProcesses() json exception: %s", e.what()); res["error"] = "Invalid parameters"; res["message"] = e.what(); } catch (const std::exception &e) { - DLOG_F(ERROR, "Error occurred in GetRunningProcesses: %s", e.what()); + LOG_F(ERROR, "Error occurred in GetRunningProcesses: %s", e.what()); res["error"] = "Error occurred in GetRunningProcesses"; res["message"] = e.what(); } @@ -175,7 +175,7 @@ const nlohmann::json WebSocketServer::GetProcessOutput(const nlohmann::json &m_p { if (!m_params.contains("process_name") || !m_params.contains("cmd_id")) { - DLOG_F(ERROR, "GetProcessOutput() : Process name is required"); + LOG_F(ERROR, "GetProcessOutput() : Process name is required"); res["error"] = "Process name is required"; return res; } @@ -187,13 +187,13 @@ const nlohmann::json WebSocketServer::GetProcessOutput(const nlohmann::json &m_p } catch (const nlohmann::json::exception &e) { - DLOG_F(ERROR, "WebSocketServer::GetProcessOutput() json exception: %s", e.what()); + LOG_F(ERROR, "WebSocketServer::GetProcessOutput() json exception: %s", e.what()); res["error"] = "Invalid parameters"; res["message"] = e.what(); } catch (const std::exception &e) { - DLOG_F(ERROR, "Error occurred in GetProcessOutput: %s", e.what()); + LOG_F(ERROR, "Error occurred in GetProcessOutput: %s", e.what()); res["error"] = "Error occurred in GetProcessOutput"; res["message"] = e.what(); } diff --git a/src/websocket/WsScriptComponent.cpp b/src/websocket/WsScriptComponent.cpp index 9c8b7501..21667a9a 100644 --- a/src/websocket/WsScriptComponent.cpp +++ b/src/websocket/WsScriptComponent.cpp @@ -43,7 +43,7 @@ const nlohmann::json WebSocketServer::runChaiCommand(const nlohmann::json &m_par { if (!m_params.contains("command")) { - DLOG_F(ERROR, "runChaiCommand() : Command is required"); + LOG_F(ERROR, "runChaiCommand() : Command is required"); res["error"] = "Invalid parameters"; res["message"] = "command content is required"; return res; @@ -57,13 +57,13 @@ const nlohmann::json WebSocketServer::runChaiCommand(const nlohmann::json &m_par } catch (const nlohmann::json::exception &e) { - DLOG_F(ERROR, "WebSocketServer::runChaiCommand() json exception: %s", e.what()); + LOG_F(ERROR, "WebSocketServer::runChaiCommand() json exception: %s", e.what()); res["error"] = "Invalid parameters"; res["message"] = e.what(); } catch (const std::exception &e) { - DLOG_F(ERROR, "Error occurred in runChaiCommand: %s", e.what()); + LOG_F(ERROR, "Error occurred in runChaiCommand: %s", e.what()); res["error"] = "StdError"; res["message"] = e.what(); } @@ -78,7 +78,7 @@ const nlohmann::json WebSocketServer::runChaiMultiCommand(const nlohmann::json & { if (!m_params.contains("command")) { - DLOG_F(ERROR, "runChaiMultiCommand() : Command is required"); + LOG_F(ERROR, "runChaiMultiCommand() : Command is required"); res["error"] = "Invalid parameters"; res["message"] = "command content is required"; return res; @@ -91,13 +91,13 @@ const nlohmann::json WebSocketServer::runChaiMultiCommand(const nlohmann::json & } catch (const nlohmann::json::exception &e) { - DLOG_F(ERROR, "WebSocketServer::runChaiMultiCommand() json exception: %s", e.what()); + LOG_F(ERROR, "WebSocketServer::runChaiMultiCommand() json exception: %s", e.what()); res["error"] = "Invalid parameters"; res["message"] = e.what(); } catch (const std::exception &e) { - DLOG_F(ERROR, "Error occurred in runChaiMultiCommand: %s", e.what()); + LOG_F(ERROR, "Error occurred in runChaiMultiCommand: %s", e.what()); res["error"] = "StdError"; res["message"] = e.what(); } @@ -112,7 +112,7 @@ const nlohmann::json WebSocketServer::runChaiScript(const nlohmann::json &m_para { if (!m_params.contains("script")) { - DLOG_F(ERROR, "runChaiScript() : Command is required"); + LOG_F(ERROR, "runChaiScript() : Command is required"); res["error"] = "Invalid parameters"; res["message"] = "script name is required"; return res; @@ -125,13 +125,13 @@ const nlohmann::json WebSocketServer::runChaiScript(const nlohmann::json &m_para } catch (const nlohmann::json::exception &e) { - DLOG_F(ERROR, "WebSocketServer::runChaiScript() json exception: %s", e.what()); + LOG_F(ERROR, "WebSocketServer::runChaiScript() json exception: %s", e.what()); res["error"] = "Invalid parameters"; res["message"] = e.what(); } catch (const std::exception &e) { - DLOG_F(ERROR, "Error occurred in runChaiScript: %s", e.what()); + LOG_F(ERROR, "Error occurred in runChaiScript: %s", e.what()); res["error"] = "StdError"; res["message"] = e.what(); } @@ -146,7 +146,7 @@ const nlohmann::json WebSocketServer::loadChaiFile(const nlohmann::json &m_param { if (!m_params.contains("command")) { - DLOG_F(ERROR, "loadChaiFile() : Command is required"); + LOG_F(ERROR, "loadChaiFile() : Command is required"); res["error"] = "Invalid parameters"; res["message"] = "script name is required"; return res; @@ -159,13 +159,13 @@ const nlohmann::json WebSocketServer::loadChaiFile(const nlohmann::json &m_param } catch (const nlohmann::json::exception &e) { - DLOG_F(ERROR, "WebSocketServer::loadChaiFile() json exception: %s", e.what()); + LOG_F(ERROR, "WebSocketServer::loadChaiFile() json exception: %s", e.what()); res["error"] = "Invalid parameters"; res["message"] = e.what(); } catch (const std::exception &e) { - DLOG_F(ERROR, "Error occurred in loadChaiFile: %s", e.what()); + LOG_F(ERROR, "Error occurred in loadChaiFile: %s", e.what()); res["error"] = "StdError"; res["message"] = e.what(); } diff --git a/src/websocket/WsTaskComponent.cpp b/src/websocket/WsTaskComponent.cpp index 82bbe890..ead45c88 100644 --- a/src/websocket/WsTaskComponent.cpp +++ b/src/websocket/WsTaskComponent.cpp @@ -44,14 +44,14 @@ const nlohmann::json WebSocketServer::AddTask(const nlohmann::json &m_params) if (!m_params.contains("device_name") && !m_params.contains("device_uuid")) { res = {{"error", "Invalid Parameters"}, {"message", "Device name or uuid is required"}}; - DLOG_F(ERROR, "WebSocketServer::AddTask() : %s", res.dump().c_str()); + LOG_F(ERROR, "WebSocketServer::AddTask() : %s", res.dump().c_str()); return res; } // 检查任务的来源是否指定,主要是来自设备管理器和插件管理器 if (!m_params.contains("task_origin") || !m_params.contains("task_name")) { res = {{"error", "Invalid Parameters"}, {"message", "Task origin and name are required"}}; - DLOG_F(ERROR, "WebSocketServer::AddTask() : %s", res.dump().c_str()); + LOG_F(ERROR, "WebSocketServer::AddTask() : %s", res.dump().c_str()); return res; } @@ -68,7 +68,7 @@ const nlohmann::json WebSocketServer::AddTask(const nlohmann::json &m_params) if (it == DeviceTypeMap.end()) { res["error"] = "Unsupport device type"; - DLOG_F(ERROR, "Unsupport device type, AddTask() : %s", res.dump().c_str()); + LOG_F(ERROR, "Unsupport device type, AddTask() : %s", res.dump().c_str()); return res; } device_type = it->second; @@ -94,13 +94,13 @@ const nlohmann::json WebSocketServer::AddTask(const nlohmann::json &m_params) } catch (const nlohmann::json::exception &e) { - DLOG_F(ERROR, "WebSocketServer::AddTask() json exception: %s", e.what()); + LOG_F(ERROR, "WebSocketServer::AddTask() json exception: %s", e.what()); res = {{"error", "Invalid Parameters"}, {"message", e.what()}}; } catch (const std::exception &e) { res = {{"error", "Unknown Error"}, {"message", e.what()}}; - DLOG_F(ERROR, "WebSocketServer::AddTask(): %s", e.what()); + LOG_F(ERROR, "WebSocketServer::AddTask(): %s", e.what()); } return res; } @@ -120,18 +120,18 @@ const nlohmann::json WebSocketServer::ExecuteAllTasks(const nlohmann::json &m_pa if (!Lithium::MyApp->executeAllTasks()) { res = {{"error", "Task Failed"}, {"message", "Failed to execute task in sequence"}}; - DLOG_F(ERROR, "WebSocketServer::ExecuteAllTasks : Failed to start executing all tasks"); + LOG_F(ERROR, "WebSocketServer::ExecuteAllTasks : Failed to start executing all tasks"); } } catch (const nlohmann::json::exception &e) { - DLOG_F(ERROR, "WebSocketServer::ExecuteAllTasks() json exception: %s", e.what()); + LOG_F(ERROR, "WebSocketServer::ExecuteAllTasks() json exception: %s", e.what()); res = {{"error", "Invalid Parameters"}, {"message", e.what()}}; } catch (const std::exception &e) { res = {{"error", "Unknown Error"}, {"message", e.what()}}; - DLOG_F(ERROR, "WebSocketServer::ExecuteAllTasks(): %s", e.what()); + LOG_F(ERROR, "WebSocketServer::ExecuteAllTasks(): %s", e.what()); } return res; } @@ -146,18 +146,18 @@ const nlohmann::json WebSocketServer::StopTask(const nlohmann::json &m_params) if (!Lithium::MyApp->stopTask()) { res = {{"error", "Task Failed"}, {"message", "Failed to stop current task"}}; - DLOG_F(ERROR, "WebSocketServer::StopTask(): Failed to stop current task"); + LOG_F(ERROR, "WebSocketServer::StopTask(): Failed to stop current task"); } } catch (const nlohmann::json::exception &e) { - DLOG_F(ERROR, "WebSocketServer::StopTask() json exception: %s", e.what()); + LOG_F(ERROR, "WebSocketServer::StopTask() json exception: %s", e.what()); res = {{"error", "Invalid Parameters"}, {"message", e.what()}}; } catch (const std::exception &e) { res = {{"error", "Unknown Error"}, {"message", e.what()}}; - DLOG_F(ERROR, "WebSocketServer::StopTask(): %s", e.what()); + LOG_F(ERROR, "WebSocketServer::StopTask(): %s", e.what()); } return res; } @@ -170,7 +170,7 @@ const nlohmann::json WebSocketServer::ExecuteTaskByName(const nlohmann::json &m_ if (!m_params.contains("task_name")) { res = {{"error", "Invalid Parameters"}, {"message", "Task name is required"}}; - DLOG_F(ERROR, "WebSocketServer::ExecuteTaskByName() : %s", res.dump().c_str()); + LOG_F(ERROR, "WebSocketServer::ExecuteTaskByName() : %s", res.dump().c_str()); return res; } @@ -180,18 +180,18 @@ const nlohmann::json WebSocketServer::ExecuteTaskByName(const nlohmann::json &m_ if (!Lithium::MyApp->executeTaskByName(task_name)) { res = {{"error", "Task Failed"}, {"message", "Failed to execute specific task"}}; - DLOG_F(ERROR, "WebSocketServer::ExecuteTaskByName(): Failed to execute specific task"); + LOG_F(ERROR, "WebSocketServer::ExecuteTaskByName(): Failed to execute specific task"); } } catch (const nlohmann::json::exception &e) { - DLOG_F(ERROR, "WebSocketServer::ExecuteTaskByName() json exception: %s", e.what()); + LOG_F(ERROR, "WebSocketServer::ExecuteTaskByName() json exception: %s", e.what()); res = {{"error", "Invalid Parameters"}, {"message", e.what()}}; } catch (const std::exception &e) { res = {{"error", "Unknown Error"}, {"message", e.what()}}; - DLOG_F(ERROR, "WebSocketServer::ExecuteTaskByName(): %s", e.what()); + LOG_F(ERROR, "WebSocketServer::ExecuteTaskByName(): %s", e.what()); } return res; } @@ -236,18 +236,18 @@ const nlohmann::json WebSocketServer::SaveTasksToJson(const nlohmann::json &m_pa if (!Lithium::MyApp->saveTasksToJson()) { res = {{"error", "Task Failed"}, {"message", "Failed to save task in sequence to a JSON file"}}; - DLOG_F(ERROR, "WebSocketServer::SaveTasksToJson(): Failed to save task in sequence to a JSON file"); + LOG_F(ERROR, "WebSocketServer::SaveTasksToJson(): Failed to save task in sequence to a JSON file"); } } catch (const nlohmann::json::exception &e) { - DLOG_F(ERROR, "WebSocketServer::SaveTasksToJson() json exception: %s", e.what()); + LOG_F(ERROR, "WebSocketServer::SaveTasksToJson() json exception: %s", e.what()); res = {{"error", "Invalid Parameters"}, {"message", e.what()}}; } catch (const std::exception &e) { res = {{"error", "Unknown Error"}, {"message", e.what()}}; - DLOG_F(ERROR, "WebSocketServer::SaveTasksToJson(): %s", e.what()); + LOG_F(ERROR, "WebSocketServer::SaveTasksToJson(): %s", e.what()); } return res; } \ No newline at end of file diff --git a/src/websocket/device/WsDeviceHub.cpp b/src/websocket/device/WsDeviceHub.cpp index 3aaaa4f0..7515d594 100644 --- a/src/websocket/device/WsDeviceHub.cpp +++ b/src/websocket/device/WsDeviceHub.cpp @@ -1,3 +1,33 @@ +/* + * WsDeviceHub.cpp + * + * Copyright (C) 2023 Max Qian + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +/************************************************* + +Copyright: 2023 Max Qian. All rights reserved + +Author: Max Qian + +E-mail: astro_air@126.com + +Date: 2023-10-20 + +Description: WebSocket Device Hub (all devices of one type in one hub) + +**************************************************/ #include "WsDeviceHub.hpp" @@ -22,7 +52,7 @@ void WsDeviceHub::sendMessage(const oatpp::String &message) } } -void WsDeviceHub::sendBinaryMessage(const void *binary_message, int size) +void WsDeviceHub::sendBinaryMessage(void *binary_message, int size) { std::lock_guard guard(m_deviceByIdLock); for (auto &pair : m_deviceById) diff --git a/src/websocket/device/WsDeviceHub.hpp b/src/websocket/device/WsDeviceHub.hpp index d33aecb5..0ae2b1a2 100644 --- a/src/websocket/device/WsDeviceHub.hpp +++ b/src/websocket/device/WsDeviceHub.hpp @@ -1,3 +1,33 @@ +/* + * WsDeviceHub.hpp + * + * Copyright (C) 2023 Max Qian + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +/************************************************* + +Copyright: 2023 Max Qian. All rights reserved + +Author: Max Qian + +E-mail: astro_air@126.com + +Date: 2023-10-20 + +Description: WebSocket Device Hub (all devices of one type in one hub) + +**************************************************/ #ifndef WSDEVICEHUB_HPP #define WSDEVICEHUB_HPP @@ -46,7 +76,7 @@ class WsDeviceHub * @param binary_message * @param size */ - void sendBinaryMessage(const void *binary_message, int size); + void sendBinaryMessage(void *binary_message, int size); }; #endif // WSDEVICEHUB_HPP diff --git a/src/websocket/device/WsDeviceInstance.cpp b/src/websocket/device/WsDeviceInstance.cpp index fc8b11f2..fcb552f3 100644 --- a/src/websocket/device/WsDeviceInstance.cpp +++ b/src/websocket/device/WsDeviceInstance.cpp @@ -1,7 +1,56 @@ +/* + * WsDeviceInstance.cpp + * + * Copyright (C) 2023 Max Qian + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +/************************************************* + +Copyright: 2023 Max Qian. All rights reserved + +Author: Max Qian + +E-mail: astro_air@126.com + +Date: 2023-10-20 + +Description: WebSocket Device Instance (each device each instance) + +**************************************************/ #include "WsDeviceInstance.hpp" #include "WsDeviceHub.hpp" +#include "loguru/loguru.hpp" +#include "nlohmann/json.hpp" + +WsDeviceInstance::WsDeviceInstance(const std::shared_ptr &socket, + const std::shared_ptr &hub, + const oatpp::String &device_name, + v_int32 userId) + : m_socket(socket), m_hub(hub), m_device_name(device_name), m_userId(userId) +{ + OATPP_LOGD(m_device_name.getValue("").c_str(), "%s created", m_device_name.getValue("").c_str()); + + LiRegisterFunc("getProperty", &WsDeviceInstance::getProperty); + LiRegisterFunc("setProperty", &WsDeviceInstance::setProperty); +} + +WsDeviceInstance::~WsDeviceInstance() +{ +} + void WsDeviceInstance::sendMessage(const oatpp::String &message) { @@ -29,7 +78,7 @@ void WsDeviceInstance::sendMessage(const oatpp::String &message) m_asyncExecutor->execute(&m_writeLock, m_socket, message); } -void WsDeviceInstance::sendBinaryMessage(const void *binary_message, int size) +void WsDeviceInstance::sendBinaryMessage(void *binary_message, int size) { oatpp::String binary((const char *)binary_message, size); class SendMessageCoroutine : public oatpp::async::Coroutine @@ -91,16 +140,77 @@ oatpp::async::CoroutineStarter WsDeviceInstance::readMessage(const std::shared_p if (size == 0) { // message transfer finished - auto wholeMessage = m_messageBuffer.toString(); m_messageBuffer.setCurrentPosition(0); - m_hub->sendMessage(m_device_name + ": " + wholeMessage); + json res; + if (!json::accept(wholeMessage->c_str())) + { + LOG_F(ERROR, "Message is not in JSON format: {}", wholeMessage->c_str()); + res = {{"error", "Invalid Format"}, {"message", "Message is not in JSON format"}}; + } + else + { + try + { + json jdata = json::parse(wholeMessage->c_str()); + try + { + if (jdata.contains("name") && jdata.contains("params")) + { + const std::string name = jdata["name"].get(); + if (m_CommandDispatcher->HasHandler(name)) + { + m_CommandDispatcher->Dispatch(name, jdata["params"]); + } + } + else + { + LOG_F(ERROR, "WebSocketServer::readMessage() missing parameter: name or params"); + res = {{"error", "Invalid Parameters"}, {"message", "Missing parameter: name or params"}}; + } + } + catch (const std::exception &e) + { + LOG_F(ERROR, "WebSocketServer::readMessage() run command failed: {}", e.what()); + res = {{"error", "Running Error"}, {"message", e.what()}}; + } + } + catch (const nlohmann::detail::parse_error &e) + { + LOG_F(ERROR, "WebSocketServer::readMessage() json exception: {}", e.what()); + res = {{"errro", "Invalid Format"}, {"message", e.what()}}; + } + catch (const std::exception &e) + { + LOG_F(ERROR, "WebSocketServer::readMessage() exception: {}", e.what()); + res = {{"errro", "Unknown Error"}, {"message", e.what()}}; + } + } } else if (size > 0) { // message frame received m_messageBuffer.writeSimple(data, size); } - return nullptr; // do nothing +} + +void WsDeviceInstance::setProperty(const json &m_params) +{ + LOG_F(INFO, "Run set property"); + sendMessage("hello"); +} + +void WsDeviceInstance::getProperty(const json &m_params) +{ + LOG_F(INFO, "Run get property"); + sendMessage("hello"); +} + +void WsDeviceInstance::runTask(const json &m_params) +{ +} + +void WsDeviceInstance::runFunc(const json &m_params) +{ } \ No newline at end of file diff --git a/src/websocket/device/WsDeviceInstance.hpp b/src/websocket/device/WsDeviceInstance.hpp index a0fdac6f..a5068443 100644 --- a/src/websocket/device/WsDeviceInstance.hpp +++ b/src/websocket/device/WsDeviceInstance.hpp @@ -1,3 +1,33 @@ +/* + * WsDeviceInstance.hpp + * + * Copyright (C) 2023 Max Qian + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +/************************************************* + +Copyright: 2023 Max Qian. All rights reserved + +Author: Max Qian + +E-mail: astro_air@126.com + +Date: 2023-10-20 + +Description: WebSocket Device Instance (each device each instance) + +**************************************************/ #ifndef WSDEVICEINSTANCE_HPP #define WSDEVICEINSTANCE_HPP @@ -23,60 +53,20 @@ #include "nlohmann/json.hpp" +using json = nlohmann::json; + class WsDeviceHub; // FWD class WsDeviceInstance : public oatpp::websocket::AsyncWebSocket::Listener { -private: - /** - * Buffer for messages. Needed for multi-frame messages. - */ - oatpp::data::stream::BufferOutputStream m_messageBuffer; - - /** - * Lock for synchronization of writes to the web socket. - */ - oatpp::async::Lock m_writeLock; - - std::unique_ptr m_CommandDispatcher; - - template - void LiRegisterFunc(const std::string &name, const nlohmann::json (ClassType::*handler)(const nlohmann::json &)) - { - m_CommandDispatcher->RegisterHandler(name, handler, this); - } - - bool LiRunFunc(const std::string &name, const nlohmann::json ¶ms) - { - if (m_CommandDispatcher->HasHandler(name)) - { - m_CommandDispatcher->Dispatch(name, params); - return true; - } - return false; - } - -private: - std::shared_ptr m_socket; - std::shared_ptr m_hub; - oatpp::String m_device_name; - v_int32 m_userId; - -private: - /** - * Inject async executor object. - */ - OATPP_COMPONENT(std::shared_ptr, m_asyncExecutor); public: WsDeviceInstance(const std::shared_ptr &socket, const std::shared_ptr &hub, const oatpp::String &device_name, - v_int32 userId) - : m_socket(socket), m_hub(hub), m_device_name(device_name), m_userId(userId) - { - OATPP_LOGD(m_device_name.getValue("").c_str(), "%s created", m_device_name.getValue("").c_str()); - } + v_int32 userId); + + ~WsDeviceInstance(); /** * Send message to WsDeviceInstance (to user). @@ -84,7 +74,7 @@ class WsDeviceInstance : public oatpp::websocket::AsyncWebSocket::Listener */ void sendMessage(const oatpp::String &message); - void sendBinaryMessage(const void *binary_message, int size); + void sendBinaryMessage(void *binary_message, int size); /** * Get hub of the WsDeviceInstance. @@ -105,15 +95,58 @@ class WsDeviceInstance : public oatpp::websocket::AsyncWebSocket::Listener v_int32 getUserId(); public: - const nlohmann::json setProperty(const nlohmann::json &m_params); - const nlohmann::json getProperty(const nlohmann::json &m_params); - const nlohmann::json runTask(const nlohmann::json &m_params); + void setProperty(const json &m_params); + void getProperty(const json &m_params); + void runTask(const json &m_params); + void runFunc(const json &m_params); public: // WebSocket Listener methods CoroutineStarter onPing(const std::shared_ptr &socket, const oatpp::String &message) override; CoroutineStarter onPong(const std::shared_ptr &socket, const oatpp::String &message) override; CoroutineStarter onClose(const std::shared_ptr &socket, v_uint16 code, const oatpp::String &message) override; CoroutineStarter readMessage(const std::shared_ptr &socket, v_uint8 opcode, p_char8 data, oatpp::v_io_size size) override; + +private: + /** + * Buffer for messages. Needed for multi-frame messages. + */ + oatpp::data::stream::BufferOutputStream m_messageBuffer; + + /** + * Lock for synchronization of writes to the web socket. + */ + oatpp::async::Lock m_writeLock; + + std::unique_ptr m_CommandDispatcher; + + template + void LiRegisterFunc(const std::string &name, void (ClassType::*handler)(const json &)) + { + m_CommandDispatcher->RegisterHandler(name, handler, this); + } + + bool LiRunFunc(const std::string &name, const json ¶ms) + { + if (m_CommandDispatcher->HasHandler(name)) + { + m_CommandDispatcher->Dispatch(name, params); + return true; + } + return false; + } + +private: + std::shared_ptr m_socket; + std::shared_ptr m_hub; + oatpp::String m_device_name; + v_int32 m_userId; + +private: + /** + * Inject async executor object. + */ + OATPP_COMPONENT(std::shared_ptr, m_asyncExecutor); + }; #endif // WSDEVICEINSTANCE_HPP diff --git a/src/websocket/device/WsDeviceServer.cpp b/src/websocket/device/WsDeviceServer.cpp index dceb2420..9ca6bb3f 100644 --- a/src/websocket/device/WsDeviceServer.cpp +++ b/src/websocket/device/WsDeviceServer.cpp @@ -1,3 +1,33 @@ +/* + * WsDeviceServer.cpp + * + * Copyright (C) 2023 Max Qian + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +/************************************************* + +Copyright: 2023 Max Qian. All rights reserved + +Author: Max Qian + +E-mail: astro_air@126.com + +Date: 2023-10-20 + +Description: WebSocket Device Server + +**************************************************/ #include "WsDeviceServer.hpp" diff --git a/src/websocket/device/WsDeviceServer.hpp b/src/websocket/device/WsDeviceServer.hpp index af2622aa..d2b125ee 100644 --- a/src/websocket/device/WsDeviceServer.hpp +++ b/src/websocket/device/WsDeviceServer.hpp @@ -1,3 +1,33 @@ +/* + * WsDeviceServer.hpp + * + * Copyright (C) 2023 Max Qian + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +/************************************************* + +Copyright: 2023 Max Qian. All rights reserved + +Author: Max Qian + +E-mail: astro_air@126.com + +Date: 2023-10-20 + +Description: WebSocket Device Server + +**************************************************/ #ifndef WSDEVICESERVER_HPP #define WSDEVICESERVER_HPP