From 2c646bcbcb0509b1a91c8ba5924f47aff368350f Mon Sep 17 00:00:00 2001 From: coffee Date: Sat, 5 Aug 2023 18:56:20 +0800 Subject: [PATCH] =?UTF-8?q?1.=20V1.0.0.0=E7=89=88=E6=9C=AC=E5=AE=8C?= =?UTF-8?q?=E6=88=90?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- CMakeLists.txt | 68 + Protocol/CMakeLists.txt | 38 + Protocol/HDSDK.cpp | 843 +++++++++ Protocol/HDSDK.h | 193 ++ SDK/Data/HEthernetInfo.cpp | 124 ++ SDK/Data/HEthernetInfo.h | 114 ++ SDK/Data/HGeneralInfo.cpp | 94 + SDK/Data/HGeneralInfo.h | 137 ++ SDK/Data/HLightInfo.cpp | 67 + SDK/Data/HLightInfo.h | 60 + SDK/Data/HOTherInfo.cpp | 36 + SDK/Data/HOTherInfo.h | 51 + SDK/Data/HSDKInfo.cpp | 69 + SDK/Data/HSDKInfo.h | 51 + SDK/Data/HScreenFunctionInfo.cpp | 127 ++ SDK/Data/HScreenFunctionInfo.h | 64 + SDK/Data/HSensorInfo.cpp | 132 ++ SDK/Data/HSensorInfo.h | 119 ++ SDK/Data/HTimeInfo.cpp | 37 + SDK/Data/HTimeInfo.h | 50 + SDK/HCatBuffer.h | 588 ++++++ SDK/HXml.cpp | 350 ++++ SDK/HXml.h | 452 +++++ SDK/SDKInfo.cpp | 833 +++++++++ SDK/SDKInfo.h | 267 +++ SDK/tinyxml2.cpp | 2994 ++++++++++++++++++++++++++++++ SDK/tinyxml2.h | 2380 ++++++++++++++++++++++++ demo/eth.cpp | 111 ++ demo/lightInfo.cpp | 122 ++ demo/sendFile.cpp | 129 ++ demo/sendXml.cpp | 102 + demo/systemVolume.cpp | 118 ++ demo/tcpServer.cpp | 108 ++ demo/time.cpp | 114 ++ 34 files changed, 11142 insertions(+) create mode 100644 CMakeLists.txt create mode 100644 Protocol/CMakeLists.txt create mode 100644 Protocol/HDSDK.cpp create mode 100644 Protocol/HDSDK.h create mode 100644 SDK/Data/HEthernetInfo.cpp create mode 100644 SDK/Data/HEthernetInfo.h create mode 100644 SDK/Data/HGeneralInfo.cpp create mode 100644 SDK/Data/HGeneralInfo.h create mode 100644 SDK/Data/HLightInfo.cpp create mode 100644 SDK/Data/HLightInfo.h create mode 100644 SDK/Data/HOTherInfo.cpp create mode 100644 SDK/Data/HOTherInfo.h create mode 100644 SDK/Data/HSDKInfo.cpp create mode 100644 SDK/Data/HSDKInfo.h create mode 100644 SDK/Data/HScreenFunctionInfo.cpp create mode 100644 SDK/Data/HScreenFunctionInfo.h create mode 100644 SDK/Data/HSensorInfo.cpp create mode 100644 SDK/Data/HSensorInfo.h create mode 100644 SDK/Data/HTimeInfo.cpp create mode 100644 SDK/Data/HTimeInfo.h create mode 100644 SDK/HCatBuffer.h create mode 100644 SDK/HXml.cpp create mode 100644 SDK/HXml.h create mode 100644 SDK/SDKInfo.cpp create mode 100644 SDK/SDKInfo.h create mode 100644 SDK/tinyxml2.cpp create mode 100644 SDK/tinyxml2.h create mode 100644 demo/eth.cpp create mode 100644 demo/lightInfo.cpp create mode 100644 demo/sendFile.cpp create mode 100644 demo/sendXml.cpp create mode 100644 demo/systemVolume.cpp create mode 100644 demo/tcpServer.cpp create mode 100644 demo/time.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt new file mode 100644 index 0000000..324b403 --- /dev/null +++ b/CMakeLists.txt @@ -0,0 +1,68 @@ +cmake_minimum_required(VERSION 3.5) + +# 设置交叉编译器 +#set(CMAKE_CXX_COMPILER /tmp/g++) +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fPIC") + +project(HDSDK LANGUAGES CXX) + +set(CMAKE_CXX_STANDARD 11) + +add_subdirectory(Protocol) + +set(ENABLE_DEMO OFF) +if(ENABLE_DEMO) + add_executable(sendXml demo/sendXml.cpp) + target_include_directories(sendXml PUBLIC + ${CMAKE_CURRENT_SOURCE_DIR} + ${CMAKE_CURRENT_SOURCE_DIR}/Protocol + ) + target_link_libraries(sendXml PRIVATE HDSDK) + + add_executable(sendFile demo/sendFile.cpp) + target_include_directories(sendFile PUBLIC + ${CMAKE_CURRENT_SOURCE_DIR} + ${CMAKE_CURRENT_SOURCE_DIR}/Protocol + ) + target_link_libraries(sendFile PRIVATE HDSDK) + + add_executable(lightInfo demo/lightInfo.cpp) + target_include_directories(lightInfo PUBLIC + ${CMAKE_CURRENT_SOURCE_DIR} + ${CMAKE_CURRENT_SOURCE_DIR}/Protocol + ${CMAKE_CURRENT_SOURCE_DIR}/SDK + ) + target_link_libraries(lightInfo PRIVATE HDSDK) + + add_executable(systemVolume demo/systemVolume.cpp) + target_include_directories(systemVolume PUBLIC + ${CMAKE_CURRENT_SOURCE_DIR} + ${CMAKE_CURRENT_SOURCE_DIR}/Protocol + ${CMAKE_CURRENT_SOURCE_DIR}/SDK + ) + target_link_libraries(systemVolume PRIVATE HDSDK) + + add_executable(tcpServer demo/tcpServer.cpp) + target_include_directories(tcpServer PUBLIC + ${CMAKE_CURRENT_SOURCE_DIR} + ${CMAKE_CURRENT_SOURCE_DIR}/Protocol + ${CMAKE_CURRENT_SOURCE_DIR}/SDK + ) + target_link_libraries(tcpServer PRIVATE HDSDK) + + add_executable(time demo/time.cpp) + target_include_directories(time PUBLIC + ${CMAKE_CURRENT_SOURCE_DIR} + ${CMAKE_CURRENT_SOURCE_DIR}/Protocol + ${CMAKE_CURRENT_SOURCE_DIR}/SDK + ) + target_link_libraries(time PRIVATE HDSDK) + + add_executable(eth demo/eth.cpp) + target_include_directories(eth PUBLIC + ${CMAKE_CURRENT_SOURCE_DIR} + ${CMAKE_CURRENT_SOURCE_DIR}/Protocol + ${CMAKE_CURRENT_SOURCE_DIR}/SDK + ) + target_link_libraries(eth PRIVATE HDSDK) +endif() diff --git a/Protocol/CMakeLists.txt b/Protocol/CMakeLists.txt new file mode 100644 index 0000000..4f019d4 --- /dev/null +++ b/Protocol/CMakeLists.txt @@ -0,0 +1,38 @@ +cmake_minimum_required(VERSION 3.5) + +project(HDSDK LANGUAGES CXX) + +set(CMAKE_CXX_STANDARD 11) + +set(ENABLE_SDK ON) +if (ENABLE_SDK) + list(APPEND SDK_FILES + ${CMAKE_CURRENT_SOURCE_DIR}/../SDK/tinyxml2.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/../SDK/HXml.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/../SDK/SDKInfo.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/../SDK/Data/HSDKInfo.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/../SDK/Data/HEthernetInfo.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/../SDK/Data/HGeneralInfo.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/../SDK/Data/HLightInfo.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/../SDK/Data/HOTherInfo.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/../SDK/Data/HScreenFunctionInfo.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/../SDK/Data/HSDKInfo.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/../SDK/Data/HSensorInfo.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/../SDK/Data/HTimeInfo.cpp + ) +endif() + +add_library(HDSDK SHARED + HDSDK.cpp + ${SDK_FILES} +) + +if (ENABLE_SDK) + target_include_directories(HDSDK PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/../SDK) + target_include_directories(HDSDK PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/../SDK/Data) +endif() + +target_include_directories(HDSDK PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}) +target_link_libraries(HDSDK PRIVATE -static-libgcc -static-libstdc++) +set_target_properties(HDSDK PROPERTIES LINK_FLAGS "-nodefaultlibs") +add_definitions(-DUSE_HD_LIB) diff --git a/Protocol/HDSDK.cpp b/Protocol/HDSDK.cpp new file mode 100644 index 0000000..446d89b --- /dev/null +++ b/Protocol/HDSDK.cpp @@ -0,0 +1,843 @@ + + +#include "HDSDK.h" + +#include +#include +#include +#include +#include +#include + + +#define MD5_LENGHT (32) +#define XML_MAX (9200) +#define LOCAL_TCP_VERSION (0x1000009) +#define LOCAL_UDP_VERSION (0x1000009) + + +typedef unsigned long long huint64; +typedef unsigned int huint32; +typedef unsigned short huint16; +typedef unsigned char huint8; + +typedef long long hint64; +typedef int hint32; +typedef short hint16; +typedef char hint8; +typedef float hfloat; +typedef double hdouble; + + + +namespace detail +{ + + +enum eHCmdType +{ + kTcpHeartbeatAsk = 0x005f, ///< TCP心跳包请求 + kTcpHeartbeatAnswer = 0x0060, ///< TCP心跳包反馈 + kSearchDeviceAsk = 0x1001, ///< 搜索设备请求 + kSearchDeviceAnswer = 0x1002, ///< 搜索设备应答 + kErrorAnswer = 0x2000, ///< 出错反馈 + + kSDKServiceAsk = 0x2001, ///< 版本协商请求 + kSDKServiceAnswer = 0x2002, ///< 版本协商应答 + kSDKCmdAsk = 0x2003, ///< sdk命令请求 + kSDKCmdAnswer = 0x2004, ///< sdk命令反馈 + kFileStartAsk = 0x8001, ///< 文件开始传输请求 + kFileStartAnswer = 0x8002, ///< 文件开始传输应答 + kFileContentAsk = 0x8003, ///< 携带文件内容的请求 + kFileContentAnswer = 0x8004, ///< 写文件内容的应答 + kFileEndAsk = 0x8005, ///< 文件结束传输请求 + kFileEndAnswer = 0x8006, ///< 文件结束传输应答 + kReadFileAsk = 0x8007, ///< 回读文件请求 + kReadFileAnswer = 0x8008, ///< 回读文件应答 +}; + + +template +class HCallBack +{ +public: + HCallBack() + : userData_(nullptr) + {} + + void Bind(const std::function<_Func> &func) { + callBack_ = func; + } + + void ClearFunc() { callBack_ = std::function<_Func>();} + + void SetUserData(void *userData) { + userData_ = userData; + } + + template +#if __cplusplus >= 201402L + decltype(auto) +#else + typename std::result_of(_Args..., void *)>::type +#endif + Emit(_Args &&...args) { + auto func(callBack_); + return func(std::forward<_Args>(args)..., userData_); + } + + template +#if __cplusplus >= 201402L + decltype(auto) +#else + typename std::result_of(_Args..., void *)>::type +#endif + operator()(_Args &&...args) { + return this->Emit(std::forward<_Args>(args)...); + } + + bool IsCanUse() const { return bool(callBack_); } + +private: + std::function<_Func> callBack_; + void *userData_; +}; + + +class HAny +{ +private: + struct DataBase; + using DataBasePtrType = std::shared_ptr; + struct DataBase{ + virtual ~DataBase() {} + virtual DataBasePtrType Clone() const = 0; + virtual const std::type_info &Type() const = 0; + }; + + template + struct Data : public DataBase + { + template + Data(Args&&...args) : data(std::forward(args)...){ } + + virtual DataBasePtrType Clone() const override { return DataBasePtrType(new Data(data)); } + virtual const std::type_info &Type() const override { return typeid(_T); } + + _T data; + }; + + DataBasePtrType Clone() const { + if (data_) { + return data_->Clone(); + } + return nullptr; + } +public: + HAny() {} + HAny(const HAny &other) : data_(other.data_) {} + template ::type, HAny>::value, _T>::type> + HAny(_T &&t) : data_(new Data::type>(std::forward<_T>(t))) {} + + const std::type_info &Type() const { return data_ ? data_->Type() : typeid(void); } + + template + bool IsType() const { return Type() == typeid(_T); } + + template + _T& Cast() const { + Detach(); + auto p = static_cast::type>*>(this->data_.get()); + return p->data; + } + +private: + void Detach() const { + if (!data_ || data_.unique()) { + return ; + } + + data_ = data_->Clone(); + } + +private: + mutable DataBasePtrType data_; +}; + + +template +std::string IconvStr(_T value) { + std::string ret; + for (std::size_t i = 0; i < sizeof(_T); ++i) { + ret.push_back(char(value & 0xff)); + value = value >> 8; + } + return ret; +} + +template +_T StrIconv(const char *value, std::size_t len = std::numeric_limits::max()) { + _T ret = _T(); + for (std::size_t i = 0; i < sizeof(typename std::remove_cv<_T>::type) && i < len; ++i) { + ret = ret | ((value[i] & 0xff) << (8 * i)); + } + return ret; +} + +template +_T StrIconv(const std::string &value) { return StrIconv<_T>(value.data(), value.size()); } + + +static std::list SplitSdkData(const std::string &xml) +{ + std::list queue; + int size = static_cast(xml.size()); + huint32 index = 0; + + for (; size > XML_MAX; size -= XML_MAX, index += XML_MAX){ + std::string data = IconvStr(12 + XML_MAX); + data.append(IconvStr(kSDKCmdAsk)); + data.append(IconvStr(xml.size())); + data.append(IconvStr(index)); + data.append(xml.data() + index, XML_MAX); + + queue.emplace_back(std::move(data)); + } + + if (size > 0){ + std::string data = IconvStr(12 + static_cast(size)); + data.append(IconvStr(kSDKCmdAsk)); + data.append(IconvStr(xml.size())); + data.append(IconvStr(index)); + data.append(xml.data() + index, size); + + queue.emplace_back(std::move(data)); + } + + return queue; +} + +static std::list SplitFileData(const char *fileData, int size) +{ + std::list queue; + huint32 index = 0; + + for (; size > XML_MAX; size -= XML_MAX, index += XML_MAX){ + std::string data = IconvStr(4 + XML_MAX); + data.append(IconvStr(kFileContentAsk)); + data.append(fileData + index, XML_MAX); + + queue.emplace_back(std::move(data)); + } + + if (size > 0){ + std::string data = IconvStr(4 + static_cast(size)); + data.append(IconvStr(kFileContentAsk)); + data.append(fileData + index, size); + + queue.emplace_back(std::move(data)); + } + + return queue; +} + + +static std::string &Remove(std::string &buff, std::size_t index, std::size_t num = std::string::npos) { + if (index > buff.size()) { + index = buff.size(); + } + + return buff.erase(index, num); +} + +static std::string Mid(const std::string &buff, std::size_t index, std::size_t len = std::string::npos) { + if (index >= buff.size()) { + return std::string(); + } + + if (len > buff.size()) { + len = buff.size(); + } + + if (len > buff.size() - index) { + len = buff.size() - index; + } + + if (index == 0 && len == buff.size()) { + return buff; + } + + return buff.substr(index, len); +} + + +static std::string GetXmlAttribute(const std::string &xml, const std::string &node, const std::string &attributeName) { + std::string nodeName = "<" + node; + std::string::size_type pos = xml.find(nodeName); + if (pos == std::string::npos) { + return ""; + } + + pos = xml.find(attributeName, pos + nodeName.size()); + if (pos == std::string::npos) { + return ""; + } + + pos = xml.find('"', pos + attributeName.size()); + if (pos == std::string::npos) { + return ""; + } + + ++pos; + std::string::size_type posEnd = xml.find('"', pos); + if (posEnd == std::string::npos) { + return ""; + } + + return xml.substr(pos, posEnd - pos); +} + +static std::string SetXmlAttribute(const std::string &xml, const std::string &node, const std::string &attributeName, const std::string &attributeValue) { + std::string nodeName = "<" + node; + std::string::size_type pos = xml.find(nodeName); + if (pos == std::string::npos) { + return xml; + } + + pos = xml.find(attributeName, pos + nodeName.size()); + if (pos == std::string::npos) { + return xml; + } + + pos = xml.find('"', pos + attributeName.size()); + if (pos == std::string::npos) { + return xml; + } + + ++pos; + std::string::size_type posEnd = xml.find('"', pos); + if (posEnd == std::string::npos) { + return xml; + } + + std::string result = xml; + return result.replace(pos, posEnd - pos, attributeValue); +} + + +struct DelaySend { + int cmd; + std::string data; + detail::HAny userData; + DelaySend() + : cmd(0) + {} + + DelaySend(int c, const std::string &d, const detail::HAny &u) + : cmd(c) + , data(d) + , userData(u) + {} + DelaySend(int c, std::string &&d, detail::HAny &&u) + : cmd(c) + , data(std::move(d)) + , userData(std::move(u)) + {} +}; + + +struct SendFileInfo { + hint64 index; + hint64 size; + hint16 type; + std::string md5; + std::string name; + std::function call; + void *userData; + + SendFileInfo() + : index(0) + , size(0) + , type(0) + , userData(nullptr) + {} + + void Clear() { + index = 0; + size = 0; + type = 0; + md5.clear(); + name.clear(); + call = std::function(); + userData = nullptr; + } +}; + + +///< 绑定成员函数的回调 +template +std::function<_Ret(_Args...)> BindMember(_Obj *obj, _Ret(_Obj::*func)(_Args...)) +{ + return [&](_Args &&...args) { + return (obj->*func)(std::forward<_Args>(args)...); + }; +} + +///< 绑定普通函数的回调 +template +std::function<_Ret(_Args...)> BindFunc(_Ret(*func)(_Args...)) +{ + return [&](_Args &&...args) { + return func(std::forward<_Args>(args)...); + }; +} + + +} + + +namespace hd +{ + + +///< SDK私有数据类, 用于保留接口一致 +class HDSDKPrivate +{ +public: + detail::HCallBack NotifyReadXml; + detail::HCallBack NotifySendData; + detail::HCallBack NotifySendFile; + +public: + enum eCmd { + kInitRun, ///< 初始化协商 + kReadData, ///< 读取数据 + kSendSDK, ///< 发送xml + kSendFile, ///< 发送文件 + }; + +public: + HDSDKPrivate() { Init(); } + + void Init(); + bool Dispose(int cmd, const std::string &data, const detail::HAny &userData = detail::HAny()); + +private: + bool ParseReadData(const std::string &data); + bool ParseNegotiate(int num); + bool ParseSDKCmdAnswer(std::string &&data); + bool ParseSendSDK(int cmd, const std::string &data, const detail::HAny &userData); + bool ParseFileStartAnswer(std::string &&buff); + bool SendFileEnd(); + bool DelaySend(); + + ///< 通知回调接口处理任务 + bool SendData(const std::string &data) { return SendData(data.c_str(), data.size()); } + bool SendData(const char *data, int len); + void ReadXml(const std::string &xml, int errorCode); + int SendFile(hint64 index, hint64 size, int status, char *buff, int buffSize); + +private: + friend class HDSDK; + std::string guid_; ///< 通信的guid + std::string sdkBuff_; ///< sdk xml缓存 + std::string readBuff_; ///< 总数据缓存 + std::list delaySendList_; ///< 延迟发送队列 + detail::SendFileInfo fileInfo_; ///< 发送文件信息 + bool negotiate_; ///< 协商状态 + bool processing_; ///< 发送文件中独占 +}; + +void HDSDKPrivate::Init() +{ + guid_.clear(); + negotiate_ = false; + processing_ = false; + delaySendList_.clear(); + std::string().swap(sdkBuff_); + std::string().swap(readBuff_); +} + +bool HDSDKPrivate::Dispose(int cmd, const std::string &data, const detail::HAny &userData) +{ + switch (cmd) { + case kInitRun: { + return ParseNegotiate(0); + } break; + case kReadData: { + return ParseReadData(data); + } break; + default: + break; + } + + if (processing_) { + delaySendList_.emplace_back(detail::DelaySend(cmd, data, userData)); + return true; + } + + switch (cmd) { + case kSendSDK: { + return ParseSendSDK(cmd, data, userData); + } break; + case kSendFile: { + if (negotiate_ == false) { + delaySendList_.emplace_back(detail::DelaySend(cmd, data, userData)); + return true; + } + + if (userData.IsType() == false) { + return false; + } + + fileInfo_ = userData.Cast(); + if (fileInfo_.size <= 0 || fileInfo_.md5.empty() || fileInfo_.name.empty()) { + return false; + } + + if (fileInfo_.md5.size() < MD5_LENGHT) { + fileInfo_.md5.append(MD5_LENGHT - fileInfo_.md5.size(), '\0'); + } + + NotifySendFile.Bind(fileInfo_.call); + NotifySendFile.SetUserData(fileInfo_.userData); + + std::string sendData = detail::IconvStr(47 + fileInfo_.name.size() + 1); + sendData.append(detail::IconvStr(detail::kFileStartAsk)); + sendData.append(fileInfo_.md5); + sendData.append(1, '\0'); + sendData.append(detail::IconvStr(fileInfo_.size)); + sendData.append(detail::IconvStr(fileInfo_.type)); + sendData.append(fileInfo_.name); + sendData.append(1, '\0'); + if (SendData(sendData) == false) { + return false; + } + + processing_ = true; + return true; + } break; + default: + break; + } + + return false; +} + +bool HDSDKPrivate::ParseReadData(const std::string &data) +{ + if (data.empty() == false) { + readBuff_.append(data); + } + + if (readBuff_.size() < 4) { + return true; + } + + std::size_t len = detail::StrIconv(readBuff_.c_str(), readBuff_.size()); + int cmd = detail::StrIconv(readBuff_.c_str() + 2, readBuff_.size() - 2); + if (len > readBuff_.size()) { + return true; + } + + if (len == 0) { + return false; + } + + std::string buff = detail::Mid(data, 0, len); + detail::Remove(readBuff_, 0, len); + + bool result = true; + switch (cmd) { + case detail::kTcpHeartbeatAsk: + case detail::kTcpHeartbeatAnswer: { + std::string sendData = detail::IconvStr(4); + sendData.append(detail::IconvStr(detail::kTcpHeartbeatAsk)); + result = SendData(sendData); + } break; + case detail::kSDKServiceAnswer: { + result = ParseNegotiate(1); + } break; + case detail::kSDKCmdAnswer: { + result = ParseSDKCmdAnswer(std::move(buff)); + } break; + case detail::kErrorAnswer: { + if (buff.size() < 6) { + return false; + } + ReadXml("", detail::StrIconv(buff.c_str() + 4, buff.size() - 4)); + } break; + case detail::kFileStartAnswer: { + result = ParseFileStartAnswer(std::move(buff)); + } break; + case detail::kFileContentAnswer: + break; + case detail::kFileEndAnswer: { + SendFile(fileInfo_.index, fileInfo_.size, 0, nullptr, 0); + processing_ = false; + result = DelaySend(); + } break; + default: + break; + } + + if (result && readBuff_.empty() == false) { + return ParseReadData(""); + } + + return result; +} + +bool HDSDKPrivate::ParseNegotiate(int num) +{ + std::string data; + if (num == 0) { + data.append(detail::IconvStr(8)); + data.append(detail::IconvStr(detail::kSDKServiceAsk)); + data.append(detail::IconvStr(LOCAL_TCP_VERSION)); + } else { + std::string xml(R"( + + + + +)"); + + data = detail::SplitSdkData(xml).front(); + } + + return SendData(data); +} + +bool HDSDKPrivate::ParseSDKCmdAnswer(std::string &&data) +{ + if (data.size() < 12) { + return false; + } + +// int len = detail::StrIconv(data.c_str()); +// int cmd = detail::StrIconv(data.c_str() + 2, data.size() - 2); + huint32 total = detail::StrIconv(data.c_str() + 4, data.size() - 4); +// int index = detail::StrIconv(data.c_str() + 8, data.size() - 8); + detail::Remove(data, 0, 12); + + if (negotiate_ == false) { + guid_ = detail::GetXmlAttribute(data, "sdk", "guid"); + negotiate_ = true; + return DelaySend(); + } + + if (data.empty()) { + return true; + } + + sdkBuff_.append(data); + if (total <= sdkBuff_.size()) { + std::string buff(std::move(sdkBuff_)); + sdkBuff_.clear(); + ReadXml(buff, 0); + } + + return true; +} + +bool HDSDKPrivate::ParseSendSDK(int cmd, const std::string &data, const detail::HAny &userData) +{ + if (negotiate_ == false) { + delaySendList_.emplace_back(detail::DelaySend(cmd, data, userData)); + return true; + } + + if (data.empty()) { + return true; + } + + std::string xml = detail::SetXmlAttribute(data, "sdk", "guid", guid_); + auto xmlList = detail::SplitSdkData(xml); + for (const auto &i : xmlList) { + if (SendData(i) == false) { + return false; + } + } + + return true; +} + +bool HDSDKPrivate::ParseFileStartAnswer(std::string &&buff) +{ + if (buff.size() < 14) { + return false; + } + + processing_ = true; + huint16 status = detail::StrIconv(buff.c_str() + 4, buff.size() - 4); + fileInfo_.index = detail::StrIconv(buff.c_str() + 6, buff.size() - 6); + if (status != 0) { + SendFile(fileInfo_.index, fileInfo_.size, status, nullptr, 0); + processing_ = false; + return DelaySend(); + } + + std::vector sendBuff(XML_MAX, '\0'); + while (fileInfo_.index < fileInfo_.size) { + int len = SendFile(fileInfo_.index, fileInfo_.size, status, sendBuff.data(), sendBuff.size()); + if (len <= 0) { + processing_ = false; + return false; + } + + fileInfo_.index += len; + auto sendList = detail::SplitFileData(sendBuff.data(), len); + for (const auto &i : sendList) { + if (SendData(i) == false) { + processing_ = false; + return false; + } + } + } + + return SendFileEnd(); +} + +bool HDSDKPrivate::SendFileEnd() +{ + std::string data = detail::IconvStr(4); + data.append(detail::IconvStr(detail::kFileEndAsk)); + return SendData(data); +} + +bool HDSDKPrivate::DelaySend() +{ + std::list sendList; + sendList.swap(delaySendList_); + while (sendList.empty() == false) { + if (processing_) { + delaySendList_.splice(delaySendList_.begin(), std::move(sendList)); + break; + } + + detail::DelaySend i = std::move(sendList.front()); + sendList.pop_front(); + if (Dispose(i.cmd, i.data, i.userData) == false) { + delaySendList_.clear(); + return false; + } + } + + return true; +} + +bool HDSDKPrivate::SendData(const char *data, int len) +{ + if (NotifySendData.IsCanUse() == false) { + return false; + } + + return NotifySendData(data, len); +} + +void HDSDKPrivate::ReadXml(const std::string &xml, int errorCode) +{ + if (NotifyReadXml.IsCanUse() == false) { + return ; + } + NotifyReadXml(xml.c_str(), xml.size(), errorCode); +} + +int HDSDKPrivate::SendFile(hint64 index, hint64 size, int status, char *buff, int buffSize) +{ + if (NotifySendFile.IsCanUse() == false) { + return -1; + } + + return NotifySendFile(index, size, status, buff, buffSize); +} + + +} + +IHDProtocol CreateProtocol() +{ + return new hd::HDSDKPrivate(); +} + +void FreeProtocol(IHDProtocol protocol) +{ + delete protocol; +} + +HBool SetProtocolFunc(IHDProtocol protocol, int func, void *data) +{ + if (protocol == nullptr) { + return HFalse; + } + + switch (func) { + case kSetReadXml: { + if (data) { + protocol->NotifyReadXml.Bind(reinterpret_cast(data)); + } else { + protocol->NotifyReadXml.ClearFunc(); + } + } break; + case kSetReadXmlData: { + protocol->NotifyReadXml.SetUserData(data); + } break; + case kSetSendFunc: { + if (data) { + protocol->NotifySendData.Bind(reinterpret_cast(data)); + } else { + protocol->NotifySendData.ClearFunc(); + } + } break; + case kSetSendFuncData: { + protocol->NotifySendData.SetUserData(data); + } break; + default: + return HFalse; + break; + } + + return HTrue; +} + +void InitProtocol(hd::IHDProtocol protocol) +{ + protocol->Init(); +} + +HBool RunProtocol(hd::IHDProtocol protocol) +{ + return protocol->Dispose(hd::HDSDKPrivate::kInitRun, "") ? HTrue : HFalse; +} + +HBool UpdateReadData(hd::IHDProtocol protocol, const char *data, int len) +{ + return protocol->Dispose(hd::HDSDKPrivate::kReadData, std::string(data, len)) ? HTrue : HFalse; +} + +HBool SendXml(hd::IHDProtocol protocol, const char *xml, int len) +{ + return protocol->Dispose(hd::HDSDKPrivate::kSendSDK, std::string(xml, len)) ? HTrue : HFalse; +} + +HBool SendFile(hd::IHDProtocol protocol, const char *fileName, int fileNameLen, const char *md5, int type, hint64 size, int (*callFun)(hint64, hint64, int, char *, int, void *), void *userData) +{ + detail::SendFileInfo info; + info.size = size; + info.type = type; + info.md5.assign(md5); + info.name.assign(fileName, fileNameLen); + info.call = callFun; + info.userData = userData; + + if (info.md5.empty() || info.md5.size() != MD5_LENGHT) { + return HFalse; + } + + if (info.name.empty()) { + return HFalse; + } + + return protocol->Dispose(hd::HDSDKPrivate::kSendFile, "", info) ? HTrue : HFalse; +} diff --git a/Protocol/HDSDK.h b/Protocol/HDSDK.h new file mode 100644 index 0000000..d1d5f38 --- /dev/null +++ b/Protocol/HDSDK.h @@ -0,0 +1,193 @@ + + +#ifndef __HDSDK_H__ +#define __HDSDK_H__ + + +#if defined(_MSC_VER) || defined(WIN64) || defined(_WIN64) || defined(__WIN64__) || defined(WIN32) || defined(_WIN32) || defined(__WIN32__) || defined(__NT__) +# define H_DECL_EXPORT __declspec(dllexport) +# define H_DECL_IMPORT __declspec(dllimport) +# define DLL_CALL __cdecl +# define H_WIN +#else +# define H_DECL_EXPORT __attribute__((visibility("default"))) +# define H_DECL_IMPORT __attribute__((visibility("default"))) +# define DLL_CALL +// __attribute__((__cdecl__)) +# define H_LINUX +#endif + +#ifdef STATIC_IMPORT +#ifdef H_DECL_IMPORT +#undef H_DECL_IMPORT +#define H_DECL_IMPORT +#endif +#endif + +#if defined(USE_HD_LIB) +# define HD_API H_DECL_EXPORT +#else +# define HD_API H_DECL_IMPORT +#endif + + +#if (defined(__cpp_exceptions) || defined(__EXCEPTIONS) || defined(_CPPUNWIND)) && !defined(HCAT_NOEXCEPTION) +#define CAT_THROW(exception) throw exception +#define CAT_TRY try +#define CAT_CATCH(exception) catch(exception) +#define CAT_INTERNAL_CATCH(exception) catch(exception) +#else +#include +#define CAT_THROW(exception) std::abort() +#define CAT_TRY if(true) +#define CAT_CATCH(exception) if(false) +#define CAT_INTERNAL_CATCH(exception) if(false) +#endif + + +// override exception macros +#if defined(CAT_THROW_USER) +#undef CAT_THROW +#define CAT_THROW CAT_THROW_USER +#endif +#if defined(CAT_TRY_USER) +#undef CAT_TRY +#define CAT_TRY CAT_TRY_USER +#endif +#if defined(CAT_CATCH_USER) +#undef CAT_CATCH +#define CAT_CATCH CAT_CATCH_USER +#undef CAT_INTERNAL_CATCH +#define CAT_INTERNAL_CATCH CAT_CATCH_USER +#endif +#if defined(CAT_INTERNAL_CATCH_USER) +#undef CAT_INTERNAL_CATCH +#define CAT_INTERNAL_CATCH CAT_INTERNAL_CATCH_USER +#endif + + +#define HBool int +#define HTrue 1 +#define HFalse 0 + +typedef unsigned long long huint64; +typedef unsigned int huint32; +typedef unsigned short huint16; +typedef unsigned char huint8; + +typedef long long hint64; +typedef int hint32; +typedef short hint16; +typedef char hint8; + + +#ifdef USE_HD_LIB +namespace hd { +typedef class HDSDKPrivate* IHDProtocol; +} +using hd::IHDProtocol; +#else +typedef void* IHDProtocol; +#endif + +#ifdef __cplusplus +extern "C" { +#endif + + +typedef enum { + /** + * void readXml(const char *xml, int len, int errorCode, void *userData) + * @param xml Xml data + * @param len Xml len + * @param errorCode Error code, normally 0 + * @param userData kSetReadXmlData value + */ + kSetReadXml = 0x0001, + kSetReadXmlData = 0x0002, + + /** + * HBool sendDataToNet(const char *data, int len, void *userData) + * @param data Send data + * @param len Send data len + * @param userData kSetSendFuncData value + * @return 0 <= return. Stop the protocol, which requires a protocol reset + */ + kSetSendFunc = 0x0003, + kSetSendFuncData = 0x0004 + +} eHDFunc ; + + +/** + * @brief CreateProtocol Create protocol. default init. + * @return IHDProtocol + */ +HD_API IHDProtocol DLL_CALL CreateProtocol(); + +/** + * @brief FreeProtocol free protocol + * @param protocol IHDProtocol + */ +HD_API void DLL_CALL FreeProtocol(IHDProtocol protocol); + +/** + * @brief SetProtocolFunc Set protocol function + * @param protocol IHDProtocol + * @param func eHDFunc + * @param data data + * @return 1 or 0 (1 = true; 0 = false) + */ +HD_API HBool DLL_CALL SetProtocolFunc(IHDProtocol protocol, int func, void *data); + +/** + * @brief InitProtocol init protocol. Required when the same protocol body needs to be reused + * @param protocol IHDProtocol + */ +HD_API void DLL_CALL InitProtocol(IHDProtocol protocol); + +/** + * @brief RunProtocol Start negotiating the protocol + * @param protocol IHDProtocol + * @return 1 or 0 (1 = true; 0 = false) + */ +HD_API HBool RunProtocol(IHDProtocol protocol); + +/** + * @brief UpdateReadData The core, the read data is passed in + * @param protocol IHDProtocol + * @param data Read data + * @param len Read data len + * @return 1 or 0 (1 = true; 0 = false) + */ +HD_API HBool UpdateReadData(IHDProtocol protocol, const char *data, int len); + +/** + * @brief SendXml Send xml data + * @param protocol IHDProtocol + * @param xml Xml data + * @param len Xml len + * @return 1 or 0 (1 = true; 0 = false) + */ +HD_API HBool DLL_CALL SendXml(IHDProtocol protocol, const char *xml, int len); + +/** + * @brief SendFile Send file + * @param protocol IHDProtocol + * @param fileName device save file name + * @param fileNameLen Send file name len + * @param md5 md5(32byte) + * @param type 0(image), 1(video), 2(font), 3(firmware), 128(temp image file), 129(temp video file) + * @param size Send file Size + * @param callFun Send file data { int(hint64 index, hint64 size, int status, char *buff, int buffSize, void *userData) } + * @param userData callFun userData + * @return 1 or 0 (1 = true; 0 = false) + */ +HD_API HBool DLL_CALL SendFile(IHDProtocol protocol, const char *fileName, int fileNameLen, const char *md5, int type, hint64 size, int(*callFun)(hint64, hint64, int, char *, int, void *), void *userData); + + +#ifdef __cplusplus +} +#endif + +#endif // __HDSDK_H__ diff --git a/SDK/Data/HEthernetInfo.cpp b/SDK/Data/HEthernetInfo.cpp new file mode 100644 index 0000000..bdd1f45 --- /dev/null +++ b/SDK/Data/HEthernetInfo.cpp @@ -0,0 +1,124 @@ + + +#include + + +namespace sdk +{ + + +void from_xml(const HXml &xml, Eth0Info &node) +{ + node.dhcp = xml.at("eth").at("dhcp").GetAttribute("auto") == "true"; + node.ip = xml.at("eth").at("address").GetAttribute("ip"); + node.netmask = xml.at("eth").at("address").GetAttribute("netmask"); + node.gateway = xml.at("eth").at("address").GetAttribute("gateway"); + node.dns = xml.at("eth").at("address").GetAttribute("dns"); +} + + +void to_xml(HXml &xml, const Eth0Info &node) +{ + xml["eth"] = {"valid", "true"}; + xml["eth"]["enable"] = {"value", "true"}; + xml["eth"]["dhcp"] = {"auto", node.dhcp}; + xml["eth"]["address"] = {{"ip", node.ip}, + {"netmask", node.netmask}, + {"gateway", node.gateway}, + {"dns", node.dns}}; +} + + +void from_xml(const HXml &xml, WifiInfo &node) +{ + node.mode = xml.at("mode").GetAttribute("value"); + node.ap.ssid = xml.at("ap").at("ssid").GetAttribute("value"); + node.ap.password = xml.at("ap").at("passwd").GetAttribute("value"); + node.ap.ipAddress = xml.at("ap").at("address").GetAttribute("ip"); + if (xml.at("ap").ContainsNodes("channel")) { + node.ap.channel = xml.at("ap").at("channel").GetAttribute("value").ToInt(); + } + + node.stationIndex = xml.at("station").at("current").GetAttribute("index").ToInt(); + + node.station.clear(); + for (const auto &i : xml.at("station").at("list").at("item")) { + WifiInfo::StationConfig info; + info.ssid = i.at("ssid").GetAttribute("value"); + info.password = i.at("passwd").GetAttribute("value"); + info.dhcp = i.at("dhcp").GetAttribute("auto") != "false"; + info.ip = i.at("address").GetAttribute("ip"); + info.mask = i.at("address").GetAttribute("netmask"); + info.gateway = i.at("address").GetAttribute("gateway"); + info.dns = i.at("address").GetAttribute("dns"); + node.station.emplace_back(std::move(info)); + } +} + + +void to_xml(HXml &xml, const WifiInfo &node) +{ + xml["mode"] = {"value", node.mode.GetConstString()}; + xml["ap"]["ssid"] = {"value", node.ap.ssid.GetConstString()}; + xml["ap"]["passwd"] = {"value", node.ap.password.GetConstString()}; + xml["ap"]["channel"] = {"value", node.ap.channel}; + xml["ap"]["encryption"] = {"value", "WPA-PSK"}; + xml["ap"]["dhcp"] = {"auto", "true"}; + xml["ap"]["address"] = {{"ip", node.ap.ipAddress.GetConstString()}, + {"netmask", ""}, + {"gateway", ""}, + {"dns", ""}}; + + xml["station"]["current"] = {"index", node.stationIndex}; + for (const auto &i : node.station) { + HXml &item = xml["station"]["list"].NewChild("item"); + item["ssid"] = {"value", i.ssid}; + item["passwd"] = {"value", i.password}; + item["signal"] = {"value", 0}; + item["apmac"] = {"value", i.mac}; + item["dhcp"] = {"auto", i.dhcp ? "true" : "false"}; + item["address"] = {{"ip", i.ip}, + {"netmask", i.mask}, + {"gateway", i.gateway}, + {"dns", i.dns}}; + } +} + + +void from_xml(const HXml &xml, PppoeInfo &node) +{ + node.vaild = xml.at("pppoe").GetAttribute("valid") == "true"; + node.enable = xml.at("pppoe").at("enable").GetAttribute("value") == "true"; + node.apn = xml.at("pppoe").at("apn").GetAttribute("value"); + node.manufacturer = xml.at("pppoe").at("manufacturer").GetAttribute("value"); + node.version = xml.at("pppoe").at("version").GetAttribute("value"); + node.model = xml.at("pppoe").at("model").GetAttribute("value"); + node.imei = xml.at("pppoe").at("imei").GetAttribute("value"); + node.number = xml.at("pppoe").at("number").GetAttribute("value"); + node.operators = xml.at("pppoe").at("operators").GetAttribute("value"); + node.signal = xml.at("pppoe").at("signal").GetAttribute("value").ToInt(); + node.dbm = xml.at("pppoe").at("dbm").GetAttribute("value").ToInt(); + node.insert = xml.at("pppoe").at("insert").GetAttribute("value") == "true"; + node.status = xml.at("pppoe").at("status").GetAttribute("value"); + node.network = xml.at("pppoe").at("network").GetAttribute("value"); + node.code = xml.at("pppoe").at("code").GetAttribute("value"); +} + + +void to_xml(HXml &xml, const PppoeInfo &node) +{ + xml["apn"] = {"value", node.apn}; +} + +const WifiInfo::StationConfig &WifiInfo::GetCurrentStation() +{ + if (stationIndex < 0 || stationIndex >= static_cast(station.size())) { + stationIndex = 0; + station.clear(); + station.emplace_back(StationConfig()); + } + return station.front(); +} + + +} diff --git a/SDK/Data/HEthernetInfo.h b/SDK/Data/HEthernetInfo.h new file mode 100644 index 0000000..d01fc74 --- /dev/null +++ b/SDK/Data/HEthernetInfo.h @@ -0,0 +1,114 @@ + + +#ifndef __HETHERNETINFO_H__ +#define __HETHERNETINFO_H__ + + +#include +#include + + +namespace sdk +{ + + +///< Eth0 +struct Eth0Info +{ + bool dhcp; ///< "true"(dhcp获取ip地址), "false"(静态ip地址) + cat::HCatBuffer ip; + cat::HCatBuffer netmask; + cat::HCatBuffer gateway; + cat::HCatBuffer dns; + + static bool MatchGet(const cat::HCatBuffer &item) { return item == "GetEth0Info"; } + static bool MatchSet(const cat::HCatBuffer &item) { return item == "SetEth0Info"; } + static cat::HCatBuffer GetMethod() { return "GetEth0Info"; } + static cat::HCatBuffer SetMethod() { return "SetEth0Info"; } +}; +void from_xml(const HXml &xml, Eth0Info &node); +void to_xml(HXml &xml, const Eth0Info &node); + + +struct WifiInfo +{ + struct ApConfig + { + cat::HCatBuffer ssid; ///< 热点名称 + cat::HCatBuffer password; ///< 热点密码 + cat::HCatBuffer ipAddress; ///< ip地址 + int channel; ///< ap通道 + ApConfig() : channel(0) { } + }; + + struct StationConfig + { + cat::HCatBuffer ssid; ///< wifi名称 + cat::HCatBuffer password; ///< wifi密码(仅设置) + bool dhcp; ///< 是否开启dhcp(默认开) + cat::HCatBuffer mac; ///< mac地址(只读) + cat::HCatBuffer ip; + cat::HCatBuffer mask; + cat::HCatBuffer gateway; + cat::HCatBuffer dns; + StationConfig() : dhcp(true) {} + }; + + cat::HCatBuffer mode; ///< 模式(ap|station) + ApConfig ap; ///< ap设置 + int stationIndex; ///< station索引 + std::list station; ///< station设置 + + WifiInfo() : stationIndex(0) {} + + const StationConfig & GetCurrentStation(); + + static bool MatchGet(const cat::HCatBuffer &item) { return item == "GetWifiInfo"; } + static bool MatchSet(const cat::HCatBuffer &item) { return item == "SetWifiInfo"; } + static cat::HCatBuffer GetMethod() { return "GetWifiInfo"; } + static cat::HCatBuffer SetMethod() { return "SetWifiInfo"; } +}; +void from_xml(const HXml &xml, WifiInfo &node); +void to_xml(HXml &xml, const WifiInfo &node); + + +struct PppoeInfo +{ + bool vaild; ///< 是否有接入 {"true"(有3/4G模块接入), "false"(无3/4G模块接入)} + bool enable; ///< {"true"(有3/4G网络接入), "false"(无3/4G网络接入)} + cat::HCatBuffer apn; ///< apn值 + cat::HCatBuffer manufacturer; ///< 模块生产商 + cat::HCatBuffer version; ///< 模块版本 + cat::HCatBuffer model; ///< 模块型号 + cat::HCatBuffer imei; ///< 模块IMEI + cat::HCatBuffer number; ///< sim卡电话号码 + cat::HCatBuffer operators; ///< 运营商 + int signal; ///< 信号强度, 取值范围[1, 5]; 1表示信号强度最差; 5表示信号强度最好 + int dbm; ///< 信号强度(单位dbm) + bool insert; ///< SIM卡是否插入, 取值范围{"true"(有SIM卡插入), "false"(无SIM卡插入)} + cat::HCatBuffer status; ///< 网络注册状态, 取值范围 {"unregister"(未注册), "register local"(已注册, 本地网络), "searching"(搜索中), "reject"(拒绝注册), "unknow"(未知错误), "register roaming"(已注册, 漫游网络), "init"(初始化状态)} + cat::HCatBuffer network; ///< 网络制式, 取值范围 {"init"(初始化状态), "unknow"(未知网络), "2G"(2G), "2.5G"(2.5G), "3GPP"(3GPP家族), "3G TD"(移动3G), "3.5G HSDPA", "3.5G HSUPA", "3.5G HSPAPlus", "4G LTE", "4G TDD", "4G FDD"} + cat::HCatBuffer code; ///< 错误码(保留) + + PppoeInfo() + : vaild(false) + , enable(false) + , signal(0) + , dbm(0) + , insert(false) + {} + + static bool MatchGet(const cat::HCatBuffer &item) { return item == "GetPppoeInfo"; } + static bool MatchSet(const cat::HCatBuffer &item) { return item == "SetApn"; } + static cat::HCatBuffer GetMethod() { return "GetPppoeInfo"; } + static cat::HCatBuffer SetMethod() { return "SetApn"; } +}; +void from_xml(const HXml &xml, PppoeInfo &node); +void to_xml(HXml &xml, const PppoeInfo &node); + + + +} + + +#endif // __HETHERNETINFO_H__ diff --git a/SDK/Data/HGeneralInfo.cpp b/SDK/Data/HGeneralInfo.cpp new file mode 100644 index 0000000..89e4f85 --- /dev/null +++ b/SDK/Data/HGeneralInfo.cpp @@ -0,0 +1,94 @@ + + +#include +#include + + +namespace sdk +{ + + +void to_xml(HXml &xml, const SystemVolumeInfo &data) +{ + xml["mode"] = HXml{"value", data.mode != SystemVolumeInfo::kDefault ? "ploys" : "default"}; + xml["volume"] = HXml{"percent", data.volume}; + for (const auto &i : data.ploys) { + xml["ploy"].emplace_back("item", {{"percent", i.volume}, + {"enable", i.enable}, + {"start", i.time}}); + } +} + + +void from_xml(const HXml &xml, SystemVolumeInfo &data) +{ + data.mode = xml.at("mode").GetAttribute("value") == "ploys" ? SystemVolumeInfo::kPloys : SystemVolumeInfo::kDefault; + data.volume = xml.at("volume").GetAttribute("percent"); + data.ploys.clear(); + if (xml.ContainsNodes("ploy", "item")) { + for (const auto &i : xml.at("ploy").at("item")) { + SystemVolumeInfo::Ploy item; + item.enable = DataToType(i.GetAttribute("enable")); + item.volume = i.GetAttribute("percent").ToInt(); + item.time = i.GetAttribute("start"); + data.ploys.emplace_back(std::move(item)); + } + } +} + + +void to_xml(HXml &xml, const DeviceNameInfo &data) +{ + xml["name"] = {"value", data.name}; +} + + +void from_xml(const HXml &xml, DeviceNameInfo &data) +{ + data.name = xml.at("name").GetAttribute("value"); +} + + +void to_xml(HXml &xml, const SDKTcpServerInfo &data) +{ + xml["server"] = {{"port", data.port}, + {"host", data.host}}; +} + + +void from_xml(const HXml &xml, SDKTcpServerInfo &data) +{ + data.port = xml.at("server").GetAttribute("port").ToInt(); + data.host = xml.at("server").GetAttribute("host"); +} + +void from_xml(const HXml &xml, DeviceInfo &data) +{ + data.device.cpu = xml.at("device").GetAttribute("cpu"); + data.device.id = xml.at("device").GetAttribute("id"); + data.device.model = xml.at("device").GetAttribute("model"); + data.device.name = xml.at("device").GetAttribute("name"); + + data.version.kernel = xml.at("version").GetAttribute("kernel"); + data.version.hardware = xml.at("version").GetAttribute("hardware"); + data.version.app = xml.at("version").GetAttribute("app"); + data.version.fpga = xml.at("version").GetAttribute("fpga"); + + data.screen.rotation = xml.at("screen").GetAttribute("rotation").ToInt(); + data.screen.width = xml.at("screen").GetAttribute("width").ToInt(); + data.screen.height = xml.at("screen").GetAttribute("height").ToInt(); +} + +void to_xml(HXml &xml, const ScreenShot2 &data) +{ + xml["image"] = {{"width", data.width}, + {"height", data.height}}; +} + +void from_xml(const HXml &xml, ScreenShot2 &data) +{ + data.rawData = cat::HCatBuffer::FromBase64(xml.at("image").GetAttribute("data")); +} + + +} diff --git a/SDK/Data/HGeneralInfo.h b/SDK/Data/HGeneralInfo.h new file mode 100644 index 0000000..cf4bef7 --- /dev/null +++ b/SDK/Data/HGeneralInfo.h @@ -0,0 +1,137 @@ + + +#ifndef __HGENERALINFO_H__ +#define __HGENERALINFO_H__ + + + +#include +#include +#include + + +namespace sdk +{ + + +///< 系统音量 +struct SystemVolumeInfo +{ + enum eMode { + kDefault, + kPloys, + }; + struct Ploy { + bool enable; ///< 是否启用时间段 + cat::HCatBuffer time; ///< 开始时间 "HH:mm:ss" + int volume; ///< 0-100 + Ploy() : enable(false), volume(0) {} + }; + + int mode; + cat::HCatBuffer volume; ///< 0-100 + std::vector ploys; ///< 分时音量 + + SystemVolumeInfo() + : mode(kDefault) + {} + + static bool MatchGet(const cat::HCatBuffer &item) { return item == "GetSystemVolume"; } + static bool MatchSet(const cat::HCatBuffer &item) { return item == "SetSystemVolume"; } + static cat::HCatBuffer GetMethod() { return "GetSystemVolume"; } + static cat::HCatBuffer SetMethod() { return "SetSystemVolume"; } +}; +void to_xml(HXml &xml, const SystemVolumeInfo &data); +void from_xml(const HXml &xml, SystemVolumeInfo &data); + + +///< 设备名 +struct DeviceNameInfo +{ + cat::HCatBuffer name; ///< 设备名 + + static bool MatchGet(const cat::HCatBuffer &item) { return item == "GetDeviceName"; } + static bool MatchSet(const cat::HCatBuffer &item) { return item == "SetDeviceName"; } + static cat::HCatBuffer GetMethod() { return "GetDeviceName"; } + static cat::HCatBuffer SetMethod() { return "SetDeviceName"; } +}; +void to_xml(HXml &xml, const DeviceNameInfo &data); +void from_xml(const HXml &xml, DeviceNameInfo &data); + + +///< tcp服务器 +struct SDKTcpServerInfo +{ + cat::HCatBuffer host; ///< 主机地址 + huint16 port; ///< 端口 + + SDKTcpServerInfo() : port(0) {} + + static bool MatchGet(const cat::HCatBuffer &item) { return item == "GetSDKTcpServer"; } + static bool MatchSet(const cat::HCatBuffer &item) { return item == "SetSDKTcpServer"; } + static cat::HCatBuffer GetMethod() { return "GetSDKTcpServer"; } + static cat::HCatBuffer SetMethod() { return "SetSDKTcpServer"; } +}; +void to_xml(HXml &xml, const SDKTcpServerInfo &data); +void from_xml(const HXml &xml, SDKTcpServerInfo &data); + + +///< 设备信息 +struct DeviceInfo +{ + struct Device { + cat::HCatBuffer cpu; ///< cpu信息 + cat::HCatBuffer id; ///< 设备id + cat::HCatBuffer model; ///< 设备类型 + cat::HCatBuffer name; ///< 设备名 + }; + struct Version { + cat::HCatBuffer kernel; ///< 内核版本 + cat::HCatBuffer hardware; ///< 硬件版本 + cat::HCatBuffer app; ///< 应用版本 + cat::HCatBuffer fpga; ///< fpga版本 + }; + struct Screen { + int rotation; ///< 旋转 + int width; ///< 屏幕宽度 + int height; ///< 屏幕高度 + Screen() + : rotation(0) + , width(0) + , height(0) + {} + }; + + Device device; + Version version; + Screen screen; + + static bool MatchGet(const cat::HCatBuffer &item) { return item == "GetDeviceInfo"; } + static cat::HCatBuffer GetMethod() { return "GetDeviceInfo"; } +}; +void from_xml(const HXml &xml, DeviceInfo &data); + + +///< 屏幕截图 +struct ScreenShot2 +{ + int width; ///< 截图宽 + int height; ///< 截图高 + cat::HCatBuffer rawData; ///< 图片base64数据 + + ScreenShot2() + : width(0) + , height(0) + {} + + static bool MatchGet(const cat::HCatBuffer &item) { return item == "GetScreenshot2"; } + static cat::HCatBuffer GetMethod() { return "GetScreenshot2"; } +}; +void to_xml(HXml &xml, const ScreenShot2 &data); +void from_xml(const HXml &xml, ScreenShot2 &data); + + +} + + +#endif // __HGENERALINFO_H__ diff --git a/SDK/Data/HLightInfo.cpp b/SDK/Data/HLightInfo.cpp new file mode 100644 index 0000000..901a337 --- /dev/null +++ b/SDK/Data/HLightInfo.cpp @@ -0,0 +1,67 @@ + + +#include +#include +#include + + +namespace sdk +{ + + +void from_xml(const HXml &xml, LightInfo &node) +{ + + cat::HCatBuffer mode = xml.at("mode").GetAttribute("value"); + if (mode == "ploys") { + node.mode = LightInfo::kPloys; + } else if (mode == "sensor") { + node.mode = LightInfo::kSensor; + } else { + node.mode = LightInfo::kDefault; + } + + node.defaultValue = xml.at("default").GetAttribute("value"); + node.sensor.min = xml.at("sensor").GetAttribute("min").ToInt(); + node.sensor.max = xml.at("sensor").GetAttribute("max").ToInt(); + node.sensor.time = xml.at("sensor").GetAttribute("time").ToInt(); + + node.ployList.clear(); + if (xml.ContainsNodes("ploy") && xml.at("ploy").ContainsNodes("item")) { + for (const auto &i : xml.at("ploy").at("item")) { + LightInfo::Ploy item; + item.enable = i.GetAttribute("enable") == "true"; + item.start = i.GetAttribute("start"); + item.percent = i.GetAttribute("percent").ToInt(); + node.ployList.emplace_back(std::move(item)); + } + } +} + + + +void to_xml(HXml &xml, const LightInfo &node) +{ + + switch (node.mode) { + case LightInfo::kDefault: xml["mode"] = {"value", "default"}; break; + case LightInfo::kPloys: xml["mode"] = {"value", "ploys"}; break; + case LightInfo::kSensor: xml["mode"] = {"value", "sensor"}; break; + default: + xml["mode"] = {"value", "default"}; + break; + } + + xml["default"] = {"value", node.defaultValue}; + xml["sensor"] = {{"min", node.sensor.min}, + {"max", node.sensor.max}, + {"time", node.sensor.time}}; + for (const auto &i : node.ployList) { + xml["ploy"].emplace_back("item", {{"enable", i.enable}, + {"start", i.start}, + {"percent", i.percent}}); + } +} + + +} diff --git a/SDK/Data/HLightInfo.h b/SDK/Data/HLightInfo.h new file mode 100644 index 0000000..931afa7 --- /dev/null +++ b/SDK/Data/HLightInfo.h @@ -0,0 +1,60 @@ + + +#ifndef __HLIGHTINFO_H__ +#define __HLIGHTINFO_H__ + + +#include +#include +#include + + +namespace sdk +{ + + +///< 亮度 +struct LightInfo +{ + enum eMode { + kDefault, ///< 默认 + kPloys, ///< 自定义模式 + kSensor, ///< 传感器模式 + }; + struct Sensor { + hint16 min; ///< 最小亮度等级 + hint16 max; ///< 最大亮度等级 + hint16 time; ///< 亮度调整间隔时间 + + Sensor() : min(1), max(100), time(5) {} + }; + struct Ploy { + bool enable; ///< 使能 + cat::HCatBuffer start; ///< 开始时间 hh:mm:ss + hint16 percent; ///< 亮度等级 + + Ploy() : enable(false), percent(0) {} + }; + + eMode mode; ///< 模式 + cat::HCatBuffer defaultValue; ///< 默认模式的值[1, 100] + Sensor sensor; ///< 传感器模式 + std::vector ployList; ///< 自定义模式 + + LightInfo() + : mode(kDefault) + {} + + static bool MatchGet(const cat::HCatBuffer &item) { return item == "GetLuminancePloy"; } + static bool MatchSet(const cat::HCatBuffer &item) { return item == "SetLuminancePloy"; } + static cat::HCatBuffer GetMethod() { return "GetLuminancePloy"; } + static cat::HCatBuffer SetMethod() { return "SetLuminancePloy"; } +}; +void from_xml(const HXml &xml, LightInfo &node); +void to_xml(HXml &xml, const LightInfo &node); + + +} + + +#endif // __HLIGHTINFO_H__ diff --git a/SDK/Data/HOTherInfo.cpp b/SDK/Data/HOTherInfo.cpp new file mode 100644 index 0000000..f948553 --- /dev/null +++ b/SDK/Data/HOTherInfo.cpp @@ -0,0 +1,36 @@ + + +#include + + +namespace sdk +{ + + +void from_xml(const HXml &xml, MulScreenSyncInfo &node) +{ + node.enable = xml.at("enable").GetAttribute("value") == "true"; +} + + +void to_xml(HXml &xml, const MulScreenSyncInfo &node) +{ + xml["enable"] = {"value", node.enable ? "true" : "false"}; +} + + +void from_xml(const HXml &xml, GpsRespondInfo &node) +{ + node.enable = xml.at("gps").GetAttribute("enable") == "true"; + node.delay = xml.at("gps").GetAttribute("delay").ToInt(); +} + + +void to_xml(HXml &xml, const GpsRespondInfo &node) +{ + xml["gps"] = {{"enable", node.enable ? "true" : "false"}, + {"delay", node.delay}}; +} + + +} diff --git a/SDK/Data/HOTherInfo.h b/SDK/Data/HOTherInfo.h new file mode 100644 index 0000000..91ee20b --- /dev/null +++ b/SDK/Data/HOTherInfo.h @@ -0,0 +1,51 @@ + + +#ifndef __HOTHERINFO_H__ +#define __HOTHERINFO_H__ + + +#include +#include + + +namespace sdk +{ + + +///< 多屏同步 +struct MulScreenSyncInfo +{ + bool enable; ///< 使能 + + MulScreenSyncInfo() : enable(false) {} + + static bool MatchGet(const cat::HCatBuffer &item) { return item == "GetMulScreenSync"; } + static bool MatchSet(const cat::HCatBuffer &item) { return item == "SetMulScreenSync"; } + static cat::HCatBuffer GetMethod() { return "GetMulScreenSync"; } + static cat::HCatBuffer SetMethod() { return "SetMulScreenSync"; } +}; +void from_xml(const HXml &xml, MulScreenSyncInfo &node); +void to_xml(HXml &xml, const MulScreenSyncInfo &node); + + +///< gps数据上报 +struct GpsRespondInfo +{ + bool enable; + hint16 delay; + + GpsRespondInfo() : enable(false), delay(0) {} + + static bool MatchGet(const cat::HCatBuffer &item) { return item == "GetGpsRespondEnable"; } + static bool MatchSet(const cat::HCatBuffer &item) { return item == "SetGpsRespondEnable"; } + static cat::HCatBuffer GetMethod() { return "GetGpsRespondEnable"; } + static cat::HCatBuffer SetMethod() { return "SetGpsRespondEnable"; } +}; +void from_xml(const HXml &xml, GpsRespondInfo &node); +void to_xml(HXml &xml, const GpsRespondInfo &node); + + +} + + +#endif // __HOTHERINFO_H__ diff --git a/SDK/Data/HSDKInfo.cpp b/SDK/Data/HSDKInfo.cpp new file mode 100644 index 0000000..e66e299 --- /dev/null +++ b/SDK/Data/HSDKInfo.cpp @@ -0,0 +1,69 @@ + + +#include +#include +#include + + +using namespace sdk; + + +template +bool UpdateNode(_T &obj, const cat::HCatBuffer &method, const HXml &xml) { + if (_T::MatchSet(method)) { + return true; + } + + if (_T::MatchGet(method) == false) { + return false; + } + + return xml.get_to(obj); +} +template +bool UpdateGetNode(_T &obj, const cat::HCatBuffer &method, const HXml &xml) { + if (_T::MatchGet(method) == false) { + return false; + } + + return xml.get_to(obj); +} + + +int HSDKInfo::ParseInfo(tinyxml2::XMLElement *outNode, const cat::HCatBuffer &method) +{ + if (outNode == nullptr) { + return 0; + } + + int result = 0; + HXml xml(outNode); + +#define UPDATE_NODE(obj) \ + if (UpdateNode(obj, method, xml)) { ++result; } +#define UPDATE_GET_NODE(obj) \ + if (UpdateGetNode(obj, method, xml)) { ++result; } + + UPDATE_NODE(lightInfo); + UPDATE_NODE(systemVolumeInfo); + UPDATE_NODE(tcpSercerInfo); + UPDATE_NODE(timeInfo); + UPDATE_NODE(ethInfo); + UPDATE_NODE(wifiInfo); + UPDATE_NODE(pppoeInfo); + UPDATE_NODE(deviceNameInfo); + UPDATE_NODE(switchTimeInfo); + UPDATE_NODE(relayInfo); + + UPDATE_GET_NODE(deviceInfo); + UPDATE_GET_NODE(screenShot2); + UPDATE_GET_NODE(sensorInfo); + UPDATE_GET_NODE(gpsInfo); + + return result; +#undef UPDATE_GET_NODE +#undef UPDATE_NODE +} diff --git a/SDK/Data/HSDKInfo.h b/SDK/Data/HSDKInfo.h new file mode 100644 index 0000000..327a13f --- /dev/null +++ b/SDK/Data/HSDKInfo.h @@ -0,0 +1,51 @@ + + +#ifndef __HSDKINFO_H__ +#define __HSDKINFO_H__ + + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +namespace sdk +{ + + +struct HSDKInfo +{ + Eth0Info ethInfo; ///< 有线 + WifiInfo wifiInfo; ///< wifi + PppoeInfo pppoeInfo; ///< pppoe + SystemVolumeInfo systemVolumeInfo; ///< 系统音量 + DeviceNameInfo deviceNameInfo; ///< 设备名 + SDKTcpServerInfo tcpSercerInfo; ///< tcp服务器 + LightInfo lightInfo; ///< 亮度 + MulScreenSyncInfo mulScreenSyncInfo; ///< 多屏同步 + GpsRespondInfo gpsResondInfo; ///< gps数据上报 + SwitchTimeInfo switchTimeInfo; ///< 开关机 + RelayInfo relayInfo; ///< 继电器 + TimeInfo timeInfo; ///< 时间 + + ///< 下面是只有获取项的 + DeviceInfo deviceInfo; ///< 设备信息 + ScreenShot2 screenShot2; ///< 截图数据 + SensorInfo sensorInfo; ///< 传感器状态 + GpsInfo gpsInfo; ///< gps信息 + + + int ParseInfo(tinyxml2::XMLElement *outNode, const cat::HCatBuffer &method); +}; + + +} + +#endif // __HSDKINFO_H__ diff --git a/SDK/Data/HScreenFunctionInfo.cpp b/SDK/Data/HScreenFunctionInfo.cpp new file mode 100644 index 0000000..ff848dd --- /dev/null +++ b/SDK/Data/HScreenFunctionInfo.cpp @@ -0,0 +1,127 @@ + + +#include + + +namespace sdk +{ + + +void from_xml(const HXml &xml, SwitchTimeInfo &node) +{ + node.ploys.clear(); + node.weekPloys.clear(); + node.open = xml.at("open").GetAttribute("enable") == "true"; + node.ployEnable = xml.at("ploy").GetAttribute("enable") == "true"; + node.mode = xml.at("ploy").GetAttribute("mode").ToInt(); + do { + if (xml.at("ploy").ContainsNodes("item") == false) { + break; + } + + for (const auto &i : xml.at("ploy").at("item")) { + SwitchTimeInfo::ployItem item; + item.enable = i.GetAttribute("enable") == "true"; + item.start = i.GetAttribute("start"); + item.end = i.GetAttribute("end"); + node.ploys.emplace_back(std::move(item)); + } + } while (false); + + do { + if (xml.at("ploy").ContainsNodes("weekItem") == false) { + break; + } + + for (const auto &i : xml.at("ploy").at("weekItem")) { + SwitchTimeInfo::weekPloyItem item; + item.openAllDay = i.GetAttribute("openAllDay").ToInt(); + item.week = i.GetAttribute("week").ToInt(); + + if (i.ContainsNodes("item")) { + for (const auto &j : i.at("item")) { + SwitchTimeInfo::weekItem itemTime; + itemTime.start = j.GetAttribute("start"); + itemTime.end = j.GetAttribute("end"); + item.ploys.emplace_back(std::move(itemTime)); + } + } + + node.weekPloys.emplace_back(std::move(item)); + } + } while (false); +} + + + +void to_xml(HXml &xml, const SwitchTimeInfo &node) +{ + xml["open"] = {"enable", node.ployEnable ? "true" : "false"}; + xml["ploy"] = {{"mode", node.mode}, + {"enbale", node.ployEnable}}; + + for (const auto &i : node.ploys) { + xml["ploy"].emplace_back("item", {{"enable", i.enable}, + {"start", i.start}, + {"end", i.end}}); + } + + for (const auto &i : node.weekPloys) { + HXml &item = xml["ploy"].NewChild("weekItem"); + item = {{"openAllDay", i.openAllDay ? 1 : 0}, + {"week", i.week}}; + + + for (const auto &j : i.ploys) { + item.emplace_back("item", {{"start", j.start}, + {"end", j.end}}); + } + } +} + + +void SwitchTimeInfo::InitWeekPloys() +{ + std::size_t week = 0; + const std::size_t weekNum = GetWeekMax(); + for (auto i = weekPloys.begin(); i != weekPloys.end();) { + if (week & (1 << i->week)) { + i = weekPloys.erase(i); + continue; + } + week |= 1 << i->week; + ++i; + } + + while (weekPloys.size() < weekNum) { + weekPloyItem item; + for (std::size_t i = 0; i < weekNum; ++i) { + if (week & (1 << i)) { + continue; + } + + week |= 1 << i; + item.week = i; + } + weekPloys.emplace_back(std::move(item)); + } +} + +SwitchTimeInfo::weekPloyItem &SwitchTimeInfo::GetWeekItem(int week) +{ + if (weekPloys.size() < GetWeekMax()) { + InitWeekPloys(); + } + + for (auto &i : weekPloys) { + if (i.week == week) { + return i; + } + } + + return weekPloys.front(); +} + + +} + diff --git a/SDK/Data/HScreenFunctionInfo.h b/SDK/Data/HScreenFunctionInfo.h new file mode 100644 index 0000000..856ec18 --- /dev/null +++ b/SDK/Data/HScreenFunctionInfo.h @@ -0,0 +1,64 @@ + + +#ifndef __HSCREENFUNCTIONINFO_H__ +#define __HSCREENFUNCTIONINFO_H__ + + +#include +#include +#include +#include + + +namespace sdk +{ + + +///< 开关机 +struct SwitchTimeInfo +{ + struct ployItem { + bool enable; ///< 该项是否使能, 取值范围{"true"(使能), "false"(不使能)} + cat::HCatBuffer start; ///< 开屏时刻, 格式hh:mm:ss + cat::HCatBuffer end; ///< 关屏时刻, 格式hh:mm:ss + }; + + struct weekItem { + cat::HCatBuffer start; ///< 格式hh:mm:ss + cat::HCatBuffer end; ///< 格式hh:mm:ss + }; + + struct weekPloyItem { + int week; ///< 星期数[0-6] + bool openAllDay; ///< 全天开机 + std::vector ploys; ///< 时间项 + weekPloyItem() + : week(0) + , openAllDay(true) + {} + }; + + bool open; ///< 当前屏幕状态 + bool ployEnable; ///< 是否启用定时开关屏 + int mode; ///< 开关屏模式 0: 每天, 1:每星期 + std::vector ploys; ///< 开关屏时间段列表 + std::vector weekPloys; ///< 按星期开关屏时间表 + + void InitWeekPloys(); + static std::size_t GetWeekMax() { return 7; } + weekPloyItem &GetWeekItem(int week); + + static bool MatchGet(const cat::HCatBuffer &item) { return item == "GetSwitchTime"; } + static bool MatchSet(const cat::HCatBuffer &item) { return item == "SetSwitchTime"; } + static cat::HCatBuffer GetMethod() { return "GetSwitchTime"; } + static cat::HCatBuffer SetMethod() { return "SetSwitchTime"; } +}; +void from_xml(const HXml &xml, SwitchTimeInfo &node); +void to_xml(HXml &xml, const SwitchTimeInfo &node); + + +} + + + +#endif // HSCREENFUNCTIONINFO_H diff --git a/SDK/Data/HSensorInfo.cpp b/SDK/Data/HSensorInfo.cpp new file mode 100644 index 0000000..6400ed3 --- /dev/null +++ b/SDK/Data/HSensorInfo.cpp @@ -0,0 +1,132 @@ + + +#include + + +// 外置继电器最大是6个, 常规系列那边第七个是内置继电器 +#define MAX_RELAY_NUM (6) + + +namespace sdk +{ + + +void from_xml(const HXml &xml, SensorInfo &node) +{ + node.luminance = xml.at("luminance").GetAttribute("connect") == "true"; + node.temp1 = xml.at("temp1").GetAttribute("connect") == "true"; + node.humidity = xml.at("humidity").GetAttribute("connect") == "true"; + node.temp2 = xml.at("temp2").GetAttribute("connect") == "true"; + node.telecontroller = xml.at("telecontroller").GetAttribute("connect") == "true"; + node.gps = xml.at("gps").GetAttribute("connect") == "true"; + node.windSpeed = xml.at("windSpeed").GetAttribute("connect") == "true"; + node.windDirection = xml.at("windDirection").GetAttribute("connect") == "true"; + node.noise = xml.at("noise").GetAttribute("connect") == "true"; + node.pressure = xml.at("pressure").GetAttribute("connect") == "true"; + node.lightIntensity = xml.at("lightIntensity").GetAttribute("connect") == "true"; + node.rainfall = xml.at("rainfall").GetAttribute("connect") == "true"; + node.co2 = xml.at("co2").GetAttribute("connect") == "true"; + node.pm2d5 = xml.at("pm2d5").GetAttribute("connect") == "true"; + node.pm10 = xml.at("pm10").GetAttribute("connect") == "true"; +} + + +void from_xml(const HXml &xml, GpsInfo &node) +{ + node.east = xml.at("gps").GetAttribute("east") == "true"; + node.north = xml.at("gps").GetAttribute("north") == "true"; + node.longitude = xml.at("gps").GetAttribute("longitude").ToFloat(); + node.latitude = xml.at("gps").GetAttribute("latitude ").ToFloat(); + node.counts = xml.at("gps").GetAttribute("counts").ToInt(); + node.speed = xml.at("gps").GetAttribute("speed ").ToFloat(); + node.direction = xml.at("gps").GetAttribute("direction").ToFloat(); +} + + +void from_xml(const HXml &xml, RelayInfo &node) +{ + node.relayList.clear(); + node.internal.ploys.clear(); + + for (const auto &i : xml.at("item")) { + RelayInfo::realyItem item; + item.name = i.GetAttribute("name"); + item.relayStatus = i.GetAttribute("relayStatus").ToInt(); + item.useSwitch = DataToType(i.GetAttribute("useSwitch")); + if (i.ContainsNodes("time") == false) { + node.relayList.emplace_back(std::move(item)); + continue; + } + + for (const auto &j : i.at("time")) { + RelayInfo::ployItem timeItem; + timeItem.start = j.GetAttribute("start"); + timeItem.end = j.GetAttribute("end"); + item.ploys.emplace_back(std::move(timeItem)); + } + node.relayList.emplace_back(std::move(item)); + } + + do { + if (xml.ContainsNodes("internal") == false) { + break; + } + + node.internal.name = xml.at("internal").GetAttribute("name"); + node.internal.relayStatus = xml.at("internal").GetAttribute("relayStatus").ToInt(); + node.internal.useSwitch = DataToType(xml.at("internal").GetAttribute("useSwitch")); + if (xml.at("internal").ContainsNodes("time") == false) { + break; + } + + for (const auto &i : xml.at("internal").at("time")) { + RelayInfo::ployItem timeItem; + timeItem.start = i.GetAttribute("start"); + timeItem.end = i.GetAttribute("end"); + node.internal.ploys.emplace_back(std::move(timeItem)); + } + } while (false); +} + + + +void to_xml(HXml &xml, const RelayInfo &node) +{ + for (const auto &i : node.relayList) { + HXml &item = xml.NewChild("item"); + item = {{"relayStatus", i.relayStatus}, + {"name", i.name}, + {"useSwitch", i.useSwitch ? 1 : 0}}; + + for (const auto &j : i.ploys) { + item.NewChild("time") = {{"start", j.start}, + {"end", j.end}}; + } + } + + for (auto i = node.relayList.size(); i < MAX_RELAY_NUM; ++i) { + xml.NewChild("item") = {{"relayStatus", "0"}, + {"name", ""}, + {"useSwitch", "0"}}; + } + + xml["internal"] = {{"relayStatus", node.internal.relayStatus}, + {"name", node.internal.name}, + {"useSwitch", node.internal.useSwitch ? 1 : 0}}; + + for (const auto &i : node.internal.ploys) { + xml["internal"].NewChild("time") = {{"start", i.start}, + {"end", i.end}}; + } +} + +void RelayInfo::InitRelayList() +{ + while (relayList.size() < MAX_RELAY_NUM) { + relayList.emplace_back(realyItem()); + } +} + + + +} diff --git a/SDK/Data/HSensorInfo.h b/SDK/Data/HSensorInfo.h new file mode 100644 index 0000000..57fded9 --- /dev/null +++ b/SDK/Data/HSensorInfo.h @@ -0,0 +1,119 @@ + + +#ifndef __HSENSORINFO_H__ +#define __HSENSORINFO_H__ + + +#include +#include +#include + + +namespace sdk +{ + + +///< 传感器状态 +struct SensorInfo +{ + bool luminance; ///< 是否接入亮度传感器 + bool temp1; ///< 是否接入温度传感器1 + bool humidity; ///< 是否接入湿度传感器 + bool temp2; ///< 是否接入温度传感器2 + bool telecontroller; ///< 是否接入遥控器 + bool gps; ///< 是否接入gps + bool windSpeed; ///< 是否接入风速传感器 + bool windDirection; ///< 是否接入风向传感器 + bool noise; ///< 是否接入噪音传感器 + bool pressure; ///< 是否接入压力传感器 + bool lightIntensity; ///< 是否接入光照强度传感器 + bool rainfall; ///< 是否接入降雨量传感器 + bool co2; ///< 是否接入二氧化碳传感器 + bool pm2d5; ///< 是否接入PM2.5传感器 + bool pm10; ///< 是否接入PM10传感器 + + SensorInfo() + : luminance(false) + , temp1(false) + , humidity(false) + , temp2(false) + , telecontroller(false) + , gps(false) + , windSpeed(false) + , windDirection(false) + , noise(false) + , pressure(false) + , lightIntensity(false) + , rainfall(false) + , co2(false) + , pm2d5(false) + , pm10(false) + {} + + static bool MatchGet(const cat::HCatBuffer &item) { return item == "GetSensorInfo"; } + static cat::HCatBuffer GetMethod() { return "GetSensorInfo"; } +}; +void from_xml(const HXml &xml, SensorInfo &node); + + +///< gps +struct GpsInfo +{ + bool east; ///< 东方 + bool north; ///< 北方 + double longitude; ///< 经度 + double latitude; ///< 纬度 + int counts; ///< 计数 + float speed; ///< 速度 + float direction; ///< 方向 + + GpsInfo() + : east(false) + , north(false) + , longitude(0.0) + , latitude(0.0) + , counts(0) + , speed(0.0) + , direction(0.0) + {} + + static bool MatchGet(const cat::HCatBuffer &item) { return item == "GetGPSInfo"; } + static cat::HCatBuffer GetMethod() { return "GetGPSInfo"; } +}; +void from_xml(const HXml &xml, GpsInfo &node); + + +///< 继电器 +struct RelayInfo +{ + struct ployItem { + cat::HCatBuffer start; ///< 格式 hh:mm:ss + cat::HCatBuffer end; ///< 格式 hh:mm:ss + }; + + struct realyItem { + int relayStatus; ///< 继电器状态{0: 未知 1:继电器开启 2:继电器关闭} + cat::HCatBuffer name; ///< 继电器名称 + bool useSwitch; ///< 关联显示屏状态 {1:true 0:false} + std::vector ploys; ///< 时间项 + realyItem() : relayStatus(0), useSwitch(false) {} + }; + + std::vector relayList; ///< 开关配置列表 + realyItem internal; ///< 板载继电器 + + void InitRelayList(); + + static bool MatchGet(const cat::HCatBuffer &item) { return item == "GetRelayInfo"; } + static bool MatchSet(const cat::HCatBuffer &item) { return item == "SetRelayInfo"; } + static cat::HCatBuffer GetMethod() { return "GetRelayInfo"; } + static cat::HCatBuffer SetMethod() { return "SetRelayInfo"; } +}; +void from_xml(const HXml &xml, RelayInfo &node); +void to_xml(HXml &xml, const RelayInfo &node); + + +} + + +#endif // HSENSORINFO_H diff --git a/SDK/Data/HTimeInfo.cpp b/SDK/Data/HTimeInfo.cpp new file mode 100644 index 0000000..5fc2b2c --- /dev/null +++ b/SDK/Data/HTimeInfo.cpp @@ -0,0 +1,37 @@ + + +#include +#include + + +namespace sdk +{ + + +void from_xml(const HXml &xml, TimeInfo &node) +{ + node.timeZone = xml.at("timezone").GetAttribute("value"); + node.summer = xml.at("summer").GetAttribute("enable") == "true"; + node.sync = xml.at("sync").GetAttribute("value"); + node.currTime = xml.at("time").GetAttribute("value"); + node.serverList.Clear(); + if (xml.ContainsNodes("server")) { + node.serverList = xml.at("server").GetAttribute("list"); + } +} + + +void to_xml(HXml &xml, const TimeInfo &node) +{ + xml["timezone"] = {"value", node.timeZone}; + xml["summer"] = {{"enable", node.summer}}; + xml["sync"] = {"value", node.sync.Empty() ? "none" : node.sync}; + xml["time"] = {"value", node.currTime}; + xml["server"] = {"list", node.serverList}; + xml["rf"]["enable"] = {"value", node.rf.enable}; + xml["rf"]["master"] = {"value", node.rf.master}; + xml["rf"]["channel"] = {"value", node.rf.channel}; +} + + +} diff --git a/SDK/Data/HTimeInfo.h b/SDK/Data/HTimeInfo.h new file mode 100644 index 0000000..9f84f0c --- /dev/null +++ b/SDK/Data/HTimeInfo.h @@ -0,0 +1,50 @@ + + +#ifndef __HTIMEINFO_H__ +#define __HTIMEINFO_H__ + + +#include +#include + + +namespace sdk +{ + + +///< 时间 +struct TimeInfo +{ + struct Rf { + bool enable; ///< rf同步是否使能 + bool master; ///< 主设备 + int channel; ///< 通道 + Rf() + : enable(false) + , master(false) + , channel(0) + {}; + }; + + cat::HCatBuffer timeZone; ///< 时区字符串 + bool summer; ///< 是否开启夏令时 + cat::HCatBuffer sync; ///< 时间同步模式 + cat::HCatBuffer currTime; ///< 当前控制卡时间 yyyy-mm-dd hh:MM:ss + cat::HCatBuffer serverList; ///< 服务器列表, 逗号分隔 + Rf rf; ///< rf模块 + + TimeInfo() + : summer(false) + {} + static bool MatchGet(const cat::HCatBuffer &item) { return item == "GetTimeInfo"; } + static bool MatchSet(const cat::HCatBuffer &item) { return item == "SetTimeInfo"; } + static cat::HCatBuffer GetMethod() { return "GetTimeInfo"; } + static cat::HCatBuffer SetMethod() { return "SetTimeInfo"; } +}; +void from_xml(const HXml &xml, TimeInfo &node); +void to_xml(HXml &xml, const TimeInfo &node); + + +} + +#endif // __HTIMEINFO_H__ diff --git a/SDK/HCatBuffer.h b/SDK/HCatBuffer.h new file mode 100644 index 0000000..2d3ea23 --- /dev/null +++ b/SDK/HCatBuffer.h @@ -0,0 +1,588 @@ + + +#ifndef __HCATBUFFER_H__ +#define __HCATBUFFER_H__ + + +#include +#include +#include +#include +#include +#include +#include + + +namespace cat +{ + + +class HCatBuffer +{ +public: + typedef typename std::string::difference_type difference_type; + typedef HCatBuffer value_type; + typedef HCatBuffer * pointer; + typedef HCatBuffer & reference; + typedef typename std::string::iterator::iterator_category iterator_category; + +public: + HCatBuffer() : buff_(new std::string()) {} + explicit HCatBuffer(std::size_t len) : buff_(new std::string(len, '\0')) {} + HCatBuffer(std::size_t len, char c) : buff_(new std::string(len, c)) {} + HCatBuffer(const char *buff, std::size_t len) : buff_(new std::string(buff, len)) {} + HCatBuffer(const char *buff) : buff_(new std::string(buff ? buff : "")) {} + HCatBuffer(const std::string &buff) : buff_(new std::string(buff)) {} + HCatBuffer(std::string &&buff) : buff_(new std::string(std::move(buff))) {} + HCatBuffer(const HCatBuffer &buff) : buff_(buff.buff_) {} + + std::string::iterator begin() { Detach(); return buff_->begin(); } + std::string::const_iterator begin() const { return buff_->begin(); } + std::string::iterator end() { Detach(); return buff_->end(); } + std::string::const_iterator end() const { return buff_->end(); } + + static bool isUpperCaseAscii(char c) { return c >= 'A' && c <= 'Z'; } + static bool isLowerCaseAscii(char c) { return c >= 'a' && c <= 'z'; } + bool isUpper() const { return !std::any_of(buff_->begin(), buff_->end(), isLowerCaseAscii); } + bool isLower() const { return !std::any_of(buff_->begin(), buff_->end(), isUpperCaseAscii); } + + static unsigned char asciiUpper(unsigned char c) { return c >= 'a' && c <= 'z' ? c & ~0x20 : c; } + static unsigned char asciiLower(unsigned char c) { return c >= 'A' && c <= 'Z' ? c | 0x20 : c; } + HCatBuffer toLower() const { + HCatBuffer result(*this); + std::transform(buff_->begin(), buff_->end(), result.begin(), asciiLower); + return result; + } + HCatBuffer toUpper() const { + HCatBuffer result(*this); + std::transform(buff_->begin(), buff_->end(), result.begin(), asciiUpper); + return result; + } + + std::string GetString() const { return *buff_; } + std::string GetString(std::size_t len) const { return buff_->substr(0, len); } + const std::string &GetConstString() const { return *buff_; } + std::string &GetRefString() { Detach(); return *buff_; } + + std::string::pointer Data() { Detach(); return &buff_->front(); } + std::string::const_pointer Data() const { return &buff_->front(); } + std::string::const_pointer ConstData() const { return buff_->data(); } + std::size_t Size() const { return buff_->size(); } + HCatBuffer &Swap(HCatBuffer &buff) { Detach(); buff_.swap(buff.buff_); return *this; } + std::string::reference At(std::size_t index) { Detach(); return buff_->at(index); } + std::string::const_reference At(std::size_t index) const { return buff_->at(index); } + bool Empty() const { return buff_->empty(); } + HCatBuffer &Clear() { Detach(); std::string().swap(*buff_); return *this; } + + std::string::reference operator [](std::size_t index) { Detach(); return buff_->at(index); } + std::string::const_reference operator [](std::size_t index) const { return buff_->at(index); } + + HCatBuffer &Insert(const char *buff, std::size_t index) { Detach(); buff_->insert(index, buff); return *this; } + HCatBuffer &Insert(const char *buff, std::size_t index, std::size_t len) { Detach(); buff_->insert(index, buff, len); return *this; } + HCatBuffer &Insert(const std::string &buff, std::size_t index) { Detach(); buff_->insert(index, buff); return *this; } + HCatBuffer &Insert(const HCatBuffer &buff, std::size_t index) { Detach(); buff_->insert(index, *buff.buff_); return *this; } + + HCatBuffer &Remove(std::size_t index, std::size_t num = std::string::npos) { + if (index > buff_->size()) { + index = buff_->size(); + } + Detach(); + buff_->erase(index, num); + return *this; + } + + HCatBuffer Mid(std::size_t index, std::size_t len = std::string::npos) const { + if (index >= buff_->size()) { + return HCatBuffer(); + } + if (len > buff_->size()) { + len = buff_->size(); + } + if (len > buff_->size() - index) { + len = buff_->size() - index; + } + if (index == 0 && len == buff_->size()) { + return *this; + } + return HCatBuffer(buff_->substr(index, len)); + } + + std::string::size_type Find(char value, std::size_t pos = 0) const { return buff_->find(value, pos); } + std::string::size_type Find(const char *value, std::size_t pos = 0) const { return buff_->find(value, pos); } + std::string::size_type Find(const std::string &value, std::size_t pos = 0) const { return buff_->find(value, pos); } + std::string::size_type IndexOf(char value, std::size_t pos = 0) const { return Find(value, pos); } + std::string::size_type IndexOf(const char *value, std::size_t pos = 0) const { return Find(value, pos); } + std::string::size_type IndexOf(const std::string &value, std::size_t pos = 0) const { return Find(value, pos); } + + std::string::size_type Rfind(char value, std::size_t pos = std::string::npos) const { return buff_->rfind(value, pos); } + std::string::size_type Rfind(const char *value, std::size_t pos = std::string::npos) const { return buff_->rfind(value, pos); } + std::string::size_type Rfind(const std::string &value, std::size_t pos = std::string::npos) const { return buff_->rfind(value, pos); } + std::string::size_type LastIndexOf(char value, std::size_t pos = std::string::npos) const { return Rfind(value, pos); } + std::string::size_type LastIndexOf(const char *value, std::size_t pos = std::string::npos) const { return Rfind(value, pos); } + std::string::size_type LastIndexOf(const std::string &value, std::size_t pos = std::string::npos) const { return Rfind(value, pos); } + + bool Contains(char c) const { return IndexOf(c) != std::string::npos; } + bool Contains(const char *c) const { return IndexOf(c) != std::string::npos; } + bool Contains(const std::string &c) const { return IndexOf(c) != std::string::npos; } + + HCatBuffer &Append(const std::string &buff) { Detach(); buff_->append(buff); return *this; } + HCatBuffer &Append(std::string &&buff) { Detach(); buff_->append(std::move(buff)); return *this; } + HCatBuffer &Append(const HCatBuffer &buff) { Detach(); buff_->append(*buff.buff_); return *this; } + HCatBuffer &Append(HCatBuffer &&buff) { Detach(); buff_->append(std::move(*buff.buff_)); return *this; } + HCatBuffer &Append(const char *buff) { if (buff == nullptr) { return *this; } Detach(); buff_->append(buff); return *this; } + HCatBuffer &Append(const char *buff, std::size_t size) { Detach(); buff_->append(buff, size); return *this; } + HCatBuffer &Append(const unsigned char *buff) { Detach(); buff_->append(reinterpret_cast(buff)); return *this; } + HCatBuffer &Append(const unsigned char *buff, std::size_t size) { Detach(); buff_->append(reinterpret_cast(buff), size); return *this; } + HCatBuffer &Append(const char buff) { Detach(); buff_->push_back(buff); return *this; } + HCatBuffer &Append(int len, const char buff) { Detach(); buff_->append(len, buff); return *this; } + HCatBuffer &Append(const unsigned char buff) { Detach(); buff_->push_back(static_cast(buff)); return *this; } + HCatBuffer &Append(int len, const unsigned char buff) { Detach(); buff_->append(len, static_cast(buff)); return *this; } + + HCatBuffer &Replace(const std::string &src, const std::string &dest) { + std::string::size_type pos = buff_->find(src); + if (pos == std::string::npos) { + return *this; + } + + Detach(); + buff_->replace(pos, src.size(), dest); + return *this; + } + + HCatBuffer Left(std::size_t len) const { + if (len >= buff_->size()) { + return *this; + } + return HCatBuffer(buff_->data(), len); + } + HCatBuffer Right(std::size_t len) const { + if (len >= buff_->size()) { + return *this; + } + return HCatBuffer((&(*buff_->end())) - len, len); + } + + bool StartsWith(const cat::HCatBuffer &other) const { + if (Size() < other.Size()) { + return false; + } + if (buff_ == other.buff_ || other.Size() == 0) { + return true; + } + return memcmp(ConstData(), other.ConstData(), other.Size()) == 0; + } + bool EndsWith(const cat::HCatBuffer &other) const { + if (Size() < other.Size()) { + return false; + } + if (buff_ == other.buff_ || other.Size() == 0) { + return true; + } + return memcmp((ConstData() + Size() - other.Size()), other.ConstData(), other.Size()) == 0; + } + + std::vector Split(const std::string &sep, bool keepEmpty = true) const { + std::vector result; + std::size_t startPos = 0; + std::size_t endPos = 0; + std::size_t extra = 0; + while ((endPos = buff_->find(sep, startPos + extra)) != std::string::npos) { + result.emplace_back(Mid(startPos, endPos - startPos)); + startPos = endPos + sep.size(); + extra = sep.size() == 0 ? 1 : 0; + } + if (startPos != buff_->size() || keepEmpty) { + result.emplace_back(Mid(startPos)); + } + return result; + } + std::vector Split(char sep, bool keepEmpty = true) const { return Split(std::string(1, sep), keepEmpty); } + static HCatBuffer Join(const std::vector &that, const cat::HCatBuffer &sep) { + std::size_t totalLen = 0; + const std::size_t size = that.size(); + for (std::size_t i = 0; i < size; ++i) { + totalLen += that.at(i).Size(); + } + if (size > 0) { + totalLen += sep.Size() * (size - 1); + } + + HCatBuffer result; + if (totalLen) { + result.buff_->reserve(totalLen); + } + for (std::size_t i = 0; i < size; ++i) { + if (i) { + result.Append(sep); + } + result.Append(that.at(i)); + } + return result; + } + static HCatBuffer Join(const std::vector &that, char sep) { return Join(that, HCatBuffer(1, sep)); } + + HCatBuffer Simplified() const { + if (buff_->empty()) { + return *this; + } + const char *srcPos = ConstData(); + const char *endPos = ConstData() + Size(); + cat::HCatBuffer result(Size()); + char *dst = result.Data(); + char *ptr = dst; + for (;;) { + while (srcPos != endPos && std::isspace(static_cast(*srcPos))) { + ++srcPos; + } + while (srcPos != endPos && !std::isspace(static_cast(*srcPos))) { + *ptr++ = *srcPos++; + } + if (srcPos == endPos) { + break; + } + *ptr++ = ' '; + } + if (ptr != dst && std::isspace(static_cast(ptr[-1]))) { + --ptr; + } + + std::size_t newLen = ptr - dst; + result.buff_->resize(newLen); + return result; + } + + static char ToHexLower(int value) noexcept { return "0123456789abcdef"[value & 0xF]; } + static char toHexUpper(int value) noexcept { return "0123456789ABCDEF"[value & 0xF]; } + HCatBuffer ToHex(char separator, bool upper = false) const { + if (buff_->empty()) { + return HCatBuffer(); + } + + const std::size_t length = separator ? (buff_->size() * 3 - 1) : (buff_->size() * 2); + HCatBuffer hex(length); + char *hexData = hex.Data(); + const unsigned char *data = reinterpret_cast(this->ConstData()); + for (std::size_t i = 0, o = 0; i < buff_->size(); ++i) { + if (upper) { + hexData[o++] = toHexUpper(data[i] >> 4); + hexData[o++] = toHexUpper(data[i] & 0xf); + } else { + hexData[o++] = ToHexLower(data[i] >> 4); + hexData[o++] = ToHexLower(data[i] & 0xf); + } + + if ((separator) && (o < length)) + hexData[o++] = separator; + } + + return hex; + } + + static int FromHex(int c) { + return ((c >= '0') && (c <= '9')) ? int(c - '0') : + ((c >= 'A') && (c <= 'F')) ? int(c - 'A' + 10) : + ((c >= 'a') && (c <= 'f')) ? int(c - 'a' + 10) : + /* otherwise */ -1; + } + static HCatBuffer FromHex(const HCatBuffer &hexEncoded) { + HCatBuffer res((hexEncoded.Size() + 1) / 2); + unsigned char *result = reinterpret_cast(res.Data() + res.Size()); + + bool odd_digit = true; + for (long i = hexEncoded.Size() - 1; i >= 0; --i) { + unsigned char ch = static_cast(hexEncoded.At(i)); + int tmp = FromHex(ch); + if (tmp == -1) + continue; + if (odd_digit) { + --result; + *result = tmp; + odd_digit = false; + } else { + *result |= tmp << 4; + odd_digit = true; + } + } + + res.Remove(0, result - reinterpret_cast(res.ConstData())); + return res; + } + + HCatBuffer ToBase64() const { + if (this->Empty()) { + return *this; + } + + const char alphabet_base64[] = "ABCDEFGH" "IJKLMNOP" "QRSTUVWX" "YZabcdef" + "ghijklmn" "opqrstuv" "wxyz0123" "456789+/"; + const char *const alphabet = alphabet_base64; + const char padchar = '='; + int padlen = 0; + const std::size_t sz = Size(); + HCatBuffer tmp((sz + 2) / 3 * 4); + + std::size_t i = 0; + char *out = tmp.Data(); + while (i < sz) { + int chunk = 0; + chunk |= int(static_cast(ConstData()[i++])) << 16; + if (i == sz) { + padlen = 2; + } else { + chunk |= int(static_cast(ConstData()[i++])) << 8; + if (i == sz) { + padlen = 1; + } else { + chunk |= int(static_cast(ConstData()[i++])); + } + } + + int j = (chunk & 0x00fc0000) >> 18; + int k = (chunk & 0x0003f000) >> 12; + int l = (chunk & 0x00000fc0) >> 6; + int m = (chunk & 0x0000003f); + *out++ = alphabet[j]; + *out++ = alphabet[k]; + + if (padlen > 1) { + *out++ = padchar; + } else { + *out++ = alphabet[l]; + } + if (padlen > 0) { + *out++ = padchar; + } else { + *out++ = alphabet[m]; + } + } + + std::size_t diffSize = out - tmp.ConstData(); + if (diffSize < tmp.Size()) { + tmp.buff_->resize(diffSize); + } + return tmp; + } + + static HCatBuffer FromBase64(const HCatBuffer &base64) { + if (base64.Empty()) { + return base64; + } + const auto inputSize = base64.Size(); + HCatBuffer result((inputSize * 3) / 4); + enum Base64Option { + Base64Encoding = 0, + Base64UrlEncoding = 1, + IgnoreBase64DecodingErrors = 0, + AbortOnBase64DecodingErrors = 4, + }; + Base64Option options = Base64Encoding; + + const char *input = base64.ConstData(); + char *output = result.Data(); + unsigned int buf = 0; + int nbits = 0; + + std::size_t offset = 0; + for (std::size_t i = 0; i < inputSize; ++i) { + int ch = input[i]; + int d; + + if (ch >= 'A' && ch <= 'Z') { + d = ch - 'A'; + } else if (ch >= 'a' && ch <= 'z') { + d = ch - 'a' + 26; + } else if (ch >= '0' && ch <= '9') { + d = ch - '0' + 52; + } else if (ch == '+' && (options & Base64UrlEncoding) == 0) { + d = 62; + } else if (ch == '-' && (options & Base64UrlEncoding) != 0) { + d = 62; + } else if (ch == '/' && (options & Base64UrlEncoding) == 0) { + d = 63; + } else if (ch == '_' && (options & Base64UrlEncoding) != 0) { + d = 63; + } else { + if (options & AbortOnBase64DecodingErrors) { + if (ch == '=') { + // can have 1 or 2 '=' signs, in both cases padding base64Size to + // a multiple of 4. Any other case is illegal. + if ((inputSize % 4) != 0) { + result.Clear(); + return result; + } else if ((i == inputSize - 1) || + (i == inputSize - 2 && input[++i] == '=')) { + d = -1; // ... and exit the loop, normally + } else { + result.Clear(); + return result; + } + } else { + result.Clear(); + return result; + } + } else { + d = -1; + } + } + + if (d != -1) { + buf = (buf << 6) | d; + nbits += 6; + if (nbits >= 8) { + nbits -= 8; + if (offset >= i) { + result.Clear(); + return result; + } + output[offset++] = buf >> nbits; + buf &= (1 << nbits) - 1; + } + } + } + + if (offset < result.Size()) { + result.buff_->resize(offset); + } + return result; + } + + int ToInt(int base = 10) const { + if (buff_->empty()) { + return 0; + } + + int result = 0; + try { +#if __cplusplus >= 201402L + result = std::stoi(buff_->data(), nullptr, base); +#else + result = strtol(buff_->data(), nullptr, base); +#endif + } catch(...) { + return result; + } + return result; + } + long long ToLongLong(int base = 10) const { + if (buff_->empty()) { + return 0; + } + + long long result = 0; + try { +#if __cplusplus >= 201402L + result = std::stoll(buff_->data(), nullptr, base); +#else + result = strtoll(buff_->data(), nullptr, base); +#endif + } catch(...) { + return result; + } + return result; + } + float ToFloat() const { + if (buff_->empty()) { + return 0.0; + } + + float result = 0.0; + try { +#if __cplusplus >= 201402L + result = std::stof(buff_->data()); +#else + result = strtof(buff_->data(), nullptr); +#endif + } catch(...) { + return result; + } + return result; + } + + HCatBuffer &SetNum(long long n, int base = 10) { + // big enough for MAX_ULLONG in base 2 + const int buffsize = 66; + char buff[buffsize]; + char *p = nullptr; + if (n < 0) { + p = LToS(buff + buffsize, static_cast(-(1 + n) + 1), base); + *--p = '-'; + } else { + p = LToS(buff + buffsize, static_cast(n), base); + } + Clear(); + return Append(p, buffsize - (p - buff)); + } + HCatBuffer &SetNum(unsigned long long n, int base = 10) { + // big enough for MAX_ULLONG in base 2 + const int buffsize = 66; + char buff[buffsize]; + char *p = LToS(buff + buffsize, n, base); + Clear(); + return Append(p, buffsize - (p - buff)); + } + + static HCatBuffer Number(int value, int base = 10) { HCatBuffer result; return result.SetNum(static_cast(value), base); } + static HCatBuffer Number(long long value, int base = 10) { HCatBuffer result; return result.SetNum(value, base); } + + + HCatBuffer operator +(const HCatBuffer &buff) const { return *buff_ + *buff.buff_; } + HCatBuffer operator +(const std::string &buff) const { return *buff_ + buff; } + HCatBuffer operator +(const char *buff) const { return *buff_ + buff; } + HCatBuffer operator +(const char buff) const { return *buff_ + buff; } + + HCatBuffer &operator +=(const HCatBuffer &buff) { return Append(buff); } + HCatBuffer &operator +=(const std::string &buff) { return Append(buff); } + HCatBuffer &operator +=(const char *buff) { return Append(buff); } + HCatBuffer &operator +=(const char buff) { return Append(buff); } + + HCatBuffer &operator =(const HCatBuffer &buff) { Detach(); buff_->assign(*buff.buff_); return *this; } + HCatBuffer &operator =(const std::string &buff) { Detach(); buff_->assign(buff); return *this; } + HCatBuffer &operator =(std::string &&buff) { Detach(); buff_->assign(std::move(buff)); return *this; } + HCatBuffer &operator =(const char *buff) { if (buff == nullptr) { return *this; } Detach(); buff_->assign(buff); return *this; } + + bool operator==(const HCatBuffer &buff) const { return *buff_ == *buff.buff_; } + bool operator==(const std::string &buff) const { return *buff_ == buff; } + bool operator==(const char *buff) const { return *buff_ == buff; } + + bool operator!=(const HCatBuffer &buff) const { return *buff_ != *buff.buff_; } + bool operator!=(const std::string &buff) const { return *buff_ != buff; } + bool operator!=(const char *buff) const { return *buff_ != buff; } + + bool operator<(const HCatBuffer &buff) const { return *buff_ < *buff.buff_; } + bool operator<=(const HCatBuffer &buff) const { return *buff_ < *buff.buff_; } + bool operator>(const HCatBuffer &buff) const { return *buff_ > *buff.buff_; } + bool operator>=(const HCatBuffer &buff) const { return *buff_ > *buff.buff_; } + +private: + void Detach() { + if (buff_.use_count() <= 1) { + return ; + } + + buff_.reset(new std::string(*buff_)); + } + + // Convert number to string + static char *LToS(char *p , unsigned long long n, int base) { + if (base < 2 || base > 36) { + base = 10; + } + const char b = 'a' - 10; + do { + const int c = n % base; + n /= base; + *--p = c + (c < 10 ? '0' : b); + } while (n); + + return p; + } + +private: + std::shared_ptr buff_; +}; + + +} + + +#endif // __HCATBUFFER_H__ diff --git a/SDK/HXml.cpp b/SDK/HXml.cpp new file mode 100644 index 0000000..958e8db --- /dev/null +++ b/SDK/HXml.cpp @@ -0,0 +1,350 @@ + + +#include +#include +#include + + + +namespace detail +{ + + +HXmlHelper::HXmlHelper(bool declaration) +{ + if (declaration) { + doc_.InsertFirstChild(doc_.NewDeclaration()); + } +} + + +HXml &HXmlHelper::FindElement(HXml &parent, const char *nodeName) +{ + // 当前自身是空节点, 是root节点 + if (parent.node_ == nullptr) { + parent.node_ = doc_.NewElement(nodeName); + doc_.InsertEndChild(parent.node_); + return AddElement(parent.node_); + } + + // 检查是否是根自身节点, 这里由于上面创建的新节点是给root节点 + // 这导致一个问题, root节点无法创建同名的子节点, 但子节点可以创建同名的孙子节点 + if (strcmp(parent.node_->Value(), nodeName) == 0) { + return parent; + } + + // 查找下一个节点 + tinyxml2::XMLElement *next = parent.node_->FirstChildElement(nodeName); + if (next == nullptr) { + next = parent.node_->InsertNewChildElement(nodeName); + } + + return AddElement(next); +} + + +const HXml &HXmlHelper::FindElement(const HXml &parent, const char *nodeName) const +{ + if (parent.node_ == nullptr) { + CAT_THROW(HXmlException(nodeName)); + } + + if (parent.node_ == doc_.RootElement()) { + if (strcmp(parent.node_->Value(), nodeName) == 0) { + return parent; + } + } + + // 查找下一个节点 + tinyxml2::XMLElement *next = parent.node_->FirstChildElement(nodeName); + if (next == nullptr) { + CAT_THROW(HXmlException(nodeName)); + } + for (const auto &i : node_){ + if (i->node_ == next) { + return *i; + } + } + CAT_THROW(HXmlException(nodeName)); +} + + +HXml &HXmlHelper::AddElement(tinyxml2::XMLElement *next) +{ + for (const auto &i : node_){ + if (i->node_ == next) { + return *i; + } + } + + node_.emplace_back(std::shared_ptr(new HXml(this, next))); + return *node_.back(); +} + + +} + + +tinyxml2::XMLElement *HXml::InitResultDoc(tinyxml2::XMLDocument &doc, const std::string &guid) +{ + tinyxml2::XMLDeclaration* declaration = doc.NewDeclaration(); + doc.InsertFirstChild(declaration); + tinyxml2::XMLElement* root = doc.NewElement("sdk"); + root->SetAttribute("guid", guid.data()); + doc.InsertEndChild(root); + return root; +} + + + +HXml::HXml() + : p_(new detail::HXmlHelper()) + , node_(nullptr) + , type_(kRoot) +{ + +} + + +HXml::HXml(tinyxml2::XMLElement *element, bool scan) + : HXml() +{ + if (element == nullptr) { + return ; + } + + p_->doc_.InsertEndChild(element->DeepClone(&p_->doc_)); + node_ = p_->doc_.RootElement(); + + if (scan) { + Scan(); + } +} + + +HXml::~HXml() +{ + if (p_ && (type_ == kRoot || type_ == kObj)) { + delete p_; + } +} + + +std::string HXml::Dump() const +{ + tinyxml2::XMLDocument *doc = nullptr; + switch (type_) { + case kRoot: { + if (!p_) { + return ""; + } + doc = &p_->doc_; + } break; + default: + if (node_ == nullptr) { + return ""; + } + doc = node_->GetDocument(); + break; + } + + if (doc == nullptr) { + return ""; + } + + tinyxml2::XMLPrinter xmlStr; + doc->Print(&xmlStr); + return xmlStr.CStr(); +} + + +bool HXml::ContainsNodes(const tinyxml2::XMLElement *node, const char *name) +{ + if (node == nullptr) { + return false; + } + + return node->FirstChildElement(name) != nullptr; +} + + + +bool HXml::ContainsAttribute(const tinyxml2::XMLElement *node, const char *name) +{ + if (node == nullptr) { + return false; + } + return node->FindAttribute(name) != nullptr; +} + + + +cat::HCatBuffer HXml::GetAttribute(const char *key, const char *defaultValue) const +{ + if (node_ == nullptr) { + return defaultValue; + } + + if (node_->FindAttribute(key) == nullptr) { + return defaultValue; + } + + return node_->Attribute(key); +} + + +HXml &HXml::operator[](const char *nodeName) +{ + return p_->FindElement(*this, nodeName); +} + + +const HXml &HXml::at(const char *nodeName) const +{ + return p_->FindElement(*this, nodeName); +} + + +void HXml::Scan() +{ + if (p_ == nullptr) { + return ; + } + + auto *root = p_->doc_.RootElement(); + Scan(root); +} + + +HXml &HXml::emplace_back(const cat::HCatBuffer &node, HXml &&sibling) +{ + tinyxml2::XMLElement *brother = p_->doc_.NewElement(node.ConstData()); + node_->InsertEndChild(brother); + return (p_->AddElement(brother) = sibling); +} + + +HXml &HXml::push_back(const cat::HCatBuffer &node, const HXml &sibling) +{ + tinyxml2::XMLElement *brother = p_->doc_.NewElement(node.ConstData()); + node_->InsertEndChild(brother); + return (p_->AddElement(brother) = sibling); +} + + +HXml &HXml::NewChild(const cat::HCatBuffer &node) +{ + tinyxml2::XMLElement *brother = p_->doc_.NewElement(node.ConstData()); + node_->InsertEndChild(brother); + return p_->AddElement(brother); +} + + +HXml &HXml::operator=(const HXml &value) +{ + switch (type_) { + case kObj: + // 这里是对象节点, + break; + case kRoot: { + // p_指针为空时说明追加对象只有属性 + if (value.p_ == nullptr) { + break; + } + + // root节点追加对象节点, 对象节点和root节点的node都是空, 比较检查p_指针就行 + if (value.type_ == kObj) { + if (p_ == nullptr) { + break; + } + + // 检查对象节点有需要追加的数据吗 + tinyxml2::XMLElement *root = value.p_->doc_.RootElement(); + if (!root) { + break; + } + + // 当前根节点是空节点的话直接复制对象节点数据 + if (p_->doc_.RootElement() == nullptr) { + value.p_->doc_.DeepCopy(&p_->doc_); + break; + } + + // 插入到根节点数据 + p_->doc_.RootElement()->InsertEndChild(root->DeepClone(&p_->doc_)); + break; + } + + // 这里追加子节点 [""] = {{}} + tinyxml2::XMLElement *root = value.p_->doc_.RootElement(); + if (root) { + node_->InsertEndChild(root->DeepClone(&p_->doc_)); + } + } break; + case kChild: { + // 子节点追加对象时需要追加对象节点的所有节点 to_xml()时 + if (value.type_ != kObj) { + break; + } + + // 这里追加类型转换出来的对象节点 [""] = class() + tinyxml2::XMLElement * root = value.p_->doc_.RootElement(); + if (root) { + node_->InsertEndChild(root->DeepClone(&p_->doc_)); + } + } break; + default: + break; + } + + // 当前无节点, 将属性保存到当前属性节点 + if (node_ == nullptr) { + attr_.insert(attr_.end(), value.attr_.begin(), value.attr_.end()); + return *this; + } + + // 将属性集合点的属性追加到这里 + for (const auto &i : value.attr_) { + if (i.first.Empty()) { + continue; + } + node_->SetAttribute(i.first.ConstData(), i.second.ConstData()); + } + return *this; +} + + +HXml::HXml(detail::HXmlHelper *p, tinyxml2::XMLElement *node) + : p_(p) + , node_(node) + , type_(kChild) +{ + +} + + +void HXml::Scan(tinyxml2::XMLElement *node) +{ + if (p_ == nullptr || node == nullptr) { + return ; + } + + for (auto *next = node->FirstChildElement(); next; next = next->NextSiblingElement()) { + p_->AddElement(next); + Scan(next); + } +} + +void HXmlIterator::operator++() const +{ + if (xml_ == nullptr || xml_->node_ == nullptr) { + return ; + } + + auto *p = xml_->node_->NextSiblingElement(xml_->node_->Value()); + if (p) { + xml_ = &xml_->p_->AddElement(p); + } else { + xml_ = nullptr; + } +} diff --git a/SDK/HXml.h b/SDK/HXml.h new file mode 100644 index 0000000..706e847 --- /dev/null +++ b/SDK/HXml.h @@ -0,0 +1,452 @@ + + +#ifndef __HXML_H__ +#define __HXML_H__ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + + +template +_Ret DataToType(const _Value &value) { + std::stringstream ss; + ss << value; + _Ret result; + ss >> result; + return result; +} +template <> +inline std::string DataToType(const cat::HCatBuffer &value) { + return value.GetString(); +} +template <> +inline std::string DataToType(const std::string &value) { + return value; +} +template <> +inline std::string DataToType(const bool &value) { + return value ? "true" : "false"; +} +template <> +inline bool DataToType(const std::string &value) { + return value == "true" ? true : value == "1" ? true : false; +} +template <> +inline bool DataToType(const cat::HCatBuffer &value) { + return DataToType(value.GetConstString()); +} + + +class HXml; +namespace detail +{ + + +template +struct static_const { static constexpr T value{}; }; + +template +constexpr T static_const::value; + +template struct priority_tag : priority_tag {}; +template<> struct priority_tag<0> {}; + +struct to_xml_fn +{ + template + auto operator()(BasicXmlType& j, T&& val) const + noexcept(noexcept(to_xml(j, std::forward(val)))) + -> decltype(to_xml(j, std::forward(val)), void()) + { + return call(j, std::forward(val), priority_tag<1>{}); + } + +private: + template + auto call(BasicXmlType& j, T&& val, priority_tag<1>) const + noexcept(noexcept(to_xml(j, std::forward(val)))) + -> decltype(to_xml(j, std::forward(val)), void()) + { + return to_xml(j, std::forward(val)); + } + + template + void call(BasicXmlType&, T&&, priority_tag<0>) const noexcept + { + static_assert(sizeof(BasicXmlType) == 0, "could not find to_xml() method in T's namespace"); + } +}; +struct from_xml_fn +{ +public: + template + auto operator()(const BasicXmlType& j, T&& val) const + noexcept(noexcept(from_xml(j, std::forward(val)))) + -> decltype(from_xml(j, std::forward(val)), void()) + { + return call(j, std::forward(val), priority_tag<1>{}); + } + +private: + template + auto call(const BasicXmlType& j, T&& val, priority_tag<1>) const + noexcept(noexcept(from_xml(j, std::forward(val)))) + -> decltype(from_xml(j, std::forward(val)), void()) + { + return from_xml(j, std::forward(val)); + } + template + void call(BasicXmlType&, T&&, priority_tag<0>) const noexcept + { + static_assert(sizeof(BasicXmlType) == 0, "could not find from_xml() method in T's namespace"); + } +}; + + +class HXmlHelper +{ +public: + explicit HXmlHelper(bool declaration = true); + + HXml &FindElement(HXml &parent, const char *nodeName); + const HXml &FindElement(const HXml &parent, const char *nodeName) const; + HXml &AddElement(tinyxml2::XMLElement *next); + +private: + friend class ::HXml; + tinyxml2::XMLDocument doc_; + std::list> node_; +}; + + +} + + +namespace +{ + + +constexpr const auto& to_xml = detail::static_const::value; +constexpr const auto& from_xml = detail::static_const::value; + + +} + + + + +///< HXml的异常 +class HXmlException : std::exception +{ +public: + explicit HXmlException(std::string &&e) : error(std::move(e)) {} + virtual const char* what() const noexcept override { return error.data(); } + + const std::string error; +}; + + +class HXmlIterator +{ +public: + explicit HXmlIterator(const HXml *xml) : xml_(xml) {} + + bool operator!=(const HXmlIterator &iterator) const { return iterator.xml_ != xml_; } + const HXml &operator*() { return *xml_; } + void operator++() const; + + +private: + mutable const HXml *xml_; +}; + + +class HXml +{ +public: + ///< 生成sdk返回的xml, 返回in节点 + static tinyxml2::XMLElement *InitResultDoc(tinyxml2::XMLDocument &doc, const std::string &guid); + + HXml(); + + ///< 将xml数据转换 + explicit HXml(tinyxml2::XMLElement *element, bool scan = true); + + HXml(HXml &&other) + : p_(other.p_) + , node_(other.node_) + , attr_(std::move(other.attr_)) + , type_(other.type_) + { + other.p_ = nullptr; + } + + ///< 这个用来追加xml节点, 请注意, xml需要root节点存在, to_xml实现会导致, 如果只是向节点追加子节点, 使用ToXml + template ::type, const char *>::value && + !std::is_same::type, char *>::value && + !std::is_same::type, std::string>::value && + !std::is_same::type, cat::HCatBuffer>::value && + !std::is_same::type, HXml>::value, _T>::type> + HXml(_T &&value) + : p_(new detail::HXmlHelper()) + , node_(nullptr) + , type_(kObj) + { + to_xml(*this, std::forward<_T>(value)); + } + + ///< 这个用于追加子节点 + template ::type, const char *>::value && + !std::is_same::type, char *>::value && + !std::is_same::type, std::string>::value && + !std::is_same::type, cat::HCatBuffer>::value && + !std::is_same::type, HXml>::value, _T>::type> + HXml &ToXml(_T &&value) { + to_xml(*this, std::forward<_T>(value)); + return *this; + } + + ///< 单个属性值生成 HXml + template + HXml(const char *key, _T &&value) : HXml(cat::HCatBuffer(key), std::forward<_T>(value)){} + template + HXml(const std::string &key, _T &&value) : HXml(cat::HCatBuffer(key), std::forward<_T>(value)){} + template ::type, const char *>::value && + !std::is_same::type, char *>::value && + !std::is_same::type, std::string>::value && + !std::is_same::type, cat::HCatBuffer>::value, _T>::type> + HXml(const cat::HCatBuffer &key, const _T &value) : HXml(key, cat::HCatBuffer(DataToType(value))) {} + HXml(const cat::HCatBuffer &key, const cat::HCatBuffer &value) + : p_(nullptr) + , node_(nullptr) + , attr_{{key, value}} + , type_(kChild) + {} + + ///< 生成属性列表 + HXml(std::initializer_list &&value) + : p_(nullptr) + , node_(nullptr) + , type_(kChild) + { + for (const auto &i : value) { + attr_.insert(attr_.end(), i.attr_.begin(), i.attr_.end()); + } + } + + ~HXml(); + + ///< 获取xml文本 + std::string Dump() const; + + ///< 获取对应的结构数据, 需自行实现 对于的 from_xml(const HXml &xml, class &userClass) + template + bool get_to(_T &value) const { + CAT_TRY { + from_xml(*this, value); + } CAT_CATCH (const HXmlException &e) { + return false; + } + + return true; + } + + ///< 递归检查当前节点的子节点是否存在该名 如当前节点node 一级节点 a 二级节点 b ContainsNodes("a", "b") 都存在返回true, 反之返回false + static bool ContainsNodes(const tinyxml2::XMLElement *node) { return node != nullptr; } + static bool ContainsNodes(const tinyxml2::XMLElement *node, const char *name); + template + bool ContainsNodes(const tinyxml2::XMLElement *node, const char *nodeName, _Args &&...args) const { + if (node == nullptr) { + return false; + } + const tinyxml2::XMLElement *next = node->FirstChildElement(nodeName); + return next != nullptr && ContainsNodes(next, std::forward<_Args>(args)...); + } + template + bool ContainsNodes(const char *nodeName, _Args &&...args) const { return ContainsNodes(node_, nodeName, std::forward<_Args>(args)...); } + + ///< 检查是否包含该属性 + static bool ContainsAttribute(const tinyxml2::XMLElement *node) { return node != nullptr; } + static bool ContainsAttribute(const tinyxml2::XMLElement *node, const char *name); + template + bool ContainsAttribute(const char *nodeName, _Args &&...args) const { + return ContainsAttribute(node_, nodeName) && ContainsAttribute(node_, std::forward<_Args>(args)...); + } + + ///< 获取属性 + cat::HCatBuffer GetAttribute(const char *key, const char *defaultValue = nullptr) const; + cat::HCatBuffer GetNodeName() const { if (node_ == nullptr) { return ""; } return node_->Value(); } + cat::HCatBuffer GetFirstChildNodeName() const { if (node_ == nullptr) { return ""; } auto node = node_->FirstChildElement(); return node ? node->Value() : ""; } + + ///< 设置文本 + HXml &SetText(const cat::HCatBuffer &text) { if (node_ == nullptr) { return *this; } node_->SetText(text.ConstData()); return *this; } + cat::HCatBuffer GetText() const { if (node_ == nullptr) { return ""; } return node_->GetText(); } + + ///< 获取节点名 + cat::HCatBuffer GetName() const { return node_ ? node_->Name() : ""; } + + ///< 获取子节点, 如不存在则创建 + ///< 无root节点会先创建root节点, 其余节点都在root节点下面 + ///< 如存在根节点后xml["root"] xml["root"]["sdk"] 和 xml["sdk"]是一样的 + HXml &operator[](const char *nodeName); + + ///< 获取子节点, 不存在则抛 HXmlException 异常 + const HXml &at(const char *nodeName) const; + + ///< 扫描节点, 生成所有对应的节点 + void Scan(); + + ///< 设置属性 + template + HXml &operator=(const std::pair &value) { + if (value.first == nullptr) { + return *this; + } + node_->SetAttribute(value.first, value.second); + return *this; + } + + + ///< HXml追加属性 + HXml &operator=(const HXml &value); + + ///< 追加兄弟节点 + HXml &emplace_back(const cat::HCatBuffer &node, HXml &&sibling); + HXml &push_back(const cat::HCatBuffer &node, const HXml &sibling); + HXml &NewChild(const cat::HCatBuffer &node); + + ///< 为了支持迭代兄弟节点, 但实际不存在HXml时将会创建 + HXmlIterator begin() const { return HXmlIterator(this); } + HXmlIterator end() const { return HXmlIterator(nullptr); } + + tinyxml2::XMLElement *GetNode() const { return node_; } + +private: + friend class detail::HXmlHelper; + friend class HXmlIterator; + + HXml(detail::HXmlHelper *p, tinyxml2::XMLElement *node); + + ///< 递归扫描所有节点 + void Scan(tinyxml2::XMLElement *node); + +private: + detail::HXmlHelper *p_; + tinyxml2::XMLElement *node_; + std::list> attr_; + enum { + kRoot, + kObj, + kChild, + } type_; +}; + + +#define CREATE_TAG_P(_doc, _parent, _node, _tagName) \ + _node = (_doc)->NewElement(_tagName); \ + if (_node == nullptr) { \ + code = cat::HErrorCode::kMemoryFailed; \ + break; \ + } else { \ + (_parent)->InsertEndChild(_node); \ + } + + +#define CREATE_TAG_ATTR(_doc, _node, _tagName, _attrName, _attrValue) \ + _node = (_doc)->NewElement(_tagName); \ + if (_node == nullptr) { \ + code = cat::HErrorCode::kMemoryFailed; \ + break; \ + } else { \ + _node->SetAttribute(_attrName, _attrValue); \ + } + + +#define CREATE_TAG_ATTR_P(_doc, _parent, _node, _tagName, _attrName, _attrValue)\ + _node = (_doc)->NewElement(_tagName); \ + if (_node == nullptr) { \ + code = cat::HErrorCode::kMemoryFailed; \ + break; \ + } else { \ + _node->SetAttribute(_attrName, _attrValue); \ + (_parent)->InsertEndChild(_node); \ + } + +#define PARSE_TAG_ATTR_P(_parent, _node, _tagName, _attrName, _attrValue) \ + _node = (_parent)->FirstChildElement(_tagName); \ + if (_node == nullptr) { \ + code = cat::HErrorCode::kParseXmlFailed; \ + break; \ + } else if (_node->FindAttribute(_attrName) == nullptr) { \ + code = cat::HErrorCode::kParseXmlFailed; \ + break; \ + } else { \ + _attrValue = _node->Attribute(_attrName); \ + } + +#define PARSE_TAG_ATTR_P_TYPE(_parent, _node, _tagName, _attrName, _attrValue, _type) \ + _node = (_parent)->FirstChildElement(_tagName); \ + if (_node == nullptr) { \ + code = cat::HErrorCode::kParseXmlFailed; \ + break; \ + } else if (_node->FindAttribute(_attrName) == nullptr) { \ + code = cat::HErrorCode::kParseXmlFailed; \ + break; \ + } else { \ + _attrValue = DataToType<_type>(_node->Attribute(_attrName)); \ + } + + +#define PARSE_TAG_ATTR_P_NULL(_parent, _node, _tagName, _attrName, _attrValue) \ + _node = (_parent)->FirstChildElement(_tagName); \ + if (_node == nullptr) { \ + _attrValue = _type(); \ + } else if (_node->FindAttribute(_attrName) == nullptr) { \ + code = cat::HErrorCode::kParseXmlFailed; \ + break; \ + } else { \ + _attrValue = _node->Attribute(_attrName); \ + } + + +#define PARSE_TAG_ATTR_P_NULL_TYPE(_parent, _node, _tagName, _attrName, _attrValue, _type) \ + _node = (_parent)->FirstChildElement(_tagName); \ + if (_node == nullptr) { \ + _attrValue = _type(); \ + } else if (_node->FindAttribute(_attrName) == nullptr) { \ + code = cat::HErrorCode::kParseXmlFailed; \ + break; \ + } else { \ + _attrValue = DataToType<_type>(_node->Attribute(_attrName)); \ + } + + +#define PARSE_TAG_ATTR(_node, _tagName, _attrName, _attrValue) \ + if (_node->FindAttribute(_attrName) == nullptr) { \ + code = cat::HErrorCode::kParseXmlFailed; \ + break; \ + } else { \ + _attrValue = _node->Attribute(_attrName); \ + } + +#define PARSE_TAG_ATTR_TYPE(_node, _tagName, _attrName, _attrValue, _type) \ + if (_node->FindAttribute(_attrName) == nullptr) { \ + code = cat::HErrorCode::kParseXmlFailed; \ + break; \ + } else { \ + _attrValue = DataToType<_type>(_node->Attribute(_attrName)); \ + } + +#endif // HXML_H diff --git a/SDK/SDKInfo.cpp b/SDK/SDKInfo.cpp new file mode 100644 index 0000000..b659f1f --- /dev/null +++ b/SDK/SDKInfo.cpp @@ -0,0 +1,833 @@ + + +#include "HDSDK.h" +#include "HScreenFunctionInfo.h" +#include "HSensorInfo.h" +#include +#include +#include +#include +#include +#include + + +namespace detail +{ + + +template +cat::HCatBuffer GetNode(const _T &) { return _T::GetMethod(); } +template +cat::HCatBuffer SetNode(const _T &) { return _T::SetMethod(); } + + +} + + +ISDKInfo DLL_CALL CreateSDKInfo() +{ + return new sdk::HSDKInfo(); +} + +void DLL_CALL FreeSDKInfo(sdk::ISDKInfo info) +{ + delete info; +} + + +HBool DLL_CALL ParseXml(const char *xml, int len, ISDKInfo info) +{ + if (xml == nullptr || info == nullptr || len <= 0) { + return HFalse; + } + + tinyxml2::XMLDocument doc; + doc.Parse(xml, len); + if (doc.Error()) { + return HFalse; + } + + tinyxml2::XMLElement *sdk = doc.FirstChildElement("sdk"); + if (!sdk) { + printf("read xml error, sdk tag not found\n"); + return HFalse; + } + + tinyxml2::XMLElement *node = sdk->FirstChildElement("out"); + if (!node) { + printf("read xml error, out tag not found\n"); + return HFalse; + } + + while (node) { + cat::HCatBuffer method(node->Attribute("method")); + if (info->ParseInfo(node, method) == 0) { + return HFalse; + } + + node = node->NextSiblingElement("out"); + } + + return HTrue; +} + +HBool UpdateItem(IHDProtocol protocol, ISDKInfo info, int updateItem) +{ + if (protocol == nullptr || info == nullptr) { + return HFalse; + } + + HXml xml; + xml["sdk"] = {"guid", "##GUID"}; + +// 存在配置信息的Get项 +#define GET_DATA_ITEM(item, obj) \ + case item: { \ + xml["sdk"]["in"] = {"method", detail::GetNode(obj)}; \ + xml["sdk"]["in"].ToXml(obj); \ + } break; + +// 常规Get项 +#define GET_ITEM(item, obj) \ + case item: { \ + xml["sdk"]["in"] = {"method", detail::GetNode(obj)}; \ + } break; + +// 常规Set项 +#define SET_ITEM(item, obj) \ + case item: { \ + xml["sdk"]["in"] = {"method", detail::SetNode(obj)}; \ + xml["sdk"]["in"].ToXml(obj); \ + } break; + +// 多处理常规Set和Get系列 +#define GET_SET_ITEM(getItem, setItem, obj) \ + GET_ITEM(getItem, obj); \ + SET_ITEM(setItem, obj); + + + switch (updateItem) { + GET_SET_ITEM(kGetLightInfo, kSetLightInfo, info->lightInfo); + GET_SET_ITEM(kGetSystemVolumeInfo, kSetSystemVolumeInfo, info->systemVolumeInfo); + GET_SET_ITEM(kGetTcpServerInfo, kSetTcpServerInfo, info->tcpSercerInfo); + GET_SET_ITEM(kGetTimeInfo, kSetTimeInfo, info->timeInfo); + GET_SET_ITEM(kGetEthInfo, kSetEthInfo, info->ethInfo); + GET_SET_ITEM(kGetWifiInfo, kSetWifiInfo, info->wifiInfo); + GET_SET_ITEM(kGetPppoeInfo, kSetPppoeInfo, info->pppoeInfo); + GET_SET_ITEM(kGetDeviceNameInfo, kSetDeviceNameInfo, info->deviceNameInfo); + GET_SET_ITEM(kGetSwitchTimeInfo, kSetSwitchTimeInfo, info->switchTimeInfo); + GET_SET_ITEM(kGetRelayInfo, kSetRelayInfo, info->relayInfo); + + GET_ITEM(kGetDeviceInfo, info->deviceInfo); + GET_DATA_ITEM(kGetScreenShot, info->screenShot2); + default: + return HFalse; + } + + std::string buff = xml.Dump(); + return SendXml(protocol, buff.c_str(), buff.size()) ? HTrue : HFalse; + +#undef GET_DATA_ITEM +#undef GET_ITEM +#undef SET_ITEM +#undef SET_ITEM_INFO +#undef GET_SET_ITEM +} + +void SetLightInfo(ISDKInfo info, int mode, int defaultModeLight) +{ + info->lightInfo.mode = static_cast(mode); + info->lightInfo.defaultValue = cat::HCatBuffer::Number(defaultModeLight); +} + +void SetLightInfoSensor(ISDKInfo info, int min, int max, int time) +{ + info->lightInfo.sensor.min = std::max(1, min); + info->lightInfo.sensor.max = std::min(max, 100); + info->lightInfo.sensor.time = std::max(5, std::min(15, time)); +} + +void AddLightInfoPloy(ISDKInfo info, HBool enable, const char *startTime, int percent) +{ + sdk::LightInfo::Ploy item; + item.enable = enable; + item.percent = percent; + item.start = cat::HCatBuffer(startTime); + + info->lightInfo.ployList.emplace_back(std::move(item)); +} + +void SetLightInfoPloy(ISDKInfo info, int index, HBool enable, const char *startTime, int percent) +{ + if (index < 0 || index >= static_cast(info->lightInfo.ployList.size())) { + return ; + } + + info->lightInfo.ployList[index].enable = enable != HFalse; + info->lightInfo.ployList[index].start = cat::HCatBuffer(startTime); + info->lightInfo.ployList[index].percent = percent; +} + +void ClearLightInfoPloy(ISDKInfo info) +{ + info->lightInfo.ployList.clear(); +} + +int GetLightInfoMode(ISDKInfo info) +{ + return info->lightInfo.mode; +} + +int GetLightInfoDefaultLight(ISDKInfo info) +{ + return info->lightInfo.defaultValue.ToInt(); +} + +int GetLightInfoPloySize(ISDKInfo info) +{ + return info->lightInfo.ployList.size(); +} + +int GetLightInfoPloyEnable(ISDKInfo info, int index) +{ + if (index < 0 || index >= static_cast(info->lightInfo.ployList.size())) { + return 0; + } + + return info->lightInfo.ployList.at(index).enable; +} + +int GetLightInfoPloyPercent(ISDKInfo info, int index) +{ + if (index < 0 || index >= static_cast(info->lightInfo.ployList.size())) { + return 0; + } + + return info->lightInfo.ployList.at(index).percent; +} + +const char *GetLightInfoPloyStart(ISDKInfo info, int index) +{ + if (index < 0 || index >= static_cast(info->lightInfo.ployList.size())) { + return nullptr; + } + + return info->lightInfo.ployList.at(index).start.ConstData(); +} + +int GetLightInfoSensorMax(ISDKInfo info) +{ + return info->lightInfo.sensor.max; +} + +int GetLightInfoSensorMin(ISDKInfo info) +{ + return info->lightInfo.sensor.min; +} + +int GetLightInfoSensorTime(ISDKInfo info) +{ + return info->lightInfo.sensor.time; +} + +void SetSystemVolumeInfo(ISDKInfo info, int mode, int volume) +{ + info->systemVolumeInfo.mode = mode; + info->systemVolumeInfo.volume = cat::HCatBuffer::Number(std::min(100, std::max(volume, 0))); +} + +void AddSystemVolumeInfoPloy(ISDKInfo info, int enable, const char *time, int volume) +{ + sdk::SystemVolumeInfo::Ploy item; + item.enable = enable; + item.volume = std::min(100, std::max(volume, 0)); + item.time = cat::HCatBuffer(time); + info->systemVolumeInfo.ploys.emplace_back(std::move(item)); +} + +void ClearSystemVolumeInfoPloy(ISDKInfo info) +{ + info->systemVolumeInfo.ploys.clear(); +} + +int GetSystemVolumeInfoMode(ISDKInfo info) +{ + return info->systemVolumeInfo.mode; +} + +int GetSystemVolumeInfoVolume(ISDKInfo info) +{ + return info->systemVolumeInfo.volume.ToInt(); +} + +int GetSystemVolumeInfoPloySize(ISDKInfo info) +{ + return info->systemVolumeInfo.ploys.size(); +} + +int GetSystemVolumeInfoPloyEnable(ISDKInfo info, int index) +{ + if (index < 0 || index >= static_cast(info->systemVolumeInfo.ploys.size())) { + return HFalse; + } + + return info->systemVolumeInfo.ploys.at(index).enable ? HTrue : HFalse; +} + +const char *GetSystemVolumeInfoPloyTime(ISDKInfo info, int index) +{ + if (index < 0 || index >= static_cast(info->systemVolumeInfo.ploys.size())) { + return nullptr; + } + + return info->systemVolumeInfo.ploys.at(index).time.ConstData(); +} + +int GetSystemVolumeInfoPloyVolume(ISDKInfo info, int index) +{ + if (index < 0 || index >= static_cast(info->systemVolumeInfo.ploys.size())) { + return 0; + } + + return info->systemVolumeInfo.ploys.at(index).volume; +} + +void SetTcpServerInfo(ISDKInfo info, const char *ip, huint16 port) +{ + info->tcpSercerInfo.host = cat::HCatBuffer(ip); + info->tcpSercerInfo.port = port; +} + +const char *GetTcpServerInfoIp(ISDKInfo info) +{ + return info->tcpSercerInfo.host.ConstData(); +} + +huint16 GetTcpServerInfoPort(ISDKInfo info) +{ + return info->tcpSercerInfo.port; +} + +void SetTimeInfo(ISDKInfo info, const char *timeZone, int summer, const char *sync, const char *currTime, const char *serverList) +{ + info->timeInfo.timeZone = cat::HCatBuffer(timeZone); + info->timeInfo.summer = summer == HTrue; + info->timeInfo.sync = cat::HCatBuffer(sync); + info->timeInfo.currTime = cat::HCatBuffer(currTime); + info->timeInfo.serverList = cat::HCatBuffer(serverList); +} + +const char *GetTimeInfoTimeZone(ISDKInfo info) +{ + return info->timeInfo.timeZone.ConstData(); +} + +int GetTimeInfoSummer(ISDKInfo info) +{ + return info->timeInfo.summer ? HTrue : HFalse; +} + +const char *GetTimeInfoSync(ISDKInfo info) +{ + return info->timeInfo.sync.ConstData(); +} + +const char *GetTimeInfoCurrTime(ISDKInfo info) +{ + return info->timeInfo.currTime.ConstData(); +} + +const char *GetTimeInfoServerList(ISDKInfo info) +{ + return info->timeInfo.serverList.ConstData(); +} + +void SetEthInfo(sdk::ISDKInfo info, HBool dhcp, const char *ip, const char *netmask, const char *gateway, const char *dns) +{ + info->ethInfo.dhcp = dhcp != HFalse; + info->ethInfo.ip = cat::HCatBuffer(ip); + info->ethInfo.netmask = cat::HCatBuffer(netmask); + info->ethInfo.gateway = cat::HCatBuffer(gateway); + info->ethInfo.dns = cat::HCatBuffer(dns); +} + +HBool GetEhtInfoDhcp(sdk::ISDKInfo info) +{ + return info->ethInfo.dhcp ? HTrue : HFalse; +} + +const char *GetEhtInfoIp(sdk::ISDKInfo info) +{ + return info->ethInfo.ip.ConstData(); +} + +const char *GetEhtInfoNetmask(sdk::ISDKInfo info) +{ + return info->ethInfo.netmask.ConstData(); +} + +const char *GetEhtInfoGateway(sdk::ISDKInfo info) +{ + return info->ethInfo.gateway.ConstData(); +} + +const char *GetEhtInfoDns(sdk::ISDKInfo info) +{ + return info->ethInfo.dns.ConstData(); +} + +void SetWifiInfo(sdk::ISDKInfo info, int mode) +{ + if (mode == 1) { + info->wifiInfo.mode = "station"; + } else { + info->wifiInfo.mode = "ap"; + } +} + +void SetWifiInfoAp(sdk::ISDKInfo info, const char *ssid, const char *password, const char *ip) +{ + info->wifiInfo.ap.ssid = cat::HCatBuffer(ssid); + info->wifiInfo.ap.password = cat::HCatBuffer(password); + info->wifiInfo.ap.ipAddress = cat::HCatBuffer(ip); + info->wifiInfo.ap.channel = 0; +} + +void SetWifiInfoStation(sdk::ISDKInfo info, const char *ssid, const char *password, int dhcp) +{ + info->wifiInfo.stationIndex = 0; + if (info->wifiInfo.station.size() > 1) { + info->wifiInfo.station.clear(); + } + if (info->wifiInfo.station.empty()) { + info->wifiInfo.station.emplace_back(sdk::WifiInfo::StationConfig()); + } + + info->wifiInfo.station.front().dhcp = dhcp != HFalse; + info->wifiInfo.station.front().ssid = cat::HCatBuffer(ssid); + info->wifiInfo.station.front().password = cat::HCatBuffer(password); +} + +void SetWifiInfoStationNet(sdk::ISDKInfo info, const char *ip, const char *mask, const char *gateway, const char *dns) +{ + info->wifiInfo.stationIndex = 0; + if (info->wifiInfo.station.size() > 1) { + info->wifiInfo.station.clear(); + } + if (info->wifiInfo.station.empty()) { + info->wifiInfo.station.emplace_back(sdk::WifiInfo::StationConfig()); + } + + info->wifiInfo.station.front().ip = cat::HCatBuffer(ip); + info->wifiInfo.station.front().mask = cat::HCatBuffer(mask); + info->wifiInfo.station.front().gateway = cat::HCatBuffer(gateway); + info->wifiInfo.station.front().dns = cat::HCatBuffer(dns); +} + +int GetWifiInfoMode(sdk::ISDKInfo info) +{ + if (info->wifiInfo.mode == "station") { + return 1; + } + + return 0; +} + +const char *GetWifiInfoApSsid(sdk::ISDKInfo info) +{ + return info->wifiInfo.ap.ssid.ConstData(); +} + +const char *GetWifiInfoApPassword(sdk::ISDKInfo info) +{ + return info->wifiInfo.ap.password.ConstData(); +} + +const char *GetWifiInfoApIp(sdk::ISDKInfo info) +{ + return info->wifiInfo.ap.ipAddress.ConstData(); +} + +const char *GetWifiInfoStationSsid(sdk::ISDKInfo info) +{ + return info->wifiInfo.GetCurrentStation().ssid.ConstData(); +} + +HBool GetWifiInfoStationDhcp(sdk::ISDKInfo info) +{ + return info->wifiInfo.GetCurrentStation().dhcp ? HTrue : HFalse; +} + +const char *GetWifiInfoStationIp(sdk::ISDKInfo info) +{ + return info->wifiInfo.GetCurrentStation().ip.ConstData(); +} + +const char *GetWifiInfoStationMask(sdk::ISDKInfo info) +{ + return info->wifiInfo.GetCurrentStation().mask.ConstData(); +} + +const char *GetWifiInfoStationGateway(sdk::ISDKInfo info) +{ + return info->wifiInfo.GetCurrentStation().gateway.ConstData(); +} + +const char *GetWifiInfoStationDns(sdk::ISDKInfo info) +{ + return info->wifiInfo.GetCurrentStation().dns.ConstData(); +} + +void SetPppoeInfoApn(sdk::ISDKInfo info, const char *apn) +{ + info->pppoeInfo.apn = cat::HCatBuffer(apn); +} + +HBool GetPppoeInfoVaild(sdk::ISDKInfo info) +{ + return info->pppoeInfo.vaild ? HTrue : HFalse; +} + +const char *GetPppoeInfoApn(sdk::ISDKInfo info) +{ + return info->pppoeInfo.apn.ConstData(); +} + +void SetDeviceNameInfo(sdk::ISDKInfo info, const char *name) +{ + info->deviceNameInfo.name = cat::HCatBuffer(name); +} + +const char *GetDeviceNameInfo(sdk::ISDKInfo info) +{ + return info->deviceNameInfo.name.ConstData(); +} + +void SetSwitchTimeInfo(sdk::ISDKInfo info, int mode, int enable) +{ + info->switchTimeInfo.mode = mode; + info->switchTimeInfo.ployEnable = enable != HFalse; +} + +void AddSwitchTimeInfoItem(sdk::ISDKInfo info, HBool enable, const char *start, const char *end) +{ + sdk::SwitchTimeInfo::ployItem item; + item.enable = enable != HFalse; + item.start = cat::HCatBuffer(start); + item.end = cat::HCatBuffer(end); + info->switchTimeInfo.ploys.emplace_back(std::move(item)); +} + +void ClearSwitchTimeInfoItem(sdk::ISDKInfo info) +{ + info->switchTimeInfo.ploys.clear(); +} + +HBool SetSwitchTimeInfoItem(sdk::ISDKInfo info, int index, HBool enable, const char *start, const char *end) +{ + if (index < 0 || index >= static_cast(info->switchTimeInfo.ploys.size())) { + return HFalse; + } + + info->switchTimeInfo.ploys[index].enable = enable != HFalse; + info->switchTimeInfo.ploys[index].start = cat::HCatBuffer(start); + info->switchTimeInfo.ploys[index].end = cat::HCatBuffer(end); + return HTrue; +} + +void AddSwitchTimeInfoWeekItem(sdk::ISDKInfo info, int week, HBool openAllDay, const char *start, const char *end) +{ + if (week < 0 || week >= static_cast(sdk::SwitchTimeInfo::GetWeekMax())) { + return ; + } + + sdk::SwitchTimeInfo::weekItem item; + item.start = cat::HCatBuffer(start); + item.end = cat::HCatBuffer(end); + info->switchTimeInfo.GetWeekItem(week).openAllDay = openAllDay != HFalse; + info->switchTimeInfo.GetWeekItem(week).ploys.emplace_back(std::move(item)); +} + +void ClearSwitchTimeInfoWeekItem(sdk::ISDKInfo info, int week) +{ + if (week < 0 || week >= static_cast(sdk::SwitchTimeInfo::GetWeekMax())) { + return ; + } + + info->switchTimeInfo.GetWeekItem(week).ploys.clear(); +} + +void SetSwitchTimeInfoWeekItem(sdk::ISDKInfo info, int week, int index, HBool openAllDay, const char *start, const char *end) +{ + if (week < 0 || week >= static_cast(sdk::SwitchTimeInfo::GetWeekMax())) { + return ; + } + + if (index < 0 || index >= static_cast(info->switchTimeInfo.weekPloys.size())) { + return ; + } + + info->switchTimeInfo.GetWeekItem(week).openAllDay = openAllDay != HFalse; + info->switchTimeInfo.GetWeekItem(week).ploys[index].start = cat::HCatBuffer(start); + info->switchTimeInfo.GetWeekItem(week).ploys[index].end = cat::HCatBuffer(end); +} + +int GetSwitchTimeInfoItemSize(sdk::ISDKInfo info) +{ + return info->switchTimeInfo.ploys.size(); +} + +int GetSwitchTimeInfoWeekItemSize(sdk::ISDKInfo info, int week) +{ + if (week < 0 || week >= static_cast(sdk::SwitchTimeInfo::GetWeekMax())) { + return 0; + } + + return info->switchTimeInfo.GetWeekItem(week).ploys.size(); +} + +HBool GetSwitchTimeInfoEnable(sdk::ISDKInfo info) +{ + return info->switchTimeInfo.ployEnable ? HTrue : HFalse; +} + +HBool GetSwitchTimeInfoItemEnable(sdk::ISDKInfo info, int index) +{ + if (index < 0 || index >= static_cast(info->switchTimeInfo.ploys.size())) { + return HFalse; + } + + return info->switchTimeInfo.ploys.at(index).enable ? HTrue : HFalse; +} + +const char *GetSwitchTimeInfoItemStart(sdk::ISDKInfo info, int index) +{ + if (index < 0 || index >= static_cast(info->switchTimeInfo.ploys.size())) { + return nullptr; + } + + return info->switchTimeInfo.ploys.at(index).start.ConstData(); +} + +const char *GetSwitchTimeInfoItemEnd(sdk::ISDKInfo info, int index) +{ + if (index < 0 || index >= static_cast(info->switchTimeInfo.ploys.size())) { + return nullptr; + } + + return info->switchTimeInfo.ploys.at(index).end.ConstData(); +} + +void SetRelayInfoItem(sdk::ISDKInfo info, int index, const char *name, HBool useSwitch) +{ + info->relayInfo.InitRelayList(); + if (index < 0 || index >= static_cast(info->relayInfo.relayList.size())) { + return ; + } + + info->relayInfo.relayList[index].name = cat::HCatBuffer(name); + info->relayInfo.relayList[index].useSwitch = useSwitch != HFalse; +} + +void AddRelayInfoItemPloy(sdk::ISDKInfo info, int index, const char *start, const char *end) +{ + info->relayInfo.InitRelayList(); + if (index >= static_cast(info->relayInfo.relayList.size())) { + return ; + } + + sdk::RelayInfo::ployItem item; + item.start = cat::HCatBuffer(start); + item.end = cat::HCatBuffer(end); + info->relayInfo.relayList[index].ploys.emplace_back(std::move(item)); +} + +void ClearRelayInfoItemPloy(sdk::ISDKInfo info, int index) +{ + info->relayInfo.InitRelayList(); + if (index < 0 || index >= static_cast(info->relayInfo.relayList.size())) { + return ; + } + + info->relayInfo.relayList[index].ploys.clear(); +} + +void SetRelayInfoItemPloyItem(sdk::ISDKInfo info, int index, int itemIndex, const char *start, const char *end) +{ + info->relayInfo.InitRelayList(); + if (index < 0 || index >= static_cast(info->relayInfo.relayList.size())) { + return ; + } + + if (itemIndex < 0 || itemIndex >= static_cast(info->relayInfo.relayList.at(index).ploys.size())) { + return ; + } + + info->relayInfo.relayList[index].ploys[itemIndex].start = cat::HCatBuffer(start); + info->relayInfo.relayList[index].ploys[itemIndex].end = cat::HCatBuffer(end); +} + +void SetRelayInfoInternal(sdk::ISDKInfo info, const char *name, HBool useSwitch) +{ + info->relayInfo.internal.name = cat::HCatBuffer(name); + info->relayInfo.internal.useSwitch = useSwitch != HFalse; +} + +void AddRelayInfoInternalPloy(sdk::ISDKInfo info, const char *start, const char *end) +{ + sdk::RelayInfo::ployItem item; + item.start = cat::HCatBuffer(start); + item.end = cat::HCatBuffer(end); + info->relayInfo.internal.ploys.emplace_back(std::move(item)); +} + +void ClearRelayInfoInternalPloy(sdk::ISDKInfo info) +{ + info->relayInfo.internal.ploys.clear(); +} + +void SetRelayInfoInternalPloyItem(sdk::ISDKInfo info, int index, const char *start, const char *end) +{ + if (index < 0 || index >= static_cast(info->relayInfo.internal.ploys.size())) { + return ; + } + + info->relayInfo.internal.ploys[index].start = cat::HCatBuffer(start); + info->relayInfo.internal.ploys[index].end = cat::HCatBuffer(end); +} + +int GetRelayInfoStatus(sdk::ISDKInfo info, int index) +{ + if (index < 0 || index >= static_cast(info->relayInfo.relayList.size())) { + return 0; + } + + return info->relayInfo.relayList.at(index).relayStatus; +} + +const char *GetRelayInfoName(sdk::ISDKInfo info, int index) +{ + if (index < 0 || index >= static_cast(info->relayInfo.relayList.size())) { + return nullptr; + } + + return info->relayInfo.relayList.at(index).name.ConstData(); +} + +HBool GetRelayInfoUseSwitch(sdk::ISDKInfo info, int index) +{ + if (index < 0 || index >= static_cast(info->relayInfo.relayList.size())) { + return HFalse; + } + + return info->relayInfo.relayList.at(index).useSwitch ? HTrue : HFalse; +} + +int GetRelayInfoItemPloySize(sdk::ISDKInfo info, int index) +{ + if (index < 0 || index >= static_cast(info->relayInfo.relayList.size())) { + return 0; + } + + return info->relayInfo.relayList.at(index).ploys.size(); +} + +const char *GetRelayInfoItemPloyStart(sdk::ISDKInfo info, int index, int itemIndex) +{ + if (index < 0 || index >= static_cast(info->relayInfo.relayList.size())) { + return nullptr; + } + + if (itemIndex < 0 || itemIndex >= static_cast(info->relayInfo.relayList.at(index).ploys.size())) { + return nullptr; + } + + return info->relayInfo.relayList.at(index).ploys.at(itemIndex).start.ConstData(); +} + +const char *GetRelayInfoItemPloyEnd(sdk::ISDKInfo info, int index, int itemIndex) +{ + if (index < 0 || index >= static_cast(info->relayInfo.relayList.size())) { + return nullptr; + } + + if (itemIndex < 0 || itemIndex >= static_cast(info->relayInfo.relayList.at(index).ploys.size())) { + return nullptr; + } + + return info->relayInfo.relayList.at(index).ploys.at(itemIndex).end.ConstData(); +} + +int GetRelayInfoInternalPloySize(sdk::ISDKInfo info) +{ + return info->relayInfo.internal.ploys.size(); +} + +const char *GetRelayInfoInternalPloyStart(sdk::ISDKInfo info, int index) +{ + if (index < 0 || index >= static_cast(info->relayInfo.internal.ploys.size())) { + return nullptr; + } + + return info->relayInfo.internal.ploys.at(index).start.ConstData(); +} + +const char *GetRelayInfoInternalPloyEnd(sdk::ISDKInfo info, int index) +{ + if (index < 0 || index >= static_cast(info->relayInfo.internal.ploys.size())) { + return nullptr; + } + + return info->relayInfo.internal.ploys.at(index).end.ConstData(); +} + +const char *GetDevceInfoId(ISDKInfo info) +{ + return info->deviceInfo.device.id.ConstData(); +} + +const char *GetDevceInfoName(ISDKInfo info) +{ + return info->deviceInfo.device.name.ConstData(); +} + +const char *GetDevceInfoAppVersion(ISDKInfo info) +{ + return info->deviceInfo.version.app.ConstData(); +} + +const char *GetDevceInfoFpgaVersion(ISDKInfo info) +{ + return info->deviceInfo.version.fpga.ConstData(); +} + +int GetDevceInfoScreenRotation(ISDKInfo info) +{ + return info->deviceInfo.screen.rotation; +} + +int GetDevceInfoScreenWidth(ISDKInfo info) +{ + return info->deviceInfo.screen.width; +} + +int GetDevceInfoScreenHeight(ISDKInfo info) +{ + return info->deviceInfo.screen.height; +} + +void SetScreenShot(ISDKInfo info, int width, int height) +{ + info->screenShot2.width = width; + info->screenShot2.height = height; +} + +const char *GetScreenShot(ISDKInfo info) +{ + return info->screenShot2.rawData.ConstData(); +} + +int GetScreenShotSize(sdk::ISDKInfo info) +{ + return info->screenShot2.rawData.Size(); +} diff --git a/SDK/SDKInfo.h b/SDK/SDKInfo.h new file mode 100644 index 0000000..e3a88be --- /dev/null +++ b/SDK/SDKInfo.h @@ -0,0 +1,267 @@ + + +#ifndef __ISDKINFO_H__ +#define __ISDKINFO_H__ + + +#include + +#ifdef USE_HD_LIB +namespace sdk{ +typedef struct HSDKInfo* ISDKInfo; +} +using sdk::ISDKInfo; +#else +typedef void* ISDKInfo; +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +///< 创建信息体 +HD_API ISDKInfo DLL_CALL CreateSDKInfo(); +///< 释放信息体 +HD_API void DLL_CALL FreeSDKInfo(ISDKInfo info); +///< 解析xml生成对应数据信息 +HD_API HBool DLL_CALL ParseXml(const char *xml, int len, ISDKInfo info); + +enum eUpdateItem { + kGetLightInfo = 0x1000, ///< 获取亮度信息 + kSetLightInfo = 0x1001, ///< 设置亮度信息 + kGetSystemVolumeInfo = 0x1002, ///< 获取系统音量 + kSetSystemVolumeInfo = 0x1003, ///< 设置系统音量 + kGetTcpServerInfo = 0x1004, ///< 获取tcp服务器 + kSetTcpServerInfo = 0x1005, ///< 设置tcp服务器 + kGetTimeInfo = 0x1006, ///< 获取时间信息 + kSetTimeInfo = 0x1007, ///< 设置时间信息 + kGetEthInfo = 0x1008, ///< 获取有线信息 + kSetEthInfo = 0x1009, ///< 设置有线信息 + kGetWifiInfo = 0x1010, ///< 获取Wifi信息 + kSetWifiInfo = 0x1011, ///< 设置Wifi信息 + kGetPppoeInfo = 0x1012, ///< 获取pppoe信息 + kSetPppoeInfo = 0x1013, ///< 设置pppoe信息 + kGetDeviceNameInfo = 0x1014, ///< 获取设备名信息 + kSetDeviceNameInfo = 0x1015, ///< 设置设备名信息 + kGetSwitchTimeInfo = 0x1016, ///< 获取开关机信息 + kSetSwitchTimeInfo = 0x1017, ///< 设置开关机信息 + kGetRelayInfo = 0x1018, ///< 获取继电器信息 + kSetRelayInfo = 0x1019, ///< 设置继电器信息 + + ///< 没有设置项, 只有获取项 + kGetDeviceInfo = 0x2000, ///< 获取设备信息 + kGetScreenShot = 0x2001, ///< 获取截图数据 +}; +///< 更新对应项, 需要参数会话, 信息体, 对应项 +HD_API HBool DLL_CALL UpdateItem(IHDProtocol protocol, ISDKInfo info, int updateItem); + +/** + * @brief SetLightInfo 设置亮度信息 + * @param info 信息体 + * @param mode 亮度模式 {0(默认), 1(自定义模式), 2(传感器模式)} + * @param defaultModeLight 默认模式下的亮度 + */ +HD_API void DLL_CALL SetLightInfo(ISDKInfo info, int mode, int defaultModeLight); +HD_API void DLL_CALL SetLightInfoSensor(ISDKInfo info, int min, int max, int time); +// startTime格式 HH:mm:ss +HD_API void DLL_CALL AddLightInfoPloy(ISDKInfo info, HBool enable, const char *startTime, int percent); +HD_API void DLL_CALL SetLightInfoPloy(ISDKInfo info, int index, HBool enable, const char *startTime, int percent); +HD_API void DLL_CALL ClearLightInfoPloy(ISDKInfo info); + +///< 亮度获取系列 +HD_API int DLL_CALL GetLightInfoMode(ISDKInfo info); +HD_API int DLL_CALL GetLightInfoDefaultLight(ISDKInfo info); +HD_API int DLL_CALL GetLightInfoPloySize(ISDKInfo info); +HD_API int DLL_CALL GetLightInfoPloyEnable(ISDKInfo info, int index); +HD_API int DLL_CALL GetLightInfoPloyPercent(ISDKInfo info, int index); +HD_API const char * DLL_CALL GetLightInfoPloyStart(ISDKInfo info, int index); +HD_API int DLL_CALL GetLightInfoSensorMax(ISDKInfo info); +HD_API int DLL_CALL GetLightInfoSensorMin(ISDKInfo info); +HD_API int DLL_CALL GetLightInfoSensorTime(ISDKInfo info); + +/** + * @brief SetSystemVolume 设置系统音量 + * @param info 信息体 + * @param mode 音量模式{0(默认), 1(分时)} + * @param volume 默认模式下的音量 + */ +HD_API void DLL_CALL SetSystemVolumeInfo(ISDKInfo info, int mode, int volume); +// time格式HH:mm:ss +HD_API void DLL_CALL AddSystemVolumeInfoPloy(ISDKInfo info, HBool enable, const char *time, int volume); +HD_API void DLL_CALL ClearSystemVolumeInfoPloy(ISDKInfo info); + +///< 系统音量获取系列 +HD_API int DLL_CALL GetSystemVolumeInfoMode(ISDKInfo info); +HD_API int DLL_CALL GetSystemVolumeInfoVolume(ISDKInfo info); +HD_API int DLL_CALL GetSystemVolumeInfoPloySize(ISDKInfo info); +HD_API HBool DLL_CALL GetSystemVolumeInfoPloyEnable(ISDKInfo info, int index); +HD_API const char * DLL_CALL GetSystemVolumeInfoPloyTime(ISDKInfo info, int index); +HD_API int DLL_CALL GetSystemVolumeInfoPloyVolume(ISDKInfo info, int index); + +/** + * @brief SetTcpServerInfo 设置tcp服务器 + * @param info 信息体 + * @param ip 服务器地址 + * @param port 端口 + */ +HD_API void DLL_CALL SetTcpServerInfo(ISDKInfo info, const char *ip, huint16 port); + +///< tcp服务器获取系列 +HD_API const char * DLL_CALL GetTcpServerInfoIp(ISDKInfo info); +HD_API huint16 DLL_CALL GetTcpServerInfoPort(ISDKInfo info); + + +/** + * @brief SetTimeInfo 设置时间 + * @param info 信息体 + * @param timeZone 时区, 格式"(UTC+08:00)Beijing,Chongqing,HongKong,Urumchi" + * @param summer 是否开启夏令时 + * @param sync 是否开启时间同步 {"none"(不开启自动同步), "gps"(gps校时), "network"(网络校时), "auto"(自动校时)} + * @param currTime 时间 格式"yyyy-MM-dd hh:mm:ss" + * @param ntp服务器列表, 以逗号分隔 + */ +HD_API void DLL_CALL SetTimeInfo(ISDKInfo info, const char *timeZone, HBool summer, const char *sync, const char *currTime, const char *serverList); + +///< 时间信息获取系列 +HD_API const char * DLL_CALL GetTimeInfoTimeZone(ISDKInfo info); +HD_API HBool DLL_CALL GetTimeInfoSummer(ISDKInfo info); +HD_API const char * DLL_CALL GetTimeInfoSync(ISDKInfo info); +HD_API const char * DLL_CALL GetTimeInfoCurrTime(ISDKInfo info); +HD_API const char * DLL_CALL GetTimeInfoServerList(ISDKInfo info); + + +/** + * @brief SetEthInfo 设置以太网信息 + * @param info 信息体 + * @param dhcp dhcp + * @param ip ip + * @param netmask 网络掩码 + * @param gateway 网关 + * @param dns dns + */ +HD_API void DLL_CALL SetEthInfo(ISDKInfo info, HBool dhcp, const char *ip, const char *netmask, const char *gateway, const char *dns); + +///< 以太网信息获取系列 +HD_API HBool DLL_CALL GetEhtInfoDhcp(ISDKInfo info); +HD_API const char * DLL_CALL GetEhtInfoIp(ISDKInfo info); +HD_API const char * DLL_CALL GetEhtInfoNetmask(ISDKInfo info); +HD_API const char * DLL_CALL GetEhtInfoGateway(ISDKInfo info); +HD_API const char * DLL_CALL GetEhtInfoDns(ISDKInfo info); + + +/** + * @brief SetWifiInfo 设置wifi信息 + * @param info 信息体 + * @param mode {0: ap模式, 1: station模式} + */ +HD_API void DLL_CALL SetWifiInfo(ISDKInfo info, int mode); +HD_API void DLL_CALL SetWifiInfoAp(ISDKInfo info, const char *ssid, const char *password, const char *ip); +HD_API void DLL_CALL SetWifiInfoStation(ISDKInfo info, const char *ssid, const char *password, HBool dhcp); +HD_API void DLL_CALL SetWifiInfoStationNet(ISDKInfo info, const char *ip, const char *mask, const char *gateway, const char *dns); + +HD_API int DLL_CALL GetWifiInfoMode(ISDKInfo info); +HD_API const char * DLL_CALL GetWifiInfoApSsid(ISDKInfo info); +HD_API const char * DLL_CALL GetWifiInfoApPassword(ISDKInfo info); +HD_API const char * DLL_CALL GetWifiInfoApIp(ISDKInfo info); +HD_API const char * DLL_CALL GetWifiInfoStationSsid(ISDKInfo info); +HD_API HBool DLL_CALL GetWifiInfoStationDhcp(ISDKInfo info); +HD_API const char * DLL_CALL GetWifiInfoStationIp(ISDKInfo info); +HD_API const char * DLL_CALL GetWifiInfoStationMask(ISDKInfo info); +HD_API const char * DLL_CALL GetWifiInfoStationGateway(ISDKInfo info); +HD_API const char * DLL_CALL GetWifiInfoStationDns(ISDKInfo info); + + +/** + * @brief SetPppoeInfoApn 设置pppoe apn + * @param info 信息体 + * @param apn apn + */ +HD_API void DLL_CALL SetPppoeInfoApn(ISDKInfo info, const char *apn); + +HD_API HBool DLL_CALL GetPppoeInfoVaild(ISDKInfo info); +HD_API const char * DLL_CALL GetPppoeInfoApn(ISDKInfo info); + + +/** + * @brief SetDeviceNameInfo 设置设备名 + * @param info 信息体 + * @param name 设备名 + **/ +HD_API void DLL_CALL SetDeviceNameInfo(ISDKInfo info, const char *name); +HD_API const char * DLL_CALL GetDeviceNameInfo(ISDKInfo info); + + +/** + * @brief SetSwitchTimeInfo 设置定时开关机 + * @param info 信息体 + * @param name 模式 + * @param enable 是否开启定时开关机 + **/ +HD_API void DLL_CALL SetSwitchTimeInfo(ISDKInfo info, int mode, HBool enable); +// start和end 格式 hh:mm:ss +HD_API void DLL_CALL AddSwitchTimeInfoItem(ISDKInfo info, HBool enable, const char *start, const char *end); +HD_API void DLL_CALL ClearSwitchTimeInfoItem(ISDKInfo info); +HD_API HBool DLL_CALL SetSwitchTimeInfoItem(ISDKInfo info, int index, HBool enable, const char *start, const char *end); +// start和end 格式 hh:mm:ss +HD_API void DLL_CALL AddSwitchTimeInfoWeekItem(ISDKInfo info, int week, HBool openAllDay, const char *start, const char *end); +HD_API void DLL_CALL ClearSwitchTimeInfoWeekItem(ISDKInfo info, int week); +HD_API void DLL_CALL SetSwitchTimeInfoWeekItem(ISDKInfo info, int week, int index, HBool openAllDay, const char *start, const char *end); + +HD_API int DLL_CALL GetSwitchTimeInfoItemSize(ISDKInfo info); +HD_API int DLL_CALL GetSwitchTimeInfoWeekItemSize(ISDKInfo info, int week); +HD_API HBool DLL_CALL GetSwitchTimeInfoEnable(ISDKInfo info); +HD_API HBool DLL_CALL GetSwitchTimeInfoItemEnable(ISDKInfo info, int index); +HD_API const char * DLL_CALL GetSwitchTimeInfoItemStart(ISDKInfo info, int index); +HD_API const char * DLL_CALL GetSwitchTimeInfoItemEnd(ISDKInfo info, int index); + + +/** + * @brief SetRelayInfoItem 设置继电器项 + * @param info 信息体 + * @param index 继电器索引 + * @param name 继电器名 + * @param useSwitch 关联显示屏状态 + **/ +HD_API void DLL_CALL SetRelayInfoItem(ISDKInfo info, int index, const char *name, HBool useSwitch); +HD_API void DLL_CALL AddRelayInfoItemPloy(ISDKInfo info, int index, const char *start, const char *end); +HD_API void DLL_CALL ClearRelayInfoItemPloy(ISDKInfo info, int index); +HD_API void DLL_CALL SetRelayInfoItemPloyItem(ISDKInfo info, int index, int itemIndex, const char *start, const char *end); +HD_API void DLL_CALL SetRelayInfoInternal(ISDKInfo info, const char *name, HBool useSwitch); +HD_API void DLL_CALL AddRelayInfoInternalPloy(ISDKInfo info, const char *start, const char *end); +HD_API void DLL_CALL ClearRelayInfoInternalPloy(ISDKInfo info); +HD_API void DLL_CALL SetRelayInfoInternalPloyItem(ISDKInfo info, int index, const char *start, const char *end); + +HD_API int DLL_CALL GetRelayInfoStatus(ISDKInfo info, int index); +HD_API const char * DLL_CALL GetRelayInfoName(ISDKInfo info, int index); +HD_API HBool DLL_CALL GetRelayInfoUseSwitch(ISDKInfo info, int index); +HD_API int DLL_CALL GetRelayInfoItemPloySize(ISDKInfo info, int index); +HD_API const char * DLL_CALL GetRelayInfoItemPloyStart(ISDKInfo info, int index, int itemIndex); +HD_API const char * DLL_CALL GetRelayInfoItemPloyEnd(ISDKInfo info, int index, int itemIndex); +HD_API int DLL_CALL GetRelayInfoInternalPloySize(ISDKInfo info); +HD_API const char * DLL_CALL GetRelayInfoInternalPloyStart(ISDKInfo info, int index); +HD_API const char * DLL_CALL GetRelayInfoInternalPloyEnd(ISDKInfo info, int index); + + + +///< 下面是获取 + +///< 获取设备信息系列 +HD_API const char * DLL_CALL GetDevceInfoId(ISDKInfo info); +HD_API const char * DLL_CALL GetDevceInfoName(ISDKInfo info); +HD_API const char * DLL_CALL GetDevceInfoAppVersion(ISDKInfo info); +HD_API const char * DLL_CALL GetDevceInfoFpgaVersion(ISDKInfo info); +HD_API int DLL_CALL GetDevceInfoScreenRotation(ISDKInfo info); +HD_API int DLL_CALL GetDevceInfoScreenWidth(ISDKInfo info); +HD_API int DLL_CALL GetDevceInfoScreenHeight(ISDKInfo info); + +///< 获取屏幕截图系列 +HD_API void DLL_CALL SetScreenShot(ISDKInfo info, int width, int height); +HD_API const char * DLL_CALL GetScreenShot(ISDKInfo info); +HD_API int DLL_CALL GetScreenShotSize(ISDKInfo info); + + +#ifdef __cplusplus +} +#endif + +#endif // ISDKINFO_H diff --git a/SDK/tinyxml2.cpp b/SDK/tinyxml2.cpp new file mode 100644 index 0000000..ac7e242 --- /dev/null +++ b/SDK/tinyxml2.cpp @@ -0,0 +1,2994 @@ +/* +Original code by Lee Thomason (www.grinninglizard.com) + +This software is provided 'as-is', without any express or implied +warranty. In no event will the authors be held liable for any +damages arising from the use of this software. + +Permission is granted to anyone to use this software for any +purpose, including commercial applications, and to alter it and +redistribute it freely, subject to the following restrictions: + +1. The origin of this software must not be misrepresented; you must +not claim that you wrote the original software. If you use this +software in a product, an acknowledgment in the product documentation +would be appreciated but is not required. + +2. Altered source versions must be plainly marked as such, and +must not be misrepresented as being the original software. + +3. This notice may not be removed or altered from any source +distribution. +*/ + +#include "tinyxml2.h" + +#include // yes, this one new style header, is in the Android SDK. +#if defined(ANDROID_NDK) || defined(__BORLANDC__) || defined(__QNXNTO__) +# include +# include +#else +# include +# include +#endif + +#if defined(_MSC_VER) && (_MSC_VER >= 1400 ) && (!defined WINCE) + // Microsoft Visual Studio, version 2005 and higher. Not WinCE. + /*int _snprintf_s( + char *buffer, + size_t sizeOfBuffer, + size_t count, + const char *format [, + argument] ... + );*/ + static inline int TIXML_SNPRINTF( char* buffer, size_t size, const char* format, ... ) + { + va_list va; + va_start( va, format ); + const int result = vsnprintf_s( buffer, size, _TRUNCATE, format, va ); + va_end( va ); + return result; + } + + static inline int TIXML_VSNPRINTF( char* buffer, size_t size, const char* format, va_list va ) + { + const int result = vsnprintf_s( buffer, size, _TRUNCATE, format, va ); + return result; + } + + #define TIXML_VSCPRINTF _vscprintf + #define TIXML_SSCANF sscanf_s +#elif defined _MSC_VER + // Microsoft Visual Studio 2003 and earlier or WinCE + #define TIXML_SNPRINTF _snprintf + #define TIXML_VSNPRINTF _vsnprintf + #define TIXML_SSCANF sscanf + #if (_MSC_VER < 1400 ) && (!defined WINCE) + // Microsoft Visual Studio 2003 and not WinCE. + #define TIXML_VSCPRINTF _vscprintf // VS2003's C runtime has this, but VC6 C runtime or WinCE SDK doesn't have. + #else + // Microsoft Visual Studio 2003 and earlier or WinCE. + static inline int TIXML_VSCPRINTF( const char* format, va_list va ) + { + int len = 512; + for (;;) { + len = len*2; + char* str = new char[len](); + const int required = _vsnprintf(str, len, format, va); + delete[] str; + if ( required != -1 ) { + TIXMLASSERT( required >= 0 ); + len = required; + break; + } + } + TIXMLASSERT( len >= 0 ); + return len; + } + #endif +#else + // GCC version 3 and higher + //#warning( "Using sn* functions." ) + #define TIXML_SNPRINTF snprintf + #define TIXML_VSNPRINTF vsnprintf + static inline int TIXML_VSCPRINTF( const char* format, va_list va ) + { + int len = vsnprintf( 0, 0, format, va ); + TIXMLASSERT( len >= 0 ); + return len; + } + #define TIXML_SSCANF sscanf +#endif + +#if defined(_WIN64) + #define TIXML_FSEEK _fseeki64 + #define TIXML_FTELL _ftelli64 +#elif defined(__APPLE__) || defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) || defined(__DragonFly__) || (__CYGWIN__) + #define TIXML_FSEEK fseeko + #define TIXML_FTELL ftello +#elif defined(__ANDROID__) + #if __ANDROID_API__ > 24 + #define TIXML_FSEEK fseeko64 + #define TIXML_FTELL ftello64 + #else + #define TIXML_FSEEK fseeko + #define TIXML_FTELL ftello + #endif +#elif defined(__unix__) && defined(__x86_64__) + #define TIXML_FSEEK fseeko64 + #define TIXML_FTELL ftello64 +#else + #define TIXML_FSEEK fseek + #define TIXML_FTELL ftell +#endif + + +static const char LINE_FEED = static_cast(0x0a); // all line endings are normalized to LF +static const char LF = LINE_FEED; +static const char CARRIAGE_RETURN = static_cast(0x0d); // CR gets filtered out +static const char CR = CARRIAGE_RETURN; +static const char SINGLE_QUOTE = '\''; +static const char DOUBLE_QUOTE = '\"'; + +// Bunch of unicode info at: +// http://www.unicode.org/faq/utf_bom.html +// ef bb bf (Microsoft "lead bytes") - designates UTF-8 + +static const unsigned char TIXML_UTF_LEAD_0 = 0xefU; +static const unsigned char TIXML_UTF_LEAD_1 = 0xbbU; +static const unsigned char TIXML_UTF_LEAD_2 = 0xbfU; + +namespace tinyxml2 +{ + +struct Entity { + const char* pattern; + int length; + char value; +}; + +static const int NUM_ENTITIES = 5; +static const Entity entities[NUM_ENTITIES] = { + { "quot", 4, DOUBLE_QUOTE }, + { "amp", 3, '&' }, + { "apos", 4, SINGLE_QUOTE }, + { "lt", 2, '<' }, + { "gt", 2, '>' } +}; + + +StrPair::~StrPair() +{ + Reset(); +} + + +void StrPair::TransferTo( StrPair* other ) +{ + if ( this == other ) { + return; + } + // This in effect implements the assignment operator by "moving" + // ownership (as in auto_ptr). + + TIXMLASSERT( other != 0 ); + TIXMLASSERT( other->_flags == 0 ); + TIXMLASSERT( other->_start == 0 ); + TIXMLASSERT( other->_end == 0 ); + + other->Reset(); + + other->_flags = _flags; + other->_start = _start; + other->_end = _end; + + _flags = 0; + _start = 0; + _end = 0; +} + + +void StrPair::Reset() +{ + if ( _flags & NEEDS_DELETE ) { + delete [] _start; + } + _flags = 0; + _start = 0; + _end = 0; +} + + +void StrPair::SetStr( const char* str, int flags ) +{ + TIXMLASSERT( str ); + Reset(); + size_t len = strlen( str ); + TIXMLASSERT( _start == 0 ); + _start = new char[ len+1 ]; + memcpy( _start, str, len+1 ); + _end = _start + len; + _flags = flags | NEEDS_DELETE; +} + + +char* StrPair::ParseText( char* p, const char* endTag, int strFlags, int* curLineNumPtr ) +{ + TIXMLASSERT( p ); + TIXMLASSERT( endTag && *endTag ); + TIXMLASSERT(curLineNumPtr); + + char* start = p; + const char endChar = *endTag; + size_t length = strlen( endTag ); + + // Inner loop of text parsing. + while ( *p ) { + if ( *p == endChar && strncmp( p, endTag, length ) == 0 ) { + Set( start, p, strFlags ); + return p + length; + } else if (*p == '\n') { + ++(*curLineNumPtr); + } + ++p; + TIXMLASSERT( p ); + } + return 0; +} + + +char* StrPair::ParseName( char* p ) +{ + if ( !p || !(*p) ) { + return 0; + } + if ( !XMLUtil::IsNameStartChar( (unsigned char) *p ) ) { + return 0; + } + + char* const start = p; + ++p; + while ( *p && XMLUtil::IsNameChar( (unsigned char) *p ) ) { + ++p; + } + + Set( start, p, 0 ); + return p; +} + + +void StrPair::CollapseWhitespace() +{ + // Adjusting _start would cause undefined behavior on delete[] + TIXMLASSERT( ( _flags & NEEDS_DELETE ) == 0 ); + // Trim leading space. + _start = XMLUtil::SkipWhiteSpace( _start, 0 ); + + if ( *_start ) { + const char* p = _start; // the read pointer + char* q = _start; // the write pointer + + while( *p ) { + if ( XMLUtil::IsWhiteSpace( *p )) { + p = XMLUtil::SkipWhiteSpace( p, 0 ); + if ( *p == 0 ) { + break; // don't write to q; this trims the trailing space. + } + *q = ' '; + ++q; + } + *q = *p; + ++q; + ++p; + } + *q = 0; + } +} + + +const char* StrPair::GetStr() +{ + TIXMLASSERT( _start ); + TIXMLASSERT( _end ); + if ( _flags & NEEDS_FLUSH ) { + *_end = 0; + _flags ^= NEEDS_FLUSH; + + if ( _flags ) { + const char* p = _start; // the read pointer + char* q = _start; // the write pointer + + while( p < _end ) { + if ( (_flags & NEEDS_NEWLINE_NORMALIZATION) && *p == CR ) { + // CR-LF pair becomes LF + // CR alone becomes LF + // LF-CR becomes LF + if ( *(p+1) == LF ) { + p += 2; + } + else { + ++p; + } + *q = LF; + ++q; + } + else if ( (_flags & NEEDS_NEWLINE_NORMALIZATION) && *p == LF ) { + if ( *(p+1) == CR ) { + p += 2; + } + else { + ++p; + } + *q = LF; + ++q; + } + else if ( (_flags & NEEDS_ENTITY_PROCESSING) && *p == '&' ) { + // Entities handled by tinyXML2: + // - special entities in the entity table [in/out] + // - numeric character reference [in] + // 中 or 中 + + if ( *(p+1) == '#' ) { + const int buflen = 10; + char buf[buflen] = { 0 }; + int len = 0; + const char* adjusted = const_cast( XMLUtil::GetCharacterRef( p, buf, &len ) ); + if ( adjusted == 0 ) { + *q = *p; + ++p; + ++q; + } + else { + TIXMLASSERT( 0 <= len && len <= buflen ); + TIXMLASSERT( q + len <= adjusted ); + p = adjusted; + memcpy( q, buf, len ); + q += len; + } + } + else { + bool entityFound = false; + for( int i = 0; i < NUM_ENTITIES; ++i ) { + const Entity& entity = entities[i]; + if ( strncmp( p + 1, entity.pattern, entity.length ) == 0 + && *( p + entity.length + 1 ) == ';' ) { + // Found an entity - convert. + *q = entity.value; + ++q; + p += entity.length + 2; + entityFound = true; + break; + } + } + if ( !entityFound ) { + // fixme: treat as error? + ++p; + ++q; + } + } + } + else { + *q = *p; + ++p; + ++q; + } + } + *q = 0; + } + // The loop below has plenty going on, and this + // is a less useful mode. Break it out. + if ( _flags & NEEDS_WHITESPACE_COLLAPSING ) { + CollapseWhitespace(); + } + _flags = (_flags & NEEDS_DELETE); + } + TIXMLASSERT( _start ); + return _start; +} + + + + +// --------- XMLUtil ----------- // + +const char* XMLUtil::writeBoolTrue = "true"; +const char* XMLUtil::writeBoolFalse = "false"; + +void XMLUtil::SetBoolSerialization(const char* writeTrue, const char* writeFalse) +{ + static const char* defTrue = "true"; + static const char* defFalse = "false"; + + writeBoolTrue = (writeTrue) ? writeTrue : defTrue; + writeBoolFalse = (writeFalse) ? writeFalse : defFalse; +} + + +const char* XMLUtil::ReadBOM( const char* p, bool* bom ) +{ + TIXMLASSERT( p ); + TIXMLASSERT( bom ); + *bom = false; + const unsigned char* pu = reinterpret_cast(p); + // Check for BOM: + if ( *(pu+0) == TIXML_UTF_LEAD_0 + && *(pu+1) == TIXML_UTF_LEAD_1 + && *(pu+2) == TIXML_UTF_LEAD_2 ) { + *bom = true; + p += 3; + } + TIXMLASSERT( p ); + return p; +} + + +void XMLUtil::ConvertUTF32ToUTF8( unsigned long input, char* output, int* length ) +{ + const unsigned long BYTE_MASK = 0xBF; + const unsigned long BYTE_MARK = 0x80; + const unsigned long FIRST_BYTE_MARK[7] = { 0x00, 0x00, 0xC0, 0xE0, 0xF0, 0xF8, 0xFC }; + + if (input < 0x80) { + *length = 1; + } + else if ( input < 0x800 ) { + *length = 2; + } + else if ( input < 0x10000 ) { + *length = 3; + } + else if ( input < 0x200000 ) { + *length = 4; + } + else { + *length = 0; // This code won't convert this correctly anyway. + return; + } + + output += *length; + + // Scary scary fall throughs are annotated with carefully designed comments + // to suppress compiler warnings such as -Wimplicit-fallthrough in gcc + switch (*length) { + case 4: + --output; + *output = static_cast((input | BYTE_MARK) & BYTE_MASK); + input >>= 6; + //fall through + case 3: + --output; + *output = static_cast((input | BYTE_MARK) & BYTE_MASK); + input >>= 6; + //fall through + case 2: + --output; + *output = static_cast((input | BYTE_MARK) & BYTE_MASK); + input >>= 6; + //fall through + case 1: + --output; + *output = static_cast(input | FIRST_BYTE_MARK[*length]); + break; + default: + TIXMLASSERT( false ); + } +} + + +const char* XMLUtil::GetCharacterRef( const char* p, char* value, int* length ) +{ + // Presume an entity, and pull it out. + *length = 0; + + if ( *(p+1) == '#' && *(p+2) ) { + unsigned long ucs = 0; + TIXMLASSERT( sizeof( ucs ) >= 4 ); + ptrdiff_t delta = 0; + unsigned mult = 1; + static const char SEMICOLON = ';'; + + if ( *(p+2) == 'x' ) { + // Hexadecimal. + const char* q = p+3; + if ( !(*q) ) { + return 0; + } + + q = strchr( q, SEMICOLON ); + + if ( !q ) { + return 0; + } + TIXMLASSERT( *q == SEMICOLON ); + + delta = q-p; + --q; + + while ( *q != 'x' ) { + unsigned int digit = 0; + + if ( *q >= '0' && *q <= '9' ) { + digit = *q - '0'; + } + else if ( *q >= 'a' && *q <= 'f' ) { + digit = *q - 'a' + 10; + } + else if ( *q >= 'A' && *q <= 'F' ) { + digit = *q - 'A' + 10; + } + else { + return 0; + } + TIXMLASSERT( digit < 16 ); + TIXMLASSERT( digit == 0 || mult <= UINT_MAX / digit ); + const unsigned int digitScaled = mult * digit; + TIXMLASSERT( ucs <= ULONG_MAX - digitScaled ); + ucs += digitScaled; + TIXMLASSERT( mult <= UINT_MAX / 16 ); + mult *= 16; + --q; + } + } + else { + // Decimal. + const char* q = p+2; + if ( !(*q) ) { + return 0; + } + + q = strchr( q, SEMICOLON ); + + if ( !q ) { + return 0; + } + TIXMLASSERT( *q == SEMICOLON ); + + delta = q-p; + --q; + + while ( *q != '#' ) { + if ( *q >= '0' && *q <= '9' ) { + const unsigned int digit = *q - '0'; + TIXMLASSERT( digit < 10 ); + TIXMLASSERT( digit == 0 || mult <= UINT_MAX / digit ); + const unsigned int digitScaled = mult * digit; + TIXMLASSERT( ucs <= ULONG_MAX - digitScaled ); + ucs += digitScaled; + } + else { + return 0; + } + TIXMLASSERT( mult <= UINT_MAX / 10 ); + mult *= 10; + --q; + } + } + // convert the UCS to UTF-8 + ConvertUTF32ToUTF8( ucs, value, length ); + return p + delta + 1; + } + return p+1; +} + + +void XMLUtil::ToStr( int v, char* buffer, int bufferSize ) +{ + TIXML_SNPRINTF( buffer, bufferSize, "%d", v ); +} + + +void XMLUtil::ToStr( unsigned v, char* buffer, int bufferSize ) +{ + TIXML_SNPRINTF( buffer, bufferSize, "%u", v ); +} + + +void XMLUtil::ToStr( bool v, char* buffer, int bufferSize ) +{ + TIXML_SNPRINTF( buffer, bufferSize, "%s", v ? writeBoolTrue : writeBoolFalse); +} + +/* + ToStr() of a number is a very tricky topic. + https://github.com/leethomason/tinyxml2/issues/106 +*/ +void XMLUtil::ToStr( float v, char* buffer, int bufferSize ) +{ + TIXML_SNPRINTF( buffer, bufferSize, "%.8g", v ); +} + + +void XMLUtil::ToStr( double v, char* buffer, int bufferSize ) +{ + TIXML_SNPRINTF( buffer, bufferSize, "%.17g", v ); +} + + +void XMLUtil::ToStr( int64_t v, char* buffer, int bufferSize ) +{ + // horrible syntax trick to make the compiler happy about %lld + TIXML_SNPRINTF(buffer, bufferSize, "%lld", static_cast(v)); +} + +void XMLUtil::ToStr( uint64_t v, char* buffer, int bufferSize ) +{ + // horrible syntax trick to make the compiler happy about %llu + TIXML_SNPRINTF(buffer, bufferSize, "%llu", (long long)v); +} + +bool XMLUtil::ToInt(const char* str, int* value) +{ + if (IsPrefixHex(str)) { + unsigned v; + if (TIXML_SSCANF(str, "%x", &v) == 1) { + *value = static_cast(v); + return true; + } + } + else { + if (TIXML_SSCANF(str, "%d", value) == 1) { + return true; + } + } + return false; +} + +bool XMLUtil::ToUnsigned(const char* str, unsigned* value) +{ + if (TIXML_SSCANF(str, IsPrefixHex(str) ? "%x" : "%u", value) == 1) { + return true; + } + return false; +} + +bool XMLUtil::ToBool( const char* str, bool* value ) +{ + int ival = 0; + if ( ToInt( str, &ival )) { + *value = (ival==0) ? false : true; + return true; + } + static const char* TRUE_VALS[] = { "true", "True", "TRUE", 0 }; + static const char* FALSE_VALS[] = { "false", "False", "FALSE", 0 }; + + for (int i = 0; TRUE_VALS[i]; ++i) { + if (StringEqual(str, TRUE_VALS[i])) { + *value = true; + return true; + } + } + for (int i = 0; FALSE_VALS[i]; ++i) { + if (StringEqual(str, FALSE_VALS[i])) { + *value = false; + return true; + } + } + return false; +} + + +bool XMLUtil::ToFloat( const char* str, float* value ) +{ + if ( TIXML_SSCANF( str, "%f", value ) == 1 ) { + return true; + } + return false; +} + + +bool XMLUtil::ToDouble( const char* str, double* value ) +{ + if ( TIXML_SSCANF( str, "%lf", value ) == 1 ) { + return true; + } + return false; +} + + +bool XMLUtil::ToInt64(const char* str, int64_t* value) +{ + if (IsPrefixHex(str)) { + unsigned long long v = 0; // horrible syntax trick to make the compiler happy about %llx + if (TIXML_SSCANF(str, "%llx", &v) == 1) { + *value = static_cast(v); + return true; + } + } + else { + long long v = 0; // horrible syntax trick to make the compiler happy about %lld + if (TIXML_SSCANF(str, "%lld", &v) == 1) { + *value = static_cast(v); + return true; + } + } + return false; +} + + +bool XMLUtil::ToUnsigned64(const char* str, uint64_t* value) { + unsigned long long v = 0; // horrible syntax trick to make the compiler happy about %llu + if(TIXML_SSCANF(str, IsPrefixHex(str) ? "%llx" : "%llu", &v) == 1) { + *value = (uint64_t)v; + return true; + } + return false; +} + + +char* XMLDocument::Identify( char* p, XMLNode** node ) +{ + TIXMLASSERT( node ); + TIXMLASSERT( p ); + char* const start = p; + int const startLine = _parseCurLineNum; + p = XMLUtil::SkipWhiteSpace( p, &_parseCurLineNum ); + if( !*p ) { + *node = 0; + TIXMLASSERT( p ); + return p; + } + + // These strings define the matching patterns: + static const char* xmlHeader = { "( _commentPool ); + returnNode->_parseLineNum = _parseCurLineNum; + p += xmlHeaderLen; + } + else if ( XMLUtil::StringEqual( p, commentHeader, commentHeaderLen ) ) { + returnNode = CreateUnlinkedNode( _commentPool ); + returnNode->_parseLineNum = _parseCurLineNum; + p += commentHeaderLen; + } + else if ( XMLUtil::StringEqual( p, cdataHeader, cdataHeaderLen ) ) { + XMLText* text = CreateUnlinkedNode( _textPool ); + returnNode = text; + returnNode->_parseLineNum = _parseCurLineNum; + p += cdataHeaderLen; + text->SetCData( true ); + } + else if ( XMLUtil::StringEqual( p, dtdHeader, dtdHeaderLen ) ) { + returnNode = CreateUnlinkedNode( _commentPool ); + returnNode->_parseLineNum = _parseCurLineNum; + p += dtdHeaderLen; + } + else if ( XMLUtil::StringEqual( p, elementHeader, elementHeaderLen ) ) { + returnNode = CreateUnlinkedNode( _elementPool ); + returnNode->_parseLineNum = _parseCurLineNum; + p += elementHeaderLen; + } + else { + returnNode = CreateUnlinkedNode( _textPool ); + returnNode->_parseLineNum = _parseCurLineNum; // Report line of first non-whitespace character + p = start; // Back it up, all the text counts. + _parseCurLineNum = startLine; + } + + TIXMLASSERT( returnNode ); + TIXMLASSERT( p ); + *node = returnNode; + return p; +} + + +bool XMLDocument::Accept( XMLVisitor* visitor ) const +{ + TIXMLASSERT( visitor ); + if ( visitor->VisitEnter( *this ) ) { + for ( const XMLNode* node=FirstChild(); node; node=node->NextSibling() ) { + if ( !node->Accept( visitor ) ) { + break; + } + } + } + return visitor->VisitExit( *this ); +} + + +// --------- XMLNode ----------- // + +XMLNode::XMLNode( XMLDocument* doc ) : + _document( doc ), + _parent( 0 ), + _value(), + _parseLineNum( 0 ), + _firstChild( 0 ), _lastChild( 0 ), + _prev( 0 ), _next( 0 ), + _userData( 0 ), + _memPool( 0 ) +{ +} + + +XMLNode::~XMLNode() +{ + DeleteChildren(); + if ( _parent ) { + _parent->Unlink( this ); + } +} + +const char* XMLNode::Value() const +{ + // Edge case: XMLDocuments don't have a Value. Return null. + if ( this->ToDocument() ) + return 0; + return _value.GetStr(); +} + +void XMLNode::SetValue( const char* str, bool staticMem ) +{ + if ( staticMem ) { + _value.SetInternedStr( str ); + } + else { + _value.SetStr( str ); + } +} + +XMLNode* XMLNode::DeepClone(XMLDocument* target) const +{ + XMLNode* clone = this->ShallowClone(target); + if (!clone) return 0; + + for (const XMLNode* child = this->FirstChild(); child; child = child->NextSibling()) { + XMLNode* childClone = child->DeepClone(target); + TIXMLASSERT(childClone); + clone->InsertEndChild(childClone); + } + return clone; +} + +void XMLNode::DeleteChildren() +{ + while( _firstChild ) { + TIXMLASSERT( _lastChild ); + DeleteChild( _firstChild ); + } + _firstChild = _lastChild = 0; +} + + +void XMLNode::Unlink( XMLNode* child ) +{ + TIXMLASSERT( child ); + TIXMLASSERT( child->_document == _document ); + TIXMLASSERT( child->_parent == this ); + if ( child == _firstChild ) { + _firstChild = _firstChild->_next; + } + if ( child == _lastChild ) { + _lastChild = _lastChild->_prev; + } + + if ( child->_prev ) { + child->_prev->_next = child->_next; + } + if ( child->_next ) { + child->_next->_prev = child->_prev; + } + child->_next = 0; + child->_prev = 0; + child->_parent = 0; +} + + +void XMLNode::DeleteChild( XMLNode* node ) +{ + TIXMLASSERT( node ); + TIXMLASSERT( node->_document == _document ); + TIXMLASSERT( node->_parent == this ); + Unlink( node ); + TIXMLASSERT(node->_prev == 0); + TIXMLASSERT(node->_next == 0); + TIXMLASSERT(node->_parent == 0); + DeleteNode( node ); +} + + +XMLNode* XMLNode::InsertEndChild( XMLNode* addThis ) +{ + TIXMLASSERT( addThis ); + if ( addThis->_document != _document ) { + TIXMLASSERT( false ); + return 0; + } + InsertChildPreamble( addThis ); + + if ( _lastChild ) { + TIXMLASSERT( _firstChild ); + TIXMLASSERT( _lastChild->_next == 0 ); + _lastChild->_next = addThis; + addThis->_prev = _lastChild; + _lastChild = addThis; + + addThis->_next = 0; + } + else { + TIXMLASSERT( _firstChild == 0 ); + _firstChild = _lastChild = addThis; + + addThis->_prev = 0; + addThis->_next = 0; + } + addThis->_parent = this; + return addThis; +} + + +XMLNode* XMLNode::InsertFirstChild( XMLNode* addThis ) +{ + TIXMLASSERT( addThis ); + if ( addThis->_document != _document ) { + TIXMLASSERT( false ); + return 0; + } + InsertChildPreamble( addThis ); + + if ( _firstChild ) { + TIXMLASSERT( _lastChild ); + TIXMLASSERT( _firstChild->_prev == 0 ); + + _firstChild->_prev = addThis; + addThis->_next = _firstChild; + _firstChild = addThis; + + addThis->_prev = 0; + } + else { + TIXMLASSERT( _lastChild == 0 ); + _firstChild = _lastChild = addThis; + + addThis->_prev = 0; + addThis->_next = 0; + } + addThis->_parent = this; + return addThis; +} + + +XMLNode* XMLNode::InsertAfterChild( XMLNode* afterThis, XMLNode* addThis ) +{ + TIXMLASSERT( addThis ); + if ( addThis->_document != _document ) { + TIXMLASSERT( false ); + return 0; + } + + TIXMLASSERT( afterThis ); + + if ( afterThis->_parent != this ) { + TIXMLASSERT( false ); + return 0; + } + if ( afterThis == addThis ) { + // Current state: BeforeThis -> AddThis -> OneAfterAddThis + // Now AddThis must disappear from it's location and then + // reappear between BeforeThis and OneAfterAddThis. + // So just leave it where it is. + return addThis; + } + + if ( afterThis->_next == 0 ) { + // The last node or the only node. + return InsertEndChild( addThis ); + } + InsertChildPreamble( addThis ); + addThis->_prev = afterThis; + addThis->_next = afterThis->_next; + afterThis->_next->_prev = addThis; + afterThis->_next = addThis; + addThis->_parent = this; + return addThis; +} + + + + +const XMLElement* XMLNode::FirstChildElement( const char* name ) const +{ + for( const XMLNode* node = _firstChild; node; node = node->_next ) { + const XMLElement* element = node->ToElementWithName( name ); + if ( element ) { + return element; + } + } + return 0; +} + + +const XMLElement* XMLNode::LastChildElement( const char* name ) const +{ + for( const XMLNode* node = _lastChild; node; node = node->_prev ) { + const XMLElement* element = node->ToElementWithName( name ); + if ( element ) { + return element; + } + } + return 0; +} + + +const XMLElement* XMLNode::NextSiblingElement( const char* name ) const +{ + for( const XMLNode* node = _next; node; node = node->_next ) { + const XMLElement* element = node->ToElementWithName( name ); + if ( element ) { + return element; + } + } + return 0; +} + + +const XMLElement* XMLNode::PreviousSiblingElement( const char* name ) const +{ + for( const XMLNode* node = _prev; node; node = node->_prev ) { + const XMLElement* element = node->ToElementWithName( name ); + if ( element ) { + return element; + } + } + return 0; +} + + +char* XMLNode::ParseDeep( char* p, StrPair* parentEndTag, int* curLineNumPtr ) +{ + // This is a recursive method, but thinking about it "at the current level" + // it is a pretty simple flat list: + // + // + // + // With a special case: + // + // + // + // + // Where the closing element (/foo) *must* be the next thing after the opening + // element, and the names must match. BUT the tricky bit is that the closing + // element will be read by the child. + // + // 'endTag' is the end tag for this node, it is returned by a call to a child. + // 'parentEnd' is the end tag for the parent, which is filled in and returned. + + XMLDocument::DepthTracker tracker(_document); + if (_document->Error()) + return 0; + + while( p && *p ) { + XMLNode* node = 0; + + p = _document->Identify( p, &node ); + TIXMLASSERT( p ); + if ( node == 0 ) { + break; + } + + const int initialLineNum = node->_parseLineNum; + + StrPair endTag; + p = node->ParseDeep( p, &endTag, curLineNumPtr ); + if ( !p ) { + DeleteNode( node ); + if ( !_document->Error() ) { + _document->SetError( XML_ERROR_PARSING, initialLineNum, 0); + } + break; + } + + const XMLDeclaration* const decl = node->ToDeclaration(); + if ( decl ) { + // Declarations are only allowed at document level + // + // Multiple declarations are allowed but all declarations + // must occur before anything else. + // + // Optimized due to a security test case. If the first node is + // a declaration, and the last node is a declaration, then only + // declarations have so far been added. + bool wellLocated = false; + + if (ToDocument()) { + if (FirstChild()) { + wellLocated = + FirstChild() && + FirstChild()->ToDeclaration() && + LastChild() && + LastChild()->ToDeclaration(); + } + else { + wellLocated = true; + } + } + if ( !wellLocated ) { + _document->SetError( XML_ERROR_PARSING_DECLARATION, initialLineNum, "XMLDeclaration value=%s", decl->Value()); + DeleteNode( node ); + break; + } + } + + XMLElement* ele = node->ToElement(); + if ( ele ) { + // We read the end tag. Return it to the parent. + if ( ele->ClosingType() == XMLElement::CLOSING ) { + if ( parentEndTag ) { + ele->_value.TransferTo( parentEndTag ); + } + node->_memPool->SetTracked(); // created and then immediately deleted. + DeleteNode( node ); + return p; + } + + // Handle an end tag returned to this level. + // And handle a bunch of annoying errors. + bool mismatch = false; + if ( endTag.Empty() ) { + if ( ele->ClosingType() == XMLElement::OPEN ) { + mismatch = true; + } + } + else { + if ( ele->ClosingType() != XMLElement::OPEN ) { + mismatch = true; + } + else if ( !XMLUtil::StringEqual( endTag.GetStr(), ele->Name() ) ) { + mismatch = true; + } + } + if ( mismatch ) { + _document->SetError( XML_ERROR_MISMATCHED_ELEMENT, initialLineNum, "XMLElement name=%s", ele->Name()); + DeleteNode( node ); + break; + } + } + InsertEndChild( node ); + } + return 0; +} + +/*static*/ void XMLNode::DeleteNode( XMLNode* node ) +{ + if ( node == 0 ) { + return; + } + TIXMLASSERT(node->_document); + if (!node->ToDocument()) { + node->_document->MarkInUse(node); + } + + MemPool* pool = node->_memPool; + node->~XMLNode(); + pool->Free( node ); +} + +void XMLNode::InsertChildPreamble( XMLNode* insertThis ) const +{ + TIXMLASSERT( insertThis ); + TIXMLASSERT( insertThis->_document == _document ); + + if (insertThis->_parent) { + insertThis->_parent->Unlink( insertThis ); + } + else { + insertThis->_document->MarkInUse(insertThis); + insertThis->_memPool->SetTracked(); + } +} + +const XMLElement* XMLNode::ToElementWithName( const char* name ) const +{ + const XMLElement* element = this->ToElement(); + if ( element == 0 ) { + return 0; + } + if ( name == 0 ) { + return element; + } + if ( XMLUtil::StringEqual( element->Name(), name ) ) { + return element; + } + return 0; +} + +// --------- XMLText ---------- // +char* XMLText::ParseDeep( char* p, StrPair*, int* curLineNumPtr ) +{ + if ( this->CData() ) { + p = _value.ParseText( p, "]]>", StrPair::NEEDS_NEWLINE_NORMALIZATION, curLineNumPtr ); + if ( !p ) { + _document->SetError( XML_ERROR_PARSING_CDATA, _parseLineNum, 0 ); + } + return p; + } + else { + int flags = _document->ProcessEntities() ? StrPair::TEXT_ELEMENT : StrPair::TEXT_ELEMENT_LEAVE_ENTITIES; + if ( _document->WhitespaceMode() == COLLAPSE_WHITESPACE ) { + flags |= StrPair::NEEDS_WHITESPACE_COLLAPSING; + } + + p = _value.ParseText( p, "<", flags, curLineNumPtr ); + if ( p && *p ) { + return p-1; + } + if ( !p ) { + _document->SetError( XML_ERROR_PARSING_TEXT, _parseLineNum, 0 ); + } + } + return 0; +} + + +XMLNode* XMLText::ShallowClone( XMLDocument* doc ) const +{ + if ( !doc ) { + doc = _document; + } + XMLText* text = doc->NewText( Value() ); // fixme: this will always allocate memory. Intern? + text->SetCData( this->CData() ); + return text; +} + + +bool XMLText::ShallowEqual( const XMLNode* compare ) const +{ + TIXMLASSERT( compare ); + const XMLText* text = compare->ToText(); + return ( text && XMLUtil::StringEqual( text->Value(), Value() ) ); +} + + +bool XMLText::Accept( XMLVisitor* visitor ) const +{ + TIXMLASSERT( visitor ); + return visitor->Visit( *this ); +} + + +// --------- XMLComment ---------- // + +XMLComment::XMLComment( XMLDocument* doc ) : XMLNode( doc ) +{ +} + + +XMLComment::~XMLComment() +{ +} + + +char* XMLComment::ParseDeep( char* p, StrPair*, int* curLineNumPtr ) +{ + // Comment parses as text. + p = _value.ParseText( p, "-->", StrPair::COMMENT, curLineNumPtr ); + if ( p == 0 ) { + _document->SetError( XML_ERROR_PARSING_COMMENT, _parseLineNum, 0 ); + } + return p; +} + + +XMLNode* XMLComment::ShallowClone( XMLDocument* doc ) const +{ + if ( !doc ) { + doc = _document; + } + XMLComment* comment = doc->NewComment( Value() ); // fixme: this will always allocate memory. Intern? + return comment; +} + + +bool XMLComment::ShallowEqual( const XMLNode* compare ) const +{ + TIXMLASSERT( compare ); + const XMLComment* comment = compare->ToComment(); + return ( comment && XMLUtil::StringEqual( comment->Value(), Value() )); +} + + +bool XMLComment::Accept( XMLVisitor* visitor ) const +{ + TIXMLASSERT( visitor ); + return visitor->Visit( *this ); +} + + +// --------- XMLDeclaration ---------- // + +XMLDeclaration::XMLDeclaration( XMLDocument* doc ) : XMLNode( doc ) +{ +} + + +XMLDeclaration::~XMLDeclaration() +{ + //printf( "~XMLDeclaration\n" ); +} + + +char* XMLDeclaration::ParseDeep( char* p, StrPair*, int* curLineNumPtr ) +{ + // Declaration parses as text. + p = _value.ParseText( p, "?>", StrPair::NEEDS_NEWLINE_NORMALIZATION, curLineNumPtr ); + if ( p == 0 ) { + _document->SetError( XML_ERROR_PARSING_DECLARATION, _parseLineNum, 0 ); + } + return p; +} + + +XMLNode* XMLDeclaration::ShallowClone( XMLDocument* doc ) const +{ + if ( !doc ) { + doc = _document; + } + XMLDeclaration* dec = doc->NewDeclaration( Value() ); // fixme: this will always allocate memory. Intern? + return dec; +} + + +bool XMLDeclaration::ShallowEqual( const XMLNode* compare ) const +{ + TIXMLASSERT( compare ); + const XMLDeclaration* declaration = compare->ToDeclaration(); + return ( declaration && XMLUtil::StringEqual( declaration->Value(), Value() )); +} + + + +bool XMLDeclaration::Accept( XMLVisitor* visitor ) const +{ + TIXMLASSERT( visitor ); + return visitor->Visit( *this ); +} + +// --------- XMLUnknown ---------- // + +XMLUnknown::XMLUnknown( XMLDocument* doc ) : XMLNode( doc ) +{ +} + + +XMLUnknown::~XMLUnknown() +{ +} + + +char* XMLUnknown::ParseDeep( char* p, StrPair*, int* curLineNumPtr ) +{ + // Unknown parses as text. + p = _value.ParseText( p, ">", StrPair::NEEDS_NEWLINE_NORMALIZATION, curLineNumPtr ); + if ( !p ) { + _document->SetError( XML_ERROR_PARSING_UNKNOWN, _parseLineNum, 0 ); + } + return p; +} + + +XMLNode* XMLUnknown::ShallowClone( XMLDocument* doc ) const +{ + if ( !doc ) { + doc = _document; + } + XMLUnknown* text = doc->NewUnknown( Value() ); // fixme: this will always allocate memory. Intern? + return text; +} + + +bool XMLUnknown::ShallowEqual( const XMLNode* compare ) const +{ + TIXMLASSERT( compare ); + const XMLUnknown* unknown = compare->ToUnknown(); + return ( unknown && XMLUtil::StringEqual( unknown->Value(), Value() )); +} + + +bool XMLUnknown::Accept( XMLVisitor* visitor ) const +{ + TIXMLASSERT( visitor ); + return visitor->Visit( *this ); +} + +// --------- XMLAttribute ---------- // + +const char* XMLAttribute::Name() const +{ + return _name.GetStr(); +} + +const char* XMLAttribute::Value() const +{ + return _value.GetStr(); +} + +char* XMLAttribute::ParseDeep( char* p, bool processEntities, int* curLineNumPtr ) +{ + // Parse using the name rules: bug fix, was using ParseText before + p = _name.ParseName( p ); + if ( !p || !*p ) { + return 0; + } + + // Skip white space before = + p = XMLUtil::SkipWhiteSpace( p, curLineNumPtr ); + if ( *p != '=' ) { + return 0; + } + + ++p; // move up to opening quote + p = XMLUtil::SkipWhiteSpace( p, curLineNumPtr ); + if ( *p != '\"' && *p != '\'' ) { + return 0; + } + + const char endTag[2] = { *p, 0 }; + ++p; // move past opening quote + + p = _value.ParseText( p, endTag, processEntities ? StrPair::ATTRIBUTE_VALUE : StrPair::ATTRIBUTE_VALUE_LEAVE_ENTITIES, curLineNumPtr ); + return p; +} + + +void XMLAttribute::SetName( const char* n ) +{ + _name.SetStr( n ); +} + + +XMLError XMLAttribute::QueryIntValue( int* value ) const +{ + if ( XMLUtil::ToInt( Value(), value )) { + return XML_SUCCESS; + } + return XML_WRONG_ATTRIBUTE_TYPE; +} + + +XMLError XMLAttribute::QueryUnsignedValue( unsigned int* value ) const +{ + if ( XMLUtil::ToUnsigned( Value(), value )) { + return XML_SUCCESS; + } + return XML_WRONG_ATTRIBUTE_TYPE; +} + + +XMLError XMLAttribute::QueryInt64Value(int64_t* value) const +{ + if (XMLUtil::ToInt64(Value(), value)) { + return XML_SUCCESS; + } + return XML_WRONG_ATTRIBUTE_TYPE; +} + + +XMLError XMLAttribute::QueryUnsigned64Value(uint64_t* value) const +{ + if(XMLUtil::ToUnsigned64(Value(), value)) { + return XML_SUCCESS; + } + return XML_WRONG_ATTRIBUTE_TYPE; +} + + +XMLError XMLAttribute::QueryBoolValue( bool* value ) const +{ + if ( XMLUtil::ToBool( Value(), value )) { + return XML_SUCCESS; + } + return XML_WRONG_ATTRIBUTE_TYPE; +} + + +XMLError XMLAttribute::QueryFloatValue( float* value ) const +{ + if ( XMLUtil::ToFloat( Value(), value )) { + return XML_SUCCESS; + } + return XML_WRONG_ATTRIBUTE_TYPE; +} + + +XMLError XMLAttribute::QueryDoubleValue( double* value ) const +{ + if ( XMLUtil::ToDouble( Value(), value )) { + return XML_SUCCESS; + } + return XML_WRONG_ATTRIBUTE_TYPE; +} + + +void XMLAttribute::SetAttribute( const char* v ) +{ + _value.SetStr( v ); +} + + +void XMLAttribute::SetAttribute( int v ) +{ + char buf[BUF_SIZE]; + XMLUtil::ToStr( v, buf, BUF_SIZE ); + _value.SetStr( buf ); +} + + +void XMLAttribute::SetAttribute( unsigned v ) +{ + char buf[BUF_SIZE]; + XMLUtil::ToStr( v, buf, BUF_SIZE ); + _value.SetStr( buf ); +} + + +void XMLAttribute::SetAttribute(int64_t v) +{ + char buf[BUF_SIZE]; + XMLUtil::ToStr(v, buf, BUF_SIZE); + _value.SetStr(buf); +} + +void XMLAttribute::SetAttribute(uint64_t v) +{ + char buf[BUF_SIZE]; + XMLUtil::ToStr(v, buf, BUF_SIZE); + _value.SetStr(buf); +} + + +void XMLAttribute::SetAttribute( bool v ) +{ + char buf[BUF_SIZE]; + XMLUtil::ToStr( v, buf, BUF_SIZE ); + _value.SetStr( buf ); +} + +void XMLAttribute::SetAttribute( double v ) +{ + char buf[BUF_SIZE]; + XMLUtil::ToStr( v, buf, BUF_SIZE ); + _value.SetStr( buf ); +} + +void XMLAttribute::SetAttribute( float v ) +{ + char buf[BUF_SIZE]; + XMLUtil::ToStr( v, buf, BUF_SIZE ); + _value.SetStr( buf ); +} + + +// --------- XMLElement ---------- // +XMLElement::XMLElement( XMLDocument* doc ) : XMLNode( doc ), + _closingType( OPEN ), + _rootAttribute( 0 ) +{ +} + + +XMLElement::~XMLElement() +{ + while( _rootAttribute ) { + XMLAttribute* next = _rootAttribute->_next; + DeleteAttribute( _rootAttribute ); + _rootAttribute = next; + } +} + + +const XMLAttribute* XMLElement::FindAttribute( const char* name ) const +{ + for( XMLAttribute* a = _rootAttribute; a; a = a->_next ) { + if ( XMLUtil::StringEqual( a->Name(), name ) ) { + return a; + } + } + return 0; +} + + +const char* XMLElement::Attribute( const char* name, const char* value ) const +{ + const XMLAttribute* a = FindAttribute( name ); + if ( !a ) { + return 0; + } + if ( !value || XMLUtil::StringEqual( a->Value(), value )) { + return a->Value(); + } + return 0; +} + +int XMLElement::IntAttribute(const char* name, int defaultValue) const +{ + int i = defaultValue; + QueryIntAttribute(name, &i); + return i; +} + +unsigned XMLElement::UnsignedAttribute(const char* name, unsigned defaultValue) const +{ + unsigned i = defaultValue; + QueryUnsignedAttribute(name, &i); + return i; +} + +int64_t XMLElement::Int64Attribute(const char* name, int64_t defaultValue) const +{ + int64_t i = defaultValue; + QueryInt64Attribute(name, &i); + return i; +} + +uint64_t XMLElement::Unsigned64Attribute(const char* name, uint64_t defaultValue) const +{ + uint64_t i = defaultValue; + QueryUnsigned64Attribute(name, &i); + return i; +} + +bool XMLElement::BoolAttribute(const char* name, bool defaultValue) const +{ + bool b = defaultValue; + QueryBoolAttribute(name, &b); + return b; +} + +double XMLElement::DoubleAttribute(const char* name, double defaultValue) const +{ + double d = defaultValue; + QueryDoubleAttribute(name, &d); + return d; +} + +float XMLElement::FloatAttribute(const char* name, float defaultValue) const +{ + float f = defaultValue; + QueryFloatAttribute(name, &f); + return f; +} + +const char* XMLElement::GetText() const +{ + /* skip comment node */ + const XMLNode* node = FirstChild(); + while (node) { + if (node->ToComment()) { + node = node->NextSibling(); + continue; + } + break; + } + + if ( node && node->ToText() ) { + return node->Value(); + } + return 0; +} + + +void XMLElement::SetText( const char* inText ) +{ + if ( FirstChild() && FirstChild()->ToText() ) + FirstChild()->SetValue( inText ); + else { + XMLText* theText = GetDocument()->NewText( inText ); + InsertFirstChild( theText ); + } +} + + +void XMLElement::SetText( int v ) +{ + char buf[BUF_SIZE]; + XMLUtil::ToStr( v, buf, BUF_SIZE ); + SetText( buf ); +} + + +void XMLElement::SetText( unsigned v ) +{ + char buf[BUF_SIZE]; + XMLUtil::ToStr( v, buf, BUF_SIZE ); + SetText( buf ); +} + + +void XMLElement::SetText(int64_t v) +{ + char buf[BUF_SIZE]; + XMLUtil::ToStr(v, buf, BUF_SIZE); + SetText(buf); +} + +void XMLElement::SetText(uint64_t v) { + char buf[BUF_SIZE]; + XMLUtil::ToStr(v, buf, BUF_SIZE); + SetText(buf); +} + + +void XMLElement::SetText( bool v ) +{ + char buf[BUF_SIZE]; + XMLUtil::ToStr( v, buf, BUF_SIZE ); + SetText( buf ); +} + + +void XMLElement::SetText( float v ) +{ + char buf[BUF_SIZE]; + XMLUtil::ToStr( v, buf, BUF_SIZE ); + SetText( buf ); +} + + +void XMLElement::SetText( double v ) +{ + char buf[BUF_SIZE]; + XMLUtil::ToStr( v, buf, BUF_SIZE ); + SetText( buf ); +} + + +XMLError XMLElement::QueryIntText( int* ival ) const +{ + if ( FirstChild() && FirstChild()->ToText() ) { + const char* t = FirstChild()->Value(); + if ( XMLUtil::ToInt( t, ival ) ) { + return XML_SUCCESS; + } + return XML_CAN_NOT_CONVERT_TEXT; + } + return XML_NO_TEXT_NODE; +} + + +XMLError XMLElement::QueryUnsignedText( unsigned* uval ) const +{ + if ( FirstChild() && FirstChild()->ToText() ) { + const char* t = FirstChild()->Value(); + if ( XMLUtil::ToUnsigned( t, uval ) ) { + return XML_SUCCESS; + } + return XML_CAN_NOT_CONVERT_TEXT; + } + return XML_NO_TEXT_NODE; +} + + +XMLError XMLElement::QueryInt64Text(int64_t* ival) const +{ + if (FirstChild() && FirstChild()->ToText()) { + const char* t = FirstChild()->Value(); + if (XMLUtil::ToInt64(t, ival)) { + return XML_SUCCESS; + } + return XML_CAN_NOT_CONVERT_TEXT; + } + return XML_NO_TEXT_NODE; +} + + +XMLError XMLElement::QueryUnsigned64Text(uint64_t* uval) const +{ + if(FirstChild() && FirstChild()->ToText()) { + const char* t = FirstChild()->Value(); + if(XMLUtil::ToUnsigned64(t, uval)) { + return XML_SUCCESS; + } + return XML_CAN_NOT_CONVERT_TEXT; + } + return XML_NO_TEXT_NODE; +} + + +XMLError XMLElement::QueryBoolText( bool* bval ) const +{ + if ( FirstChild() && FirstChild()->ToText() ) { + const char* t = FirstChild()->Value(); + if ( XMLUtil::ToBool( t, bval ) ) { + return XML_SUCCESS; + } + return XML_CAN_NOT_CONVERT_TEXT; + } + return XML_NO_TEXT_NODE; +} + + +XMLError XMLElement::QueryDoubleText( double* dval ) const +{ + if ( FirstChild() && FirstChild()->ToText() ) { + const char* t = FirstChild()->Value(); + if ( XMLUtil::ToDouble( t, dval ) ) { + return XML_SUCCESS; + } + return XML_CAN_NOT_CONVERT_TEXT; + } + return XML_NO_TEXT_NODE; +} + + +XMLError XMLElement::QueryFloatText( float* fval ) const +{ + if ( FirstChild() && FirstChild()->ToText() ) { + const char* t = FirstChild()->Value(); + if ( XMLUtil::ToFloat( t, fval ) ) { + return XML_SUCCESS; + } + return XML_CAN_NOT_CONVERT_TEXT; + } + return XML_NO_TEXT_NODE; +} + +int XMLElement::IntText(int defaultValue) const +{ + int i = defaultValue; + QueryIntText(&i); + return i; +} + +unsigned XMLElement::UnsignedText(unsigned defaultValue) const +{ + unsigned i = defaultValue; + QueryUnsignedText(&i); + return i; +} + +int64_t XMLElement::Int64Text(int64_t defaultValue) const +{ + int64_t i = defaultValue; + QueryInt64Text(&i); + return i; +} + +uint64_t XMLElement::Unsigned64Text(uint64_t defaultValue) const +{ + uint64_t i = defaultValue; + QueryUnsigned64Text(&i); + return i; +} + +bool XMLElement::BoolText(bool defaultValue) const +{ + bool b = defaultValue; + QueryBoolText(&b); + return b; +} + +double XMLElement::DoubleText(double defaultValue) const +{ + double d = defaultValue; + QueryDoubleText(&d); + return d; +} + +float XMLElement::FloatText(float defaultValue) const +{ + float f = defaultValue; + QueryFloatText(&f); + return f; +} + + +XMLAttribute* XMLElement::FindOrCreateAttribute( const char* name ) +{ + XMLAttribute* last = 0; + XMLAttribute* attrib = 0; + for( attrib = _rootAttribute; + attrib; + last = attrib, attrib = attrib->_next ) { + if ( XMLUtil::StringEqual( attrib->Name(), name ) ) { + break; + } + } + if ( !attrib ) { + attrib = CreateAttribute(); + TIXMLASSERT( attrib ); + if ( last ) { + TIXMLASSERT( last->_next == 0 ); + last->_next = attrib; + } + else { + TIXMLASSERT( _rootAttribute == 0 ); + _rootAttribute = attrib; + } + attrib->SetName( name ); + } + return attrib; +} + + +void XMLElement::DeleteAttribute( const char* name ) +{ + XMLAttribute* prev = 0; + for( XMLAttribute* a=_rootAttribute; a; a=a->_next ) { + if ( XMLUtil::StringEqual( name, a->Name() ) ) { + if ( prev ) { + prev->_next = a->_next; + } + else { + _rootAttribute = a->_next; + } + DeleteAttribute( a ); + break; + } + prev = a; + } +} + + +char* XMLElement::ParseAttributes( char* p, int* curLineNumPtr ) +{ + XMLAttribute* prevAttribute = 0; + + // Read the attributes. + while( p ) { + p = XMLUtil::SkipWhiteSpace( p, curLineNumPtr ); + if ( !(*p) ) { + _document->SetError( XML_ERROR_PARSING_ELEMENT, _parseLineNum, "XMLElement name=%s", Name() ); + return 0; + } + + // attribute. + if (XMLUtil::IsNameStartChar( (unsigned char) *p ) ) { + XMLAttribute* attrib = CreateAttribute(); + TIXMLASSERT( attrib ); + attrib->_parseLineNum = _document->_parseCurLineNum; + + const int attrLineNum = attrib->_parseLineNum; + + p = attrib->ParseDeep( p, _document->ProcessEntities(), curLineNumPtr ); + if ( !p || Attribute( attrib->Name() ) ) { + DeleteAttribute( attrib ); + _document->SetError( XML_ERROR_PARSING_ATTRIBUTE, attrLineNum, "XMLElement name=%s", Name() ); + return 0; + } + // There is a minor bug here: if the attribute in the source xml + // document is duplicated, it will not be detected and the + // attribute will be doubly added. However, tracking the 'prevAttribute' + // avoids re-scanning the attribute list. Preferring performance for + // now, may reconsider in the future. + if ( prevAttribute ) { + TIXMLASSERT( prevAttribute->_next == 0 ); + prevAttribute->_next = attrib; + } + else { + TIXMLASSERT( _rootAttribute == 0 ); + _rootAttribute = attrib; + } + prevAttribute = attrib; + } + // end of the tag + else if ( *p == '>' ) { + ++p; + break; + } + // end of the tag + else if ( *p == '/' && *(p+1) == '>' ) { + _closingType = CLOSED; + return p+2; // done; sealed element. + } + else { + _document->SetError( XML_ERROR_PARSING_ELEMENT, _parseLineNum, 0 ); + return 0; + } + } + return p; +} + +void XMLElement::DeleteAttribute( XMLAttribute* attribute ) +{ + if ( attribute == 0 ) { + return; + } + MemPool* pool = attribute->_memPool; + attribute->~XMLAttribute(); + pool->Free( attribute ); +} + +XMLAttribute* XMLElement::CreateAttribute() +{ + TIXMLASSERT( sizeof( XMLAttribute ) == _document->_attributePool.ItemSize() ); + XMLAttribute* attrib = new (_document->_attributePool.Alloc() ) XMLAttribute(); + TIXMLASSERT( attrib ); + attrib->_memPool = &_document->_attributePool; + attrib->_memPool->SetTracked(); + return attrib; +} + + +XMLElement* XMLElement::InsertNewChildElement(const char* name) +{ + XMLElement* node = _document->NewElement(name); + return InsertEndChild(node) ? node : 0; +} + +XMLComment* XMLElement::InsertNewComment(const char* comment) +{ + XMLComment* node = _document->NewComment(comment); + return InsertEndChild(node) ? node : 0; +} + +XMLText* XMLElement::InsertNewText(const char* text) +{ + XMLText* node = _document->NewText(text); + return InsertEndChild(node) ? node : 0; +} + +XMLDeclaration* XMLElement::InsertNewDeclaration(const char* text) +{ + XMLDeclaration* node = _document->NewDeclaration(text); + return InsertEndChild(node) ? node : 0; +} + +XMLUnknown* XMLElement::InsertNewUnknown(const char* text) +{ + XMLUnknown* node = _document->NewUnknown(text); + return InsertEndChild(node) ? node : 0; +} + + + +// +// +// foobar +// +char* XMLElement::ParseDeep( char* p, StrPair* parentEndTag, int* curLineNumPtr ) +{ + // Read the element name. + p = XMLUtil::SkipWhiteSpace( p, curLineNumPtr ); + + // The closing element is the form. It is + // parsed just like a regular element then deleted from + // the DOM. + if ( *p == '/' ) { + _closingType = CLOSING; + ++p; + } + + p = _value.ParseName( p ); + if ( _value.Empty() ) { + return 0; + } + + p = ParseAttributes( p, curLineNumPtr ); + if ( !p || !*p || _closingType != OPEN ) { + return p; + } + + p = XMLNode::ParseDeep( p, parentEndTag, curLineNumPtr ); + return p; +} + + + +XMLNode* XMLElement::ShallowClone( XMLDocument* doc ) const +{ + if ( !doc ) { + doc = _document; + } + XMLElement* element = doc->NewElement( Value() ); // fixme: this will always allocate memory. Intern? + for( const XMLAttribute* a=FirstAttribute(); a; a=a->Next() ) { + element->SetAttribute( a->Name(), a->Value() ); // fixme: this will always allocate memory. Intern? + } + return element; +} + + +bool XMLElement::ShallowEqual( const XMLNode* compare ) const +{ + TIXMLASSERT( compare ); + const XMLElement* other = compare->ToElement(); + if ( other && XMLUtil::StringEqual( other->Name(), Name() )) { + + const XMLAttribute* a=FirstAttribute(); + const XMLAttribute* b=other->FirstAttribute(); + + while ( a && b ) { + if ( !XMLUtil::StringEqual( a->Value(), b->Value() ) ) { + return false; + } + a = a->Next(); + b = b->Next(); + } + if ( a || b ) { + // different count + return false; + } + return true; + } + return false; +} + + +bool XMLElement::Accept( XMLVisitor* visitor ) const +{ + TIXMLASSERT( visitor ); + if ( visitor->VisitEnter( *this, _rootAttribute ) ) { + for ( const XMLNode* node=FirstChild(); node; node=node->NextSibling() ) { + if ( !node->Accept( visitor ) ) { + break; + } + } + } + return visitor->VisitExit( *this ); +} + + +// --------- XMLDocument ----------- // + +// Warning: List must match 'enum XMLError' +const char* XMLDocument::_errorNames[XML_ERROR_COUNT] = { + "XML_SUCCESS", + "XML_NO_ATTRIBUTE", + "XML_WRONG_ATTRIBUTE_TYPE", + "XML_ERROR_FILE_NOT_FOUND", + "XML_ERROR_FILE_COULD_NOT_BE_OPENED", + "XML_ERROR_FILE_READ_ERROR", + "XML_ERROR_PARSING_ELEMENT", + "XML_ERROR_PARSING_ATTRIBUTE", + "XML_ERROR_PARSING_TEXT", + "XML_ERROR_PARSING_CDATA", + "XML_ERROR_PARSING_COMMENT", + "XML_ERROR_PARSING_DECLARATION", + "XML_ERROR_PARSING_UNKNOWN", + "XML_ERROR_EMPTY_DOCUMENT", + "XML_ERROR_MISMATCHED_ELEMENT", + "XML_ERROR_PARSING", + "XML_CAN_NOT_CONVERT_TEXT", + "XML_NO_TEXT_NODE", + "XML_ELEMENT_DEPTH_EXCEEDED" +}; + + +XMLDocument::XMLDocument( bool processEntities, Whitespace whitespaceMode ) : + XMLNode( 0 ), + _writeBOM( false ), + _processEntities( processEntities ), + _errorID(XML_SUCCESS), + _whitespaceMode( whitespaceMode ), + _errorStr(), + _errorLineNum( 0 ), + _charBuffer( 0 ), + _parseCurLineNum( 0 ), + _parsingDepth(0), + _unlinked(), + _elementPool(), + _attributePool(), + _textPool(), + _commentPool() +{ + // avoid VC++ C4355 warning about 'this' in initializer list (C4355 is off by default in VS2012+) + _document = this; +} + + +XMLDocument::~XMLDocument() +{ + Clear(); +} + + +void XMLDocument::MarkInUse(const XMLNode* const node) +{ + TIXMLASSERT(node); + TIXMLASSERT(node->_parent == 0); + + for (int i = 0; i < _unlinked.Size(); ++i) { + if (node == _unlinked[i]) { + _unlinked.SwapRemove(i); + break; + } + } +} + +void XMLDocument::Clear() +{ + DeleteChildren(); + while( _unlinked.Size()) { + DeleteNode(_unlinked[0]); // Will remove from _unlinked as part of delete. + } + +#ifdef TINYXML2_DEBUG + const bool hadError = Error(); +#endif + ClearError(); + + delete [] _charBuffer; + _charBuffer = 0; + _parsingDepth = 0; + +#if 0 + _textPool.Trace( "text" ); + _elementPool.Trace( "element" ); + _commentPool.Trace( "comment" ); + _attributePool.Trace( "attribute" ); +#endif + +#ifdef TINYXML2_DEBUG + if ( !hadError ) { + TIXMLASSERT( _elementPool.CurrentAllocs() == _elementPool.Untracked() ); + TIXMLASSERT( _attributePool.CurrentAllocs() == _attributePool.Untracked() ); + TIXMLASSERT( _textPool.CurrentAllocs() == _textPool.Untracked() ); + TIXMLASSERT( _commentPool.CurrentAllocs() == _commentPool.Untracked() ); + } +#endif +} + + +void XMLDocument::DeepCopy(XMLDocument* target) const +{ + TIXMLASSERT(target); + if (target == this) { + return; // technically success - a no-op. + } + + target->Clear(); + for (const XMLNode* node = this->FirstChild(); node; node = node->NextSibling()) { + target->InsertEndChild(node->DeepClone(target)); + } +} + +XMLElement* XMLDocument::NewElement( const char* name ) +{ + XMLElement* ele = CreateUnlinkedNode( _elementPool ); + ele->SetName( name ); + return ele; +} + + +XMLComment* XMLDocument::NewComment( const char* str ) +{ + XMLComment* comment = CreateUnlinkedNode( _commentPool ); + comment->SetValue( str ); + return comment; +} + + +XMLText* XMLDocument::NewText( const char* str ) +{ + XMLText* text = CreateUnlinkedNode( _textPool ); + text->SetValue( str ); + return text; +} + + +XMLDeclaration* XMLDocument::NewDeclaration( const char* str ) +{ + XMLDeclaration* dec = CreateUnlinkedNode( _commentPool ); + dec->SetValue( str ? str : "xml version=\"1.0\" encoding=\"UTF-8\"" ); + return dec; +} + + +XMLUnknown* XMLDocument::NewUnknown( const char* str ) +{ + XMLUnknown* unk = CreateUnlinkedNode( _commentPool ); + unk->SetValue( str ); + return unk; +} + +static FILE* callfopen( const char* filepath, const char* mode ) +{ + TIXMLASSERT( filepath ); + TIXMLASSERT( mode ); +#if defined(_MSC_VER) && (_MSC_VER >= 1400 ) && (!defined WINCE) + FILE* fp = 0; + const errno_t err = fopen_s( &fp, filepath, mode ); + if ( err ) { + return 0; + } +#else + FILE* fp = fopen( filepath, mode ); +#endif + return fp; +} + +void XMLDocument::DeleteNode( XMLNode* node ) { + TIXMLASSERT( node ); + TIXMLASSERT(node->_document == this ); + if (node->_parent) { + node->_parent->DeleteChild( node ); + } + else { + // Isn't in the tree. + // Use the parent delete. + // Also, we need to mark it tracked: we 'know' + // it was never used. + node->_memPool->SetTracked(); + // Call the static XMLNode version: + XMLNode::DeleteNode(node); + } +} + + +XMLError XMLDocument::LoadFile( const char* filename ) +{ + if ( !filename ) { + TIXMLASSERT( false ); + SetError( XML_ERROR_FILE_COULD_NOT_BE_OPENED, 0, "filename=" ); + return _errorID; + } + + Clear(); + FILE* fp = callfopen( filename, "rb" ); + if ( !fp ) { + SetError( XML_ERROR_FILE_NOT_FOUND, 0, "filename=%s", filename ); + return _errorID; + } + LoadFile( fp ); + fclose( fp ); + return _errorID; +} + +XMLError XMLDocument::LoadFile( FILE* fp ) +{ + Clear(); + + TIXML_FSEEK( fp, 0, SEEK_SET ); + if ( fgetc( fp ) == EOF && ferror( fp ) != 0 ) { + SetError( XML_ERROR_FILE_READ_ERROR, 0, 0 ); + return _errorID; + } + + TIXML_FSEEK( fp, 0, SEEK_END ); + + unsigned long long filelength; + { + const long long fileLengthSigned = TIXML_FTELL( fp ); + TIXML_FSEEK( fp, 0, SEEK_SET ); + if ( fileLengthSigned == -1L ) { + SetError( XML_ERROR_FILE_READ_ERROR, 0, 0 ); + return _errorID; + } + TIXMLASSERT( fileLengthSigned >= 0 ); + filelength = static_cast(fileLengthSigned); + } + + const size_t maxSizeT = static_cast(-1); + // We'll do the comparison as an unsigned long long, because that's guaranteed to be at + // least 8 bytes, even on a 32-bit platform. + if ( filelength >= static_cast(maxSizeT) ) { + // Cannot handle files which won't fit in buffer together with null terminator + SetError( XML_ERROR_FILE_READ_ERROR, 0, 0 ); + return _errorID; + } + + if ( filelength == 0 ) { + SetError( XML_ERROR_EMPTY_DOCUMENT, 0, 0 ); + return _errorID; + } + + const size_t size = static_cast(filelength); + TIXMLASSERT( _charBuffer == 0 ); + _charBuffer = new char[size+1]; + const size_t read = fread( _charBuffer, 1, size, fp ); + if ( read != size ) { + SetError( XML_ERROR_FILE_READ_ERROR, 0, 0 ); + return _errorID; + } + + _charBuffer[size] = 0; + + Parse(); + return _errorID; +} + + +XMLError XMLDocument::SaveFile( const char* filename, bool compact ) +{ + if ( !filename ) { + TIXMLASSERT( false ); + SetError( XML_ERROR_FILE_COULD_NOT_BE_OPENED, 0, "filename=" ); + return _errorID; + } + + FILE* fp = callfopen( filename, "w" ); + if ( !fp ) { + SetError( XML_ERROR_FILE_COULD_NOT_BE_OPENED, 0, "filename=%s", filename ); + return _errorID; + } + SaveFile(fp, compact); + fclose( fp ); + return _errorID; +} + + +XMLError XMLDocument::SaveFile( FILE* fp, bool compact ) +{ + // Clear any error from the last save, otherwise it will get reported + // for *this* call. + ClearError(); + XMLPrinter stream( fp, compact ); + Print( &stream ); + return _errorID; +} + + +XMLError XMLDocument::Parse( const char* xml, size_t nBytes ) +{ + Clear(); + + if ( nBytes == 0 || !xml || !*xml ) { + SetError( XML_ERROR_EMPTY_DOCUMENT, 0, 0 ); + return _errorID; + } + if ( nBytes == static_cast(-1) ) { + nBytes = strlen( xml ); + } + TIXMLASSERT( _charBuffer == 0 ); + _charBuffer = new char[ nBytes+1 ]; + memcpy( _charBuffer, xml, nBytes ); + _charBuffer[nBytes] = 0; + + Parse(); + if ( Error() ) { + // clean up now essentially dangling memory. + // and the parse fail can put objects in the + // pools that are dead and inaccessible. + DeleteChildren(); + _elementPool.Clear(); + _attributePool.Clear(); + _textPool.Clear(); + _commentPool.Clear(); + } + return _errorID; +} + + +void XMLDocument::Print( XMLPrinter* streamer ) const +{ + if ( streamer ) { + Accept( streamer ); + } + else { + XMLPrinter stdoutStreamer( stdout ); + Accept( &stdoutStreamer ); + } +} + + +void XMLDocument::ClearError() { + _errorID = XML_SUCCESS; + _errorLineNum = 0; + _errorStr.Reset(); +} + + +void XMLDocument::SetError( XMLError error, int lineNum, const char* format, ... ) +{ + TIXMLASSERT( error >= 0 && error < XML_ERROR_COUNT ); + _errorID = error; + _errorLineNum = lineNum; + _errorStr.Reset(); + + const size_t BUFFER_SIZE = 1000; + char* buffer = new char[BUFFER_SIZE]; + + TIXMLASSERT(sizeof(error) <= sizeof(int)); + TIXML_SNPRINTF(buffer, BUFFER_SIZE, "Error=%s ErrorID=%d (0x%x) Line number=%d", ErrorIDToName(error), int(error), int(error), lineNum); + + if (format) { + size_t len = strlen(buffer); + TIXML_SNPRINTF(buffer + len, BUFFER_SIZE - len, ": "); + len = strlen(buffer); + + va_list va; + va_start(va, format); + TIXML_VSNPRINTF(buffer + len, BUFFER_SIZE - len, format, va); + va_end(va); + } + _errorStr.SetStr(buffer); + delete[] buffer; +} + + +/*static*/ const char* XMLDocument::ErrorIDToName(XMLError errorID) +{ + TIXMLASSERT( errorID >= 0 && errorID < XML_ERROR_COUNT ); + const char* errorName = _errorNames[errorID]; + TIXMLASSERT( errorName && errorName[0] ); + return errorName; +} + +const char* XMLDocument::ErrorStr() const +{ + return _errorStr.Empty() ? "" : _errorStr.GetStr(); +} + + +void XMLDocument::PrintError() const +{ + printf("%s\n", ErrorStr()); +} + +const char* XMLDocument::ErrorName() const +{ + return ErrorIDToName(_errorID); +} + +void XMLDocument::Parse() +{ + TIXMLASSERT( NoChildren() ); // Clear() must have been called previously + TIXMLASSERT( _charBuffer ); + _parseCurLineNum = 1; + _parseLineNum = 1; + char* p = _charBuffer; + p = XMLUtil::SkipWhiteSpace( p, &_parseCurLineNum ); + p = const_cast( XMLUtil::ReadBOM( p, &_writeBOM ) ); + if ( !*p ) { + SetError( XML_ERROR_EMPTY_DOCUMENT, 0, 0 ); + return; + } + ParseDeep(p, 0, &_parseCurLineNum ); +} + +void XMLDocument::PushDepth() +{ + _parsingDepth++; + if (_parsingDepth == TINYXML2_MAX_ELEMENT_DEPTH) { + SetError(XML_ELEMENT_DEPTH_EXCEEDED, _parseCurLineNum, "Element nesting is too deep." ); + } +} + +void XMLDocument::PopDepth() +{ + TIXMLASSERT(_parsingDepth > 0); + --_parsingDepth; +} + +XMLPrinter::XMLPrinter( FILE* file, bool compact, int depth ) : + _elementJustOpened( false ), + _stack(), + _firstElement( true ), + _fp( file ), + _depth( depth ), + _textDepth( -1 ), + _processEntities( true ), + _compactMode( compact ), + _buffer() +{ + for( int i=0; i(entityValue); + TIXMLASSERT( flagIndex < ENTITY_RANGE ); + _entityFlag[flagIndex] = true; + } + _restrictedEntityFlag[static_cast('&')] = true; + _restrictedEntityFlag[static_cast('<')] = true; + _restrictedEntityFlag[static_cast('>')] = true; // not required, but consistency is nice + _buffer.Push( 0 ); +} + + +void XMLPrinter::Print( const char* format, ... ) +{ + va_list va; + va_start( va, format ); + + if ( _fp ) { + vfprintf( _fp, format, va ); + } + else { + const int len = TIXML_VSCPRINTF( format, va ); + // Close out and re-start the va-args + va_end( va ); + TIXMLASSERT( len >= 0 ); + va_start( va, format ); + TIXMLASSERT( _buffer.Size() > 0 && _buffer[_buffer.Size() - 1] == 0 ); + char* p = _buffer.PushArr( len ) - 1; // back up over the null terminator. + TIXML_VSNPRINTF( p, len+1, format, va ); + } + va_end( va ); +} + + +void XMLPrinter::Write( const char* data, size_t size ) +{ + if ( _fp ) { + fwrite ( data , sizeof(char), size, _fp); + } + else { + char* p = _buffer.PushArr( static_cast(size) ) - 1; // back up over the null terminator. + memcpy( p, data, size ); + p[size] = 0; + } +} + + +void XMLPrinter::Putc( char ch ) +{ + if ( _fp ) { + fputc ( ch, _fp); + } + else { + char* p = _buffer.PushArr( sizeof(char) ) - 1; // back up over the null terminator. + p[0] = ch; + p[1] = 0; + } +} + + +void XMLPrinter::PrintSpace( int depth ) +{ + for( int i=0; i 0 && *q < ENTITY_RANGE ) { + // Check for entities. If one is found, flush + // the stream up until the entity, write the + // entity, and keep looking. + if ( flag[static_cast(*q)] ) { + while ( p < q ) { + const size_t delta = q - p; + const int toPrint = ( INT_MAX < delta ) ? INT_MAX : static_cast(delta); + Write( p, toPrint ); + p += toPrint; + } + bool entityPatternPrinted = false; + for( int i=0; i(delta); + Write( p, toPrint ); + } + } + else { + Write( p ); + } +} + + +void XMLPrinter::PushHeader( bool writeBOM, bool writeDec ) +{ + if ( writeBOM ) { + static const unsigned char bom[] = { TIXML_UTF_LEAD_0, TIXML_UTF_LEAD_1, TIXML_UTF_LEAD_2, 0 }; + Write( reinterpret_cast< const char* >( bom ) ); + } + if ( writeDec ) { + PushDeclaration( "xml version=\"1.0\"" ); + } +} + +void XMLPrinter::PrepareForNewNode( bool compactMode ) +{ + SealElementIfJustOpened(); + + if ( compactMode ) { + return; + } + + if ( _firstElement ) { + PrintSpace (_depth); + } else if ( _textDepth < 0) { + Putc( '\n' ); + PrintSpace( _depth ); + } + + _firstElement = false; +} + +void XMLPrinter::OpenElement( const char* name, bool compactMode ) +{ + PrepareForNewNode( compactMode ); + _stack.Push( name ); + + Write ( "<" ); + Write ( name ); + + _elementJustOpened = true; + ++_depth; +} + + +void XMLPrinter::PushAttribute( const char* name, const char* value ) +{ + TIXMLASSERT( _elementJustOpened ); + Putc ( ' ' ); + Write( name ); + Write( "=\"" ); + PrintString( value, false ); + Putc ( '\"' ); +} + + +void XMLPrinter::PushAttribute( const char* name, int v ) +{ + char buf[BUF_SIZE]; + XMLUtil::ToStr( v, buf, BUF_SIZE ); + PushAttribute( name, buf ); +} + + +void XMLPrinter::PushAttribute( const char* name, unsigned v ) +{ + char buf[BUF_SIZE]; + XMLUtil::ToStr( v, buf, BUF_SIZE ); + PushAttribute( name, buf ); +} + + +void XMLPrinter::PushAttribute(const char* name, int64_t v) +{ + char buf[BUF_SIZE]; + XMLUtil::ToStr(v, buf, BUF_SIZE); + PushAttribute(name, buf); +} + + +void XMLPrinter::PushAttribute(const char* name, uint64_t v) +{ + char buf[BUF_SIZE]; + XMLUtil::ToStr(v, buf, BUF_SIZE); + PushAttribute(name, buf); +} + + +void XMLPrinter::PushAttribute( const char* name, bool v ) +{ + char buf[BUF_SIZE]; + XMLUtil::ToStr( v, buf, BUF_SIZE ); + PushAttribute( name, buf ); +} + + +void XMLPrinter::PushAttribute( const char* name, double v ) +{ + char buf[BUF_SIZE]; + XMLUtil::ToStr( v, buf, BUF_SIZE ); + PushAttribute( name, buf ); +} + + +void XMLPrinter::CloseElement( bool compactMode ) +{ + --_depth; + const char* name = _stack.Pop(); + + if ( _elementJustOpened ) { + Write( "/>" ); + } + else { + if ( _textDepth < 0 && !compactMode) { + Putc( '\n' ); + PrintSpace( _depth ); + } + Write ( "" ); + } + + if ( _textDepth == _depth ) { + _textDepth = -1; + } + if ( _depth == 0 && !compactMode) { + Putc( '\n' ); + } + _elementJustOpened = false; +} + + +void XMLPrinter::SealElementIfJustOpened() +{ + if ( !_elementJustOpened ) { + return; + } + _elementJustOpened = false; + Putc( '>' ); +} + + +void XMLPrinter::PushText( const char* text, bool cdata ) +{ + _textDepth = _depth-1; + + SealElementIfJustOpened(); + if ( cdata ) { + Write( "" ); + } + else { + PrintString( text, true ); + } +} + + +void XMLPrinter::PushText( int64_t value ) +{ + char buf[BUF_SIZE]; + XMLUtil::ToStr( value, buf, BUF_SIZE ); + PushText( buf, false ); +} + + +void XMLPrinter::PushText( uint64_t value ) +{ + char buf[BUF_SIZE]; + XMLUtil::ToStr(value, buf, BUF_SIZE); + PushText(buf, false); +} + + +void XMLPrinter::PushText( int value ) +{ + char buf[BUF_SIZE]; + XMLUtil::ToStr( value, buf, BUF_SIZE ); + PushText( buf, false ); +} + + +void XMLPrinter::PushText( unsigned value ) +{ + char buf[BUF_SIZE]; + XMLUtil::ToStr( value, buf, BUF_SIZE ); + PushText( buf, false ); +} + + +void XMLPrinter::PushText( bool value ) +{ + char buf[BUF_SIZE]; + XMLUtil::ToStr( value, buf, BUF_SIZE ); + PushText( buf, false ); +} + + +void XMLPrinter::PushText( float value ) +{ + char buf[BUF_SIZE]; + XMLUtil::ToStr( value, buf, BUF_SIZE ); + PushText( buf, false ); +} + + +void XMLPrinter::PushText( double value ) +{ + char buf[BUF_SIZE]; + XMLUtil::ToStr( value, buf, BUF_SIZE ); + PushText( buf, false ); +} + + +void XMLPrinter::PushComment( const char* comment ) +{ + PrepareForNewNode( _compactMode ); + + Write( "" ); +} + + +void XMLPrinter::PushDeclaration( const char* value ) +{ + PrepareForNewNode( _compactMode ); + + Write( "" ); +} + + +void XMLPrinter::PushUnknown( const char* value ) +{ + PrepareForNewNode( _compactMode ); + + Write( "' ); +} + + +bool XMLPrinter::VisitEnter( const XMLDocument& doc ) +{ + _processEntities = doc.ProcessEntities(); + if ( doc.HasBOM() ) { + PushHeader( true, false ); + } + return true; +} + + +bool XMLPrinter::VisitEnter( const XMLElement& element, const XMLAttribute* attribute ) +{ + const XMLElement* parentElem = 0; + if ( element.Parent() ) { + parentElem = element.Parent()->ToElement(); + } + const bool compactMode = parentElem ? CompactMode( *parentElem ) : _compactMode; + OpenElement( element.Name(), compactMode ); + while ( attribute ) { + PushAttribute( attribute->Name(), attribute->Value() ); + attribute = attribute->Next(); + } + return true; +} + + +bool XMLPrinter::VisitExit( const XMLElement& element ) +{ + CloseElement( CompactMode(element) ); + return true; +} + + +bool XMLPrinter::Visit( const XMLText& text ) +{ + PushText( text.Value(), text.CData() ); + return true; +} + + +bool XMLPrinter::Visit( const XMLComment& comment ) +{ + PushComment( comment.Value() ); + return true; +} + +bool XMLPrinter::Visit( const XMLDeclaration& declaration ) +{ + PushDeclaration( declaration.Value() ); + return true; +} + + +bool XMLPrinter::Visit( const XMLUnknown& unknown ) +{ + PushUnknown( unknown.Value() ); + return true; +} + +} // namespace tinyxml2 diff --git a/SDK/tinyxml2.h b/SDK/tinyxml2.h new file mode 100644 index 0000000..2ed9daa --- /dev/null +++ b/SDK/tinyxml2.h @@ -0,0 +1,2380 @@ +/* +Original code by Lee Thomason (www.grinninglizard.com) + +This software is provided 'as-is', without any express or implied +warranty. In no event will the authors be held liable for any +damages arising from the use of this software. + +Permission is granted to anyone to use this software for any +purpose, including commercial applications, and to alter it and +redistribute it freely, subject to the following restrictions: + +1. The origin of this software must not be misrepresented; you must +not claim that you wrote the original software. If you use this +software in a product, an acknowledgment in the product documentation +would be appreciated but is not required. + +2. Altered source versions must be plainly marked as such, and +must not be misrepresented as being the original software. + +3. This notice may not be removed or altered from any source +distribution. +*/ + +#ifndef TINYXML2_INCLUDED +#define TINYXML2_INCLUDED + +#if defined(ANDROID_NDK) || defined(__BORLANDC__) || defined(__QNXNTO__) +# include +# include +# include +# include +# include +# if defined(__PS3__) +# include +# endif +#else +# include +# include +# include +# include +# include +#endif +#include + +/* + TODO: intern strings instead of allocation. +*/ +/* + gcc: + g++ -Wall -DTINYXML2_DEBUG tinyxml2.cpp xmltest.cpp -o gccxmltest.exe + + Formatting, Artistic Style: + AStyle.exe --style=1tbs --indent-switches --break-closing-brackets --indent-preprocessor tinyxml2.cpp tinyxml2.h +*/ + +#if defined( _DEBUG ) || defined (__DEBUG__) +# ifndef TINYXML2_DEBUG +# define TINYXML2_DEBUG +# endif +#endif + +#ifdef _MSC_VER +# pragma warning(push) +# pragma warning(disable: 4251) +#endif + +#ifdef _WIN32 +# ifdef TINYXML2_EXPORT +# define TINYXML2_LIB __declspec(dllexport) +# elif defined(TINYXML2_IMPORT) +# define TINYXML2_LIB __declspec(dllimport) +# else +# define TINYXML2_LIB +# endif +#elif __GNUC__ >= 4 +# define TINYXML2_LIB __attribute__((visibility("default"))) +#else +# define TINYXML2_LIB +#endif + + +#if !defined(TIXMLASSERT) +#if defined(TINYXML2_DEBUG) +# if defined(_MSC_VER) +# // "(void)0," is for suppressing C4127 warning in "assert(false)", "assert(true)" and the like +# define TIXMLASSERT( x ) do { if ( !((void)0,(x))) { __debugbreak(); } } while(false) +# elif defined (ANDROID_NDK) +# include +# define TIXMLASSERT( x ) do { if ( !(x)) { __android_log_assert( "assert", "grinliz", "ASSERT in '%s' at %d.", __FILE__, __LINE__ ); } } while(false) +# else +# include +# define TIXMLASSERT assert +# endif +#else +# define TIXMLASSERT( x ) do {} while(false) +#endif +#endif + +/* Versioning, past 1.0.14: + http://semver.org/ +*/ +static const int TIXML2_MAJOR_VERSION = 9; +static const int TIXML2_MINOR_VERSION = 0; +static const int TIXML2_PATCH_VERSION = 0; + +#define TINYXML2_MAJOR_VERSION 9 +#define TINYXML2_MINOR_VERSION 0 +#define TINYXML2_PATCH_VERSION 0 + +// A fixed element depth limit is problematic. There needs to be a +// limit to avoid a stack overflow. However, that limit varies per +// system, and the capacity of the stack. On the other hand, it's a trivial +// attack that can result from ill, malicious, or even correctly formed XML, +// so there needs to be a limit in place. +static const int TINYXML2_MAX_ELEMENT_DEPTH = 100; + +namespace tinyxml2 +{ +class XMLDocument; +class XMLElement; +class XMLAttribute; +class XMLComment; +class XMLText; +class XMLDeclaration; +class XMLUnknown; +class XMLPrinter; + +/* + A class that wraps strings. Normally stores the start and end + pointers into the XML file itself, and will apply normalization + and entity translation if actually read. Can also store (and memory + manage) a traditional char[] + + Isn't clear why TINYXML2_LIB is needed; but seems to fix #719 +*/ +class TINYXML2_LIB StrPair +{ +public: + enum Mode { + NEEDS_ENTITY_PROCESSING = 0x01, + NEEDS_NEWLINE_NORMALIZATION = 0x02, + NEEDS_WHITESPACE_COLLAPSING = 0x04, + + TEXT_ELEMENT = NEEDS_ENTITY_PROCESSING | NEEDS_NEWLINE_NORMALIZATION, + TEXT_ELEMENT_LEAVE_ENTITIES = NEEDS_NEWLINE_NORMALIZATION, + ATTRIBUTE_NAME = 0, + ATTRIBUTE_VALUE = NEEDS_ENTITY_PROCESSING | NEEDS_NEWLINE_NORMALIZATION, + ATTRIBUTE_VALUE_LEAVE_ENTITIES = NEEDS_NEWLINE_NORMALIZATION, + COMMENT = NEEDS_NEWLINE_NORMALIZATION + }; + + StrPair() : _flags( 0 ), _start( 0 ), _end( 0 ) {} + ~StrPair(); + + void Set( char* start, char* end, int flags ) { + TIXMLASSERT( start ); + TIXMLASSERT( end ); + Reset(); + _start = start; + _end = end; + _flags = flags | NEEDS_FLUSH; + } + + const char* GetStr(); + + bool Empty() const { + return _start == _end; + } + + void SetInternedStr( const char* str ) { + Reset(); + _start = const_cast(str); + } + + void SetStr( const char* str, int flags=0 ); + + char* ParseText( char* in, const char* endTag, int strFlags, int* curLineNumPtr ); + char* ParseName( char* in ); + + void TransferTo( StrPair* other ); + void Reset(); + +private: + void CollapseWhitespace(); + + enum { + NEEDS_FLUSH = 0x100, + NEEDS_DELETE = 0x200 + }; + + int _flags; + char* _start; + char* _end; + + StrPair( const StrPair& other ); // not supported + void operator=( const StrPair& other ); // not supported, use TransferTo() +}; + + +/* + A dynamic array of Plain Old Data. Doesn't support constructors, etc. + Has a small initial memory pool, so that low or no usage will not + cause a call to new/delete +*/ +template +class DynArray +{ +public: + DynArray() : + _mem( _pool ), + _allocated( INITIAL_SIZE ), + _size( 0 ) + { + } + + ~DynArray() { + if ( _mem != _pool ) { + delete [] _mem; + } + } + + void Clear() { + _size = 0; + } + + void Push( T t ) { + TIXMLASSERT( _size < INT_MAX ); + EnsureCapacity( _size+1 ); + _mem[_size] = t; + ++_size; + } + + T* PushArr( int count ) { + TIXMLASSERT( count >= 0 ); + TIXMLASSERT( _size <= INT_MAX - count ); + EnsureCapacity( _size+count ); + T* ret = &_mem[_size]; + _size += count; + return ret; + } + + T Pop() { + TIXMLASSERT( _size > 0 ); + --_size; + return _mem[_size]; + } + + void PopArr( int count ) { + TIXMLASSERT( _size >= count ); + _size -= count; + } + + bool Empty() const { + return _size == 0; + } + + T& operator[](int i) { + TIXMLASSERT( i>= 0 && i < _size ); + return _mem[i]; + } + + const T& operator[](int i) const { + TIXMLASSERT( i>= 0 && i < _size ); + return _mem[i]; + } + + const T& PeekTop() const { + TIXMLASSERT( _size > 0 ); + return _mem[ _size - 1]; + } + + int Size() const { + TIXMLASSERT( _size >= 0 ); + return _size; + } + + int Capacity() const { + TIXMLASSERT( _allocated >= INITIAL_SIZE ); + return _allocated; + } + + void SwapRemove(int i) { + TIXMLASSERT(i >= 0 && i < _size); + TIXMLASSERT(_size > 0); + _mem[i] = _mem[_size - 1]; + --_size; + } + + const T* Mem() const { + TIXMLASSERT( _mem ); + return _mem; + } + + T* Mem() { + TIXMLASSERT( _mem ); + return _mem; + } + +private: + DynArray( const DynArray& ); // not supported + void operator=( const DynArray& ); // not supported + + void EnsureCapacity( int cap ) { + TIXMLASSERT( cap > 0 ); + if ( cap > _allocated ) { + TIXMLASSERT( cap <= INT_MAX / 2 ); + const int newAllocated = cap * 2; + T* newMem = new T[newAllocated]; + TIXMLASSERT( newAllocated >= _size ); + memcpy( newMem, _mem, sizeof(T)*_size ); // warning: not using constructors, only works for PODs + if ( _mem != _pool ) { + delete [] _mem; + } + _mem = newMem; + _allocated = newAllocated; + } + } + + T* _mem; + T _pool[INITIAL_SIZE]; + int _allocated; // objects allocated + int _size; // number objects in use +}; + + +/* + Parent virtual class of a pool for fast allocation + and deallocation of objects. +*/ +class MemPool +{ +public: + MemPool() {} + virtual ~MemPool() {} + + virtual int ItemSize() const = 0; + virtual void* Alloc() = 0; + virtual void Free( void* ) = 0; + virtual void SetTracked() = 0; +}; + + +/* + Template child class to create pools of the correct type. +*/ +template< int ITEM_SIZE > +class MemPoolT : public MemPool +{ +public: + MemPoolT() : _blockPtrs(), _root(0), _currentAllocs(0), _nAllocs(0), _maxAllocs(0), _nUntracked(0) {} + ~MemPoolT() { + MemPoolT< ITEM_SIZE >::Clear(); + } + + void Clear() { + // Delete the blocks. + while( !_blockPtrs.Empty()) { + Block* lastBlock = _blockPtrs.Pop(); + delete lastBlock; + } + _root = 0; + _currentAllocs = 0; + _nAllocs = 0; + _maxAllocs = 0; + _nUntracked = 0; + } + + virtual int ItemSize() const { + return ITEM_SIZE; + } + int CurrentAllocs() const { + return _currentAllocs; + } + + virtual void* Alloc() { + if ( !_root ) { + // Need a new block. + Block* block = new Block(); + _blockPtrs.Push( block ); + + Item* blockItems = block->items; + for( int i = 0; i < ITEMS_PER_BLOCK - 1; ++i ) { + blockItems[i].next = &(blockItems[i + 1]); + } + blockItems[ITEMS_PER_BLOCK - 1].next = 0; + _root = blockItems; + } + Item* const result = _root; + TIXMLASSERT( result != 0 ); + _root = _root->next; + + ++_currentAllocs; + if ( _currentAllocs > _maxAllocs ) { + _maxAllocs = _currentAllocs; + } + ++_nAllocs; + ++_nUntracked; + return result; + } + + virtual void Free( void* mem ) { + if ( !mem ) { + return; + } + --_currentAllocs; + Item* item = static_cast( mem ); +#ifdef TINYXML2_DEBUG + memset( item, 0xfe, sizeof( *item ) ); +#endif + item->next = _root; + _root = item; + } + void Trace( const char* name ) { + printf( "Mempool %s watermark=%d [%dk] current=%d size=%d nAlloc=%d blocks=%d\n", + name, _maxAllocs, _maxAllocs * ITEM_SIZE / 1024, _currentAllocs, + ITEM_SIZE, _nAllocs, _blockPtrs.Size() ); + } + + void SetTracked() { + --_nUntracked; + } + + int Untracked() const { + return _nUntracked; + } + + // This number is perf sensitive. 4k seems like a good tradeoff on my machine. + // The test file is large, 170k. + // Release: VS2010 gcc(no opt) + // 1k: 4000 + // 2k: 4000 + // 4k: 3900 21000 + // 16k: 5200 + // 32k: 4300 + // 64k: 4000 21000 + // Declared public because some compilers do not accept to use ITEMS_PER_BLOCK + // in private part if ITEMS_PER_BLOCK is private + enum { ITEMS_PER_BLOCK = (4 * 1024) / ITEM_SIZE }; + +private: + MemPoolT( const MemPoolT& ); // not supported + void operator=( const MemPoolT& ); // not supported + + union Item { + Item* next; + char itemData[ITEM_SIZE]; + }; + struct Block { + Item items[ITEMS_PER_BLOCK]; + }; + DynArray< Block*, 10 > _blockPtrs; + Item* _root; + + int _currentAllocs; + int _nAllocs; + int _maxAllocs; + int _nUntracked; +}; + + + +/** + Implements the interface to the "Visitor pattern" (see the Accept() method.) + If you call the Accept() method, it requires being passed a XMLVisitor + class to handle callbacks. For nodes that contain other nodes (Document, Element) + you will get called with a VisitEnter/VisitExit pair. Nodes that are always leafs + are simply called with Visit(). + + If you return 'true' from a Visit method, recursive parsing will continue. If you return + false, no children of this node or its siblings will be visited. + + All flavors of Visit methods have a default implementation that returns 'true' (continue + visiting). You need to only override methods that are interesting to you. + + Generally Accept() is called on the XMLDocument, although all nodes support visiting. + + You should never change the document from a callback. + + @sa XMLNode::Accept() +*/ +class TINYXML2_LIB XMLVisitor +{ +public: + virtual ~XMLVisitor() {} + + /// Visit a document. + virtual bool VisitEnter( const XMLDocument& /*doc*/ ) { + return true; + } + /// Visit a document. + virtual bool VisitExit( const XMLDocument& /*doc*/ ) { + return true; + } + + /// Visit an element. + virtual bool VisitEnter( const XMLElement& /*element*/, const XMLAttribute* /*firstAttribute*/ ) { + return true; + } + /// Visit an element. + virtual bool VisitExit( const XMLElement& /*element*/ ) { + return true; + } + + /// Visit a declaration. + virtual bool Visit( const XMLDeclaration& /*declaration*/ ) { + return true; + } + /// Visit a text node. + virtual bool Visit( const XMLText& /*text*/ ) { + return true; + } + /// Visit a comment node. + virtual bool Visit( const XMLComment& /*comment*/ ) { + return true; + } + /// Visit an unknown node. + virtual bool Visit( const XMLUnknown& /*unknown*/ ) { + return true; + } +}; + +// WARNING: must match XMLDocument::_errorNames[] +enum XMLError { + XML_SUCCESS = 0, + XML_NO_ATTRIBUTE, + XML_WRONG_ATTRIBUTE_TYPE, + XML_ERROR_FILE_NOT_FOUND, + XML_ERROR_FILE_COULD_NOT_BE_OPENED, + XML_ERROR_FILE_READ_ERROR, + XML_ERROR_PARSING_ELEMENT, + XML_ERROR_PARSING_ATTRIBUTE, + XML_ERROR_PARSING_TEXT, + XML_ERROR_PARSING_CDATA, + XML_ERROR_PARSING_COMMENT, + XML_ERROR_PARSING_DECLARATION, + XML_ERROR_PARSING_UNKNOWN, + XML_ERROR_EMPTY_DOCUMENT, + XML_ERROR_MISMATCHED_ELEMENT, + XML_ERROR_PARSING, + XML_CAN_NOT_CONVERT_TEXT, + XML_NO_TEXT_NODE, + XML_ELEMENT_DEPTH_EXCEEDED, + + XML_ERROR_COUNT +}; + + +/* + Utility functionality. +*/ +class TINYXML2_LIB XMLUtil +{ +public: + static const char* SkipWhiteSpace( const char* p, int* curLineNumPtr ) { + TIXMLASSERT( p ); + + while( IsWhiteSpace(*p) ) { + if (curLineNumPtr && *p == '\n') { + ++(*curLineNumPtr); + } + ++p; + } + TIXMLASSERT( p ); + return p; + } + static char* SkipWhiteSpace( char* const p, int* curLineNumPtr ) { + return const_cast( SkipWhiteSpace( const_cast(p), curLineNumPtr ) ); + } + + // Anything in the high order range of UTF-8 is assumed to not be whitespace. This isn't + // correct, but simple, and usually works. + static bool IsWhiteSpace( char p ) { + return !IsUTF8Continuation(p) && isspace( static_cast(p) ); + } + + inline static bool IsNameStartChar( unsigned char ch ) { + if ( ch >= 128 ) { + // This is a heuristic guess in attempt to not implement Unicode-aware isalpha() + return true; + } + if ( isalpha( ch ) ) { + return true; + } + return ch == ':' || ch == '_'; + } + + inline static bool IsNameChar( unsigned char ch ) { + return IsNameStartChar( ch ) + || isdigit( ch ) + || ch == '.' + || ch == '-'; + } + + inline static bool IsPrefixHex( const char* p) { + p = SkipWhiteSpace(p, 0); + return p && *p == '0' && ( *(p + 1) == 'x' || *(p + 1) == 'X'); + } + + inline static bool StringEqual( const char* p, const char* q, int nChar=INT_MAX ) { + if ( p == q ) { + return true; + } + TIXMLASSERT( p ); + TIXMLASSERT( q ); + TIXMLASSERT( nChar >= 0 ); + return strncmp( p, q, nChar ) == 0; + } + + inline static bool IsUTF8Continuation( const char p ) { + return ( p & 0x80 ) != 0; + } + + static const char* ReadBOM( const char* p, bool* hasBOM ); + // p is the starting location, + // the UTF-8 value of the entity will be placed in value, and length filled in. + static const char* GetCharacterRef( const char* p, char* value, int* length ); + static void ConvertUTF32ToUTF8( unsigned long input, char* output, int* length ); + + // converts primitive types to strings + static void ToStr( int v, char* buffer, int bufferSize ); + static void ToStr( unsigned v, char* buffer, int bufferSize ); + static void ToStr( bool v, char* buffer, int bufferSize ); + static void ToStr( float v, char* buffer, int bufferSize ); + static void ToStr( double v, char* buffer, int bufferSize ); + static void ToStr(int64_t v, char* buffer, int bufferSize); + static void ToStr(uint64_t v, char* buffer, int bufferSize); + + // converts strings to primitive types + static bool ToInt( const char* str, int* value ); + static bool ToUnsigned( const char* str, unsigned* value ); + static bool ToBool( const char* str, bool* value ); + static bool ToFloat( const char* str, float* value ); + static bool ToDouble( const char* str, double* value ); + static bool ToInt64(const char* str, int64_t* value); + static bool ToUnsigned64(const char* str, uint64_t* value); + // Changes what is serialized for a boolean value. + // Default to "true" and "false". Shouldn't be changed + // unless you have a special testing or compatibility need. + // Be careful: static, global, & not thread safe. + // Be sure to set static const memory as parameters. + static void SetBoolSerialization(const char* writeTrue, const char* writeFalse); + +private: + static const char* writeBoolTrue; + static const char* writeBoolFalse; +}; + + +/** XMLNode is a base class for every object that is in the + XML Document Object Model (DOM), except XMLAttributes. + Nodes have siblings, a parent, and children which can + be navigated. A node is always in a XMLDocument. + The type of a XMLNode can be queried, and it can + be cast to its more defined type. + + A XMLDocument allocates memory for all its Nodes. + When the XMLDocument gets deleted, all its Nodes + will also be deleted. + + @verbatim + A Document can contain: Element (container or leaf) + Comment (leaf) + Unknown (leaf) + Declaration( leaf ) + + An Element can contain: Element (container or leaf) + Text (leaf) + Attributes (not on tree) + Comment (leaf) + Unknown (leaf) + + @endverbatim +*/ +class TINYXML2_LIB XMLNode +{ + friend class XMLDocument; + friend class XMLElement; +public: + + /// Get the XMLDocument that owns this XMLNode. + const XMLDocument* GetDocument() const { + TIXMLASSERT( _document ); + return _document; + } + /// Get the XMLDocument that owns this XMLNode. + XMLDocument* GetDocument() { + TIXMLASSERT( _document ); + return _document; + } + + /// Safely cast to an Element, or null. + virtual XMLElement* ToElement() { + return 0; + } + /// Safely cast to Text, or null. + virtual XMLText* ToText() { + return 0; + } + /// Safely cast to a Comment, or null. + virtual XMLComment* ToComment() { + return 0; + } + /// Safely cast to a Document, or null. + virtual XMLDocument* ToDocument() { + return 0; + } + /// Safely cast to a Declaration, or null. + virtual XMLDeclaration* ToDeclaration() { + return 0; + } + /// Safely cast to an Unknown, or null. + virtual XMLUnknown* ToUnknown() { + return 0; + } + + virtual const XMLElement* ToElement() const { + return 0; + } + virtual const XMLText* ToText() const { + return 0; + } + virtual const XMLComment* ToComment() const { + return 0; + } + virtual const XMLDocument* ToDocument() const { + return 0; + } + virtual const XMLDeclaration* ToDeclaration() const { + return 0; + } + virtual const XMLUnknown* ToUnknown() const { + return 0; + } + + /** The meaning of 'value' changes for the specific type. + @verbatim + Document: empty (NULL is returned, not an empty string) + Element: name of the element + Comment: the comment text + Unknown: the tag contents + Text: the text string + @endverbatim + */ + const char* Value() const; + + /** Set the Value of an XML node. + @sa Value() + */ + void SetValue( const char* val, bool staticMem=false ); + + /// Gets the line number the node is in, if the document was parsed from a file. + int GetLineNum() const { return _parseLineNum; } + + /// Get the parent of this node on the DOM. + const XMLNode* Parent() const { + return _parent; + } + + XMLNode* Parent() { + return _parent; + } + + /// Returns true if this node has no children. + bool NoChildren() const { + return !_firstChild; + } + + /// Get the first child node, or null if none exists. + const XMLNode* FirstChild() const { + return _firstChild; + } + + XMLNode* FirstChild() { + return _firstChild; + } + + /** Get the first child element, or optionally the first child + element with the specified name. + */ + const XMLElement* FirstChildElement( const char* name = 0 ) const; + + XMLElement* FirstChildElement( const char* name = 0 ) { + return const_cast(const_cast(this)->FirstChildElement( name )); + } + + /// Get the last child node, or null if none exists. + const XMLNode* LastChild() const { + return _lastChild; + } + + XMLNode* LastChild() { + return _lastChild; + } + + /** Get the last child element or optionally the last child + element with the specified name. + */ + const XMLElement* LastChildElement( const char* name = 0 ) const; + + XMLElement* LastChildElement( const char* name = 0 ) { + return const_cast(const_cast(this)->LastChildElement(name) ); + } + + /// Get the previous (left) sibling node of this node. + const XMLNode* PreviousSibling() const { + return _prev; + } + + XMLNode* PreviousSibling() { + return _prev; + } + + /// Get the previous (left) sibling element of this node, with an optionally supplied name. + const XMLElement* PreviousSiblingElement( const char* name = 0 ) const ; + + XMLElement* PreviousSiblingElement( const char* name = 0 ) { + return const_cast(const_cast(this)->PreviousSiblingElement( name ) ); + } + + /// Get the next (right) sibling node of this node. + const XMLNode* NextSibling() const { + return _next; + } + + XMLNode* NextSibling() { + return _next; + } + + /// Get the next (right) sibling element of this node, with an optionally supplied name. + const XMLElement* NextSiblingElement( const char* name = 0 ) const; + + XMLElement* NextSiblingElement( const char* name = 0 ) { + return const_cast(const_cast(this)->NextSiblingElement( name ) ); + } + + /** + Add a child node as the last (right) child. + If the child node is already part of the document, + it is moved from its old location to the new location. + Returns the addThis argument or 0 if the node does not + belong to the same document. + */ + XMLNode* InsertEndChild( XMLNode* addThis ); + + XMLNode* LinkEndChild( XMLNode* addThis ) { + return InsertEndChild( addThis ); + } + /** + Add a child node as the first (left) child. + If the child node is already part of the document, + it is moved from its old location to the new location. + Returns the addThis argument or 0 if the node does not + belong to the same document. + */ + XMLNode* InsertFirstChild( XMLNode* addThis ); + /** + Add a node after the specified child node. + If the child node is already part of the document, + it is moved from its old location to the new location. + Returns the addThis argument or 0 if the afterThis node + is not a child of this node, or if the node does not + belong to the same document. + */ + XMLNode* InsertAfterChild( XMLNode* afterThis, XMLNode* addThis ); + + /** + Delete all the children of this node. + */ + void DeleteChildren(); + + /** + Delete a child of this node. + */ + void DeleteChild( XMLNode* node ); + + /** + Make a copy of this node, but not its children. + You may pass in a Document pointer that will be + the owner of the new Node. If the 'document' is + null, then the node returned will be allocated + from the current Document. (this->GetDocument()) + + Note: if called on a XMLDocument, this will return null. + */ + virtual XMLNode* ShallowClone( XMLDocument* document ) const = 0; + + /** + Make a copy of this node and all its children. + + If the 'target' is null, then the nodes will + be allocated in the current document. If 'target' + is specified, the memory will be allocated is the + specified XMLDocument. + + NOTE: This is probably not the correct tool to + copy a document, since XMLDocuments can have multiple + top level XMLNodes. You probably want to use + XMLDocument::DeepCopy() + */ + XMLNode* DeepClone( XMLDocument* target ) const; + + /** + Test if 2 nodes are the same, but don't test children. + The 2 nodes do not need to be in the same Document. + + Note: if called on a XMLDocument, this will return false. + */ + virtual bool ShallowEqual( const XMLNode* compare ) const = 0; + + /** Accept a hierarchical visit of the nodes in the TinyXML-2 DOM. Every node in the + XML tree will be conditionally visited and the host will be called back + via the XMLVisitor interface. + + This is essentially a SAX interface for TinyXML-2. (Note however it doesn't re-parse + the XML for the callbacks, so the performance of TinyXML-2 is unchanged by using this + interface versus any other.) + + The interface has been based on ideas from: + + - http://www.saxproject.org/ + - http://c2.com/cgi/wiki?HierarchicalVisitorPattern + + Which are both good references for "visiting". + + An example of using Accept(): + @verbatim + XMLPrinter printer; + tinyxmlDoc.Accept( &printer ); + const char* xmlcstr = printer.CStr(); + @endverbatim + */ + virtual bool Accept( XMLVisitor* visitor ) const = 0; + + /** + Set user data into the XMLNode. TinyXML-2 in + no way processes or interprets user data. + It is initially 0. + */ + void SetUserData(void* userData) { _userData = userData; } + + /** + Get user data set into the XMLNode. TinyXML-2 in + no way processes or interprets user data. + It is initially 0. + */ + void* GetUserData() const { return _userData; } + +protected: + explicit XMLNode( XMLDocument* ); + virtual ~XMLNode(); + + virtual char* ParseDeep( char* p, StrPair* parentEndTag, int* curLineNumPtr); + + XMLDocument* _document; + XMLNode* _parent; + mutable StrPair _value; + int _parseLineNum; + + XMLNode* _firstChild; + XMLNode* _lastChild; + + XMLNode* _prev; + XMLNode* _next; + + void* _userData; + +private: + MemPool* _memPool; + void Unlink( XMLNode* child ); + static void DeleteNode( XMLNode* node ); + void InsertChildPreamble( XMLNode* insertThis ) const; + const XMLElement* ToElementWithName( const char* name ) const; + + XMLNode( const XMLNode& ); // not supported + XMLNode& operator=( const XMLNode& ); // not supported +}; + + +/** XML text. + + Note that a text node can have child element nodes, for example: + @verbatim + This is bold + @endverbatim + + A text node can have 2 ways to output the next. "normal" output + and CDATA. It will default to the mode it was parsed from the XML file and + you generally want to leave it alone, but you can change the output mode with + SetCData() and query it with CData(). +*/ +class TINYXML2_LIB XMLText : public XMLNode +{ + friend class XMLDocument; +public: + virtual bool Accept( XMLVisitor* visitor ) const; + + virtual XMLText* ToText() { + return this; + } + virtual const XMLText* ToText() const { + return this; + } + + /// Declare whether this should be CDATA or standard text. + void SetCData( bool isCData ) { + _isCData = isCData; + } + /// Returns true if this is a CDATA text element. + bool CData() const { + return _isCData; + } + + virtual XMLNode* ShallowClone( XMLDocument* document ) const; + virtual bool ShallowEqual( const XMLNode* compare ) const; + +protected: + explicit XMLText( XMLDocument* doc ) : XMLNode( doc ), _isCData( false ) {} + virtual ~XMLText() {} + + char* ParseDeep( char* p, StrPair* parentEndTag, int* curLineNumPtr ); + +private: + bool _isCData; + + XMLText( const XMLText& ); // not supported + XMLText& operator=( const XMLText& ); // not supported +}; + + +/** An XML Comment. */ +class TINYXML2_LIB XMLComment : public XMLNode +{ + friend class XMLDocument; +public: + virtual XMLComment* ToComment() { + return this; + } + virtual const XMLComment* ToComment() const { + return this; + } + + virtual bool Accept( XMLVisitor* visitor ) const; + + virtual XMLNode* ShallowClone( XMLDocument* document ) const; + virtual bool ShallowEqual( const XMLNode* compare ) const; + +protected: + explicit XMLComment( XMLDocument* doc ); + virtual ~XMLComment(); + + char* ParseDeep( char* p, StrPair* parentEndTag, int* curLineNumPtr); + +private: + XMLComment( const XMLComment& ); // not supported + XMLComment& operator=( const XMLComment& ); // not supported +}; + + +/** In correct XML the declaration is the first entry in the file. + @verbatim + + @endverbatim + + TinyXML-2 will happily read or write files without a declaration, + however. + + The text of the declaration isn't interpreted. It is parsed + and written as a string. +*/ +class TINYXML2_LIB XMLDeclaration : public XMLNode +{ + friend class XMLDocument; +public: + virtual XMLDeclaration* ToDeclaration() { + return this; + } + virtual const XMLDeclaration* ToDeclaration() const { + return this; + } + + virtual bool Accept( XMLVisitor* visitor ) const; + + virtual XMLNode* ShallowClone( XMLDocument* document ) const; + virtual bool ShallowEqual( const XMLNode* compare ) const; + +protected: + explicit XMLDeclaration( XMLDocument* doc ); + virtual ~XMLDeclaration(); + + char* ParseDeep( char* p, StrPair* parentEndTag, int* curLineNumPtr ); + +private: + XMLDeclaration( const XMLDeclaration& ); // not supported + XMLDeclaration& operator=( const XMLDeclaration& ); // not supported +}; + + +/** Any tag that TinyXML-2 doesn't recognize is saved as an + unknown. It is a tag of text, but should not be modified. + It will be written back to the XML, unchanged, when the file + is saved. + + DTD tags get thrown into XMLUnknowns. +*/ +class TINYXML2_LIB XMLUnknown : public XMLNode +{ + friend class XMLDocument; +public: + virtual XMLUnknown* ToUnknown() { + return this; + } + virtual const XMLUnknown* ToUnknown() const { + return this; + } + + virtual bool Accept( XMLVisitor* visitor ) const; + + virtual XMLNode* ShallowClone( XMLDocument* document ) const; + virtual bool ShallowEqual( const XMLNode* compare ) const; + +protected: + explicit XMLUnknown( XMLDocument* doc ); + virtual ~XMLUnknown(); + + char* ParseDeep( char* p, StrPair* parentEndTag, int* curLineNumPtr ); + +private: + XMLUnknown( const XMLUnknown& ); // not supported + XMLUnknown& operator=( const XMLUnknown& ); // not supported +}; + + + +/** An attribute is a name-value pair. Elements have an arbitrary + number of attributes, each with a unique name. + + @note The attributes are not XMLNodes. You may only query the + Next() attribute in a list. +*/ +class TINYXML2_LIB XMLAttribute +{ + friend class XMLElement; +public: + /// The name of the attribute. + const char* Name() const; + + /// The value of the attribute. + const char* Value() const; + + /// Gets the line number the attribute is in, if the document was parsed from a file. + int GetLineNum() const { return _parseLineNum; } + + /// The next attribute in the list. + const XMLAttribute* Next() const { + return _next; + } + + /** IntValue interprets the attribute as an integer, and returns the value. + If the value isn't an integer, 0 will be returned. There is no error checking; + use QueryIntValue() if you need error checking. + */ + int IntValue() const { + int i = 0; + QueryIntValue(&i); + return i; + } + + int64_t Int64Value() const { + int64_t i = 0; + QueryInt64Value(&i); + return i; + } + + uint64_t Unsigned64Value() const { + uint64_t i = 0; + QueryUnsigned64Value(&i); + return i; + } + + /// Query as an unsigned integer. See IntValue() + unsigned UnsignedValue() const { + unsigned i=0; + QueryUnsignedValue( &i ); + return i; + } + /// Query as a boolean. See IntValue() + bool BoolValue() const { + bool b=false; + QueryBoolValue( &b ); + return b; + } + /// Query as a double. See IntValue() + double DoubleValue() const { + double d=0; + QueryDoubleValue( &d ); + return d; + } + /// Query as a float. See IntValue() + float FloatValue() const { + float f=0; + QueryFloatValue( &f ); + return f; + } + + /** QueryIntValue interprets the attribute as an integer, and returns the value + in the provided parameter. The function will return XML_SUCCESS on success, + and XML_WRONG_ATTRIBUTE_TYPE if the conversion is not successful. + */ + XMLError QueryIntValue( int* value ) const; + /// See QueryIntValue + XMLError QueryUnsignedValue( unsigned int* value ) const; + /// See QueryIntValue + XMLError QueryInt64Value(int64_t* value) const; + /// See QueryIntValue + XMLError QueryUnsigned64Value(uint64_t* value) const; + /// See QueryIntValue + XMLError QueryBoolValue( bool* value ) const; + /// See QueryIntValue + XMLError QueryDoubleValue( double* value ) const; + /// See QueryIntValue + XMLError QueryFloatValue( float* value ) const; + + /// Set the attribute to a string value. + void SetAttribute( const char* value ); + /// Set the attribute to value. + void SetAttribute( int value ); + /// Set the attribute to value. + void SetAttribute( unsigned value ); + /// Set the attribute to value. + void SetAttribute(int64_t value); + /// Set the attribute to value. + void SetAttribute(uint64_t value); + /// Set the attribute to value. + void SetAttribute( bool value ); + /// Set the attribute to value. + void SetAttribute( double value ); + /// Set the attribute to value. + void SetAttribute( float value ); + +private: + enum { BUF_SIZE = 200 }; + + XMLAttribute() : _name(), _value(),_parseLineNum( 0 ), _next( 0 ), _memPool( 0 ) {} + virtual ~XMLAttribute() {} + + XMLAttribute( const XMLAttribute& ); // not supported + void operator=( const XMLAttribute& ); // not supported + void SetName( const char* name ); + + char* ParseDeep( char* p, bool processEntities, int* curLineNumPtr ); + + mutable StrPair _name; + mutable StrPair _value; + int _parseLineNum; + XMLAttribute* _next; + MemPool* _memPool; +}; + + +/** The element is a container class. It has a value, the element name, + and can contain other elements, text, comments, and unknowns. + Elements also contain an arbitrary number of attributes. +*/ +class TINYXML2_LIB XMLElement : public XMLNode +{ + friend class XMLDocument; +public: + /// Get the name of an element (which is the Value() of the node.) + const char* Name() const { + return Value(); + } + /// Set the name of the element. + void SetName( const char* str, bool staticMem=false ) { + SetValue( str, staticMem ); + } + + virtual XMLElement* ToElement() { + return this; + } + virtual const XMLElement* ToElement() const { + return this; + } + virtual bool Accept( XMLVisitor* visitor ) const; + + /** Given an attribute name, Attribute() returns the value + for the attribute of that name, or null if none + exists. For example: + + @verbatim + const char* value = ele->Attribute( "foo" ); + @endverbatim + + The 'value' parameter is normally null. However, if specified, + the attribute will only be returned if the 'name' and 'value' + match. This allow you to write code: + + @verbatim + if ( ele->Attribute( "foo", "bar" ) ) callFooIsBar(); + @endverbatim + + rather than: + @verbatim + if ( ele->Attribute( "foo" ) ) { + if ( strcmp( ele->Attribute( "foo" ), "bar" ) == 0 ) callFooIsBar(); + } + @endverbatim + */ + const char* Attribute( const char* name, const char* value=0 ) const; + + /** Given an attribute name, IntAttribute() returns the value + of the attribute interpreted as an integer. The default + value will be returned if the attribute isn't present, + or if there is an error. (For a method with error + checking, see QueryIntAttribute()). + */ + int IntAttribute(const char* name, int defaultValue = 0) const; + /// See IntAttribute() + unsigned UnsignedAttribute(const char* name, unsigned defaultValue = 0) const; + /// See IntAttribute() + int64_t Int64Attribute(const char* name, int64_t defaultValue = 0) const; + /// See IntAttribute() + uint64_t Unsigned64Attribute(const char* name, uint64_t defaultValue = 0) const; + /// See IntAttribute() + bool BoolAttribute(const char* name, bool defaultValue = false) const; + /// See IntAttribute() + double DoubleAttribute(const char* name, double defaultValue = 0) const; + /// See IntAttribute() + float FloatAttribute(const char* name, float defaultValue = 0) const; + + /** Given an attribute name, QueryIntAttribute() returns + XML_SUCCESS, XML_WRONG_ATTRIBUTE_TYPE if the conversion + can't be performed, or XML_NO_ATTRIBUTE if the attribute + doesn't exist. If successful, the result of the conversion + will be written to 'value'. If not successful, nothing will + be written to 'value'. This allows you to provide default + value: + + @verbatim + int value = 10; + QueryIntAttribute( "foo", &value ); // if "foo" isn't found, value will still be 10 + @endverbatim + */ + XMLError QueryIntAttribute( const char* name, int* value ) const { + const XMLAttribute* a = FindAttribute( name ); + if ( !a ) { + return XML_NO_ATTRIBUTE; + } + return a->QueryIntValue( value ); + } + + /// See QueryIntAttribute() + XMLError QueryUnsignedAttribute( const char* name, unsigned int* value ) const { + const XMLAttribute* a = FindAttribute( name ); + if ( !a ) { + return XML_NO_ATTRIBUTE; + } + return a->QueryUnsignedValue( value ); + } + + /// See QueryIntAttribute() + XMLError QueryInt64Attribute(const char* name, int64_t* value) const { + const XMLAttribute* a = FindAttribute(name); + if (!a) { + return XML_NO_ATTRIBUTE; + } + return a->QueryInt64Value(value); + } + + /// See QueryIntAttribute() + XMLError QueryUnsigned64Attribute(const char* name, uint64_t* value) const { + const XMLAttribute* a = FindAttribute(name); + if(!a) { + return XML_NO_ATTRIBUTE; + } + return a->QueryUnsigned64Value(value); + } + + /// See QueryIntAttribute() + XMLError QueryBoolAttribute( const char* name, bool* value ) const { + const XMLAttribute* a = FindAttribute( name ); + if ( !a ) { + return XML_NO_ATTRIBUTE; + } + return a->QueryBoolValue( value ); + } + /// See QueryIntAttribute() + XMLError QueryDoubleAttribute( const char* name, double* value ) const { + const XMLAttribute* a = FindAttribute( name ); + if ( !a ) { + return XML_NO_ATTRIBUTE; + } + return a->QueryDoubleValue( value ); + } + /// See QueryIntAttribute() + XMLError QueryFloatAttribute( const char* name, float* value ) const { + const XMLAttribute* a = FindAttribute( name ); + if ( !a ) { + return XML_NO_ATTRIBUTE; + } + return a->QueryFloatValue( value ); + } + + /// See QueryIntAttribute() + XMLError QueryStringAttribute(const char* name, const char** value) const { + const XMLAttribute* a = FindAttribute(name); + if (!a) { + return XML_NO_ATTRIBUTE; + } + *value = a->Value(); + return XML_SUCCESS; + } + + + + /** Given an attribute name, QueryAttribute() returns + XML_SUCCESS, XML_WRONG_ATTRIBUTE_TYPE if the conversion + can't be performed, or XML_NO_ATTRIBUTE if the attribute + doesn't exist. It is overloaded for the primitive types, + and is a generally more convenient replacement of + QueryIntAttribute() and related functions. + + If successful, the result of the conversion + will be written to 'value'. If not successful, nothing will + be written to 'value'. This allows you to provide default + value: + + @verbatim + int value = 10; + QueryAttribute( "foo", &value ); // if "foo" isn't found, value will still be 10 + @endverbatim + */ + XMLError QueryAttribute( const char* name, int* value ) const { + return QueryIntAttribute( name, value ); + } + + XMLError QueryAttribute( const char* name, unsigned int* value ) const { + return QueryUnsignedAttribute( name, value ); + } + + XMLError QueryAttribute(const char* name, int64_t* value) const { + return QueryInt64Attribute(name, value); + } + + XMLError QueryAttribute(const char* name, uint64_t* value) const { + return QueryUnsigned64Attribute(name, value); + } + + XMLError QueryAttribute( const char* name, bool* value ) const { + return QueryBoolAttribute( name, value ); + } + + XMLError QueryAttribute( const char* name, double* value ) const { + return QueryDoubleAttribute( name, value ); + } + + XMLError QueryAttribute( const char* name, float* value ) const { + return QueryFloatAttribute( name, value ); + } + + XMLError QueryAttribute(const char* name, const char** value) const { + return QueryStringAttribute(name, value); + } + + /// Sets the named attribute to value. + void SetAttribute( const char* name, const char* value ) { + XMLAttribute* a = FindOrCreateAttribute( name ); + a->SetAttribute( value ); + } + /// Sets the named attribute to value. + void SetAttribute( const char* name, int value ) { + XMLAttribute* a = FindOrCreateAttribute( name ); + a->SetAttribute( value ); + } + /// Sets the named attribute to value. + void SetAttribute( const char* name, unsigned value ) { + XMLAttribute* a = FindOrCreateAttribute( name ); + a->SetAttribute( value ); + } + + /// Sets the named attribute to value. + void SetAttribute(const char* name, int64_t value) { + XMLAttribute* a = FindOrCreateAttribute(name); + a->SetAttribute(value); + } + + /// Sets the named attribute to value. + void SetAttribute(const char* name, uint64_t value) { + XMLAttribute* a = FindOrCreateAttribute(name); + a->SetAttribute(value); + } + + /// Sets the named attribute to value. + void SetAttribute( const char* name, bool value ) { + XMLAttribute* a = FindOrCreateAttribute( name ); + a->SetAttribute( value ); + } + /// Sets the named attribute to value. + void SetAttribute( const char* name, double value ) { + XMLAttribute* a = FindOrCreateAttribute( name ); + a->SetAttribute( value ); + } + /// Sets the named attribute to value. + void SetAttribute( const char* name, float value ) { + XMLAttribute* a = FindOrCreateAttribute( name ); + a->SetAttribute( value ); + } + + /** + Delete an attribute. + */ + void DeleteAttribute( const char* name ); + + /// Return the first attribute in the list. + const XMLAttribute* FirstAttribute() const { + return _rootAttribute; + } + /// Query a specific attribute in the list. + const XMLAttribute* FindAttribute( const char* name ) const; + + /** Convenience function for easy access to the text inside an element. Although easy + and concise, GetText() is limited compared to getting the XMLText child + and accessing it directly. + + If the first child of 'this' is a XMLText, the GetText() + returns the character string of the Text node, else null is returned. + + This is a convenient method for getting the text of simple contained text: + @verbatim + This is text + const char* str = fooElement->GetText(); + @endverbatim + + 'str' will be a pointer to "This is text". + + Note that this function can be misleading. If the element foo was created from + this XML: + @verbatim + This is text + @endverbatim + + then the value of str would be null. The first child node isn't a text node, it is + another element. From this XML: + @verbatim + This is text + @endverbatim + GetText() will return "This is ". + */ + const char* GetText() const; + + /** Convenience function for easy access to the text inside an element. Although easy + and concise, SetText() is limited compared to creating an XMLText child + and mutating it directly. + + If the first child of 'this' is a XMLText, SetText() sets its value to + the given string, otherwise it will create a first child that is an XMLText. + + This is a convenient method for setting the text of simple contained text: + @verbatim + This is text + fooElement->SetText( "Hullaballoo!" ); + Hullaballoo! + @endverbatim + + Note that this function can be misleading. If the element foo was created from + this XML: + @verbatim + This is text + @endverbatim + + then it will not change "This is text", but rather prefix it with a text element: + @verbatim + Hullaballoo!This is text + @endverbatim + + For this XML: + @verbatim + + @endverbatim + SetText() will generate + @verbatim + Hullaballoo! + @endverbatim + */ + void SetText( const char* inText ); + /// Convenience method for setting text inside an element. See SetText() for important limitations. + void SetText( int value ); + /// Convenience method for setting text inside an element. See SetText() for important limitations. + void SetText( unsigned value ); + /// Convenience method for setting text inside an element. See SetText() for important limitations. + void SetText(int64_t value); + /// Convenience method for setting text inside an element. See SetText() for important limitations. + void SetText(uint64_t value); + /// Convenience method for setting text inside an element. See SetText() for important limitations. + void SetText( bool value ); + /// Convenience method for setting text inside an element. See SetText() for important limitations. + void SetText( double value ); + /// Convenience method for setting text inside an element. See SetText() for important limitations. + void SetText( float value ); + + /** + Convenience method to query the value of a child text node. This is probably best + shown by example. Given you have a document is this form: + @verbatim + + 1 + 1.4 + + @endverbatim + + The QueryIntText() and similar functions provide a safe and easier way to get to the + "value" of x and y. + + @verbatim + int x = 0; + float y = 0; // types of x and y are contrived for example + const XMLElement* xElement = pointElement->FirstChildElement( "x" ); + const XMLElement* yElement = pointElement->FirstChildElement( "y" ); + xElement->QueryIntText( &x ); + yElement->QueryFloatText( &y ); + @endverbatim + + @returns XML_SUCCESS (0) on success, XML_CAN_NOT_CONVERT_TEXT if the text cannot be converted + to the requested type, and XML_NO_TEXT_NODE if there is no child text to query. + + */ + XMLError QueryIntText( int* ival ) const; + /// See QueryIntText() + XMLError QueryUnsignedText( unsigned* uval ) const; + /// See QueryIntText() + XMLError QueryInt64Text(int64_t* uval) const; + /// See QueryIntText() + XMLError QueryUnsigned64Text(uint64_t* uval) const; + /// See QueryIntText() + XMLError QueryBoolText( bool* bval ) const; + /// See QueryIntText() + XMLError QueryDoubleText( double* dval ) const; + /// See QueryIntText() + XMLError QueryFloatText( float* fval ) const; + + int IntText(int defaultValue = 0) const; + + /// See QueryIntText() + unsigned UnsignedText(unsigned defaultValue = 0) const; + /// See QueryIntText() + int64_t Int64Text(int64_t defaultValue = 0) const; + /// See QueryIntText() + uint64_t Unsigned64Text(uint64_t defaultValue = 0) const; + /// See QueryIntText() + bool BoolText(bool defaultValue = false) const; + /// See QueryIntText() + double DoubleText(double defaultValue = 0) const; + /// See QueryIntText() + float FloatText(float defaultValue = 0) const; + + /** + Convenience method to create a new XMLElement and add it as last (right) + child of this node. Returns the created and inserted element. + */ + XMLElement* InsertNewChildElement(const char* name); + /// See InsertNewChildElement() + XMLComment* InsertNewComment(const char* comment); + /// See InsertNewChildElement() + XMLText* InsertNewText(const char* text); + /// See InsertNewChildElement() + XMLDeclaration* InsertNewDeclaration(const char* text); + /// See InsertNewChildElement() + XMLUnknown* InsertNewUnknown(const char* text); + + + // internal: + enum ElementClosingType { + OPEN, // + CLOSED, // + CLOSING // + }; + ElementClosingType ClosingType() const { + return _closingType; + } + virtual XMLNode* ShallowClone( XMLDocument* document ) const; + virtual bool ShallowEqual( const XMLNode* compare ) const; + +protected: + char* ParseDeep( char* p, StrPair* parentEndTag, int* curLineNumPtr ); + +private: + XMLElement( XMLDocument* doc ); + virtual ~XMLElement(); + XMLElement( const XMLElement& ); // not supported + void operator=( const XMLElement& ); // not supported + + XMLAttribute* FindOrCreateAttribute( const char* name ); + char* ParseAttributes( char* p, int* curLineNumPtr ); + static void DeleteAttribute( XMLAttribute* attribute ); + XMLAttribute* CreateAttribute(); + + enum { BUF_SIZE = 200 }; + ElementClosingType _closingType; + // The attribute list is ordered; there is no 'lastAttribute' + // because the list needs to be scanned for dupes before adding + // a new attribute. + XMLAttribute* _rootAttribute; +}; + + +enum Whitespace { + PRESERVE_WHITESPACE, + COLLAPSE_WHITESPACE +}; + + +/** A Document binds together all the functionality. + It can be saved, loaded, and printed to the screen. + All Nodes are connected and allocated to a Document. + If the Document is deleted, all its Nodes are also deleted. +*/ +class TINYXML2_LIB XMLDocument : public XMLNode +{ + friend class XMLElement; + // Gives access to SetError and Push/PopDepth, but over-access for everything else. + // Wishing C++ had "internal" scope. + friend class XMLNode; + friend class XMLText; + friend class XMLComment; + friend class XMLDeclaration; + friend class XMLUnknown; +public: + /// constructor + XMLDocument( bool processEntities = true, Whitespace whitespaceMode = PRESERVE_WHITESPACE ); + ~XMLDocument(); + + virtual XMLDocument* ToDocument() { + TIXMLASSERT( this == _document ); + return this; + } + virtual const XMLDocument* ToDocument() const { + TIXMLASSERT( this == _document ); + return this; + } + + /** + Parse an XML file from a character string. + Returns XML_SUCCESS (0) on success, or + an errorID. + + You may optionally pass in the 'nBytes', which is + the number of bytes which will be parsed. If not + specified, TinyXML-2 will assume 'xml' points to a + null terminated string. + */ + XMLError Parse( const char* xml, size_t nBytes=static_cast(-1) ); + + /** + Load an XML file from disk. + Returns XML_SUCCESS (0) on success, or + an errorID. + */ + XMLError LoadFile( const char* filename ); + + /** + Load an XML file from disk. You are responsible + for providing and closing the FILE*. + + NOTE: The file should be opened as binary ("rb") + not text in order for TinyXML-2 to correctly + do newline normalization. + + Returns XML_SUCCESS (0) on success, or + an errorID. + */ + XMLError LoadFile( FILE* ); + + /** + Save the XML file to disk. + Returns XML_SUCCESS (0) on success, or + an errorID. + */ + XMLError SaveFile( const char* filename, bool compact = false ); + + /** + Save the XML file to disk. You are responsible + for providing and closing the FILE*. + + Returns XML_SUCCESS (0) on success, or + an errorID. + */ + XMLError SaveFile( FILE* fp, bool compact = false ); + + bool ProcessEntities() const { + return _processEntities; + } + Whitespace WhitespaceMode() const { + return _whitespaceMode; + } + + /** + Returns true if this document has a leading Byte Order Mark of UTF8. + */ + bool HasBOM() const { + return _writeBOM; + } + /** Sets whether to write the BOM when writing the file. + */ + void SetBOM( bool useBOM ) { + _writeBOM = useBOM; + } + + /** Return the root element of DOM. Equivalent to FirstChildElement(). + To get the first node, use FirstChild(). + */ + XMLElement* RootElement() { + return FirstChildElement(); + } + const XMLElement* RootElement() const { + return FirstChildElement(); + } + + /** Print the Document. If the Printer is not provided, it will + print to stdout. If you provide Printer, this can print to a file: + @verbatim + XMLPrinter printer( fp ); + doc.Print( &printer ); + @endverbatim + + Or you can use a printer to print to memory: + @verbatim + XMLPrinter printer; + doc.Print( &printer ); + // printer.CStr() has a const char* to the XML + @endverbatim + */ + void Print( XMLPrinter* streamer=0 ) const; + virtual bool Accept( XMLVisitor* visitor ) const; + + /** + Create a new Element associated with + this Document. The memory for the Element + is managed by the Document. + */ + XMLElement* NewElement( const char* name ); + /** + Create a new Comment associated with + this Document. The memory for the Comment + is managed by the Document. + */ + XMLComment* NewComment( const char* comment ); + /** + Create a new Text associated with + this Document. The memory for the Text + is managed by the Document. + */ + XMLText* NewText( const char* text ); + /** + Create a new Declaration associated with + this Document. The memory for the object + is managed by the Document. + + If the 'text' param is null, the standard + declaration is used.: + @verbatim + + @endverbatim + */ + XMLDeclaration* NewDeclaration( const char* text=0 ); + /** + Create a new Unknown associated with + this Document. The memory for the object + is managed by the Document. + */ + XMLUnknown* NewUnknown( const char* text ); + + /** + Delete a node associated with this document. + It will be unlinked from the DOM. + */ + void DeleteNode( XMLNode* node ); + + /// Clears the error flags. + void ClearError(); + + /// Return true if there was an error parsing the document. + bool Error() const { + return _errorID != XML_SUCCESS; + } + /// Return the errorID. + XMLError ErrorID() const { + return _errorID; + } + const char* ErrorName() const; + static const char* ErrorIDToName(XMLError errorID); + + /** Returns a "long form" error description. A hopefully helpful + diagnostic with location, line number, and/or additional info. + */ + const char* ErrorStr() const; + + /// A (trivial) utility function that prints the ErrorStr() to stdout. + void PrintError() const; + + /// Return the line where the error occurred, or zero if unknown. + int ErrorLineNum() const + { + return _errorLineNum; + } + + /// Clear the document, resetting it to the initial state. + void Clear(); + + /** + Copies this document to a target document. + The target will be completely cleared before the copy. + If you want to copy a sub-tree, see XMLNode::DeepClone(). + + NOTE: that the 'target' must be non-null. + */ + void DeepCopy(XMLDocument* target) const; + + // internal + char* Identify( char* p, XMLNode** node ); + + // internal + void MarkInUse(const XMLNode* const); + + virtual XMLNode* ShallowClone( XMLDocument* /*document*/ ) const { + return 0; + } + virtual bool ShallowEqual( const XMLNode* /*compare*/ ) const { + return false; + } + +private: + XMLDocument( const XMLDocument& ); // not supported + void operator=( const XMLDocument& ); // not supported + + bool _writeBOM; + bool _processEntities; + XMLError _errorID; + Whitespace _whitespaceMode; + mutable StrPair _errorStr; + int _errorLineNum; + char* _charBuffer; + int _parseCurLineNum; + int _parsingDepth; + // Memory tracking does add some overhead. + // However, the code assumes that you don't + // have a bunch of unlinked nodes around. + // Therefore it takes less memory to track + // in the document vs. a linked list in the XMLNode, + // and the performance is the same. + DynArray _unlinked; + + MemPoolT< sizeof(XMLElement) > _elementPool; + MemPoolT< sizeof(XMLAttribute) > _attributePool; + MemPoolT< sizeof(XMLText) > _textPool; + MemPoolT< sizeof(XMLComment) > _commentPool; + + static const char* _errorNames[XML_ERROR_COUNT]; + + void Parse(); + + void SetError( XMLError error, int lineNum, const char* format, ... ); + + // Something of an obvious security hole, once it was discovered. + // Either an ill-formed XML or an excessively deep one can overflow + // the stack. Track stack depth, and error out if needed. + class DepthTracker { + public: + explicit DepthTracker(XMLDocument * document) { + this->_document = document; + document->PushDepth(); + } + ~DepthTracker() { + _document->PopDepth(); + } + private: + XMLDocument * _document; + }; + void PushDepth(); + void PopDepth(); + + template + NodeType* CreateUnlinkedNode( MemPoolT& pool ); +}; + +template +inline NodeType* XMLDocument::CreateUnlinkedNode( MemPoolT& pool ) +{ + TIXMLASSERT( sizeof( NodeType ) == PoolElementSize ); + TIXMLASSERT( sizeof( NodeType ) == pool.ItemSize() ); + NodeType* returnNode = new (pool.Alloc()) NodeType( this ); + TIXMLASSERT( returnNode ); + returnNode->_memPool = &pool; + + _unlinked.Push(returnNode); + return returnNode; +} + +/** + A XMLHandle is a class that wraps a node pointer with null checks; this is + an incredibly useful thing. Note that XMLHandle is not part of the TinyXML-2 + DOM structure. It is a separate utility class. + + Take an example: + @verbatim + + + + + + + @endverbatim + + Assuming you want the value of "attributeB" in the 2nd "Child" element, it's very + easy to write a *lot* of code that looks like: + + @verbatim + XMLElement* root = document.FirstChildElement( "Document" ); + if ( root ) + { + XMLElement* element = root->FirstChildElement( "Element" ); + if ( element ) + { + XMLElement* child = element->FirstChildElement( "Child" ); + if ( child ) + { + XMLElement* child2 = child->NextSiblingElement( "Child" ); + if ( child2 ) + { + // Finally do something useful. + @endverbatim + + And that doesn't even cover "else" cases. XMLHandle addresses the verbosity + of such code. A XMLHandle checks for null pointers so it is perfectly safe + and correct to use: + + @verbatim + XMLHandle docHandle( &document ); + XMLElement* child2 = docHandle.FirstChildElement( "Document" ).FirstChildElement( "Element" ).FirstChildElement().NextSiblingElement(); + if ( child2 ) + { + // do something useful + @endverbatim + + Which is MUCH more concise and useful. + + It is also safe to copy handles - internally they are nothing more than node pointers. + @verbatim + XMLHandle handleCopy = handle; + @endverbatim + + See also XMLConstHandle, which is the same as XMLHandle, but operates on const objects. +*/ +class TINYXML2_LIB XMLHandle +{ +public: + /// Create a handle from any node (at any depth of the tree.) This can be a null pointer. + explicit XMLHandle( XMLNode* node ) : _node( node ) { + } + /// Create a handle from a node. + explicit XMLHandle( XMLNode& node ) : _node( &node ) { + } + /// Copy constructor + XMLHandle( const XMLHandle& ref ) : _node( ref._node ) { + } + /// Assignment + XMLHandle& operator=( const XMLHandle& ref ) { + _node = ref._node; + return *this; + } + + /// Get the first child of this handle. + XMLHandle FirstChild() { + return XMLHandle( _node ? _node->FirstChild() : 0 ); + } + /// Get the first child element of this handle. + XMLHandle FirstChildElement( const char* name = 0 ) { + return XMLHandle( _node ? _node->FirstChildElement( name ) : 0 ); + } + /// Get the last child of this handle. + XMLHandle LastChild() { + return XMLHandle( _node ? _node->LastChild() : 0 ); + } + /// Get the last child element of this handle. + XMLHandle LastChildElement( const char* name = 0 ) { + return XMLHandle( _node ? _node->LastChildElement( name ) : 0 ); + } + /// Get the previous sibling of this handle. + XMLHandle PreviousSibling() { + return XMLHandle( _node ? _node->PreviousSibling() : 0 ); + } + /// Get the previous sibling element of this handle. + XMLHandle PreviousSiblingElement( const char* name = 0 ) { + return XMLHandle( _node ? _node->PreviousSiblingElement( name ) : 0 ); + } + /// Get the next sibling of this handle. + XMLHandle NextSibling() { + return XMLHandle( _node ? _node->NextSibling() : 0 ); + } + /// Get the next sibling element of this handle. + XMLHandle NextSiblingElement( const char* name = 0 ) { + return XMLHandle( _node ? _node->NextSiblingElement( name ) : 0 ); + } + + /// Safe cast to XMLNode. This can return null. + XMLNode* ToNode() { + return _node; + } + /// Safe cast to XMLElement. This can return null. + XMLElement* ToElement() { + return ( _node ? _node->ToElement() : 0 ); + } + /// Safe cast to XMLText. This can return null. + XMLText* ToText() { + return ( _node ? _node->ToText() : 0 ); + } + /// Safe cast to XMLUnknown. This can return null. + XMLUnknown* ToUnknown() { + return ( _node ? _node->ToUnknown() : 0 ); + } + /// Safe cast to XMLDeclaration. This can return null. + XMLDeclaration* ToDeclaration() { + return ( _node ? _node->ToDeclaration() : 0 ); + } + +private: + XMLNode* _node; +}; + + +/** + A variant of the XMLHandle class for working with const XMLNodes and Documents. It is the + same in all regards, except for the 'const' qualifiers. See XMLHandle for API. +*/ +class TINYXML2_LIB XMLConstHandle +{ +public: + explicit XMLConstHandle( const XMLNode* node ) : _node( node ) { + } + explicit XMLConstHandle( const XMLNode& node ) : _node( &node ) { + } + XMLConstHandle( const XMLConstHandle& ref ) : _node( ref._node ) { + } + + XMLConstHandle& operator=( const XMLConstHandle& ref ) { + _node = ref._node; + return *this; + } + + const XMLConstHandle FirstChild() const { + return XMLConstHandle( _node ? _node->FirstChild() : 0 ); + } + const XMLConstHandle FirstChildElement( const char* name = 0 ) const { + return XMLConstHandle( _node ? _node->FirstChildElement( name ) : 0 ); + } + const XMLConstHandle LastChild() const { + return XMLConstHandle( _node ? _node->LastChild() : 0 ); + } + const XMLConstHandle LastChildElement( const char* name = 0 ) const { + return XMLConstHandle( _node ? _node->LastChildElement( name ) : 0 ); + } + const XMLConstHandle PreviousSibling() const { + return XMLConstHandle( _node ? _node->PreviousSibling() : 0 ); + } + const XMLConstHandle PreviousSiblingElement( const char* name = 0 ) const { + return XMLConstHandle( _node ? _node->PreviousSiblingElement( name ) : 0 ); + } + const XMLConstHandle NextSibling() const { + return XMLConstHandle( _node ? _node->NextSibling() : 0 ); + } + const XMLConstHandle NextSiblingElement( const char* name = 0 ) const { + return XMLConstHandle( _node ? _node->NextSiblingElement( name ) : 0 ); + } + + + const XMLNode* ToNode() const { + return _node; + } + const XMLElement* ToElement() const { + return ( _node ? _node->ToElement() : 0 ); + } + const XMLText* ToText() const { + return ( _node ? _node->ToText() : 0 ); + } + const XMLUnknown* ToUnknown() const { + return ( _node ? _node->ToUnknown() : 0 ); + } + const XMLDeclaration* ToDeclaration() const { + return ( _node ? _node->ToDeclaration() : 0 ); + } + +private: + const XMLNode* _node; +}; + + +/** + Printing functionality. The XMLPrinter gives you more + options than the XMLDocument::Print() method. + + It can: + -# Print to memory. + -# Print to a file you provide. + -# Print XML without a XMLDocument. + + Print to Memory + + @verbatim + XMLPrinter printer; + doc.Print( &printer ); + SomeFunction( printer.CStr() ); + @endverbatim + + Print to a File + + You provide the file pointer. + @verbatim + XMLPrinter printer( fp ); + doc.Print( &printer ); + @endverbatim + + Print without a XMLDocument + + When loading, an XML parser is very useful. However, sometimes + when saving, it just gets in the way. The code is often set up + for streaming, and constructing the DOM is just overhead. + + The Printer supports the streaming case. The following code + prints out a trivially simple XML file without ever creating + an XML document. + + @verbatim + XMLPrinter printer( fp ); + printer.OpenElement( "foo" ); + printer.PushAttribute( "foo", "bar" ); + printer.CloseElement(); + @endverbatim +*/ +class TINYXML2_LIB XMLPrinter : public XMLVisitor +{ +public: + /** Construct the printer. If the FILE* is specified, + this will print to the FILE. Else it will print + to memory, and the result is available in CStr(). + If 'compact' is set to true, then output is created + with only required whitespace and newlines. + */ + XMLPrinter( FILE* file=0, bool compact = false, int depth = 0 ); + virtual ~XMLPrinter() {} + + /** If streaming, write the BOM and declaration. */ + void PushHeader( bool writeBOM, bool writeDeclaration ); + /** If streaming, start writing an element. + The element must be closed with CloseElement() + */ + void OpenElement( const char* name, bool compactMode=false ); + /// If streaming, add an attribute to an open element. + void PushAttribute( const char* name, const char* value ); + void PushAttribute( const char* name, int value ); + void PushAttribute( const char* name, unsigned value ); + void PushAttribute( const char* name, int64_t value ); + void PushAttribute( const char* name, uint64_t value ); + void PushAttribute( const char* name, bool value ); + void PushAttribute( const char* name, double value ); + /// If streaming, close the Element. + virtual void CloseElement( bool compactMode=false ); + + /// Add a text node. + void PushText( const char* text, bool cdata=false ); + /// Add a text node from an integer. + void PushText( int value ); + /// Add a text node from an unsigned. + void PushText( unsigned value ); + /// Add a text node from a signed 64bit integer. + void PushText( int64_t value ); + /// Add a text node from an unsigned 64bit integer. + void PushText( uint64_t value ); + /// Add a text node from a bool. + void PushText( bool value ); + /// Add a text node from a float. + void PushText( float value ); + /// Add a text node from a double. + void PushText( double value ); + + /// Add a comment + void PushComment( const char* comment ); + + void PushDeclaration( const char* value ); + void PushUnknown( const char* value ); + + virtual bool VisitEnter( const XMLDocument& /*doc*/ ); + virtual bool VisitExit( const XMLDocument& /*doc*/ ) { + return true; + } + + virtual bool VisitEnter( const XMLElement& element, const XMLAttribute* attribute ); + virtual bool VisitExit( const XMLElement& element ); + + virtual bool Visit( const XMLText& text ); + virtual bool Visit( const XMLComment& comment ); + virtual bool Visit( const XMLDeclaration& declaration ); + virtual bool Visit( const XMLUnknown& unknown ); + + /** + If in print to memory mode, return a pointer to + the XML file in memory. + */ + const char* CStr() const { + return _buffer.Mem(); + } + /** + If in print to memory mode, return the size + of the XML file in memory. (Note the size returned + includes the terminating null.) + */ + int CStrSize() const { + return _buffer.Size(); + } + /** + If in print to memory mode, reset the buffer to the + beginning. + */ + void ClearBuffer( bool resetToFirstElement = true ) { + _buffer.Clear(); + _buffer.Push(0); + _firstElement = resetToFirstElement; + } + +protected: + virtual bool CompactMode( const XMLElement& ) { return _compactMode; } + + /** Prints out the space before an element. You may override to change + the space and tabs used. A PrintSpace() override should call Print(). + */ + virtual void PrintSpace( int depth ); + virtual void Print( const char* format, ... ); + virtual void Write( const char* data, size_t size ); + virtual void Putc( char ch ); + + inline void Write(const char* data) { Write(data, strlen(data)); } + + void SealElementIfJustOpened(); + bool _elementJustOpened; + DynArray< const char*, 10 > _stack; + +private: + /** + Prepares to write a new node. This includes sealing an element that was + just opened, and writing any whitespace necessary if not in compact mode. + */ + void PrepareForNewNode( bool compactMode ); + void PrintString( const char*, bool restrictedEntitySet ); // prints out, after detecting entities. + + bool _firstElement; + FILE* _fp; + int _depth; + int _textDepth; + bool _processEntities; + bool _compactMode; + + enum { + ENTITY_RANGE = 64, + BUF_SIZE = 200 + }; + bool _entityFlag[ENTITY_RANGE]; + bool _restrictedEntityFlag[ENTITY_RANGE]; + + DynArray< char, 20 > _buffer; + + // Prohibit cloning, intentionally not implemented + XMLPrinter( const XMLPrinter& ); + XMLPrinter& operator=( const XMLPrinter& ); +}; + + +} // tinyxml2 + +#if defined(_MSC_VER) +# pragma warning(pop) +#endif + +#endif // TINYXML2_INCLUDED diff --git a/demo/eth.cpp b/demo/eth.cpp new file mode 100644 index 0000000..e442976 --- /dev/null +++ b/demo/eth.cpp @@ -0,0 +1,111 @@ + + +#include +#include +#include +#include +#include +#include +#include + +#include "../SDK/SDKInfo.h" + + +using namespace std; + + +struct Proto +{ + IHDProtocol proto; + ISDKInfo info; +}; + +int IsRead = 0; + + +static bool SendData(const char *data, int len, void *userData) { + int fd = (int)(intptr_t)userData; + return write(fd, data, len) > 0; +} + +static void ReadXml(const char *xml, int len, int errorCode, void *userData) { + Proto *info = (Proto *)userData; + ++IsRead; + if (errorCode != 0) { + printf("error code[%d]\n", errorCode); + return ; + } + ParseXml(xml, len, info->info); + + std::cout << "dhcp:" << GetEhtInfoDhcp(info->info) << "\n" + << "ip:" << GetEhtInfoIp(info->info) << "\n" + << "netmask:" << GetEhtInfoNetmask(info->info) << "\n" + << "gateway:" << GetEhtInfoGateway(info->info) << "\n" + << "dns:" << GetEhtInfoDns(info->info) << "\n" + << std::endl; + + if (IsRead == 1) { +// UpdateItem(info->proto, info->info, kSetEthInfo); + } + UpdateItem(info->proto, info->info, kGetEthInfo); +} + + +int main(int argc, char *argv[]) +{ + if (argc < 2) { + printf("a.out ip\n"); + return 0; + } + + int fd = socket(AF_INET, SOCK_STREAM, 0); + if (fd < 0) { + perror("create socket faild"); + return 1; + } + + struct sockaddr_in addrSrv; + memset(&addrSrv, 0, sizeof(addrSrv)); + addrSrv.sin_family = AF_INET; + addrSrv.sin_port = htons(10001); + addrSrv.sin_addr.s_addr = inet_addr(argv[1]); + + int result = connect(fd, reinterpret_cast(&addrSrv), sizeof(addrSrv)); + if (result < 0) { + close(fd); + perror("Not connect client"); + return 2; + } + + ISDKInfo sdkInfo = CreateSDKInfo(); + IHDProtocol proto = CreateProtocol(); + Proto a; + a.proto = proto; + a.info = sdkInfo; + SetProtocolFunc(proto, kSetSendFunc, (void *)SendData); + SetProtocolFunc(proto, kSetSendFuncData, (void *)(intptr_t)(fd)); + SetProtocolFunc(proto, kSetReadXml, (void *)ReadXml); + SetProtocolFunc(proto, kSetReadXmlData, (void *)&a); + + RunProtocol(proto); + + UpdateItem(proto, sdkInfo, kGetEthInfo); + + char buff[1024]; + for (;;) { + int len = read(fd, buff, sizeof(buff)); + if (len <= 0) { + break; + } + + UpdateReadData(proto, buff, len); + if (IsRead > 2) { + break; + } + } + + FreeSDKInfo(sdkInfo); + FreeProtocol(proto); + close(fd); + return 0; +} diff --git a/demo/lightInfo.cpp b/demo/lightInfo.cpp new file mode 100644 index 0000000..0a2f9b9 --- /dev/null +++ b/demo/lightInfo.cpp @@ -0,0 +1,122 @@ + + +#include +#include +#include +#include +#include +#include +#include + +#include "../SDK/SDKInfo.h" + + +using namespace std; + + +struct Proto +{ + IHDProtocol proto; + ISDKInfo info; +}; + +int IsRead = 0; + + +static bool SendData(const char *data, int len, void *userData) { + int fd = (int)(intptr_t)userData; + return write(fd, data, len) > 0; +} + +static void ReadXml(const char *xml, int len, int errorCode, void *userData) { + Proto *info = (Proto *)userData; + ++IsRead; + if (errorCode != 0) { + printf("error code[%d]\n", errorCode); + return ; + } + ParseXml(xml, len, info->info); + + std::cout << "mode:" << GetLightInfoMode(info->info) << "\n" + << "defaultLight:" << GetLightInfoDefaultLight(info->info) << "\n" + << "ploySize:" << GetLightInfoPloySize(info->info) << "\n" + << "ployEnable:" << GetLightInfoPloyEnable(info->info, 0) << "\n" + << "ployPercent:" << GetLightInfoPloyPercent(info->info, 0) << "\n" + << "ployStart:" << GetLightInfoPloyStart(info->info, 0) << "\n" + << "sensorMax:" << GetLightInfoSensorMax(info->info) << "\n" + << "sensorMin:" << GetLightInfoSensorMin(info->info) << "\n" + << "sensorTime:" << GetLightInfoSensorTime(info->info) << "\n" + << std::endl; + + ClearLightInfoPloy(info->info); + std::cout << GetLightInfoPloySize(info->info) << std::endl; + if (IsRead == 1) { + SetLightInfo(info->info, 0, 100); + SetLightInfoSensor(info->info, 0, 100, 5); + AddLightInfoPloy(info->info, HFalse, "12:12:12", 50); + SetLightInfoPloy(info->info, 0, HFalse, "11:11:11", 50); + UpdateItem(info->proto, info->info, kSetLightInfo); + } else { + UpdateItem(info->proto, info->info, kGetLightInfo); + } +} + + +int main(int argc, char *argv[]) +{ + if (argc < 2) { + printf("a.out ip\n"); + return 0; + } + + int fd = socket(AF_INET, SOCK_STREAM, 0); + if (fd < 0) { + perror("create socket faild"); + return 1; + } + + struct sockaddr_in addrSrv; + memset(&addrSrv, 0, sizeof(addrSrv)); + addrSrv.sin_family = AF_INET; + addrSrv.sin_port = htons(10001); + addrSrv.sin_addr.s_addr = inet_addr(argv[1]); + + int result = connect(fd, reinterpret_cast(&addrSrv), sizeof(addrSrv)); + if (result < 0) { + close(fd); + perror("Not connect client"); + return 2; + } + + ISDKInfo sdkInfo = CreateSDKInfo(); + IHDProtocol proto = CreateProtocol(); + Proto a; + a.proto = proto; + a.info = sdkInfo; + SetProtocolFunc(proto, kSetSendFunc, (void *)SendData); + SetProtocolFunc(proto, kSetSendFuncData, (void *)(intptr_t)(fd)); + SetProtocolFunc(proto, kSetReadXml, (void *)ReadXml); + SetProtocolFunc(proto, kSetReadXmlData, (void *)&a); + + RunProtocol(proto); + + UpdateItem(proto, sdkInfo, kGetLightInfo); + + char buff[1024]; + for (;;) { + int len = read(fd, buff, sizeof(buff)); + if (len <= 0) { + break; + } + + UpdateReadData(proto, buff, len); + if (IsRead > 2) { + break; + } + } + + FreeSDKInfo(sdkInfo); + FreeProtocol(proto); + close(fd); + return 0; +} diff --git a/demo/sendFile.cpp b/demo/sendFile.cpp new file mode 100644 index 0000000..c11ff24 --- /dev/null +++ b/demo/sendFile.cpp @@ -0,0 +1,129 @@ + + +#include +#include +#include +#include +#include +#include +#include + +#include "HDSDK.h" + + +using namespace std; + +int IsRead = 0; + + +static bool SendData(const char *data, int len, void *userData) { + int fd = (int)(intptr_t)userData; + return write(fd, data, len) > 0; +} + +static void ReadXml(const char *xml, int len, int errorCode, void *userData) { + (void)len; + (void)userData; + ++IsRead; + if (errorCode != 0) { + printf("error code[%d]\n", errorCode); + return ; + } + printf("====[%s]===\n", xml); +} + +static int SendPngFile(hint64 index, hint64 size, int status, char *buff, int buffSize, void *userData) { + if (status != 0) { + printf("send file faild[%d]\n", status); + return 0; + } + + printf("[%lld][%lld][%f]\r", index, size, 1.0f * index / size); + if (index == size) { + ++IsRead; + printf("\n"); + return 0; + } + + int fd = (int)(intptr_t)userData; + if (lseek(fd, 0, SEEK_CUR) != index) { + lseek(fd, index, SEEK_SET); + } + int len = read(fd, buff, buffSize); + return len; +} + + +int main(int argc, char *argv[]) +{ + if (argc < 2) { + printf("a.out ip\n"); + return 0; + } + + int fileFd = open("./1.png", O_RDONLY); + if (fileFd == -1) { + perror("not open file[1.png]"); + return 1; + } + + int fd = socket(AF_INET, SOCK_STREAM, 0); + if (fd < 0) { + perror("create socket faild"); + return 1; + } + + struct sockaddr_in addrSrv; + memset(&addrSrv, 0, sizeof(addrSrv)); + addrSrv.sin_family = AF_INET; + addrSrv.sin_port = htons(10001); + addrSrv.sin_addr.s_addr = inet_addr(argv[1]); + + int result = connect(fd, reinterpret_cast(&addrSrv), sizeof(addrSrv)); + if (result < 0) { + close(fd); + perror("Not connect client"); + return 2; + } + + IHDProtocol proto = CreateProtocol(); + SetProtocolFunc(proto, kSetSendFunc, (void *)SendData); + SetProtocolFunc(proto, kSetSendFuncData, (void *)(intptr_t)(fd)); + SetProtocolFunc(proto, kSetReadXml, (void *)ReadXml); + + RunProtocol(proto); + + const char *xml = R"( + + +)"; + + const char *getFiles = R"( + + + +)"; + + SendXml(proto, xml, strlen(xml)); + const char *fileName = "test.png"; + SendFile(proto, fileName, strlen(fileName), "6070a9ea174fdae68e8fe89bc5ec7403", 0, 21060215, SendPngFile, (void *)(intptr_t)fileFd); + SendXml(proto, getFiles, strlen(getFiles)); + + char buff[1024]; + for (;;) { + int len = read(fd, buff, sizeof(buff)); + if (len <= 0) { + break; + } + + UpdateReadData(proto, buff, len); + if (IsRead > 4) { + break; + } + } + + FreeProtocol(proto); + close(fileFd); + close(fd); + return 0; +} diff --git a/demo/sendXml.cpp b/demo/sendXml.cpp new file mode 100644 index 0000000..ff1c2bf --- /dev/null +++ b/demo/sendXml.cpp @@ -0,0 +1,102 @@ + + +#include +#include +#include +#include +#include +#include + +#include "HDSDK.h" + + +using namespace std; + +int IsRead = 0; + + +static bool SendData(const char *data, int len, void *userData) { + int fd = (int)(intptr_t)userData; + return write(fd, data, len) > 0; +} + +static void ReadXml(const char *xml, int len, int errorCode, void *userData) { + (void)len; + (void)userData; + ++IsRead; + if (errorCode != 0) { + printf("error code[%d]\n", errorCode); + return ; + } + printf("====[%s]===\n", xml); + + char **p = (char **)(userData); + free(*p); + *p = (char *)malloc(len); + memcpy(*p, xml, len); +} + + +int main(int argc, char *argv[]) +{ + if (argc < 2) { + printf("a.out ip\n"); + return 0; + } + + int fd = socket(AF_INET, SOCK_STREAM, 0); + if (fd < 0) { + perror("create socket faild"); + return 1; + } + + struct sockaddr_in addrSrv; + memset(&addrSrv, 0, sizeof(addrSrv)); + addrSrv.sin_family = AF_INET; + addrSrv.sin_port = htons(10001); + addrSrv.sin_addr.s_addr = inet_addr(argv[1]); + + int result = connect(fd, reinterpret_cast(&addrSrv), sizeof(addrSrv)); + if (result < 0) { + close(fd); + perror("Not connect client"); + return 2; + } + + char *p_buff = NULL; + + IHDProtocol proto = CreateProtocol(); + SetProtocolFunc(proto, kSetSendFunc, (void *)SendData); + SetProtocolFunc(proto, kSetSendFuncData, (void *)(intptr_t)(fd)); + SetProtocolFunc(proto, kSetReadXml, (void *)ReadXml); + SetProtocolFunc(proto, kSetReadXmlData, &p_buff); + + RunProtocol(proto); + + const char *xml = R"( + + +)"; + + SendXml(proto, xml, strlen(xml)); + SendXml(proto, xml, strlen(xml)); + + char buff[1024]; + for (;;) { + int len = read(fd, buff, sizeof(buff)); + if (len <= 0) { + break; + } + + UpdateReadData(proto, buff, len); + if (IsRead > 1) { + break; + } + } + + printf("read xml[\n%s]\n", p_buff); + free(p_buff); + FreeProtocol(proto); + close(fd); + return 0; +} diff --git a/demo/systemVolume.cpp b/demo/systemVolume.cpp new file mode 100644 index 0000000..1407eb0 --- /dev/null +++ b/demo/systemVolume.cpp @@ -0,0 +1,118 @@ + + +#include +#include +#include +#include +#include +#include +#include + +#include "../SDK/SDKInfo.h" + + +using namespace std; + + +struct Proto +{ + IHDProtocol proto; + ISDKInfo info; +}; + +int IsRead = 0; + + +static bool SendData(const char *data, int len, void *userData) { + int fd = (int)(intptr_t)userData; + return write(fd, data, len) > 0; +} + +static void ReadXml(const char *xml, int len, int errorCode, void *userData) { + Proto *info = (Proto *)userData; + ++IsRead; + if (errorCode != 0) { + printf("error code[%d]\n", errorCode); + return ; + } + ParseXml(xml, len, info->info); + + std::cout << "mode:" << GetSystemVolumeInfoMode(info->info) << "\n" + << "volume:" << GetSystemVolumeInfoVolume(info->info) << "\n" + << "ploySize:" << GetSystemVolumeInfoPloySize(info->info) << "\n" + << "ployEnable:" << GetSystemVolumeInfoPloyEnable(info->info, 0) << "\n" + << "ployTime:" << GetSystemVolumeInfoPloyTime(info->info, 0) << "\n" + << "ployVolume:" << GetSystemVolumeInfoPloyVolume(info->info, 0) << "\n" + << std::endl; + + if (IsRead == 1) { + SetSystemVolumeInfo(info->info, 0, 100); + AddSystemVolumeInfoPloy(info->info, HFalse, "11:11:11", 100); + ClearSystemVolumeInfoPloy(info->info); + AddSystemVolumeInfoPloy(info->info, HFalse, "12:12:12", 100); + + UpdateItem(info->proto, info->info, kSetSystemVolumeInfo); + } else { + UpdateItem(info->proto, info->info, kGetSystemVolumeInfo); + } +} + + +int main(int argc, char *argv[]) +{ + if (argc < 2) { + printf("a.out ip\n"); + return 0; + } + + int fd = socket(AF_INET, SOCK_STREAM, 0); + if (fd < 0) { + perror("create socket faild"); + return 1; + } + + struct sockaddr_in addrSrv; + memset(&addrSrv, 0, sizeof(addrSrv)); + addrSrv.sin_family = AF_INET; + addrSrv.sin_port = htons(10001); + addrSrv.sin_addr.s_addr = inet_addr(argv[1]); + + int result = connect(fd, reinterpret_cast(&addrSrv), sizeof(addrSrv)); + if (result < 0) { + close(fd); + perror("Not connect client"); + return 2; + } + + ISDKInfo sdkInfo = CreateSDKInfo(); + IHDProtocol proto = CreateProtocol(); + Proto a; + a.proto = proto; + a.info = sdkInfo; + SetProtocolFunc(proto, kSetSendFunc, (void *)SendData); + SetProtocolFunc(proto, kSetSendFuncData, (void *)(intptr_t)(fd)); + SetProtocolFunc(proto, kSetReadXml, (void *)ReadXml); + SetProtocolFunc(proto, kSetReadXmlData, (void *)&a); + + RunProtocol(proto); + + UpdateItem(proto, sdkInfo, kGetSystemVolumeInfo); + + char buff[1024]; + for (;;) { + int len = read(fd, buff, sizeof(buff)); + if (len <= 0) { + break; + } + + UpdateReadData(proto, buff, len); + if (IsRead > 2) { + break; + } + } + + FreeSDKInfo(sdkInfo); + FreeProtocol(proto); + close(fd); + return 0; +} diff --git a/demo/tcpServer.cpp b/demo/tcpServer.cpp new file mode 100644 index 0000000..ccf98cf --- /dev/null +++ b/demo/tcpServer.cpp @@ -0,0 +1,108 @@ + + +#include +#include +#include +#include +#include +#include +#include + +#include "../SDK/SDKInfo.h" + + +using namespace std; + + +struct Proto +{ + IHDProtocol proto; + ISDKInfo info; +}; + +int IsRead = 0; + + +static bool SendData(const char *data, int len, void *userData) { + int fd = (int)(intptr_t)userData; + return write(fd, data, len) > 0; +} + +static void ReadXml(const char *xml, int len, int errorCode, void *userData) { + Proto *info = (Proto *)userData; + ++IsRead; + if (errorCode != 0) { + printf("error code[%d]\n", errorCode); + return ; + } + ParseXml(xml, len, info->info); + + std::cout << "ip:" << GetTcpServerInfoIp(info->info) << "\n" + << "port:" << GetTcpServerInfoPort(info->info) << "\n" + << std::endl; + + if (IsRead == 1) { +// UpdateItem(info->proto, info->info, kSetTcpServerInfo); + } + UpdateItem(info->proto, info->info, kGetTcpServerInfo); +} + + +int main(int argc, char *argv[]) +{ + if (argc < 2) { + printf("a.out ip\n"); + return 0; + } + + int fd = socket(AF_INET, SOCK_STREAM, 0); + if (fd < 0) { + perror("create socket faild"); + return 1; + } + + struct sockaddr_in addrSrv; + memset(&addrSrv, 0, sizeof(addrSrv)); + addrSrv.sin_family = AF_INET; + addrSrv.sin_port = htons(10001); + addrSrv.sin_addr.s_addr = inet_addr(argv[1]); + + int result = connect(fd, reinterpret_cast(&addrSrv), sizeof(addrSrv)); + if (result < 0) { + close(fd); + perror("Not connect client"); + return 2; + } + + ISDKInfo sdkInfo = CreateSDKInfo(); + IHDProtocol proto = CreateProtocol(); + Proto a; + a.proto = proto; + a.info = sdkInfo; + SetProtocolFunc(proto, kSetSendFunc, (void *)SendData); + SetProtocolFunc(proto, kSetSendFuncData, (void *)(intptr_t)(fd)); + SetProtocolFunc(proto, kSetReadXml, (void *)ReadXml); + SetProtocolFunc(proto, kSetReadXmlData, (void *)&a); + + RunProtocol(proto); + + UpdateItem(proto, sdkInfo, kGetTcpServerInfo); + + char buff[1024]; + for (;;) { + int len = read(fd, buff, sizeof(buff)); + if (len <= 0) { + break; + } + + UpdateReadData(proto, buff, len); + if (IsRead > 2) { + break; + } + } + + FreeSDKInfo(sdkInfo); + FreeProtocol(proto); + close(fd); + return 0; +} diff --git a/demo/time.cpp b/demo/time.cpp new file mode 100644 index 0000000..da42732 --- /dev/null +++ b/demo/time.cpp @@ -0,0 +1,114 @@ + + +#include +#include +#include +#include +#include +#include +#include + +#include "../SDK/SDKInfo.h" + + +using namespace std; + + +struct Proto +{ + IHDProtocol proto; + ISDKInfo info; +}; + +int IsRead = 0; + + +static bool SendData(const char *data, int len, void *userData) { + int fd = (int)(intptr_t)userData; + return write(fd, data, len) > 0; +} + +static void ReadXml(const char *xml, int len, int errorCode, void *userData) { + Proto *info = (Proto *)userData; + ++IsRead; + if (errorCode != 0) { + printf("error code[%d]\n", errorCode); + return ; + } + ParseXml(xml, len, info->info); + + std::cout << "timeZone:" << GetTimeInfoTimeZone(info->info) << "\n" + << "summer:" << GetTimeInfoSummer(info->info) << "\n" + << "sync:" << GetTimeInfoSync(info->info) << "\n" + << "currentTime:" << GetTimeInfoCurrTime(info->info) << "\n" + << "serverList:" << GetTimeInfoServerList(info->info) << "\n" + << std::endl; + + if (IsRead == 1) { + SetTimeInfo(info->info, GetTimeInfoTimeZone(info->info), GetTimeInfoSummer(info->info), "network", "2000-01-01 11:11:11", GetTimeInfoServerList(info->info)); + + UpdateItem(info->proto, info->info, kSetTimeInfo); + } else { + UpdateItem(info->proto, info->info, kGetTimeInfo); + } +} + + +int main(int argc, char *argv[]) +{ + if (argc < 2) { + printf("a.out ip\n"); + return 0; + } + + int fd = socket(AF_INET, SOCK_STREAM, 0); + if (fd < 0) { + perror("create socket faild"); + return 1; + } + + struct sockaddr_in addrSrv; + memset(&addrSrv, 0, sizeof(addrSrv)); + addrSrv.sin_family = AF_INET; + addrSrv.sin_port = htons(10001); + addrSrv.sin_addr.s_addr = inet_addr(argv[1]); + + int result = connect(fd, reinterpret_cast(&addrSrv), sizeof(addrSrv)); + if (result < 0) { + close(fd); + perror("Not connect client"); + return 2; + } + + ISDKInfo sdkInfo = CreateSDKInfo(); + IHDProtocol proto = CreateProtocol(); + Proto a; + a.proto = proto; + a.info = sdkInfo; + SetProtocolFunc(proto, kSetSendFunc, (void *)SendData); + SetProtocolFunc(proto, kSetSendFuncData, (void *)(intptr_t)(fd)); + SetProtocolFunc(proto, kSetReadXml, (void *)ReadXml); + SetProtocolFunc(proto, kSetReadXmlData, (void *)&a); + + RunProtocol(proto); + + UpdateItem(proto, sdkInfo, kGetTimeInfo); + + char buff[1024]; + for (;;) { + int len = read(fd, buff, sizeof(buff)); + if (len <= 0) { + break; + } + + UpdateReadData(proto, buff, len); + if (IsRead > 2) { + break; + } + } + + FreeSDKInfo(sdkInfo); + FreeProtocol(proto); + close(fd); + return 0; +}