96 lines
2.0 KiB
C++
96 lines
2.0 KiB
C++
#include "XNDDSInterface.h"
|
|
#include "XNObject_p.h"
|
|
#include <nlohmann/json.hpp>
|
|
|
|
using json = nlohmann::json;
|
|
|
|
XNByteArray XNDDSInterface::getUDPPackage()
|
|
{
|
|
XNByteArray result;
|
|
|
|
size_t currentPos = 0;
|
|
|
|
// 复制头部
|
|
result.append(header, headerSize);
|
|
currentPos = headerSize;
|
|
|
|
// 复制数据
|
|
for (auto func : getByteArrayFunction) {
|
|
if (currentPos + func.size <= MAX_UDP_PACKET_SIZE) {
|
|
result.append(func.func());
|
|
currentPos += func.size;
|
|
} else {
|
|
break; // 超出最大包大小
|
|
}
|
|
}
|
|
|
|
// 更新包大小
|
|
if (currentPos >= 8 && currentPos < MAX_UDP_PACKET_SIZE) {
|
|
result[6] = static_cast<uint8_t>((currentPos >> 8) & 0xFF);
|
|
result[7] = static_cast<uint8_t>(currentPos & 0xFF);
|
|
}
|
|
|
|
return result;
|
|
}
|
|
|
|
void XNDDSInterface::setDataByUDPPackage(const XNByteArray &package)
|
|
{
|
|
clearOutData();
|
|
if (package.size() < headerSize) {
|
|
return;
|
|
}
|
|
|
|
// 获取包大小
|
|
uint16_t packageSize = (package[6] << 8) | package[7];
|
|
if (packageSize > MAX_UDP_PACKET_SIZE) {
|
|
return;
|
|
}
|
|
|
|
size_t currentPos = 8;
|
|
|
|
// 获取数据
|
|
for (auto func : setByteArrayFunction) {
|
|
if (currentPos + func.second.size <= packageSize) {
|
|
XNByteArray byteArray(func.second.size);
|
|
for (size_t i = 0; i < func.second.size; i++) {
|
|
byteArray[i] = package[currentPos + i];
|
|
}
|
|
func.second.func(byteArray);
|
|
currentPos += func.second.size;
|
|
} else {
|
|
break;
|
|
}
|
|
}
|
|
sendOutData();
|
|
}
|
|
|
|
std::unordered_map<std::string, std::string>
|
|
XNDDSInterface::getStringData(std::vector<std::string> varNames)
|
|
{
|
|
std::unordered_map<std::string, std::string> result;
|
|
|
|
std::lock_guard<std::mutex> lock(mutex);
|
|
for (const auto &varName : varNames) {
|
|
auto it = getDataFunction.find(varName);
|
|
if (it == getDataFunction.end()) {
|
|
continue;
|
|
}
|
|
result[varName] = it->second();
|
|
}
|
|
|
|
return result;
|
|
}
|
|
|
|
void XNDDSInterface::setDataByString(std::unordered_map<std::string, std::string> data)
|
|
{
|
|
clearOutData();
|
|
for (const auto &[varName, value] : data) {
|
|
auto it = setDataFunction.find(varName);
|
|
if (it == setDataFunction.end()) {
|
|
continue;
|
|
}
|
|
it->second(value);
|
|
}
|
|
sendOutData();
|
|
}
|