Home Database Mysql Tutorial VC++与OPC(pc access)通讯

VC++与OPC(pc access)通讯

Jun 07, 2016 pm 03:43 PM
access Host computer develop want communication

最近做上位机开发,需要与PLC 通讯 。以前不知道以为要与PLC程序配合写 通讯 程序,后来联系西门子客服才知道这个问题早被解决了。网上《OPC_client_在VC环境下编程.doc》比较适合我(适合你的是最好的),表示感谢作者。在这篇的基础上我添加了一下自己的东

最近做上位机开发,需要与PLC通讯。以前不知道以为要与PLC程序配合写通讯程序,后来联系西门子客服才知道这个问题早被解决了。网上《OPC_client_在VC环境下编程.doc》比较适合我(适合你的是最好的),表示感谢作者。在这篇的基础上我添加了一下自己的东西。具体的Demo在http://download.csdn.net/detail/yuanhaosh/8098867下载

在这之前需要添加几个OPC相关的文件 opccomn_i.c ,opccomn.h, opcda.h, opcda_i.c,  opcerror.h,已经包含在demo中了

这部分是初始化OPC的部分。

BOOL COPCDEMODlg::InitOPCServer()
{
    CLSID clsid;
HRESULT hr = S_OK;
CString strServer = "S7200.OPCServer";  //OPC.SimaticNET S7200.OPCServer


/*初始化COM库*/
if (FAILED(::CoInitialize(NULL))) 
{
AfxMessageBox("Error during CoInitialize", MB_OK );
        return FALSE;
}

/*查找OPC服务*/
hr = CLSIDFromProgID( strServer.AllocSysString(), &clsid );
if( FAILED(hr))
{
        AfxMessageBox("Error during CLSIDFromProgID", MB_OK);
        return FALSE;
}

/*创建OPC服务器对象*/
LPUNKNOWN pUnkn = NULL;  
hr = CoCreateInstance(clsid, NULL, CLSCTX_LOCAL_SERVER , IID_IOPCServer, (void**)&m_IOPCServer); //CLSCTX_LOCAL_SERVER CLSCTX_ALL
if( FAILED(hr) || m_IOPCServer == NULL)
{
        AfxMessageBox("Error during CoCreateInstance", MB_OK);
        return FALSE;
}


/*添加组到OPC服务器*/
FLOAT PercentDeadband = 0.0;
DWORD RevisedUpdateRate;
hr = m_IOPCServer->AddGroup(
L"group",                     //[in]  组名
        TRUE,                         //[in]  活动状态
        500,                          //[in]  向服务器发送请求的刷新率
        1,                            //[in]  客户端的操作句柄
        NULL,                         //[in]  与标准时间的校正值
        &PercentDeadband,             //[in]  要舍弃的数据
        0,                            //[in]  服务器使用的语言
        &m_GrpSrvHandle,              //[out] 添加组以后服务器返回的组句柄
        &RevisedUpdateRate,           //[out] 服务器的数据刷新率  
        IID_IOPCItemMgt,              //[in]  添加组的接口类型
        (LPUNKNOWN*)&m_IOPCItemMgt);  //[out] 服务器返回的接口对象指针
if( FAILED(hr) )
{  
LPWSTR pErrString;
        AfxMessageBox("Error during AddGroup", MB_OK);
hr = m_IOPCServer->GetErrorString(hr, LOCALE_SYSTEM_DEFAULT, &pErrString);
if(SUCCEEDED(hr))
{
//输出错误信息
}
else
{
//添加组失败;
}
m_IOPCServer->Release();
m_IOPCServer=NULL;
CoUninitialize();
        return FALSE;
}

Item*  pcItem ;
OPCITEMDEF *m_Items = new OPCITEMDEF[COUNT];                        //项的存取路径, 定义和被请求的数据类等

for(int i = 0; i {
pcItem = new Item;
pcItem->quality = QUAL_BAD;


//pcItem->name = _T("" + TableStr[i]);                             //设置opc节点 Microwin.NewPLC.group.
pcItem->name = _T("Microwin.NewPLC.group.NewItem1");             //这里的字符串填写你的item就行
m_Items[i].szItemID = pcItem->name.AllocSysString();
m_Items[i].dwBlobSize = 0;
m_Items[i].pBlob = NULL;
m_Items[i].bActive = TRUE;
m_Items[i].hClient = (OPCHANDLE)pcItem;
m_Items[i].szAccessPath = pcItem->cAccessPath.AllocSysString();; //pcItem->cAccessPath.AllocSysString();
m_Items[i].vtRequestedDataType = VT_EMPTY;                       //VT_EMPTY;
}


/*添加项目*/ 
    OPCITEMRESULT *pOPCResults = NULL;
HRESULT *pOPCErrors = NULL;
    hr = m_IOPCItemMgt->AddItems(COUNT, 
m_Items,
&pOPCResults, 
&pOPCErrors);
if(FAILED(hr))
{
LPWSTR pErrString;
        AfxMessageBox("Error during AddGroup", MB_OK);
hr = m_IOPCServer->GetErrorString(hr, LOCALE_SYSTEM_DEFAULT, &pErrString);
if(SUCCEEDED(hr))
{

//输出错误信息
}
else
{
//pErrString = "添加组失败.";
}
m_IOPCServer->Release();
m_IOPCServer=NULL;
CoUninitialize();
        return FALSE;
}

/*保存item对应的服务句柄*/
pdwServerHandles = new DWORD[COUNT];
for(i = 0; i {
pdwServerHandles[i] = pOPCResults[i].hServer;
        if(pOPCErrors[i]= S_OK)
{
pdwServerHandles[i] = pOPCResults[i].hServer;  
}
}


/*获取同步IO口*/
hr = m_IOPCItemMgt->QueryInterface(IID_IOPCSyncIO, (void**)&m_IOPCSyncIO);
    if(FAILED(hr))
{
LPWSTR pErrString;
        AfxMessageBox("获取IO口失败", MB_OK);
hr = m_IOPCServer->GetErrorString(hr, LOCALE_SYSTEM_DEFAULT, &pErrString);
if(SUCCEEDED(hr))
{

//输出错误信息
}
else
{
//pErrString = "获取IO口失败.";
}
m_IOPCServer->Release();
m_IOPCServer=NULL;
CoUninitialize();
        return FALSE;
}

// delete[] pdwServerHandles;  会出现异常报错请使用者再次检查原因,防止内存泄露
// delete[] m_Items;
// delete pcItem;
return TRUE; //初始化完成,可以开始查询.
}


/**************************************************************************************************
*  读取OPC服务器中的状态信息
*  phServe:  读取项的句柄 
*  dwSource: 状态获取来源,缓存、内存 
***************************************************************************************************
*/
BOOL COPCDEMODlg::ReadOPCServe(OPCITEMSTATE **pValues, OPCHANDLE *phServe, OPCDATASOURCE dwSource)
{
HRESULT hr = S_OK;
    OPCHANDLE *phserve = phServe;


LPWSTR pErrString; //记录错误信息字符串
HRESULT *pErrors= new HRESULT;


try 
{
hr = m_IOPCSyncIO->Read(
dwSource,               // OPC_DS_CACHE, Source (device or cache)
1,                  // Item count
(OPCHANDLE*)phServe,// Array of server handles for items
pValues,            // Array of values
&pErrors);            // Array of errors
        if(FAILED(hr))
   {   
            AfxMessageBox("Error during ReadOPC", MB_OK);
   hr = m_IOPCServer->GetErrorString(hr, LOCALE_SYSTEM_DEFAULT, &pErrString);
   if(SUCCEEDED(hr))
   {
   //pErrString输出错误信息
   }
   else
   {
   //pErrString = "读取失败.";
   }
   m_IOPCServer->Release();
   m_IOPCServer=NULL;
   CoUninitialize();
            return FALSE;
   }



}
catch(...)
{



//delete pErrors; 会出现异常报错请使用者再次检查原因,防止内存泄露
return  TRUE;
}


/*****************************************************************************************
* 写入OPC服务器中的状态信息
* 后续需要再写 OPCITEMSTATE **pValues, OPCHANDLE *phServe, OPCDATASOURCE dwSource
******************************************************************************************/
BOOL COPCDEMODlg::WriteOPCServe(OPCHANDLE *phServe,  BYTE Values) 
{
HRESULT hr = S_OK;
VARIANT *pItemValues = new VARIANT;
OPCHANDLE *phserve = phServe;
HRESULT *pErrors= new HRESULT;
LPWSTR pErrString;


    VariantClear(pItemValues);
memset(pItemValues, 0, sizeof(VARIANT));
    pItemValues->vt = VT_I2;
short value = Values;
    pItemValues->bVal = value;


try
{
        hr = m_IOPCSyncIO->Write(1,
                               phserve,
                               pItemValues,
                               &pErrors);
if(FAILED(hr))
   {   
   hr = m_IOPCServer->GetErrorString(hr, LOCALE_SYSTEM_DEFAULT, &pErrString);
   if(SUCCEEDED(hr))
   {
   //pErrString输出错误信息
   }
   else
   {
   //pErrString = "写入失败.";
   }
   m_IOPCServer->Release();
   m_IOPCServer=NULL;
   CoUninitialize();
            return FALSE;
   }
}
catch(...)
{} 
//delete pErrors; 会出现异常报错请使用者再次检查原因,防止内存泄露

return TRUE;
}

Copy after login


Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1671
14
PHP Tutorial
1276
29
C# Tutorial
1256
24
How to use sql if statement How to use sql if statement Apr 09, 2025 pm 06:12 PM

SQL IF statements are used to conditionally execute SQL statements, with the syntax as: IF (condition) THEN {statement} ELSE {statement} END IF;. The condition can be any valid SQL expression, and if the condition is true, execute the THEN clause; if the condition is false, execute the ELSE clause. IF statements can be nested, allowing for more complex conditional checks.

How to solve the 'Network Error' caused by Vue Axios across domains How to solve the 'Network Error' caused by Vue Axios across domains Apr 07, 2025 pm 10:27 PM

Methods to solve the cross-domain problem of Vue Axios include: Configuring the CORS header on the server side using the Axios proxy using JSONP using WebSocket using the CORS plug-in

How to configure zend for apache How to configure zend for apache Apr 13, 2025 pm 12:57 PM

How to configure Zend in Apache? The steps to configure Zend Framework in an Apache Web Server are as follows: Install Zend Framework and extract it into the Web Server directory. Create a .htaccess file. Create the Zend application directory and add the index.php file. Configure the Zend application (application.ini). Restart the Apache Web server.

What are the benefits of multithreading in c#? What are the benefits of multithreading in c#? Apr 03, 2025 pm 02:51 PM

The advantage of multithreading is that it can improve performance and resource utilization, especially for processing large amounts of data or performing time-consuming operations. It allows multiple tasks to be performed simultaneously, improving efficiency. However, too many threads can lead to performance degradation, so you need to carefully select the number of threads based on the number of CPU cores and task characteristics. In addition, multi-threaded programming involves challenges such as deadlock and race conditions, which need to be solved using synchronization mechanisms, and requires solid knowledge of concurrent programming, weighing the pros and cons and using them with caution.

Unable to log in to mysql as root Unable to log in to mysql as root Apr 08, 2025 pm 04:54 PM

The main reasons why you cannot log in to MySQL as root are permission problems, configuration file errors, password inconsistent, socket file problems, or firewall interception. The solution includes: check whether the bind-address parameter in the configuration file is configured correctly. Check whether the root user permissions have been modified or deleted and reset. Verify that the password is accurate, including case and special characters. Check socket file permission settings and paths. Check that the firewall blocks connections to the MySQL server.

Summary of phpmyadmin vulnerabilities Summary of phpmyadmin vulnerabilities Apr 10, 2025 pm 10:24 PM

The key to PHPMyAdmin security defense strategy is: 1. Use the latest version of PHPMyAdmin and regularly update PHP and MySQL; 2. Strictly control access rights, use .htaccess or web server access control; 3. Enable strong password and two-factor authentication; 4. Back up the database regularly; 5. Carefully check the configuration files to avoid exposing sensitive information; 6. Use Web Application Firewall (WAF); 7. Carry out security audits. These measures can effectively reduce the security risks caused by PHPMyAdmin due to improper configuration, over-old version or environmental security risks, and ensure the security of the database.

How to monitor Nginx SSL performance on Debian How to monitor Nginx SSL performance on Debian Apr 12, 2025 pm 10:18 PM

This article describes how to effectively monitor the SSL performance of Nginx servers on Debian systems. We will use NginxExporter to export Nginx status data to Prometheus and then visually display it through Grafana. Step 1: Configuring Nginx First, we need to enable the stub_status module in the Nginx configuration file to obtain the status information of Nginx. Add the following snippet in your Nginx configuration file (usually located in /etc/nginx/nginx.conf or its include file): location/nginx_status{stub_status

Using Dicr/Yii2-Google to integrate Google API in YII2 Using Dicr/Yii2-Google to integrate Google API in YII2 Apr 18, 2025 am 11:54 AM

VprocesserazrabotkiveB-enclosed, Мнепришлостольностьсясзадачейтерациигооглапидляпапакробоглесхетсigootrive. LEAVALLYSUMBALLANCEFRIABLANCEFAUMDOPTOMATIFICATION, ČtookazaLovnetakProsto, Kakaožidal.Posenesko

See all articles