diff --git a/LocalSyncWrapper/LocalSyncOPCCLient.cpp b/LocalSyncWrapper/LocalSyncOPCCLient.cpp index a24cd3f..7d767bc 100644 --- a/LocalSyncWrapper/LocalSyncOPCCLient.cpp +++ b/LocalSyncWrapper/LocalSyncOPCCLient.cpp @@ -39,7 +39,9 @@ bool LocalSyncOPCCLient::Connect(std::string serverName) { // check if opc service runing if (!DetectService("OpcEnum")) + { return false; + } is_env_ready = true; // create local host @@ -55,7 +57,9 @@ bool LocalSyncOPCCLient::Connect(std::string serverName) std::vector localServerList; p_host_->getListOfDAServers(IID_CATID_OPCDAServer20, localServerList, localClassIdList); if (!localServerList.size()) + { return false; + } p_opc_server_ = p_host_->connectDAServer(COPCHost::S2WS(serverName)); std::vector item_name_vector; @@ -67,11 +71,13 @@ bool LocalSyncOPCCLient::Connect(std::string serverName) // add items int item_index = 0; for (unsigned int i = 0; i < item_name_vector.size(); ++i) + { if (ItemNameFilter(COPCHost::WS2S(item_name_vector[i]))) { name_item_map_[item_name_vector[i]] = p_group_->addItem(item_name_vector[i], true); ++item_index; - } // if + } + } // if if (!IsConnected()) { @@ -87,11 +93,15 @@ bool LocalSyncOPCCLient::Connect(std::string serverName) bool LocalSyncOPCCLient::IsConnected() { if (!is_env_ready) + { return false; + } // check is opc server runing if (IsOPCRuning() && IsOPCConnectedPLC()) + { return true; + } return false; @@ -100,7 +110,9 @@ bool LocalSyncOPCCLient::IsConnected() bool LocalSyncOPCCLient::DisConnect() { if (!is_env_ready) + { return true; + } CleanOPCMember(); return true; @@ -110,12 +122,16 @@ bool LocalSyncOPCCLient::DisConnect() bool LocalSyncOPCCLient::IsOPCRuning() { if (!p_opc_server_) + { return false; + } ServerStatus status = {0}; p_opc_server_->getStatus(status); if (status.dwServerState != OPC_STATUS_RUNNING) + { return false; + } return true; @@ -241,7 +257,9 @@ bool LocalSyncOPCCLient::ReadUint16Array(std::string item_name, uint16_t *item_v uint16_t *buf; SafeArrayAccessData(array_variant.parray, (void **)&buf); for (int i = 0; i < array_size; ++i) + { item_value_array[i] = buf[i]; + } SafeArrayUnaccessData(array_variant.parray); VariantClear(&array_variant); @@ -263,7 +281,9 @@ bool LocalSyncOPCCLient::WriteUint16Array(std::string item_name, uint16_t *item_ uint16_t *buf; SafeArrayAccessData(array_variant.parray, (void **)&buf); for (int i = 0; i < array_size; ++i) + { buf[i] = item_value_array[i]; + } SafeArrayUnaccessData(array_variant.parray); // write variant @@ -278,7 +298,9 @@ bool LocalSyncOPCCLient::CleanOPCMember() if (IsOPCRuning()) // delete heap if connected { for (auto iter = name_item_map_.begin(); iter != name_item_map_.end(); ++iter) + { delete iter->second; + } name_item_map_.clear(); diff --git a/OPCClientDemo/OPCClientDemo.cpp b/OPCClientDemo/OPCClientDemo.cpp index ec63607..5982bee 100644 --- a/OPCClientDemo/OPCClientDemo.cpp +++ b/OPCClientDemo/OPCClientDemo.cpp @@ -64,8 +64,10 @@ class CMyCallback : public IAsyncDataCallback const COPCItem *item = data->item(); // retrieve original item pointer from item data.. if (item) + { printf("-----> '%ws', handle: %u, changed async read quality %d value %d\n", item->getName().c_str(), handle, data->wQuality, data->vDataValue.iVal); + } } // if } // while @@ -118,15 +120,16 @@ void main(void) { COPCClient::init(); - printf( - "input hostname (warning: NOT an IP address, use such as: 'Jhon-PC' or 'localhost' / ):\n"); // See - // readme - // to find - // reason + printf("input hostname (warning: NOT an IP address, use such as: 'Jhon-PC' or 'localhost' / ):\n"); // See + // readme + // to find + // reason char c_string[100] = {0}; gets_s(c_string); if (!strlen(c_string)) + { strcpy_s(c_string, sizeof(c_string), "localhost"); + } COPCHost *host = COPCClient::makeHost(COPCHost::S2WS(c_string)); // list servers @@ -140,14 +143,18 @@ void main(void) { printf("%d: '%ws'\n", i, localServerList[i].c_str()); if (localServerList[i] == L"Matrikon.OPC.Simulation.1") + { server_id = i; + } } // for // connect to OPC printf("\nselect server ID or for Matrikon:\n"); gets_s(c_string); if (strlen(c_string)) + { server_id = atol(c_string); + } std::wstring serverName = localServerList[server_id]; printf("server name: '%ws'\n", serverName.c_str()); COPCServer *opcServer = host->connectDAServer(serverName); @@ -168,7 +175,9 @@ void main(void) opcServer->getItemNames(opcItemNames); printf("\n\ngot %d names:\n", static_cast(opcItemNames.size())); for (unsigned i = 0; i < opcItemNames.size(); ++i) + { printf("%3d: '%ws'\n", i + 1, opcItemNames[i].c_str()); + } // make demo group unsigned long refreshRate; @@ -186,21 +195,28 @@ void main(void) itemNames.push_back(opcItemNames[21]); // 15 -> Bucket Brigade.UInt2 itemNames.push_back(opcItemNames[22]); // 16 -> Bucket Brigade.UInt4 if (demoGroup->addItems(itemNames, itemsCreated, errors, true) != 0) + { printf("add items to group FAILED\n"); + } // get properties std::vector propDesc; readWritableItem->getSupportedProperties(propDesc); printf("supported properties for '%ws'\n", readWritableItem->getName().c_str()); for (unsigned i = 0; i < propDesc.size(); ++i) + { printf("%3d: ID = %u, description = '%ws', type = %d\n", i, propDesc[i].id, propDesc[i].desc.c_str(), propDesc[i].type); + } CAutoPtrArray propVals; readWritableItem->getProperties(propDesc, propVals); for (unsigned i = 0; i < propDesc.size(); ++i) + { if (!propVals[i]) + { printf("FAILED to get property %u\n", propDesc[i].id); + } else { printf("Property %u=", propDesc[i].id); @@ -229,7 +245,8 @@ void main(void) printf("\n"); break; } // switch - } // else + } + } // else // sync read of item OPCItemData data; diff --git a/OPCClientToolKit/OPCClient.cpp b/OPCClientToolKit/OPCClient.cpp index c668d57..3dcb71f 100644 --- a/OPCClientToolKit/OPCClient.cpp +++ b/OPCClientToolKit/OPCClient.cpp @@ -41,12 +41,18 @@ bool COPCClient::init(OPCOLEInitMode mode) { HRESULT result = -1; if (mode == APARTMENTTHREADED) + { result = CoInitialize(nullptr); + } if (mode == MULTITHREADED) + { result = CoInitializeEx(nullptr, COINIT_MULTITHREADED); + } if (FAILED(result)) + { throw OPCException(L"COPCClient::init: CoInitialize failed"); + } CoInitializeSecurity(nullptr, -1, nullptr, nullptr, RPC_C_AUTHN_LEVEL_NONE, RPC_C_IMP_LEVEL_IMPERSONATE, nullptr, EOAC_NONE, nullptr); @@ -55,7 +61,9 @@ bool COPCClient::init(OPCOLEInitMode mode) { result = CoGetMalloc(MEMCTX_TASK, &iMalloc); if (FAILED(result)) + { throw OPCException(L"COPCClient::init: CoGetMalloc FAILED"); + } } // if ++ReleaseCount; @@ -66,7 +74,9 @@ bool COPCClient::init(OPCOLEInitMode mode) void COPCClient::stop() { if (--ReleaseCount <= 0) + { iMalloc.Release(); + } CoUninitialize(); @@ -90,7 +100,9 @@ void COPCClient::comFreeVariant(VARIANT *memory, unsigned size) COPCHost *COPCClient::makeHost(const std::wstring &hostName) { if (!hostName.size() || (hostName == L"localhost") || (hostName == L"127.0.0.1")) + { return new CLocalHost(); + } return new CRemoteHost(hostName); diff --git a/OPCClientToolKit/OPCGroup.cpp b/OPCClientToolKit/OPCGroup.cpp index fb85d01..5cf7eab 100644 --- a/OPCClientToolKit/OPCGroup.cpp +++ b/OPCClientToolKit/OPCGroup.cpp @@ -56,12 +56,19 @@ class CAsyncDataCallback : public IOPCDataCallback STDMETHODIMP QueryInterface(REFIID iid, LPVOID *ppInterface) { if (!ppInterface) + { return E_INVALIDARG; + } if (iid == IID_IUnknown) - *ppInterface = (IUnknown *)this; + { + *ppInterface = (IUnknown *) + } + this; else if (iid == IID_IOPCDataCallback) + { *ppInterface = (IOPCDataCallback *)this; + } else { *ppInterface = nullptr; @@ -88,7 +95,9 @@ class CAsyncDataCallback : public IOPCDataCallback DWORD count = ReferenceCount ? --ReferenceCount : 0; if (!count) + { delete this; + } return count; @@ -120,7 +129,9 @@ class CAsyncDataCallback : public IOPCDataCallback } // if else + { throw OPCException(L"CAsyncDataCallback::OnDataChange: FAILED to lookup transaction ID in map"); + } } // if if (usrHandler) @@ -168,10 +179,11 @@ class CAsyncDataCallback : public IOPCDataCallback for (unsigned i = 0; i < count; ++i) { OPCItemData *data = nullptr; - if (transaction->getItemDataMap().Lookup(clientHandles[i], data) && - data) // look up adjoining OPC data in map.. - transaction->setItemError(data->item(), errors[i]); // this records error state - may be good - } // for + if (transaction->getItemDataMap().Lookup(clientHandles[i], data) && data) + { // look up adjoining OPC data in map.. + transaction->setItemError(data->item(), errors[i]); + } // this records error state - may be good + } // for transaction->setCompleted(); } // if return S_OK; @@ -193,9 +205,13 @@ class CAsyncDataCallback : public IOPCDataCallback { OPCItemData *data = nullptr; if (FAILED(error)) + { data = new OPCItemData(item, error); + } else + { data = new OPCItemData(item, value, quality, time, error); + } return data; } // makeOPCDataItem @@ -218,16 +234,21 @@ class CAsyncDataCallback : public IOPCDataCallback OPCItemData *data = makeOPCDataItem(values[i], quality[i], time[i], errors[i], item); // make data item.. if (!pair) + { itemDataMap.SetAt(clientHandles[i], data); // create new item in OPC data map, but without valid OPC item pointer ! + } else - itemDataMap.SetValueAt(pair, - data); // update existing item in OPC data map with new OPC data item.. - } // if + { + itemDataMap.SetValueAt(pair, data); + } // update existing item in OPC data map with new OPC data item.. + } // if else - pair->m_value->set(values[i], quality[i], time[i], errors[i]); // just set values of existing item.. - } // for + { + pair->m_value->set(values[i], quality[i], time[i], errors[i]); + } // just set values of existing item.. + } // for } // updateOPCData @@ -241,19 +262,27 @@ COPCGroup::COPCGroup(const std::wstring &groupName, bool active, unsigned long r &deadBand, 0, &GroupHandle, &revisedUpdateRate_ms, IID_IOPCGroupStateMgt, (LPUNKNOWN *)&iStateManagement); if (FAILED(result)) + { throw OPCException(L"COPCGroup::COPCGroup: FAILED to Add group"); + } result = iStateManagement->QueryInterface(IID_IOPCSyncIO, (void **)&iSyncIO); if (FAILED(result)) + { throw OPCException(L"COPCGroup::COPCGroup: FAILED to get IID_IOPCSyncIO"); + } result = iStateManagement->QueryInterface(IID_IOPCAsyncIO2, (void **)&iAsync2IO); if (FAILED(result)) + { throw OPCException(L"COPCGroup::COPCGroup: FAILED to get IID_IOPCAsyncIO2"); + } result = iStateManagement->QueryInterface(IID_IOPCItemMgt, (void **)&iItemManagement); if (FAILED(result)) + { throw OPCException(L"COPCGroup::COPCGroup: FAILED to get IID_IOPCItemMgt"); + } } // COPCGroup::COPCGroup @@ -302,9 +331,13 @@ void COPCGroup::readSync(std::vector &items, COPCItemDataMap &itemDa states[i].ftTimeStamp, results[i], items[i]); COPCItemDataMap::CPair *pair = itemDataMap.Lookup(handle); if (!pair) + { itemDataMap.SetAt(handle, data); + } else + { itemDataMap.SetValueAt(pair, data); + } } // for delete[] handles; @@ -333,11 +366,13 @@ CTransaction *COPCGroup::readAsync(std::vector &items, ITransactionC transaction->setCancelId(cancelID); unsigned failCount = 0; for (unsigned i = 0; i < nbrItems; ++i) + { if (FAILED(results[i])) { transaction->setItemError(items[i], results[i]); ++failCount; - } // if + } + } // if if (failCount == items.size()) transaction->setCompleted(); // if all items return error then no callback will occur. p 101 @@ -368,15 +403,21 @@ CTransaction *COPCGroup::refresh(OPCDATASOURCE source, ITransactionComplete *tra bool COPCGroup::cancelRefresh(CTransaction *&transaction) { if (!transaction) + { return false; + } DWORD cancelID = transaction->getCancelId(); if (!deleteTransaction(transaction)) + { return false; + } HRESULT result = iAsync2IO->Cancel2(cancelID); - if (FAILED(result) && (result != E_FAIL)) // 0x80004005L "Unspecified error", just return if this happened.. + if (FAILED(result) && (result != E_FAIL)) + { // 0x80004005L "Unspecified error", just return if this happened.. throw OPCException(L"COPCGroup::cancelRefresh: cancel async refresh FAILED"); + } return !FAILED(result); @@ -389,7 +430,9 @@ COPCItem *COPCGroup::addItem(std::wstring &name, bool active) std::vector names; names.push_back(name); if (addItems(names, items, errors, active) != 0) + { throw OPCException(L"COPCGroup::addItem: FAILED to add item"); + } return items[0]; @@ -423,16 +466,22 @@ int COPCGroup::addItems(std::vector &names, std::vectorAddItems(nbrItems, itemDef, &details, &results); delete[] itemDef; for (unsigned i = 0; i < names.size(); ++i) + { delete nameVector[i]; + } if (FAILED(result)) + { throw OPCException(L"COPCGroup::addItems: FAILED to add items"); + } int errorCount = 0; for (unsigned i = 0; i < nbrItems; ++i) { if (details[i].pBlob) + { COPCClient::comFree(details[0].pBlob); + } if (FAILED(results[i])) { @@ -469,7 +518,9 @@ bool COPCGroup::lookupOpcItem(OPCHANDLE handle, COPCItem *&item) bool result = false; OPCItemData *itemData = nullptr; if ((result = GroupItemDataMap.Lookup(handle, itemData)) && itemData) + { item = itemData->item(); + } return result; } // COPCGroup::lookupOpcItem @@ -478,7 +529,9 @@ DWORD COPCGroup::addTransaction(CTransaction *transaction) { DWORD transactionID = getTransactionID(transaction); if (transactionID) + { TransactionMap.SetAt(transactionID, transaction); + } return transactionID; @@ -504,17 +557,23 @@ bool COPCGroup::lookupTransaction(DWORD transactionID, CTransaction *&transactio bool COPCGroup::enableAsync(IAsyncDataCallback *handler) { if (AsyncDataCallBackHandler) + { throw OPCException(L"COPCGroup::enableAsync: async already enabled"); + } ATL::CComPtr iConnectionPointContainer = 0; HRESULT result = iStateManagement->QueryInterface(IID_IConnectionPointContainer, (void **)&iConnectionPointContainer); if (FAILED(result)) + { throw OPCException(L"COPCGroup::enableAsync: could not get IID_IConnectionPointContainer"); + } result = iConnectionPointContainer->FindConnectionPoint(IID_IOPCDataCallback, &iAsyncDataCallbackConnectionPoint); if (FAILED(result)) + { throw OPCException(L"COPCGroup::enableAsync: could not get IID_IOPCDataCallback"); + } AsyncDataCallBackHandler = new CAsyncDataCallback(*this); result = iAsyncDataCallbackConnectionPoint->Advise(AsyncDataCallBackHandler, &GroupCallbackHandle); @@ -541,7 +600,9 @@ void COPCGroup::setState(DWORD reqUpdateRate_ms, DWORD &returnedUpdateRate_ms, f bool COPCGroup::disableAsync() { if (!AsyncDataCallBackHandler) + { throw OPCException(L"COPCGroup::disableAsync: async is not enabled"); + } iAsyncDataCallbackConnectionPoint->Unadvise(GroupCallbackHandle); iAsyncDataCallbackConnectionPoint = nullptr; diff --git a/OPCClientToolKit/OPCHost.cpp b/OPCClientToolKit/OPCHost.cpp index 6f143e5..0724e56 100644 --- a/OPCClientToolKit/OPCHost.cpp +++ b/OPCClientToolKit/OPCHost.cpp @@ -87,7 +87,9 @@ void COPCHost::getListOfDAServersEx(std::wstring hostName, tagCLSCTX serverLocat HRESULT result = iCatInfo->EnumClassesOfCategories(1, implist, 0, nullptr, &iEnum); if (FAILED(result)) + { throw OPCException(L"COPCHost::getListOfDAServersEx: FAILED to get enum for categeories"); + } GUID classID = {0, 0, 0, {0}}; ULONG actual = 0; @@ -99,7 +101,9 @@ void COPCHost::getListOfDAServersEx(std::wstring hostName, tagCLSCTX serverLocat result = iCatInfo->GetClassDetails(classID, &progID, &userType); // ProgIDFromCLSID ( classID, &progID ) if (FAILED(result)) + { throw OPCException(L"COPCHost::getListOfDAServersEx: FAILED to get prog ID from class ID"); + } else { listOfClassIDs.push_back(classID); @@ -108,7 +112,9 @@ void COPCHost::getListOfDAServersEx(std::wstring hostName, tagCLSCTX serverLocat LPOLESTR classIDStr = nullptr; result = StringFromCLSID(classID, &classIDStr); if (FAILED(result)) + { throw OPCException(L"COPCHost::getListOfDAServersEx: FAILED to get class ID string from class ID"); + } printf("prog ID: '%ws' - class ID: %ws\n", progID, classIDStr); @@ -132,11 +138,15 @@ COPCServer *CRemoteHost::connectDAServer(const std::wstring &serverProgIDOrClsID LPCOLESTR strClsId = serverProgIDOrClsID.c_str(); HRESULT result = CLSIDFromString(strClsId, &clsid); if (FAILED(result)) + { throw OPCException(L"CRemoteHost::connectDAServer: invalid class ID string"); + } } // if else + { clsid = GetCLSIDFromRemoteRegistry(HostName, serverProgIDOrClsID); + } return connectDAServer(clsid); @@ -162,14 +172,18 @@ CLSID CRemoteHost::GetCLSIDFromRemoteRegistry(const std::wstring &hostName, cons unsigned bufferSize = 100; result = RegQueryValueEx(keyHandle, nullptr, 0, &entryType, (LPBYTE)classIdStr, (LPDWORD)&bufferSize); if (FAILED(result)) + { throw OPCException( L"CRemoteHost::GetCLSIDFromRemoteRegistry: FAILED to get class ID from remote registry"); + } else { USES_CONVERSION; LPOLESTR sz = A2W(classIdStr); if (CLSIDFromString(sz, &classId) != S_OK) + { printf("FAILED sz:(%ws) classIdStr(%s)\n", sz, classIdStr); + } } // else } // if } // if @@ -188,7 +202,9 @@ COPCServer *CRemoteHost::connectDAServer(const CLSID &serverClassID) HRESULT result = iUnknown->QueryInterface(IID_IOPCServer, (void **)&iOpcServer); if (FAILED(result)) + { throw OPCException(L"CRemoteHost::connectDAServer: FAILED to obtain IID_IOPCServer interface from server"); + } return new COPCServer(iOpcServer); @@ -210,7 +226,9 @@ CLSID CRemoteHost::getCLSID(const std::wstring &serverProgID) HRESULT result = iCatInfo->CLSIDFromProgID(progId, &clsId); if (FAILED(result)) + { throw OPCException(L"CRemoteHost::getCLSID: FAILED to get class ID"); + } return clsId; @@ -226,22 +244,30 @@ COPCServer *CLocalHost::connectDAServer(const std::wstring &serverProgID) LPCOLESTR strClsId = serverProgID.c_str(); HRESULT result = CLSIDFromProgID(strClsId, &clsid); if (FAILED(result)) + { throw OPCException(L"CLocalHost::connectDAServer: FAILED to convert prog ID to class ID"); + } ATL::CComPtr iClassFactory; result = CoGetClassObject(clsid, CLSCTX_LOCAL_SERVER, nullptr, IID_IClassFactory, (void **)&iClassFactory); if (FAILED(result)) + { throw OPCException(L"CLocalHost::connectDAServer: FAILED get class factory"); + } ATL::CComPtr iUnknown; result = iClassFactory->CreateInstance(nullptr, IID_IUnknown, (void **)&iUnknown); if (FAILED(result)) + { throw OPCException(L"CLocalHost::connectDAServer: FAILED get create OPC server ref"); + } ATL::CComPtr iOpcServer; result = iUnknown->QueryInterface(IID_IOPCServer, (void **)&iOpcServer); if (FAILED(result)) + { throw OPCException(L"CLocalHost::connectDAServer: FAILED to obtain IID_IOPCServer interface from server"); + } return new COPCServer(iOpcServer); @@ -252,17 +278,23 @@ COPCServer *CLocalHost::connectDAServer(const CLSID &clsid) ATL::CComPtr iClassFactory; HRESULT result = CoGetClassObject(clsid, CLSCTX_LOCAL_SERVER, nullptr, IID_IClassFactory, (void **)&iClassFactory); if (FAILED(result)) + { throw OPCException(L"CLocalHost::connectDAServer: FAILED get class factory"); + } ATL::CComPtr iUnknown; result = iClassFactory->CreateInstance(nullptr, IID_IUnknown, (void **)&iUnknown); if (FAILED(result)) + { throw OPCException(L"CLocalHost::connectDAServer: FAILED get create OPC server ref"); + } ATL::CComPtr iOpcServer; result = iUnknown->QueryInterface(IID_IOPCServer, (void **)&iOpcServer); if (FAILED(result)) + { throw OPCException(L"CLocalHost::connectDAServer: FAILED obtain IID_IOPCServer interface from server"); + } return new COPCServer(iOpcServer); diff --git a/OPCClientToolKit/OPCItem.cpp b/OPCClientToolKit/OPCItem.cpp index dc08dd9..4a81149 100644 --- a/OPCClientToolKit/OPCItem.cpp +++ b/OPCClientToolKit/OPCItem.cpp @@ -52,7 +52,9 @@ bool COPCItem::writeSync(VARIANT &data) HRESULT *itemWriteErrors; HRESULT result = ItemGroup.getSyncIOInterface()->Write(1, &ServersItemHandle, &data, &itemWriteErrors); if (FAILED(result)) + { throw OPCException(L"COPCItem::writeSync: synchronous write FAILED"); + } if (FAILED(itemWriteErrors[0])) { @@ -138,10 +140,14 @@ bool COPCItem::getSupportedProperties(std::vector &desc) HRESULT result = ItemGroup.getServer().getPropertiesInterface()->QueryAvailableProperties( &ItemName[0], &nbrProperties, &pPropertyIDs, &pDescriptions, &pvtDataTypes); if (FAILED(result)) + { throw OPCException(L"COPCItem::getSupportedProperties: FAILED to retrieve properties", result); + } for (unsigned i = 0; i < nbrProperties; ++i) + { desc.push_back(CPropertyDescription(pPropertyIDs[i], pDescriptions[i], pvtDataTypes[i])); + } COPCClient::comFree(pPropertyIDs); COPCClient::comFree(pDescriptions); @@ -158,7 +164,9 @@ bool COPCItem::getProperties(const std::vector &propsToRea HRESULT *pErrors = nullptr; DWORD *pPropertyIDs = new DWORD[nbrProperties]; for (unsigned i = 0; i < nbrProperties; ++i) + { pPropertyIDs[i] = propsToRead[i].id; + } propsRead.RemoveAll(); propsRead.SetCount(nbrProperties); @@ -168,13 +176,17 @@ bool COPCItem::getProperties(const std::vector &propsToRea &ItemName[0], nbrProperties, pPropertyIDs, &pValues, &pErrors); delete[] pPropertyIDs; if (FAILED(result)) + { throw OPCException(L"COPCItem::getProperties: FAILED to retrieve property values", result); + } for (unsigned i = 0; i < nbrProperties; ++i) { CAutoPtr value; if (!FAILED(pErrors[i])) + { value.Attach(new SPropertyValue(propsToRead[i], pValues[i])); + } propsRead[i] = value; } // for diff --git a/OPCClientToolKit/OPCItemData.cpp b/OPCClientToolKit/OPCItemData.cpp index 3915d05..b0acc37 100644 --- a/OPCClientToolKit/OPCItemData.cpp +++ b/OPCClientToolKit/OPCItemData.cpp @@ -51,7 +51,9 @@ OPCItemData::OPCItemData(COPCItem *item, VARIANT &value, WORD quality, FILETIME VariantInit(&vDataValue); // initialize variant.. HRESULT result = VariantCopy(&vDataValue, &value); if (FAILED(result)) + { throw OPCException(L"OPCItemData::OPCItemData: VarCopy FAILED"); + } } // OPCItemData::OPCItemData @@ -60,7 +62,9 @@ OPCItemData::OPCItemData(const OPCItemData &other) VariantInit(&vDataValue); // initialize variant.. HRESULT result = VariantCopy(&vDataValue, &other.vDataValue); if (FAILED(result)) + { throw OPCException(L"OPCItemData::OPCItemData: VariantCopy() FAILED"); + } Item = other.Item; wQuality = other.wQuality; @@ -79,7 +83,9 @@ OPCItemData &OPCItemData::operator=(const OPCItemData &other) { HRESULT result = VariantCopy(&vDataValue, &other.vDataValue); if (FAILED(result)) + { throw OPCException(L"OPCItemData::operator=: VariantCopy() FAILED"); + } Item = other.Item; wQuality = other.wQuality; @@ -93,7 +99,9 @@ void OPCItemData::set(OPCITEMSTATE &itemState) { HRESULT result = VariantCopy(&vDataValue, &itemState.vDataValue); if (FAILED(result)) + { throw OPCException(L"OPCItemData::set: VariantCopy() FAILED"); + } wQuality = itemState.wQuality; ftTimeStamp = itemState.ftTimeStamp; @@ -119,7 +127,9 @@ COPCItemDataMap::~COPCItemDataMap() { OPCItemData *data = GetNextValue(pos); if (data) + { delete data; + } } // while RemoveAll(); diff --git a/OPCClientToolKit/OPCProperties.cpp b/OPCClientToolKit/OPCProperties.cpp index 582c937..15c2dca 100644 --- a/OPCClientToolKit/OPCProperties.cpp +++ b/OPCClientToolKit/OPCProperties.cpp @@ -30,7 +30,9 @@ SPropertyValue::SPropertyValue(const CPropertyDescription &desc, VARIANT &val) : value.vt = VT_EMPTY; HRESULT result = VariantCopy(&value, &val); if (FAILED(result)) + { throw OPCException(L"SPropertyValue::SPropertyValue: VariantCopy() FAILED", result); + } } // SPropertyValue::SPropertyValue diff --git a/OPCClientToolKit/OPCServer.cpp b/OPCClientToolKit/OPCServer.cpp index de2fd80..b4b724b 100644 --- a/OPCClientToolKit/OPCServer.cpp +++ b/OPCClientToolKit/OPCServer.cpp @@ -31,12 +31,16 @@ COPCServer::COPCServer(ATL::CComPtr &opcServerInterface) HRESULT result = opcServerInterface->QueryInterface(IID_IOPCBrowseServerAddressSpace, (void **)&iOpcNameSpace); if (FAILED(result)) + { throw OPCException(L"COPCServer::COPCServer: FAILED to obtain IID_IOPCBrowseServerAddressSpace interface", result); + } result = opcServerInterface->QueryInterface(IID_IOPCItemProperties, (void **)&iOpcProperties); if (FAILED(result)) + { throw OPCException(L"COPCServer::COPCServer: FAILED to obtain IID_IOPCItemProperties interface", result); + } } // COPCServer::COPCServer @@ -54,7 +58,9 @@ COPCGroup *COPCServer::makeGroup(const std::wstring &groupName, bool active, uns bool COPCServer::getItemNames(std::vector &opcItemNames) { if (!iOpcNameSpace) + { return false; + } OPCNAMESPACETYPE nameSpaceType = OPC_NS_FLAT; HRESULT result = iOpcNameSpace->QueryOrganization(&nameSpaceType); @@ -67,7 +73,9 @@ bool COPCServer::getItemNames(std::vector &opcItemNames) ATL::CComPtr iEnum; result = iOpcNameSpace->BrowseOPCItemIDs(OPC_FLAT, emptyString, VT_EMPTY, 0, &iEnum); if (FAILED(result)) + { return false; + } LPWSTR name = nullptr; ULONG nameSize = 0; @@ -94,7 +102,9 @@ bool COPCServer::getStatus(ServerStatus &status) OPCSERVERSTATUS *serverStatus = nullptr; HRESULT result = iOpcServer->GetStatus(&serverStatus); if (FAILED(result)) + { throw OPCException(L"COPCServer::getStatus: FAILED to get status"); + } status.ftStartTime = serverStatus->ftStartTime; status.ftCurrentTime = serverStatus->ftCurrentTime; diff --git a/OPCClientToolKit/Transaction.cpp b/OPCClientToolKit/Transaction.cpp index 57ba427..6e81afe 100644 --- a/OPCClientToolKit/Transaction.cpp +++ b/OPCClientToolKit/Transaction.cpp @@ -35,7 +35,9 @@ CTransaction::CTransaction(std::vector &items, ITransactionComplete : Completed(false), CancelID(0xffffffff), CompleteCallBack(completeCB) { for (unsigned i = 0; i < items.size(); ++i) + { COPCGroup::addItemData(ItemDataMap, items[i]); + } } // CTransaction::CTransaction @@ -51,12 +53,18 @@ void CTransaction::setItemError(COPCItem *item, HRESULT error) OPCHANDLE handle = COPCGroup::getOpcHandle(item); COPCItemDataMap::CPair *pair = ItemDataMap.Lookup(handle); if (!pair) + { throw OPCException(L"CTransaction::setItemError: FAILED to find OPC item in OPC data map"); + } if (!pair->m_value) + { ItemDataMap.SetValueAt(pair, new OPCItemData(item, error)); + } else - pair->m_value->set(error); // just set error of existing item data.. + { + pair->m_value->set(error); + } // just set error of existing item data.. } // CTransaction::setItemError @@ -65,12 +73,18 @@ void CTransaction::setItemValue(COPCItem *item, FILETIME time, WORD quality, VAR OPCHANDLE handle = COPCGroup::getOpcHandle(item); COPCItemDataMap::CPair *pair = ItemDataMap.Lookup(handle); if (!pair) + { throw OPCException(L"CTransaction::setItemValue: FAILED to find OPC item in OPC data map"); + } if (!pair->m_value) + { ItemDataMap.SetValueAt(pair, new OPCItemData(item, value, quality, time, error)); // make new item data.. + } else - pair->m_value->set(value, quality, time, error); // just set values of existing item data.. + { + pair->m_value->set(value, quality, time, error); + } // just set values of existing item data.. } // CTransaction::setItemValue @@ -79,7 +93,9 @@ const OPCItemData *CTransaction::getItemValue(COPCItem *item) const OPCHANDLE handle = COPCGroup::getOpcHandle(item); const COPCItemDataMap::CPair *pair = ItemDataMap.Lookup(handle); if (!pair) + { throw OPCException(L"CTransaction::getItemValue: FAILED to find OPC item in transaction OPC data map"); + } return pair->m_value; @@ -89,7 +105,9 @@ void CTransaction::setCompleted() { Completed = true; if (CompleteCallBack) + { CompleteCallBack->complete(*this); + } } // CTransaction::setCompleted diff --git a/OPCPerformance/OPCPerformance.cpp b/OPCPerformance/OPCPerformance.cpp index a9b12da..386c093 100644 --- a/OPCPerformance/OPCPerformance.cpp +++ b/OPCPerformance/OPCPerformance.cpp @@ -54,7 +54,9 @@ class CTransComplete : public ITransactionComplete { OPCItemData *data = transaction.getItemDataMap().GetNextValue(pos); if (!data || FAILED(data->wQuality)) + { ++nbrErrors; + } } // while printf("refresh %d completed with %d errors\n", completeCount, nbrErrors); @@ -93,7 +95,9 @@ void recordNameSpace(COPCServer &opcServer, const char *fileName) fstream itemListFile(fileName, ios::out); for (unsigned i = 0; i < opcItemNames.size(); ++i) + { itemListFile << COPCHost::WS2S(opcItemNames[i]) << "\n"; + } itemListFile.close(); @@ -112,7 +116,9 @@ void runRefreshTest(COPCServer &opcServer, const char *fileName, unsigned nbrRef char str[256] = {0}; itemListFile.getline(str, 255); if (strlen(str)) + { itemNames.push_back(COPCHost::S2WS(str)); + } } // while itemListFile.close(); @@ -194,9 +200,13 @@ int main(int argc, char *argv[]) Sleep(1000); if (saveNameSpace) + { recordNameSpace(*opcServer, argv[1]); + } else + { runRefreshTest(*opcServer, argv[1], atoi(argv[4])); + } return 0; }