Files
energy_storage/src/app/Device.cpp
2025-08-26 18:36:25 +08:00

121 lines
3.2 KiB
C++
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#include "Device.h"
#include "common/Logger.h"
#include "common/Utils.h"
#include "protocol/Communicator.h"
#include "common/JsonN.h"
//int DeviceEntity::getAttrInt(std::string key)
//{
// auto iter = mapAttrs.find(key);
// if (iter == mapAttrs.end()) { return 0; }
// return Utils::toInt(iter->second);
//}
//
//float DeviceEntity::getAttrFloat(std::string key)
//{
// auto iter = mapAttrs.find(key);
// if (iter == mapAttrs.end()) { return 0.0f; }
// return Utils::toFloat(iter->second);
//}
//
//double DeviceEntity::getAttrDouble(std::string key)
//{
// auto iter = mapAttrs.find(key);
// if (iter == mapAttrs.end()) { return 0.0; }
// return Utils::toDouble(iter->second);
//}
//
//std::string DeviceEntity::getAttrStr(std::string key)
//{
// auto iter = mapAttrs.find(key);
// if (iter == mapAttrs.end()) { return ""; }
// return iter->second;
//}
int Device::startComm()
{
if (!isOpen)
{
if (commEntity && commEntity->isAlive())
{
commEntity->close();
}
return 0;
}
// 从属性列表中获取通讯方式和通讯地址、端口
std::string commType = attrs.value("commType");
// 如果entity的通讯协议类型当前配置不一致需要关闭连接删除通讯后创建新的通讯
if (commEntity && commEntity->type != commType)
{
commEntity->close();
commEntity = nullptr;
}
// 创建新的通讯
if (!commEntity)
{
commEntity = Communicator::createEntity(attrs);
if (!commEntity) { return -1; }
}
commEntity->start();
return 0;
}
std::shared_ptr<Device> Device::create(Fields& fields)
{
auto device = std::make_shared<Device>();
device->deviceId = fields.get<int>("device_id");
device->type = fields.get<int>("type");
device->name = fields.value("name");
device->code = fields.value("code");
device->isOpen = fields.get<int>("is_open");
device->attrsJson = fields.value("attrs");
// 解析属性的JSON字符串转换成键值对
NJsonNode jsonroot;
bool ret = NJson::parse(device->attrsJson, jsonroot);
if (!ret) // 解析错误
{
XLOGE() << "device attr json parse error, device_id=" << device->deviceId;
}
else
{
for (auto& [key, val] : jsonroot.items()) {
std::string valType = val.type_name();
if (valType == "string") {
device->attrs.set(key, val.get<std::string>());
}
else if (valType == "number") {
device->attrs.set(key, val.get<int>());
}
else {
XLOGE() << key << ": [" << valType << "]";
}
}
}
// 启动通讯该函数中会自动判断isOpen状态选择是否进行通讯连接
device->startComm();
return device;
}
//
//std::vector<std::shared_ptr<DeviceEntity>> Device::getDeviceByType(int type)
//{
// std::vector<std::shared_ptr<DeviceEntity>> vecDevice;
// for (auto iter = mapDevices.begin(); iter!=mapDevices.end(); ++iter)
// {
// auto device = iter->second;
// if (device && (type<=0 || device->type == type))
// {
// vecDevice.push_back(device);
// }
// }
// return vecDevice;
//}