我所使用的环境是网络非常不稳定,在用CVI软件编写Opc客户端程序时,希望增加对网络是否正常的判断。目前的现象是当网络正常时,已能实现对Opc服务器数据的正常读取(我不需要修改数据),但网络掉线时,我的程序就死掉了。我在程序中采用定时器读取数据,因网络掉线时导致死机,我曾试图在定时器的启动后立即停止该定时器的再次触发直到数据读取成功,但问题仍然没能解决。
下面附上我的CVI程序部分,请高手帮忙分析,我应如何解决死机问题,谢谢
int ParamNum=7 ; //定义所要读取参数的个数
static char* opcURLs[ParamNum] = {0}; //服务器地址
static DSHandle opcHandles[ParamNum] = {0}; //连接句柄
static DSEnum_Status status[ParamNum];
//回调函数
static void CVICALLBACK OurDSCallback (DSHandle dsHandle, int event,void *callbackData)
{
int im = (int) callbackData;
if (event == DS_EVENT_STATUSUPDATED)
{
// Detect the DataSocket entity that triggered the callback using the callbackData
// and store the current status of the DataSocket entity
if (im < ParamNum)
DS_GetStatus (dsHandle, &status[im]); //获取连接状态
}
}
int main (int argc, char *argv[])
{
...
//联机程序段
for (im = 0; im < ParamNum; im++) //如有连接没断开,系统退出
{
if (status[im] == DSConst_Connecting)
return -1;
}
for (im = 0; im < ParamNum; im++)
{
if (opcHandles[im] != 0) //如有连接存在,则关闭连接
{
hr = DS_DiscardObjHandle (opcHandles[im]);
if (!SUCCEEDED(hr))
{
ShowDataSocketError(hr);
return -1;
}
opcHandles[im] = 0;
status[im] = DSConst_Unconnected;
}
}
sNumTraces = 0; //开始连接
for (im = 0; im < ParamNum; im++)
{
if (opcURLs[im] == NULL)
continue;
//Creates a DataSocket object and connects it to a data source,否则运行失败
hr = DS_Open (opcURLs[im], DSConst_Read, OurDSCallback, (void*)im, &(opcHandles[im]));
if (!SUCCEEDED(hr))
{
ShowDataSocketError(hr);
return -1;
}
sNumTraces++;
}
...
}
//采样时钟
int CVICALLBACK F_MAIN_TIMER3 (int panel, int control, int event,void *callbackData, int eventData1, int eventData2)
{
HRESULT hr = S_OK;
unsigned type;
int i;
unsigned short temp_Ushort[ParamNum]={0};
float Values[ParamNum]={0};
switch (event)
{
case EVENT_TIMER_TICK:
for (i = 0; i < sNumTraces; i++)
{
// Get the updated data from the OPC Items if they are active, else return
if (opcHandles[i] != 0 && status[i] == DSConst_ConnectionActive)
{
hr = DS_Update (opcHandles[i]);
if (!SUCCEEDED(hr))
{
ShowDataSocketError(hr);
return -1;
}
hr = DS_GetDataType (opcHandles[i], &type, NULL, NULL);
if (!SUCCEEDED(hr))
{
ShowDataSocketError(hr);
return -1;
}
switch(type)
{
case CAVT_USHORT:
hr = DS_GetDataValue (opcHandles[i], CAVT_USHORT, &(temp_Ushort[i]), 1, NULL, NULL);
if (!SUCCEEDED(hr))
{
ShowDataSocketError(hr);
return -1;
}
break;
default:continue;
}
}
break;
}
...
return 0;
}