Knowledge Base Nr: 00056 s7blockopc.cpp - http://www.swe-kaiser.de

Downloads: BeispielprogrammOPC C++-Klasse

OPC: siemens s7 blockbefehle verarbeiten (safearrays)

  
BOOL CMyOPCClient::ReadData(CItem& cItem, unsigned char ucData[], int& nSize)
{
long lBound = 0;
long uBound = 0;

HRESULT hr;

SAFEARRAY* psa = cItem.m_varValue.parray;

hr = SafeArrayGetLBound(psa, 1, &lBound);
if(FAILED(hr))
{
sprintf(g_szLog, "ERROR: Daten können nicht gelesen werden (falsches S7 Format - SafeArrayGetLBound() failed)!\n");
DoLog(g_szLog);
return FALSE;
}

hr = SafeArrayGetUBound(psa, 1, &uBound);
if(FAILED(hr))
{
sprintf(g_szLog, "ERROR: Daten können nicht gelesen werden (falsches S7 Format - SafeArrayGetUBound() failed)!\n");
DoLog(g_szLog);
return FALSE;
}

VARIANT var;
VariantInit(&var);
VariantChangeType(&var, &var, 0, VT_UI1);

for(long i = lBound; i <= uBound; ++i)
{
long index = i;
unsigned char byte = 0;

hr = SafeArrayGetElement(psa, &index, &byte);
if(FAILED(hr))
{
sprintf(g_szLog, "ERROR: Daten können nicht gelesen werden (falsches S7 Format - SafeArrayGetElement() failed)!\n");
DoLog(g_szLog);
return FALSE;
}

ucData[i] = byte;
}

nSize = uBound;
return TRUE;
}

BOOL CMyOPCClient::SendeUhrzeit()
{
SAFEARRAYBOUND rgsabound[1];
rgsabound[0].lLbound = 0;
rgsabound[0].cElements = 8;

SAFEARRAY* psa = SafeArrayCreate(VT_UI1, 1, rgsabound);
if(psa == NULL)
{
sprintf(g_szLog, "ERROR: SendeUhrzeit() SAFEARRAY kann nicht angelegt werden!\n");
DoLog(g_szLog);
}

long ix = 0;
unsigned char byte = 0;

time_t now;
time(&now);
struct tm *nowtime = localtime( &now );

ix = 0; byte = nowtime->tm_year - 100; //jahr
SafeArrayPutElement(psa, &ix, &byte);
ix = 1; byte = nowtime->tm_mon + 1; //monat
SafeArrayPutElement(psa, &ix, &byte);
ix = 2; byte = nowtime->tm_mday; //tag
SafeArrayPutElement(psa, &ix, &byte);
ix = 3; byte = nowtime->tm_hour; //stunde
SafeArrayPutElement(psa, &ix, &byte);
ix = 4; byte = nowtime->tm_min; //minute
SafeArrayPutElement(psa, &ix, &byte);
ix = 5; byte = nowtime->tm_sec; //sekunde
SafeArrayPutElement(psa, &ix, &byte);
ix = 6; byte = 0; //msec high
SafeArrayPutElement(psa, &ix, &byte);
ix = 7; byte = 0; //msec low
SafeArrayPutElement(psa, &ix, &byte);

CItem cItem;

cItem.m_strName = ITEM_DB10;
cItem.m_varValue = (long)0;
cItem.m_varValue.vt = VT_ARRAY|VT_UI1;
cItem.m_varValue.parray = psa;

BOOL bSucc = WriteItem(VALUEGROUPNAME, cItem);

return bSucc;
}