diff --git a/src/core/service/cameraManager.cpp b/src/core/service/cameraManager.cpp index 2b4dc0e..ac347f7 100644 --- a/src/core/service/cameraManager.cpp +++ b/src/core/service/cameraManager.cpp @@ -20,14 +20,43 @@ static MV_CC_DEVICE_INFO_LIST QByteArrayToMV_CC_DeviceInfoList(const QByteArray& } return deviceInfoList; } -static MV_CC_DEVICE_INFO_LIST searchMvDevice() + +static QByteArray MV_GENTL_IF_INFO_LISTToQByteArray(const MV_GENTL_IF_INFO_LIST& deviceInfoList) { + QByteArray byteArray; + byteArray.resize(sizeof(MV_GENTL_IF_INFO_LIST)); + memcpy(byteArray.data(), &deviceInfoList, sizeof(MV_GENTL_IF_INFO_LIST)); + return byteArray; +} +static MV_GENTL_IF_INFO_LIST QByteArrayToMV_GENTL_IF_INFO_LIST(const QByteArray& byteArray) { + MV_GENTL_IF_INFO_LIST deviceInfoList; + if (byteArray.size() == sizeof(MV_GENTL_IF_INFO_LIST)) { + memcpy(&deviceInfoList, byteArray.constData(), sizeof(MV_GENTL_IF_INFO_LIST)); + } + else { + qDebug() << "Invalid size of QByteArray for MV_GENTL_IF_INFO_LIST!"; + } + return deviceInfoList; +} + +static MV_CC_DEVICE_INFO_LIST searchMV_CC_DEVICE_INFO_LIST() { MV_CC_DEVICE_INFO_LIST m_stDevList; memset(&m_stDevList, 0, sizeof(MV_CC_DEVICE_INFO_LIST)); int nRet = MV_CC_EnumDevices(MV_GIGE_DEVICE | MV_USB_DEVICE, &m_stDevList); return m_stDevList; } - +static MV_GENTL_IF_INFO_LIST searchMV_GENTL_IF_INFO_LIST() +{ + MV_GENTL_IF_INFO_LIST m_stIFList; + const char* chCtiPath = "MvFGProducerXoF.cti";//.cti文件路径 + int nRet = 0; + nRet = MV_CC_EnumInterfacesByGenTL(&m_stIFList, chCtiPath); + if (nRet != MV_OK) + { + qDebug() << "EnumInterfacsByGenTL fail"; + } + return m_stIFList; +} camera::camera(cameraStruct configIn, int indexIn, qtFuncBridge* bridgeIn){ bridge = bridgeIn; config = configIn; @@ -47,37 +76,15 @@ void camera::run(){ QMutexLocker locker(&mutex); data = requestQueue.dequeue(); } + if(data->oriImgs.size() >=data->imgAmountMin)continue; QMutexLocker locker2(&data->oriImgMutex); while (1) { trigger(); getCameraImg(data->oriImgs, data->imgAmountMin); if (data->oriImgs.size() >= data->imgAmountMin) { qDebug() << data->uuid << " Min:" << data->imgAmountMin << " Get:" << data->oriImgs.size(); - //if (lastUpdateTime.elapsed() > 200) {//显示在界面 - // lastUpdateTime.start(); // 记录本次更新时间 - // for (int i = 0; i < data->oriImgs.size(); i++) { - // QPixmap pixmap; - // cvMatToQPixMap(data->oriImgs[i], pixmap); - // showImgPack* pack = new showImgPack( - // config._cameraStruct.imageShowList[imgShowCnt].first, - // config._cameraStruct.imageShowList[imgShowCnt].second - // ); - // pack->img = pixmap; - // emit bridge->displayWidget_sendImg(pack); - - // imgShowCnt++; - // if (imgShowCnt >= config._cameraStruct.imageShowList.size()) - // imgShowCnt = 0; - // } - - //} - //else { - // showLost++; - // qDebug() << config.dllPath << "Lost show"; - //} break; } - QThread::msleep(1); } } @@ -119,8 +126,11 @@ void cameraManager::run(){ #pragma endregion //非海康相机可跳过 - MV_CC_DEVICE_INFO_LIST m_stDevList = searchMvDevice(); - QByteArray mvDevices = "deviceList" + MV_CC_DeviceInfoListToQByteArray(m_stDevList); + MV_CC_DEVICE_INFO_LIST m_stDevList = searchMV_CC_DEVICE_INFO_LIST(); + QByteArray mvDevices1 = "deviceList" + MV_CC_DeviceInfoListToQByteArray(m_stDevList); + + MV_GENTL_IF_INFO_LIST m_stIFList = searchMV_GENTL_IF_INFO_LIST(); + QByteArray mvDevices2 = "deviceList" + MV_GENTL_IF_INFO_LISTToQByteArray(m_stIFList); for (auto i = 0; i < _cameraStructs.size(); i++) { auto& m_module = _cameraStructs[i]; @@ -136,14 +146,28 @@ void cameraManager::run(){ m_module.module_ptr->writeData(vec_mat, m_keyByte); //初始化相机 //非海康相机可跳过 for (int i = 0; i < m_stDevList.nDeviceNum; i++){ + std::string userDefineName = static_cast((LPCSTR)m_stDevList.pDeviceInfo[i]->SpecialInfo.stGigEInfo.chUserDefinedName); + if(userDefineName == "") + userDefineName = static_cast((LPCSTR)m_stDevList.pDeviceInfo[i]->SpecialInfo.stUsb3VInfo.chUserDefinedName); + std::string serialNumber = static_cast((LPCSTR)m_stDevList.pDeviceInfo[i]->SpecialInfo.stGigEInfo.chSerialNumber); - if (!serialNumber.compare(m_module.connectionName) || !userDefineName.compare(m_module.connectionName)){ - m_module.module_ptr->writeData(vec_mat, mvDevices); + if (serialNumber == "") + serialNumber = static_cast((LPCSTR)m_stDevList.pDeviceInfo[i]->SpecialInfo.stUsb3VInfo.chSerialNumber); + + if (m_module.connectionName.find(serialNumber) != std::string::npos || m_module.connectionName.find(userDefineName) != std::string::npos){ + m_module.module_ptr->writeData(vec_mat, mvDevices1); + break; + } + } + for(int i = 0; i < m_stIFList.nInterfaceNum; i++) { + std::string serialNumber = static_cast((LPCSTR)m_stIFList.pIFInfo[i]->chInterfaceID); + std::string userDefineName = static_cast((LPCSTR)m_stIFList.pIFInfo[i]->chInterfaceID); + if (m_module.connectionName.find(serialNumber) != std::string::npos || m_module.connectionName.find(userDefineName) != std::string::npos) { + m_module.module_ptr->writeData(vec_mat, mvDevices1); break; } } - } status = NotInit; diff --git a/subModule/Hd_CameraModule_HIK_soft_GIGE/CMakeLists.txt b/subModule/Hd_25DCameraVJ_module/CMakeLists.txt similarity index 91% rename from subModule/Hd_CameraModule_HIK_soft_GIGE/CMakeLists.txt rename to subModule/Hd_25DCameraVJ_module/CMakeLists.txt index 8412669..47da335 100644 --- a/subModule/Hd_CameraModule_HIK_soft_GIGE/CMakeLists.txt +++ b/subModule/Hd_25DCameraVJ_module/CMakeLists.txt @@ -3,7 +3,7 @@ get_filename_component(CURRENT_FOLDER ${CMAKE_CURRENT_SOURCE_DIR} NAME) string(TIMESTAMP RUN_TIME) message( " model start : " ${CURRENT_FOLDER}:${RUN_TIME}) -set(DLL_NAMES "mvs" "opencv") +set(DLL_NAMES "opencv" "keyence2_5D" "2_5Ddll") foreach(child ${DLL_NAMES}) LIST(APPEND ENV_INCLUDE ${${child}_include}) LIST(APPEND ENV_LIB ${${child}_lib}) @@ -12,6 +12,7 @@ endforeach() message(" ENV_INCLUDE : " ${ENV_INCLUDE} ) message(" ENV_LIB : " ${ENV_LIB} ) message(" ENV_TARGET : " ${ENV_TARGET} ) + include_directories( ${ENV_INCLUDE} @@ -19,7 +20,6 @@ include_directories( link_directories ( ${ENV_LIB} - ) @@ -28,7 +28,7 @@ SET(CMAKE_CXX_STANDARD 11) SET(CMAKE_CXX_STANDARD_REQUIRED ON) set(CMAKE_AUTOMOC ON) -SET(CMAKE_AUTOUIC OFF) +SET(CMAKE_AUTOUIC ON) set(CMAKE_AUTORCC ON) FILE(GLOB HEAD_FILES "./*.h" ) @@ -56,15 +56,14 @@ set_target_properties(${CURRENT_FOLDER} PROPERTIES LINKER_LANGUAGE C target_link_libraries(${CURRENT_FOLDER} PRIVATE - ${ENV_TARGET} + ${qt_target_link} + ${opencv_target_link} + ${keyence2_5D_target_link} Qt${QT_VERSION_MAJOR}::Core ) # target_compile_definitions(${CURRENT_FOLDER} PRIVATE HD_AIDEMO_MODULE_LIBRARY) - - - string(TIMESTAMP RUN_TIME) message( " model end : " ${CURRENT_FOLDER}:${RUN_TIME}) diff --git a/subModule/Hd_25DCameraVJ_module/Hd_25DCameraVJ_module.cpp b/subModule/Hd_25DCameraVJ_module/Hd_25DCameraVJ_module.cpp new file mode 100644 index 0000000..581008f --- /dev/null +++ b/subModule/Hd_25DCameraVJ_module/Hd_25DCameraVJ_module.cpp @@ -0,0 +1,1013 @@ +#include "Hd_25DCameraVJ_module.h" +#include + +#include "KglDevice.h" +#include "KglStream.h" +#include "KglSystem.h" +#include "KglBuffer.h" +#include "KglDefine.h" +#include "KglResult.h" +using namespace Keyence; +#include + +KglDevice* kglDevice; +KglStream* kglStream; +KglGenParameterArray* kgllFeatureNodes; +KglBuffer* kglBuffer; +std::string sModelName; +// Camera type +#define CameraTypeArea 1 +#define CameraTypeLine 2 +#define CameraTypeXT 3 +#define CameraTypeRB 4 +int iCameraType; +int getImageTimeOut = 3000; +QString lastError; +QQueue> queuePic; +QMutex* n_mutex = new QMutex(); +std::vector sImageType; +static int imgNum = 1; +std::string serialNum; +#pragma region Device control +void Connect(int index) +{ + KglSystem kglSystem; + const KglDeviceInfo* deviceInfo; + std::string inputkey; + if (KGL_SUCCESS != kglSystem.find()) { + qDebug() << "Failed to find camera device."; + return; + } + + uint32_t count = kglSystem.getDeviceCount(); + if (count == 0) + { + qDebug() << ("No camera device can be found.\n"); + return; + } + + if ((index < 0) || (count <= index)) + { + qDebug() << ("The entry is invalid.\n"); + return; + } + + kglDevice = new KglDevice(); + kglStream = new KglStream(); + + for (int i = 0; i < count; i++) + { + deviceInfo = kglSystem.getDeviceInfo(index + i); + cout << deviceInfo->getIPAddress() << endl; + cout << deviceInfo->getSerialNumber() << endl; + std::string abc = deviceInfo->getSerialNumber(); + if (abc == serialNum) + { + break; + } + } + sModelName = deviceInfo->getModelName(); + if ((sModelName == ("CA-HL02MX")) || + (sModelName == ("CA-HL04MX")) || + (sModelName == ("CA-HL08MX"))) + { + iCameraType = CameraTypeLine; + } + else if ((sModelName == ("XT-024")) || + (sModelName == ("XT-060"))) + { + iCameraType = CameraTypeXT; + } + else if ((sModelName == ("RB-500")) || + (sModelName == ("RB-800")) || + (sModelName == ("RB-1200"))) + { + iCameraType = CameraTypeRB; + } + else { + iCameraType = CameraTypeArea; + } + cout << deviceInfo->getIPAddress() << endl; + int cnt = 0; + while (KGL_SUCCESS != kglDevice->connect(deviceInfo->getIPAddress())) { + cnt++; + Sleep(1000); + if (cnt > 3) + { + qDebug() << ("Cannot connect to the camera device.\n"); + return; + } + } + + if (KGL_SUCCESS != kglStream->open(*kglDevice)) { + qDebug() << ("Cannot connect to the stream.\n"); + return; + } + + // Get FeatureNode of camera device + kgllFeatureNodes = kglDevice->getDeviceParameters(); +} + +void Disconnect() +{ + if ((kglStream != NULL) && (kglStream->isOpen())) + { + KglResult result = kglStream->close(*kglDevice); + if (KGL_SUCCESS != result) { + qDebug() << ("Cannot disconnect from the stream.\n"); + return; + } + } + + if ((kglDevice != NULL) && (kglDevice->isConnected())) + { + if (KGL_SUCCESS != kglDevice->disconnect()) { + qDebug() << ("Cannot disconnect from the camera device.\n"); + return; + } + } +} +#pragma endregion + +#pragma region Feature access +void setIntegerValue(const std::string sFeatureName, const int64_t value) +{ + KglResult result; + KglString sConfigurationLastFailureCause; + + result = kgllFeatureNodes->setIntegerValue(sFeatureName.c_str(), value); + if (KGL_SUCCESS != result) + { + qDebug() << ("Error : setParam\n"); + return; + } +} + +void setFloatValue(const std::string sFeatureName, const double value) +{ + KglResult result; + KglString sConfigurationLastFailureCause; + + result = kgllFeatureNodes->setFloatValue(sFeatureName.c_str(), value); + if (KGL_SUCCESS != result) + { + if (KGL_SUCCESS != result) + { + qDebug() << ("Error : setParam\n"); + return; + } + } +} + +void setBooleanValue(const std::string sFeatureName, const bool value) +{ + KglResult result; + KglString sConfigurationLastFailureCause; + + result = kgllFeatureNodes->setBooleanValue(sFeatureName.c_str(), value); + if (KGL_SUCCESS != result) + { + if (KGL_SUCCESS != result) + { + qDebug() << ("Error : setParam\n"); + return; + } + } +} + +void setEnumValue(const std::string sFeatureName, std::string value) +{ + KglResult result; + KglString sConfigurationLastFailureCause; + + result = kgllFeatureNodes->setEnumValue(sFeatureName.c_str(), value.c_str()); + if (KGL_SUCCESS != result) + { + qDebug() << ("Error : setParam\n"); + return; + } +} + +void setStringValue(const std::string sFeatureName, const std::string value) +{ + KglResult result; + KglString sConfigurationLastFailureCause; + + result = kgllFeatureNodes->setStringValue(sFeatureName.c_str(), value.c_str()); + if (KGL_SUCCESS != result) + { + qDebug() << ("Error : setParam\n"); + return; + } +} + +void executeCommand(const std::string sFeatureName) +{ + KglResult result; + + result = kgllFeatureNodes->executeCommand(sFeatureName.c_str()); + if (KGL_SUCCESS != result) + { + qDebug() << ("Error : execCommand\n"); + return; + } +} + +void getIntegerValue(const std::string sFeatureName, int64_t& value) +{ + KglResult result; + + result = kgllFeatureNodes->getIntegerValue(sFeatureName.c_str(), value); + if (KGL_SUCCESS != result) + { + qDebug() << ("Error : getParam\n"); + return; + } +} + +void getFloatValue(const std::string sFeatureName, double& value) +{ + KglResult result; + + result = kgllFeatureNodes->getFloatValue(sFeatureName.c_str(), value); + if (KGL_SUCCESS != result) + { + qDebug() << ("Error : getParam\n"); + return; + } +} + +void getBooleanValue(const std::string sFeatureName, bool& value) +{ + KglResult result; + + result = kgllFeatureNodes->getBooleanValue(sFeatureName.c_str(), value); + if (KGL_SUCCESS != result) + { + qDebug() << ("Error : getParam\n"); + return; + } +} + +void getEnumValue(const std::string sFeatureName, std::string& value) +{ + KglResult result; + KglString featurevalue; + + result = kgllFeatureNodes->getEnumValue(sFeatureName.c_str(), featurevalue); + value = featurevalue; + + if (KGL_SUCCESS != result) + { + qDebug() << ("Error : getParam\n"); + return; + } +} + +void getStringValue(const std::string sFeatureName, std::string& value) +{ + KglResult result; + KglString featurevalue; + + result = kgllFeatureNodes->getStringValue(sFeatureName.c_str(), featurevalue); + value = featurevalue; + if (KGL_SUCCESS != result) + { + qDebug() << ("Error : getParam\n"); + return; + } +} +#pragma endregion + +#pragma region Import XML +void ImportDeviceParameters(std::string sFilePath) +{ + setEnumValue("OperationMode", "SetupMode"); + + if (!sFilePath.empty()) + { + KglTargetDataSet target = (KglTargetDataSet)(KglTargetData::CameraParameters) + | (KglTargetDataSet)(KglTargetData::ParameterSetOfCameraParameter) + | (KglTargetDataSet)(KglTargetData::ModelImageOfCameraParameter) + | (KglTargetDataSet)(KglTargetData::CameraParametersOfEnvironmentSettings) + | (KglTargetDataSet)(KglTargetData::CommonParametersOfEnvironmentSettings) + | (KglTargetDataSet)(KglTargetData::CommonCameraParameters) + | (KglTargetDataSet)(KglTargetData::CalibrationOfCameraParameter); + KglImportDeviceParamOption option = KglImportDeviceParamOption(); + option.bOverwriteModelImage = true; + option.bOverwriteCalibration = true; + KglString failFeature; + + KglResult ret = kglDevice->importDeviceParameters(sFilePath.c_str(), failFeature, target, option); + if (ret != KGL_SUCCESS) + { + qDebug() << ("Failed to load a Feature List file.\n"); + return; + } + } + + setEnumValue("OperationMode", "RunMode"); +} +#pragma endregion + +#pragma region Optional Functions +std::vector GetEnableImageType(std::string sImageType) +{ + std::vector EnableImageType; + + std::string StdImageTypeTable[1][2] = + { + { "StdNormalImageEnable", "StdNormalImage" } + }; + + std::string LtrxNmlImageTypeTable[15][2] = + { + { "LtrxNormalImageEnable", "LtrxNormalImage" }, + { "LtrxUpperImageEnable", "LtrxUpperImage" }, + { "LtrxUpperRightImageEnable", "LtrxUpperRightImage" }, + { "LtrxRightImageEnable", "LtrxRightImage" }, + { "LtrxLowerRightImageEnable", "LtrxLowerRightImage" }, + { "LtrxLowerImageEnable", "LtrxLowerImage" }, + { "LtrxLowerLeftImageEnable", "LtrxLowerLeftImage" }, + { "LtrxLeftImageEnable", "LtrxLeftImage" }, + { "LtrxUpperLeftImageEnable", "LtrxUpperLeftImage" }, + { "LtrxShapeImage1Enable", "LtrxShapeImage1" }, + { "LtrxShapeImage2Enable", "LtrxShapeImage2" }, + { "LtrxShapeImage3Enable", "LtrxShapeImage3" }, + { "LtrxTextureImageEnable", "LtrxTextureImage" }, + { "LtrxGradientXImageEnable", "LtrxGradientXImage" }, + { "LtrxGradientYImageEnable", "LtrxGradientYImage" }, + }; + + std::string MlspImageTypeTable[11][2] = + { + { "MlspUVImageEnable", "MlspUVImage" }, + { "MlspBlueImageEnable", "MlspBlueImage" }, + { "MlspGreenImageEnable", "MlspGreenImage" }, + { "MlspAmberImageEnable", "MlspAmberImage" }, + { "MlspRedImageEnable", "MlspRedImage" }, + { "MlspFarRedImageEnable", "MlspFarRedImage" }, + { "MlspIRImageEnable", "MlspIRImage" }, + { "MlspWhiteImageEnable", "MlspWhiteImage" }, + { "MlspAverageGrayscaleImageEnable", "MlspAverageGrayscaleImage" }, + { "MlspColorImageEnable", "MlspColorImage" }, + { "MlspColorDifferenceImageEnable", "MlspColorDifferenceImage" } + }; + + std::string SprfImageTypeTable[16][2] = + { + { "SprfX1ImageEnable", "SprfX1Image" }, + { "SprfX2ImageEnable", "SprfX2Image" }, + { "SprfX3ImageEnable", "SprfX3Image" }, + { "SprfX4ImageEnable", "SprfX4Image" }, + { "SprfY1ImageEnable", "SprfY1Image" }, + { "SprfY2ImageEnable", "SprfY2Image" }, + { "SprfY3ImageEnable", "SprfY3Image" }, + { "SprfY4ImageEnable", "SprfY4Image" }, + { "SprfSpecularReflectionImageEnable", "SprfSpecularReflectionImage" }, + { "SprfDiffuseReflectionImageEnable", "SprfDiffuseReflectionImage" }, + { "SprfShapeImage1Enable", "SprfShapeImage1" }, + { "SprfShapeImage2Enable", "SprfShapeImage2" }, + { "SprfPhaseXImageEnable", "SprfPhaseXImage" }, + { "SprfPhaseYImageEnable", "SprfPhaseYImage" }, + { "SprfGlossRatioImageEnable", "SprfGlossRatioImage" }, + { "SprfNormalImageEnable", "SprfNormalImage" } + }; + + std::string Cap3DImageTypeTable[2][2] = + { + { "Cap3DAreascan3DImageEnable", "Areascan3DImage" }, + { "Cap3DAreascan2DImageEnable", "Areascan2DImage" }, + }; + + std::string RBImageTypeTable[2][2] = + { + { "Areascan3DImageEnable", "Areascan3DImage" }, + { "Areascan2DGrayscaleImageEnable", "Areascan2DGrayscaleImage" }, + }; + + std::string XTImageTypeTable[3][2] = + { + { "Areascan3DImageEnable", "Areascan3DImage" }, + { "Areascan2DColorImageEnable", "Areascan2DColorImage" }, + { "Areascan2DGrayscaleImageEnable", "Areascan2DGrayscaleImage" } + }; + + std::string FilteredImageTable[8][2] = + { + { "FilteredImageEnable", "FilteredImage1" }, + { "FilteredImageEnable", "FilteredImage2" }, + { "FilteredImageEnable", "FilteredImage3" }, + { "FilteredImageEnable", "FilteredImage4" }, + { "FilteredImageEnable", "FilteredImage5" }, + { "FilteredImageEnable", "FilteredImage6" }, + { "FilteredImageEnable", "FilteredImage7" }, + { "FilteredImageEnable", "FilteredImage8" } + }; + + int64_t sTargetParameterSet; + getIntegerValue("TargetParameterSet", sTargetParameterSet); + setIntegerValue("ParameterSetSelector", sTargetParameterSet); + + if (iCameraType == CameraTypeLine) + { + std::string sCaptureMode; + getEnumValue("CaptureMode", sCaptureMode); + if (sCaptureMode == "Fixed_MultipleImages") + { + bool sEnable; + getBooleanValue("IndividualFilterPerFixedCaptureNoEnable", sEnable); + if (sEnable) + { + int64_t sTargetCaptureCount; + getIntegerValue("TargetFixedCaptureNo", sTargetCaptureCount); + setIntegerValue("FixedCaptureNoSelector", sTargetCaptureCount); + } + } + } + + bool sEnable; + if (iCameraType == CameraTypeRB) + { + for (UINT i = 0; i < 2; i++) + { + std::string sFeatureName = RBImageTypeTable[i][0]; + std::string sImageName = RBImageTypeTable[i][1]; + getBooleanValue(sFeatureName, sEnable); + if (sEnable) + { + EnableImageType.push_back(sImageName); + } + } + } + else if (iCameraType == CameraTypeXT) + { + for (UINT i = 0; i < 3; i++) + { + std::string sFeatureName = XTImageTypeTable[i][0]; + std::string sImageName = XTImageTypeTable[i][1]; + getBooleanValue(sFeatureName, sEnable); + if (sEnable) + { + EnableImageType.push_back(sImageName); + } + } + } + else + { + std::string sLightingMode = ""; + getEnumValue("ImagingMode", sLightingMode); + + if (sLightingMode == "StandardLighting") + { + for (UINT i = 0; i < 1; i++) + { + std::string sFeatureName = StdImageTypeTable[i][0]; + std::string sImageName = StdImageTypeTable[i][1]; + getBooleanValue(sFeatureName, sEnable); + if (sEnable) + { + EnableImageType.push_back(sImageName); + } + } + } + else if (sLightingMode == "LumiTrax") + { + for (UINT i = 0; i < 15; i++) + { + std::string sFeatureName = LtrxNmlImageTypeTable[i][0]; + std::string sImageName = LtrxNmlImageTypeTable[i][1]; + getBooleanValue(sFeatureName, sEnable); + if (sEnable) + { + EnableImageType.push_back(sImageName); + } + } + } + else if (sLightingMode == "MultiSpectrum") + { + for (UINT i = 0; i < 11; i++) + { + std::string sFeatureName = MlspImageTypeTable[i][0]; + std::string sImageName = MlspImageTypeTable[i][1]; + getBooleanValue(sFeatureName, sEnable); + if (sEnable) + { + EnableImageType.push_back(sImageName); + } + } + } + else if (sLightingMode == "LumiTraxSpecularReflection") + { + for (UINT i = 0; i < 16; i++) + { + std::string sFeatureName = SprfImageTypeTable[i][0]; + std::string sImageName = SprfImageTypeTable[i][1]; + getBooleanValue(sFeatureName, sEnable); + if (sEnable) + { + EnableImageType.push_back(sImageName); + } + } + } + else if (sLightingMode == "Capture3D") + { + for (UINT i = 0; i < 2; i++) + { + std::string sFeatureName = Cap3DImageTypeTable[i][0]; + std::string sImageName = Cap3DImageTypeTable[i][1]; + getBooleanValue(sFeatureName, sEnable); + if (sEnable) + { + EnableImageType.push_back(sImageName); + } + } + } + } + + for (UINT i = 0; i < 8; i++) + { + setIntegerValue("FilteredImageSelector", (i + 1)); + + std::string sFeatureName = FilteredImageTable[i][0]; + std::string sImageName = FilteredImageTable[i][1]; + getBooleanValue(sFeatureName, sEnable); + if (sEnable) + { + EnableImageType.push_back(sImageName); + } + } + + UINT ImageTypeSize = (UINT)EnableImageType.size(); + if (ImageTypeSize < 5) + { + for (int i = ImageTypeSize; i < 5; i++) + { + EnableImageType.push_back(""); + } + } + + qDebug() << ("Select an image type.\n\n"); + + for (UINT i = 0; i < ImageTypeSize; ++i) + { + qDebug() << ((std::to_string(i + 1) + " :" + EnableImageType[i] + "\n").c_str()); + } + + uint32_t iSelected = atoi(sImageType.c_str()); + if ((iSelected == 0) || (iSelected > ImageTypeSize)) + { + qDebug() << ("The entry is invalid.\n"); + return EnableImageType; + } + return EnableImageType; +} + +void ConvertRGBA8toBGRA8(void* buffer, int pixelSize) +{ + std::byte dataR; + std::byte dataB; + + for (int i = 0; i < pixelSize; i++) + { + dataR = *((std::byte*)(buffer)+(i * 4)); + dataB = *((std::byte*)(buffer)+(i * 4) + 2); + + *((std::byte*)(buffer)+(i * 4)) = dataB; + *((std::byte*)(buffer)+(i * 4) + 2) = dataR; + } +} +#pragma endregion + +#pragma region Acquisition control + +bool AcquisitionStart() +{ + KglResult result; + + result = kglStream->startAcquisition(*kglDevice); + if (KGL_SUCCESS != result) { + qDebug() << ("Error : acquisitionStart\n error:")<< result; + return false; + } + + return true; +} + +void AcquisitionStop() +{ + KglResult result; + + result = kglStream->stopAcquisition(*kglDevice); + if (KGL_SUCCESS != result) { + qDebug() << ("Error : acquisitionStop\n"); + return; + } +} + +bool QueueBuffer() +{ + KglResult result; + KglResult operationResult; + + uint32_t payloadsize = kglDevice->getPayloadSize(); + if (payloadsize == 0) + { + qDebug() << ("Error : getPayloadSize\n"); + return false; + } + + kglBuffer = new KglBuffer(); + result = kglBuffer->allocate(payloadsize); + if (KGL_SUCCESS != result) + { + qDebug() << ("Error : allocate\n"); + return false; + } + + result = kglStream->queueBuffer(kglBuffer); + if ((KGL_SUCCESS != result) && (KGL_PENDING != result)) + { + qDebug() << ("Error : queueBuffer\n"); + return false; + } +} + +cv::Mat RetrieveBuffer() +{ + KglResult result; + KglResult operationResult; + + result = kglStream->retrieveBuffer(&kglBuffer, operationResult); + if ((KGL_SUCCESS != result) || (KGL_SUCCESS != operationResult)) + { + if (kglBuffer != NULL) + { + kglBuffer->free(); + delete(kglBuffer); + kglBuffer = NULL; + } + qDebug() << ("Error : retrieveBuffer\n error:")<< kglStream; + return Mat(); + } + + UINT bmpSize = kglBuffer->getAcquiredSize(); + char* data = (char*)malloc(bmpSize); + + CopyMemory((void*)data, kglBuffer->getDataPointer(), bmpSize); + + cv::Mat mat; + int64_t width; + int64_t height; + std::string sPixelFormat; + getIntegerValue("Width", width); + getIntegerValue("Height", height); + getEnumValue("PixelFormat", sPixelFormat); + + if (sPixelFormat == "Mono8") + { + mat = cv::Mat(height, width, CV_8UC1, data); + } + + else if (sPixelFormat == "Mono16") + { + mat = cv::Mat(height, width, CV_16UC1, data); + } + + else if (sPixelFormat == "BGR8Packed") + { + mat = cv::Mat(height, width, CV_8UC3, data); + } + + else if (sPixelFormat == "RGB8Packed") + { + mat = cv::Mat(height, width, CV_8UC3, data); + cv::cvtColor(mat, mat, COLOR_BGR2RGB); + + } + else if (sPixelFormat == "BGRA8Packed") + { + mat = cv::Mat(height, width, CV_8UC4, data); + } + + else if (sPixelFormat == "RGBA8Packed") + { + mat = cv::Mat(height, width, CV_8UC3, data); + cv::cvtColor(mat, mat, COLOR_BGRA2RGBA); + } + + if (kglBuffer != NULL) + { + kglBuffer->free(); + delete(kglBuffer); + kglBuffer = NULL; + } + + cv::Mat bmpMat; + mat.copyTo(bmpMat); + if (data) + { + free(data); + } + //imwrite("C:\\pic\\Img" + to_string(imgNum) + ".bmp", bmpMat); + //imgNum++; + return bmpMat; +} + +void SaveBMP(cv::Mat bmp) +{ + std::string inputkey; + std::string sFilePath; + + qDebug() << ("Do you want to save the image as a BMP file?\n\n"); + qDebug() << ("1 :Yes\n"); + qDebug() << ("2 : No\n"); + std::cin >> inputkey; + qDebug() << ("------------------------------\n"); + switch (atoi(inputkey.c_str())) + { + case 1: + qDebug() << ("Enter the full path of the BMP file.\n\n"); + std::cin >> sFilePath; + qDebug() << ("------------------------------\n"); + break; + case 2: + return; + break; + default: + qDebug() << ("The entry is invalid.\n"); + return; + break; + } + try + { + /*System::String^ FilePath = gcnew System::String(sFilePath.c_str()); + FileStream^ stream = gcnew FileStream(FilePath, FileMode::Create, FileAccess::Write); + TiffBitmapEncoder^ encoder = gcnew TiffBitmapEncoder(); + encoder->Compression = TiffCompressOption::None; + encoder->Frames->Add(BitmapFrame::Create(bmp)); + encoder->Save(stream);*/ + //cv::imwrite(sFilePath, bmp); + } + catch (char) + { + qDebug() << ("Failed to save the BMP file.\n"); + qDebug() << ("------------------------------"); + } +} + +void TriggerSoftware() +{ + Sleep(5000); + kgllFeatureNodes->executeCommand("TriggerSoftware"); +} + + +bool AcquisitionStartEx_SingleFrame(bool bMultiCaptureUpdateImage, std::string sMultiCaptureImageType, std::vector& matVec) +{ + + std::string sPixelFormat; + + setBooleanValue("MultiCaptureUpdateImage", bMultiCaptureUpdateImage); + setEnumValue("MultiCaptureImageType", sMultiCaptureImageType); + + //cv::Mat bmp; + + //bmp = QueueBuffer(); + cv::Mat bmp; + + if (!QueueBuffer()) + return false; + + AcquisitionStart(); + bmp = RetrieveBuffer(); + if (!bmp.empty()) + { + matVec.push_back(bmp); + AcquisitionStop(); + bmp.release(); + return true; + } + else + { + AcquisitionStop(); + bmp.release(); + return false; + } + + + //if (sPixelFormat == "RGBA8Packed") + //{ + // ConvertRGBA8toBGRA8(BitmapImage->BackBuffer.ToPointer(), (BitmapImage->PixelWidth * BitmapImage->PixelHeight)); + //} + + //SaveBMP(bmp); + +} + +#pragma endregion + + +void MyThread::run() +{ + while (m_runFlag) + { + std::vector matVecs; + if (AcquisitionStartEx_SingleFrame(TRUE, sImageType[0], matVecs) == true) {//为true的话就是重新获取一组图片中的一张sImageType类型的图片 false就是在同一组图片获取sImageType类型的图片 + for (int i = 1; i < 3; i++) + AcquisitionStartEx_SingleFrame(FALSE, sImageType[i], matVecs);//为true的话就是重新获取一组图片中的一张sImageType类型的图片 false就是在同一组图片获取sImageType类型的图片 + if (matVecs.size() > 0) + { + n_mutex->lock(); + queuePic.append(matVecs); + qDebug() << "Acquisition sucess size" << queuePic.size(); + m_flag = true; + n_mutex->unlock(); + + } + } + else + matVecs.clear(); + + //QThread::msleep(5); + } +} + +Hd_25DCameraVJ_module* create() +{ + qDebug() << "[info]" << __FUNCTION__ << "line:" << __LINE__ << "Hd_MvCamera_module create success!"; + return new Hd_25DCameraVJ_module; +} + +void destory(Hd_25DCameraVJ_module* ptr) +{ + if (ptr) + { + delete ptr; + ptr = nullptr; + } + qDebug() << "[info] " << __FUNCTION__ << " line:" << __LINE__ << "Hd_MvCamera_module destory success!"; +} + +Hd_25DCameraVJ_module::Hd_25DCameraVJ_module() +{ + //m_thread = new MyThread; + //m_mutex = new QMutex(); + workThread = new MyThread(); +} + +Hd_25DCameraVJ_module::~Hd_25DCameraVJ_module() +{ + if (workThread) + { + workThread->setFlag(false); + workThread->wait(); + workThread->quit(); + workThread->deleteLater(); + workThread = nullptr; + } + + Disconnect(); + + if (n_mutex) + { + delete n_mutex; + n_mutex = nullptr; + } + + qDebug() << "[info]" << __FUNCTION__ << "line:" << __LINE__ << " delete success!"; +} + +bool Hd_25DCameraVJ_module::readData(std::vector&mat , QByteArray& data) +{ + Q_UNUSED(data) + + if (data == "getStatus") { + data = lastError.toUtf8(); + return true; + } + + if (queuePic.isEmpty()) + { + return false; + } + QMutexLocker locker(n_mutex); + vector dstMat = queuePic.dequeue(); + //for (int i=0;i& mat , QByteArray&data) +{ + Q_UNUSED(mat) + + cameraIndex = data.toInt(); + return true; +} + +bool Hd_25DCameraVJ_module::initParas(QByteArray& initData) +{ +#if 1 + QByteArrayList valueList = initData.split('#'); + if (valueList.size() < 3) { + qDebug() << "[Error] Hd_25DCameraVJ_module initParas fail--params error!参数数量不满足"; + lastError = "参数数量不满足"; + return false; + } + serialNum = valueList[0]; + std::string path = valueList[1].toStdString(); + getImageTimeOut = valueList[2].toInt(); + + KglResult initRes = KglSystem::initialize(); + Connect(0); + setBooleanValue("GevGVCPPendingAck", TRUE); + + //ImportDeviceParameters("C://EVE2.5dConfig//CA-HL08MX_hardTrigger.XML"); + ImportDeviceParameters(path.c_str()); + //setEnumValue("AcquisitionMode", "SingleFrame"); + bool bBGEnable; + getBooleanValue("ImageCaptureBufferEnable", bBGEnable); + if (bBGEnable) + { + executeCommand("ImageCaptureBufferClear"); + executeCommand("BufferCaptureAcquisitionStart"); + } + std::string sImageType1 = "1"; + sImageType = GetEnableImageType(sImageType1); //获取图像类别 6张 + + std::string sTriggerMode; + getEnumValue("TriggerMode", sTriggerMode); + sTriggerSource = ""; + if (sTriggerMode == "On") + { + getEnumValue("TriggerSource", sTriggerSource); + //if (sTriggerSource.compare("Software")) + // workThread->start(); + qDebug() << __FUNCTION__ << __LINE__ << "sTriggerSource:" << QString::fromStdString(sTriggerSource); + } + else + { + //workThread->start(); + qDebug() << __FUNCTION__ << __LINE__ << "hardTrigger"; + } + std::vector matVecs; + workThread->start(); + //workThread->run(); + + //KglResult res = kgllFeatureNodes->executeCommand("TriggerSoftware"); +#endif + return true; +} + +bool Hd_25DCameraVJ_module::run()//软触发 +{ + //qDebug() << "[info]" << __FUNCTION__ << " line:" << __LINE__ << " run start" < 0) + { + n_mutex->lock(); + result = true; + n_mutex->unlock(); + softwareTriggerStatus = 0; + return true; + } + if (!sTriggerSource.compare("Software") && softwareTriggerStatus == 0) + { + KglResult res = kgllFeatureNodes->executeCommand("TriggerSoftware");//软触发 + softwareTriggerStatus = 1; + return false; + } +#endif + { + QMutexLocker locker(n_mutex); + queuePic.clear(); + } + int sleepMs = 10; + int cnt = 0; + int timeoutCnt = getImageTimeOut / sleepMs; + while (true) + { + QMutexLocker locker(n_mutex); + if (queuePic.size() > 0)return true; + if (cnt++ > timeoutCnt) { + queuePic.push_back(cv::Mat(200, 200, CV_8UC1, cv::Scalar(0))); //返回空图 + qDebug() << QString::fromStdString(serialNum) << "timeout"; + return true; + } + QThread::msleep(sleepMs); + } + return true; + } + catch (QString ev) + { + qDebug() << "[info] FUNCTION:" << __FUNCTION__ << " line:" << __LINE__ << " ev:" << ev; + } + //qDebug() << "[info]"<< __FUNCTION__ << " line:" << __LINE__ << " run end" ; + return true; +} \ No newline at end of file diff --git a/subModule/Hd_25DCameraVJ_module/Hd_25DCameraVJ_module.h b/subModule/Hd_25DCameraVJ_module/Hd_25DCameraVJ_module.h new file mode 100644 index 0000000..868df2a --- /dev/null +++ b/subModule/Hd_25DCameraVJ_module/Hd_25DCameraVJ_module.h @@ -0,0 +1,56 @@ +#ifndef Hd_25DCameraVJ_module_H +#define Hd_25DCameraVJ_module_H +#include +#include +#include +#include +#include +#include + +#include + +using namespace cv; +using namespace std; +#pragma execution_character_set("utf-8") +static bool m_flag = true; +class MyThread : public QThread +{ + Q_OBJECT +public: + explicit MyThread(QObject* parent = nullptr) :m_obj(parent) {} + void run(); + void setFlag(bool r) { m_runFlag = r; }; +private: + bool m_runFlag = true; + QObject* m_obj; +signals: + +}; + + +class Hd_25DCameraVJ_module :public dsModuleBase +{ +public: + Hd_25DCameraVJ_module(); + virtual ~Hd_25DCameraVJ_module(); + bool readData(std::vector&, QByteArray&); + bool writeData(std::vector&, QByteArray&); + bool initParas(QByteArray&); + bool run(); + + std::string sTriggerSource; +private: + bool softwareTriggerStatus = 0; + int cameraIndex = 0; + MyThread* workThread = nullptr; + +}; + +extern "C" +{ +Q_DECL_EXPORT Hd_25DCameraVJ_module * create(); +Q_DECL_EXPORT void destory(Hd_25DCameraVJ_module * ptr); +} + +#endif // Hd_25DCameraVJ_module_H +//Hd_25DCameraVJ_module diff --git a/subModule/Hd_25DCameraVJ_module/readme.txt b/subModule/Hd_25DCameraVJ_module/readme.txt new file mode 100644 index 0000000..52d011d --- /dev/null +++ b/subModule/Hd_25DCameraVJ_module/readme.txt @@ -0,0 +1,3 @@ +基恩士2.5D相机 +初始化格式 序列号#路径#超时时间 +SAMPLE: xxxxxxxxx#C://EVE2.5dConfig//CA-HL08MX_hardTrigger.XML#1000 \ No newline at end of file diff --git a/subModule/Hd_CameraModule_3DKeyence/Hd_CameraModule_3DKeyence.cpp b/subModule/Hd_CameraModule_3DKeyence/Hd_CameraModule_3DKeyence.cpp index 12900e1..2e1d3fc 100644 --- a/subModule/Hd_CameraModule_3DKeyence/Hd_CameraModule_3DKeyence.cpp +++ b/subModule/Hd_CameraModule_3DKeyence/Hd_CameraModule_3DKeyence.cpp @@ -16,6 +16,8 @@ int G_yImageSize = 0; // Number of Y lines. //int _lastImageSizeHeight[MAX_LJXA_DEVICENUM]; int imgTakeNum = 0, imgTarget = 1; int imgIndex = 0; +int getImageTimeOut = 3000; +QString lastError; QMutex* m_mutex = nullptr; std::mutex bufferMutex; QQueue< cv::Mat> heightMatS;//高度图 @@ -330,86 +332,35 @@ bool Hd_CameraModule_3DKeyence::writeData(std::vector &mat,QByteArray & //传入initParas函数,格式为:相机key+参数名1#参数值1#参数值2+参数名2#参数值1... bool Hd_CameraModule_3DKeyence::initParas(QByteArray& initData) { + QByteArrayList valueList = initData.split('#'); + if (valueList.size() < 6) { + qDebug() << "[Error] " << " Hd_CameraModule_HIK initParas fail--params error!参数数量不满足"; + lastError = "参数数量不满足"; + return false; + } EthernetConfig.wPortNo = 24691; - QByteArrayList valueList = initData.split('+'); - camera_name = valueList[0]; - //deviceId = valueList[0].toInt(); //相机头序号 - if (valueList.size() > 1) - for (int i = 0; i < valueList.size(); i++) - { - QString valuei = byteArrayToUnicode(valueList[i]); - if (valuei.contains("ip")) - { - //ip#192.168.0.1 - QStringList valueL = valuei.split("#"); - if (valueL.size() == 2) - { - QStringList valueL1 = valueL[1].split("."); - if (valueL1.size() == 4) - { - EthernetConfig.abyIpAddress[0] = valueL1.at(0).toInt(); - EthernetConfig.abyIpAddress[1] = valueL1.at(1).toInt(); - EthernetConfig.abyIpAddress[2] = valueL1.at(2).toInt(); - EthernetConfig.abyIpAddress[3] = valueL1.at(3).toInt(); - } - } - } - if (valuei.contains("deviceId")) - { - QStringList valueL = valuei.split('#'); - if (valueL.size() == 2) - { - deviceId = valueL[1].toInt(); - } - } - if (valuei.contains("port")) - { - //port#24691 - QStringList valueL = valuei.split('#'); - if (valueL.size() == 2) - { - EthernetConfig.wPortNo = valueL[1].toInt(); - } - } - if (valuei.contains("xImageSize")) - { - //xImageSize#1600 - QStringList valueL = valuei.split('#'); - if (valueL.size() == 2) - { - xImageSize = valueL[1].toInt(); - G_xImageSize = valueL[1].toInt(); - } - } - if (valuei.contains("yImageSize")) - { - //yImageSize#2000 - QStringList valueL = valuei.split('#'); - if (valueL.size() == 2) - { - yImageSize = valueL[1].toInt(); - G_yImageSize = valueL[1].toInt(); - } - } - if (valuei.contains("y_pitch_um")) - { - //y_pitch_um#40 - QStringList valueL = valuei.split('#'); - if (valueL.size() == 2) - { - y_pitch_um = valueL[1].toDouble(); - } - } - if (valuei.contains("imgTarget")) - { - QStringList valueL = valuei.split('#'); - if (valueL.size() == 2) - { - imgTarget = valueL[1].toInt(); - } - } - } + camera_name = valueList[0]; + auto valueL1 = valueList[0].split('.'); + if (valueL1.size() == 4) + { + EthernetConfig.abyIpAddress[0] = valueL1.at(0).toInt(); + EthernetConfig.abyIpAddress[1] = valueL1.at(1).toInt(); + EthernetConfig.abyIpAddress[2] = valueL1.at(2).toInt(); + EthernetConfig.abyIpAddress[3] = valueL1.at(3).toInt(); + } + + deviceId = valueList[1].toInt(); + + xImageSize = valueList[2].toInt(); + G_xImageSize = valueList[2].toInt(); + + yImageSize = valueList[3].toInt(); + G_yImageSize = valueList[3].toInt(); + + imgTarget = valueList[4].toInt(); + + getImageTimeOut = valueList[5].toInt(); yCounts = yImageSize; qDebug() << __FUNCTION__ << " line:" << __LINE__ << " camera_name:" << camera_name << " paras init is success!"; @@ -527,20 +478,22 @@ bool Hd_CameraModule_3DKeyence::run() { while (imgTakeNum != imgTarget) { - int timeOutCnt = 0; - while (_imageAvailable[deviceId] != 1 && timeOutCnt < 120) + int sleepMs = 10; + int cnt = 0; + int timeoutCnt = getImageTimeOut / sleepMs; + while (_imageAvailable[deviceId] != 1 ) { - timeOutCnt++; QThread::msleep(10); + if (cnt++ >= timeoutCnt) + { + heightMatS.push_back(cv::Mat(G_yImageSize, G_xImageSize, CV_8UC1, cv::Scalar(0, 0, 0))); + luminanceMatS.push_back(cv::Mat(G_yImageSize, G_xImageSize, CV_8UC1, cv::Scalar(0, 0, 0))); + imgTakeNum++; + qDebug() << "imgGetERROR insert blank img cameraID:" << camera_name; + continue; + } } - if (timeOutCnt >= 120) - { - heightMatS.push_back(cv::Mat(G_yImageSize, G_xImageSize, CV_8UC1, cv::Scalar(0, 0, 0))); - luminanceMatS.push_back(cv::Mat(G_yImageSize, G_xImageSize, CV_8UC1, cv::Scalar(0, 0, 0))); - imgTakeNum++; - qDebug() << "imgGetERROR insert blank img cameraID:" << camera_name; - continue; - } + std::lock_guard lock(bufferMutex); _getParam[deviceId].luminance_enabled = profileInfo_ptr->byLuminanceOutput; @@ -603,7 +556,7 @@ bool Hd_CameraModule_3DKeyence::run() _lastImageSizeHeight[deviceId] = 0; imgTakeNum++; } - qDebug() << "take2 Finish"; + qDebug() << camera_name <<"Finish"; return true; } catch (QString ev) diff --git a/subModule/Hd_CameraModule_3DKeyence/readme.txt b/subModule/Hd_CameraModule_3DKeyence/readme.txt new file mode 100644 index 0000000..7a69391 --- /dev/null +++ b/subModule/Hd_CameraModule_3DKeyence/readme.txt @@ -0,0 +1,3 @@ +基恩士3D相机 +初始化格式 IP#DEVICE-ID(手动按照初始化的顺序从0开始递增)#图像宽(X)#图像高(Y)#取图次数#超时时间 +192.168.31.1#0#3200#850#1#1000 \ No newline at end of file diff --git a/subModule/Hd_CameraModule_HIK_hard_GIGE/CMakeLists.txt b/subModule/Hd_CameraModule_HIK_General/CMakeLists.txt similarity index 100% rename from subModule/Hd_CameraModule_HIK_hard_GIGE/CMakeLists.txt rename to subModule/Hd_CameraModule_HIK_General/CMakeLists.txt diff --git a/subModule/Hd_CameraModule_HIK_General/Hd_CameraModule_HIK_General.cpp b/subModule/Hd_CameraModule_HIK_General/Hd_CameraModule_HIK_General.cpp new file mode 100644 index 0000000..aff70fc --- /dev/null +++ b/subModule/Hd_CameraModule_HIK_General/Hd_CameraModule_HIK_General.cpp @@ -0,0 +1,375 @@ +#include "Hd_CameraModule_HIK_General.h" +using namespace std; +#include +#include +#include +#include +#include +enum statusEnum { + CONNECTED, + RECONNECTING, + DISCONNECTED +}; +enum triggerModeEnum { + SOFTWARE, + HARDWARE, + EMPTY +}; +statusEnum cameraStatus = DISCONNECTED; +triggerModeEnum triggerMode = HARDWARE; +int getImageTimeOut = 3000; +bool runFlag = true; +//总取图数 +int imgIndex = 0; +MV_CC_DEVICE_INFO_LIST m_stDevList; // ch:设备信息列表结构体变量,用来存储设备列表 +string Username = ""; +int cameraIndex = -1; +QString lastError; +QQueue queuepic; +QMutex* n_mutex = new QMutex(); + +void* handle = NULL; +void CloseDevice(); + +//0106 断线重连 +void __stdcall ReconnectDevice(unsigned int nMsgType, void* pUser); +void __stdcall ImageCallBackEx(unsigned char* pData0, MV_FRAME_OUT_INFO_EX* pFrameInfo0, void* pUser0); +//搜索所有设备 +int SearchDevice(){ + + if (m_stDevList.nDeviceNum == 0) { + memset(&m_stDevList, 0, sizeof(MV_CC_DEVICE_INFO_LIST)); + // ch:枚举子网内所有设备 | en:Enumerate all devices within subnet + int nRet = MV_CC_EnumDevices(MV_GIGE_DEVICE | MV_USB_DEVICE, &m_stDevList); + if (MV_OK != nRet) + { + return -1; + } + } + for (int i = 0; i < m_stDevList.nDeviceNum; i++) + { + //SN + unsigned char* name = m_stDevList.pDeviceInfo[i]->SpecialInfo.stGigEInfo.chSerialNumber; + string userName = static_cast((LPCSTR)name); + if (Username == userName) + { + return i; + break; + } + + name = m_stDevList.pDeviceInfo[i]->SpecialInfo.stUsb3VInfo.chSerialNumber; + userName = static_cast((LPCSTR)name); + if (Username == userName) + { + return i; + break; + } + } + return -1; +} + +bool connectDevice() +{ + int cameraIndex = SearchDevice(); + if (cameraIndex == -1){ + //未匹配到相机 + qDebug() << "[Waring] " << "Hd_CameraModule_HIK not match --CameraName:" << QString::fromStdString(Username); + lastError = "找不到相机" + QString::fromStdString(Username); + return false; + } + if (handle != NULL) + { + MV_CC_StopGrabbing(handle); + MV_CC_CloseDevice(handle); + MV_CC_DestroyHandle(handle); + } + + //打开相机 + MV_CC_CreateHandle(&handle, m_stDevList.pDeviceInfo[cameraIndex]); + int nRet = MV_CC_OpenDevice(handle); + ////触发模式 + if(triggerMode == SOFTWARE) + { + MV_CC_SetEnumValue(handle, "TriggerMode", MV_TRIGGER_MODE_ON); + MV_CC_SetEnumValue(handle, "TriggerSource", MV_TRIGGER_SOURCE_SOFTWARE); + } + else if(triggerMode == HARDWARE) + { + MV_CC_SetEnumValue(handle, "TriggerMode", MV_TRIGGER_MODE_ON); + MV_CC_SetEnumValue(handle, "TriggerSource", MV_TRIGGER_SOURCE_LINE0); + } + + // //加载用户集,相机设置应当UserSet1 + nRet = MV_CC_SetEnumValueByString(handle, "UserSetSelector", "UserSet1"); + if (MV_OK != nRet)qDebug() << "Set UserSetSelector fail! nRet " << nRet; + // ch:注册抓图回调 | en:Register image callback + MV_CC_SetIntValueEx(handle, "GevHeartbeatTimeout", 3000);//心跳日志 + + nRet = MV_CC_RegisterImageCallBackEx(handle, ImageCallBackEx, handle);//注册回调 + if (MV_OK != nRet)return false; + nRet = MV_CC_RegisterExceptionCallBack(handle, ReconnectDevice, NULL);//断线重连 + if (MV_OK != nRet)return false; + + MV_CC_StartGrabbing(handle); + cameraStatus = CONNECTED; + return true; +} +void SetExposureTime(float exposureValue) +{ + qDebug() << "[INFO] " << "exposureValue:" << exposureValue; + MV_CC_SetEnumValue(handle, "ExposureAuto", MV_EXPOSURE_AUTO_MODE_OFF); + MV_CC_SetFloatValue(handle, "ExposureTime", exposureValue); +} + +void SetGain(float GainValue) +{ + qDebug() << "[INFO] " << "GainValue:" << GainValue; + MV_CC_SetEnumValue(handle, "GainAuto", 0); + MV_CC_SetFloatValue(handle, "Gain", GainValue); +} + +//断线重连 +void __stdcall ReconnectDevice(unsigned int nMsgType, void* pUser){ + + qDebug() << "[Error] " << " MV camera disconnects!"; + + if (nMsgType == MV_EXCEPTION_DEV_DISCONNECT && cameraStatus == CONNECTED){ + + cameraStatus = RECONNECTING; + // 启动后台线程负责重连,避免在回调线程中长时间阻塞 + std::thread([]() { + qDebug() << "[Info] start reconnect thread"; + + // 确保设备资源关闭 + CloseDevice(); + int times = 0; + while (runFlag) + { + qDebug() << "[Info] reconnect times:" << times++; + if (connectDevice()) + { + qWarning() << "[Hd_CameraModule_HIK] reconnect success!"; + cameraStatus = CONNECTED; + return; + } + + } + }).detach(); + } +} + +//回调函数; +//经测试,相机像素格式Mono8、RGB8是可以正常转换的,YUV422还需要优化;RGB8格式比YUV422帧率低;BGR格式会导致异色问题 +void __stdcall ImageCallBackEx(unsigned char* pData0, MV_FRAME_OUT_INFO_EX* pFrameInfo0, void* pUser0) +{ + Q_UNUSED(pUser0) + int frameNum = 0; + double time_Start = (double)clock(); + QMutexLocker locker(n_mutex); + cv::Mat srcImage = cv::Mat(); + //qDebug() << "[info]" << __FUNCTION__ << " line:" << __LINE__ << "--- start"; + if (pFrameInfo0) + { + //获取的是单通道灰度图 + if (pFrameInfo0->enPixelType == PixelType_Gvsp_Mono8)//获取当前采集到的图像格式 + { + srcImage = cv::Mat(pFrameInfo0->nHeight, pFrameInfo0->nWidth, CV_8UC1, pData0); + } + //获取的是RGB8图 + else if (pFrameInfo0->enPixelType == PixelType_Gvsp_BGR8_Packed) + { + srcImage = cv::Mat(pFrameInfo0->nHeight, pFrameInfo0->nWidth, CV_8UC3, pData0); + + //cvtColor(srcImage, srcImage, COLOR_RGB2BGR);//导致异色 + } + else if (IsColor(pFrameInfo0->enPixelType)) //其它格式彩色图 + { + MvGvspPixelType enDstPixelType = PixelType_Gvsp_Undefined; + enDstPixelType = PixelType_Gvsp_BGR8_Packed; + unsigned char* pConvertData = NULL; + pConvertData = (unsigned char*)malloc(pFrameInfo0->nWidth * pFrameInfo0->nHeight * 3); + if (NULL == pConvertData) + { + printf("malloc pConvertData fail!\n"); + } + else + { + unsigned int nConvertDataSize = 0; + nConvertDataSize = pFrameInfo0->nWidth * pFrameInfo0->nHeight * 3; + + // ch:像素格式转换 | en:Convert pixel format + MV_CC_PIXEL_CONVERT_PARAM stConvertParam = { 0 }; + + frameNum = pFrameInfo0->nFrameNum; //ch:帧号 | en:frame number + stConvertParam.nWidth = pFrameInfo0->nWidth; //ch:图像宽 | en:image width + stConvertParam.nHeight = pFrameInfo0->nHeight; //ch:图像高 | en:image height + stConvertParam.pSrcData = pData0; //ch:输入数据缓存 | en:input data buffer + stConvertParam.nSrcDataLen = pFrameInfo0->nFrameLen; //ch:输入数据大小 | en:input data size + stConvertParam.enSrcPixelType = pFrameInfo0->enPixelType; //ch:输入像素格式 | en:input pixel format + stConvertParam.enDstPixelType = enDstPixelType; //ch:输出像素格式 | en:output pixel format + stConvertParam.pDstBuffer = pConvertData; //ch:输出数据缓存 | en:output data buffer + stConvertParam.nDstBufferSize = nConvertDataSize; //ch:输出缓存大小 | en:output buffer size + int nRet = MV_CC_ConvertPixelType(handle, &stConvertParam); + + Mat mysrcImage = cv::Mat(pFrameInfo0->nHeight, pFrameInfo0->nWidth, CV_8UC3, stConvertParam.pDstBuffer); + mysrcImage.copyTo(srcImage); + + free(pConvertData); + pConvertData = NULL; + stConvertParam = { 0 }; + } + } + } + if (srcImage.empty()) + { + srcImage = cv::Mat(5, 5, CV_8UC1).setTo(0); + } + queuepic.push_back(srcImage); + pData0 = { 0 }; + double time_End = (double)clock(); + qDebug() << "[INFO] " << __FUNCTION__ << " line:" << __LINE__ << " checkImg getImg,Time:" << (time_End - time_Start) << "ms" + << "--CameraName:" << QString::fromStdString(Username) << " imgIndex:" << imgIndex << "nFrameNum : " << frameNum; +} + +//关闭设备 +void CloseDevice() +{ + + // 如果 handle 已经为空,直接返回 + if (handle == nullptr) + return; + + // 使用 SDK 正确的停止/关闭/销毁流程,避免使用 CloseHandle 等不匹配的 API + MV_CC_StopGrabbing(handle); + MV_CC_CloseDevice(handle); + MV_CC_DestroyHandle(handle); + handle = nullptr; +} + +Hd_CameraModule_HIK_General::~Hd_CameraModule_HIK_General() +{ + runFlag = false; + CloseDevice(); + if (n_mutex) + { + delete n_mutex; + n_mutex = nullptr; + } + + qDebug() << "[INFO] " << " delete success!"; +} +//从类中读数据到实例对象 +bool Hd_CameraModule_HIK_General::readData(std::vector& mat, QByteArray& data) +{ + if(data == "getStatus"){ + data = lastError.toUtf8(); + return true; + } + + if (queuepic.isEmpty()) + { + return false; + } + QMutexLocker locker(n_mutex); + cv::Mat img = queuepic.dequeue(); + mat.push_back(img); + + qDebug() << "[INFO] " << __FUNCTION__ << " line:" << __LINE__ << " checkImg readData--CameraName:" << QString::fromStdString(Username) << "--imgIndex : " << imgIndex; + return true; +} + +//实例对象把数据写入到类;加载模型后会运行此函数 +bool Hd_CameraModule_HIK_General::writeData(std::vector& mat, QByteArray& data) +{ + Q_UNUSED(mat); + if (data.contains("deviceList")) { + auto result = QByteArrayToMV_CC_DeviceInfoList(data.mid(10)); + if (result.nDeviceNum != 0) { + m_stDevList = result; + return true; + } + } + return true; +} +//传入initParas函数,格式为:相机key+参数名1#参数值1#参数值2+参数名2#参数值1... +bool Hd_CameraModule_HIK_General::initParas(QByteArray& initData) +{ + QByteArrayList valueList = initData.split('#'); + if (valueList.size() < 3) { + qDebug() << "[Error] " << " Hd_CameraModule_HIK initParas fail--params error!参数数量不满足"; + lastError = "参数数量不满足"; + return false; + } + Username = valueList[0]; + + auto triggerModeStr = valueList[1]; + if (triggerModeStr == "HARDWARE") + triggerMode = HARDWARE; + else if (triggerModeStr == "SOFTWARE") + triggerMode = SOFTWARE; + else if (triggerModeStr == "EMPTY") + triggerMode = EMPTY; + else { + qDebug() << "[Error] " << " Hd_CameraModule_HIK initParas fail--params error!触发模式参数错误"; + lastError = "触发模式参数错误"; + return false; + } + + getImageTimeOut = valueList[2].toInt(); + + imgIndex = 0; + return connectDevice(); +} + +bool Hd_CameraModule_HIK_General::run() +{ + qDebug() << "[INFO] " << " run start" << QString::fromStdString(Username); + if (triggerMode == SOFTWARE) + MV_CC_SetCommandValue(handle, "TriggerSoftware"); + try + { + int sleepMs = 10; + int cnt = 0; + int timeoutCnt = getImageTimeOut / sleepMs; + while (true) + { + QMutexLocker locker(n_mutex); + if (queuepic.size() > 0)return true; + if (cnt++ > timeoutCnt) { + queuepic.push_back(cv::Mat(200, 200, CV_8UC1, cv::Scalar(0))); //返回空图 + qDebug() << QString::fromStdString(Username) << "timeout" ; + return true; + } + QThread::msleep(sleepMs); + } + } + catch (QString ev) + { + qDebug() << "[Error] " << " ev:" << ev; + } + return true; +} + +//相机连接状态:正常连接或断开 +bool Hd_CameraModule_HIK_General::checkStatus() +{ + //status = moduleStatus; + return status; +} + + +Hd_CameraModule_HIK_General* create() +{ + qDebug() << "[INFO] " << "Hd_CameraModule_HIK create success!"; + return new Hd_CameraModule_HIK_General; +} + +void destory(Hd_CameraModule_HIK_General* ptr) +{ + if (ptr) + { + delete ptr; + ptr = nullptr; + } + qDebug() << "[INFO] " << "Hd_CameraModule_HIK destory success!"; +} \ No newline at end of file diff --git a/subModule/Hd_CameraModule_HIK_General/Hd_CameraModule_HIK_General.h b/subModule/Hd_CameraModule_HIK_General/Hd_CameraModule_HIK_General.h new file mode 100644 index 0000000..2483799 --- /dev/null +++ b/subModule/Hd_CameraModule_HIK_General/Hd_CameraModule_HIK_General.h @@ -0,0 +1,84 @@ +#ifndef Hd_CameraModule_HIK_General_H +#define Hd_CameraModule_HIK_General_H +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using namespace cv; +#pragma execution_character_set("utf-8") + +static MV_CC_DEVICE_INFO_LIST QByteArrayToMV_CC_DeviceInfoList(const QByteArray& byteArray) { + MV_CC_DEVICE_INFO_LIST deviceInfoList; + if (byteArray.size() == sizeof(MV_CC_DEVICE_INFO_LIST)) { + memcpy(&deviceInfoList, byteArray.constData(), sizeof(MV_CC_DEVICE_INFO_LIST)); + } + else { + qDebug() << "Invalid size of QByteArray for MV_CC_DEVICE_INFO_LIST!"; + } + return deviceInfoList; +} +bool IsColor(MvGvspPixelType enType) +{ + switch (enType) + { + case PixelType_Gvsp_RGB8_Packed: + case PixelType_Gvsp_YUV422_Packed: + case PixelType_Gvsp_YUV422_YUYV_Packed: + case PixelType_Gvsp_BayerGR8: + case PixelType_Gvsp_BayerRG8: + case PixelType_Gvsp_BayerGB8: + case PixelType_Gvsp_BayerBG8: + case PixelType_Gvsp_BayerGB10: + case PixelType_Gvsp_BayerGB10_Packed: + case PixelType_Gvsp_BayerBG10: + case PixelType_Gvsp_BayerBG10_Packed: + case PixelType_Gvsp_BayerRG10: + case PixelType_Gvsp_BayerRG10_Packed: + case PixelType_Gvsp_BayerGR10: + case PixelType_Gvsp_BayerGR10_Packed: + case PixelType_Gvsp_BayerGB12: + case PixelType_Gvsp_BayerGB12_Packed: + case PixelType_Gvsp_BayerBG12: + case PixelType_Gvsp_BayerBG12_Packed: + case PixelType_Gvsp_BayerRG12: + case PixelType_Gvsp_BayerRG12_Packed: + case PixelType_Gvsp_BayerGR12: + case PixelType_Gvsp_BayerGR12_Packed: + return true; + default: + return false; + } +} +class Hd_CameraModule_HIK_General :public dsModuleBase +{ +public: + Hd_CameraModule_HIK_General() {}; + virtual ~Hd_CameraModule_HIK_General(); + //从类中读数据到实例对象 + bool readData(std::vector& mat, QByteArray& data); + //实例对象把数据写入到类 + bool writeData(std::vector& mat, QByteArray& data); + bool initParas(QByteArray& initData); + bool run(); + bool checkStatus(); +private: + + //MyThread *m_thread = nullptr; + //QMutex* m_mutex; +}; + +extern "C" +{ +Q_DECL_EXPORT Hd_CameraModule_HIK_General * create(); +Q_DECL_EXPORT void destory(Hd_CameraModule_HIK_General * ptr); +} + +#endif // Hd_CameraModule_HIK_hard_H +//Hd_CameraModule_HIK_General diff --git a/subModule/Hd_CameraModule_HIK_General/readme.txt b/subModule/Hd_CameraModule_HIK_General/readme.txt new file mode 100644 index 0000000..ccb05c9 --- /dev/null +++ b/subModule/Hd_CameraModule_HIK_General/readme.txt @@ -0,0 +1,3 @@ +֧³ÖUSBÉ豸ºÍÍø¿ÚÉ豸£¬²»֧³ֲɼ¯¿¨É豸 +³õʼ»¯¸ñʽ "Ïà»úÐòÁкÅ#HARDWARE/SOFTWARE/EMPTY#ȡͼ³¬ʱʱ¼ä" +SAMPLE: Vir76210850#SOFTWARE#2000 \ No newline at end of file diff --git a/subModule/Hd_CameraModule_HIK_hard_PCIE/CMakeLists.txt b/subModule/Hd_CameraModule_HIK_PCIE/CMakeLists.txt similarity index 100% rename from subModule/Hd_CameraModule_HIK_hard_PCIE/CMakeLists.txt rename to subModule/Hd_CameraModule_HIK_PCIE/CMakeLists.txt diff --git a/subModule/Hd_CameraModule_HIK_PCIE/Hd_CameraModule_HIK_PCIE.cpp b/subModule/Hd_CameraModule_HIK_PCIE/Hd_CameraModule_HIK_PCIE.cpp new file mode 100644 index 0000000..677e85d --- /dev/null +++ b/subModule/Hd_CameraModule_HIK_PCIE/Hd_CameraModule_HIK_PCIE.cpp @@ -0,0 +1,380 @@ +#include "Hd_CameraModule_HIK_PCIE.h" +using namespace std; +#include +#include +#include +#include +#include +enum statusEnum { + CONNECTED, + RECONNECTING, + DISCONNECTED +}; +enum triggerModeEnum { + SOFTWARE, + HARDWARE, + EMPTY +}; +statusEnum cameraStatus = DISCONNECTED; +triggerModeEnum triggerMode = HARDWARE; +int getImageTimeOut = 3000; +bool runFlag = true; +//总取图数 +int imgIndex = 0; +MV_GENTL_DEV_INFO_LIST m_stDevList; // ch:设备信息列表结构体变量,用来存储设备列表 +MV_GENTL_IF_INFO_LIST m_stIFList; +string Username = ""; +int cameraIndex = -1; +QString lastError; +QQueue queuepic; +QMutex* n_mutex = new QMutex(); + +void* handle = NULL; +void CloseDevice(); + +//0106 断线重连 +void __stdcall ReconnectDevice(unsigned int nMsgType, void* pUser); +void __stdcall ImageCallBackEx(unsigned char* pData0, MV_FRAME_OUT_INFO_EX* pFrameInfo0, void* pUser0); +//搜索所有设备 +int SearchDevice(){ + + if (m_stIFList.nInterfaceNum != 0) { + const char* chCtiPath = "MvFGProducerXoF.cti";//.cti文件路径 + int nRet = 0; + nRet = MV_CC_EnumInterfacesByGenTL(&m_stIFList, chCtiPath); + if (nRet != MV_OK) + { + qDebug() << "EnumInterfacsByGenTL fail"; + return -1; + } + + } + if (m_stIFList.nInterfaceNum == 0) + { + qDebug() << "No Device"; + return -1; + } + int nRet = 0; + // ch:枚举子网内所有设备 | en:Enumerate all devices within subnet + for (int p = 0; p < m_stIFList.nInterfaceNum; p++) + { + memset(&m_stDevList, 0, sizeof(MV_CC_DEVICE_INFO_LIST)); + nRet = MV_CC_EnumDevicesByGenTL(m_stIFList.pIFInfo[p], &m_stDevList); + for (int i = 0; i < m_stDevList.nDeviceNum; i++) + { + //SN + unsigned char* name = m_stDevList.pDeviceInfo[i]->chSerialNumber; + string userName = static_cast((LPCSTR)name); + if (Username == userName) + { + return i; + } + } + } + if (MV_OK != nRet) + { + return -1; + } + return -1; +} + +bool connectDevice() +{ + int cameraIndex = SearchDevice(); + if (cameraIndex == -1) { + //未匹配到相机 + qDebug() << "[Waring] " << "Hd_CameraModule_HIK not match --CameraName:" << QString::fromStdString(Username); + lastError = "找不到相机" + QString::fromStdString(Username); + return false; + } + if (handle != NULL) + { + MV_CC_StopGrabbing(handle); + MV_CC_CloseDevice(handle); + MV_CC_DestroyHandle(handle); + } + + //打开相机 + MV_CC_CreateHandleByGenTL(&handle, m_stDevList.pDeviceInfo[cameraIndex]); + int nRet = MV_CC_OpenDevice(handle); + // //加载用户集,相机设置应当UserSet1 + nRet = MV_CC_SetEnumValueByString(handle, "UserSetSelector", "UserSet1"); + if (MV_OK != nRet) + { + qDebug() << "Set UserSetSelector fail! nRet " << nRet; + } + // ch:注册抓图回调 | en:Register image callback + MV_CC_SetIntValueEx(handle, "GevHeartbeatTimeout", 3000);//心跳日志 + + nRet = MV_CC_RegisterImageCallBackEx(handle, ImageCallBackEx, handle);//注册回调 + if (MV_OK != nRet) + return false; + nRet = MV_CC_RegisterExceptionCallBack(handle, ReconnectDevice, NULL);//断线重连 + if (MV_OK != nRet) + return false; + MV_CC_StartGrabbing(handle); + return true; +} +void SetExposureTime(float exposureValue) +{ + qDebug() << "[INFO] " << "exposureValue:" << exposureValue; + MV_CC_SetEnumValue(handle, "ExposureAuto", MV_EXPOSURE_AUTO_MODE_OFF); + MV_CC_SetFloatValue(handle, "ExposureTime", exposureValue); +} + +void SetGain(float GainValue) +{ + qDebug() << "[INFO] " << "GainValue:" << GainValue; + MV_CC_SetEnumValue(handle, "GainAuto", 0); + MV_CC_SetFloatValue(handle, "Gain", GainValue); +} + +void __stdcall ReconnectDevice(unsigned int nMsgType, void* pUser) { + + qDebug() << "[Error] " << " MV camera disconnects!"; + + if (nMsgType == MV_EXCEPTION_DEV_DISCONNECT && cameraStatus == CONNECTED) { + + cameraStatus = RECONNECTING; + // 启动后台线程负责重连,避免在回调线程中长时间阻塞 + std::thread([]() { + qDebug() << "[Info] start reconnect thread"; + + // 确保设备资源关闭 + CloseDevice(); + int times = 0; + while (runFlag) + { + qDebug() << "[Info] reconnect times:" << times++; + if (connectDevice()) + { + qWarning() << "[Hd_CameraModule_HIK] reconnect success!"; + cameraStatus = CONNECTED; + return; + } + + } + }).detach(); + } +} + + + +//回调函数; +//经测试,相机像素格式Mono8、RGB8是可以正常转换的,YUV422还需要优化;RGB8格式比YUV422帧率低;BGR格式会导致异色问题 +void __stdcall ImageCallBackEx(unsigned char* pData0, MV_FRAME_OUT_INFO_EX* pFrameInfo0, void* pUser0) +{ + Q_UNUSED(pUser0) + int frameNum = 0; + double time_Start = (double)clock(); + QMutexLocker locker(n_mutex); + cv::Mat srcImage = cv::Mat(); + //qDebug() << "[info]" << __FUNCTION__ << " line:" << __LINE__ << "--- start"; + if (pFrameInfo0) + { + //获取的是单通道灰度图 + if (pFrameInfo0->enPixelType == PixelType_Gvsp_Mono8)//获取当前采集到的图像格式 + { + srcImage = cv::Mat(pFrameInfo0->nHeight, pFrameInfo0->nWidth, CV_8UC1, pData0); + } + //获取的是RGB8图 + else if (pFrameInfo0->enPixelType == PixelType_Gvsp_BGR8_Packed) + { + srcImage = cv::Mat(pFrameInfo0->nHeight, pFrameInfo0->nWidth, CV_8UC3, pData0); + + //cvtColor(srcImage, srcImage, COLOR_RGB2BGR);//导致异色 + } + else if (IsColor(pFrameInfo0->enPixelType)) //其它格式彩色图 + { + MvGvspPixelType enDstPixelType = PixelType_Gvsp_Undefined; + enDstPixelType = PixelType_Gvsp_BGR8_Packed; + unsigned char* pConvertData = NULL; + pConvertData = (unsigned char*)malloc(pFrameInfo0->nWidth * pFrameInfo0->nHeight * 3); + if (NULL == pConvertData) + { + printf("malloc pConvertData fail!\n"); + } + else + { + unsigned int nConvertDataSize = 0; + nConvertDataSize = pFrameInfo0->nWidth * pFrameInfo0->nHeight * 3; + + // ch:像素格式转换 | en:Convert pixel format + MV_CC_PIXEL_CONVERT_PARAM stConvertParam = { 0 }; + + frameNum = pFrameInfo0->nFrameNum; //ch:帧号 | en:frame number + stConvertParam.nWidth = pFrameInfo0->nWidth; //ch:图像宽 | en:image width + stConvertParam.nHeight = pFrameInfo0->nHeight; //ch:图像高 | en:image height + stConvertParam.pSrcData = pData0; //ch:输入数据缓存 | en:input data buffer + stConvertParam.nSrcDataLen = pFrameInfo0->nFrameLen; //ch:输入数据大小 | en:input data size + stConvertParam.enSrcPixelType = pFrameInfo0->enPixelType; //ch:输入像素格式 | en:input pixel format + stConvertParam.enDstPixelType = enDstPixelType; //ch:输出像素格式 | en:output pixel format + stConvertParam.pDstBuffer = pConvertData; //ch:输出数据缓存 | en:output data buffer + stConvertParam.nDstBufferSize = nConvertDataSize; //ch:输出缓存大小 | en:output buffer size + int nRet = MV_CC_ConvertPixelType(handle, &stConvertParam); + + Mat mysrcImage = cv::Mat(pFrameInfo0->nHeight, pFrameInfo0->nWidth, CV_8UC3, stConvertParam.pDstBuffer); + mysrcImage.copyTo(srcImage); + + free(pConvertData); + pConvertData = NULL; + stConvertParam = { 0 }; + } + } + } + if (srcImage.empty()) + { + srcImage = cv::Mat(5, 5, CV_8UC1).setTo(0); + } + + queuepic.push_back(srcImage); + pData0 = { 0 }; + double time_End = (double)clock(); + qDebug() << "[INFO] " << __FUNCTION__ << " line:" << __LINE__ << " checkImg getImg,Time:" << (time_End - time_Start) << "ms" + << "--CameraName:" << QString::fromStdString(Username) << " imgIndex:" << imgIndex << "nFrameNum : " << frameNum; +} + +Hd_CameraModule_HIK_hard_PCIE::Hd_CameraModule_HIK_hard_PCIE() +{ + //m_thread = new MyThread; + //m_mutex = new QMutex(); +} +//关闭设备 +void CloseDevice() +{ + if (handle == nullptr) + return; + unsigned int nRet = MV_CC_StopGrabbing(handle); + if (nRet == 0) { + //MV_CC_CloseDevice(handle); + //MV_CC_DestroyHandle(handle); + } + //nRet = MV_CC_CloseDevice(handle); + //nRet = MV_CC_DestroyHandle(handle); +} +Hd_CameraModule_HIK_hard_PCIE::~Hd_CameraModule_HIK_hard_PCIE() +{ + CloseDevice(); + if (n_mutex) + { + delete n_mutex; + n_mutex = nullptr; + } + + qDebug() << "[INFO] " << " delete success!"; +} +//从类中读数据到实例对象 +bool Hd_CameraModule_HIK_hard_PCIE::readData(std::vector& mat, QByteArray& data) +{ + if (data == "getStatus") { + data = lastError.toUtf8(); + return true; + } + + if (queuepic.isEmpty()) + { + return false; + } + QMutexLocker locker(n_mutex); + cv::Mat img = queuepic.dequeue(); + mat.push_back(img); + + qDebug() << "[INFO] " << __FUNCTION__ << " line:" << __LINE__ << " checkImg readData--CameraName:" << QString::fromStdString(Username) << "--imgIndex : " << imgIndex; + return true; +} + +//实例对象把数据写入到类;加载模型后会运行此函数 +bool Hd_CameraModule_HIK_hard_PCIE::writeData(std::vector& mat, QByteArray& data) +{ + Q_UNUSED(mat); + if (data.contains("deviceList")) { + auto result = QByteArrayToMV_GENTL_IF_INFO_LIST(data.mid(10)); + if (result.nInterfaceNum != 0) { + m_stIFList = result; + return true; + } + } + return true; +} + +bool Hd_CameraModule_HIK_hard_PCIE::initParas(QByteArray& initData) +{ + QByteArrayList valueList = initData.split('#'); + if (valueList.size() < 3) { + qDebug() << "[Error] " << " Hd_CameraModule_HIK initParas fail--params error!参数数量不满足"; + lastError = "参数数量不满足"; + return false; + } + Username = valueList[0]; + + auto triggerModeStr = valueList[1]; + if (triggerModeStr == "HARDWARE") + triggerMode = HARDWARE; + else if (triggerModeStr == "SOFTWARE") + triggerMode = SOFTWARE; + else if (triggerModeStr == "EMPTY") + triggerMode = EMPTY; + else { + qDebug() << "[Error] " << " Hd_CameraModule_HIK initParas fail--params error!触发模式参数错误"; + lastError = "触发模式参数错误"; + return false; + } + + getImageTimeOut = valueList[2].toInt(); + + imgIndex = 0; + return connectDevice(); +} + +bool Hd_CameraModule_HIK_hard_PCIE::run() +{ + qDebug() << "[INFO] " << " run start" << QString::fromStdString(Username); + if (triggerMode == SOFTWARE) + MV_CC_SetCommandValue(handle, "TriggerSoftware"); + try + { + int sleepMs = 10; + int cnt = 0; + int timeoutCnt = getImageTimeOut / sleepMs; + while (true) + { + QMutexLocker locker(n_mutex); + if (queuepic.size() > 0)return true; + if (cnt++ > timeoutCnt) { + queuepic.push_back(cv::Mat(200, 200, CV_8UC1, cv::Scalar(0))); //返回空图 + qDebug() << QString::fromStdString(Username) << "timeout"; + return true; + } + QThread::msleep(sleepMs); + } + } + catch (QString ev) + { + qDebug() << "[Error] " << " ev:" << ev; + } + return true; +} + + +//相机连接状态:正常连接或断开 +bool Hd_CameraModule_HIK_hard_PCIE::checkStatus() +{ + //status = moduleStatus; + return status; +} + +Hd_CameraModule_HIK_hard_PCIE* create() +{ + qDebug() << "[INFO] " << "Hd_CameraModule_HIK create success!"; + return new Hd_CameraModule_HIK_hard_PCIE; +} + +void destory(Hd_CameraModule_HIK_hard_PCIE* ptr) +{ + if (ptr) + { + delete ptr; + ptr = nullptr; + } + qDebug() << "[INFO] " << "Hd_CameraModule_HIK destory success!"; +} \ No newline at end of file diff --git a/subModule/Hd_CameraModule_HIK_PCIE/Hd_CameraModule_HIK_PCIE.h b/subModule/Hd_CameraModule_HIK_PCIE/Hd_CameraModule_HIK_PCIE.h new file mode 100644 index 0000000..9dae2e6 --- /dev/null +++ b/subModule/Hd_CameraModule_HIK_PCIE/Hd_CameraModule_HIK_PCIE.h @@ -0,0 +1,84 @@ +#ifndef Hd_CameraModule_HIK_hard_PCIE_H +#define Hd_CameraModule_HIK_hard_PCIE_H +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using namespace cv; +#pragma execution_character_set("utf-8") +static MV_GENTL_IF_INFO_LIST QByteArrayToMV_GENTL_IF_INFO_LIST(const QByteArray& byteArray) { + MV_GENTL_IF_INFO_LIST deviceInfoList; + if (byteArray.size() == sizeof(MV_GENTL_IF_INFO_LIST)) { + memcpy(&deviceInfoList, byteArray.constData(), sizeof(MV_GENTL_IF_INFO_LIST)); + } + else { + qDebug() << "Invalid size of QByteArray for MV_GENTL_IF_INFO_LIST!"; + } + return deviceInfoList; +} +bool IsColor(MvGvspPixelType enType) +{ + switch (enType) + { + case PixelType_Gvsp_RGB8_Packed: + case PixelType_Gvsp_YUV422_Packed: + case PixelType_Gvsp_YUV422_YUYV_Packed: + case PixelType_Gvsp_BayerGR8: + case PixelType_Gvsp_BayerRG8: + case PixelType_Gvsp_BayerGB8: + case PixelType_Gvsp_BayerBG8: + case PixelType_Gvsp_BayerGB10: + case PixelType_Gvsp_BayerGB10_Packed: + case PixelType_Gvsp_BayerBG10: + case PixelType_Gvsp_BayerBG10_Packed: + case PixelType_Gvsp_BayerRG10: + case PixelType_Gvsp_BayerRG10_Packed: + case PixelType_Gvsp_BayerGR10: + case PixelType_Gvsp_BayerGR10_Packed: + case PixelType_Gvsp_BayerGB12: + case PixelType_Gvsp_BayerGB12_Packed: + case PixelType_Gvsp_BayerBG12: + case PixelType_Gvsp_BayerBG12_Packed: + case PixelType_Gvsp_BayerRG12: + case PixelType_Gvsp_BayerRG12_Packed: + case PixelType_Gvsp_BayerGR12: + case PixelType_Gvsp_BayerGR12_Packed: + return true; + default: + return false; + } +} +class Hd_CameraModule_HIK_hard_PCIE :public dsModuleBase +{ +public: + Hd_CameraModule_HIK_hard_PCIE(); + virtual ~Hd_CameraModule_HIK_hard_PCIE(); + //从类中读数据到实例对象 + bool readData(std::vector& mat, QByteArray& data); + //实例对象把数据写入到类 + bool writeData(std::vector& mat, QByteArray& data); + bool initParas(QByteArray& initData); + bool run(); + bool checkStatus(); +private: + std::vector imgShouldGetVec; + int imgShouldGetIndex = 0; + //MyThread *m_thread = nullptr; + //QMutex* m_mutex; +}; + +extern "C" +{ +Q_DECL_EXPORT Hd_CameraModule_HIK_hard_PCIE * create(); +Q_DECL_EXPORT void destory(Hd_CameraModule_HIK_hard_PCIE * ptr); +} + +#endif // Hd_CameraModule_HIK_hard_H +//Hd_CameraModule_HIK_hard_PCIE diff --git a/subModule/Hd_CameraModule_HIK_PCIE/readme.txt b/subModule/Hd_CameraModule_HIK_PCIE/readme.txt new file mode 100644 index 0000000..11cf21a --- /dev/null +++ b/subModule/Hd_CameraModule_HIK_PCIE/readme.txt @@ -0,0 +1,3 @@ +֧³ֲɼ¯¿¨Ïà»ú +³õʼ»¯¸ñʽ "Ïà»úÐòÁкÅ#HARDWARE/SOFTWARE/EMPTY#ȡͼ³¬ʱʱ¼ä" +SAMPLE: Vir76210850#SOFTWARE#2000 \ No newline at end of file diff --git a/subModule/Hd_CameraModule_HIK_hard_GIGE/Hd_CameraModule_HIK_hard_GIGE.cpp b/subModule/Hd_CameraModule_HIK_hard_GIGE/Hd_CameraModule_HIK_hard_GIGE.cpp deleted file mode 100644 index 3789fba..0000000 --- a/subModule/Hd_CameraModule_HIK_hard_GIGE/Hd_CameraModule_HIK_hard_GIGE.cpp +++ /dev/null @@ -1,593 +0,0 @@ -#include "Hd_CameraModule_HIK_hard_GIGE.h" -#include -using namespace std; -#include -#include -#include -#include -#include - -static std::atomic g_reconnecting(false); -static std::mutex g_reconnect_mutex; - -QByteArray mv_Status = "connected";//0106 新增相机断联报警 -long long index = 0; //相机序号 -void* handle; -string Username = ""; -bool m_flag = false; -//MV_CC_DEVICE_INFO_LIST m_stDevList;//相机设备 -bool moduleStatus = true; -QQueue queuepic; -//data == "rest_newProductIn"时要结束run;机台报警,取图超时,复位后重新拍的情况。 -bool ifBreak = false; -//ifRunning减少ifBreak的判断;"rest_newProductIn"时,Logic_camera_thread框架会结束未处理完的相相机取图 -bool ifRunning = false; - -MV_CC_DEVICE_INFO_LIST m_stDevList; // ch:设备信息列表结构体变量,用来存储设备列表 -//MV_GENTL_IF_INFO_LIST m_stIFList; -void CloseDevice(); -static MV_CC_DEVICE_INFO_LIST QByteArrayToMV_CC_DeviceInfoList(const QByteArray& byteArray) { - MV_CC_DEVICE_INFO_LIST deviceInfoList; - if (byteArray.size() == sizeof(MV_CC_DEVICE_INFO_LIST)) { - memcpy(&deviceInfoList, byteArray.constData(), sizeof(MV_CC_DEVICE_INFO_LIST)); - } - else { - qDebug() << "Invalid size of QByteArray for MV_CC_DEVICE_INFO_LIST!"; - } - return deviceInfoList; -} -QString byteArrayToUnicode(const QByteArray array) { - - // state用于保存转换状态,它的成员invalidChars,可用来判断是否转换成功 - // 如果转换成功,则值为0,如果值大于0,则说明转换失败 - QTextCodec::ConverterState state; - // 先尝试使用utf-8的方式把QByteArray转换成QString - QString text = QTextCodec::codecForName("UTF-8")->toUnicode(array.constData(), array.size(), &state); - // 如果转换时无效字符数量大于0,说明编码格式不对 - if (state.invalidChars > 0) - { - // 再尝试使用GBK的方式进行转换,一般就能转换正确(当然也可能是其它格式,但比较少见了) - text = QTextCodec::codecForName("GBK")->toUnicode(array); - } - return text; -} -QMutex* n_mutex = new QMutex(); -//cv::Mat srcImage; -//是否为标准通信流程: -//标准通信流程,run函数设置曝光/增益;非标准通信流程(简单通信流程),回调函数设置曝光/增益 -int imgCnt = 0; -bool ifStandard = false; -//相机取图超时时间 -int getImageTimeOut = 3000; -//总取图数 -int imgIndex = 0; -//曝光值列表 -QQueue expourseTimeList; -//增益列表 -QQueue gainList; - -bool IsColor(MvGvspPixelType enType) -{ - switch (enType) - { - case PixelType_Gvsp_RGB8_Packed: - case PixelType_Gvsp_YUV422_Packed: - case PixelType_Gvsp_YUV422_YUYV_Packed: - case PixelType_Gvsp_BayerGR8: - case PixelType_Gvsp_BayerRG8: - case PixelType_Gvsp_BayerGB8: - case PixelType_Gvsp_BayerBG8: - case PixelType_Gvsp_BayerGB10: - case PixelType_Gvsp_BayerGB10_Packed: - case PixelType_Gvsp_BayerBG10: - case PixelType_Gvsp_BayerBG10_Packed: - case PixelType_Gvsp_BayerRG10: - case PixelType_Gvsp_BayerRG10_Packed: - case PixelType_Gvsp_BayerGR10: - case PixelType_Gvsp_BayerGR10_Packed: - case PixelType_Gvsp_BayerGB12: - case PixelType_Gvsp_BayerGB12_Packed: - case PixelType_Gvsp_BayerBG12: - case PixelType_Gvsp_BayerBG12_Packed: - case PixelType_Gvsp_BayerRG12: - case PixelType_Gvsp_BayerRG12_Packed: - case PixelType_Gvsp_BayerGR12: - case PixelType_Gvsp_BayerGR12_Packed: - return true; - default: - return false; - } -} -//0106 断线重连 -void __stdcall ReconnectDevice(unsigned int nMsgType, void* pUser); -void __stdcall ImageCallBackEx(unsigned char* pData0, MV_FRAME_OUT_INFO_EX* pFrameInfo0, void* pUser0); -//搜索所有设备 -int SearchDevice() -{ - if (m_stDevList.nDeviceNum == 0) { - memset(&m_stDevList, 0, sizeof(MV_CC_DEVICE_INFO_LIST)); - // ch:枚举子网内所有设备 | en:Enumerate all devices within subnet - int nRet = MV_CC_EnumDevices(MV_GIGE_DEVICE | MV_USB_DEVICE, &m_stDevList); - if (MV_OK != nRet) - { - return 0; - } - } - for (int i = 0; i < m_stDevList.nDeviceNum; i++) - { - //SN - unsigned char* name = m_stDevList.pDeviceInfo[i]->SpecialInfo.stGigEInfo.chSerialNumber; - //userID - //unsigned char* name=m_stDevList.pDeviceInfo[i]->SpecialInfo.stGigEInfo.chUserDefinedName; - string userName = static_cast((LPCSTR)name); - if (Username == userName) - { - index = i; - break; - } - } - return -1; -} - -bool connectDevice() -{ - //MV_CC_Initialize(); - index = -1; - SearchDevice(); - if (index == -1) - { - //未匹配到相机 - //qDebug() << "[Waring] " << "Hd_CameraModule_HIK not match --CameraName:" << QString::fromStdString(Username); - return false; - } - unsigned char* name = m_stDevList.pDeviceInfo[index]->SpecialInfo.stGigEInfo.chUserDefinedName; - string userName = static_cast((LPCSTR)name); - qDebug() << "[INFO] " << " start" << "--UserName:" << QString::fromStdString(userName); - if (handle != NULL) - { - MV_CC_StopGrabbing(handle); - MV_CC_CloseDevice(handle); - MV_CC_DestroyHandle(handle); - } - - //打开相机 - MV_CC_CreateHandle(&handle, m_stDevList.pDeviceInfo[index]); - int nRet = MV_CC_OpenDevice(handle); - ////触发模式 - MV_CC_SetEnumValue(handle, "TriggerSource", MV_TRIGGER_SOURCE_LINE0); - MV_CC_SetEnumValue(handle, "TriggerMode", MV_TRIGGER_MODE_ON); - // //加载用户集,相机设置应当UserSet1 - nRet = MV_CC_SetEnumValueByString(handle, "UserSetSelector", "UserSet1"); - if (MV_OK != nRet) - { - qDebug() << "Set UserSetSelector fail! nRet " << nRet; - } - // ch:注册抓图回调 | en:Register image callback - MV_CC_SetIntValueEx(handle, "GevHeartbeatTimeout", 3000);//心跳日志 - - nRet = MV_CC_RegisterImageCallBackEx(handle, ImageCallBackEx, handle);//注册回调 - if (MV_OK != nRet) - return false; - nRet = MV_CC_RegisterExceptionCallBack(handle, ReconnectDevice, NULL);//断线重连 - if (MV_OK != nRet) - return false; - MV_CC_StartGrabbing(handle); - return true; -} -void SetExposureTime(float exposureValue) -{ - qDebug() << "[INFO] " << "exposureValue:" << exposureValue; - MV_CC_SetEnumValue(handle, "ExposureAuto", MV_EXPOSURE_AUTO_MODE_OFF); - MV_CC_SetFloatValue(handle, "ExposureTime", exposureValue); -} - -void SetGain(float GainValue) -{ - qDebug() << "[INFO] " << "GainValue:" << GainValue; - MV_CC_SetEnumValue(handle, "GainAuto", 0); - MV_CC_SetFloatValue(handle, "Gain", GainValue); -} - -//0518 断线重连 -void __stdcall ReconnectDevice(unsigned int nMsgType, void* pUser) -{ - mv_Status = "disconnect"; - qDebug() << "[Error] " << " MV camera disconnects!"; - moduleStatus = false; - - if (nMsgType == MV_EXCEPTION_DEV_DISCONNECT) - { - // 如果已有重连线程在运行,则直接返回 - bool expected = false; - if (!g_reconnecting.compare_exchange_strong(expected, true)) - { - qDebug() << "[Info] reconnect already in progress"; - return; - } - - // 启动后台线程负责重连,避免在回调线程中长时间阻塞 - std::thread([]() { - qDebug() << "[Info] start reconnect thread"; - - // 确保设备资源关闭 - CloseDevice(); - - int attempt = 0; - int delay_ms = 500; // 初始延迟 - while (true) - { - attempt++; - qDebug() << "[Info] reconnect attempt:" << attempt; - if (connectDevice()) - { - qWarning() << "[Hd_CameraModule_HIK] reconnect success!"; - moduleStatus = true; - mv_Status = "connected"; - g_reconnecting = false; - break; - } - - // 指数退避,最大 5000ms - std::this_thread::sleep_for(std::chrono::milliseconds(delay_ms)); - delay_ms = delay_ms * 2; - if (delay_ms > 5000) delay_ms = 5000; - - // 在某些场景可能希望退出重连(例如程序关闭),如果未来需要可增加退出条件 - } - }).detach(); - } -} - -//0106 断连提示 -void _stdcall ExceptionCB(unsigned int nMesgType, void* pUser) { - mv_Status = "disconnect"; - qDebug() << "[Error] " << " MvCameraTL disconnects!"; -} - - -Hd_CameraModule_HIK_hard_PCIE* create() -{ - qDebug() << "[INFO] " << "Hd_CameraModule_HIK create success!"; - return new Hd_CameraModule_HIK_hard_PCIE; -} - -void destory(Hd_CameraModule_HIK_hard_PCIE* ptr) -{ - if (ptr) - { - delete ptr; - ptr = nullptr; - } - qDebug() << "[INFO] " << "Hd_CameraModule_HIK destory success!"; -} - -//回调函数; -//经测试,相机像素格式Mono8、RGB8是可以正常转换的,YUV422还需要优化;RGB8格式比YUV422帧率低;BGR格式会导致异色问题 -void __stdcall ImageCallBackEx(unsigned char* pData0, MV_FRAME_OUT_INFO_EX* pFrameInfo0, void* pUser0) -{ - Q_UNUSED(pUser0) - int frameNum = 0; - double time_Start = (double)clock(); - n_mutex->lock(); - cv::Mat srcImage = cv::Mat(); - //qDebug() << "[info]" << __FUNCTION__ << " line:" << __LINE__ << "--- start"; - if (pFrameInfo0) - { - //获取的是单通道灰度图 - if (pFrameInfo0->enPixelType == PixelType_Gvsp_Mono8)//获取当前采集到的图像格式 - { - srcImage = cv::Mat(pFrameInfo0->nHeight, pFrameInfo0->nWidth, CV_8UC1, pData0); - } - //获取的是RGB8图 - else if (pFrameInfo0->enPixelType == PixelType_Gvsp_BGR8_Packed) - { - srcImage = cv::Mat(pFrameInfo0->nHeight, pFrameInfo0->nWidth, CV_8UC3, pData0); - - //cvtColor(srcImage, srcImage, COLOR_RGB2BGR);//导致异色 - } - else if (IsColor(pFrameInfo0->enPixelType)) //其它格式彩色图 - { - MvGvspPixelType enDstPixelType = PixelType_Gvsp_Undefined; - enDstPixelType = PixelType_Gvsp_BGR8_Packed; - unsigned char* pConvertData = NULL; - pConvertData = (unsigned char*)malloc(pFrameInfo0->nWidth * pFrameInfo0->nHeight * 3); - if (NULL == pConvertData) - { - printf("malloc pConvertData fail!\n"); - } - else - { - unsigned int nConvertDataSize = 0; - nConvertDataSize = pFrameInfo0->nWidth * pFrameInfo0->nHeight * 3; - - // ch:像素格式转换 | en:Convert pixel format - MV_CC_PIXEL_CONVERT_PARAM stConvertParam = { 0 }; - - frameNum = pFrameInfo0->nFrameNum; //ch:帧号 | en:frame number - stConvertParam.nWidth = pFrameInfo0->nWidth; //ch:图像宽 | en:image width - stConvertParam.nHeight = pFrameInfo0->nHeight; //ch:图像高 | en:image height - stConvertParam.pSrcData = pData0; //ch:输入数据缓存 | en:input data buffer - stConvertParam.nSrcDataLen = pFrameInfo0->nFrameLen; //ch:输入数据大小 | en:input data size - stConvertParam.enSrcPixelType = pFrameInfo0->enPixelType; //ch:输入像素格式 | en:input pixel format - stConvertParam.enDstPixelType = enDstPixelType; //ch:输出像素格式 | en:output pixel format - stConvertParam.pDstBuffer = pConvertData; //ch:输出数据缓存 | en:output data buffer - stConvertParam.nDstBufferSize = nConvertDataSize; //ch:输出缓存大小 | en:output buffer size - int nRet = MV_CC_ConvertPixelType(handle, &stConvertParam); - - Mat mysrcImage = cv::Mat(pFrameInfo0->nHeight, pFrameInfo0->nWidth, CV_8UC3, stConvertParam.pDstBuffer); - mysrcImage.copyTo(srcImage); - - free(pConvertData); - pConvertData = NULL; - stConvertParam = { 0 }; - } - } - } - if (srcImage.empty()) - { - srcImage = cv::Mat(5, 5, CV_8UC1).setTo(0); - } - if (ifStandard == false) - { - imgIndex++; - if (expourseTimeList.size() > 1 && expourseTimeList[imgIndex % expourseTimeList.size()] != expourseTimeList[(imgIndex - 1) % expourseTimeList.size()]) - SetExposureTime(expourseTimeList[imgIndex % expourseTimeList.size()]); - if (gainList.size() > 1 && gainList[imgIndex % gainList.size()] != gainList[(imgIndex - 1) % gainList.size()]) - SetGain(gainList[imgIndex % gainList.size()]); - } - queuepic.push_back(srcImage); - m_flag = true; - n_mutex->unlock(); - pData0 = { 0 }; - imgCnt++; - double time_End = (double)clock(); - std::cout << "[INFO] " << __FUNCTION__ << " line:" << __LINE__ << " checkImg getImg,Time:" << (time_End - time_Start) << "ms" - << "--CameraName:" << Username << " imgIndex:" << imgCnt << "nFrameNum : " << frameNum << std::endl; - qDebug() << "[INFO] " << __FUNCTION__ << " line:" << __LINE__ << " checkImg getImg,Time:" << (time_End - time_Start) << "ms" - << "--CameraName:" << QString::fromStdString(Username) << " imgIndex:" << imgCnt << "nFrameNum : " << frameNum; -} - -Hd_CameraModule_HIK_hard_PCIE::Hd_CameraModule_HIK_hard_PCIE() -{ - //m_thread = new MyThread; - //m_mutex = new QMutex(); -} -//关闭设备 -void CloseDevice() -{ - - // 如果 handle 已经为空,直接返回 - if (handle == nullptr) - return; - - // 使用 SDK 正确的停止/关闭/销毁流程,避免使用 CloseHandle 等不匹配的 API - MV_CC_StopGrabbing(handle); - MV_CC_CloseDevice(handle); - MV_CC_DestroyHandle(handle); - handle = nullptr; -} - -Hd_CameraModule_HIK_hard_PCIE::~Hd_CameraModule_HIK_hard_PCIE() -{ - CloseDevice(); - if (n_mutex) - { - delete n_mutex; - n_mutex = nullptr; - } - - qDebug() << "[INFO] " << " delete success!"; -} -//从类中读数据到实例对象 -bool Hd_CameraModule_HIK_hard_PCIE::readData(std::vector& mat, QByteArray& data) -{ - if (queuepic.isEmpty()) - { - //qCritical() << __FUNCTION__ << " line:" <<__LINE__ << " srcImage is null"; - return false; - } - n_mutex->lock(); - cv::Mat img = queuepic.dequeue(); - mat.push_back(img); - n_mutex->unlock(); - - qDebug() << "[INFO] " << __FUNCTION__ << " line:" << __LINE__ << " checkImg readData--CameraName:" << QString::fromStdString(Username) << "--imgIndex : " << imgIndex; - return true; -} - -//实例对象把数据写入到类;加载模型后会运行此函数 -bool Hd_CameraModule_HIK_hard_PCIE::writeData(std::vector& mat, QByteArray& data) -{ - Q_UNUSED(mat); - if (data.contains("deviceList")) { - auto result = QByteArrayToMV_CC_DeviceInfoList(data.mid(10)); - if (result.nDeviceNum != 0) { - m_stDevList = result; - return true; - } - } - QStringList dataList = QString::fromUtf8(data).split("_"); - //2024.02.18更新,相机对应的读SN信号时,表示新产品进入,设置初始值 - if (data == "rest_newProductIn") - { - //根据实际项目,设置初始值:曝光、增益,ROI区域等 - { - if (expourseTimeList.size() > 0) - SetExposureTime(expourseTimeList[0]); - if (gainList.size() > 0) - SetGain(gainList[0]); - } - if (queuepic.size() > 0) - { - n_mutex->lock(); - //queuepic.clear(); - n_mutex->unlock(); - std::cout << "rest_newProductIn , queuePic.size() > 0 ,signal maybe too fast " << Username << std::endl; - qWarning() << __FUNCTION__ << " line: " << __LINE__ << "rest_newProductIn , queuePic.size() > 0 ,signal maybe too fast " << QString::fromStdString(Username); - } - if (ifRunning == true) - { - ifBreak = true; - Sleep(10); - } - imgIndex = 0; - return true; - } - else if (dataList.size() > 1) { - if (dataList[0] == "cameraTriggerSignal") { - imgShouldGetVec.clear(); - imgShouldGetIndex = 0; - for (int i = 1; i < dataList.size(); i++) - imgShouldGetVec.push_back(dataList[i].toInt()); - } - } - else - { - m_flag = false; - expourseTimeList.clear(); - gainList.clear(); - } - //Username= data.toStdString(); - return true; -} -//传入initParas函数,格式为:相机key+参数名1#参数值1#参数值2+参数名2#参数值1... -bool Hd_CameraModule_HIK_hard_PCIE::initParas(QByteArray& initData) -{ - QByteArrayList valueList = initData.split('+'); - Username = valueList[0]; - imgIndex = 0; - expourseTimeList.clear(); - gainList.clear(); - if (valueList.size() > 1) - for (int i = 1; i < valueList.size(); i++) - { - QString valuei = byteArrayToUnicode(valueList[i]); - //valuei.prepend(valueList[i]); - if (valuei.contains("expourseTime")) - { - QStringList expourseTimeL = valuei.split('#'); - if (expourseTimeL.size() > 1) - for (int j = 1; j < expourseTimeL.size(); j++) - expourseTimeList.enqueue(expourseTimeL[j].toFloat()); - } - if (valuei.contains("gain")) - { - QStringList gainL = valuei.split('#'); - if (gainL.size() > 1) - for (int j = 1; j < gainL.size(); j++) - gainList.enqueue(gainL[j].toFloat()); - } - - if (valuei.contains("是否为标准通信流程")) - { - if (valuei.contains("true")) - ifStandard = true; - } - if (valuei.contains("取图超时")) - { - QStringList gainL = valuei.split('#'); - if (gainL.size() > 1) - getImageTimeOut = gainL[1].toInt(); - if (getImageTimeOut < 50) - getImageTimeOut = 1000; - } - if (valuei.contains("OffsetX")) - { - QStringList valueL = valuei.split('#'); - if (valueL.size() > 1) - if (valueL[1].toInt() >= 0) - MV_CC_SetIntValue(handle, "OffsetX", valueL[1].toInt()); - } - if (valuei.contains("OffsetY")) - { - QStringList valueL = valuei.split('#'); - if (valueL.size() > 1) - if (valueL[1].toInt() >= 0) - MV_CC_SetIntValue(handle, "OffsetY", valueL[1].toInt()); - } - if (valuei.contains("Width")) - { - QStringList valueL = valuei.split('#'); - if (valueL.size() > 1) - if (valueL[1].toInt() >= 0) - MV_CC_SetIntValue(handle, "Width", valueL[1].toInt()); - } - if (valuei.contains("Height")) - { - QStringList valueL = valuei.split('#'); - if (valueL.size() > 1) - if (valueL[1].toInt() >= 0) - MV_CC_SetIntValue(handle, "Height", valueL[1].toInt()); - } - } - - bool ifOk = connectDevice(); - if (ifOk == true) - { - if (expourseTimeList.size() > 0) - SetExposureTime(expourseTimeList[0]); - if (gainList.size() > 0) - SetGain(gainList[0]); - } - imgIndex = 0; - return ifOk; -} - -bool Hd_CameraModule_HIK_hard_PCIE::run() -{ - //queuepic.clear(); - qDebug() << "[INFO] " << " run start" << QString::fromStdString(Username); - bool result = false; - ifRunning = true; - ifBreak = false; - //MV_CC_SetCommandValue(handle, "TriggerSoftware"); - try - { - m_flag = false; - int mytime = 0; - int cnt = 0; - while (true) - { - n_mutex->lock(); - cnt++; - if (queuepic.size() > 0) - { - n_mutex->unlock(); - result = true; - break; - } - if (cnt > 120) { - queuepic.push_back(cv::Mat(200, 200, CV_8UC1, cv::Scalar(0))); //返回空图 - std::cout << "timeout" << std::endl; - n_mutex->unlock(); - return true; - } - n_mutex->unlock(); - QThread::msleep(10); - } - //考虑到误触发、漏触发的图,在这里进行设置。 - //需要设置曝光时 - if (ifStandard == true) - { - imgIndex++; - if (expourseTimeList.size() > 1 && expourseTimeList[imgIndex % expourseTimeList.size()] != expourseTimeList[(imgIndex - 1) % expourseTimeList.size()]) - SetExposureTime(expourseTimeList[imgIndex % expourseTimeList.size()]); - if (gainList.size() > 1 && gainList[imgIndex % gainList.size()] != gainList[(imgIndex - 1) % gainList.size()]) - SetGain(gainList[imgIndex % gainList.size()]); - } - } - catch (QString ev) - { - qDebug() << "[Error] " << " ev:" << ev; - } - qDebug() << "[INFO] " << __LINE__ << " run end"; - return result; -} - -//相机连接状态:正常连接或断开 -bool Hd_CameraModule_HIK_hard_PCIE::checkStatus() -{ - //status = moduleStatus; - return moduleStatus; -} - diff --git a/subModule/Hd_CameraModule_HIK_hard_GIGE/Hd_CameraModule_HIK_hard_GIGE.h b/subModule/Hd_CameraModule_HIK_hard_GIGE/Hd_CameraModule_HIK_hard_GIGE.h deleted file mode 100644 index 5bf23b2..0000000 --- a/subModule/Hd_CameraModule_HIK_hard_GIGE/Hd_CameraModule_HIK_hard_GIGE.h +++ /dev/null @@ -1,43 +0,0 @@ -#ifndef Hd_CameraModule_HIK_hard_PCIE_H -#define Hd_CameraModule_HIK_hard_PCIE_H -#include -#include -#include -#include -#include -#include -#include -#include - -#include - -using namespace cv; -#pragma execution_character_set("utf-8") - -class Hd_CameraModule_HIK_hard_PCIE :public dsModuleBase -{ -public: - Hd_CameraModule_HIK_hard_PCIE(); - virtual ~Hd_CameraModule_HIK_hard_PCIE(); - //从类中读数据到实例对象 - bool readData(std::vector& mat, QByteArray& data); - //实例对象把数据写入到类 - bool writeData(std::vector& mat, QByteArray& data); - bool initParas(QByteArray& initData); - bool run(); - bool checkStatus(); -private: - std::vector imgShouldGetVec; - int imgShouldGetIndex = 0; - //MyThread *m_thread = nullptr; - //QMutex* m_mutex; -}; - -extern "C" -{ -Q_DECL_EXPORT Hd_CameraModule_HIK_hard_PCIE * create(); -Q_DECL_EXPORT void destory(Hd_CameraModule_HIK_hard_PCIE * ptr); -} - -#endif // Hd_CameraModule_HIK_hard_H -//Hd_CameraModule_HIK_hard_PCIE diff --git a/subModule/Hd_CameraModule_HIK_hard_PCIE/Hd_CameraModule_HIK_hard_PCIE.cpp b/subModule/Hd_CameraModule_HIK_hard_PCIE/Hd_CameraModule_HIK_hard_PCIE.cpp deleted file mode 100644 index 1abe4b2..0000000 --- a/subModule/Hd_CameraModule_HIK_hard_PCIE/Hd_CameraModule_HIK_hard_PCIE.cpp +++ /dev/null @@ -1,571 +0,0 @@ -#include "Hd_CameraModule_HIK_hard_PCIE.h" -#include -using namespace std; -#include -QByteArray mv_Status = "connected";//0106 新增相机断联报警 -long long index = 0; //相机序号 -void* handle; -string Username = ""; -bool m_flag = false; -//MV_CC_DEVICE_INFO_LIST m_stDevList;//相机设备 -bool moduleStatus = true; -QQueue queuepic; -//data == "rest_newProductIn"时要结束run;机台报警,取图超时,复位后重新拍的情况。 -bool ifBreak = false; -//ifRunning减少ifBreak的判断;"rest_newProductIn"时,Logic_camera_thread框架会结束未处理完的相相机取图 -bool ifRunning = false; - -MV_GENTL_DEV_INFO_LIST m_stDevList; // ch:设备信息列表结构体变量,用来存储设备列表 -MV_GENTL_IF_INFO_LIST m_stIFList; -void CloseDevice(); -QString byteArrayToUnicode(const QByteArray array) { - - // state用于保存转换状态,它的成员invalidChars,可用来判断是否转换成功 - // 如果转换成功,则值为0,如果值大于0,则说明转换失败 - QTextCodec::ConverterState state; - // 先尝试使用utf-8的方式把QByteArray转换成QString - QString text = QTextCodec::codecForName("UTF-8")->toUnicode(array.constData(), array.size(), &state); - // 如果转换时无效字符数量大于0,说明编码格式不对 - if (state.invalidChars > 0) - { - // 再尝试使用GBK的方式进行转换,一般就能转换正确(当然也可能是其它格式,但比较少见了) - text = QTextCodec::codecForName("GBK")->toUnicode(array); - } - return text; -} -QMutex* n_mutex = new QMutex(); -//cv::Mat srcImage; -//是否为标准通信流程: -//标准通信流程,run函数设置曝光/增益;非标准通信流程(简单通信流程),回调函数设置曝光/增益 -int imgCnt = 0; -bool ifStandard = false; -//相机取图超时时间 -int getImageTimeOut = 3000; -//总取图数 -int imgIndex = 0; -//曝光值列表 -QQueue expourseTimeList; -//增益列表 -QQueue gainList; - -bool IsColor(MvGvspPixelType enType) -{ - switch (enType) - { - case PixelType_Gvsp_RGB8_Packed: - case PixelType_Gvsp_YUV422_Packed: - case PixelType_Gvsp_YUV422_YUYV_Packed: - case PixelType_Gvsp_BayerGR8: - case PixelType_Gvsp_BayerRG8: - case PixelType_Gvsp_BayerGB8: - case PixelType_Gvsp_BayerBG8: - case PixelType_Gvsp_BayerGB10: - case PixelType_Gvsp_BayerGB10_Packed: - case PixelType_Gvsp_BayerBG10: - case PixelType_Gvsp_BayerBG10_Packed: - case PixelType_Gvsp_BayerRG10: - case PixelType_Gvsp_BayerRG10_Packed: - case PixelType_Gvsp_BayerGR10: - case PixelType_Gvsp_BayerGR10_Packed: - case PixelType_Gvsp_BayerGB12: - case PixelType_Gvsp_BayerGB12_Packed: - case PixelType_Gvsp_BayerBG12: - case PixelType_Gvsp_BayerBG12_Packed: - case PixelType_Gvsp_BayerRG12: - case PixelType_Gvsp_BayerRG12_Packed: - case PixelType_Gvsp_BayerGR12: - case PixelType_Gvsp_BayerGR12_Packed: - return true; - default: - return false; - } -} -//0106 断线重连 -void __stdcall ReconnectDevice(unsigned int nMsgType, void* pUser); -void __stdcall ImageCallBackEx(unsigned char* pData0, MV_FRAME_OUT_INFO_EX* pFrameInfo0, void* pUser0); -//搜索所有设备 -int SearchDevice() -{ - //MV_CC_Initialize(); - /* MV_CC_DEVICE_INFO_LIST stDeviceList; - memset(&stDeviceList, 0, sizeof(MV_CC_DEVICE_INFO_LIST)); - unsigned int nnRet = MV_CC_EnumDevices(MV_GIGE_DEVICE | MV_USB_DEVICE | MV_GENTL_CAMERALINK_DEVICE | MV_GENTL_CXP_DEVICE | MV_GENTL_XOF_DEVICE, &stDeviceList); - return 1;*/ - const char* chCtiPath = "MvFGProducerXoF.cti";//.cti文件路径 - int nRet = 0; - nRet = MV_CC_EnumInterfacesByGenTL(&m_stIFList, chCtiPath); - if (nRet != MV_OK) - { - qDebug() << "EnumInterfacsByGenTL fail"; - return 0; - } - - if (m_stIFList.nInterfaceNum == 0) - { - qDebug() << "No Device"; - return 0; - } - - // ch:枚举子网内所有设备 | en:Enumerate all devices within subnet - for (int p = 0; p < m_stIFList.nInterfaceNum; p++) - { - memset(&m_stDevList, 0, sizeof(MV_CC_DEVICE_INFO_LIST)); - nRet = MV_CC_EnumDevicesByGenTL(m_stIFList.pIFInfo[p], &m_stDevList); - bool ifHas = false; - for (int i = 0; i < m_stDevList.nDeviceNum; i++) - { - //SN - unsigned char* name = m_stDevList.pDeviceInfo[i]->chSerialNumber; - string userName = static_cast((LPCSTR)name); - if (Username == userName) - { - index = i; - ifHas = true; - break; - } - } - if (ifHas)break; - } - if (MV_OK != nRet) - { - return 0; - } - return -1; -} - -bool connectDevice() -{ - //MV_CC_Initialize(); - index = -1; - SearchDevice(); - if (index == -1) - { - //未匹配到相机 - //qDebug() << "[Waring] " << "Hd_CameraModule_HIK not match --CameraName:" << QString::fromStdString(Username); - return false; - } - unsigned char* name = m_stDevList.pDeviceInfo[index]->chSerialNumber; - string userName = static_cast((LPCSTR)name); - qDebug() << "[INFO] " << " start" << "--UserName:" << QString::fromStdString(userName); - if (handle != NULL) - { - MV_CC_StopGrabbing(handle); - MV_CC_CloseDevice(handle); - MV_CC_DestroyHandle(handle); - } - - //打开相机 - MV_CC_CreateHandleByGenTL(&handle, m_stDevList.pDeviceInfo[index]); - int nRet = MV_CC_OpenDevice(handle); - ////触发模式 - //MV_CC_SetEnumValue(handle, "TriggerSource", MV_TRIGGER_SOURCE_LINE0); - //MV_CC_SetEnumValue(handle, "TriggerMode", MV_TRIGGER_MODE_ON); - // //加载用户集,相机设置应当UserSet1 - nRet = MV_CC_SetEnumValueByString(handle, "UserSetSelector", "UserSet1"); - if (MV_OK != nRet) - { - qDebug() << "Set UserSetSelector fail! nRet " << nRet; - } - // ch:注册抓图回调 | en:Register image callback - MV_CC_SetIntValueEx(handle, "GevHeartbeatTimeout", 3000);//心跳日志 - - nRet = MV_CC_RegisterImageCallBackEx(handle, ImageCallBackEx, handle);//注册回调 - if (MV_OK != nRet) - return false; - nRet = MV_CC_RegisterExceptionCallBack(handle, ReconnectDevice, NULL);//断线重连 - if (MV_OK != nRet) - return false; - MV_CC_StartGrabbing(handle); - return true; -} -void SetExposureTime(float exposureValue) -{ - qDebug() << "[INFO] " << "exposureValue:" << exposureValue; - MV_CC_SetEnumValue(handle, "ExposureAuto", MV_EXPOSURE_AUTO_MODE_OFF); - MV_CC_SetFloatValue(handle, "ExposureTime", exposureValue); -} - -void SetGain(float GainValue) -{ - qDebug() << "[INFO] " << "GainValue:" << GainValue; - MV_CC_SetEnumValue(handle, "GainAuto", 0); - MV_CC_SetFloatValue(handle, "Gain", GainValue); -} - -//0518 断线重连 -void __stdcall ReconnectDevice(unsigned int nMsgType, void* pUser) -{ - mv_Status = "disconnect"; - std::cout << "相机重连中..." << std::endl; - qDebug() << "[Error] " << " MV camera disconnects!"; - moduleStatus = false; - if (nMsgType == MV_EXCEPTION_DEV_DISCONNECT) - { - //断开连接 - CloseDevice(); - handle = nullptr; - BOOL bConnected = FALSE; - while (1) - { - Sleep(100); - if (connectDevice() == true) - { - qWarning() << "[Hd_CameraModule_HIK] " << " Hd_CameraModule_HIK create success again! "; - moduleStatus = true; - break; - } - - } - } -} - -//0106 断连提示 -void _stdcall ExceptionCB(unsigned int nMesgType, void* pUser) { - mv_Status = "disconnect"; - qDebug() << "[Error] " << " MvCameraTL disconnects!"; -} - - -Hd_CameraModule_HIK_hard_PCIE* create() -{ - qDebug() << "[INFO] " << "Hd_CameraModule_HIK create success!"; - return new Hd_CameraModule_HIK_hard_PCIE; -} - -void destory(Hd_CameraModule_HIK_hard_PCIE* ptr) -{ - if (ptr) - { - delete ptr; - ptr = nullptr; - } - qDebug() << "[INFO] " << "Hd_CameraModule_HIK destory success!"; -} - -//回调函数; -//经测试,相机像素格式Mono8、RGB8是可以正常转换的,YUV422还需要优化;RGB8格式比YUV422帧率低;BGR格式会导致异色问题 -void __stdcall ImageCallBackEx(unsigned char* pData0, MV_FRAME_OUT_INFO_EX* pFrameInfo0, void* pUser0) -{ - Q_UNUSED(pUser0) - int frameNum = 0; - double time_Start = (double)clock(); - n_mutex->lock(); - cv::Mat srcImage = cv::Mat(); - //qDebug() << "[info]" << __FUNCTION__ << " line:" << __LINE__ << "--- start"; - if (pFrameInfo0) - { - //获取的是单通道灰度图 - if (pFrameInfo0->enPixelType == PixelType_Gvsp_Mono8)//获取当前采集到的图像格式 - { - srcImage = cv::Mat(pFrameInfo0->nHeight, pFrameInfo0->nWidth, CV_8UC1, pData0); - } - //获取的是RGB8图 - else if (pFrameInfo0->enPixelType == PixelType_Gvsp_BGR8_Packed) - { - srcImage = cv::Mat(pFrameInfo0->nHeight, pFrameInfo0->nWidth, CV_8UC3, pData0); - - //cvtColor(srcImage, srcImage, COLOR_RGB2BGR);//导致异色 - } - else if (IsColor(pFrameInfo0->enPixelType)) //其它格式彩色图 - { - MvGvspPixelType enDstPixelType = PixelType_Gvsp_Undefined; - enDstPixelType = PixelType_Gvsp_BGR8_Packed; - unsigned char* pConvertData = NULL; - pConvertData = (unsigned char*)malloc(pFrameInfo0->nWidth * pFrameInfo0->nHeight * 3); - if (NULL == pConvertData) - { - printf("malloc pConvertData fail!\n"); - } - else - { - unsigned int nConvertDataSize = 0; - nConvertDataSize = pFrameInfo0->nWidth * pFrameInfo0->nHeight * 3; - - // ch:像素格式转换 | en:Convert pixel format - MV_CC_PIXEL_CONVERT_PARAM stConvertParam = { 0 }; - - frameNum = pFrameInfo0->nFrameNum; //ch:帧号 | en:frame number - stConvertParam.nWidth = pFrameInfo0->nWidth; //ch:图像宽 | en:image width - stConvertParam.nHeight = pFrameInfo0->nHeight; //ch:图像高 | en:image height - stConvertParam.pSrcData = pData0; //ch:输入数据缓存 | en:input data buffer - stConvertParam.nSrcDataLen = pFrameInfo0->nFrameLen; //ch:输入数据大小 | en:input data size - stConvertParam.enSrcPixelType = pFrameInfo0->enPixelType; //ch:输入像素格式 | en:input pixel format - stConvertParam.enDstPixelType = enDstPixelType; //ch:输出像素格式 | en:output pixel format - stConvertParam.pDstBuffer = pConvertData; //ch:输出数据缓存 | en:output data buffer - stConvertParam.nDstBufferSize = nConvertDataSize; //ch:输出缓存大小 | en:output buffer size - int nRet = MV_CC_ConvertPixelType(handle, &stConvertParam); - - Mat mysrcImage = cv::Mat(pFrameInfo0->nHeight, pFrameInfo0->nWidth, CV_8UC3, stConvertParam.pDstBuffer); - mysrcImage.copyTo(srcImage); - - free(pConvertData); - pConvertData = NULL; - stConvertParam = { 0 }; - } - } - } - if (srcImage.empty()) - { - srcImage = cv::Mat(5, 5, CV_8UC1).setTo(0); - } - if (ifStandard == false) - { - imgIndex++; - if (expourseTimeList.size() > 1 && expourseTimeList[imgIndex % expourseTimeList.size()] != expourseTimeList[(imgIndex - 1) % expourseTimeList.size()]) - SetExposureTime(expourseTimeList[imgIndex % expourseTimeList.size()]); - if (gainList.size() > 1 && gainList[imgIndex % gainList.size()] != gainList[(imgIndex - 1) % gainList.size()]) - SetGain(gainList[imgIndex % gainList.size()]); - } - queuepic.push_back(srcImage); - m_flag = true; - n_mutex->unlock(); - pData0 = { 0 }; - imgCnt++; - double time_End = (double)clock(); - std::cout << "[INFO] " << __FUNCTION__ << " line:" << __LINE__ << " checkImg getImg,Time:" << (time_End - time_Start) << "ms" - << "--CameraName:" << Username << " imgIndex:" << imgCnt << "nFrameNum : " << frameNum << std::endl; - qDebug() << "[INFO] " << __FUNCTION__ << " line:" << __LINE__ << " checkImg getImg,Time:" << (time_End - time_Start) << "ms" - << "--CameraName:" << QString::fromStdString(Username) << " imgIndex:" << imgCnt << "nFrameNum : " << frameNum; -} - -Hd_CameraModule_HIK_hard_PCIE::Hd_CameraModule_HIK_hard_PCIE() -{ - //m_thread = new MyThread; - //m_mutex = new QMutex(); -} -//关闭设备 -void CloseDevice() -{ - if (handle == nullptr) - return; - unsigned int nRet = MV_CC_StopGrabbing(handle); - if (nRet == 0) { - //MV_CC_CloseDevice(handle); - //MV_CC_DestroyHandle(handle); - } - //nRet = MV_CC_CloseDevice(handle); - //nRet = MV_CC_DestroyHandle(handle); -} -Hd_CameraModule_HIK_hard_PCIE::~Hd_CameraModule_HIK_hard_PCIE() -{ - CloseDevice(); - if (n_mutex) - { - delete n_mutex; - n_mutex = nullptr; - } - - qDebug() << "[INFO] " << " delete success!"; -} -//从类中读数据到实例对象 -bool Hd_CameraModule_HIK_hard_PCIE::readData(std::vector& mat, QByteArray& data) -{ - if (queuepic.isEmpty()) - { - //qCritical() << __FUNCTION__ << " line:" <<__LINE__ << " srcImage is null"; - return false; - } - n_mutex->lock(); - cv::Mat img = queuepic.dequeue(); - mat.push_back(img); - queuepic.clear(); - n_mutex->unlock(); - - qDebug() << "[INFO] " << __FUNCTION__ << " line:" << __LINE__ << " checkImg readData--CameraName:" << QString::fromStdString(Username) << "--imgIndex : " << imgIndex; - return true; -} - -//实例对象把数据写入到类;加载模型后会运行此函数 -bool Hd_CameraModule_HIK_hard_PCIE::writeData(std::vector& mat, QByteArray& data) -{ - Q_UNUSED(mat); - QStringList dataList = QString::fromUtf8(data).split("_"); - //2024.02.18更新,相机对应的读SN信号时,表示新产品进入,设置初始值 - if (data == "rest_newProductIn") - { - //根据实际项目,设置初始值:曝光、增益,ROI区域等 - { - if (expourseTimeList.size() > 0) - SetExposureTime(expourseTimeList[0]); - if (gainList.size() > 0) - SetGain(gainList[0]); - } - if (queuepic.size() > 0) - { - n_mutex->lock(); - queuepic.clear(); - n_mutex->unlock(); - std::cout << "rest_newProductIn , queuePic.size() > 0 ,signal maybe too fast " << Username << std::endl; - qWarning() << __FUNCTION__ << " line: " << __LINE__ << "rest_newProductIn , queuePic.size() > 0 ,signal maybe too fast " << QString::fromStdString(Username); - } - if (ifRunning == true) - { - ifBreak = true; - Sleep(10); - } - imgIndex = 0; - return true; - } - else if (dataList.size() > 1) { - if (dataList[0] == "cameraTriggerSignal") { - imgShouldGetVec.clear(); - imgShouldGetIndex = 0; - for (int i = 1; i < dataList.size(); i++) - imgShouldGetVec.push_back(dataList[i].toInt()); - } - } - else - { - m_flag = false; - expourseTimeList.clear(); - gainList.clear(); - } - //Username= data.toStdString(); - return true; -} -//传入initParas函数,格式为:相机key+参数名1#参数值1#参数值2+参数名2#参数值1... -bool Hd_CameraModule_HIK_hard_PCIE::initParas(QByteArray& initData) -{ - QByteArrayList valueList = initData.split('+'); - Username = valueList[0]; - imgIndex = 0; - expourseTimeList.clear(); - gainList.clear(); - if (valueList.size() > 1) - for (int i = 1; i < valueList.size(); i++) - { - QString valuei = byteArrayToUnicode(valueList[i]); - //valuei.prepend(valueList[i]); - if (valuei.contains("expourseTime")) - { - QStringList expourseTimeL = valuei.split('#'); - if (expourseTimeL.size() > 1) - for (int j = 1; j < expourseTimeL.size(); j++) - expourseTimeList.enqueue(expourseTimeL[j].toFloat()); - } - if (valuei.contains("gain")) - { - QStringList gainL = valuei.split('#'); - if (gainL.size() > 1) - for (int j = 1; j < gainL.size(); j++) - gainList.enqueue(gainL[j].toFloat()); - } - - if (valuei.contains("是否为标准通信流程")) - { - if (valuei.contains("true")) - ifStandard = true; - } - if (valuei.contains("取图超时")) - { - QStringList gainL = valuei.split('#'); - if (gainL.size() > 1) - getImageTimeOut = gainL[1].toInt(); - if (getImageTimeOut < 50) - getImageTimeOut = 1000; - } - if (valuei.contains("OffsetX")) - { - QStringList valueL = valuei.split('#'); - if (valueL.size() > 1) - if (valueL[1].toInt() >= 0) - MV_CC_SetIntValue(handle, "OffsetX", valueL[1].toInt()); - } - if (valuei.contains("OffsetY")) - { - QStringList valueL = valuei.split('#'); - if (valueL.size() > 1) - if (valueL[1].toInt() >= 0) - MV_CC_SetIntValue(handle, "OffsetY", valueL[1].toInt()); - } - if (valuei.contains("Width")) - { - QStringList valueL = valuei.split('#'); - if (valueL.size() > 1) - if (valueL[1].toInt() >= 0) - MV_CC_SetIntValue(handle, "Width", valueL[1].toInt()); - } - if (valuei.contains("Height")) - { - QStringList valueL = valuei.split('#'); - if (valueL.size() > 1) - if (valueL[1].toInt() >= 0) - MV_CC_SetIntValue(handle, "Height", valueL[1].toInt()); - } - } - - bool ifOk = connectDevice(); - if (ifOk == true) - { - if (expourseTimeList.size() > 0) - SetExposureTime(expourseTimeList[0]); - if (gainList.size() > 0) - SetGain(gainList[0]); - } - imgIndex = 0; - return ifOk; -} - -bool Hd_CameraModule_HIK_hard_PCIE::run() -{ - - qDebug() << "[INFO] " << " run start" << QString::fromStdString(Username); - bool result = false; - ifRunning = true; - ifBreak = false; - try - { - m_flag = false; - int mytime = 0; - int cnt = 0; - while (true) - { - /* if (moduleStatus == false || mytime++ > getImageTimeOut || ifBreak == true) - { - result = false; - break; - }*/ - - cnt++; - if (queuepic.size() > 0) - { - result = true; - std::cout << "\n gotImg" << std::endl; - break; - } - if (cnt > 150) { - n_mutex->lock(); - //queuepic.push_back(cv::imread("D://Image_20250809202445856.bmp", -1)); - queuepic.push_back(cv::Mat(200, 200, CV_8UC1, cv::Scalar(0))); //返回空图 - std::cout << "timeout" << std::endl; - n_mutex->unlock(); - return true; - } - QThread::msleep(10); - } - //考虑到误触发、漏触发的图,在这里进行设置。 - //需要设置曝光时 - if (ifStandard == true) - { - imgIndex++; - if (expourseTimeList.size() > 1 && expourseTimeList[imgIndex % expourseTimeList.size()] != expourseTimeList[(imgIndex - 1) % expourseTimeList.size()]) - SetExposureTime(expourseTimeList[imgIndex % expourseTimeList.size()]); - if (gainList.size() > 1 && gainList[imgIndex % gainList.size()] != gainList[(imgIndex - 1) % gainList.size()]) - SetGain(gainList[imgIndex % gainList.size()]); - } - } - catch (QString ev) - { - qDebug() << "[Error] " << " ev:" << ev; - } - qDebug() << "[INFO] " << __LINE__ << " run end"; - return result; -} - -//相机连接状态:正常连接或断开 -bool Hd_CameraModule_HIK_hard_PCIE::checkStatus() -{ - //status = moduleStatus; - return moduleStatus; -} - diff --git a/subModule/Hd_CameraModule_HIK_hard_PCIE/Hd_CameraModule_HIK_hard_PCIE.h b/subModule/Hd_CameraModule_HIK_hard_PCIE/Hd_CameraModule_HIK_hard_PCIE.h deleted file mode 100644 index 5bf23b2..0000000 --- a/subModule/Hd_CameraModule_HIK_hard_PCIE/Hd_CameraModule_HIK_hard_PCIE.h +++ /dev/null @@ -1,43 +0,0 @@ -#ifndef Hd_CameraModule_HIK_hard_PCIE_H -#define Hd_CameraModule_HIK_hard_PCIE_H -#include -#include -#include -#include -#include -#include -#include -#include - -#include - -using namespace cv; -#pragma execution_character_set("utf-8") - -class Hd_CameraModule_HIK_hard_PCIE :public dsModuleBase -{ -public: - Hd_CameraModule_HIK_hard_PCIE(); - virtual ~Hd_CameraModule_HIK_hard_PCIE(); - //从类中读数据到实例对象 - bool readData(std::vector& mat, QByteArray& data); - //实例对象把数据写入到类 - bool writeData(std::vector& mat, QByteArray& data); - bool initParas(QByteArray& initData); - bool run(); - bool checkStatus(); -private: - std::vector imgShouldGetVec; - int imgShouldGetIndex = 0; - //MyThread *m_thread = nullptr; - //QMutex* m_mutex; -}; - -extern "C" -{ -Q_DECL_EXPORT Hd_CameraModule_HIK_hard_PCIE * create(); -Q_DECL_EXPORT void destory(Hd_CameraModule_HIK_hard_PCIE * ptr); -} - -#endif // Hd_CameraModule_HIK_hard_H -//Hd_CameraModule_HIK_hard_PCIE diff --git a/subModule/Hd_CameraModule_HIK_hard_USB/CMakeLists.txt b/subModule/Hd_CameraModule_HIK_hard_USB/CMakeLists.txt deleted file mode 100644 index a629df5..0000000 --- a/subModule/Hd_CameraModule_HIK_hard_USB/CMakeLists.txt +++ /dev/null @@ -1,70 +0,0 @@ -# 获取获取当前目录名 -get_filename_component(CURRENT_FOLDER ${CMAKE_CURRENT_SOURCE_DIR} NAME) -string(TIMESTAMP RUN_TIME) -message( " model start : " ${CURRENT_FOLDER}:${RUN_TIME}) - -set(DLL_NAMES "mvs" "opencv") -foreach(child ${DLL_NAMES}) - LIST(APPEND ENV_INCLUDE ${${child}_include}) - LIST(APPEND ENV_LIB ${${child}_lib}) - LIST(APPEND ENV_TARGET ${${child}_target_link}) -endforeach() -message(" ENV_INCLUDE : " ${ENV_INCLUDE} ) -message(" ENV_LIB : " ${ENV_LIB} ) -message(" ENV_TARGET : " ${ENV_TARGET} ) -include_directories( - - ${ENV_INCLUDE} - ) - -link_directories ( - ${ENV_LIB} - - ) - - -set(CMAKE_INCLUDE_CURRENT_DIR ON) -SET(CMAKE_CXX_STANDARD 11) -SET(CMAKE_CXX_STANDARD_REQUIRED ON) - -set(CMAKE_AUTOMOC ON) -SET(CMAKE_AUTOUIC OFF) -set(CMAKE_AUTORCC ON) - -FILE(GLOB HEAD_FILES "./*.h" ) -FILE(GLOB SRC_FILES "./*.cpp") -FILE(GLOB UI_FILES "./*.ui") - - -#find_package(Qt5 COMPONENTS Core REQUIRED) -find_package(QT NAMES Qt6 Qt5 COMPONENTS Core REQUIRED) -find_package(Qt${QT_VERSION_MAJOR} COMPONENTS Core REQUIRED) - -add_library(${CURRENT_FOLDER} SHARED - ${HEAD_FILES} - ${SRC_FILES} - ${UI_FILES} - ) - - - -set_target_properties(${CURRENT_FOLDER} PROPERTIES LINKER_LANGUAGE C - RUNTIME_OUTPUT_DIRECTORY ${CMAKE_RUNTIME_OUTPUT_DIRECTORY} - LIBRARY_OUTPUT_DIRECTORY ${CMAKE_LIBRARY_OUTPUT_DIRECTORY} - ARCHIVE_OUTPUT_DIRECTORY ${CMAKE_ARCHIVE_OUTPUT_DIRECTORY} - ) - - -target_link_libraries(${CURRENT_FOLDER} PRIVATE - ${ENV_TARGET} - Qt${QT_VERSION_MAJOR}::Core - ) - - -# target_compile_definitions(${CURRENT_FOLDER} PRIVATE HD_AIDEMO_MODULE_LIBRARY) - - - - -string(TIMESTAMP RUN_TIME) -message( " model end : " ${CURRENT_FOLDER}:${RUN_TIME}) diff --git a/subModule/Hd_CameraModule_HIK_hard_USB/Hd_CameraModule_HIK_hard_USB.cpp b/subModule/Hd_CameraModule_HIK_hard_USB/Hd_CameraModule_HIK_hard_USB.cpp deleted file mode 100644 index 1559841..0000000 --- a/subModule/Hd_CameraModule_HIK_hard_USB/Hd_CameraModule_HIK_hard_USB.cpp +++ /dev/null @@ -1,739 +0,0 @@ -#include "Hd_CameraModule_HIK_hard_USB.h" -using namespace std; -#include -#include -#include -#include -QByteArray mv_Status = "connected";//0106 新增相机断联报警 -//cv::Mat srcImage; -int index = -1; //相机序号 -void* handle; //相机指针 -string Username = ""; -bool m_flag = false; -MV_CC_DEVICE_INFO_LIST m_stDevList;//相机设备 -bool moduleStatus = true; -QQueue queuepic; -cv::Mat matList[1000] = { cv::Mat() }; -//data == "rest_newProductIn"时要结束run;机台报警,取图超时,复位后重新拍的情况。 -bool ifBreak = false; -//ifRunning减少ifBreak的判断;"rest_newProductIn"时,Logic_camera_thread框架会结束未处理完的相相机取图 -bool ifRunning = false; -bool ifChangeExpourseAndGain = true; - - -QString byteArrayToUnicode(const QByteArray array) { - - // state用于保存转换状态,它的成员invalidChars,可用来判断是否转换成功 - // 如果转换成功,则值为0,如果值大于0,则说明转换失败 - QTextCodec::ConverterState state; - // 先尝试使用utf-8的方式把QByteArray转换成QString - QString text = QTextCodec::codecForName("UTF-8")->toUnicode(array.constData(), array.size(), &state); - // 如果转换时无效字符数量大于0,说明编码格式不对 - if (state.invalidChars > 0) - { - // 再尝试使用GBK的方式进行转换,一般就能转换正确(当然也可能是其它格式,但比较少见了) - text = QTextCodec::codecForName("GBK")->toUnicode(array); - } - return text; -} -static MV_CC_DEVICE_INFO_LIST QByteArrayToMV_CC_DeviceInfoList(const QByteArray& byteArray) { - MV_CC_DEVICE_INFO_LIST deviceInfoList; - if (byteArray.size() == sizeof(MV_CC_DEVICE_INFO_LIST)) { - memcpy(&deviceInfoList, byteArray.constData(), sizeof(MV_CC_DEVICE_INFO_LIST)); - } - else { - qDebug() << "Invalid size of QByteArray for MV_CC_DEVICE_INFO_LIST!"; - } - return deviceInfoList; -} -#pragma execution_character_set("utf-8") - -QMutex* n_mutex;// = new QMutex(); -//是否为标准通信流程: -//标准通信流程,run函数设置曝光/增益;非标准通信流程(简单通信流程),回调函数设置曝光/增益 -bool ifStandard = false; -//相机取图超时时间 -int getImageTimeOut = 1000; -//总取图数 -int imgIndex = 0; -//曝光值列表 -QQueue expourseTimeList; -//增益列表 -QQueue gainList; - -//0106 断线重连 -void __stdcall ReconnectDevice(unsigned int nMsgType, void* pUser); -void __stdcall ImageCallBackEx(unsigned char* pData0, MV_FRAME_OUT_INFO_EX* pFrameInfo0, void* pUser0); - - -bool IsColor(MvGvspPixelType enType) -{ - switch (enType) - { - case PixelType_Gvsp_RGB8_Packed: - case PixelType_Gvsp_YUV422_Packed: - case PixelType_Gvsp_YUV422_YUYV_Packed: - case PixelType_Gvsp_BayerGR8: - case PixelType_Gvsp_BayerRG8: - case PixelType_Gvsp_BayerGB8: - case PixelType_Gvsp_BayerBG8: - case PixelType_Gvsp_BayerGB10: - case PixelType_Gvsp_BayerGB10_Packed: - case PixelType_Gvsp_BayerBG10: - case PixelType_Gvsp_BayerBG10_Packed: - case PixelType_Gvsp_BayerRG10: - case PixelType_Gvsp_BayerRG10_Packed: - case PixelType_Gvsp_BayerGR10: - case PixelType_Gvsp_BayerGR10_Packed: - case PixelType_Gvsp_BayerGB12: - case PixelType_Gvsp_BayerGB12_Packed: - case PixelType_Gvsp_BayerBG12: - case PixelType_Gvsp_BayerBG12_Packed: - case PixelType_Gvsp_BayerRG12: - case PixelType_Gvsp_BayerRG12_Packed: - case PixelType_Gvsp_BayerGR12: - case PixelType_Gvsp_BayerGR12_Packed: - return true; - default: - return false; - } -} - -//搜索所有设备 -int SearchDevice() -{ - if (m_stDevList.nDeviceNum == 0) { - memset(&m_stDevList, 0, sizeof(MV_CC_DEVICE_INFO_LIST)); - // ch:枚举子网内所有设备 | en:Enumerate all devices within subnet - int nRet = MV_CC_EnumDevices(MV_GIGE_DEVICE | MV_USB_DEVICE, &m_stDevList); - if (MV_OK != nRet) - { - return 0; - } - } - for (int i = 0; i < m_stDevList.nDeviceNum; i++) - { - //SN - unsigned char* name = m_stDevList.pDeviceInfo[i]->SpecialInfo.stUsb3VInfo.chSerialNumber; - //userID - //unsigned char* name=m_stDevList.pDeviceInfo[i]->SpecialInfo.stGigEInfo.chUserDefinedName; - string userName = static_cast((LPCSTR)name); - if (Username == userName) - { - index = i; - break; - } - } - return -1; -} - -bool connectDevice() -{ - index = -1; - SearchDevice(); - if (index == -1) - { - //未匹配到相机 - qDebug() << "[Waring] " << "Hd_CameraModule_HIK_hard_USB not match --CameraName:" << QString::fromStdString(Username); - return false; - } - unsigned char* name = m_stDevList.pDeviceInfo[index]->SpecialInfo.stGigEInfo.chUserDefinedName; - string userName = static_cast((LPCSTR)name); - qDebug() << "[INFO] " << " start" << "--UserName:" << QString::fromStdString(userName); - if (handle != NULL) - { - MV_CC_StopGrabbing(handle); - MV_CC_CloseDevice(handle); - MV_CC_DestroyHandle(handle); - } - - //打开相机 - MV_CC_CreateHandle(&handle, m_stDevList.pDeviceInfo[index]); - int nRet = MV_CC_OpenDevice(handle); - ////触发模式 - MV_CC_SetEnumValue(handle, "TriggerSource", MV_TRIGGER_SOURCE_LINE0); - MV_CC_SetEnumValue(handle, "TriggerMode", MV_TRIGGER_MODE_ON); - // //加载用户集,相机设置应当UserSet1 - nRet = MV_CC_SetEnumValueByString(handle, "UserSetSelector", "UserSet1"); - if (MV_OK != nRet) - { - qDebug() << "Set UserSetSelector fail! nRet " << nRet; - } - // ch:注册抓图回调 | en:Register image callback - MV_CC_SetIntValueEx(handle, "GevHeartbeatTimeout", 3000);//心跳日志 - - nRet = MV_CC_RegisterImageCallBackEx(handle, ImageCallBackEx, handle);//注册回调 - if (MV_OK != nRet) - return false; - nRet = MV_CC_RegisterExceptionCallBack(handle, ReconnectDevice, NULL);//断线重连 - if (MV_OK != nRet) - return false; - MV_CC_StartGrabbing(handle); - return true; -} - -//0106 断线重连 -void __stdcall ReconnectDevice(unsigned int nMsgType, void* pUser) -{ - mv_Status = "disconnect"; - qDebug() << "[Error] " << " MV camera disconnects!"; - moduleStatus = false; - if (nMsgType == MV_EXCEPTION_DEV_DISCONNECT) - { - //断开连接 - MV_CC_CloseDevice(handle); - int nRet = MV_CC_DestroyHandle(handle); - handle = nullptr; - BOOL bConnected = FALSE; - while (1) - { - Sleep(100); - if (connectDevice() == true) - { - qWarning() << "[Hd_CameraModule_HIK_hard_USB] " << " Hd_CameraModule_HIK_hard_USB create success again! "; - moduleStatus = true; - break; - } - - } - } -} -void _stdcall ExceptionCB(unsigned int nMesgType, void* pUser) { - mv_Status = "disconnect"; - qDebug() << "[Error] " << " MV camera disconnects!"; - moduleStatus = false; -} - -int RGB2BGR(unsigned char* pRgbData, unsigned int nWidth, unsigned int nHeight) -{ - - if (NULL == pRgbData) - { - return MV_E_PARAMETER; - } - - for (unsigned int j = 0; j < nHeight; j++) - { - for (unsigned int i = 0; i < nWidth; i++) - { - unsigned char red = pRgbData[j * (nWidth * 3) + i * 3]; - pRgbData[j * (nWidth * 3) + i * 3] = pRgbData[j * (nWidth * 3) + i * 3 + 2]; - pRgbData[j * (nWidth * 3) + i * 3 + 2] = red; - } - } - - return MV_OK; - -} - -Hd_CameraModule_HIK_hard_USB* create() -{ - qDebug() << "[INFO] " << "Hd_CameraModule_HIK_hard_USB create success!" ; - return new Hd_CameraModule_HIK_hard_USB; -} - -void destory(Hd_CameraModule_HIK_hard_USB * ptr) -{ - if(ptr) - { - delete ptr; - ptr = nullptr; - } - qDebug() << "[INFO] " << "Hd_CameraModule_HIK_hard_USB destory success!"; -} -//回调函数; -//经测试,相机像素格式Mono8、RGB8是可以正常转换的,YUV422还需要优化;RGB8格式比YUV422帧率低;BGR格式会导致异色问题 -void __stdcall ImageCallBackEx(unsigned char* pData0, MV_FRAME_OUT_INFO_EX* pFrameInfo0, void* pUser0) -{ - n_mutex->lock(); - double time_Start = (double)clock(); - int frameNum = 0; - cv::Mat srcImage = cv::Mat(); - if (pFrameInfo0) - { - //获取的是单通道灰度图 - if (pFrameInfo0->enPixelType == PixelType_Gvsp_Mono8)//获取当前采集到的图像格式 - { - srcImage = cv::Mat(pFrameInfo0->nHeight, pFrameInfo0->nWidth, CV_8UC1, pData0); - } - //获取的是RGB8图 - else if (pFrameInfo0->enPixelType == PixelType_Gvsp_BGR8_Packed) - { - srcImage = cv::Mat(pFrameInfo0->nHeight, pFrameInfo0->nWidth, CV_8UC3, pData0); - } - - ////获取的是RGB8图 - //else if (pFrameInfo0->enPixelType == PixelType_Gvsp_RGB8_Packed) - //{ - // cv::Mat dst = cv::Mat(pFrameInfo0->nHeight, pFrameInfo0->nWidth, CV_8UC3, pData0); - // //cv::cvtColor(matimage, matimage, cv::COLOR_RGB2BGR); - // srcImage = cv::Mat::zeros(pFrameInfo0->nHeight, pFrameInfo0->nWidth, CV_8UC3); - // std::vector channels; - // cv::split(dst, channels);//分割matimage的通道 - // std::vector dstchannels; - // for (int i = 2; i >= 0; i--) - // { - // dstchannels.push_back(channels[i]); - // } - // merge(dstchannels, srcImage); - //} - - else if (IsColor(pFrameInfo0->enPixelType)) //其它格式彩色图 - { - MvGvspPixelType enDstPixelType = PixelType_Gvsp_Undefined; - enDstPixelType = PixelType_Gvsp_BGR8_Packed; - unsigned char* pConvertData = NULL; - pConvertData = (unsigned char*)malloc(pFrameInfo0->nWidth * pFrameInfo0->nHeight * 3); - if (NULL == pConvertData) - { - printf("malloc pConvertData fail!\n"); - } - else - { - unsigned int nConvertDataSize = 0; - nConvertDataSize = pFrameInfo0->nWidth * pFrameInfo0->nHeight * 3; - - // ch:像素格式转换 | en:Convert pixel format - MV_CC_PIXEL_CONVERT_PARAM stConvertParam = { 0 }; - - frameNum = pFrameInfo0->nFrameNum; //ch:帧号 | en:frame number - stConvertParam.nWidth = pFrameInfo0->nWidth; //ch:图像宽 | en:image width - stConvertParam.nHeight = pFrameInfo0->nHeight; //ch:图像高 | en:image height - stConvertParam.pSrcData = pData0; //ch:输入数据缓存 | en:input data buffer - stConvertParam.nSrcDataLen = pFrameInfo0->nFrameLen; //ch:输入数据大小 | en:input data size - stConvertParam.enSrcPixelType = pFrameInfo0->enPixelType; //ch:输入像素格式 | en:input pixel format - stConvertParam.enDstPixelType = enDstPixelType; //ch:输出像素格式 | en:output pixel format - stConvertParam.pDstBuffer = pConvertData; //ch:输出数据缓存 | en:output data buffer - stConvertParam.nDstBufferSize = nConvertDataSize; //ch:输出缓存大小 | en:output buffer size - int nRet = MV_CC_ConvertPixelType(handle, &stConvertParam); - - Mat mysrcImage = cv::Mat(pFrameInfo0->nHeight, pFrameInfo0->nWidth, CV_8UC3, stConvertParam.pDstBuffer); - mysrcImage.copyTo(srcImage); - - free(pConvertData); - pConvertData = NULL; - stConvertParam = { 0 }; - } - } - } - if(srcImage.empty()) - { - srcImage = cv::Mat(5, 5, CV_8UC1).setTo(0); - } - - m_flag = true; - queuepic.push_back(srcImage.clone()); - n_mutex->unlock(); - pData0 = { 0 }; - double time_End = (double)clock(); - std::cout << "[INFO] " << __FUNCTION__ << " line:" << __LINE__ << " checkImg getImg,Time:" << (time_End - time_Start) << "ms" - << "--CameraName:" << Username << " imgIndex:" << imgIndex << "nFrameNum : " << frameNum << std::endl; - - qDebug() << "[INFO] " << __FUNCTION__ << " line:" << __LINE__ << " checkImg getImg,Time:" << (time_End - time_Start) << "ms" - << "--CameraName:" << QString::fromStdString(Username) << " imgIndex:" << imgIndex << "nFrameNum : " << frameNum; - /*QString savePath = "../runtime/Bin_DEVICE/testImg/camera_" + QString::number(imgIndex + 1)+".png"; - cv::Mat resizeS; - cv::resize(srcImage, resizeS, cv::Size(), 0.1, 0.1); - cv::imwrite(savePath.toStdString(), resizeS);*/ -} - -void SetExposureTime(float exposureValue) -{ - qDebug() << "[INFO] " << "exposureValue:" << exposureValue; - MV_CC_SetEnumValue(handle, "ExposureAuto", MV_EXPOSURE_AUTO_MODE_OFF); - MV_CC_SetFloatValue(handle, "ExposureTime", exposureValue); -} - -void SetGain(float GainValue) -{ - qDebug() << "[INFO] " << "GainValue:" << GainValue; - MV_CC_SetEnumValue(handle, "GainAuto", 0); - MV_CC_SetFloatValue(handle, "Gain", GainValue); -} -Hd_CameraModule_HIK_hard_USB::Hd_CameraModule_HIK_hard_USB() -{ - n_mutex = new QMutex(); - m_thread = new MyThread; -} -//关闭设备 -void CloseDevice() -{ - MV_CC_StopGrabbing(handle); - MV_CC_CloseDevice(handle); - MV_CC_DestroyHandle(handle); - handle = nullptr; //此处注释掉的话,软件断开再连接,回调函数不出图 -} - -Hd_CameraModule_HIK_hard_USB::~Hd_CameraModule_HIK_hard_USB() -{ - m_flag = true; - Sleep(10); - CloseDevice(); - if (n_mutex) - { - delete n_mutex; - n_mutex = nullptr; - } - if(m_thread) - { - m_thread->exit(); - m_thread->wait(1); - delete m_thread; - m_thread = nullptr; - } - - qDebug() << "[INFO] " << " delete success!"; -} -//从类中读数据到实例对象 -bool Hd_CameraModule_HIK_hard_USB::readData(std::vector &mat,QByteArray &data) -{ - if (queuepic.isEmpty()) - { - qCritical() << __FUNCTION__ << " line:" <<__LINE__ << " srcImage is null"; - return false; - } - n_mutex->lock(); - cv::Mat img = cv::Mat(); - queuepic.dequeue().copyTo(img); - mat.push_back(img.clone()); - n_mutex->unlock(); - QString qimgIndex = "imgIndex_" + QString::number(imgIndex-1)+"_中文测试"; - data = qimgIndex.toLocal8Bit(); - qDebug() << "[INFO] " << __FUNCTION__ << " line:" << __LINE__ << " checkImg readData--CameraName:" << QString::fromStdString(Username) << "--imgIndex : " << imgIndex-1; - return true; -} -//实例对象把数据写入到类 -bool Hd_CameraModule_HIK_hard_USB::writeData(std::vector &mat,QByteArray &data) -{ - //2024.02.18更新,相机对应的读SN信号时,表示新产品进入,设置初始值 - if (data.contains("deviceList")) { - auto result = QByteArrayToMV_CC_DeviceInfoList(data.mid(10)); - if (result.nDeviceNum != 0) { - m_stDevList = result; - return true; - } - } - if (data == "rest_newProductIn") - { - //根据实际项目,设置初始值:曝光、增益,ROI区域等 - { - if (expourseTimeList.size() > 0) - SetExposureTime(expourseTimeList[0]); - if (gainList.size() > 0) - SetGain(gainList[0]); - } - - if (queuepic.size() > 0) - { - n_mutex->lock(); - //queuepic.clear(); - n_mutex->unlock(); - std::cout << "rest_newProductIn , queuePic.size() > 0 ,signal maybe too fast " << Username << std::endl; - qWarning() << __FUNCTION__ << " line: " << __LINE__ << "rest_newProductIn , queuePic.size() > 0 ,signal maybe too fast " << QString::fromStdString(Username); - } - if (ifRunning == true) - { - ifBreak = true; - Sleep(10); - } - imgIndex = 0; - return true; - } - else - { - m_flag = false; - //expourseTimeList.clear(); - //gainList.clear(); - } - //if (data == "ifChangeExpourseAndGain_false") - // ifChangeExpourseAndGain = false; - //else - // ifChangeExpourseAndGain = true; - //if (data.contains("SetExposureTime_")) - //{ - // QByteArrayList dataList = data.split('#'); - // for (int i = 0; i < dataList.size(); i++) - // { - // if (dataList[i].contains("SetExposureTime_")) - // { - // int value = byteArrayToUnicode(dataList[i]).split("SetExposureTime_")[1].toInt(); - // SetExposureTime(value); - // } - // if (dataList[i].contains("SetGain_")) - // { - // double value = byteArrayToUnicode(dataList[i]).split("SetGain_")[1].toInt(); - // SetGain(value); - // } - // if (dataList[i].contains("TriggerMode_")) - // { - // QString value = byteArrayToUnicode(dataList[i]).split("TriggerMode_")[1]; - // if (value == "软触发") - // ////触发模式 - // { - // MV_CC_SetEnumValue(handle, "TriggerSource", MV_TRIGGER_SOURCE_SOFTWARE); - // currentTriggerSource = MV_TRIGGER_SOURCE_SOFTWARE; - // } - // else - // { - // MV_CC_SetEnumValue(handle, "TriggerSource", MV_TRIGGER_SOURCE_LINE0); - // currentTriggerSource = MV_TRIGGER_SOURCE_LINE0; - // } - // } - // } - //} - ////调试模式下,data==ifChangeExpourseAndGain_false;非调试模式运行时,data不包含SetExposureTime_ - //else if (data != "ifChangeExpourseAndGain_false" && initTriggerSource != currentTriggerSource) - //{ - // MV_CC_SetEnumValue(handle, "TriggerSource", initTriggerSource); - // currentTriggerSource = initTriggerSource; - //} - - - /*data.append("SetExposureTime_" + ui.spinBox->text() + "#"); - data.append("SetGain_" + ui.doubleSpinBox->text() + "#"); - data.append("TriggerMode_" + ui.comboBox_triggerMode->currentText());*/ - - - qDebug() << "Hd_CameraModule_HIK_hard_USB::writeData::" << data; - - m_flag = false; - //Username = data.toStdString(); - return true; -} - - -//传入initParas函数,格式为:相机key+参数名1#参数值1#参数值2+参数名2#参数值1... -bool Hd_CameraModule_HIK_hard_USB::initParas(QByteArray& initData) -{ - QByteArrayList valueList = initData.split('+'); - Username = valueList[0]; - imgIndex = 0; - - expourseTimeList.clear(); - gainList.clear(); - - - bool ifOk = true; - if (handle == NULL) - ifOk = connectDevice(); - if (ifOk == false) - return false; - if (valueList.size() > 1) - for (int i = 1; i < valueList.size(); i++) - { - QString valuei = byteArrayToUnicode(valueList[i]); - //valuei.prepend(valueList[i]); - if (valuei.contains("expourseTime")) - { - QStringList expourseTimeL = valuei.split('#'); - if (expourseTimeL.size() > 1) - for (int j = 1; j < expourseTimeL.size(); j++) - expourseTimeList.enqueue(expourseTimeL[j].toFloat()); - } - if (valuei.contains("gain")) - { - QStringList gainL = valuei.split('#'); - if (gainL.size() > 1) - for (int j = 1; j < gainL.size(); j++) - gainList.enqueue(gainL[j].toFloat()); - } - - if (valuei.contains("是否为标准通信流程")) - { - if (valuei.contains("true")) - ifStandard = true; - } - if (valuei.contains("取图超时")) - { - QStringList gainL = valuei.split('#'); - if (gainL.size() > 1) - getImageTimeOut = gainL[1].toInt(); - if (getImageTimeOut < 50) - getImageTimeOut = 1000; - } - if (valuei.contains("OffsetX")) - { - QStringList valueL = valuei.split('#'); - if (valueL.size() > 1) - if(valueL[1].toInt()>=0) - MV_CC_SetIntValue(handle, "OffsetX", valueL[1].toInt()); - } - if (valuei.contains("OffsetY")) - { - QStringList valueL = valuei.split('#'); - if (valueL.size() > 1) - if (valueL[1].toInt() >= 0) - MV_CC_SetIntValue(handle, "OffsetY", valueL[1].toInt()); - } - if (valuei.contains("Width")) - { - QStringList valueL = valuei.split('#'); - if (valueL.size() > 1) - if (valueL[1].toInt() >= 0) - MV_CC_SetIntValue(handle, "Width", valueL[1].toInt()); - } - if (valuei.contains("Height")) - { - QStringList valueL = valuei.split('#'); - if (valueL.size() > 1) - if (valueL[1].toInt() >= 0) - MV_CC_SetIntValue(handle, "Height", valueL[1].toInt()); - } - - //if (valuei.contains("触发方式")) - //{ - // QStringList valueL = valuei.split('#'); - // if (valueL.size() > 1) - // if (valueL[1].toInt() >= 0) - // if (valueL[1] == "软触发") - // { - // MV_CC_SetEnumValue(handle, "TriggerSource", MV_TRIGGER_SOURCE_SOFTWARE); - // currentTriggerSource = MV_TRIGGER_SOURCE_SOFTWARE; - // initTriggerSource = MV_TRIGGER_SOURCE_SOFTWARE; - // } - // else - // { - // MV_CC_SetEnumValue(handle, "TriggerSource", MV_TRIGGER_SOURCE_LINE0); - // currentTriggerSource = MV_TRIGGER_SOURCE_LINE0; - // initTriggerSource = MV_TRIGGER_SOURCE_LINE0; - // } - //} - } - - if (ifOk == true) - { - if (expourseTimeList.size() > 0) - SetExposureTime(expourseTimeList[0]); - if (gainList.size() > 0) - SetGain(gainList[0]); - } - imgIndex = 0; - if (ifOk == true) - { - MVCC_FLOATVALUE mf = { 0 }; - MV_CC_GetFloatValue(handle, "ExposureTime", &mf); - std::cout << "ExposureTime::" << mf.fCurValue << std::endl; - mf = { 0 }; - MV_CC_GetFloatValue(handle, "Gain", &mf); - std::cout << "Gain::" << mf.fCurValue << std::endl; - MVCC_INTVALUE mI = { 0 }; - MV_CC_GetIntValue(handle, "OffsetX", &mI); - std::cout << "OffsetX::" << mI.nCurValue << std::endl; - mI = { 0 }; - MV_CC_GetIntValue(handle, "OffsetY", &mI); - std::cout << "OffsetY::" << mI.nCurValue << std::endl; - mI = { 0 }; - MV_CC_GetIntValue(handle, "Width", &mI); - std::cout << "Width::" << mI.nCurValue << std::endl; - mI = { 0 }; - MV_CC_GetIntValue(handle, "Height", &mI); - std::cout << "Height::" << mI.nCurValue << std::endl; - MVCC_ENUMVALUE me = { 0 }; - MV_CC_GetEnumValue(handle,"BalanceWhiteAuto",&me); //自动白平衡 - std::cout << "BalanceWhiteAuto::" << me.nCurValue << std::endl; - - } - - return ifOk; -} -bool Hd_CameraModule_HIK_hard_USB::run() -{ - if (imgIndex == expourseTimeList.size()) - imgIndex = 0; - //Sleep(100); - qDebug() << "[INFO] " << " run start" <lock(); - m_flag = false; - //Sleep(2); - //n_mutex->unlock(); - //m_thread->run(); //start()线程运行,频率高时有低概率无响应; - - //if (currentTriggerSource == MV_TRIGGER_SOURCE_SOFTWARE) - //{ - // MV_CC_SetCommandValue(handle, "TriggerSoftware"); - // qDebug() << "[INFO] " << "TriggerSoftware"; - //} - //else - // qDebug() << "[INFO] " << "TriggerHardware"; - //MV_CC_SetCommandValue(handle, "TriggerSoftware"); - //Sleep(15); - //int mytime = 0; - int cnt = 0; - while (true) - { - /* if (moduleStatus == false || mytime++ > getImageTimeOut || ifBreak == true) - { - result = false; - break; - }*/ - n_mutex->lock(); - cnt++; - if (queuepic.size() > 0) - { - n_mutex->unlock(); - result = true; - std::cout << "\n gotImg" << std::endl; - break; - } - if (cnt > 150) { - queuepic.push_back(cv::Mat(200, 200, CV_8UC1, cv::Scalar(0))); //返回空图 - std::cout << "timeout" << std::endl; - n_mutex->unlock(); - return true; - } - n_mutex->unlock(); - QThread::msleep(10); - } - - //qDebug() << "[INFO] " << " expourseTimeList " << QString::fromStdString(Username); - //软触发,不考虑误触发、漏触发 - if (ifChangeExpourseAndGain == true) - { - imgIndex++; - if (expourseTimeList.size() > 1 && expourseTimeList[imgIndex % expourseTimeList.size()] != expourseTimeList[(imgIndex - 1) % expourseTimeList.size()]) - SetExposureTime(expourseTimeList[imgIndex % expourseTimeList.size()]); - //Sleep(1); - if (gainList.size() > 1 && gainList[imgIndex % gainList.size()] != gainList[(imgIndex - 1) % gainList.size()]) - SetGain(gainList[imgIndex % gainList.size()]); - //Sleep(1); - } - if (result == false) - { - QString currPath = "../runtime/Bin_DEVICE/testImg/testImg_"; - if (ifChangeExpourseAndGain == true) - currPath +=QString::number(imgIndex-1); - else - currPath += QString::number(imgIndex); - currPath += ".jpg"; - cv::Mat readMat = cv::imread(currPath.toStdString()); - queuepic.push_back(readMat); - qDebug() << "取图失败,读取图片:" << currPath; - result = true; - } - - } - catch (QString ev) - { - qDebug() << "[Error] " << " ev:" << ev ; - } - qDebug() << "[INFO] " << __LINE__ << " run end" ; - return result; -} - -//相机连接状态:正常连接或断开 -bool Hd_CameraModule_HIK_hard_USB::checkStatus() -{ - //status = moduleStatus; - return moduleStatus; -} - -void MyThread::run() -{ - MV_CC_SetCommandValue(handle, "TriggerSoftware"); -} diff --git a/subModule/Hd_CameraModule_HIK_hard_USB/Hd_CameraModule_HIK_hard_USB.h b/subModule/Hd_CameraModule_HIK_hard_USB/Hd_CameraModule_HIK_hard_USB.h deleted file mode 100644 index cd42309..0000000 --- a/subModule/Hd_CameraModule_HIK_hard_USB/Hd_CameraModule_HIK_hard_USB.h +++ /dev/null @@ -1,59 +0,0 @@ -#ifndef Hd_CameraModule_HIK_hard_USB_H -#define Hd_CameraModule_HIK_hard_USB_H - -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - - -#include - -using namespace cv; -#pragma execution_character_set("utf-8") - - -class MyThread; -class Hd_CameraModule_HIK_hard_USB :public dsModuleBase -{ -public: - Hd_CameraModule_HIK_hard_USB(); - virtual ~Hd_CameraModule_HIK_hard_USB(); - //从类中读数据到实例对象 - bool readData(std::vector& mat, QByteArray& data); - //实例对象把数据写入到类 - bool writeData(std::vector& mat, QByteArray& data); - bool initParas(QByteArray&); - bool run(); - bool checkStatus(); -private: - MyThread *m_thread = nullptr; -}; - -class MyThread : public QThread -{ - Q_OBJECT -public: - explicit MyThread(QObject *parent = nullptr):m_obj(parent){} - void run(); -private: - QObject *m_obj; -signals: - -}; - -extern "C" -{ -Q_DECL_EXPORT Hd_CameraModule_HIK_hard_USB * create(); -Q_DECL_EXPORT void destory(Hd_CameraModule_HIK_hard_USB * ptr); -} - -#endif // Hd_CameraModule_HIK_hard_USB_H diff --git a/subModule/Hd_CameraModule_HIK_soft_GIGE/Hd_CameraModule_HIK_soft_GIGE.cpp b/subModule/Hd_CameraModule_HIK_soft_GIGE/Hd_CameraModule_HIK_soft_GIGE.cpp deleted file mode 100644 index 9391dbb..0000000 --- a/subModule/Hd_CameraModule_HIK_soft_GIGE/Hd_CameraModule_HIK_soft_GIGE.cpp +++ /dev/null @@ -1,598 +0,0 @@ -#include "Hd_CameraModule_HIK_soft_GIGE.h" -#include -using namespace std; -#include -#include -#include -#include -#include - -QByteArray mv_Status = "connected";//0106 新增相机断联报警 -long long index = 0; //相机序号 -void* handle; -string Username = ""; -bool m_flag = false; -//MV_CC_DEVICE_INFO_LIST m_stDevList;//相机设备 -bool moduleStatus = true; -static std::atomic g_reconnecting(false); -static std::mutex g_reconnect_mutex; -QQueue queuepic; -//data == "rest_newProductIn"时要结束run;机台报警,取图超时,复位后重新拍的情况。 -bool ifBreak = false; -//ifRunning减少ifBreak的判断;"rest_newProductIn"时,Logic_camera_thread框架会结束未处理完的相相机取图 -bool ifRunning = false; - -MV_CC_DEVICE_INFO_LIST m_stDevList; // ch:设备信息列表结构体变量,用来存储设备列表 -//MV_GENTL_IF_INFO_LIST m_stIFList; -void CloseDevice(); -static MV_CC_DEVICE_INFO_LIST QByteArrayToMV_CC_DeviceInfoList(const QByteArray& byteArray) { - MV_CC_DEVICE_INFO_LIST deviceInfoList; - if (byteArray.size() == sizeof(MV_CC_DEVICE_INFO_LIST)) { - memcpy(&deviceInfoList, byteArray.constData(), sizeof(MV_CC_DEVICE_INFO_LIST)); - } - else { - qDebug() << "Invalid size of QByteArray for MV_CC_DEVICE_INFO_LIST!"; - } - return deviceInfoList; -} -QString byteArrayToUnicode(const QByteArray array) { - - // state用于保存转换状态,它的成员invalidChars,可用来判断是否转换成功 - // 如果转换成功,则值为0,如果值大于0,则说明转换失败 - QTextCodec::ConverterState state; - // 先尝试使用utf-8的方式把QByteArray转换成QString - QString text = QTextCodec::codecForName("UTF-8")->toUnicode(array.constData(), array.size(), &state); - // 如果转换时无效字符数量大于0,说明编码格式不对 - if (state.invalidChars > 0) - { - // 再尝试使用GBK的方式进行转换,一般就能转换正确(当然也可能是其它格式,但比较少见了) - text = QTextCodec::codecForName("GBK")->toUnicode(array); - } - return text; -} -QMutex* n_mutex = new QMutex(); -//cv::Mat srcImage; -//是否为标准通信流程: -//标准通信流程,run函数设置曝光/增益;非标准通信流程(简单通信流程),回调函数设置曝光/增益 -int imgCnt = 0; -bool ifStandard = false; -//相机取图超时时间 -int getImageTimeOut = 3000; -//总取图数 -int imgIndex = 0; -//曝光值列表 -QQueue expourseTimeList; -//增益列表 -QQueue gainList; - -bool IsColor(MvGvspPixelType enType) -{ - switch (enType) - { - case PixelType_Gvsp_RGB8_Packed: - case PixelType_Gvsp_YUV422_Packed: - case PixelType_Gvsp_YUV422_YUYV_Packed: - case PixelType_Gvsp_BayerGR8: - case PixelType_Gvsp_BayerRG8: - case PixelType_Gvsp_BayerGB8: - case PixelType_Gvsp_BayerBG8: - case PixelType_Gvsp_BayerGB10: - case PixelType_Gvsp_BayerGB10_Packed: - case PixelType_Gvsp_BayerBG10: - case PixelType_Gvsp_BayerBG10_Packed: - case PixelType_Gvsp_BayerRG10: - case PixelType_Gvsp_BayerRG10_Packed: - case PixelType_Gvsp_BayerGR10: - case PixelType_Gvsp_BayerGR10_Packed: - case PixelType_Gvsp_BayerGB12: - case PixelType_Gvsp_BayerGB12_Packed: - case PixelType_Gvsp_BayerBG12: - case PixelType_Gvsp_BayerBG12_Packed: - case PixelType_Gvsp_BayerRG12: - case PixelType_Gvsp_BayerRG12_Packed: - case PixelType_Gvsp_BayerGR12: - case PixelType_Gvsp_BayerGR12_Packed: - return true; - default: - return false; - } -} -//0106 断线重连 -void __stdcall ReconnectDevice(unsigned int nMsgType, void* pUser); -void __stdcall ImageCallBackEx(unsigned char* pData0, MV_FRAME_OUT_INFO_EX* pFrameInfo0, void* pUser0); -//搜索所有设备 -int SearchDevice() -{ - if (m_stDevList.nDeviceNum == 0) { - memset(&m_stDevList, 0, sizeof(MV_CC_DEVICE_INFO_LIST)); - // ch:枚举子网内所有设备 | en:Enumerate all devices within subnet - int nRet = MV_CC_EnumDevices(MV_GIGE_DEVICE | MV_USB_DEVICE, &m_stDevList); - if (MV_OK != nRet) - { - return 0; - } - } - for (int i = 0; i < m_stDevList.nDeviceNum; i++) - { - //SN - unsigned char* name = m_stDevList.pDeviceInfo[i]->SpecialInfo.stGigEInfo.chSerialNumber; - //userID - //unsigned char* name=m_stDevList.pDeviceInfo[i]->SpecialInfo.stGigEInfo.chUserDefinedName; - string userName = static_cast((LPCSTR)name); - if (Username == userName) - { - index = i; - break; - } - } - return -1; -} - -bool connectDevice() -{ - //MV_CC_Initialize(); - index = -1; - SearchDevice(); - if (index == -1) - { - //未匹配到相机 - //qDebug() << "[Waring] " << "Hd_CameraModule_HIK not match --CameraName:" << QString::fromStdString(Username); - return false; - } - unsigned char* name = m_stDevList.pDeviceInfo[index]->SpecialInfo.stGigEInfo.chUserDefinedName; - string userName = static_cast((LPCSTR)name); - qDebug() << "[INFO] " << " start" << "--UserName:" << QString::fromStdString(userName); - if (handle != NULL) - { - MV_CC_StopGrabbing(handle); - MV_CC_CloseDevice(handle); - MV_CC_DestroyHandle(handle); - } - - //打开相机 - MV_CC_CreateHandle(&handle, m_stDevList.pDeviceInfo[index]); - int nRet = MV_CC_OpenDevice(handle); - ////触发模式 - MV_CC_SetEnumValue(handle, "TriggerMode", MV_TRIGGER_MODE_ON); - MV_CC_SetEnumValue(handle, "TriggerSource", MV_TRIGGER_SOURCE_SOFTWARE); - // //加载用户集,相机设置应当UserSet1 - nRet = MV_CC_SetEnumValueByString(handle, "UserSetSelector", "UserSet1"); - if (MV_OK != nRet) - { - qDebug() << "Set UserSetSelector fail! nRet " << nRet; - } - // ch:注册抓图回调 | en:Register image callback - MV_CC_SetIntValueEx(handle, "GevHeartbeatTimeout", 3000);//心跳日志 - - nRet = MV_CC_RegisterImageCallBackEx(handle, ImageCallBackEx, handle);//注册回调 - if (MV_OK != nRet) - return false; - nRet = MV_CC_RegisterExceptionCallBack(handle, ReconnectDevice, NULL);//断线重连 - if (MV_OK != nRet) - return false; - MV_CC_StartGrabbing(handle); - return true; -} -void SetExposureTime(float exposureValue) -{ - qDebug() << "[INFO] " << "exposureValue:" << exposureValue; - MV_CC_SetEnumValue(handle, "ExposureAuto", MV_EXPOSURE_AUTO_MODE_OFF); - MV_CC_SetFloatValue(handle, "ExposureTime", exposureValue); -} - -void SetGain(float GainValue) -{ - qDebug() << "[INFO] " << "GainValue:" << GainValue; - MV_CC_SetEnumValue(handle, "GainAuto", 0); - MV_CC_SetFloatValue(handle, "Gain", GainValue); -} - -//关闭设备 -void CloseDevice() -{ - // 如果 handle 已经为空,直接返回 - if (handle == nullptr) - return; - - // 使用 SDK 正确的停止/关闭/销毁流程,避免在回调或其他线程中出错 - MV_CC_StopGrabbing(handle); - MV_CC_CloseDevice(handle); - MV_CC_DestroyHandle(handle); - handle = nullptr; //确保后续可以重新创建 handle -} - -//0518 断线重连 -void __stdcall ReconnectDevice(unsigned int nMsgType, void* pUser) -{ - mv_Status = "disconnect"; - qDebug() << "[Error] " << " MV camera disconnects!"; - moduleStatus = false; - - if (nMsgType == MV_EXCEPTION_DEV_DISCONNECT) - { - // 如果已有重连线程在运行,则直接返回 - bool expected = false; - if (!g_reconnecting.compare_exchange_strong(expected, true)) - { - qDebug() << "[Info] reconnect already in progress"; - return; - } - - // 启动后台线程负责重连,避免在回调线程中长时间阻塞 - std::thread([]() { - qDebug() << "[Info] start reconnect thread"; - - // 确保设备资源关闭 - CloseDevice(); - - int attempt = 0; - int delay_ms = 500; // 初始延迟 - while (true) - { - attempt++; - qDebug() << "[Info] reconnect attempt:" << attempt; - if (connectDevice()) - { - qWarning() << "[Hd_CameraModule_HIK] reconnect success!"; - moduleStatus = true; - mv_Status = "connected"; - g_reconnecting = false; - break; - } - - // 指数退避,最大 5000ms - std::this_thread::sleep_for(std::chrono::milliseconds(delay_ms)); - delay_ms = delay_ms * 2; - if (delay_ms > 5000) delay_ms = 5000; - - // 在某些场景可能希望退出重连(例如程序关闭),如果未来需要可增加退出条件 - } - }).detach(); - } -} - -//0106 断连提示 -void _stdcall ExceptionCB(unsigned int nMesgType, void* pUser) { - mv_Status = "disconnect"; - qDebug() << "[Error] " << " MvCameraTL disconnects!"; -} - - -Hd_CameraModule_HIK_soft_GIGE* create() -{ - qDebug() << "[INFO] " << "Hd_CameraModule_HIK create success!"; - return new Hd_CameraModule_HIK_soft_GIGE; -} - -void destory(Hd_CameraModule_HIK_soft_GIGE* ptr) -{ - if (ptr) - { - delete ptr; - ptr = nullptr; - } - qDebug() << "[INFO] " << "Hd_CameraModule_HIK destory success!"; -} - -//回调函数; -//经测试,相机像素格式Mono8、RGB8是可以正常转换的,YUV422还需要优化;RGB8格式比YUV422帧率低;BGR格式会导致异色问题 -void __stdcall ImageCallBackEx(unsigned char* pData0, MV_FRAME_OUT_INFO_EX* pFrameInfo0, void* pUser0) -{ - Q_UNUSED(pUser0) - int frameNum = 0; - double time_Start = (double)clock(); - n_mutex->lock(); - cv::Mat srcImage = cv::Mat(); - //qDebug() << "[info]" << __FUNCTION__ << " line:" << __LINE__ << "--- start"; - if (pFrameInfo0) - { - //获取的是单通道灰度图 - if (pFrameInfo0->enPixelType == PixelType_Gvsp_Mono8)//获取当前采集到的图像格式 - { - srcImage = cv::Mat(pFrameInfo0->nHeight, pFrameInfo0->nWidth, CV_8UC1, pData0); - } - //获取的是RGB8图 - else if (pFrameInfo0->enPixelType == PixelType_Gvsp_BGR8_Packed) - { - srcImage = cv::Mat(pFrameInfo0->nHeight, pFrameInfo0->nWidth, CV_8UC3, pData0); - - //cvtColor(srcImage, srcImage, COLOR_RGB2BGR);//导致异色 - } - else if (IsColor(pFrameInfo0->enPixelType)) //其它格式彩色图 - { - MvGvspPixelType enDstPixelType = PixelType_Gvsp_Undefined; - enDstPixelType = PixelType_Gvsp_BGR8_Packed; - unsigned char* pConvertData = NULL; - pConvertData = (unsigned char*)malloc(pFrameInfo0->nWidth * pFrameInfo0->nHeight * 3); - if (NULL == pConvertData) - { - printf("malloc pConvertData fail!\n"); - } - else - { - unsigned int nConvertDataSize = 0; - nConvertDataSize = pFrameInfo0->nWidth * pFrameInfo0->nHeight * 3; - - // ch:像素格式转换 | en:Convert pixel format - MV_CC_PIXEL_CONVERT_PARAM stConvertParam = { 0 }; - - frameNum = pFrameInfo0->nFrameNum; //ch:帧号 | en:frame number - stConvertParam.nWidth = pFrameInfo0->nWidth; //ch:图像宽 | en:image width - stConvertParam.nHeight = pFrameInfo0->nHeight; //ch:图像高 | en:image height - stConvertParam.pSrcData = pData0; //ch:输入数据缓存 | en:input data buffer - stConvertParam.nSrcDataLen = pFrameInfo0->nFrameLen; //ch:输入数据大小 | en:input data size - stConvertParam.enSrcPixelType = pFrameInfo0->enPixelType; //ch:输入像素格式 | en:input pixel format - stConvertParam.enDstPixelType = enDstPixelType; //ch:输出像素格式 | en:output pixel format - stConvertParam.pDstBuffer = pConvertData; //ch:输出数据缓存 | en:output data buffer - stConvertParam.nDstBufferSize = nConvertDataSize; //ch:输出缓存大小 | en:output buffer size - int nRet = MV_CC_ConvertPixelType(handle, &stConvertParam); - - Mat mysrcImage = cv::Mat(pFrameInfo0->nHeight, pFrameInfo0->nWidth, CV_8UC3, stConvertParam.pDstBuffer); - mysrcImage.copyTo(srcImage); - - free(pConvertData); - pConvertData = NULL; - stConvertParam = { 0 }; - } - } - } - if (srcImage.empty()) - { - srcImage = cv::Mat(5, 5, CV_8UC1).setTo(0); - } - if (ifStandard == false) - { - imgIndex++; - if (expourseTimeList.size() > 1 && expourseTimeList[imgIndex % expourseTimeList.size()] != expourseTimeList[(imgIndex - 1) % expourseTimeList.size()]) - SetExposureTime(expourseTimeList[imgIndex % expourseTimeList.size()]); - if (gainList.size() > 1 && gainList[imgIndex % gainList.size()] != gainList[(imgIndex - 1) % gainList.size()]) - SetGain(gainList[imgIndex % gainList.size()]); - } - queuepic.push_back(srcImage); - m_flag = true; - n_mutex->unlock(); - pData0 = { 0 }; - imgCnt++; - double time_End = (double)clock(); - std::cout << "[INFO] " << __FUNCTION__ << " line:" << __LINE__ << " checkImg getImg,Time:" << (time_End - time_Start) << "ms" - << "--CameraName:" << Username << " imgIndex:" << imgCnt << "nFrameNum : " << frameNum << std::endl; - qDebug() << "[INFO] " << __FUNCTION__ << " line:" << __LINE__ << " checkImg getImg,Time:" << (time_End - time_Start) << "ms" - << "--CameraName:" << QString::fromStdString(Username) << " imgIndex:" << imgCnt << "nFrameNum : " << frameNum; -} - -Hd_CameraModule_HIK_soft_GIGE::Hd_CameraModule_HIK_soft_GIGE() -{ - //m_thread = new MyThread; - //m_mutex = new QMutex(); -} -Hd_CameraModule_HIK_soft_GIGE::~Hd_CameraModule_HIK_soft_GIGE() -{ - CloseDevice(); - if (n_mutex) - { - delete n_mutex; - n_mutex = nullptr; - } - - qDebug() << "[INFO] " << " delete success!"; -} -//从类中读数据到实例对象 -bool Hd_CameraModule_HIK_soft_GIGE::readData(std::vector& mat, QByteArray& data) -{ - if (queuepic.isEmpty()) - { - //qCritical() << __FUNCTION__ << " line:" <<__LINE__ << " srcImage is null"; - return false; - } - n_mutex->lock(); - cv::Mat img = queuepic.dequeue(); - mat.push_back(img); - n_mutex->unlock(); - - qDebug() << "[INFO] " << __FUNCTION__ << " line:" << __LINE__ << " checkImg readData--CameraName:" << QString::fromStdString(Username) << "--imgIndex : " << imgIndex; - return true; -} - -//实例对象把数据写入到类;加载模型后会运行此函数 -bool Hd_CameraModule_HIK_soft_GIGE::writeData(std::vector& mat, QByteArray& data) -{ - Q_UNUSED(mat); - if (data.contains("deviceList")) { - auto result = QByteArrayToMV_CC_DeviceInfoList(data.mid(10)); - if (result.nDeviceNum != 0) { - m_stDevList = result; - return true; - } - } - QStringList dataList = QString::fromUtf8(data).split("_"); - //2024.02.18更新,相机对应的读SN信号时,表示新产品进入,设置初始值 - if (data == "rest_newProductIn") - { - //根据实际项目,设置初始值:曝光、增益,ROI区域等 - { - if (expourseTimeList.size() > 0) - SetExposureTime(expourseTimeList[0]); - if (gainList.size() > 0) - SetGain(gainList[0]); - } - if (queuepic.size() > 0) - { - n_mutex->lock(); - //queuepic.clear(); - n_mutex->unlock(); - std::cout << "rest_newProductIn , queuePic.size() > 0 ,signal maybe too fast " << Username << std::endl; - qWarning() << __FUNCTION__ << " line: " << __LINE__ << "rest_newProductIn , queuePic.size() > 0 ,signal maybe too fast " << QString::fromStdString(Username); - } - if (ifRunning == true) - { - ifBreak = true; - Sleep(10); - } - imgIndex = 0; - return true; - } - else if (dataList.size() > 1) { - if (dataList[0] == "cameraTriggerSignal") { - imgShouldGetVec.clear(); - imgShouldGetIndex = 0; - for (int i = 1; i < dataList.size(); i++) - imgShouldGetVec.push_back(dataList[i].toInt()); - } - } - else - { - m_flag = false; - expourseTimeList.clear(); - gainList.clear(); - } - //Username= data.toStdString(); - return true; -} -//传入initParas函数,格式为:相机key+参数名1#参数值1#参数值2+参数名2#参数值1... -bool Hd_CameraModule_HIK_soft_GIGE::initParas(QByteArray& initData) -{ - QByteArrayList valueList = initData.split('+'); - Username = valueList[0]; - imgIndex = 0; - expourseTimeList.clear(); - gainList.clear(); - if (valueList.size() > 1) - for (int i = 1; i < valueList.size(); i++) - { - QString valuei = byteArrayToUnicode(valueList[i]); - //valuei.prepend(valueList[i]); - if (valuei.contains("expourseTime")) - { - QStringList expourseTimeL = valuei.split('#'); - if (expourseTimeL.size() > 1) - for (int j = 1; j < expourseTimeL.size(); j++) - expourseTimeList.enqueue(expourseTimeL[j].toFloat()); - } - if (valuei.contains("gain")) - { - QStringList gainL = valuei.split('#'); - if (gainL.size() > 1) - for (int j = 1; j < gainL.size(); j++) - gainList.enqueue(gainL[j].toFloat()); - } - - if (valuei.contains("是否为标准通信流程")) - { - if (valuei.contains("true")) - ifStandard = true; - } - if (valuei.contains("取图超时")) - { - QStringList gainL = valuei.split('#'); - if (gainL.size() > 1) - getImageTimeOut = gainL[1].toInt(); - if (getImageTimeOut < 50) - getImageTimeOut = 1000; - } - if (valuei.contains("OffsetX")) - { - QStringList valueL = valuei.split('#'); - if (valueL.size() > 1) - if (valueL[1].toInt() >= 0) - MV_CC_SetIntValue(handle, "OffsetX", valueL[1].toInt()); - } - if (valuei.contains("OffsetY")) - { - QStringList valueL = valuei.split('#'); - if (valueL.size() > 1) - if (valueL[1].toInt() >= 0) - MV_CC_SetIntValue(handle, "OffsetY", valueL[1].toInt()); - } - if (valuei.contains("Width")) - { - QStringList valueL = valuei.split('#'); - if (valueL.size() > 1) - if (valueL[1].toInt() >= 0) - MV_CC_SetIntValue(handle, "Width", valueL[1].toInt()); - } - if (valuei.contains("Height")) - { - QStringList valueL = valuei.split('#'); - if (valueL.size() > 1) - if (valueL[1].toInt() >= 0) - MV_CC_SetIntValue(handle, "Height", valueL[1].toInt()); - } - } - - bool ifOk = connectDevice(); - if (ifOk == true) - { - if (expourseTimeList.size() > 0) - SetExposureTime(expourseTimeList[0]); - if (gainList.size() > 0) - SetGain(gainList[0]); - } - imgIndex = 0; - return ifOk; -} - -bool Hd_CameraModule_HIK_soft_GIGE::run() -{ - //queuepic.clear(); - qDebug() << "[INFO] " << " run start" << QString::fromStdString(Username); - bool result = false; - ifRunning = true; - ifBreak = false; - - try - { - m_flag = false; - int mytime = 0; - int cnt = 0; - MV_CC_SetCommandValue(handle, "TriggerSoftware"); - while (true) - { - /* if (moduleStatus == false || mytime++ > getImageTimeOut || ifBreak == true) - { - result = false; - break; - }*/ - n_mutex->lock(); - cnt++; - if (queuepic.size() > 0) - { - n_mutex->unlock(); - result = true; - std::cout << "\n gotImg" << std::endl; - break; - } - if (cnt > 120) { - queuepic.push_back(cv::Mat(200, 200, CV_8UC1, cv::Scalar(0))); //返回空图 - std::cout << "timeout" << std::endl; - n_mutex->unlock(); - return true; - } - n_mutex->unlock(); - QThread::msleep(10); - } - //考虑到误触发、漏触发的图,在这里进行设置。 - //需要设置曝光时 - if (ifStandard == true) - { - imgIndex++; - if (expourseTimeList.size() > 1 && expourseTimeList[imgIndex % expourseTimeList.size()] != expourseTimeList[(imgIndex - 1) % expourseTimeList.size()]) - SetExposureTime(expourseTimeList[imgIndex % expourseTimeList.size()]); - if (gainList.size() > 1 && gainList[imgIndex % gainList.size()] != gainList[(imgIndex - 1) % gainList.size()]) - SetGain(gainList[imgIndex % gainList.size()]); - } - } - catch (QString ev) - { - qDebug() << "[Error] " << " ev:" << ev; - } - qDebug() << "[INFO] " << __LINE__ << " run end"; - return result; -} - -//相机连接状态:正常连接或断开 -bool Hd_CameraModule_HIK_soft_GIGE::checkStatus() -{ - //status = moduleStatus; - return moduleStatus; -} - diff --git a/subModule/Hd_CameraModule_HIK_soft_GIGE/Hd_CameraModule_HIK_soft_GIGE.h b/subModule/Hd_CameraModule_HIK_soft_GIGE/Hd_CameraModule_HIK_soft_GIGE.h deleted file mode 100644 index 294c838..0000000 --- a/subModule/Hd_CameraModule_HIK_soft_GIGE/Hd_CameraModule_HIK_soft_GIGE.h +++ /dev/null @@ -1,43 +0,0 @@ -#ifndef Hd_CameraModule_HIK_soft_GIGE_H -#define Hd_CameraModule_HIK_soft_GIGE_H -#include -#include -#include -#include -#include -#include -#include -#include - -#include - -using namespace cv; -#pragma execution_character_set("utf-8") - -class Hd_CameraModule_HIK_soft_GIGE :public dsModuleBase -{ -public: - Hd_CameraModule_HIK_soft_GIGE(); - virtual ~Hd_CameraModule_HIK_soft_GIGE(); - //从类中读数据到实例对象 - bool readData(std::vector& mat, QByteArray& data); - //实例对象把数据写入到类 - bool writeData(std::vector& mat, QByteArray& data); - bool initParas(QByteArray& initData); - bool run(); - bool checkStatus(); -private: - std::vector imgShouldGetVec; - int imgShouldGetIndex = 0; - //MyThread *m_thread = nullptr; - //QMutex* m_mutex; -}; - -extern "C" -{ -Q_DECL_EXPORT Hd_CameraModule_HIK_soft_GIGE * create(); -Q_DECL_EXPORT void destory(Hd_CameraModule_HIK_soft_GIGE * ptr); -} - -#endif // Hd_CameraModule_HIK_hard_H -//Hd_CameraModule_HIK_soft_GIGE diff --git a/subModule/Hd_SocketModule_FinsTcp/CMakeLists.txt b/subModule/Hd_SocketModule_FinsTcp/CMakeLists.txt deleted file mode 100644 index 93c262c..0000000 --- a/subModule/Hd_SocketModule_FinsTcp/CMakeLists.txt +++ /dev/null @@ -1,70 +0,0 @@ -# 获取获取当前目录名 -get_filename_component(CURRENT_FOLDER ${CMAKE_CURRENT_SOURCE_DIR} NAME) -string(TIMESTAMP RUN_TIME) -message( " model start : " ${CURRENT_FOLDER}:${RUN_TIME}) - -STRING(REPLACE "/EHsc" "/EHa" CMAKE_CXX_FLAGS ${CMAKE_CXX_FLAGS}) -STRING(REPLACE "/RTC1" "" CMAKE_CXX_FLAGS_DEBUG ${CMAKE_CXX_FLAGS_DEBUG}) -SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /AI${CMAKE_CURRENT_SOURCE_DIR} /clr") -message( " model start : " ${CURRENT_FOLDER}:${RUN_TIME}) - -set(DLL_NAMES "opencv") -foreach(child ${DLL_NAMES}) - LIST(APPEND ENV_INCLUDE ${${child}_include}) - LIST(APPEND ENV_LIB ${${child}_lib}) - LIST(APPEND ENV_TARGET ${${child}_target_link}) -endforeach() -message(" ENV_INCLUDE : " ${ENV_INCLUDE} ) -message(" ENV_LIB : " ${ENV_LIB} ) -message(" ENV_TARGET : " ${ENV_TARGET} ) -include_directories( - ${ENV_INCLUDE} -) -link_directories ( - ${ENV_LIB} - -) - - -set(CMAKE_INCLUDE_CURRENT_DIR ON) -SET(CMAKE_CXX_STANDARD 11) -SET(CMAKE_CXX_STANDARD_REQUIRED ON) - -set(CMAKE_AUTOMOC ON) -SET(CMAKE_AUTOUIC OFF) -set(CMAKE_AUTORCC ON) - -FILE(GLOB HEAD_FILES "./*.h" ) -FILE(GLOB SRC_FILES "./*.cpp") -FILE(GLOB UI_FILES "./*.ui") - - -#find_package(Qt5 COMPONENTS Core REQUIRED) -find_package(QT NAMES Qt6 Qt5 COMPONENTS Core REQUIRED) -find_package(Qt${QT_VERSION_MAJOR} COMPONENTS Core Network REQUIRED) - -add_library(${CURRENT_FOLDER} SHARED - ${HEAD_FILES} - ${SRC_FILES} - ${UI_FILES} - ) - - - - -set_target_properties(${CURRENT_FOLDER} PROPERTIES LINKER_LANGUAGE C - RUNTIME_OUTPUT_DIRECTORY ${CMAKE_RUNTIME_OUTPUT_DIRECTORY} - LIBRARY_OUTPUT_DIRECTORY ${CMAKE_LIBRARY_OUTPUT_DIRECTORY} - ARCHIVE_OUTPUT_DIRECTORY ${CMAKE_ARCHIVE_OUTPUT_DIRECTORY} -) - -target_link_libraries(${CURRENT_FOLDER} PRIVATE - - ${opencv_target_link} - Qt${QT_VERSION_MAJOR}::Core - Qt${QT_VERSION_MAJOR}::Network -) - - -string(TIMESTAMP RUN_TIME) -message( " model end : " ${CURRENT_FOLDER}:${RUN_TIME}) diff --git a/subModule/Hd_SocketModule_FinsTcp/Hd_SocketModule_FinsTcp.cpp b/subModule/Hd_SocketModule_FinsTcp/Hd_SocketModule_FinsTcp.cpp deleted file mode 100644 index 886a2e1..0000000 --- a/subModule/Hd_SocketModule_FinsTcp/Hd_SocketModule_FinsTcp.cpp +++ /dev/null @@ -1,603 +0,0 @@ -#include "Hd_SocketModule_FinsTcp.h" -#include "qprocess.h" - - -static QQueue ReadPack; -//static QVector Failed_address; -//static QVector Failed_address; -static QQueue Failed_data; - -QMutex* readData_Mutex = new QMutex(); -QMutex* recive_Mutex = new QMutex(); -Hd_SocketModule_FinsTcp* create() -{ - qDebug() << "Hd_SocketModule_FinsTcp create success!"; - return new Hd_SocketModule_FinsTcp; -} - -void destory(Hd_SocketModule_FinsTcp* ptr) -{ - - if (ptr) - { - delete ptr; - ptr = nullptr; - } - qDebug() << " Hd_SocketModule_FinsTcp destory success!"; -} -bool ifRun = true; -Hd_SocketModule_FinsTcp::Hd_SocketModule_FinsTcp() -{ - ifRun = true; - *m_pFinsTcpNet = gcnew HslCommunication::Profinet::Omron::OmronFinsNet(); -} -bool m_IsFinsTcp = false; -Hd_SocketModule_FinsTcp::~Hd_SocketModule_FinsTcp() -{ - ifRun = false; - Sleep(100); - if (status == false) - Sleep(3000); - if (m_IsFinsTcp) - { - if ((*m_pFinsTcpNet)->ConnectClose()->IsSuccess) - { - qDebug() << " (*m_pFinsTcpNet)->ConnectClose() success!"; - }else { - qCritical() << " (*m_pFinsTcpNet)->ConnectClose() failed!"; - } - m_IsFinsTcp = false; - } - qDebug() << " ~Hd_SocketModule_FinsTcp success!"; -} - -// 从类中读数据到实例对象 -bool Hd_SocketModule_FinsTcp::readData(std::vector& vec_mat, QByteArray& data) -{ - Q_UNUSED(vec_mat); - QMutexLocker locker(readData_Mutex); - - QByteArray statusVaule; - /*if (tcp_Status) - { - statusVaule = "truee"; - } - else - { - statusVaule = "false"; - }*/ - - if (ReadPack.isEmpty()) - { - data = statusVaule; - return true; - } - else - { - data.append(statusVaule); - data.append(ReadPack.dequeue()); - //qDebug() << " ReadPack len: " << ReadPack.length() << " data: " << data; - } - return true; -} -bool ifRetryCMD = false; -// 实例对象把数据写入到类 -bool Hd_SocketModule_FinsTcp::writeData(std::vector& vec_mat, QByteArray& data) -{ - Q_UNUSED(vec_mat); - if (ifRetryCMD == false) - QMutexLocker locker(recive_Mutex); - Sleep(sleepvalue); - QString str = QString(data); - if ( data.isEmpty() ) - { - qCritical() << " str is null"; - return false; - } - - QList m_list = data.split('_'); - if (m_list.size() < 4) - { - qCritical() << data+" m_list.size() != 4;command err"; - return false; - } - QString m_value= m_list.at(3); - QString commond = m_list.at(0); - if ( commond == "init" ){ - System::String^ Code = gcnew System::String("b5f8f9f7-c075-4913-ae6e-d7d2cc6f2de1"); - if (HslCommunication::Authorization::SetAuthorizationCode(Code)) - { - std::cout << "Register HSLCode Success" << std::endl; - } - else - { - std::cout << "Register HSLCode Fail" << std::endl; - } - - if (m_list.length() < 6) - { - qCritical() << " m_list failed! " << m_list; - return false; - } - - m_IP = m_list.at(1); - m_port = m_list.at(2); - SA1 = m_list.at(3); - DA1 = m_list.at(4); - DA2 = m_list.at(5); - } - else if (commond == "read") { - //"read_byte_D3000_300", - while (ifRun) - { - //if (sleepvalue < 2) - // Sleep(2); // 读取速度过快,添加10ms延时 - //else - Sleep(sleepvalue); - - int length = m_list[3].toInt(); - System::String^ address = gcnew System::String(m_list[2].toStdString().c_str()); - HslCommunication::OperateResult^>^ result = (*m_pFinsTcpNet)->Read(address, length); - if (!result->IsSuccess) - { - tcp_Status = false; - qCritical() << " (*FinsTcp)->ReadInt16 failed! check DA1: " << DA1; - - QProcess pingProcess; - QString strArg = "ping " + m_IP + " -n 1 -i 2"; //strPingIP 为设备IP地址 - pingProcess.start(strArg, QIODevice::ReadOnly); - pingProcess.waitForFinished(-1); - - QString p_stdout = QString::fromLocal8Bit(pingProcess.readAllStandardOutput()); - - //qDebug() << p_stdout; - bool bPingSuccess = false; - - if (p_stdout.contains("TTL=")) //通过特殊字符串进行判断ping是否成功 - { - //printf("Ping true\n"); - bPingSuccess = true; - //QMessageBox::information(this, "ping PLC:", "success!"); - //qCritical() << __FUNCTION__ << " line:" << __LINE__ << " ping PLC success! "; - } - else - { - /*printf("Ping false\n"); - bPingSuccess = false; - QMessageBox::information(this, "ping PLC:", "failed!");*/ - qCritical() << __FUNCTION__ << " line:" << __LINE__ << " ping PLC failed! "; - } - // - if (!Failed_data.contains(data)) - Failed_data.enqueue(data); - //if (m_IsFinsTcp) - { - //(*m_pFinsTcpNet)->Dispose(); - //qDebug() << " (*m_pFinsTcpNet)->Dispose() success!"; - - if ((*m_pFinsTcpNet)->ConnectClose()->IsSuccess) - { - qDebug() << " (*m_pFinsTcpNet)->ConnectClose() success!"; - } - else { - qCritical() << " (*m_pFinsTcpNet)->ConnectClose() failed!"; - } - //m_IsFinsTcp = false; - delete* m_pFinsTcpNet; - Sleep(50); - *m_pFinsTcpNet = gcnew HslCommunication::Profinet::Omron::OmronFinsNet(); - (*m_pFinsTcpNet)->IpAddress = gcnew System::String(m_IP.toStdString().c_str()); - (*m_pFinsTcpNet)->Port = stoi(m_port.toStdString()); - Sleep(10); - } - - //if ((*m_pFinsTcpNet)->ConnectClose()->IsSuccess) - //{ - // qDebug() << " (*m_pFinsTcpNet)->ConnectClose() success!"; - //} - //else { - // qCritical() << " (*m_pFinsTcpNet)->ConnectClose() failed!"; - //} - int xunhuan_num = 20; - while (xunhuan_num && ifRun) { - qDebug() << " TRY xunhuan_num: "<< xunhuan_num; - (*m_pFinsTcpNet)->SA1 = (unsigned char)stoi(SA1.toStdString()); - (*m_pFinsTcpNet)->DA1 = (unsigned char)stoi(DA1.toStdString());//DA1.toStdString().c_str();//可以测试DA1累加1,不超过255 - (*m_pFinsTcpNet)->DA2 = (unsigned char)stoi(DA2.toStdString()); - (*m_pFinsTcpNet)->ConnectTimeOut = 1000; // 连接超时2秒 - (*m_pFinsTcpNet)->ReceiveTimeOut = 500; // 收发超时0.5秒 - if ((*m_pFinsTcpNet)->ConnectServer()->IsSuccess) - { - m_IsFinsTcp = true; - tcp_Status = true; - /*QVector Writefailpack; - for (QVector::iterator ii = WriteFailPack.begin(); ii != WriteFailPack.end(); ii++) - { - for (int val = 0; val < 5; val++) - { - if (!(*m_pFinsTcpNet)->Write(address, ii)->IsSuccess) - { - if (val == 4) Writefailpack.push_back(*ii); - continue; - } - else - { - break; - } - } - } - WriteFailPack.clear(); - WriteFailPack = Writefailpack; - Writefailpack.clear();*/ - qDebug() << " Connect Success! SA1: " << SA1 << "DA1 :" << DA1; - - ifRetryCMD = true; - for (int i = 0; i < Failed_data.size(); i++) - { - QByteArray try_data = Failed_data.dequeue(); - std::vector my_vec_mat; - qDebug() << " try_data:: " << try_data; - writeData(my_vec_mat, try_data); - Sleep(10); - } - ifRetryCMD = false; - return tcp_Status; - } - else - { - xunhuan_num--; - if (SA1 > 255) - SA1 = 50; - SA1 = QString::number(SA1.toInt() + 1); - if (DA1 > 255) - DA1 = 50; - DA1 = QString::number(DA1.toInt() + 1); - tcp_Status = false; - qCritical() << " Connect failed! SA1: " << SA1 << "DA1 : " << DA1; - Sleep(100); - } - } - return false; - //continue; - } - - unsigned char* valuePtr = new unsigned char[m_list[3].toInt() * 2]; - QByteArray byte; - for (int i = 0; i < length * 2; i++) - { - valuePtr[i] = result->Content[i]; - char v = result->Content[i]; - byte.append(v); - } - - ReadPack.append(byte); - if (valuePtr) { - delete[] valuePtr; - valuePtr = nullptr; - } - tcp_Status = true; - break; - } - - } - else if ( commond == "write" ) - { - //例"write_short_D1003_1","write_short_D1003_1,1,1,1", - if (m_list[1] == "short") - { - QString vecValue = m_list.at(3); - QStringList valueList = vecValue.split(","); - cli::array^ write_list = gcnew cli::array(valueList.length()); - for (int i = 0; i < valueList.length(); i++) - { - write_list[i] = valueList[i].toShort(); - } - - System::String^ address = gcnew System::String(m_list[2].toStdString().c_str()); - for (auto val = 0; val < 5; val++) - { - //Sleep(sleepvalue); - if (!(*m_pFinsTcpNet)->HslCommunication::Core::Net::NetworkDeviceBase::Write(address, write_list)->IsSuccess) - { - qCritical() << " val: " << val++ << " writeAll failed! m_list: " << m_list; - Failed_data.enqueue(data); - Sleep(sleepvalue); - } - else { - qDebug() << "[TCP] " << str << endl; - return true; - } - } - tcp_Status = false; - return false; - } - if (m_list[1] == "float") - { - QString vecValue = m_list.at(3); - QStringList valueList = vecValue.split(","); - cli::array^ write_list = gcnew cli::array(valueList.length()); - for (int i = 0; i < valueList.length(); i++) - { - write_list[i] = valueList[i].toFloat(); - } - - System::String^ address = gcnew System::String(m_list[2].toStdString().c_str()); - for (auto val = 0; val < 5; val++) - { - //Sleep(sleepvalue); - if (!(*m_pFinsTcpNet)->HslCommunication::Core::Net::NetworkDeviceBase::Write(address, write_list)->IsSuccess) - { - qCritical() << " val: " << val++ << " writeAll failed! m_list: " << m_list; - Failed_data.enqueue(data); - Sleep(sleepvalue); - } - else { - qDebug() << "[TCP] " << str << endl; - return true; - } - } - tcp_Status = false; - return false; - } - if (m_list[1] == "double") - { - QString vecValue = m_list.at(3); - QStringList valueList = vecValue.split(","); - cli::array^ write_list = gcnew cli::array(valueList.length()); - for (int i = 0; i < valueList.length(); i++) - { - write_list[i] = valueList[i].toDouble(); - } - - System::String^ address = gcnew System::String(m_list[2].toStdString().c_str()); - for (auto val = 0; val < 5; val++) - { - //Sleep(sleepvalue); - if (!(*m_pFinsTcpNet)->HslCommunication::Core::Net::NetworkDeviceBase::Write(address, write_list)->IsSuccess) - { - qCritical() << " val: " << val++ << " writeAll failed! m_list: " << m_list; - Failed_data.enqueue(data); - Sleep(sleepvalue); - } - else { - qDebug() << "[TCP] " << str << endl; - return true; - } - } - tcp_Status = false; - return false; - } - - - if (m_list[1] == "string") - { - System::String^ address = gcnew System::String(m_list[2].toStdString().c_str()); - System::String^ write_Value = gcnew System::String(m_list.at(3).toStdString().c_str()); - for (auto val = 0; val < 5; val++) - { - //Sleep(sleepvalue); - if (!(*m_pFinsTcpNet)->Write(address, write_Value)->IsSuccess) { - qCritical() << " val: " << val++ << " writeString failed! m_list: " << m_list; - Failed_data.enqueue(data); - Sleep(sleepvalue); - } - else { - qDebug() << "[TCP] " << str << endl; - return true; - } - } - tcp_Status = false; - return false; - } - } - else if (commond == "writeHeart") - { - //例"write_short_D1003_1","write_short_D1003_1,1,1,1", - if (m_list[1] == "short") - { - QString vecValue = m_list.at(3); - QStringList valueList = vecValue.split(","); - cli::array^ write_list = gcnew cli::array(valueList.length()); - for (int i = 0; i < valueList.length(); i++) - { - write_list[i] = valueList[i].toShort(); - } - - System::String^ address = gcnew System::String(m_list[2].toStdString().c_str()); - for (auto val = 0; val < 5; val++) - { - //Sleep(sleepvalue); - if (!(*m_pFinsTcpNet)->HslCommunication::Core::Net::NetworkDeviceBase::Write(address, write_list)->IsSuccess) - { - qCritical() << " val: " << val++ << " writeAll failed! m_list: " << m_list; - Failed_data.enqueue(data); - Sleep(sleepvalue); - } - else { - return true; - } - } - tcp_Status = false; - return false; - } - if (m_list[1] == "float") - { - QString vecValue = m_list.at(3); - QStringList valueList = vecValue.split(","); - cli::array^ write_list = gcnew cli::array(valueList.length()); - for (int i = 0; i < valueList.length(); i++) - { - write_list[i] = valueList[i].toFloat(); - } - - System::String^ address = gcnew System::String(m_list[2].toStdString().c_str()); - for (auto val = 0; val < 5; val++) - { - //Sleep(sleepvalue); - if (!(*m_pFinsTcpNet)->HslCommunication::Core::Net::NetworkDeviceBase::Write(address, write_list)->IsSuccess) - { - qCritical() << " val: " << val++ << " writeAll failed! m_list: " << m_list; - Failed_data.enqueue(data); - Sleep(sleepvalue); - } - else { - qDebug() << "[TCP] " << str << endl; - return true; - } - } - tcp_Status = false; - return false; - } - if (m_list[1] == "double") - { - QString vecValue = m_list.at(3); - QStringList valueList = vecValue.split(","); - cli::array^ write_list = gcnew cli::array(valueList.length()); - for (int i = 0; i < valueList.length(); i++) - { - write_list[i] = valueList[i].toDouble(); - } - - System::String^ address = gcnew System::String(m_list[2].toStdString().c_str()); - for (auto val = 0; val < 5; val++) - { - //Sleep(sleepvalue); - if (!(*m_pFinsTcpNet)->HslCommunication::Core::Net::NetworkDeviceBase::Write(address, write_list)->IsSuccess) - { - qCritical() << " val: " << val++ << " writeAll failed! m_list: " << m_list; - Failed_data.enqueue(data); - Sleep(sleepvalue); - } - else { - qDebug() << "[TCP] " << str << endl; - return true; - } - } - tcp_Status = false; - return false; - } - - - if (m_list[1] == "string") - { - System::String^ address = gcnew System::String(m_list[2].toStdString().c_str()); - System::String^ write_Value = gcnew System::String(m_list.at(3).toStdString().c_str()); - for (auto val = 0; val < 5; val++) - { - //Sleep(sleepvalue); - if (!(*m_pFinsTcpNet)->Write(address, write_Value)->IsSuccess) { - qCritical() << " val: " << val++ << " writeString failed! m_list: " << m_list; - Failed_data.enqueue(data); - Sleep(sleepvalue); - } - else { - qDebug() << "[TCP] " << str << endl; - return true; - } - } - tcp_Status = false; - return false; - } - } - return true; -} - -bool Hd_SocketModule_FinsTcp::initParas(QByteArray& data) -{ - - if (data.isEmpty()) - { - qWarning()<< "[TCP] " << " data is null!"; - } - else - { - QString initDat = QString::fromUtf8(data); - QStringList list = initDat.split("_"); - if (list.size() < 3) - { - qCritical() << "[TCP] " << " list size error :" << list.size(); - return false; - } - - QString sleepname = list.at(0); - sleepvalue = list.at(1).toInt(); - if (sleepvalue == 0)sleepvalue = 1; - /*if (sleepvalue <= 5) - sleepvalue = 30;*/ - QString readname = list.at(2); - QString readvalue = list.at(3); - QString write_type = list.at(4); - QString write_value = list.at(5); - } - - // 连接通讯 - *m_pFinsTcpNet = gcnew HslCommunication::Profinet::Omron::OmronFinsNet(); - (*m_pFinsTcpNet)->IpAddress = gcnew System::String(m_IP.toStdString().c_str()); - (*m_pFinsTcpNet)->Port = stoi(m_port.toStdString()); - int xunhuan_num = 20; - while (xunhuan_num && ifRun) { - (*m_pFinsTcpNet)->SA1 = (unsigned char)stoi(SA1.toStdString()); - (*m_pFinsTcpNet)->DA1 = (unsigned char)stoi(DA1.toStdString());//DA1.toStdString().c_str(); - (*m_pFinsTcpNet)->DA2 = (unsigned char)stoi(DA2.toStdString()); - (*m_pFinsTcpNet)->ConnectTimeOut = 500; // 连接超时0.5秒 - (*m_pFinsTcpNet)->ReceiveTimeOut = 500; // 收发超时0.5秒 - if ((*m_pFinsTcpNet)->ConnectServer()->IsSuccess) - { - m_IsFinsTcp = true; - tcp_Status = true; - qDebug() << " Connect Success! SA1: " << SA1; - return tcp_Status; - } - else - { - xunhuan_num--; - SA1 = QString::number(SA1.toInt() + 1); - tcp_Status = false; - qCritical() <<" Connect failed! SA1: " << SA1; - - } - Sleep(100); - } - return tcp_Status; - -} - -bool Hd_SocketModule_FinsTcp::run() -{ - // 没有用到 - //qDebug() << "[info] " << __FUNCTION__ << " line:" << __LINE__ << " success!"; - return true; -} - - -bool Hd_SocketModule_FinsTcp::decodeWriteResult(QByteArray byte, QVector& vec_ret) -{ - try - { - if (byte.isEmpty()) - { - qCritical() << __FUNCTION__ << "line:" << __LINE__ << " byte is null!"; - return false; - } - while (!byte.isEmpty()) - { - int len = 0; - QByteArray m_len = byte.mid(0, 4); - memcpy((void*)&len, (void*)m_len.data(), 4); - byte.remove(0, 4); - - QByteArray mm_data = byte.mid(0, len); - vec_ret.append(QString::fromUtf8(mm_data)); - byte.remove(0, len); - } - } - catch (QString ev) { - qCritical() << __FUNCTION__ << " line:" << __LINE__ << " ev:" << ev; - return false; - } - return true; -} -bool Hd_SocketModule_FinsTcp::checkStatus() -{ - return tcp_Status; -} \ No newline at end of file diff --git a/subModule/Hd_SocketModule_FinsTcp/Hd_SocketModule_FinsTcp.h b/subModule/Hd_SocketModule_FinsTcp/Hd_SocketModule_FinsTcp.h deleted file mode 100644 index 2b3f969..0000000 --- a/subModule/Hd_SocketModule_FinsTcp/Hd_SocketModule_FinsTcp.h +++ /dev/null @@ -1,50 +0,0 @@ -#ifndef Hd_SocketModule_FinsTcp_H -#define Hd_SocketModule_FinsTcp_H - -#include -#include -#include -#include -#include -#include -#include - -#include -#include - -#using "../../bin/HslCommunication.dll" - -using namespace HslCommunication; -using namespace cli; - -class Hd_SocketModule_FinsTcp :public dsModuleBase -{ -public: - Hd_SocketModule_FinsTcp(); - virtual ~Hd_SocketModule_FinsTcp(); - //bool readData(std::vector& vec_mat, QByteArray& data, nlohmann::json&); // readData将PLC读取或者发送的返回值发回给主线程,通过全局变量的方式逐条发送 - //bool writeData(std::vector& vec_mat, QByteArray& data, nlohmann::json&); // writeData调用PLC的收发,将需要的数据发给寄存器,返回OK/NG - bool readData(std::vector&, QByteArray&); - bool writeData(std::vector&, QByteArray&); - bool initParas(QByteArray&); - bool run(); - bool decodeWriteResult(QByteArray byteArray, QVector& vec_ret); - bool checkStatus(); -private: - gcroot* m_pFinsTcpNet = new gcroot; - bool tcp_Status = true; // 检查tcp状态 - QString m_IP; - QString SA1; - QString DA1; - QString DA2; - QString m_port; // 端口 - int sleepvalue=1; // 刷新间隔 -}; - -extern "C" -{ -Q_DECL_EXPORT Hd_SocketModule_FinsTcp * create(); -Q_DECL_EXPORT void destory(Hd_SocketModule_FinsTcp * ptr); -} - -#endif // Hd_SocketModule_FinsTcp_H diff --git a/subModule/Hd_SocketModule_FinsTcp/HslCommunication.dll b/subModule/Hd_SocketModule_FinsTcp/HslCommunication.dll deleted file mode 100644 index 8a764c1..0000000 Binary files a/subModule/Hd_SocketModule_FinsTcp/HslCommunication.dll and /dev/null differ