qt访问OPC服务端读数据的代码
时间: 2023-06-20 14:10:27 浏览: 142
QT实现的OPC客户端源码
3星 · 编辑精心推荐
以下是使用Qt访问OPC服务端读取数据的示例代码:
```cpp
#include <QCoreApplication>
#include <opcda.h>
#include <QDebug>
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
// 初始化COM库
CoInitialize(NULL);
// 创建OPC服务器对象
CLSID clsid;
HRESULT hr = CLSIDFromProgID(L"OPC.SimaticNET", &clsid);
if (FAILED(hr)) {
qDebug() << "Failed to get CLSID for OPC server";
return -1;
}
IID iid;
hr = IIDFromString(L"{B8C9B8A1-EDC8-11D1-85DB-080009A0C907}", &iid);
if (FAILED(hr)) {
qDebug() << "Failed to get IID for IOPCServer";
return -1;
}
IUnknown* pUnk = NULL;
hr = CoCreateInstance(clsid, NULL, CLSCTX_SERVER, iid, (LPVOID*)&pUnk);
if (FAILED(hr)) {
qDebug() << "Failed to create OPC server instance";
return -1;
}
IOPCServer* pServer = NULL;
hr = pUnk->QueryInterface(IID_IOPCServer, (LPVOID*)&pServer);
if (FAILED(hr)) {
qDebug() << "Failed to get IOPCServer interface";
return -1;
}
// 连接OPC服务端
DWORD dwAuthnLevel = RPC_C_AUTHN_LEVEL_NONE;
DWORD dwImpLevel = RPC_C_IMP_LEVEL_IMPERSONATE;
WCHAR* pszServerName = L"localhost";
WCHAR* pszClientName = L"";
WCHAR* pszUser = L"";
WCHAR* pszPassword = L"";
hr = pServer->AddGroup(L"TestGroup", TRUE, 1000, 0, NULL, NULL, dwAuthnLevel, dwImpLevel, NULL, 0, &m_hGroup, &m_hServerRate, &iid, (LPVOID*)&m_pGroup);
if (FAILED(hr)) {
qDebug() << "Failed to add group";
return -1;
}
// 读取数据
DWORD dwCount = 2;
DWORD* phServer = new DWORD[dwCount];
LPWSTR* pszItemID = new LPWSTR[dwCount];
pszItemID[0] = L"Channel1.Device1.Tag1";
pszItemID[1] = L"Channel1.Device1.Tag2";
hr = m_pGroup->AddItems(dwCount, pszItemID, NULL, phServer, NULL, NULL, NULL, &iid, NULL);
if (FAILED(hr)) {
qDebug() << "Failed to add items to group";
return -1;
}
OPCITEMSTATE* pItemState = NULL;
hr = m_pGroup->Read(OPC_DS_DEVICE, dwCount, phServer, &pItemState, NULL, NULL);
if (FAILED(hr)) {
qDebug() << "Failed to read items from group";
return -1;
}
for (DWORD i = 0; i < dwCount; i++) {
qDebug() << "Item ID:" << QString::fromWCharArray(pszItemID[i]) << "Value:" << pItemState[i].vDataValue.dblVal;
}
// 释放资源
if (pItemState) {
CoTaskMemFree(pItemState);
}
delete[] phServer;
delete[] pszItemID;
if (m_pGroup) {
m_pGroup->Release();
}
if (m_hGroup) {
pServer->RemoveGroup(m_hGroup, TRUE);
}
if (pServer) {
pServer->Release();
}
CoUninitialize();
return a.exec();
}
```
需要注意的是,代码中使用了OPC.SimaticNET作为OPC服务端的ProgID,如果你使用的是其他OPC服务端,需要替换该值。另外,代码中也使用了Simatic S7-1200 PLC作为OPC服务端,读取了两个Tag的值,如果你需要读取其他Tag的值,需要替换pszItemID数组中的值。
阅读全文