90 lines
2.8 KiB
C++
90 lines
2.8 KiB
C++
#ifndef OPCUAMANAGER_H
|
||
#define OPCUAMANAGER_H
|
||
|
||
#include <QObject>
|
||
#include <QOpcUaClient>
|
||
#include <QOpcUaNode>
|
||
#include <QOpcUaEndpointDescription>
|
||
#include <QVector>
|
||
#include <QUrl>
|
||
#include <QTimer>
|
||
class OpcUaManager : public QObject
|
||
{
|
||
Q_OBJECT
|
||
public:
|
||
explicit OpcUaManager(QObject *parent = nullptr);
|
||
~OpcUaManager();
|
||
|
||
// 连接服务器
|
||
bool connectToServer(const QString &url, const QString &username, const QString &password);
|
||
// 断开连接
|
||
void disconnectFromServer();
|
||
// 读取节点值
|
||
bool readNodeValue(const QString &nodeId);
|
||
// 写入节点值
|
||
bool writeNodeValue(const QString &nodeId, const QVariant &value);
|
||
// 获取连接状态
|
||
QOpcUaClient::ClientState connectionState() const;
|
||
|
||
signals:
|
||
// 状态变化信号
|
||
void stateChanged(QOpcUaClient::ClientState state);
|
||
// 读取完成信号(返回值和节点ID)
|
||
void readCompleted(const QVariant &value, const QString &nodeId);
|
||
// 写入完成信号(返回是否成功和节点ID)
|
||
void writeCompleted(bool success, const QString &nodeId);
|
||
// 错误信号(返回错误信息)
|
||
void errorOccurred(const QString &errorString);
|
||
void reconnected(); // 新增:重连成功后广播
|
||
private slots:
|
||
// 端点请求完成处理
|
||
void onEndpointsRequestFinished(QVector<QOpcUaEndpointDescription> endpoints,
|
||
QOpcUa::UaStatusCode statusCode,
|
||
QUrl requestedUrl);
|
||
// 客户端状态变化处理
|
||
void onClientStateChanged(QOpcUaClient::ClientState state);
|
||
// 属性读取完成处理(用于普通读取)
|
||
void onAttributeRead(QOpcUa::NodeAttributes attrs);
|
||
// 属性写入完成处理
|
||
void onAttributeWritten(QOpcUa::NodeAttribute attribute, QOpcUa::UaStatusCode statusCode);
|
||
// 写入前读取值类型(用于动态类型适配)
|
||
void onPreWriteValueTypeRead(QOpcUa::NodeAttributes attrs);
|
||
|
||
void tryReconnect(); // 新增:真正执行重连
|
||
private:
|
||
// 创建客户端实例
|
||
void createClient();
|
||
|
||
/** @brief OPC UA客户端实例 */
|
||
QOpcUaClient *mClient;
|
||
|
||
/** @brief 当前操作的节点 */
|
||
QOpcUaNode *mCurrentNode;
|
||
|
||
/** @brief 当前节点ID */
|
||
QString mCurrentNodeId;
|
||
|
||
/** @brief 服务器地址 */
|
||
QUrl mServerUrl;
|
||
|
||
/** @brief 登录用户名 */
|
||
QString mUserName;
|
||
|
||
/** @brief 登录密码 */
|
||
QString mPassword;
|
||
|
||
/** @brief 节点数据类型(备用) */
|
||
int mNodeDataType;
|
||
|
||
/** @brief 待写入的值(临时存储) */
|
||
QVariant mPendingWriteValue;
|
||
|
||
/** @brief 重连定时器 */
|
||
QTimer *mReconnectTimer = nullptr;
|
||
|
||
/** @brief 每次重连的时间间隔 */
|
||
const int RECONNECT_INTERVAL = 3000; //
|
||
};
|
||
|
||
#endif // OPCUAMANAGER_H
|