From 1864c6cf044f87e115a2390d57a4d00cefbb86e2 Mon Sep 17 00:00:00 2001 From: seiyu Date: Tue, 12 Mar 2024 15:50:59 +0800 Subject: [PATCH] =?UTF-8?q?=E8=BE=83=E5=A4=9A=E5=8F=98=E5=8A=A8=E4=B8=BB?= =?UTF-8?q?=E8=A6=81=E6=98=AF=E5=9C=A8=E4=BA=8E=E6=94=B9=E5=8F=98=E4=BA=86?= =?UTF-8?q?=E7=BC=96=E7=A0=81=EF=BC=8C=E4=BB=A3=E7=A0=81=E6=A0=BC=E5=BC=8F?= =?UTF-8?q?=E5=8F=91=E7=94=9F=E5=8F=98=E5=8C=96;=20=E4=BB=A3=E7=A0=81?= =?UTF-8?q?=E5=8F=98=E5=8A=A8=E4=B8=BB=E8=A6=81=E5=9C=A8syncworkthread.cpp?= =?UTF-8?q?=EF=BC=8C=E4=BF=AE=E5=A4=8D=E4=BA=86=E7=9B=B8=E6=9C=BA=E6=96=AD?= =?UTF-8?q?=E5=BC=80=E5=90=8E=E6=95=B0=E6=8D=AE=E4=BB=8D=E5=9C=A8=E5=8F=98?= =?UTF-8?q?=E5=8A=A8=E7=9A=84=E9=97=AE=E9=A2=98=E3=80=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Cigarette/ASyncQueue.cpp | 2 +- Cigarette/ASyncQueue.h | 56 +- Cigarette/AlarmInfo.cpp | 3 - Cigarette/AlarmInfo.h | 13 +- Cigarette/CaptureThread.cpp | 204 +- Cigarette/CaptureThread.h | 330 +- Cigarette/CaptureThreadBasler.cpp | 284 +- Cigarette/CaptureThreadBasler.h | 298 +- Cigarette/CaptureThreadHIK.cpp | 387 +- Cigarette/CaptureThreadHIK.h | 62 +- Cigarette/Cigarette.vcxproj | 4 - Cigarette/Cigarette.vcxproj.filters | 3 - Cigarette/Cleanthread.cpp | 238 +- Cigarette/Cleanthread.h | 28 +- Cigarette/FtpManager.h | 102 +- Cigarette/Logthread.cpp | 220 +- Cigarette/Logthread.h | 72 +- Cigarette/PLC/PLCDevice.cpp | 158 +- Cigarette/PLC/PLCDevice.h | 14 +- Cigarette/SyncQueue.cpp | 2 +- Cigarette/SyncQueue.h | 84 +- Cigarette/alarmdialog.cpp | 56 +- Cigarette/alarmdialog.hpp | 14 +- Cigarette/alg_jd.cpp | 238 +- Cigarette/alg_jd.h | 38 +- Cigarette/balluffcamera.cpp | 8 +- Cigarette/balluffcamera.h | 18 +- Cigarette/basecamera.h | 18 +- Cigarette/baslercamera.cpp | 50 +- Cigarette/baslercamera.h | 22 +- Cigarette/camera_glue.cpp | 44 +- Cigarette/camera_glue.h | 18 +- Cigarette/change_shift.cpp | 128 +- Cigarette/change_shift.h | 14 +- Cigarette/cigarette.cpp | 7092 ++++++++++++++------------- Cigarette/cigarette.h | 304 +- Cigarette/common.cpp | 648 +-- Cigarette/common.h | 292 +- Cigarette/db_label.cpp | 14 +- Cigarette/db_label.h | 6 +- Cigarette/debugthread.h | 111 +- Cigarette/dialogin.cpp | 91 +- Cigarette/dialogin.hpp | 44 +- Cigarette/dialogsetup.cpp | 1342 ++--- Cigarette/dialogsetup.hpp | 110 +- Cigarette/dialogsetuppasswd.cpp | 88 +- Cigarette/dialogsetuppasswd.hpp | 44 +- Cigarette/exportData.cpp | 606 +-- Cigarette/exportData.h | 192 +- Cigarette/hikcamera.cpp | 34 +- Cigarette/hikcamera.h | 10 +- Cigarette/main.cpp | 32 +- Cigarette/output_statistic.cpp | 64 +- Cigarette/output_statistic.h | 12 +- Cigarette/plc_item.h | 12 +- Cigarette/plcsetup.cpp | 462 +- Cigarette/plcsetup.hpp | 34 +- Cigarette/savethread.h | 140 +- Cigarette/syncworkthread.cpp | 515 +- Cigarette/syncworkthread.h | 44 +- Cigarette/threadReceive.cpp | 124 +- Cigarette/threadReceive.h | 42 +- Cigarette/threadSend.cpp | 92 +- Cigarette/threadSend.h | 112 +- Cigarette/threadSendTCP.cpp | 7 +- Cigarette/threadSendTCP.h | 64 +- Cigarette/tinyxml2.cpp | 4598 ++++++++--------- Cigarette/tinyxml2.h | 4044 +++++++-------- Cigarette/workthread.cpp | 472 +- Cigarette/workthread.h | 46 +- 70 files changed, 12592 insertions(+), 12582 deletions(-) diff --git a/Cigarette/ASyncQueue.cpp b/Cigarette/ASyncQueue.cpp index a019c79c..5f96635a 100644 --- a/Cigarette/ASyncQueue.cpp +++ b/Cigarette/ASyncQueue.cpp @@ -1,3 +1,3 @@ #include "ASyncQueue.h" - + diff --git a/Cigarette/ASyncQueue.h b/Cigarette/ASyncQueue.h index b4d004e6..578cd0ec 100644 --- a/Cigarette/ASyncQueue.h +++ b/Cigarette/ASyncQueue.h @@ -3,28 +3,28 @@ //#include #include #include - + using namespace std; - + template class ASyncQueue { public: - ASyncQueue(int max_size); - ~ASyncQueue(); - void put(const T& val); - void take(T& val); - void clear(); - bool isEmpty(); - bool isFull(); - int count(); + ASyncQueue(int max_size); + ~ASyncQueue(); + void put(const T& val); + void take(T& val); + void clear(); + bool isEmpty(); + bool isFull(); + int count(); public: - string name; + string name; private: - mutex lock; - //condition_variable_any cv_full, cv_empty; - list q; - int size; - int max_size; + mutex lock; + //condition_variable_any cv_full, cv_empty; + list q; + int size; + int max_size; }; using namespace std; @@ -42,40 +42,40 @@ ASyncQueue::~ASyncQueue() template void ASyncQueue::put(const T& val) { - lock_guard locker(lock); - q.emplace_back(val); + lock_guard locker(lock); + q.emplace_back(val); } template void ASyncQueue::take(T& val) { - lock_guard locker(lock); - val = q.front(); - q.pop_front(); + lock_guard locker(lock); + val = q.front(); + q.pop_front(); } template void ASyncQueue::clear() { - lock_guard locker(lock); - q.clear(); + lock_guard locker(lock); + q.clear(); } template bool ASyncQueue::isEmpty() { - return q.size() == 0; + return q.size() == 0; } template bool ASyncQueue::isFull() { - return q.size() == max_size; + return q.size() == max_size; } template int ASyncQueue::count() { - lock_guard locker(lock); - return q.size(); -} \ No newline at end of file + lock_guard locker(lock); + return q.size(); +} diff --git a/Cigarette/AlarmInfo.cpp b/Cigarette/AlarmInfo.cpp index 9728b747..1e5c799f 100644 --- a/Cigarette/AlarmInfo.cpp +++ b/Cigarette/AlarmInfo.cpp @@ -1,12 +1,9 @@ #include "AlarmInfo.h" - - AlarmInfo::AlarmInfo() { } - AlarmInfo::~AlarmInfo() { } diff --git a/Cigarette/AlarmInfo.h b/Cigarette/AlarmInfo.h index 4bee8660..dbb2e46d 100644 --- a/Cigarette/AlarmInfo.h +++ b/Cigarette/AlarmInfo.h @@ -3,13 +3,12 @@ class AlarmInfo { public: - AlarmInfo(); - ~AlarmInfo(); + AlarmInfo(); + ~AlarmInfo(); public: - std::string alarm_start; //报警发生时间 - std::string alarm_handle; //报警处理时间 - std::string alarm_msg; //报警信息 - int alarm_code; //报警代码 + std::string alarm_start; //鎶ヨ鍙戠敓鏃堕棿 + std::string alarm_handle; //鎶ヨ澶勭悊鏃堕棿 + std::string alarm_msg; //鎶ヨ淇℃伅 + int alarm_code; //鎶ヨ浠g爜 }; - diff --git a/Cigarette/CaptureThread.cpp b/Cigarette/CaptureThread.cpp index fa956f92..709857cb 100644 --- a/Cigarette/CaptureThread.cpp +++ b/Cigarette/CaptureThread.cpp @@ -2,165 +2,165 @@ #include "common.h" #include "exportData.h" -extern bool g_debug_mode; //相机调试模式,工作模式必须停止状态才能打开 +extern bool g_debug_mode; //鐩告満璋冭瘯妯″紡锛屽伐浣滄ā寮忓繀椤诲仠姝㈢姸鎬佹墠鑳芥墦寮 extern SyncQueue<_XMLExportDataInfo>* export_XMLData_Info_queue; //----------------------------------------------------------------------------- -CaptureThread::CaptureThread( Device* pCurrDev, bool boTerminated, FunctionInterface* pFI_ ,int Num) : - pDev_( pCurrDev ), boTerminated_( boTerminated ), requestPendingForDisplay_( INVALID_ID ), pFI_( pFI_ ),Local_Num(Num) -//----------------------------------------------------------------------------- +CaptureThread::CaptureThread(Device* pCurrDev, bool boTerminated, FunctionInterface* pFI_, int Num) : + pDev_(pCurrDev), boTerminated_(boTerminated), requestPendingForDisplay_(INVALID_ID), pFI_(pFI_), Local_Num(Num) + //----------------------------------------------------------------------------- { - p_unit_queue = new ASyncQueue(Unit_Queue_Size); + p_unit_queue = new ASyncQueue(Unit_Queue_Size); } void CaptureThread::fpsTimeout(void) { - uint64_t delta = m_cntGrabbedImages - m_cntLastGrabbedImages; - m_cntLastGrabbedImages = m_cntGrabbedImages; - QString data = QString("%1").arg(delta); - emit updateStatistics(data.left(4), Local_Num); + uint64_t delta = m_cntGrabbedImages - m_cntLastGrabbedImages; + m_cntLastGrabbedImages = m_cntGrabbedImages; + QString data = QString("%1").arg(delta); + emit updateStatistics(data.left(4), Local_Num); } CaptureThread::~CaptureThread() { - delete p_unit_queue; + delete p_unit_queue; } //----------------------------------------------------------------------------- -void CaptureThread::process( void ) +void CaptureThread::process(void) //----------------------------------------------------------------------------- { try { - //Line5回调 - mvIMPACT::acquire::GenICam::EventControl pEventCtrl_(pDev_); - //pEventCtrl_.eventSelector.writeS("Line5FallingEdge"); - //pEventCtrl_.eventNotification.writeS("Off"); - //pEventCtrl_.eventSelector.writeS("Line5RisingEdge"); - //pEventCtrl_.eventNotification.writeS("Off"); - pEventCtrl_.eventSelector.writeS("Line5AnyEdge"); + //Line5鍥炶皟 + mvIMPACT::acquire::GenICam::EventControl pEventCtrl_(pDev_); + //pEventCtrl_.eventSelector.writeS("Line5FallingEdge"); + //pEventCtrl_.eventNotification.writeS("Off"); + //pEventCtrl_.eventSelector.writeS("Line5RisingEdge"); + //pEventCtrl_.eventNotification.writeS("Off"); + pEventCtrl_.eventSelector.writeS("Line5AnyEdge"); #ifdef IMM_PROCESS - pEventCtrl_.eventNotification.writeS("Off"); + pEventCtrl_.eventNotification.writeS("Off"); #else - pEventCtrl_.eventNotification.writeS("On"); + pEventCtrl_.eventNotification.writeS("On"); #endif #ifndef IMM_PROCESS - EventCallback eventCallback(&pEventCtrl_); - eventCallback.p_unit_queue_ = p_unit_queue; + EventCallback eventCallback(&pEventCtrl_); + eventCallback.p_unit_queue_ = p_unit_queue; #ifdef SYNC_CAMERA - eventCallback.p_image_sync_arr_ = p_image_sync_arr; - eventCallback.p_image_sync_queue_ = p_image_sync_queue; + eventCallback.p_image_sync_arr_ = p_image_sync_arr; + eventCallback.p_image_sync_queue_ = p_image_sync_queue; #else - eventCallback.p_image_queue_ = p_image_queue; + eventCallback.p_image_queue_ = p_image_queue; #endif - eventCallback.p_result_wait_queue_ = p_result_wait_queue; - eventCallback.p_shooted_queue_ = p_shooted_queue; - eventCallback.p_double_queue_ = p_double_queue; - eventCallback.m_pMVCamera = pDev_; - eventCallback.pCaptureThread = this; - eventCallback.registerComponent(pEventCtrl_.eventLine5AnyEdge); + eventCallback.p_result_wait_queue_ = p_result_wait_queue; + eventCallback.p_shooted_queue_ = p_shooted_queue; + eventCallback.p_double_queue_ = p_double_queue; + eventCallback.m_pMVCamera = pDev_; + eventCallback.pCaptureThread = this; + eventCallback.registerComponent(pEventCtrl_.eventLine5AnyEdge); #endif - m_threadFunc.m_pMVCamera = pDev_; - m_threadFunc.p_result_queue_ = p_result_queue; - m_threadFunc.p_double_queue_ = p_double_queue; + m_threadFunc.m_pMVCamera = pDev_; + m_threadFunc.p_result_queue_ = p_result_queue; + m_threadFunc.p_double_queue_ = p_double_queue; - //相机掉线回调 - CIwtCameraLostCallbackMV cam_lost_cb; - cam_lost_cb.channel_ = Local_Num; - if (cam_lost_cb.registerComponent(pDev_->state) != true) - { - std::cout << "ERROR: Unable to register the camera's lost CallBack function!\n"; - } - //图像采集循环 + //鐩告満鎺夌嚎鍥炶皟 + CIwtCameraLostCallbackMV cam_lost_cb; + cam_lost_cb.channel_ = Local_Num; + if (cam_lost_cb.registerComponent(pDev_->state) != true) + { + std::cout << "ERROR: Unable to register the camera's lost CallBack function!\n"; + } + //鍥惧儚閲囬泦寰幆 TDMR_ERROR result = DMR_NO_ERROR; - while( ( result = static_cast< TDMR_ERROR >( pFI_->imageRequestSingle() ) ) == DMR_NO_ERROR ) {}; - if( result != DEV_NO_FREE_REQUEST_AVAILABLE ) + while ((result = static_cast(pFI_->imageRequestSingle())) == DMR_NO_ERROR) {}; + if (result != DEV_NO_FREE_REQUEST_AVAILABLE) { - qDebug() << "'FunctionInterface.imageRequestSingle' returned with an unexpected result: " << QString::fromStdString( mvIMPACT::acquire::ImpactAcquireException::getErrorCodeAsString( result ) ); + qDebug() << "'FunctionInterface.imageRequestSingle' returned with an unexpected result: " << QString::fromStdString(mvIMPACT::acquire::ImpactAcquireException::getErrorCodeAsString(result)); } - manuallyStartAcquisitionIfNeeded( pDev_, *pFI_ ); + manuallyStartAcquisitionIfNeeded(pDev_, *pFI_); int cnt = 0; // run thread loop - mvIMPACT::acquire::Statistics statistics( pDev_ ); + mvIMPACT::acquire::Statistics statistics(pDev_); mvIMPACT::acquire::Request* pRequest = 0; - mvIMPACT::acquire::Request* pPreviousRequest = nullptr; - const unsigned int timeout_ms = 100; - Ready = true; - while( !boTerminated_ ) + mvIMPACT::acquire::Request* pPreviousRequest = nullptr; + const unsigned int timeout_ms = 100; + Ready = true; + while (!boTerminated_) { - const int requestNr = pFI_->imageRequestWaitFor( timeout_ms ); - pRequest = pFI_->isRequestNrValid( requestNr ) ? pFI_->getRequest( requestNr ) : 0; - if( pRequest ) + const int requestNr = pFI_->imageRequestWaitFor(timeout_ms); + pRequest = pFI_->isRequestNrValid(requestNr) ? pFI_->getRequest(requestNr) : 0; + if (pRequest) { - if (pRequest->isOK()) - { - // do something with the image - int openCVDataType = CV_8UC1; - if ((pRequest->imagePixelFormat.read() == ibpfBGR888Packed) || (pRequest->imagePixelFormat.read() == ibpfRGB888Packed)) - openCVDataType = CV_8UC3; - cv::Mat openCVImage(cv::Size(pRequest->imageWidth.read(), pRequest->imageHeight.read()), openCVDataType, pRequest->imageData.read(), pRequest->imageLinePitch.read()); - cv::Mat image_clone = openCVImage.clone(); - if (!g_debug_mode) - { + if (pRequest->isOK()) + { + // do something with the image + int openCVDataType = CV_8UC1; + if ((pRequest->imagePixelFormat.read() == ibpfBGR888Packed) || (pRequest->imagePixelFormat.read() == ibpfRGB888Packed)) + openCVDataType = CV_8UC3; + cv::Mat openCVImage(cv::Size(pRequest->imageWidth.read(), pRequest->imageHeight.read()), openCVDataType, pRequest->imageData.read(), pRequest->imageLinePitch.read()); + cv::Mat image_clone = openCVImage.clone(); + if (!g_debug_mode) + { #ifdef IMM_PROCESS - p_image_queue->put(std::make_pair(1,image_clone)); //放入临时队列 + p_image_queue->put(std::make_pair(1, image_clone)); //鏀惧叆涓存椂闃熷垪 #else - p_unit_queue->put(image_clone); //放入临时队列 + p_unit_queue->put(image_clone); //鏀惧叆涓存椂闃熷垪 #endif - } - else - { - p_debug_queue->put(image_clone); //放入调试队列 - } - cnt++; - // display some statistics - if (cnt % 10 == 0) - { - QString data = QString::fromStdString(statistics.framesPerSecond.readS()); - emit updateStatistics(data.left(4),Local_Num); - } - } - else - { - // some error: pRequest->requestResult.readS() will return a string representation - } - // this image has been used thus the buffer is no longer needed... - if (pPreviousRequest) - { - // this image has been displayed thus the buffer is no longer needed... - pPreviousRequest->unlock(); - } - pPreviousRequest = pRequest; - // send a new image request into the capture queue - pFI_->imageRequestSingle(); + } + else + { + p_debug_queue->put(image_clone); //鏀惧叆璋冭瘯闃熷垪 + } + cnt++; + // display some statistics + if (cnt % 10 == 0) + { + QString data = QString::fromStdString(statistics.framesPerSecond.readS()); + emit updateStatistics(data.left(4), Local_Num); + } + } + else + { + // some error: pRequest->requestResult.readS() will return a string representation + } + // this image has been used thus the buffer is no longer needed... + if (pPreviousRequest) + { + // this image has been displayed thus the buffer is no longer needed... + pPreviousRequest->unlock(); + } + pPreviousRequest = pRequest; + // send a new image request into the capture queue + pFI_->imageRequestSingle(); } #if defined (IMM_FEED_BACK) || defined (CAP_FEED_BACK) - m_threadFunc.SendFeedBack(ImageCap); + m_threadFunc.SendFeedBack(ImageCap); #endif - } - manuallyStopAcquisitionIfNeeded( pDev_, *pFI_ ); - if( pRequest ) + } + manuallyStopAcquisitionIfNeeded(pDev_, *pFI_); + if (pRequest) { pRequest->unlock(); } - pFI_->imageRequestReset( 0, 0 ); + pFI_->imageRequestReset(0, 0); } - catch( const ImpactAcquireException& e ) + catch (const ImpactAcquireException& e) { - emit error( QString::fromStdString( e.getErrorCodeAsString() ) ); + emit error(QString::fromStdString(e.getErrorCodeAsString())); } } //----------------------------------------------------------------------------- -int CaptureThread::getPendingRequestNr( void ) +int CaptureThread::getPendingRequestNr(void) //----------------------------------------------------------------------------- { - QMutexLocker lockedScope( &lock_ ); + QMutexLocker lockedScope(&lock_); int result = requestPendingForDisplay_; // Reset the ID of the request to tell the capture loop that this request has already been // picked up and someone else will take care of it from now on. requestPendingForDisplay_ = INVALID_ID; return result; -} \ No newline at end of file +} diff --git a/Cigarette/CaptureThread.h b/Cigarette/CaptureThread.h index 36973b91..638fab26 100644 --- a/Cigarette/CaptureThread.h +++ b/Cigarette/CaptureThread.h @@ -25,20 +25,20 @@ class CaptureThread_Func { public: Device* m_pMVCamera; - ASyncQueue *p_result_queue_; - ASyncQueue *p_double_queue_; + ASyncQueue* p_result_queue_; + ASyncQueue* p_double_queue_; void SendFeedBack(int OpID) { - bool send_ng=false; - bool send_ok=false; - if(OpID == EdgeEvent) + bool send_ng = false; + bool send_ok = false; + if (OpID == EdgeEvent) { #if defined DOUBLE_FEED_BACK - if(p_double_queue_->count() > 0) + if (p_double_queue_->count() > 0) { bool temp; p_double_queue_->take(temp); - send_ng=true; + send_ng = true; } #endif } @@ -47,88 +47,88 @@ public: bool result; p_result_queue_->take(result); if (!result) - { + { #if defined DOUBLE_FEED_BACK - p_double_queue_->put(true); + p_double_queue_->put(true); #endif - send_ng=true; + send_ng = true; + } + else + { + send_ok = true; + } + } + try + { + mvIMPACT::acquire::GenICam::DigitalIOControl mvDIOC(m_pMVCamera); + if (send_ng) { + mvDIOC.userOutputSelector.writeS("UserOutput0"); + mvIMPACT::acquire::TBoolean tb = mvDIOC.userOutputValue.read(); + if (tb == bFalse) + mvDIOC.userOutputValue.write(bTrue); + else + mvDIOC.userOutputValue.write(bFalse); } - else - { - send_ok=true; - } + else if (send_ok) + { + mvDIOC.userOutputSelector.writeS("UserOutput1"); + mvIMPACT::acquire::TBoolean tb = mvDIOC.userOutputValue.read(); + if (tb == bFalse) + mvDIOC.userOutputValue.write(bTrue); + else + mvDIOC.userOutputValue.write(bFalse); + } + } + catch (const ImpactAcquireException& e) + { + std::cout << "(error code: " << e.getErrorCodeAsString() << "). Press [ENTER] to end the application..." << std::endl; } - try - { - mvIMPACT::acquire::GenICam::DigitalIOControl mvDIOC(m_pMVCamera); - if(send_ng){ - mvDIOC.userOutputSelector.writeS("UserOutput0"); - mvIMPACT::acquire::TBoolean tb = mvDIOC.userOutputValue.read(); - if (tb == bFalse) - mvDIOC.userOutputValue.write(bTrue); - else - mvDIOC.userOutputValue.write(bFalse); - } - else if (send_ok) - { - mvDIOC.userOutputSelector.writeS("UserOutput1"); - mvIMPACT::acquire::TBoolean tb = mvDIOC.userOutputValue.read(); - if (tb == bFalse) - mvDIOC.userOutputValue.write(bTrue); - else - mvDIOC.userOutputValue.write(bFalse); - } - } - catch (const ImpactAcquireException& e) - { - std::cout<< "(error code: " << e.getErrorCodeAsString() << "). Press [ENTER] to end the application..." << std::endl; - } } }; class CaptureThread : public QObject -//----------------------------------------------------------------------------- + //----------------------------------------------------------------------------- { Q_OBJECT public: - explicit CaptureThread( Device* pCurrDev, bool boTerminated, FunctionInterface* pFi ,int Num); - CaptureThread::~CaptureThread(void); - void terminate( void ) + explicit CaptureThread(Device* pCurrDev, bool boTerminated, FunctionInterface* pFi, int Num); + CaptureThread::~CaptureThread(void); + void terminate(void) { boTerminated_ = true; } int getPendingRequestNr(); - + signals: - void error( QString err ); - void finished( void ); - void requestReady( void ); - void updateStatistics( const QString& data ,int Num); + void error(QString err); + void finished(void); + void requestReady(void); + void updateStatistics(const QString& data, int Num); private slots: - void process( void ); - void fpsTimeout(void); + void process(void); + void fpsTimeout(void); public: - int Local_Num; - QTimer* m_Timer; - uint64_t m_cntGrabbedImages = 0; - uint64_t m_cntLastGrabbedImages = 0; + int Local_Num; + QTimer* m_Timer; + uint64_t m_cntGrabbedImages = 0; + uint64_t m_cntLastGrabbedImages = 0; #ifdef SYNC_CAMERA - ImageSyncArr *p_image_sync_arr; - SyncQueue>>* p_image_sync_queue; + ImageSyncArr* p_image_sync_arr; + SyncQueue>>* p_image_sync_queue; #else - SyncQueue > *p_image_queue; + SyncQueue >* p_image_queue; #endif - ASyncQueue *p_unit_queue; - ASyncQueue *p_result_queue; - ASyncQueue *p_result_wait_queue; - ASyncQueue *p_double_queue; - ASyncQueue *p_shooted_queue; - SyncQueue *p_debug_queue; + ASyncQueue* p_unit_queue; + ASyncQueue* p_result_queue; + ASyncQueue* p_result_wait_queue; + ASyncQueue* p_double_queue; + ASyncQueue* p_shooted_queue; + SyncQueue* p_debug_queue; bool Ready = false; - CaptureThread_Func m_threadFunc; + CaptureThread_Func m_threadFunc; private: Device* pDev_; volatile bool boTerminated_; @@ -143,125 +143,125 @@ private: class EventCallback : public mvIMPACT::acquire::ComponentCallback { public: - ASyncQueue *p_unit_queue_; + ASyncQueue* p_unit_queue_; #ifdef SYNC_CAMERA - ImageSyncArr *p_image_sync_arr_; - SyncQueue>> *p_image_sync_queue_; + ImageSyncArr* p_image_sync_arr_; + SyncQueue>>* p_image_sync_queue_; #else - SyncQueue > *p_image_queue_; + SyncQueue >* p_image_queue_; #endif - ASyncQueue *p_result_wait_queue_; - ASyncQueue *p_shooted_queue_; - ASyncQueue *p_double_queue_; - explicit EventCallback(void* pUserData = 0) : ComponentCallback(pUserData) {} - Device* m_pMVCamera; - CaptureThread* pCaptureThread = NULL; - int count = 0; + ASyncQueue* p_result_wait_queue_; + ASyncQueue* p_shooted_queue_; + ASyncQueue* p_double_queue_; + explicit EventCallback(void* pUserData = 0) : ComponentCallback(pUserData) {} + Device* m_pMVCamera; + CaptureThread* pCaptureThread = NULL; + int count = 0; - virtual void execute(Component& c, void* pUserData) - { - try - { - // re-generating the object/data previously attached to the callback object. This could now be used to call a certain member function e.g. to update a class instance about this event! - mvIMPACT::acquire::GenICam::EventControl* ec = reinterpret_cast(pUserData); - // Execute the followings if the component is a property. - if (c.isProp()) - { - mvIMPACT::acquire::GenICam::DigitalIOControl mvDIOC(m_pMVCamera); - mvDIOC.lineSelector.writeS("Line5"); - if (mvDIOC.lineStatus.read()) - { + virtual void execute(Component& c, void* pUserData) + { + try + { + // re-generating the object/data previously attached to the callback object. This could now be used to call a certain member function e.g. to update a class instance about this event! + mvIMPACT::acquire::GenICam::EventControl* ec = reinterpret_cast(pUserData); + // Execute the followings if the component is a property. + if (c.isProp()) + { + mvIMPACT::acquire::GenICam::DigitalIOControl mvDIOC(m_pMVCamera); + mvDIOC.lineSelector.writeS("Line5"); + if (mvDIOC.lineStatus.read()) + { #ifdef IMM_FEED_BACK - if (p_shooted_queue_->count() > 0) - { - bool temp; - p_shooted_queue_->take(temp); - } + if (p_shooted_queue_->count() > 0) + { + bool temp; + p_shooted_queue_->take(temp); + } #elif defined ONE_TIME_SHIFT - if ( - p_shooted_queue_->count() > 0 + if ( + p_shooted_queue_->count() > 0 #if defined DOUBLE_FEED_BACK - || p_double_queue_->count() >0 + || p_double_queue_->count() > 0 #endif - ) - { - if (p_shooted_queue_->count() > 0){ - bool temp; - p_shooted_queue_->take(temp); - } - pCaptureThread->m_threadFunc.SendFeedBack(EdgeEvent); - } + ) + { + if (p_shooted_queue_->count() > 0) { + bool temp; + p_shooted_queue_->take(temp); + } + pCaptureThread->m_threadFunc.SendFeedBack(EdgeEvent); + } #else - if (p_result_wait_queue_->count() > 0) - { - bool temp; - p_result_wait_queue_->take(temp); - pCaptureThread->m_threadFunc.SendFeedBack(EdgeEvent); - } - if (p_shooted_queue_->count() > 0) - { - bool temp; - p_shooted_queue_->take(temp); - p_result_wait_queue_->put(true); - } + if (p_result_wait_queue_->count() > 0) + { + bool temp; + p_result_wait_queue_->take(temp); + pCaptureThread->m_threadFunc.SendFeedBack(EdgeEvent); + } + if (p_shooted_queue_->count() > 0) + { + bool temp; + p_shooted_queue_->take(temp); + p_result_wait_queue_->put(true); + } #endif - } - else - { - int unit_count = p_unit_queue_->count(); - if (unit_count > 0) - { - cv::Mat long_image; - for (int i = 0; i < unit_count; i++) - { - cv::Mat image; - p_unit_queue_->take(image); - if (0 == i) - { - long_image = cv::Mat::zeros(image.rows * unit_count, image.cols, image.type()); - } - cv::Rect r(0, i * image.rows, image.cols, image.rows); - cv::Mat roi = long_image(r); - image.copyTo(roi); - } + } + else + { + int unit_count = p_unit_queue_->count(); + if (unit_count > 0) + { + cv::Mat long_image; + for (int i = 0; i < unit_count; i++) + { + cv::Mat image; + p_unit_queue_->take(image); + if (0 == i) + { + long_image = cv::Mat::zeros(image.rows * unit_count, image.cols, image.type()); + } + cv::Rect r(0, i * image.rows, image.cols, image.rows); + cv::Mat roi = long_image(r); + image.copyTo(roi); + } #ifdef SYNC_CAMERA - { - std::lock_guard locker(p_image_sync_arr_->lock); - p_image_sync_arr_->image_sync_arr.at(pCaptureThread->Local_Num) = std::make_pair(unit_count, long_image); - p_image_sync_arr_->collect_cnt++; - if (p_image_sync_arr_->collect_cnt == work_camera_nums) - { - p_image_sync_queue_->put(p_image_sync_arr_->image_sync_arr); - p_image_sync_arr_->collect_cnt = 0; - } - } + { + std::lock_guard locker(p_image_sync_arr_->lock); + p_image_sync_arr_->image_sync_arr.at(pCaptureThread->Local_Num) = std::make_pair(unit_count, long_image); + p_image_sync_arr_->collect_cnt++; + if (p_image_sync_arr_->collect_cnt == work_camera_nums) + { + p_image_sync_queue_->put(p_image_sync_arr_->image_sync_arr); + p_image_sync_arr_->collect_cnt = 0; + } + } #else - p_image_queue_->put(std::make_pair(unit_count, long_image)); + p_image_queue_->put(std::make_pair(unit_count, long_image)); #endif - p_shooted_queue_->put(true); - } - p_unit_queue_->clear(); - } - } - } - catch (const ImpactAcquireException& e) - { - qDebug() << "Error"; - } - } + p_shooted_queue_->put(true); + } + p_unit_queue_->clear(); + } + } + } + catch (const ImpactAcquireException& e) + { + qDebug() << "Error"; + } + } }; class CIwtCameraLostCallbackMV : public mvIMPACT::acquire::ComponentCallback { public: - CIwtCameraLostCallbackMV() : ComponentCallback() {} - int channel_; - virtual void execute(mvIMPACT::acquire::Component& c, void* pDummy) - { - PropertyIDeviceState p(c); - std::cout << p.name() << " = " << p.readS() << endl; - SingleCamInfo[channel_].OffLine = true; - } + CIwtCameraLostCallbackMV() : ComponentCallback() {} + int channel_; + virtual void execute(mvIMPACT::acquire::Component& c, void* pDummy) + { + PropertyIDeviceState p(c); + std::cout << p.name() << " = " << p.readS() << endl; + SingleCamInfo[channel_].OffLine = true; + } }; //----------------------------------------------------------------------------- diff --git a/Cigarette/CaptureThreadBasler.cpp b/Cigarette/CaptureThreadBasler.cpp index 36fe9887..41febfc5 100644 --- a/Cigarette/CaptureThreadBasler.cpp +++ b/Cigarette/CaptureThreadBasler.cpp @@ -5,203 +5,203 @@ #include #include extern SyncQueue<_XMLExportDataInfo>* export_XMLData_Info_queue; -extern PLCDevice * m_PLCDevice; -//----------------------------------------------------------------------------- -CaptureThreadBasler::CaptureThreadBasler(Pylon::CBaslerUniversalInstantCamera* pCurrDev, bool boTerminated,int Num,int shoot) : - pDev_( pCurrDev ), boTerminated_( boTerminated ),Local_Num(Num) +extern PLCDevice* m_PLCDevice; //----------------------------------------------------------------------------- +CaptureThreadBasler::CaptureThreadBasler(Pylon::CBaslerUniversalInstantCamera* pCurrDev, bool boTerminated, int Num, int shoot) : + pDev_(pCurrDev), boTerminated_(boTerminated), Local_Num(Num) + //----------------------------------------------------------------------------- { - p_unit_queue = new ASyncQueue(Unit_Queue_Size); - Shoot_Num = shoot; + p_unit_queue = new ASyncQueue(Unit_Queue_Size); + Shoot_Num = shoot; } CaptureThreadBasler::~CaptureThreadBasler() { - delete p_unit_queue; + delete p_unit_queue; } //----------------------------------------------------------------------------- void CaptureThreadBasler::process(void) //----------------------------------------------------------------------------- { - bool last_high = false; - bool last_result = false; + bool last_high = false; + bool last_result = false; - CSampleConfigurationEventHandler* CfgEvent = NULL; - CfgEvent = new CSampleConfigurationEventHandler; - CfgEvent->channel_ = Local_Num; - pDev_->RegisterConfiguration(CfgEvent, Pylon::RegistrationMode_Append, Pylon::Cleanup_None); + CSampleConfigurationEventHandler* CfgEvent = NULL; + CfgEvent = new CSampleConfigurationEventHandler; + CfgEvent->channel_ = Local_Num; + pDev_->RegisterConfiguration(CfgEvent, Pylon::RegistrationMode_Append, Pylon::Cleanup_None); - CSampleImageEventHandler ImageEvent; + CSampleImageEventHandler ImageEvent; #ifdef SYNC_CAMERA - ImageEvent.p_image_sync_arr_ = p_image_sync_arr; - ImageEvent.p_image_sync_queue_ = p_image_sync_queue; + ImageEvent.p_image_sync_arr_ = p_image_sync_arr; + ImageEvent.p_image_sync_queue_ = p_image_sync_queue; #else - ImageEvent.p_image_queue_ = p_image_queue; + ImageEvent.p_image_queue_ = p_image_queue; #endif - ImageEvent.p_unit_queue_ = p_unit_queue; - ImageEvent.p_shooted_queue_ = p_shooted_queue; - ImageEvent.p_debug_queue_ = p_debug_queue; - ImageEvent.m_cntGrabbedImages_ = &m_cntGrabbedImages; - ImageEvent.Shoot_Num_ = Shoot_Num; - ImageEvent.pDev__ = pDev_; - pDev_->RegisterImageEventHandler(&ImageEvent, Pylon::RegistrationMode_Append, Pylon::Cleanup_None); + ImageEvent.p_unit_queue_ = p_unit_queue; + ImageEvent.p_shooted_queue_ = p_shooted_queue; + ImageEvent.p_debug_queue_ = p_debug_queue; + ImageEvent.m_cntGrabbedImages_ = &m_cntGrabbedImages; + ImageEvent.Shoot_Num_ = Shoot_Num; + ImageEvent.pDev__ = pDev_; + pDev_->RegisterImageEventHandler(&ImageEvent, Pylon::RegistrationMode_Append, Pylon::Cleanup_None); - CSampleCameraEventHandler BurstEvent; + CSampleCameraEventHandler BurstEvent; #ifdef SYNC_CAMERA - BurstEvent.p_image_sync_arr_ = p_image_sync_arr; - BurstEvent.p_image_sync_queue_ = p_image_sync_queue; + BurstEvent.p_image_sync_arr_ = p_image_sync_arr; + BurstEvent.p_image_sync_queue_ = p_image_sync_queue; #else - BurstEvent.p_image_queue_ = p_image_queue; + BurstEvent.p_image_queue_ = p_image_queue; #endif - BurstEvent.p_unit_queue_ = p_unit_queue; - BurstEvent.p_result_wait_queue_ = p_result_wait_queue; - BurstEvent.p_result_queue_ = p_result_queue; - BurstEvent.p_shooted_queue_ = p_shooted_queue; - BurstEvent.p_double_queue_ = p_double_queue; - BurstEvent.pDev__ = pDev_; - BurstEvent.pCaptureThreadBasler = this; + BurstEvent.p_unit_queue_ = p_unit_queue; + BurstEvent.p_result_wait_queue_ = p_result_wait_queue; + BurstEvent.p_result_queue_ = p_result_queue; + BurstEvent.p_shooted_queue_ = p_shooted_queue; + BurstEvent.p_double_queue_ = p_double_queue; + BurstEvent.pDev__ = pDev_; + BurstEvent.pCaptureThreadBasler = this; - try - { - m_threadFunc.pDev__ = pDev_; - m_threadFunc.p_result_queue_ = p_result_queue; - m_threadFunc.p_double_queue_ = p_double_queue; - m_threadFunc.m_IOTimer_ = m_IOTimer; + try + { + m_threadFunc.pDev__ = pDev_; + m_threadFunc.p_result_queue_ = p_result_queue; + m_threadFunc.p_double_queue_ = p_double_queue; + m_threadFunc.m_IOTimer_ = m_IOTimer; #ifndef USB_BASLER_NEW_FW - if (pDev_->TriggerSelector.TrySetValue(Basler_UniversalCameraParams::TriggerSelector_FrameBurstStart)) - { - pDev_->TriggerMode.SetValue(Basler_UniversalCameraParams::TriggerMode_On); - pDev_->TriggerSource.SetValue(Basler_UniversalCameraParams::TriggerSource_Line1); - pDev_->TriggerActivation.SetValue(Basler_UniversalCameraParams::TriggerActivation_RisingEdge); - pDev_->AcquisitionBurstFrameCount.SetValue(Shoot_Num); - if (pDev_->EventSelector.TrySetValue(Basler_UniversalCameraParams::EventSelector_FrameBurstStart)) - { - if (!pDev_->EventNotification.TrySetValue(Basler_UniversalCameraParams::EventNotification_On)) - { - pDev_->EventNotification.SetValue(Basler_UniversalCameraParams::EventNotification_GenICamEvent); - } + if (pDev_->TriggerSelector.TrySetValue(Basler_UniversalCameraParams::TriggerSelector_FrameBurstStart)) + { + pDev_->TriggerMode.SetValue(Basler_UniversalCameraParams::TriggerMode_On); + pDev_->TriggerSource.SetValue(Basler_UniversalCameraParams::TriggerSource_Line1); + pDev_->TriggerActivation.SetValue(Basler_UniversalCameraParams::TriggerActivation_RisingEdge); + pDev_->AcquisitionBurstFrameCount.SetValue(Shoot_Num); + if (pDev_->EventSelector.TrySetValue(Basler_UniversalCameraParams::EventSelector_FrameBurstStart)) + { + if (!pDev_->EventNotification.TrySetValue(Basler_UniversalCameraParams::EventNotification_On)) + { + pDev_->EventNotification.SetValue(Basler_UniversalCameraParams::EventNotification_GenICamEvent); + } - m_IOTimer = new QTimer(); - connect(m_IOTimer, SIGNAL(timeout()), this, SLOT(ioTimeout())); - m_IOTimer->setSingleShot(true); - BurstEvent.ioTimer = m_IOTimer; - pDev_->RegisterCameraEventHandler(&BurstEvent, "EventFrameBurstStartData", eMyFrameBurstStartEvent, Pylon::RegistrationMode_Append, Pylon::Cleanup_None); - } + m_IOTimer = new QTimer(); + connect(m_IOTimer, SIGNAL(timeout()), this, SLOT(ioTimeout())); + m_IOTimer->setSingleShot(true); + BurstEvent.ioTimer = m_IOTimer; + pDev_->RegisterCameraEventHandler(&BurstEvent, "EventFrameBurstStartData", eMyFrameBurstStartEvent, Pylon::RegistrationMode_Append, Pylon::Cleanup_None); + } - if(pDev_->EventSelector.TrySetValue("Line1RisingEdge")) - { - pDev_->EventNotification.SetValue(Basler_UniversalCameraParams::EventNotification_Off); - } - if(pDev_->EventSelector.TrySetValue("Line1FallingEdge")) - { - pDev_->EventNotification.SetValue(Basler_UniversalCameraParams::EventNotification_Off); - } - } + if (pDev_->EventSelector.TrySetValue("Line1RisingEdge")) + { + pDev_->EventNotification.SetValue(Basler_UniversalCameraParams::EventNotification_Off); + } + if (pDev_->EventSelector.TrySetValue("Line1FallingEdge")) + { + pDev_->EventNotification.SetValue(Basler_UniversalCameraParams::EventNotification_Off); + } + } #else - /*Set here*/ - if (pDev_->TriggerSelector.TrySetValue(Basler_UniversalCameraParams::TriggerSelector_FrameBurstStart)) - { - pDev_->TriggerMode.SetValue(Basler_UniversalCameraParams::TriggerMode_Off); - if(pDev_->EventSelector.TrySetValue(Basler_UniversalCameraParams::EventSelector_FrameBurstStart)) - { - pDev_->EventNotification.SetValue(Basler_UniversalCameraParams::EventNotification_Off); - } - } + /*Set here*/ + if (pDev_->TriggerSelector.TrySetValue(Basler_UniversalCameraParams::TriggerSelector_FrameBurstStart)) + { + pDev_->TriggerMode.SetValue(Basler_UniversalCameraParams::TriggerMode_Off); + if (pDev_->EventSelector.TrySetValue(Basler_UniversalCameraParams::EventSelector_FrameBurstStart)) + { + pDev_->EventNotification.SetValue(Basler_UniversalCameraParams::EventNotification_Off); + } + } - pDev_->RegisterCameraEventHandler(&BurstEvent, "EventLine1RisingEdgeData", Line1RisingEdge, Pylon::RegistrationMode_Append, Pylon::Cleanup_None); - pDev_->EventSelector.SetValue("Line1RisingEdge"); + pDev_->RegisterCameraEventHandler(&BurstEvent, "EventLine1RisingEdgeData", Line1RisingEdge, Pylon::RegistrationMode_Append, Pylon::Cleanup_None); + pDev_->EventSelector.SetValue("Line1RisingEdge"); #ifdef IMM_PROCESS - pDev_->EventNotification.SetValue(Basler_UniversalCameraParams::EventNotification_Off); + pDev_->EventNotification.SetValue(Basler_UniversalCameraParams::EventNotification_Off); #else - pDev_->EventNotification.SetValue(Basler_UniversalCameraParams::EventNotification_On); + pDev_->EventNotification.SetValue(Basler_UniversalCameraParams::EventNotification_On); #endif - pDev_->RegisterCameraEventHandler(&BurstEvent, "EventLine1FallingEdgeData", Line1FallingEdge, Pylon::RegistrationMode_Append, Pylon::Cleanup_None); - pDev_->EventSelector.SetValue("Line1FallingEdge"); + pDev_->RegisterCameraEventHandler(&BurstEvent, "EventLine1FallingEdgeData", Line1FallingEdge, Pylon::RegistrationMode_Append, Pylon::Cleanup_None); + pDev_->EventSelector.SetValue("Line1FallingEdge"); #ifdef IMM_PROCESS - pDev_->EventNotification.SetValue(Basler_UniversalCameraParams::EventNotification_Off); + pDev_->EventNotification.SetValue(Basler_UniversalCameraParams::EventNotification_Off); #else - pDev_->EventNotification.SetValue(Basler_UniversalCameraParams::EventNotification_On); + pDev_->EventNotification.SetValue(Basler_UniversalCameraParams::EventNotification_On); #endif #endif - const unsigned int timeout_ms = 100; - // This smart pointer will receive the grab result data. - Pylon::CGrabResultPtr ptrGrabResult; + const unsigned int timeout_ms = 100; + // This smart pointer will receive the grab result data. + Pylon::CGrabResultPtr ptrGrabResult; - pDev_->StartGrabbing(); + pDev_->StartGrabbing(); - m_Timer = new QTimer(); - connect(m_Timer, SIGNAL(timeout()), this, SLOT(fpsTimeout())); - m_Timer->start(1000); - Ready = true; - while (!boTerminated_) - { - // Retrieve grab results and notify the camera event and image event handlers. - pDev_->RetrieveResult(timeout_ms, ptrGrabResult, Pylon::TimeoutHandling_Return); + m_Timer = new QTimer(); + connect(m_Timer, SIGNAL(timeout()), this, SLOT(fpsTimeout())); + m_Timer->start(1000); + Ready = true; + while (!boTerminated_) + { + // Retrieve grab results and notify the camera event and image event handlers. + pDev_->RetrieveResult(timeout_ms, ptrGrabResult, Pylon::TimeoutHandling_Return); #if defined (IMM_FEED_BACK) || defined (CAP_FEED_BACK) - m_threadFunc.SendFeedBack(ImageCap); + m_threadFunc.SendFeedBack(ImageCap); #endif - QCoreApplication::processEvents();//Make sure the timer is triggered - } + QCoreApplication::processEvents();//Make sure the timer is triggered + } #ifndef USB_BASLER_NEW_FW - // Disable sending Event Overrun events. - if (pDev_->EventSelector.TrySetValue(Basler_UniversalCameraParams::EventSelector_FrameBurstStart)) - { - pDev_->EventNotification.TrySetValue(Basler_UniversalCameraParams::EventNotification_Off); - } - if (m_IOTimer) delete m_IOTimer; + // Disable sending Event Overrun events. + if (pDev_->EventSelector.TrySetValue(Basler_UniversalCameraParams::EventSelector_FrameBurstStart)) + { + pDev_->EventNotification.TrySetValue(Basler_UniversalCameraParams::EventNotification_Off); + } + if (m_IOTimer) delete m_IOTimer; #endif - if (m_Timer) delete m_Timer; - pDev_->StopGrabbing(); - pDev_->Close(); - pDev_->DeregisterConfiguration(CfgEvent); - pDev_->DeregisterImageEventHandler(&ImageEvent); + if (m_Timer) delete m_Timer; + pDev_->StopGrabbing(); + pDev_->Close(); + pDev_->DeregisterConfiguration(CfgEvent); + pDev_->DeregisterImageEventHandler(&ImageEvent); #ifndef USB_BASLER_NEW_FW - pDev_->DeregisterCameraEventHandler(&BurstEvent, "EventFrameBurstStartData"); + pDev_->DeregisterCameraEventHandler(&BurstEvent, "EventFrameBurstStartData"); #else - pDev_->DeregisterCameraEventHandler(&BurstEvent, "EventLine1RisingEdgeData"); - pDev_->DeregisterCameraEventHandler(&BurstEvent, "EventLine1FallingEdgeData"); + pDev_->DeregisterCameraEventHandler(&BurstEvent, "EventLine1RisingEdgeData"); + pDev_->DeregisterCameraEventHandler(&BurstEvent, "EventLine1FallingEdgeData"); #endif } - catch(const Pylon::GenericException& e) + catch (const Pylon::GenericException& e) { - emit error( QString::fromStdString( e.GetDescription()) ); - std::cout << e.GetSourceLine()<IsCameraDeviceRemoved()) - { - cout << "The camera has been removed from the computer." << endl; - } - else - { - pDev_->StopGrabbing(); - pDev_->GrabCameraEvents = false; - pDev_->Close(); - pDev_->DeregisterConfiguration(CfgEvent); - pDev_->DeregisterImageEventHandler(&ImageEvent); + emit error(QString::fromStdString(e.GetDescription())); + std::cout << e.GetSourceLine() << e.GetDescription() << std::endl; + if (pDev_->IsCameraDeviceRemoved()) + { + cout << "The camera has been removed from the computer." << endl; + } + else + { + pDev_->StopGrabbing(); + pDev_->GrabCameraEvents = false; + pDev_->Close(); + pDev_->DeregisterConfiguration(CfgEvent); + pDev_->DeregisterImageEventHandler(&ImageEvent); #ifndef USB_BASLER_NEW_FW - pDev_->DeregisterCameraEventHandler(&BurstEvent, "EventFrameBurstStartData"); + pDev_->DeregisterCameraEventHandler(&BurstEvent, "EventFrameBurstStartData"); #else - pDev_->DeregisterCameraEventHandler(&BurstEvent, "EventLine1RisingEdgeData"); - pDev_->DeregisterCameraEventHandler(&BurstEvent, "EventLine1FallingEdgeData"); + pDev_->DeregisterCameraEventHandler(&BurstEvent, "EventLine1RisingEdgeData"); + pDev_->DeregisterCameraEventHandler(&BurstEvent, "EventLine1FallingEdgeData"); #endif - } - + } + } } void CaptureThreadBasler::fpsTimeout() { - uint64_t delta = m_cntGrabbedImages - m_cntLastGrabbedImages; - m_cntLastGrabbedImages = m_cntGrabbedImages; - QString data = QString("%1").arg(delta); - emit updateStatistics(data.left(4), Local_Num); + uint64_t delta = m_cntGrabbedImages - m_cntLastGrabbedImages; + m_cntLastGrabbedImages = m_cntGrabbedImages; + QString data = QString("%1").arg(delta); + emit updateStatistics(data.left(4), Local_Num); } void CaptureThreadBasler::ioTimeout() { - pDev_->UserOutputSelector.SetValue(Basler_UniversalCameraParams::UserOutputSelector_UserOutput1); - pDev_->UserOutputValue.SetValue(false); + pDev_->UserOutputSelector.SetValue(Basler_UniversalCameraParams::UserOutputSelector_UserOutput1); + pDev_->UserOutputValue.SetValue(false); - pDev_->UserOutputSelector.SetValue(Basler_UniversalCameraParams::UserOutputSelector_UserOutput3); - pDev_->UserOutputValue.SetValue(false); + pDev_->UserOutputSelector.SetValue(Basler_UniversalCameraParams::UserOutputSelector_UserOutput3); + pDev_->UserOutputValue.SetValue(false); -} \ No newline at end of file +} diff --git a/Cigarette/CaptureThreadBasler.h b/Cigarette/CaptureThreadBasler.h index 93c4cf3e..a3c33bff 100644 --- a/Cigarette/CaptureThreadBasler.h +++ b/Cigarette/CaptureThreadBasler.h @@ -28,21 +28,21 @@ class CaptureThreadBasler_Func { public: Pylon::CBaslerUniversalInstantCamera* pDev__; - ASyncQueue *p_result_queue_; - ASyncQueue *p_double_queue_; - QTimer *m_IOTimer_ = NULL; + ASyncQueue* p_result_queue_; + ASyncQueue* p_double_queue_; + QTimer* m_IOTimer_ = NULL; void SendFeedBack(int OpID) { - bool send_ng=false; - bool send_ok=false; - if(OpID == EdgeEvent) + bool send_ng = false; + bool send_ok = false; + if (OpID == EdgeEvent) { #if defined DOUBLE_FEED_BACK - if(p_double_queue_->count() > 0) + if (p_double_queue_->count() > 0) { bool temp; p_double_queue_->take(temp); - send_ng=true; + send_ng = true; } #endif } @@ -54,11 +54,11 @@ public: #if defined DOUBLE_FEED_BACK p_double_queue_->put(true); #endif - send_ng=true; + send_ng = true; } - else + else { - send_ok=true; + send_ok = true; } } #ifndef USB_BASLER_NEW_FW @@ -92,21 +92,21 @@ class CaptureThreadBasler : public QObject Q_OBJECT public: - explicit CaptureThreadBasler(Pylon::CBaslerUniversalInstantCamera* pCurrDev, bool boTerminated,int Num,int shoot); + explicit CaptureThreadBasler(Pylon::CBaslerUniversalInstantCamera* pCurrDev, bool boTerminated, int Num, int shoot); CaptureThreadBasler::~CaptureThreadBasler(void); - void terminate( void ) + void terminate(void) { boTerminated_ = true; } signals: - void error( QString err ); - void finished( void ); - void requestReady( void ); - void updateStatistics( const QString& data ,int Num); + void error(QString err); + void finished(void); + void requestReady(void); + void updateStatistics(const QString& data, int Num); private slots: - void process( void ); + void process(void); void fpsTimeout(void); void ioTimeout(void); @@ -114,18 +114,18 @@ public: int Local_Num; int Shoot_Num; #ifdef SYNC_CAMERA - ImageSyncArr *p_image_sync_arr; + ImageSyncArr* p_image_sync_arr; SyncQueue>>* p_image_sync_queue; #else SyncQueue >* p_image_queue; #endif - ASyncQueue *p_unit_queue; - ASyncQueue *p_result_queue; - ASyncQueue *p_result_wait_queue; - ASyncQueue *p_double_queue; - ASyncQueue *p_shooted_queue; - SyncQueue *p_debug_queue; - QTimer *m_Timer = NULL,*m_IOTimer = NULL; + ASyncQueue* p_unit_queue; + ASyncQueue* p_result_queue; + ASyncQueue* p_result_wait_queue; + ASyncQueue* p_double_queue; + ASyncQueue* p_shooted_queue; + SyncQueue* p_debug_queue; + QTimer* m_Timer = NULL, * m_IOTimer = NULL; uint64_t m_cntGrabbedImages = 0; uint64_t m_cntLastGrabbedImages = 0; bool Ready = false; @@ -141,7 +141,7 @@ class CSampleConfigurationEventHandler : public Pylon::CBaslerUniversalConfigura public: int channel_; // This method is called from a different thread when the camera device removal has been detected. - void OnCameraDeviceRemoved( Pylon::CBaslerUniversalInstantCamera& camera ) + void OnCameraDeviceRemoved(Pylon::CBaslerUniversalInstantCamera& camera) { SingleCamInfo[channel_].OffLine = true; } @@ -151,158 +151,158 @@ public: class CSampleCameraEventHandler : public Pylon::CBaslerUniversalCameraEventHandler { public: - QTimer * ioTimer; + QTimer* ioTimer; ASyncQueue* p_unit_queue_; - ASyncQueue *p_result_wait_queue_; - ASyncQueue *p_result_queue_; - ASyncQueue *p_double_queue_; - ASyncQueue *p_shooted_queue_; + ASyncQueue* p_result_wait_queue_; + ASyncQueue* p_result_queue_; + ASyncQueue* p_double_queue_; + ASyncQueue* p_shooted_queue_; #ifdef SYNC_CAMERA - ImageSyncArr *p_image_sync_arr_; - SyncQueue>> *p_image_sync_queue_; + ImageSyncArr* p_image_sync_arr_; + SyncQueue>>* p_image_sync_queue_; #else - SyncQueue >* p_image_queue_; + SyncQueue >* p_image_queue_; #endif Pylon::CBaslerUniversalInstantCamera* pDev__; CaptureThreadBasler* pCaptureThreadBasler = NULL; // Only very short processing tasks should be performed by this method. Otherwise, the event notification will block the // processing of images. - virtual void OnCameraEvent(Pylon::CBaslerUniversalInstantCamera& camera, intptr_t userProvidedId, GenApi::INode* pNode) + virtual void OnCameraEvent(Pylon::CBaslerUniversalInstantCamera& camera, intptr_t userProvidedId, GenApi::INode* pNode) { switch (userProvidedId) { #ifndef USB_BASLER_NEW_FW - case eMyFrameBurstStartEvent: - { + case eMyFrameBurstStartEvent: + { #ifdef IMM_FEED_BACK - if (p_shooted_queue_->count() > 0) - { + if (p_shooted_queue_->count() > 0) + { + bool temp; + p_shooted_queue_->take(temp); + } +#elif defined ONE_TIME_SHIFT + if ( + p_shooted_queue_->count() > 0 +#if defined DOUBLE_FEED_BACK + || p_double_queue_->count() > 0 +#endif + ) + { + if (p_shooted_queue_->count() > 0) { bool temp; p_shooted_queue_->take(temp); } -#elif defined ONE_TIME_SHIFT - if ( - p_shooted_queue_->count() > 0 - #if defined DOUBLE_FEED_BACK - || p_double_queue_->count() >0 - #endif - ) - { - if (p_shooted_queue_->count() > 0){ - bool temp; - p_shooted_queue_->take(temp); - } - pCaptureThreadBasler->m_threadFunc.SendFeedBack(EdgeEvent); - } + pCaptureThreadBasler->m_threadFunc.SendFeedBack(EdgeEvent); + } #else - if(p_unit_queue_->count() > 0){ - int unit_count = p_unit_queue_->count(); - cv::Mat long_image; - for (int i = 0; i < unit_count; i++) + if (p_unit_queue_->count() > 0) { + int unit_count = p_unit_queue_->count(); + cv::Mat long_image; + for (int i = 0; i < unit_count; i++) + { + cv::Mat image; + p_unit_queue_->take(image); + if (0 == i) { - cv::Mat image; - p_unit_queue_->take(image); - if (0 == i) - { - long_image = cv::Mat::zeros(image.rows * unit_count, image.cols, image.type()); - } - cv::Rect r(0, i * image.rows, image.cols, image.rows); - cv::Mat roi = long_image(r); - image.copyTo(roi); + long_image = cv::Mat::zeros(image.rows * unit_count, image.cols, image.type()); } - p_image_queue_->put(std::make_pair(unit_count, long_image)); - p_shooted_queue_->put(true); - p_unit_queue_->clear(); - } - if(p_result_wait_queue_->count() > 0) - { - bool temp; - p_result_wait_queue_->take(temp); - pCaptureThreadBasler->m_threadFunc.SendFeedBack(EdgeEvent); - } - if(p_shooted_queue_->count() > 0) - { - bool temp; - p_shooted_queue_->take(temp); - p_result_wait_queue_->put(true); + cv::Rect r(0, i * image.rows, image.cols, image.rows); + cv::Mat roi = long_image(r); + image.copyTo(roi); } + p_image_queue_->put(std::make_pair(unit_count, long_image)); + p_shooted_queue_->put(true); + p_unit_queue_->clear(); + } + if (p_result_wait_queue_->count() > 0) + { + bool temp; + p_result_wait_queue_->take(temp); + pCaptureThreadBasler->m_threadFunc.SendFeedBack(EdgeEvent); + } + if (p_shooted_queue_->count() > 0) + { + bool temp; + p_shooted_queue_->take(temp); + p_result_wait_queue_->put(true); + } #endif break; - } + } #else - case Line1RisingEdge: - { + case Line1RisingEdge: + { #ifdef IMM_FEED_BACK - if (p_shooted_queue_->count() > 0) - { - bool temp; - p_shooted_queue_->take(temp); - } + if (p_shooted_queue_->count() > 0) + { + bool temp; + p_shooted_queue_->take(temp); + } #elif defined ONE_TIME_SHIFT - if ( - p_shooted_queue_->count() > 0 - #if defined DOUBLE_FEED_BACK - || p_double_queue_->count() >0 - #endif - ) - { - bool temp; - p_shooted_queue_->take(temp); - pCaptureThreadBasler->m_threadFunc.SendFeedBack(EdgeEvent); - } -#else - if(p_result_wait_queue_->count() > 0) - { - bool temp; - p_result_wait_queue_->take(temp); - pCaptureThreadBasler->m_threadFunc.SendFeedBack(EdgeEvent); - } - if(p_shooted_queue_->count() > 0) - { - bool temp; - p_shooted_queue_->take(temp); - p_result_wait_queue_->put(true); - } + if ( + p_shooted_queue_->count() > 0 +#if defined DOUBLE_FEED_BACK + || p_double_queue_->count() > 0 #endif - break; + ) + { + bool temp; + p_shooted_queue_->take(temp); + pCaptureThreadBasler->m_threadFunc.SendFeedBack(EdgeEvent); } - case Line1FallingEdge: +#else + if (p_result_wait_queue_->count() > 0) { - int unit_count = p_unit_queue_->count(); - if (unit_count > 0) + bool temp; + p_result_wait_queue_->take(temp); + pCaptureThreadBasler->m_threadFunc.SendFeedBack(EdgeEvent); + } + if (p_shooted_queue_->count() > 0) + { + bool temp; + p_shooted_queue_->take(temp); + p_result_wait_queue_->put(true); + } +#endif + break; + } + case Line1FallingEdge: + { + int unit_count = p_unit_queue_->count(); + if (unit_count > 0) + { + cv::Mat long_image; + for (int i = 0; i < unit_count; i++) { - cv::Mat long_image; - for (int i = 0; i < unit_count; i++) + cv::Mat image; + p_unit_queue_->take(image); + if (0 == i) { - cv::Mat image; - p_unit_queue_->take(image); - if (0 == i) - { - long_image = cv::Mat::zeros(image.rows * unit_count, image.cols, image.type()); - } - cv::Rect r(0, i * image.rows, image.cols, image.rows); - cv::Mat roi = long_image(r); - image.copyTo(roi); + long_image = cv::Mat::zeros(image.rows * unit_count, image.cols, image.type()); } + cv::Rect r(0, i * image.rows, image.cols, image.rows); + cv::Mat roi = long_image(r); + image.copyTo(roi); + } #ifdef SYNC_CAMERA - { - std::lock_guard locker(p_image_sync_arr_->lock); - p_image_sync_arr_->image_sync_arr.at(pCaptureThreadBasler->Local_Num) = std::make_pair(unit_count, long_image); - p_image_sync_arr_->collect_cnt++; - if (p_image_sync_arr_->collect_cnt == work_camera_nums) - { - p_image_sync_queue_->put(p_image_sync_arr_->image_sync_arr); - p_image_sync_arr_->collect_cnt = 0; - } - } + { + std::lock_guard locker(p_image_sync_arr_->lock); + p_image_sync_arr_->image_sync_arr.at(pCaptureThreadBasler->Local_Num) = std::make_pair(unit_count, long_image); + p_image_sync_arr_->collect_cnt++; + if (p_image_sync_arr_->collect_cnt == work_camera_nums) + { + p_image_sync_queue_->put(p_image_sync_arr_->image_sync_arr); + p_image_sync_arr_->collect_cnt = 0; + } + } #else - p_image_queue_->put(std::make_pair(unit_count, long_image)); + p_image_queue_->put(std::make_pair(unit_count, long_image)); #endif - p_shooted_queue_->put(true); - } - p_unit_queue_->clear(); - break; + p_shooted_queue_->put(true); } + p_unit_queue_->clear(); + break; + } #endif default: break; @@ -315,13 +315,13 @@ class CSampleImageEventHandler : public Pylon::CBaslerUniversalImageEventHandler public: ASyncQueue* p_unit_queue_; #ifdef SYNC_CAMERA - ImageSyncArr *p_image_sync_arr_; - SyncQueue>> *p_image_sync_queue_; + ImageSyncArr* p_image_sync_arr_; + SyncQueue>>* p_image_sync_queue_; #else - SyncQueue >* p_image_queue_; + SyncQueue >* p_image_queue_; #endif SyncQueue* p_debug_queue_; - ASyncQueue *p_shooted_queue_; + ASyncQueue* p_shooted_queue_; Pylon::CBaslerUniversalInstantCamera* pDev__; uint64_t* m_cntGrabbedImages_; int Shoot_Num_; @@ -347,7 +347,7 @@ public: if (!g_debug_mode) { #ifdef IMM_PROCESS - p_image_queue_->put(std::make_pair(1,image_clone)); + p_image_queue_->put(std::make_pair(1, image_clone)); #else p_unit_queue_->put(image_clone); #endif diff --git a/Cigarette/CaptureThreadHIK.cpp b/Cigarette/CaptureThreadHIK.cpp index 16ea7921..a5cf0c9f 100644 --- a/Cigarette/CaptureThreadHIK.cpp +++ b/Cigarette/CaptureThreadHIK.cpp @@ -4,105 +4,114 @@ #include "common.h" #include #include "exportData.h" -extern bool g_debug_mode; //相机调试模式,工作模式必须停止状态才能打开 +extern bool g_debug_mode; //鐩告満璋冭瘯妯″紡锛屽伐浣滄ā寮忓繀椤诲仠姝㈢姸鎬佹墠鑳芥墦寮 extern SingleCamInfoStruct SingleCamInfo[NumberOfSupportedCameras]; extern SyncQueue<_XMLExportDataInfo>* export_XMLData_Info_queue; extern PLCDevice* m_PLCDevice; extern int work_camera_nums; -inline void LossCallBackfunction(unsigned int pData, void* pUser){ - try{ - CaptureThreadHIK* CaptureThreadHIKptr = (CaptureThreadHIK*)pUser; - SingleCamInfo[CaptureThreadHIKptr->Local_Num].OffLine = true; - CaptureThreadHIKptr->terminate(); - } - catch(...){ - std::cout << "LossCallBackfunction error" << std::endl; - } +inline void LossCallBackfunction(unsigned int pData, void* pUser) { + try { + CaptureThreadHIK* CaptureThreadHIKptr = (CaptureThreadHIK*)pUser; + SingleCamInfo[CaptureThreadHIKptr->Local_Num].OffLine = true; + CaptureThreadHIKptr->terminate(); + } + catch (...) { + std::cout << "LossCallBackfunction error" << std::endl; + } } -inline void FallingGpioEventfunction(MV_EVENT_OUT_INFO* pEventInfo, void* pUser){ - try{ - CaptureThreadHIK* CaptureThreadHIKptr = (CaptureThreadHIK*)pUser; - int unit_count = CaptureThreadHIKptr->p_unit_queue->count(); - if (unit_count > 0) - { - cv::Mat long_image; - for (int i = 0; i < unit_count; i++) - { - cv::Mat image; - CaptureThreadHIKptr->p_unit_queue->take(image); - if (0 == i) - { - long_image = cv::Mat::zeros(image.rows * unit_count, image.cols, image.type()); - } - cv::Rect r(0, i * image.rows, image.cols, image.rows); - cv::Mat roi = long_image(r); - image.copyTo(roi); - } +inline void FallingGpioEventfunction(MV_EVENT_OUT_INFO* pEventInfo, void* pUser) { + try { + CaptureThreadHIK* CaptureThreadHIKptr = (CaptureThreadHIK*)pUser; + int unit_count = CaptureThreadHIKptr->p_unit_queue->count(); + if (unit_count > 0) + { + cv::Mat long_image; + for (int i = 0; i < unit_count; i++) + { + cv::Mat image; + CaptureThreadHIKptr->p_unit_queue->take(image); + if (0 == i) + { + long_image = cv::Mat::zeros(image.rows * unit_count, image.cols, image.type()); + } + cv::Rect r(0, i * image.rows, image.cols, image.rows); + cv::Mat roi = long_image(r); + image.copyTo(roi); + } #ifdef SYNC_CAMERA - { - std::lock_guard locker(CaptureThreadHIKptr->p_image_sync_arr->lock); - CaptureThreadHIKptr->p_image_sync_arr->image_sync_arr.at(CaptureThreadHIKptr->Local_Num) = std::make_pair(unit_count, long_image); - CaptureThreadHIKptr->p_image_sync_arr->collect_cnt++; - if (CaptureThreadHIKptr->p_image_sync_arr->collect_cnt == work_camera_nums) - { - CaptureThreadHIKptr->p_image_sync_queue->put(CaptureThreadHIKptr->p_image_sync_arr->image_sync_arr); - CaptureThreadHIKptr->p_image_sync_arr->collect_cnt = 0; - } - } + { + std::lock_guard locker(CaptureThreadHIKptr->p_image_sync_arr->lock); + CaptureThreadHIKptr->p_image_sync_arr->image_sync_arr.at(CaptureThreadHIKptr->Local_Num) = std::make_pair(unit_count, long_image); + CaptureThreadHIKptr->p_image_sync_arr->collect_cnt++; + if (CaptureThreadHIKptr->p_image_sync_arr->collect_cnt == work_camera_nums) + { + CaptureThreadHIKptr->p_image_sync_queue->put(CaptureThreadHIKptr->p_image_sync_arr->image_sync_arr); + CaptureThreadHIKptr->p_image_sync_arr->collect_cnt = 0; + //CaptureThreadHIKptr->p_image_sync_arr->image_sync_arr.swap(std::vector>()); + } + } #else - CaptureThreadHIKptr->p_image_queue->put(std::make_pair(unit_count, long_image)); -#endif - CaptureThreadHIKptr->p_shooted_queue->put(true); - } - CaptureThreadHIKptr->p_unit_queue->clear(); - } - catch(...){ - std::cout << "FallingGpioEventfunction error" << std::endl; - } + CaptureThreadHIKptr->p_image_queue->put(std::make_pair(unit_count, long_image)); +#endif + CaptureThreadHIKptr->p_shooted_queue->put(true); + } + CaptureThreadHIKptr->p_unit_queue->clear(); + } + catch (...) { + //std::cout << "FallingGpioEventfunction error" << std::endl; + std::exception_ptr p = std::current_exception(); + try { + if (p) + std::rethrow_exception(p); + } + catch (const std::exception& e) { + qDebug() << "Caught an exception: " << e.what(); + } + } } -inline void RisingGpioEventfunction(MV_EVENT_OUT_INFO* pEventInfo, void* pUser){ - try{ - CaptureThreadHIK* CaptureThreadHIKptr = (CaptureThreadHIK*)pUser; +inline void RisingGpioEventfunction(MV_EVENT_OUT_INFO* pEventInfo, void* pUser) { + try { + CaptureThreadHIK* CaptureThreadHIKptr = (CaptureThreadHIK*)pUser; #ifdef IMM_FEED_BACK - if (CaptureThreadHIKptr->p_shooted_queue->count() > 0) - { - bool temp; - CaptureThreadHIKptr->p_shooted_queue->take(temp); - } + if (CaptureThreadHIKptr->p_shooted_queue->count() > 0) + { + bool temp; + CaptureThreadHIKptr->p_shooted_queue->take(temp); + } #elif defined ONE_TIME_SHIFT - if( - CaptureThreadHIKptr->p_shooted_queue->count() > 0 - #if defined DOUBLE_FEED_BACK - || CaptureThreadHIKptr->p_double_queue->count() > 0 - #endif - ) - { - if (CaptureThreadHIKptr->p_shooted_queue->count() > 0){ - bool temp; - CaptureThreadHIKptr->p_shooted_queue->take(temp); - } - CaptureThreadHIKptr->m_threadFunc.SendFeedBack(EdgeEvent); - } + if ( + CaptureThreadHIKptr->p_shooted_queue->count() > 0 +#if defined DOUBLE_FEED_BACK + || CaptureThreadHIKptr->p_double_queue->count() > 0 +#endif + ) + { + if (CaptureThreadHIKptr->p_shooted_queue->count() > 0) { + bool temp; + CaptureThreadHIKptr->p_shooted_queue->take(temp); + } + CaptureThreadHIKptr->m_threadFunc.SendFeedBack(EdgeEvent); + } #else - if(CaptureThreadHIKptr->p_result_wait_queue->count() > 0) - { - bool temp; - CaptureThreadHIKptr->p_result_wait_queue->take(temp); - CaptureThreadHIKptr->m_threadFunc.SendFeedBack(EdgeEvent); - } - if(CaptureThreadHIKptr->p_shooted_queue->count() > 0) - { - bool temp; - CaptureThreadHIKptr->p_shooted_queue->take(temp); - CaptureThreadHIKptr->p_result_wait_queue->put(true); - } -#endif - } - catch(...){ - std::cout << "RisingGpioEventfunction error" << std::endl; - } + if (CaptureThreadHIKptr->p_result_wait_queue->count() > 0) + { + bool temp; + CaptureThreadHIKptr->p_result_wait_queue->take(temp); + CaptureThreadHIKptr->m_threadFunc.SendFeedBack(EdgeEvent); + } + if (CaptureThreadHIKptr->p_shooted_queue->count() > 0) + { + bool temp; + CaptureThreadHIKptr->p_shooted_queue->take(temp); + CaptureThreadHIKptr->p_result_wait_queue->put(true); + } +#endif + } + catch (...) { + std::cout << "RisingGpioEventfunction error" << std::endl; + } } #define CaptureThreadHIK_init(a)\ @@ -134,185 +143,185 @@ CaptureThreadHIK_init(7) CaptureThreadHIK_init(8) #endif -void(*LossCallBack[NumberOfSupportedCameras])(unsigned int pData, void* pUser) = { +void(*LossCallBack[NumberOfSupportedCameras])(unsigned int pData, void* pUser) = { #if defined(NumberOfSupportedCameras) && (NumberOfSupportedCameras>0) - LossCallBack1 + LossCallBack1 #endif #if defined(NumberOfSupportedCameras) && (NumberOfSupportedCameras>1) - ,LossCallBack2 + ,LossCallBack2 #endif #if defined(NumberOfSupportedCameras) && (NumberOfSupportedCameras>2) - ,LossCallBack3 + ,LossCallBack3 #endif #if defined(NumberOfSupportedCameras) && (NumberOfSupportedCameras>3) - ,LossCallBack4 + ,LossCallBack4 #endif #if defined(NumberOfSupportedCameras) && (NumberOfSupportedCameras>4) - ,LossCallBack5 + ,LossCallBack5 #endif #if defined(NumberOfSupportedCameras) && (NumberOfSupportedCameras>5) - ,LossCallBack6 + ,LossCallBack6 #endif #if defined(NumberOfSupportedCameras) && (NumberOfSupportedCameras>6) - ,LossCallBack7 + ,LossCallBack7 #endif #if defined(NumberOfSupportedCameras) && (NumberOfSupportedCameras>7) - ,LossCallBack8 + ,LossCallBack8 #endif }; -void(*FallingGpioEvent[NumberOfSupportedCameras])(MV_EVENT_OUT_INFO* pEventInfo, void* pUser) = { +void(*FallingGpioEvent[NumberOfSupportedCameras])(MV_EVENT_OUT_INFO* pEventInfo, void* pUser) = { #if defined(NumberOfSupportedCameras) && (NumberOfSupportedCameras>0) - FallingGpioEvent1 + FallingGpioEvent1 #endif #if defined(NumberOfSupportedCameras) && (NumberOfSupportedCameras>1) - ,FallingGpioEvent2 + ,FallingGpioEvent2 #endif #if defined(NumberOfSupportedCameras) && (NumberOfSupportedCameras>2) - ,FallingGpioEvent3 + ,FallingGpioEvent3 #endif #if defined(NumberOfSupportedCameras) && (NumberOfSupportedCameras>3) - ,FallingGpioEvent4 + ,FallingGpioEvent4 #endif #if defined(NumberOfSupportedCameras) && (NumberOfSupportedCameras>4) - ,FallingGpioEvent5 + ,FallingGpioEvent5 #endif #if defined(NumberOfSupportedCameras) && (NumberOfSupportedCameras>5) - ,FallingGpioEvent6 + ,FallingGpioEvent6 #endif #if defined(NumberOfSupportedCameras) && (NumberOfSupportedCameras>6) - ,FallingGpioEvent7 + ,FallingGpioEvent7 #endif #if defined(NumberOfSupportedCameras) && (NumberOfSupportedCameras>7) - ,FallingGpioEvent8 + ,FallingGpioEvent8 #endif }; -void(*RisingGpioEvent[NumberOfSupportedCameras])(MV_EVENT_OUT_INFO* pEventInfo, void* pUser) = { +void(*RisingGpioEvent[NumberOfSupportedCameras])(MV_EVENT_OUT_INFO* pEventInfo, void* pUser) = { #if defined(NumberOfSupportedCameras) && (NumberOfSupportedCameras>0) - RisingGpioEvent1 + RisingGpioEvent1 #endif #if defined(NumberOfSupportedCameras) && (NumberOfSupportedCameras>1) - ,RisingGpioEvent2 + ,RisingGpioEvent2 #endif #if defined(NumberOfSupportedCameras) && (NumberOfSupportedCameras>2) - ,RisingGpioEvent3 + ,RisingGpioEvent3 #endif #if defined(NumberOfSupportedCameras) && (NumberOfSupportedCameras>3) - ,RisingGpioEvent4 + ,RisingGpioEvent4 #endif #if defined(NumberOfSupportedCameras) && (NumberOfSupportedCameras>4) - ,RisingGpioEvent5 + ,RisingGpioEvent5 #endif #if defined(NumberOfSupportedCameras) && (NumberOfSupportedCameras>5) - ,RisingGpioEvent6 + ,RisingGpioEvent6 #endif #if defined(NumberOfSupportedCameras) && (NumberOfSupportedCameras>6) - ,RisingGpioEvent7 + ,RisingGpioEvent7 #endif #if defined(NumberOfSupportedCameras) && (NumberOfSupportedCameras>7) - ,RisingGpioEvent8 + ,RisingGpioEvent8 #endif }; void CaptureThreadHIK::fpsTimeout(void) { - uint64_t delta = m_cntGrabbedImages - m_cntLastGrabbedImages; - m_cntLastGrabbedImages = m_cntGrabbedImages; - QString data = QString("%1").arg(delta); - emit updateStatistics(data.left(4), Local_Num); + uint64_t delta = m_cntGrabbedImages - m_cntLastGrabbedImages; + m_cntLastGrabbedImages = m_cntGrabbedImages; + QString data = QString("%1").arg(delta); + emit updateStatistics(data.left(4), Local_Num); } //----------------------------------------------------------------------------- -CaptureThreadHIK::CaptureThreadHIK(void *camhandle, bool boTerminated,int Num) : - CamHandle( camhandle ), boTerminated_( boTerminated ),Local_Num(Num) -//----------------------------------------------------------------------------- +CaptureThreadHIK::CaptureThreadHIK(void* camhandle, bool boTerminated, int Num) : + CamHandle(camhandle), boTerminated_(boTerminated), Local_Num(Num) + //----------------------------------------------------------------------------- { - p_unit_queue = new ASyncQueue(Unit_Queue_Size); - g_pImage_buf = (unsigned char*)malloc(3000 * 3000 * 3); + p_unit_queue = new ASyncQueue(Unit_Queue_Size); + g_pImage_buf = (unsigned char*)malloc(3000 * 3000 * 3); } CaptureThreadHIK::~CaptureThreadHIK() { - delete p_unit_queue; - free(g_pImage_buf); + delete p_unit_queue; + free(g_pImage_buf); } //----------------------------------------------------------------------------- -void CaptureThreadHIK::process( void ) +void CaptureThreadHIK::process(void) //----------------------------------------------------------------------------- { - try { - int nRet = MV_OK, nnRet = MV_OK; - - m_threadFunc.CamHandle_ = CamHandle; - m_threadFunc.p_result_queue_ = p_result_queue; - m_threadFunc.p_double_queue_ = p_double_queue; + try { + int nRet = MV_OK, nnRet = MV_OK; + + m_threadFunc.CamHandle_ = CamHandle; + m_threadFunc.p_result_queue_ = p_result_queue; + m_threadFunc.p_double_queue_ = p_double_queue; - nRet = MV_CC_RegisterExceptionCallBack(CamHandle, LossCallBack[Local_Num], this); - if (nRet) { std::cout << "can not register loss callback" << std::endl; nnRet = nRet; } + nRet = MV_CC_RegisterExceptionCallBack(CamHandle, LossCallBack[Local_Num], this); + if (nRet) { std::cout << "can not register loss callback" << std::endl; nnRet = nRet; } -//#ifdef IMM_FEED_BACK ///不打开无反馈等( 延后一次两次用ifndef // 不延后用ifdef) - nRet = MV_CC_SetEnumValueByString(CamHandle, "EventSelector", "Line0FallingEdge"); - if (nRet) { std::cout << "can not set EventSelector" << std::endl; nnRet = nRet; } + //#ifdef IMM_FEED_BACK ///涓嶆墦寮鏃犲弽棣堢瓑( 寤跺悗涓娆′袱娆$敤ifndef // 涓嶅欢鍚庣敤ifdef) + nRet = MV_CC_SetEnumValueByString(CamHandle, "EventSelector", "Line0FallingEdge"); + if (nRet) { std::cout << "can not set EventSelector" << std::endl; nnRet = nRet; } - nRet = MV_CC_SetEnumValueByString(CamHandle, "EventNotification", "On"); - if (nRet) { std::cout << "can not set EventNotification" << std::endl; nnRet = nRet; } + nRet = MV_CC_SetEnumValueByString(CamHandle, "EventNotification", "On"); + if (nRet) { std::cout << "can not set EventNotification" << std::endl; nnRet = nRet; } - nRet = MV_CC_SetEnumValueByString(CamHandle, "EventSelector", "Line0RisingEdge"); - if (nRet) { std::cout << "can not set EventSelector" << std::endl; nnRet = nRet; } + nRet = MV_CC_SetEnumValueByString(CamHandle, "EventSelector", "Line0RisingEdge"); + if (nRet) { std::cout << "can not set EventSelector" << std::endl; nnRet = nRet; } - nRet = MV_CC_SetEnumValueByString(CamHandle, "EventNotification", "On"); - if (nRet) { std::cout << "can not set EventNotification" << std::endl; nnRet = nRet; } + nRet = MV_CC_SetEnumValueByString(CamHandle, "EventNotification", "On"); + if (nRet) { std::cout << "can not set EventNotification" << std::endl; nnRet = nRet; } - nRet = MV_CC_RegisterEventCallBackEx(CamHandle, "Line0FallingEdge", FallingGpioEvent[Local_Num], this); - if (nRet) { std::cout << "can not register GPIO callback" << std::endl; nnRet = nRet; } + nRet = MV_CC_RegisterEventCallBackEx(CamHandle, "Line0FallingEdge", FallingGpioEvent[Local_Num], this); + if (nRet) { std::cout << "can not register GPIO callback" << std::endl; nnRet = nRet; } - nRet = MV_CC_RegisterEventCallBackEx(CamHandle, "Line0RisingEdge", RisingGpioEvent[Local_Num], this); - if (nRet) { std::cout << "can not register GPIO callback" << std::endl; nnRet = nRet; } -//#endif + nRet = MV_CC_RegisterEventCallBackEx(CamHandle, "Line0RisingEdge", RisingGpioEvent[Local_Num], this); + if (nRet) { std::cout << "can not register GPIO callback" << std::endl; nnRet = nRet; } + //#endif - m_Timer = new QTimer(); - connect(m_Timer, SIGNAL(timeout()), this, SLOT(fpsTimeout())); - m_Timer->start(1000); + m_Timer = new QTimer(); + connect(m_Timer, SIGNAL(timeout()), this, SLOT(fpsTimeout())); + m_Timer->start(1000); - unsigned int nDataSize; - MVCC_INTVALUE_EX stIntValue = { 0 }; - nRet = MV_CC_GetIntValueEx(CamHandle, "PayloadSize", &stIntValue); - if (nRet) { std::cout << "Get PayloadSize error" << std::endl; } - nDataSize = stIntValue.nCurValue*3;/// - MV_CC_StartGrabbing(CamHandle); - Ready = true; - while(!boTerminated_) - { - //nRet = MV_CC_GetOneFrameTimeout(CamHandle, g_pImage_buf, nDataSize, &stFrameInfo, 200); - nRet = MV_CC_GetImageForBGR(CamHandle, g_pImage_buf, nDataSize, &stFrameInfo, 100); - if (MV_OK == nRet) - { - m_cntGrabbedImages++; + unsigned int nDataSize; + MVCC_INTVALUE_EX stIntValue = { 0 }; + nRet = MV_CC_GetIntValueEx(CamHandle, "PayloadSize", &stIntValue); + if (nRet) { std::cout << "Get PayloadSize error" << std::endl; } + nDataSize = stIntValue.nCurValue * 3;/// + MV_CC_StartGrabbing(CamHandle); + Ready = true; + while (!boTerminated_) + { + //nRet = MV_CC_GetOneFrameTimeout(CamHandle, g_pImage_buf, nDataSize, &stFrameInfo, 200); + nRet = MV_CC_GetImageForBGR(CamHandle, g_pImage_buf, nDataSize, &stFrameInfo, 100); + if (MV_OK == nRet) + { + m_cntGrabbedImages++; - cv::Mat openCVImage(stFrameInfo.nHeight, stFrameInfo.nWidth, CV_8UC3, g_pImage_buf); - cv::Mat image_clone = openCVImage.clone(); - if (!g_debug_mode) - { + cv::Mat openCVImage(stFrameInfo.nHeight, stFrameInfo.nWidth, CV_8UC3, g_pImage_buf); + cv::Mat image_clone = openCVImage.clone(); + if (!g_debug_mode) + { #ifdef IMM_PROCESS - p_image_queue->put(std::make_pair(1,image_clone)); + p_image_queue->put(std::make_pair(1, image_clone)); #else - p_unit_queue->put(image_clone); //放入临时队列 -#endif - } - else - { - p_debug_queue->put(image_clone); //放入调试队列 - } - } + p_unit_queue->put(image_clone); //鏀惧叆涓存椂闃熷垪 +#endif + } + else + { + p_debug_queue->put(image_clone); //鏀惧叆璋冭瘯闃熷垪 + } + } #if defined (IMM_FEED_BACK) || defined (CAP_FEED_BACK) - m_threadFunc.SendFeedBack(ImageCap); -#endif - QCoreApplication::processEvents();//Make sure the timer is triggered - } - MV_CC_StopGrabbing(CamHandle); - MV_CC_CloseDevice(CamHandle); - delete m_Timer; - } - catch (cv::Exception& e) { - const char* err_msg = e.what(); - std::cout << "exception caught: " << err_msg << std::endl; - } + m_threadFunc.SendFeedBack(ImageCap); +#endif + QCoreApplication::processEvents();//Make sure the timer is triggered + } + MV_CC_StopGrabbing(CamHandle); + MV_CC_CloseDevice(CamHandle); + delete m_Timer; + } + catch (cv::Exception& e) { + const char* err_msg = e.what(); + std::cout << "exception caught: " << err_msg << std::endl; + } } //----------------------------------------------------------------------------- diff --git a/Cigarette/CaptureThreadHIK.h b/Cigarette/CaptureThreadHIK.h index c16c5baa..348075a6 100644 --- a/Cigarette/CaptureThreadHIK.h +++ b/Cigarette/CaptureThreadHIK.h @@ -17,21 +17,21 @@ class CaptureThreadHIK_Func { public: - void *CamHandle_; - ASyncQueue *p_result_queue_; - ASyncQueue *p_double_queue_; + void* CamHandle_; + ASyncQueue* p_result_queue_; + ASyncQueue* p_double_queue_; void SendFeedBack(int OpID) { - bool send_ng=false; - bool send_ok=false; - if(OpID == EdgeEvent) + bool send_ng = false; + bool send_ok = false; + if (OpID == EdgeEvent) { #if defined DOUBLE_FEED_BACK - if(p_double_queue_->count() > 0) + if (p_double_queue_->count() > 0) { bool temp; p_double_queue_->take(temp); - send_ng=true; + send_ng = true; } #endif } @@ -44,10 +44,10 @@ public: #if defined DOUBLE_FEED_BACK p_double_queue_->put(true); #endif - send_ng=true; + send_ng = true; } } - if(send_ng) + if (send_ng) { MV_CC_SetEnumValue(CamHandle_, "LineSelector", 1); MV_CC_SetCommandValue(CamHandle_, "LineTriggerSoftware"); @@ -57,50 +57,50 @@ public: //----------------------------------------------------------------------------- class CaptureThreadHIK : public QObject -//----------------------------------------------------------------------------- + //----------------------------------------------------------------------------- { Q_OBJECT public: - explicit CaptureThreadHIK(void *camhandle, bool boTerminated,int Num); + explicit CaptureThreadHIK(void* camhandle, bool boTerminated, int Num); CaptureThreadHIK::~CaptureThreadHIK(void); - void terminate( void ) + void terminate(void) { boTerminated_ = true; } signals: - void error( QString err ); - void finished( void ); - void requestReady( void ); - void updateStatistics( const QString& data ,int Num); - + void error(QString err); + void finished(void); + void requestReady(void); + void updateStatistics(const QString& data, int Num); + private slots: - void process( void ); - void fpsTimeout(void); + void process(void); + void fpsTimeout(void); public: int Local_Num; #ifdef SYNC_CAMERA - ImageSyncArr *p_image_sync_arr; + ImageSyncArr* p_image_sync_arr; SyncQueue>>* p_image_sync_queue; #else SyncQueue >* p_image_queue; #endif - ASyncQueue *p_unit_queue; - ASyncQueue *p_result_queue; - ASyncQueue *p_result_wait_queue; - ASyncQueue *p_double_queue; - ASyncQueue *p_shooted_queue; - SyncQueue *p_debug_queue; + ASyncQueue* p_unit_queue; + ASyncQueue* p_result_queue; + ASyncQueue* p_result_wait_queue; + ASyncQueue* p_double_queue; + ASyncQueue* p_shooted_queue; + SyncQueue* p_debug_queue; void* CamHandle; - QTimer* m_Timer; - uint64_t m_cntGrabbedImages = 0; - uint64_t m_cntLastGrabbedImages = 0; + QTimer* m_Timer; + uint64_t m_cntGrabbedImages = 0; + uint64_t m_cntLastGrabbedImages = 0; bool Ready = false; CaptureThreadHIK_Func m_threadFunc; private: MV_FRAME_OUT_INFO_EX stFrameInfo; - unsigned char* g_pImage_buf; + unsigned char* g_pImage_buf; volatile bool boTerminated_; QMutex lock_; }; diff --git a/Cigarette/Cigarette.vcxproj b/Cigarette/Cigarette.vcxproj index 0c448e3c..2c01adc9 100644 --- a/Cigarette/Cigarette.vcxproj +++ b/Cigarette/Cigarette.vcxproj @@ -249,10 +249,6 @@ true true - - true - true - diff --git a/Cigarette/Cigarette.vcxproj.filters b/Cigarette/Cigarette.vcxproj.filters index 373546c8..944c6bc8 100644 --- a/Cigarette/Cigarette.vcxproj.filters +++ b/Cigarette/Cigarette.vcxproj.filters @@ -263,9 +263,6 @@ Source Files - - Source Files - Source Files diff --git a/Cigarette/Cleanthread.cpp b/Cigarette/Cleanthread.cpp index b00aeb99..eb97ba00 100644 --- a/Cigarette/Cleanthread.cpp +++ b/Cigarette/Cleanthread.cpp @@ -17,142 +17,142 @@ CleanWorkThread::~CleanWorkThread() { } void CleanWorkThread::setSelAuto() { - delSelection = 1; + delSelection = 1; } void CleanWorkThread::setSel() { - delSelection = 2; + delSelection = 2; } void CleanWorkThread::startWork() { - emit workStart(); - doWork(); + emit workStart(); + doWork(); } void CleanWorkThread::startWorkAuto() { - emit workStartAuto(); - doWork(); + emit workStartAuto(); + doWork(); } void CleanWorkThread::doWork() { - qint64 spaceSize; - qint64 dirSize; - QString dirPath = g_conf_path.save_pics_path; - //QString iDriver = "D:/"; - char drive[_MAX_DRIVE]; - char dir_1[_MAX_DIR]; - char fname[_MAX_FNAME]; - char ext[_MAX_EXT]; + qint64 spaceSize; + qint64 dirSize; + QString dirPath = g_conf_path.save_pics_path; + //QString iDriver = "D:/"; + char drive[_MAX_DRIVE]; + char dir_1[_MAX_DIR]; + char fname[_MAX_FNAME]; + char ext[_MAX_EXT]; - _splitpath(dirPath.toStdString().c_str(), drive, dir_1, fname, ext); - QString iDriver = drive + QString("/"); - LPCWSTR strDriver = (LPCWSTR)iDriver.utf16(); - ULARGE_INTEGER freeDiskSpaceAvailable, totalDiskSpace, totalFreeDiskSpace; - qint64 gb = (1024 * 1024 * 1024); - //QString dir("D:/image"); - QString dir(g_conf_path.save_pics_path + "/ALL"); + _splitpath(dirPath.toStdString().c_str(), drive, dir_1, fname, ext); + QString iDriver = drive + QString("/"); + LPCWSTR strDriver = (LPCWSTR)iDriver.utf16(); + ULARGE_INTEGER freeDiskSpaceAvailable, totalDiskSpace, totalFreeDiskSpace; + qint64 gb = (1024 * 1024 * 1024); + //QString dir("D:/image"); + QString dir(g_conf_path.save_pics_path + "/ALL"); - if (delSelection == 2) - { - CleanImageFile(dir, 1); - } - else - { - qint64 delDays = g_sys_conf.save_days;/// - qint64 freeSize = g_sys_conf.freesize; - CleanImageFile(dir, delDays--); - //璋冪敤鍑芥暟鑾峰彇纾佺洏鍙傛暟(鍗曚綅涓哄瓧鑺侭yte),杞寲涓篏B锛岄渶瑕侀櫎浠(1024*1024*1024) - GetDiskFreeSpaceEx(strDriver, &freeDiskSpaceAvailable, &totalDiskSpace, &totalFreeDiskSpace); - spaceSize = ((qint64)totalFreeDiskSpace.QuadPart * (100/freeSize)) / (qint64)totalDiskSpace.QuadPart; - dirSize = DirFileSize(dir) / gb; - //delDays = g_sys_conf.save_days; - while ((spaceSize < 1) && (delDays > 1)) { //纾佺洏鍓╀綑绌洪棿灏忎簬鐧惧垎涔嬪崄 - CleanImageFile(dir, delDays--); - GetDiskFreeSpaceEx(strDriver, &freeDiskSpaceAvailable, &totalDiskSpace, &totalFreeDiskSpace); - spaceSize = ((qint64)totalFreeDiskSpace.QuadPart * (100 / freeSize)) / (qint64)totalDiskSpace.QuadPart; - } - } - emit workFinished(); + if (delSelection == 2) + { + CleanImageFile(dir, 1); + } + else + { + qint64 delDays = g_sys_conf.save_days;/// + qint64 freeSize = g_sys_conf.freesize; + CleanImageFile(dir, delDays--); + //璋冪敤鍑芥暟鑾峰彇纾佺洏鍙傛暟(鍗曚綅涓哄瓧鑺侭yte),杞寲涓篏B锛岄渶瑕侀櫎浠(1024*1024*1024) + GetDiskFreeSpaceEx(strDriver, &freeDiskSpaceAvailable, &totalDiskSpace, &totalFreeDiskSpace); + spaceSize = ((qint64)totalFreeDiskSpace.QuadPart * (100 / freeSize)) / (qint64)totalDiskSpace.QuadPart; + dirSize = DirFileSize(dir) / gb; + //delDays = g_sys_conf.save_days; + while ((spaceSize < 1) && (delDays > 1)) { //纾佺洏鍓╀綑绌洪棿灏忎簬鐧惧垎涔嬪崄 + CleanImageFile(dir, delDays--); + GetDiskFreeSpaceEx(strDriver, &freeDiskSpaceAvailable, &totalDiskSpace, &totalFreeDiskSpace); + spaceSize = ((qint64)totalFreeDiskSpace.QuadPart * (100 / freeSize)) / (qint64)totalDiskSpace.QuadPart; + } + } + emit workFinished(); } void CleanWorkThread::CleanImageFile(const QString& path, const qint64& delDays) { - QDir dir(path); - QFileInfoList list; - QFileInfo curFile; - if (!dir.exists()) { return; }//鏂囦欢涓嶅瓨锛屽垯杩斿洖false - dir.setFilter(QDir::Dirs | QDir::Files); - list = dir.entryInfoList(QDir::Dirs | QDir::Files - | QDir::Readable | QDir::Writable - | QDir::Hidden | QDir::NoDotAndDotDot - , QDir::Time); - if (list.isEmpty()) { return; }//鏂囦欢澶逛负绌猴紝鍒欒繑鍥瀎alse - int i = list.size() - 1; - do { - QFileInfo fileInfo = list.at(i); - // dir.removeRecursively(); - while (fileInfo.fileName() == "." || fileInfo.fileName() == ".." && i >= 0) - { - i--; - } - if (i < 0) { - break; - } - bool bisDir = fileInfo.isDir(); - if (bisDir) - { - QRegExp rx("\\d{4}-\\d{2}-\\d{2}"); - QRegExpValidator v(rx, 0); - int pos = 0; - int match; - QString name = fileInfo.fileName(); - match = v.validate(name, pos); - if (match == 2) - { - QDate delDate = QDate::currentDate(); - QDate dirDate; - QString name = fileInfo.fileName(); - dirDate = QDate::fromString(fileInfo.fileName(), "yyyy-MM-dd"); - qint64 nDays = dirDate.daysTo(delDate); - if (nDays >= delDays) - { - if (fileInfo.isDir()) { - QString n = fileInfo.absoluteFilePath(); - QDir subPath(fileInfo.absoluteFilePath()); - subPath.removeRecursively(); - } - else - { - fileInfo.dir().remove(fileInfo.fileName()); - } - } - } - else - { - CleanImageFile(fileInfo.filePath(), delDays); - } - } - else - { - fileInfo.dir().remove(fileInfo.fileName()); - } - i--; - } while (i >= 0); + QDir dir(path); + QFileInfoList list; + QFileInfo curFile; + if (!dir.exists()) { return; }//鏂囦欢涓嶅瓨锛屽垯杩斿洖false + dir.setFilter(QDir::Dirs | QDir::Files); + list = dir.entryInfoList(QDir::Dirs | QDir::Files + | QDir::Readable | QDir::Writable + | QDir::Hidden | QDir::NoDotAndDotDot + , QDir::Time); + if (list.isEmpty()) { return; }//鏂囦欢澶逛负绌猴紝鍒欒繑鍥瀎alse + int i = list.size() - 1; + do { + QFileInfo fileInfo = list.at(i); + // dir.removeRecursively(); + while (fileInfo.fileName() == "." || fileInfo.fileName() == ".." && i >= 0) + { + i--; + } + if (i < 0) { + break; + } + bool bisDir = fileInfo.isDir(); + if (bisDir) + { + QRegExp rx("\\d{4}-\\d{2}-\\d{2}"); + QRegExpValidator v(rx, 0); + int pos = 0; + int match; + QString name = fileInfo.fileName(); + match = v.validate(name, pos); + if (match == 2) + { + QDate delDate = QDate::currentDate(); + QDate dirDate; + QString name = fileInfo.fileName(); + dirDate = QDate::fromString(fileInfo.fileName(), "yyyy-MM-dd"); + qint64 nDays = dirDate.daysTo(delDate); + if (nDays >= delDays) + { + if (fileInfo.isDir()) { + QString n = fileInfo.absoluteFilePath(); + QDir subPath(fileInfo.absoluteFilePath()); + subPath.removeRecursively(); + } + else + { + fileInfo.dir().remove(fileInfo.fileName()); + } + } + } + else + { + CleanImageFile(fileInfo.filePath(), delDays); + } + } + else + { + fileInfo.dir().remove(fileInfo.fileName()); + } + i--; + } while (i >= 0); } qint64 CleanWorkThread::DirFileSize(const QString& path) { - QDir dir(path); - quint64 size = 0; - //dir.entryInfoList(QDir::Files)杩斿洖鏂囦欢淇℃伅 - foreach(QFileInfo fileInfo, dir.entryInfoList(QDir::Files)) - { - //璁$畻鏂囦欢澶у皬 - size += fileInfo.size(); - } - //dir.entryList(QDir::Dirs|QDir::NoDotAndDotDot)杩斿洖鎵鏈夊瓙鐩綍锛屽苟杩涜杩囨护 - foreach(QString subDir, dir.entryList(QDir::Dirs | QDir::NoDotAndDotDot)) - { - //鑻ュ瓨鍦ㄥ瓙鐩綍锛屽垯閫掑綊璋冪敤dirFileSize()鍑芥暟 - size += DirFileSize(path + QDir::separator() + subDir); - } - return size; -} \ No newline at end of file + QDir dir(path); + quint64 size = 0; + //dir.entryInfoList(QDir::Files)杩斿洖鏂囦欢淇℃伅 + foreach(QFileInfo fileInfo, dir.entryInfoList(QDir::Files)) + { + //璁$畻鏂囦欢澶у皬 + size += fileInfo.size(); + } + //dir.entryList(QDir::Dirs|QDir::NoDotAndDotDot)杩斿洖鎵鏈夊瓙鐩綍锛屽苟杩涜杩囨护 + foreach(QString subDir, dir.entryList(QDir::Dirs | QDir::NoDotAndDotDot)) + { + //鑻ュ瓨鍦ㄥ瓙鐩綍锛屽垯閫掑綊璋冪敤dirFileSize()鍑芥暟 + size += DirFileSize(path + QDir::separator() + subDir); + } + return size; +} diff --git a/Cigarette/Cleanthread.h b/Cigarette/Cleanthread.h index 48a72fef..a17d3b88 100644 --- a/Cigarette/Cleanthread.h +++ b/Cigarette/Cleanthread.h @@ -2,23 +2,23 @@ #include class CleanWorkThread : public QObject { - Q_OBJECT + Q_OBJECT public: - CleanWorkThread(QObject* parent = nullptr); - ~CleanWorkThread(); + CleanWorkThread(QObject* parent = nullptr); + ~CleanWorkThread(); public slots: - void startWork(); - void startWorkAuto(); - void doWork(); - void setSelAuto(); - void setSel(); + void startWork(); + void startWorkAuto(); + void doWork(); + void setSelAuto(); + void setSel(); signals: - void workFinished(); - void workStart(); - void workStartAuto(); + void workFinished(); + void workStart(); + void workStartAuto(); public: - qint64 DirFileSize(const QString& path); - void CleanImageFile(const QString& path, const qint64& delDays); + qint64 DirFileSize(const QString& path); + void CleanImageFile(const QString& path, const qint64& delDays); private: - int delSelection; + int delSelection; }; diff --git a/Cigarette/FtpManager.h b/Cigarette/FtpManager.h index 6b3f58f7..e2740187 100644 --- a/Cigarette/FtpManager.h +++ b/Cigarette/FtpManager.h @@ -13,63 +13,63 @@ class FtpManager { private: - QUrl url; - QNetworkAccessManager manager; + QUrl url; + QNetworkAccessManager manager; public: - FtpManager() { - /* 设置通讯协议 */ - url.setScheme("ftp"); - /* 设置用户名 */ - url.setUserName("FTP2"); - /* 设置密码 */ - url.setPassword("123"); - /* 设置主机,也可以是域名 */ - url.setHost("192.168.1.170"); - /* 设置端口号,一般为21 */ - url.setPort(666); - } + FtpManager() { + /* 璁剧疆閫氳鍗忚 */ + url.setScheme("ftp"); + /* 璁剧疆鐢ㄦ埛鍚 */ + url.setUserName("FTP2"); + /* 璁剧疆瀵嗙爜 */ + url.setPassword("123"); + /* 璁剧疆涓绘満锛屼篃鍙互鏄煙鍚 */ + url.setHost("192.168.1.170"); + /* 璁剧疆绔彛鍙凤紝涓鑸负21 */ + url.setPort(666); + } - void uploadSingleFile(QString filePath, QString remotePath) { + void uploadSingleFile(QString filePath, QString remotePath) { - // 设置路径 - url.setPath(remotePath); - qDebug() << "uploadSingleFile path " << url.path(); + // 璁剧疆璺緞 + url.setPath(remotePath); + qDebug() << "uploadSingleFile path " << url.path(); - // 装载本地文件 - QFile file(filePath); - bool isopen = false; - isopen = file.open(QIODevice::ReadOnly); - qDebug() << "Open file " << isopen; - if (isopen) { - // 读取本地文件数据 - QByteArray data = file.readAll(); - file.close(); + // 瑁呰浇鏈湴鏂囦欢 + QFile file(filePath); + bool isopen = false; + isopen = file.open(QIODevice::ReadOnly); + qDebug() << "Open file " << isopen; + if (isopen) { + // 璇诲彇鏈湴鏂囦欢鏁版嵁 + QByteArray data = file.readAll(); + file.close(); - // 上传数据,上传成功后会在远端创建文件 - manager.setNetworkAccessible(QNetworkAccessManager::Accessible); - QNetworkReply* reply = manager.put(QNetworkRequest(url), data); + // 涓婁紶鏁版嵁锛屼笂浼犳垚鍔熷悗浼氬湪杩滅鍒涘缓鏂囦欢 + manager.setNetworkAccessible(QNetworkAccessManager::Accessible); + QNetworkReply* reply = manager.put(QNetworkRequest(url), data); - QEventLoop eventLoop; - //QObject::connect(reply, SIGNAL(finished()), &eventLoop, SLOT(quit())); - //// 进入等待,但事件循环依然进行 */ - //eventLoop.exec(); + QEventLoop eventLoop; + //QObject::connect(reply, SIGNAL(finished()), &eventLoop, SLOT(quit())); + //// 杩涘叆绛夊緟锛屼絾浜嬩欢寰幆渚濈劧杩涜 */ + //eventLoop.exec(); - //QObject::connect(reply, &QNetworkReply::finished, [&]() { - // if (reply->error() == QNetworkReply::NoError) { - // // 读取响应数据 - // QByteArray responseData = reply->readAll(); - // // 处理响应数据 - // qDebug() << "Received response:" << responseData; - // } - // else { - // // 处理错误 - // qDebug() << "Error occurred:" << reply->errorString(); - // } + //QObject::connect(reply, &QNetworkReply::finished, [&]() { + // if (reply->error() == QNetworkReply::NoError) { + // // 璇诲彇鍝嶅簲鏁版嵁 + // QByteArray responseData = reply->readAll(); + // // 澶勭悊鍝嶅簲鏁版嵁 + // qDebug() << "Received response:" << responseData; + // } + // else { + // // 澶勭悊閿欒 + // qDebug() << "Error occurred:" << reply->errorString(); + // } - // // 清理资源 - // reply->deleteLater(); - // }); - } - } -}; \ No newline at end of file + // // 娓呯悊璧勬簮 + // reply->deleteLater(); + // }); + } + } +}; diff --git a/Cigarette/Logthread.cpp b/Cigarette/Logthread.cpp index 3132f1df..1c084913 100644 --- a/Cigarette/Logthread.cpp +++ b/Cigarette/Logthread.cpp @@ -20,145 +20,145 @@ void CLog::setLogType(const CLog::CLOG_TYPE& level) bool CLog::init(LogConfig& logConfig) { - isRecord2File = logConfig.isRecord2File; - QString logDir = QString(PATH_LogPath); - if (createDir(logDir)) - { - QString fileName = logDir + QDir::separator() + QDate::currentDate().toString("yyyy-MM-dd") + QString(Suffix); - QFileInfo fi(fileName); - if (fi.exists()) - { - if (!localFile.exists()) - { - localFile.setFileName(fileName); - if (localFile.open(QFile::WriteOnly | QFile::Append | QFile::Text)) - { - isFileReady = true; - } - } - else - { - isFileReady = true; - } - } - else - { - localFile.setFileName(fileName); - if (localFile.open(QFile::WriteOnly | QFile::Append | QFile::Text)) - { - isFileReady = true; - } - } - } - return isFileReady; + isRecord2File = logConfig.isRecord2File; + QString logDir = QString(PATH_LogPath); + if (createDir(logDir)) + { + QString fileName = logDir + QDir::separator() + QDate::currentDate().toString("yyyy-MM-dd") + QString(Suffix); + QFileInfo fi(fileName); + if (fi.exists()) + { + if (!localFile.exists()) + { + localFile.setFileName(fileName); + if (localFile.open(QFile::WriteOnly | QFile::Append | QFile::Text)) + { + isFileReady = true; + } + } + else + { + isFileReady = true; + } + } + else + { + localFile.setFileName(fileName); + if (localFile.open(QFile::WriteOnly | QFile::Append | QFile::Text)) + { + isFileReady = true; + } + } + } + return isFileReady; } bool CLog::createDir(QString dirPath) { - QFileInfo fileInfo(dirPath); - if (!fileInfo.exists()) - { - QDir tmpDir; - return tmpDir.mkpath(dirPath); - } - - return true; + QFileInfo fileInfo(dirPath); + if (!fileInfo.exists()) + { + QDir tmpDir; + return tmpDir.mkpath(dirPath); + } + + return true; } void CLog::log(CLOG_TYPE nType, const char* fileDesc, const char* functionDesc, int lineNum, const char* data, ...) { - QMutexLocker locker(&mutexLog); - if (isFileReady) - { - QString recordInfo = QString("[%1]").arg(QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss:zzz")); - recordInfo.append(getTypeDesc(nType)); + QMutexLocker locker(&mutexLog); + if (isFileReady) + { + QString recordInfo = QString("[%1]").arg(QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss:zzz")); + recordInfo.append(getTypeDesc(nType)); #ifndef QT_NO_DEBUG - recordInfo.append(QString("[%1:%2:%3]").arg(fileDesc).arg(functionDesc).arg(lineNum)); + recordInfo.append(QString("[%1:%2:%3]").arg(fileDesc).arg(functionDesc).arg(lineNum)); #endif - va_list vlist; - va_start(vlist, data); + va_list vlist; + va_start(vlist, data); - QByteArray byteArray; + QByteArray byteArray; #if defined(Q_OS_WIN) - int recordLen = _vscprintf(data, vlist); - byteArray.resize(recordLen); + int recordLen = _vscprintf(data, vlist); + byteArray.resize(recordLen); #else - byteArray.resize(1024); + byteArray.resize(1024); #endif - vsprintf(byteArray.data(), data, vlist); - recordInfo.append(byteArray); - va_end(vlist); - - recordInfo.append("\n"); - - if (isRecord2File) { - localFile.write(recordInfo.toLocal8Bit().data(), recordInfo.toLocal8Bit().length()); - localFile.flush(); - } - else { - // qDebug()< class CLog : public QObject { - Q_OBJECT + Q_OBJECT public: - enum CLOG_TYPE - { + enum CLOG_TYPE + { - STARTAPP, - STARTWORK, - PAUSEWORK, - UNLOCK, - DEBUGMODE, - UNKICKMODE, - SETTING, - CLEANPIC, - DOUBLECLICK, - ROTATEPIC, - PLCSETTING, - ALARM - }; - //Q_DECLARE_FLAGS(CLOG_TYPE_Flags, CLOG_TYPE) - Q_ENUM(CLOG_TYPE) + STARTAPP, + STARTWORK, + PAUSEWORK, + UNLOCK, + DEBUGMODE, + UNKICKMODE, + SETTING, + CLEANPIC, + DOUBLECLICK, + ROTATEPIC, + PLCSETTING, + ALARM + }; + //Q_DECLARE_FLAGS(CLOG_TYPE_Flags, CLOG_TYPE) + Q_ENUM(CLOG_TYPE) - struct LogConfig - { - bool isRecord2File; - int level; - }; + struct LogConfig + { + bool isRecord2File; + int level; + }; - CLog(); + CLog(); - void setLogType(const CLog::CLOG_TYPE& type); - // CLog::CLOG_TYPE getLogType() { return logType; } + void setLogType(const CLog::CLOG_TYPE& type); + // CLog::CLOG_TYPE getLogType() { return logType; } - //void startClog(); - //void doWork(); - static bool init(CLog::LogConfig& logConfig); - static bool createDir(QString dirPath); - static void log(CLOG_TYPE nType, const char* fileDesc, const char* functionDesc, int lineNum, const char* data, ...); - static void log(CLOG_TYPE nType, const char* data, ...); + //void startClog(); + //void doWork(); + static bool init(CLog::LogConfig& logConfig); + static bool createDir(QString dirPath); + static void log(CLOG_TYPE nType, const char* fileDesc, const char* functionDesc, int lineNum, const char* data, ...); + static void log(CLOG_TYPE nType, const char* data, ...); public slots: - void recMegFromCigarette(QString); + void recMegFromCigarette(QString); private: - static QString getTypeDesc(CLOG_TYPE type); + static QString getTypeDesc(CLOG_TYPE type); private: - static bool isRecord2File; - static bool isFileReady; + static bool isRecord2File; + static bool isFileReady; }; #ifdef Q_OS_WIN diff --git a/Cigarette/PLC/PLCDevice.cpp b/Cigarette/PLC/PLCDevice.cpp index 58a23f2e..9618e44d 100644 --- a/Cigarette/PLC/PLCDevice.cpp +++ b/Cigarette/PLC/PLCDevice.cpp @@ -7,104 +7,104 @@ extern SysConf g_sys_conf; -modbus_t * g_modbus = NULL; //Modbus TCP +modbus_t* g_modbus = NULL; //Modbus TCP bool PLCDevice::init_plc(PLCDevice* PLCptr) { - // modbus_connect() 寤虹珛杩炴帴锛屾垚鍔熻繑鍥0锛岄敊璇繑鍥-1 - // modbus_new_rtu 鐢熸垚RTU鐨勮繛鎺ワ紝寤虹珛鎴愬姛鍒欒繑鍥炴寚鍚憁odbus_t缁撴瀯鐨勬寚閽堬紝鍚﹀垯灏嗚繑鍥濶ULL/0 + // modbus_connect() 寤虹珛杩炴帴锛屾垚鍔熻繑鍥0锛岄敊璇繑鍥-1 + // modbus_new_rtu 鐢熸垚RTU鐨勮繛鎺ワ紝寤虹珛鎴愬姛鍒欒繑鍥炴寚鍚憁odbus_t缁撴瀯鐨勬寚閽堬紝鍚﹀垯灏嗚繑鍥濶ULL/0 - const char* comport = g_sys_conf.ComPort.data(); - qDebug() << "COM:" << comport; - //杩炴帴PLC - g_modbus = modbus_new_rtu(comport, 9600, 'N', 8, 1); - modbus_set_debug(g_modbus, 0); // 鐢╢lag璁剧疆debug璋冭瘯鏍囧織浣嶏紝flag=1鏃舵樉绀簃odbus娑堟伅鐨勫瓧鑺 - modbus_set_response_timeout(g_modbus, 1, 0); // 璁剧疆鍝嶅簲瓒呮椂 - modbus_connect(g_modbus); - modbus_set_slave(g_modbus, 1); // 璁剧疆浠庣珯id + const char* comport = g_sys_conf.ComPort.data(); + qDebug() << "COM:" << comport; + //杩炴帴PLC + g_modbus = modbus_new_rtu(comport, 9600, 'N', 8, 1); + modbus_set_debug(g_modbus, 0); // 鐢╢lag璁剧疆debug璋冭瘯鏍囧織浣嶏紝flag=1鏃舵樉绀簃odbus娑堟伅鐨勫瓧鑺 + modbus_set_response_timeout(g_modbus, 1, 0); // 璁剧疆鍝嶅簲瓒呮椂 + modbus_connect(g_modbus); + modbus_set_slave(g_modbus, 1); // 璁剧疆浠庣珯id - uint8_t data; - int ret = modbus_read_bits(g_modbus, 30000, 1, &data); - if (g_modbus && ret == -1) { - PLCptr->g_plc_ok = false; - } - else { - - PLCptr->g_plc_ok = true; - } - return true; + uint8_t data; + int ret = modbus_read_bits(g_modbus, 30000, 1, &data); + if (g_modbus && ret == -1) { + PLCptr->g_plc_ok = false; + } + else { + + PLCptr->g_plc_ok = true; + } + return true; } bool PLCDevice::disconnect_plc(void) { - if(g_modbus) - { - modbus_close(g_modbus); - modbus_free(g_modbus); - } - return true; + if (g_modbus) + { + modbus_close(g_modbus); + modbus_free(g_modbus); + } + return true; } int PLCDevice::write_bit_2_plc(int addr, int value) { - if (g_plc_ok) - { - g_mutex.lock(); - int ret = modbus_write_bit(g_modbus, addr, value); - g_mutex.unlock(); - //printf("modbus_write_bit:addr=%d,value=%d,ret=%d\n", addr, value, ret); - return ret; - } - else { - //std::cout << "PLC no ok" << std::endl; - return false; - } + if (g_plc_ok) + { + g_mutex.lock(); + int ret = modbus_write_bit(g_modbus, addr, value); + g_mutex.unlock(); + //printf("modbus_write_bit:addr=%d,value=%d,ret=%d\n", addr, value, ret); + return ret; + } + else { + //std::cout << "PLC no ok" << std::endl; + return false; + } } -int PLCDevice::read_bits_from_plc(int addr, int nb,uint8_t* value) +int PLCDevice::read_bits_from_plc(int addr, int nb, uint8_t* value) { - if (g_plc_ok) - { - g_mutex.lock(); - int ret = modbus_read_bits(g_modbus, addr, nb ,value); - g_mutex.unlock(); - //printf("modbus_read_bits:addr=%d,nb=%d,value=%d,ret=%d\n", addr, nb, *value, ret); - return ret; - } - else { - //std::cout << "PLC no ok" << std::endl; - return false; - } + if (g_plc_ok) + { + g_mutex.lock(); + int ret = modbus_read_bits(g_modbus, addr, nb, value); + g_mutex.unlock(); + //printf("modbus_read_bits:addr=%d,nb=%d,value=%d,ret=%d\n", addr, nb, *value, ret); + return ret; + } + else { + //std::cout << "PLC no ok" << std::endl; + return false; + } } -int PLCDevice::write_short_2_plc(int addr, int nb, uint16_t *value) +int PLCDevice::write_short_2_plc(int addr, int nb, uint16_t* value) { - if (g_plc_ok) - { - g_mutex.lock(); - int ret = modbus_write_registers(g_modbus, addr, nb, value); - g_mutex.unlock(); - //printf("modbus_write_registers:addr=%d,nb=%d,value=%d,ret=%d\n", addr, nb, *value, ret); - return ret; - } - else { - //std::cout << "PLC no ok" << std::endl; - return false; - } + if (g_plc_ok) + { + g_mutex.lock(); + int ret = modbus_write_registers(g_modbus, addr, nb, value); + g_mutex.unlock(); + //printf("modbus_write_registers:addr=%d,nb=%d,value=%d,ret=%d\n", addr, nb, *value, ret); + return ret; + } + else { + //std::cout << "PLC no ok" << std::endl; + return false; + } } -int PLCDevice::read_short_from_plc(int addr, int nb, uint16_t *value) +int PLCDevice::read_short_from_plc(int addr, int nb, uint16_t* value) { - if (g_plc_ok) - { - g_mutex.lock(); - int ret = modbus_read_registers(g_modbus, addr, nb, value); - g_mutex.unlock(); - //printf("modbus_read_registers:addr=%d,nb=%d,value=%d,ret=%d\n", addr, nb, *value ,ret); - return ret; - } - else { - //std::cout << "PLC no ok" << std::endl; - return false; - } -} \ No newline at end of file + if (g_plc_ok) + { + g_mutex.lock(); + int ret = modbus_read_registers(g_modbus, addr, nb, value); + g_mutex.unlock(); + //printf("modbus_read_registers:addr=%d,nb=%d,value=%d,ret=%d\n", addr, nb, *value ,ret); + return ret; + } + else { + //std::cout << "PLC no ok" << std::endl; + return false; + } +} diff --git a/Cigarette/PLC/PLCDevice.h b/Cigarette/PLC/PLCDevice.h index e9bc1618..a227e596 100644 --- a/Cigarette/PLC/PLCDevice.h +++ b/Cigarette/PLC/PLCDevice.h @@ -3,18 +3,18 @@ class PLCDevice { public: - QMutex g_mutex; //璁块棶Modbus鐨勪簰鏂ラ攣 + QMutex g_mutex; //璁块棶Modbus鐨勪簰鏂ラ攣 bool g_plc_ok; //[0]:1=杩炴帴,0=鏂紑 uint8_t g_plc_status; - static bool init_plc(PLCDevice *PLCptr); - - int write_bit_2_plc(int addr, int value); - int read_bits_from_plc(int addr, int nb, uint8_t* value); - int write_short_2_plc(int addr, int nb, uint16_t *value); - int read_short_from_plc(int addr, int nb, uint16_t *value); + static bool init_plc(PLCDevice* PLCptr); + + int write_bit_2_plc(int addr, int value); + int read_bits_from_plc(int addr, int nb, uint8_t* value); + int write_short_2_plc(int addr, int nb, uint16_t* value); + int read_short_from_plc(int addr, int nb, uint16_t* value); bool disconnect_plc(void); }; diff --git a/Cigarette/SyncQueue.cpp b/Cigarette/SyncQueue.cpp index 707b7029..113b5911 100644 --- a/Cigarette/SyncQueue.cpp +++ b/Cigarette/SyncQueue.cpp @@ -1,3 +1,3 @@ #include "SyncQueue.h" - + diff --git a/Cigarette/SyncQueue.h b/Cigarette/SyncQueue.h index bb9a09f1..32af85a3 100644 --- a/Cigarette/SyncQueue.h +++ b/Cigarette/SyncQueue.h @@ -3,28 +3,28 @@ #include #include #include - + using namespace std; - + template class SyncQueue { public: - SyncQueue(int max_size); - ~SyncQueue(); - void put(const T& val); - void take(T& val); - void clear(); - bool isEmpty(); - bool isFull(); - int count(); + SyncQueue(int max_size); + ~SyncQueue(); + void put(const T& val); + void take(T& val); + void clear(); + bool isEmpty(); + bool isFull(); + int count(); public: - string name; + string name; private: - mutex lock; - condition_variable_any cv_full, cv_empty; - list q; - int size; - int max_size; + mutex lock; + condition_variable_any cv_full, cv_empty; + list q; + int size; + int max_size; }; using namespace std; @@ -42,54 +42,54 @@ SyncQueue::~SyncQueue() template void SyncQueue::put(const T& val) { - lock_guard locker(lock); - while (isFull()) - { - //cout << "\nQueue " << name << " is full now, wait a minute!" << endl; - cv_full.wait(lock); - } - q.emplace_back(val); - cv_empty.notify_one(); - //cout << " Put image success " << endl; + lock_guard locker(lock); + while (isFull()) + { + //cout << "\nQueue " << name << " is full now, wait a minute!" << endl; + cv_full.wait(lock); + } + q.emplace_back(val); + cv_empty.notify_one(); + //cout << " Put image success " << endl; } template void SyncQueue::take(T& val) { - lock_guard locker(lock); - while (isEmpty()) - { - //cout << "\nQueue "<< name << " is empty now, wait a minute!" << endl; - cv_empty.wait(lock); - } - val = q.front(); - q.pop_front(); - cv_full.notify_one(); - //cout << " Take image success "<< endl; + lock_guard locker(lock); + while (isEmpty()) + { + //cout << "\nQueue "<< name << " is empty now, wait a minute!" << endl; + cv_empty.wait(lock); + } + val = q.front(); + q.pop_front(); + cv_full.notify_one(); + //cout << " Take image success "<< endl; } template void SyncQueue::clear() { - lock_guard locker(lock); - q.clear(); + lock_guard locker(lock); + q.clear(); } template bool SyncQueue::isEmpty() { - return q.size() == 0; + return q.size() == 0; } template bool SyncQueue::isFull() { - return q.size() == max_size; + return q.size() == max_size; } template int SyncQueue::count() { - lock_guard locker(lock); - return q.size(); -} \ No newline at end of file + lock_guard locker(lock); + return q.size(); +} diff --git a/Cigarette/alarmdialog.cpp b/Cigarette/alarmdialog.cpp index 56566cb4..677291e5 100644 --- a/Cigarette/alarmdialog.cpp +++ b/Cigarette/alarmdialog.cpp @@ -3,43 +3,43 @@ extern std::vector g_vec_alarm; -AlarmDialog::AlarmDialog(QWidget * parent) : QDialog(parent) { - ui.setupUi(this); - this->setWindowFlags(Qt::FramelessWindowHint); - ui.tableWidget->setColumnCount(4); - ui.tableWidget->setRowCount(g_vec_alarm.size()); - QStringList header_list; - header_list << QStringLiteral("鎶ヨ寮濮嬫椂闂") << QStringLiteral("鎶ヨ澶勭悊鏃堕棿") - << QStringLiteral("鎶ヨ淇℃伅") << QStringLiteral("鎶ヨ浠g爜"); - ui.tableWidget->setHorizontalHeaderLabels(header_list); - ui.tableWidget->setColumnWidth(0, 140); - ui.tableWidget->setColumnWidth(1, 140); - ui.tableWidget->setColumnWidth(2, 380); - ui.tableWidget->setColumnWidth(3, 120); - for (int i = 0; i < g_vec_alarm.size(); i++) - { - ui.tableWidget->setItem(i, 0, new QTableWidgetItem(QString(g_vec_alarm[i].alarm_start.c_str()))); - ui.tableWidget->setItem(i, 1, new QTableWidgetItem(QString(g_vec_alarm[i].alarm_handle.c_str()))); - ui.tableWidget->setItem(i, 2, new QTableWidgetItem(QString(g_vec_alarm[i].alarm_msg.c_str()))); - ui.tableWidget->setItem(i, 3, new QTableWidgetItem(QString::number(g_vec_alarm[i].alarm_code))); - } +AlarmDialog::AlarmDialog(QWidget* parent) : QDialog(parent) { + ui.setupUi(this); + this->setWindowFlags(Qt::FramelessWindowHint); + ui.tableWidget->setColumnCount(4); + ui.tableWidget->setRowCount(g_vec_alarm.size()); + QStringList header_list; + header_list << QStringLiteral("鎶ヨ寮濮嬫椂闂") << QStringLiteral("鎶ヨ澶勭悊鏃堕棿") + << QStringLiteral("鎶ヨ淇℃伅") << QStringLiteral("鎶ヨ浠g爜"); + ui.tableWidget->setHorizontalHeaderLabels(header_list); + ui.tableWidget->setColumnWidth(0, 140); + ui.tableWidget->setColumnWidth(1, 140); + ui.tableWidget->setColumnWidth(2, 380); + ui.tableWidget->setColumnWidth(3, 120); + for (int i = 0; i < g_vec_alarm.size(); i++) + { + ui.tableWidget->setItem(i, 0, new QTableWidgetItem(QString(g_vec_alarm[i].alarm_start.c_str()))); + ui.tableWidget->setItem(i, 1, new QTableWidgetItem(QString(g_vec_alarm[i].alarm_handle.c_str()))); + ui.tableWidget->setItem(i, 2, new QTableWidgetItem(QString(g_vec_alarm[i].alarm_msg.c_str()))); + ui.tableWidget->setItem(i, 3, new QTableWidgetItem(QString::number(g_vec_alarm[i].alarm_code))); + } } AlarmDialog::~AlarmDialog() { - + } void AlarmDialog::on_pushButton_close_released() { - this->close(); + this->close(); } void AlarmDialog::on_pushButton_clear_released() { - int rowNum = ui.tableWidget->rowCount(); - for (int i = rowNum - 1; i >= 0; i--) - { - ui.tableWidget->removeRow(i); - } - g_vec_alarm.clear(); + int rowNum = ui.tableWidget->rowCount(); + for (int i = rowNum - 1; i >= 0; i--) + { + ui.tableWidget->removeRow(i); + } + g_vec_alarm.clear(); } diff --git a/Cigarette/alarmdialog.hpp b/Cigarette/alarmdialog.hpp index d27bdf38..a2943559 100644 --- a/Cigarette/alarmdialog.hpp +++ b/Cigarette/alarmdialog.hpp @@ -1,18 +1,18 @@ -锘#pragma once +#pragma once #include #include "ui_alarmdialog.h" class AlarmDialog : public QDialog { - Q_OBJECT + Q_OBJECT public: - AlarmDialog(QWidget * parent = Q_NULLPTR); - ~AlarmDialog(); + AlarmDialog(QWidget* parent = Q_NULLPTR); + ~AlarmDialog(); private slots: - void on_pushButton_close_released(); - void on_pushButton_clear_released(); + void on_pushButton_close_released(); + void on_pushButton_clear_released(); private: - Ui::AlarmDialog ui; + Ui::AlarmDialog ui; }; diff --git a/Cigarette/alg_jd.cpp b/Cigarette/alg_jd.cpp index 72273804..e7025a19 100644 --- a/Cigarette/alg_jd.cpp +++ b/Cigarette/alg_jd.cpp @@ -1,10 +1,10 @@ #include "alg_jd.h" -#include //所需的库文件 +#include //鎵闇鐨勫簱鏂囦欢 extern SysConf g_sys_conf; // Initialize the parameters -static float confThreshold = g_sys_conf.ConfThreshold*0.01; // Confidence threshold +static float confThreshold = g_sys_conf.ConfThreshold * 0.01; // Confidence threshold static float nmsThreshold = 0.4; // Non-maximum suppression threshold static int inpWidth = 416; // Width of network's input image static int inpHeight = 416; // Height of network's input image @@ -20,7 +20,7 @@ bool AlgJd::init(QString model_path, QString model_name) QString image_path; if (model_path.length() > 0 && model_name.length() > 0) { - // 拼凑的模型文件路径 + // 鎷煎噾鐨勬ā鍨嬫枃浠惰矾寰 modelWeights = model_path.toStdString() + "/" + model_name.toStdString(); modelConfiguration = model_path.toStdString() + "/jd.cfg"; classesFile = model_path.toStdString() + "/jd.names"; @@ -41,8 +41,8 @@ bool AlgJd::init(QString model_path, QString model_name) while (std::getline(classNamesFile, className)) classes.push_back(className); } - else{ - return false; + else { + return false; } // Load the network @@ -50,8 +50,8 @@ bool AlgJd::init(QString model_path, QString model_name) net.setPreferableBackend(cv::dnn::DNN_BACKEND_CUDA); net.setPreferableTarget(cv::dnn::DNN_TARGET_CUDA); - - //cv::Mat image = cv::imread("alg_jd.bmp"); + + //cv::Mat image = cv::imread("alg_jd.bmp"); cv::Mat image = cv::imread(image_path.toStdString()); /*if (g_sys_conf.model_jpg_path.length() > 0) { image = cv::imread(g_sys_conf.model_jpg_path.toStdString()); @@ -60,23 +60,23 @@ bool AlgJd::init(QString model_path, QString model_name) image = cv::imread("D:/Release/alg_jd.bmp"); }*/ - //识别一张图,测试模型是否正确,并且完成GPU数据加载 - if (!image.data) return false; //判断测试图片是否正常读取 - std::vector > results; - detect(image, image, results); - if (results.size() > 0) - return true; //检测到目标,则初始化成功 - else - return false; //否则初始化失败 + //璇嗗埆涓寮犲浘锛屾祴璇曟ā鍨嬫槸鍚︽纭紝骞朵笖瀹屾垚GPU鏁版嵁鍔犺浇 + if (!image.data) return false; //鍒ゆ柇娴嬭瘯鍥剧墖鏄惁姝e父璇诲彇 + std::vector > results; + detect(image, image, results); + if (results.size() > 0) + return true; //妫娴嬪埌鐩爣锛屽垯鍒濆鍖栨垚鍔 + else + return false; //鍚﹀垯鍒濆鍖栧け璐 } bool AlgJd::test_detect() { cv::Mat m1; m1 = cv::Mat(544, 728, CV_8UC3, cv::Scalar(0, 0, 0)); - std::vector > results; + std::vector > results; double t = (double)cv::getTickCount(); - detect(m1, m1, results); + detect(m1, m1, results); t = ((double)cv::getTickCount() - t) / cv::getTickFrequency(); DEBUG(" test_detect time process:%f\n", t); return true; @@ -95,33 +95,33 @@ bool AlgJd::test_detect_batcht(int shoot) m4 = cv::Mat(544, 728, CV_8UC3, cv::Scalar(0, 0, 0)); double t = (double)cv::getTickCount(); - switch(shoot){ - case 1:{ - std::vector > results; - detect(m1, m1, results); - break; - } - case 3:vec_in.push_back(m3); - case 2:vec_in.push_back(m2); - case 4:vec_in.push_back(m4); - default:{ - vec_in.push_back(m1); - detect_batch(vec_in, vec_out, vec_results); - } + switch (shoot) { + case 1: { + std::vector > results; + detect(m1, m1, results); + break; + } + case 3:vec_in.push_back(m3); + case 2:vec_in.push_back(m2); + case 4:vec_in.push_back(m4); + default: { + vec_in.push_back(m1); + detect_batch(vec_in, vec_out, vec_results); + } } t = ((double)cv::getTickCount() - t) / cv::getTickFrequency(); DEBUG(" test_detect_batcht time process:%f\n", t); return true; } -int AlgJd::detect(cv::Mat& _frame, cv::Mat &out, std::vector > &results) +int AlgJd::detect(cv::Mat& _frame, cv::Mat& out, std::vector >& results) { cv::Mat frame = _frame.clone(); - cv::Mat image_clone=frame.clone(); + cv::Mat image_clone = frame.clone(); // Process frames. // Create a 4D blob from a frame. cv::Mat blob; - cv::dnn::blobFromImage(frame, blob, 1/255.0, cv::Size(inpWidth, inpHeight), cv::Scalar(0,0,0), true, false); + cv::dnn::blobFromImage(frame, blob, 1 / 255.0, cv::Size(inpWidth, inpHeight), cv::Scalar(0, 0, 0), true, false); //Sets the input to the network net.setInput(blob); @@ -140,8 +140,8 @@ int AlgJd::detect(cv::Mat& _frame, cv::Mat &out, std::vector >& vec_results) @@ -155,7 +155,7 @@ void AlgJd::analyse(cv::Mat vec_in, std::vector >& vec_ cv::imshow("analyse", topography); cv::waitKey(1); } - + } // Get the names of the output layers @@ -173,12 +173,12 @@ std::vector AlgJd::getOutputsNames(const cv::dnn::Net& net) // Get the names of the output layers in names names.resize(outLayers.size()); for (size_t i = 0; i < outLayers.size(); ++i) - names[i] = layersNames[outLayers[i] - 1]; + names[i] = layersNames[outLayers[i] - 1]; } return names; } -void AlgJd::post_process(cv::Mat& frame, std::vector& outs, std::vector > &results) +void AlgJd::post_process(cv::Mat& frame, std::vector& outs, std::vector >& results) { std::vector < std::vector> classIds(classes.size()); std::vector < std::vector> confidences(classes.size()); @@ -235,18 +235,18 @@ void AlgJd::post_process(cv::Mat& frame, std::vector& outs, std::vector // Draw the predicted bounding box void AlgJd::drawPred(int classId, float conf, int left, int top, int right, int bottom, cv::Mat& frame) { - cv::Scalar color; - if(classId==0) - color = cv::Scalar(0,255,0); - else if(classId == 1) - color = cv::Scalar(255,0,0); - else - color = cv::Scalar(0, 255, 0); + cv::Scalar color; + if (classId == 0) + color = cv::Scalar(0, 255, 0); + else if (classId == 1) + color = cv::Scalar(255, 0, 0); + else + color = cv::Scalar(0, 255, 0); //Draw a rectangle displaying the bounding box cv::rectangle(frame, cv::Point(left, top), cv::Point(right, bottom), color, 4); - + //Get the label for the class name and its confidence - std::string label = cv::format("%.2f%%", (conf*100));/// + std::string label = cv::format("%.2f%%", (conf * 100));/// if (!classes.empty()) { CV_Assert(classId < (int)classes.size()); @@ -254,98 +254,98 @@ void AlgJd::drawPred(int classId, float conf, int left, int top, int right, int } else { - std::cout<<"classes is empty..."<& vec_in, std::vector &vec_out, std::vector > > &vec_results) +void AlgJd::detect_batch(std::vector& vec_in, std::vector& vec_out, std::vector > >& vec_results) { - cv::Mat blobs; + cv::Mat blobs; std::vector image; - - cv::dnn::blobFromImages(vec_in, blobs, 1 / 255.0, cv::Size(inpWidth, inpHeight), cv::Scalar(0, 0, 0), true, false); - //Sets the input to the network - net.setInput(blobs); + cv::dnn::blobFromImages(vec_in, blobs, 1 / 255.0, cv::Size(inpWidth, inpHeight), cv::Scalar(0, 0, 0), true, false); + + //Sets the input to the network + net.setInput(blobs); - // Runs the forward pass to get output of the output layers - std::vector outs; - net.forward(outs, getOutputsNames(net)); + // Runs the forward pass to get output of the output layers + std::vector outs; + net.forward(outs, getOutputsNames(net)); - for (int i = 0; i < vec_in.size(); i++) - { - image.push_back(vec_in[i].clone()); - } + for (int i = 0; i < vec_in.size(); i++) + { + image.push_back(vec_in[i].clone()); + } - // Remove the bounding boxes with low confidence - post_process_batch(image, outs, vec_results); + // Remove the bounding boxes with low confidence + post_process_batch(image, outs, vec_results); - // Write the frame with the detection boxes - for (int i = 0; i < vec_in.size(); i++) - { - cv::Mat detectedFrame, out; - image[i].convertTo(detectedFrame, CV_8U); - out = detectedFrame.clone(); - vec_out.push_back(out); - } + // Write the frame with the detection boxes + for (int i = 0; i < vec_in.size(); i++) + { + cv::Mat detectedFrame, out; + image[i].convertTo(detectedFrame, CV_8U); + out = detectedFrame.clone(); + vec_out.push_back(out); + } } -void AlgJd::post_process_batch(std::vector& vec_frame, std::vector& outs, std::vector > > &vec_results) +void AlgJd::post_process_batch(std::vector& vec_frame, std::vector& outs, std::vector > >& vec_results) { - int batch = vec_frame.size(); + int batch = vec_frame.size(); double confidence;/// - for (int k = 0; k < batch; k++) - { + for (int k = 0; k < batch; k++) + { std::vector < std::vector> classIds(classes.size()); std::vector < std::vector> confidences(classes.size()); std::vector < std::vector> boxes(classes.size()); //std::cout << "outs.size()\t" << outs.size() << std::endl; - //std::cout << "Type\t" << outs[0].type() << std::endl; - - for (size_t i = 0; i < outs.size(); ++i) - { - //std::cout << "outs.dims\t" << outs[i].dims << std::endl; - //std::cout << "outs[" << i << "].rows\t" << outs[i].size[0] << std::endl; - //std::cout << "outs[" << i << "].cols\t" << outs[i].size[1] << std::endl; - //std::cout << "outs[" << i << "].cols\t" << outs[i].size[2] << std::endl; - // Scan through all the bounding boxes output from the network and keep only the - // ones with high confidence scores. Assign the box's class label as the class - // - cv::Mat m0(outs[i].size[1], outs[i].size[2], CV_32F, outs[i].data + outs[i].step[0] * k); - // with the highest score for the box. - float* data = (float*)m0.data; - for (int j = 0; j < m0.rows; ++j, data += m0.cols) - { - cv::Mat scores = m0.row(j).colRange(5, m0.cols); - cv::Point classIdPoint; - //double confidence; - // Get the value and location of the maximum score - cv::minMaxLoc(scores, 0, &confidence, 0, &classIdPoint); - - if (confidence > confThreshold) - { - int centerX = (int)(data[0] * vec_frame[k].cols); - int centerY = (int)(data[1] * vec_frame[k].rows); - int width = (int)(data[2] * vec_frame[k].cols); - int height = (int)(data[3] * vec_frame[k].rows); - int left = centerX - width / 2; - int top = centerY - height / 2; - - classIds[classIdPoint.x].push_back(classIdPoint.x); - confidences[classIdPoint.x].push_back((float)confidence); - boxes[classIdPoint.x].push_back(cv::Rect(left, top, width, height)); - } - } - } - std::vector > results; + //std::cout << "Type\t" << outs[0].type() << std::endl; + + for (size_t i = 0; i < outs.size(); ++i) + { + //std::cout << "outs.dims\t" << outs[i].dims << std::endl; + //std::cout << "outs[" << i << "].rows\t" << outs[i].size[0] << std::endl; + //std::cout << "outs[" << i << "].cols\t" << outs[i].size[1] << std::endl; + //std::cout << "outs[" << i << "].cols\t" << outs[i].size[2] << std::endl; + // Scan through all the bounding boxes output from the network and keep only the + // ones with high confidence scores. Assign the box's class label as the class + // + cv::Mat m0(outs[i].size[1], outs[i].size[2], CV_32F, outs[i].data + outs[i].step[0] * k); + // with the highest score for the box. + float* data = (float*)m0.data; + for (int j = 0; j < m0.rows; ++j, data += m0.cols) + { + cv::Mat scores = m0.row(j).colRange(5, m0.cols); + cv::Point classIdPoint; + //double confidence; + // Get the value and location of the maximum score + cv::minMaxLoc(scores, 0, &confidence, 0, &classIdPoint); + + if (confidence > confThreshold) + { + int centerX = (int)(data[0] * vec_frame[k].cols); + int centerY = (int)(data[1] * vec_frame[k].rows); + int width = (int)(data[2] * vec_frame[k].cols); + int height = (int)(data[3] * vec_frame[k].rows); + int left = centerX - width / 2; + int top = centerY - height / 2; + + classIds[classIdPoint.x].push_back(classIdPoint.x); + confidences[classIdPoint.x].push_back((float)confidence); + boxes[classIdPoint.x].push_back(cv::Rect(left, top, width, height)); + } + } + } + std::vector > results; // Perform non maximum suppression to eliminate redundant overlapping boxes with // lower confidences for (size_t i = 0; i < classes.size(); ++i) @@ -356,17 +356,17 @@ void AlgJd::post_process_batch(std::vector& vec_frame, std::vector g_sys_conf.ConfThreshold * 0.01)///识别度低于阈值NG处理 + if (confidences[i][idx] > g_sys_conf.ConfThreshold * 0.01)///璇嗗埆搴︿綆浜庨槇鍊糔G澶勭悊 { if (box.width > 15) - {//识别框宽度大于15显示识别,小于认为无胶点,NG处理 + {//璇嗗埆妗嗗搴﹀ぇ浜15鏄剧ず璇嗗埆锛屽皬浜庤涓烘棤鑳剁偣锛孨G澶勭悊 drawPred(classIds[i][idx], confidences[i][idx], box.x, box.y, box.x + box.width, box.y + box.height, vec_frame[k]); results.push_back(std::make_pair(classIds[i][idx], box)); } } } - } - vec_results.push_back(results); - } + } + vec_results.push_back(results); + } } diff --git a/Cigarette/alg_jd.h b/Cigarette/alg_jd.h index 36e42593..e3aa2ab2 100644 --- a/Cigarette/alg_jd.h +++ b/Cigarette/alg_jd.h @@ -11,25 +11,25 @@ #include "common.h" class AlgJd { - public: - bool init(QString model_path, QString model_name); - bool test_detect(); - bool test_detect_batcht(int shoot); - int detect(cv::Mat& in, cv::Mat &out, std::vector > &results); - // Remove the bounding boxes with low confidence using non-maxima suppression - void post_process(cv::Mat& frame, std::vector& outs, std::vector > &results); - void CircleImagePro(cv::Mat src, cv::Mat dst, std::vector radius); - void detect_batch(std::vector& vec_in, std::vector &vec_out, std::vector > > &vec_results); - // Remove the bounding boxes with low confidence using non-maxima suppression - void post_process_batch(std::vector& vec_frame, std::vector& outs, std::vector > > &vec_results); - void analyse(cv::Mat vec_in, std::vector > & vec_results); - // Get the names of the output layers - std::vector getOutputsNames(const cv::dnn::Net& net); - // Draw the predicted bounding box - void drawPred(int classId, float conf, int left, int top, int right, int bottom, cv::Mat& frame); - private: - cv::dnn::Net net; - std::vector classes; +public: + bool init(QString model_path, QString model_name); + bool test_detect(); + bool test_detect_batcht(int shoot); + int detect(cv::Mat& in, cv::Mat& out, std::vector >& results); + // Remove the bounding boxes with low confidence using non-maxima suppression + void post_process(cv::Mat& frame, std::vector& outs, std::vector >& results); + void CircleImagePro(cv::Mat src, cv::Mat dst, std::vector radius); + void detect_batch(std::vector& vec_in, std::vector& vec_out, std::vector > >& vec_results); + // Remove the bounding boxes with low confidence using non-maxima suppression + void post_process_batch(std::vector& vec_frame, std::vector& outs, std::vector > >& vec_results); + void analyse(cv::Mat vec_in, std::vector >& vec_results); + // Get the names of the output layers + std::vector getOutputsNames(const cv::dnn::Net& net); + // Draw the predicted bounding box + void drawPred(int classId, float conf, int left, int top, int right, int bottom, cv::Mat& frame); +private: + cv::dnn::Net net; + std::vector classes; }; #endif //end of _CIGARETTE_JD diff --git a/Cigarette/balluffcamera.cpp b/Cigarette/balluffcamera.cpp index 4eddee44..ae739c59 100644 --- a/Cigarette/balluffcamera.cpp +++ b/Cigarette/balluffcamera.cpp @@ -3,11 +3,11 @@ #include #include -mvIMPACT::acquire::DeviceManager BalluffCamera:: devMgr; +mvIMPACT::acquire::DeviceManager BalluffCamera::devMgr; bool BalluffCamera::license_pass = false; BalluffCamera::BalluffCamera() { - + } @@ -18,5 +18,5 @@ BalluffCamera::~BalluffCamera() int BalluffCamera::Enumerate() { - return devMgr.deviceCount(); -} \ No newline at end of file + return devMgr.deviceCount(); +} diff --git a/Cigarette/balluffcamera.h b/Cigarette/balluffcamera.h index 9d58e034..cefb343f 100644 --- a/Cigarette/balluffcamera.h +++ b/Cigarette/balluffcamera.h @@ -6,15 +6,15 @@ #define BalluffClassID 0x01 -class BalluffCamera: public BaseCamera +class BalluffCamera : public BaseCamera { public: - BalluffCamera(); - ~BalluffCamera(); + BalluffCamera(); + ~BalluffCamera(); - static int Enumerate(); - -public: - static mvIMPACT::acquire::DeviceManager devMgr; - static bool license_pass; -}; \ No newline at end of file + static int Enumerate(); + +public: + static mvIMPACT::acquire::DeviceManager devMgr; + static bool license_pass; +}; diff --git a/Cigarette/basecamera.h b/Cigarette/basecamera.h index d3f3bad8..ce47ec61 100644 --- a/Cigarette/basecamera.h +++ b/Cigarette/basecamera.h @@ -8,20 +8,20 @@ #define ImageCap 2 typedef struct _SingleCamInfoStruct { - int unfiltered_num; - int filtered_num; - int CamClass; - int UserID; - bool Detect; - bool IsOpen; - bool OffLine; + int unfiltered_num; + int filtered_num; + int CamClass; + int UserID; + bool Detect; + bool IsOpen; + bool OffLine; }SingleCamInfoStruct; class BaseCamera { public: - BaseCamera(); - ~BaseCamera(); + BaseCamera(); + ~BaseCamera(); public: }; diff --git a/Cigarette/baslercamera.cpp b/Cigarette/baslercamera.cpp index 38715fb6..a334a299 100644 --- a/Cigarette/baslercamera.cpp +++ b/Cigarette/baslercamera.cpp @@ -13,33 +13,33 @@ BaslerCamera::BaslerCamera() BaslerCamera::~BaslerCamera() { - Pylon::PylonTerminate(); + Pylon::PylonTerminate(); } int BaslerCamera::Enumerate() { - int n_basler_cam = 0; - - // Before using any pylon methods, the pylon runtime must be initialized. - Pylon::PylonInitialize(); - try - { - // Get the transport layer factory. - Pylon::CTlFactory& tlFactory = Pylon::CTlFactory::GetInstance(); - - // Get all attached devices and exit application if no device is found. - if (tlFactory.EnumerateDevices(devices) == 0) - { - return 0; - } - n_basler_cam = min(devices.size(), c_maxCamerasToUse); - } - catch (const Pylon::GenericException& e) - { - // Error handling - cerr << "An exception occurred." << endl - << e.GetDescription() << endl; - } - return n_basler_cam; -} \ No newline at end of file + int n_basler_cam = 0; + + // Before using any pylon methods, the pylon runtime must be initialized. + Pylon::PylonInitialize(); + try + { + // Get the transport layer factory. + Pylon::CTlFactory& tlFactory = Pylon::CTlFactory::GetInstance(); + + // Get all attached devices and exit application if no device is found. + if (tlFactory.EnumerateDevices(devices) == 0) + { + return 0; + } + n_basler_cam = min(devices.size(), c_maxCamerasToUse); + } + catch (const Pylon::GenericException& e) + { + // Error handling + cerr << "An exception occurred." << endl + << e.GetDescription() << endl; + } + return n_basler_cam; +} diff --git a/Cigarette/baslercamera.h b/Cigarette/baslercamera.h index c87f82a7..6c9311d1 100644 --- a/Cigarette/baslercamera.h +++ b/Cigarette/baslercamera.h @@ -12,21 +12,21 @@ #define BaslerClassID 0x02 #define c_maxCamerasToUse (size_t)2 -//5:灰色 -//6:黑色 -//1:红色 -//2:黄色 -//3:白色 -//4:绿色 +//5:鐏拌壊 +//6:榛戣壊 +//1:绾㈣壊 +//2:榛勮壊 +//3:鐧借壊 +//4:缁胯壊 -class BaslerCamera: public BaseCamera +class BaslerCamera : public BaseCamera { public: - BaslerCamera(); - ~BaslerCamera(); + BaslerCamera(); + ~BaslerCamera(); - static int Enumerate(); + static int Enumerate(); public: - static Pylon::DeviceInfoList_t devices; + static Pylon::DeviceInfoList_t devices; }; diff --git a/Cigarette/camera_glue.cpp b/Cigarette/camera_glue.cpp index 6fd0349a..ca058c22 100644 --- a/Cigarette/camera_glue.cpp +++ b/Cigarette/camera_glue.cpp @@ -5,34 +5,34 @@ spinBox[a][1] = ui.spinBox_##b##2;\ spinBox[a][2] = ui.spinBox_##b##3; -camera_glue::camera_glue(QDialog *parent) - : QDialog(parent) +camera_glue::camera_glue(QDialog* parent) + : QDialog(parent) { - ui.setupUi(this); - this->setWindowFlags(windowFlags()&~Qt::WindowContextHelpButtonHint); + ui.setupUi(this); + this->setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint); #if defined(NumberOfSupportedCameras) && (NumberOfSupportedCameras>0) - camera_glue_init(0,1) + camera_glue_init(0, 1) #endif #if defined(NumberOfSupportedCameras) && (NumberOfSupportedCameras>1) - camera_glue_init(1,2) + camera_glue_init(1, 2) #endif #if defined(NumberOfSupportedCameras) && (NumberOfSupportedCameras>2) - camera_glue_init(2,3) + camera_glue_init(2, 3) #endif #if defined(NumberOfSupportedCameras) && (NumberOfSupportedCameras>3) - camera_glue_init(3,4) + camera_glue_init(3, 4) #endif #if defined(NumberOfSupportedCameras) && (NumberOfSupportedCameras>4) - camera_glue_init(4,5) + camera_glue_init(4, 5) #endif #if defined(NumberOfSupportedCameras) && (NumberOfSupportedCameras>5) - camera_glue_init(5,6) + camera_glue_init(5, 6) #endif #if defined(NumberOfSupportedCameras) && (NumberOfSupportedCameras>6) - camera_glue_init(6,7) + camera_glue_init(6, 7) #endif #if defined(NumberOfSupportedCameras) && (NumberOfSupportedCameras>7) - camera_glue_init(7,8) + camera_glue_init(7, 8) #endif } @@ -43,17 +43,17 @@ camera_glue::~camera_glue() void camera_glue::recMsgFromDialogSetup(int ptr[][3]) { - for(int i=0;isetValue(ptr[i][j]); + for (int i = 0; i < NumberOfSupportedCameras; i++) + for (int j = 0; j < 3; j++) + spinBox[i][j]->setValue(ptr[i][j]); } void camera_glue::on_pushButton_take_released(void) { - int mat[NumberOfSupportedCameras][3]; - for(int i=0;ivalue(); - emit sendMsgToDialogSetup(mat); - this->close(); -} \ No newline at end of file + int mat[NumberOfSupportedCameras][3]; + for (int i = 0; i < NumberOfSupportedCameras; i++) + for (int j = 0; j < 3; j++) + mat[i][j] = spinBox[i][j]->value(); + emit sendMsgToDialogSetup(mat); + this->close(); +} diff --git a/Cigarette/camera_glue.h b/Cigarette/camera_glue.h index d0b500b2..247440f8 100644 --- a/Cigarette/camera_glue.h +++ b/Cigarette/camera_glue.h @@ -6,20 +6,20 @@ #include "common.h" class camera_glue : public QDialog { - Q_OBJECT + Q_OBJECT public: - camera_glue(QDialog *parent = Q_NULLPTR); - ~camera_glue(); + camera_glue(QDialog* parent = Q_NULLPTR); + ~camera_glue(); signals: - void sendMsgToDialogSetup(int ptr[][3]); + void sendMsgToDialogSetup(int ptr[][3]); public slots: - void recMsgFromDialogSetup(int ptr[][3]); - void on_pushButton_take_released(void); + void recMsgFromDialogSetup(int ptr[][3]); + void on_pushButton_take_released(void); private: - Ui::camera_glue ui; - QSpinBox *spinBox[NumberOfSupportedCameras][3]; - SysConf local_SysConf; + Ui::camera_glue ui; + QSpinBox* spinBox[NumberOfSupportedCameras][3]; + SysConf local_SysConf; }; diff --git a/Cigarette/change_shift.cpp b/Cigarette/change_shift.cpp index 6950b510..18bb49af 100644 --- a/Cigarette/change_shift.cpp +++ b/Cigarette/change_shift.cpp @@ -3,30 +3,30 @@ #include extern SysConf g_sys_conf; -change_shift::change_shift(QDialog *parent) - : QDialog(parent) +change_shift::change_shift(QDialog* parent) + : QDialog(parent) { - ui.setupUi(this); - this->setWindowFlags(windowFlags()&~Qt::WindowContextHelpButtonHint); + ui.setupUi(this); + this->setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint); - if (g_sys_conf.auto_shift == 1) { - ui.radioButton_auto->setChecked(true); - } - else { - ui.radioButton_auto->setChecked(false); - } - if (g_sys_conf.shift_byhand == 1) { - ui.radioButton_byhand->setChecked(true); - } - else { - ui.radioButton_byhand->setChecked(false); - } - if (g_sys_conf.timing_shift == 1) { - ui.radioButton_time->setChecked(true); - } - else { - ui.radioButton_time->setChecked(false); - } + if (g_sys_conf.auto_shift == 1) { + ui.radioButton_auto->setChecked(true); + } + else { + ui.radioButton_auto->setChecked(false); + } + if (g_sys_conf.shift_byhand == 1) { + ui.radioButton_byhand->setChecked(true); + } + else { + ui.radioButton_byhand->setChecked(false); + } + if (g_sys_conf.timing_shift == 1) { + ui.radioButton_time->setChecked(true); + } + else { + ui.radioButton_time->setChecked(false); + } } change_shift::~change_shift() @@ -35,56 +35,56 @@ change_shift::~change_shift() void change_shift::on_pushButton_apply_released() { - QTime timeA; - QTime timeB; - QTime timeC; - if (ui.radioButton_auto->isChecked()) { /// 已隐藏 - g_sys_conf.auto_shift = 1; - g_sys_conf.timing_shift = 0; - g_sys_conf.shift_byhand = 0; + QTime timeA; + QTime timeB; + QTime timeC; + if (ui.radioButton_auto->isChecked()) { /// 宸查殣钘 + g_sys_conf.auto_shift = 1; + g_sys_conf.timing_shift = 0; + g_sys_conf.shift_byhand = 0; - timeA.setHMS(ui.A_hour->minimum(), ui.A_minute->minimum(), 0); - timeB.setHMS(ui.B_hour->minimum(), ui.B_minute->minimum(), 0); - timeC.setHMS(ui.C_hour->minimum(), ui.C_minute->minimum(), 0); - //emit sendMsgToDialogSetup(timeA, timeB, timeC); - //this->close(); - } - else if (ui.radioButton_time->isChecked()) { - g_sys_conf.auto_shift = 0; - g_sys_conf.timing_shift = 1; - g_sys_conf.shift_byhand = 0; + timeA.setHMS(ui.A_hour->minimum(), ui.A_minute->minimum(), 0); + timeB.setHMS(ui.B_hour->minimum(), ui.B_minute->minimum(), 0); + timeC.setHMS(ui.C_hour->minimum(), ui.C_minute->minimum(), 0); + //emit sendMsgToDialogSetup(timeA, timeB, timeC); + //this->close(); + } + else if (ui.radioButton_time->isChecked()) { + g_sys_conf.auto_shift = 0; + g_sys_conf.timing_shift = 1; + g_sys_conf.shift_byhand = 0; - timeA.setHMS(ui.A_hour->text().toInt(), ui.A_minute->text().toInt(), 0); - timeB.setHMS(ui.B_hour->text().toInt(), ui.B_minute->text().toInt(), 0); - timeC.setHMS(ui.C_hour->text().toInt(), ui.C_minute->text().toInt(), 0); - //emit sendMsgToDialogSetup(timeA, timeB, timeC); - //this->close(); - } - else if (ui.radioButton_byhand->isChecked()) { - g_sys_conf.auto_shift = 0; - g_sys_conf.timing_shift = 0; - g_sys_conf.shift_byhand = 1; + timeA.setHMS(ui.A_hour->text().toInt(), ui.A_minute->text().toInt(), 0); + timeB.setHMS(ui.B_hour->text().toInt(), ui.B_minute->text().toInt(), 0); + timeC.setHMS(ui.C_hour->text().toInt(), ui.C_minute->text().toInt(), 0); + //emit sendMsgToDialogSetup(timeA, timeB, timeC); + //this->close(); + } + else if (ui.radioButton_byhand->isChecked()) { + g_sys_conf.auto_shift = 0; + g_sys_conf.timing_shift = 0; + g_sys_conf.shift_byhand = 1; - timeA.setHMS(ui.A_hour->minimum(), ui.A_minute->minimum(), 0); - timeB.setHMS(ui.B_hour->minimum(), ui.B_minute->minimum(), 0); - timeC.setHMS(ui.C_hour->minimum(), ui.C_minute->minimum(), 0); + timeA.setHMS(ui.A_hour->minimum(), ui.A_minute->minimum(), 0); + timeB.setHMS(ui.B_hour->minimum(), ui.B_minute->minimum(), 0); + timeC.setHMS(ui.C_hour->minimum(), ui.C_minute->minimum(), 0); - } - emit sendMsgToDialogSetup(timeA, timeB, timeC); - this->close(); - DialogSetup::write_config(); + } + emit sendMsgToDialogSetup(timeA, timeB, timeC); + this->close(); + DialogSetup::write_config(); } void change_shift::recMsgFromDialogSetup(QTime timeA, QTime timeB, QTime timeC) { - ui.A_hour->setValue(timeA.hour()); - ui.A_minute->setValue(timeA.minute()); + ui.A_hour->setValue(timeA.hour()); + ui.A_minute->setValue(timeA.minute()); - ui.B_hour->setValue(timeB.hour()); - ui.B_minute->setValue(timeB.minute()); + ui.B_hour->setValue(timeB.hour()); + ui.B_minute->setValue(timeB.minute()); - ui.C_hour->setValue(timeC.hour()); - ui.C_minute->setValue(timeC.minute()); + ui.C_hour->setValue(timeC.hour()); + ui.C_minute->setValue(timeC.minute()); - this->show(); -} \ No newline at end of file + this->show(); +} diff --git a/Cigarette/change_shift.h b/Cigarette/change_shift.h index 00c64515..0bfe8fa0 100644 --- a/Cigarette/change_shift.h +++ b/Cigarette/change_shift.h @@ -6,22 +6,22 @@ class change_shift : public QDialog { - Q_OBJECT + Q_OBJECT public: - change_shift(QDialog *parent = Q_NULLPTR); - ~change_shift(); + change_shift(QDialog* parent = Q_NULLPTR); + ~change_shift(); private: - Ui::change_shift ui; + Ui::change_shift ui; private slots: - void on_pushButton_apply_released(); + void on_pushButton_apply_released(); public slots: - void recMsgFromDialogSetup(QTime timeA, QTime timeB, QTime timeC); + void recMsgFromDialogSetup(QTime timeA, QTime timeB, QTime timeC); signals: - void sendMsgToDialogSetup(QTime timeA, QTime timeB, QTime timeC); + void sendMsgToDialogSetup(QTime timeA, QTime timeB, QTime timeC); }; diff --git a/Cigarette/cigarette.cpp b/Cigarette/cigarette.cpp index 04fd395d..8968b2ad 100644 --- a/Cigarette/cigarette.cpp +++ b/Cigarette/cigarette.cpp @@ -1,4 +1,4 @@ -#include "cigarette.h" +锘#include "cigarette.h" #include #include #include @@ -9,58 +9,58 @@ #include "exportData.h" #include -int g_op_time; //操作员权限时长(默认300秒) -int g_admin_time; //管理员操作权限时长(默认300秒) +int g_op_time; //鎿嶄綔鍛樻潈闄愭椂闀匡紙榛樿300绉掞級 +int g_admin_time; //绠$悊鍛樻搷浣滄潈闄愭椂闀匡紙榛樿300绉掞級 -int rotationAngle[NumberOfSupportedCameras]; //图片旋转角度 +int rotationAngle[NumberOfSupportedCameras]; //鍥剧墖鏃嬭浆瑙掑害 bool isNeedRotate[NumberOfSupportedCameras]; DisplayLabelConf g_display_label_conf[NumberOfSupportedCameras]; ConfPath g_conf_path; -SysConf g_sys_conf; //系统配置参数 -ModbusConf g_modbus_conf; //modbus地址参数 +SysConf g_sys_conf; //绯荤粺閰嶇疆鍙傛暟 +ModbusConf g_modbus_conf; //modbus鍦板潃鍙傛暟 PLCDevice* m_PLCDevice; -bool g_plc_dialog_open; //是否打开plc配置对话框 +bool g_plc_dialog_open; //鏄惁鎵撳紑plc閰嶇疆瀵硅瘽妗 QDateTime g_ts_start; extern SingleCamInfoStruct SingleCamInfo[NumberOfSupportedCameras]; -AlgJd alg_jd[NumberOfSupportedCameras]; //检测胶点的AI算法 +AlgJd alg_jd[NumberOfSupportedCameras]; //妫娴嬭兌鐐圭殑AI绠楁硶 #ifdef __DEBUG -AlgJd alg_test;//test AI算法 +AlgJd alg_test;//test AI绠楁硶 #endif QThread* pThread[NumberOfSupportedCameras]; int work_camera_nums; -//巴鲁夫相机相关 +//宸撮瞾澶浉鏈虹浉鍏 CaptureThread* pCaptureThread[NumberOfSupportedCameras]; FunctionInterface* pFI[NumberOfSupportedCameras]; mvIMPACT::acquire::GenICam::AcquisitionControl* pAC[NumberOfSupportedCameras]; -//巴斯勒相机相关 +//宸存柉鍕掔浉鏈虹浉鍏 CaptureThreadBasler* pBaslerCaptureThread[NumberOfSupportedCameras]; Pylon::CBaslerUniversalInstantCamera* BaslerCamHandle[NumberOfSupportedCameras]; -//海康相机相关 -void *HIKCamHandle[NumberOfSupportedCameras]; +//娴峰悍鐩告満鐩稿叧 +void* HIKCamHandle[NumberOfSupportedCameras]; CaptureThreadHIK* pHIKCaptureThread[NumberOfSupportedCameras]; -SyncQueue> *g_save_queue; //图片保存队列 +SyncQueue>* g_save_queue; //鍥剧墖淇濆瓨闃熷垪 #ifdef SYNC_CAMERA ImageSyncArr g_image_sync_arr; -SyncQueue>> *g_image_sync_queue; //int表示一个目标拍了几张 +SyncQueue>>* g_image_sync_queue; //int琛ㄧず涓涓洰鏍囨媿浜嗗嚑寮 #else -SyncQueue > *g_image_queue[NumberOfSupportedCameras]; //int表示一个目标拍了几张 +SyncQueue >* g_image_queue[NumberOfSupportedCameras]; //int琛ㄧず涓涓洰鏍囨媿浜嗗嚑寮 #endif -ASyncQueue *g_shooted_queue[NumberOfSupportedCameras]; // -ASyncQueue *g_result_wait_queue[NumberOfSupportedCameras]; // -ASyncQueue *g_double_queue[NumberOfSupportedCameras]; // -ASyncQueue *g_result_queue[NumberOfSupportedCameras]; // -bool g_debug_mode; //相机调试模式,工作模式必须暂停状态才能打开 -SyncQueue *g_debug_queue[NumberOfSupportedCameras]; //相机调试模式图像队列 +ASyncQueue* g_shooted_queue[NumberOfSupportedCameras]; // +ASyncQueue* g_result_wait_queue[NumberOfSupportedCameras]; // +ASyncQueue* g_double_queue[NumberOfSupportedCameras]; // +ASyncQueue* g_result_queue[NumberOfSupportedCameras]; // +bool g_debug_mode; //鐩告満璋冭瘯妯″紡锛屽伐浣滄ā寮忓繀椤绘殏鍋滅姸鎬佹墠鑳芥墦寮 +SyncQueue* g_debug_queue[NumberOfSupportedCameras]; //鐩告満璋冭瘯妯″紡鍥惧儚闃熷垪 #ifdef __UDPSend SyncQueue<_UDPSendInfo>* UDP_Info_queue; @@ -74,19 +74,19 @@ SyncQueue<_XMLExportDataInfo>* export_XMLData_Info_queue; ExportDataThread exportDataThread; #endif -bool g_admin_mode; //是否管理员模式 -QString g_admin_pswd; //管理员密码 -bool g_op_mode; //是否操作员模式 -QString g_op_pswd; //操作员密码 -bool g_working; //true 开始工作状态; false 停止工作状态 -int last_shift; //记录上一次班 +bool g_admin_mode; //鏄惁绠$悊鍛樻ā寮 +QString g_admin_pswd; //绠$悊鍛樺瘑鐮 +bool g_op_mode; //鏄惁鎿嶄綔鍛樻ā寮 +QString g_op_pswd; //鎿嶄綔鍛樺瘑鐮 +bool g_working; //true 寮濮嬪伐浣滅姸鎬侊紱 false 鍋滄宸ヤ綔鐘舵 +int last_shift; //璁板綍涓婁竴娆$彮 QStringList g_alarm_msg; std::vector g_vec_alarm; int g_last_alarm_code; -int g_lst_quantiy; //上一秒的产量 -int quantity_stop_count; //产量不变的秒数 +int g_lst_quantiy; //涓婁竴绉掔殑浜ч噺 +int quantity_stop_count; //浜ч噺涓嶅彉鐨勭鏁 int g_seconds; int CurOpLabel; bool onrestart = false; @@ -94,724 +94,726 @@ bool onrestart = false; VOID BeforeWork(int shoot[]) { #ifdef AI_WARM_UP - for (int j = 0;j < 10; j++) - { - for (int i = 0; i < NumberOfSupportedCameras; i++) - { - if (SingleCamInfo[i].Detect && SingleCamInfo[i].IsOpen) { - alg_jd[i].test_detect_batcht(shoot[i]); - } - } - } + for (int j = 0; j < 10; j++) + { + for (int i = 0; i < NumberOfSupportedCameras; i++) + { + if (SingleCamInfo[i].Detect && SingleCamInfo[i].IsOpen) { + alg_jd[i].test_detect_batcht(shoot[i]); + } + } + } #endif } -Cigarette::Cigarette(QWidget *parent) - : QMainWindow(parent) +Cigarette::Cigarette(QWidget* parent) + : QMainWindow(parent) { - ui.setupUi(this); - InitPtrMat(); - read_conf(g_conf_path); - - if (!g_conf_path.config_path.isEmpty()) { - // 如果非空 - QDir* dirinfo = new QDir(g_conf_path.config_path); - if (!dirinfo->exists()) { - // 如果文件夹信息不存在 - delete dirinfo, dirinfo = nullptr; - g_conf_path.config_path = "D:/conf"; - } - delete dirinfo, dirinfo = nullptr; - } - else - g_conf_path.config_path = "D:/conf"; - - bool update_rotate = false; - if (!read_rotate_message()) { - update_rotate = true; - } - - QThread* hThread = new QThread(); - CLog* clogWorkThread = new CLog(); - clogWorkThread->moveToThread(hThread); - connect(this, &Cigarette::destroyed, hThread, &QThread::quit); - connect(hThread, &QThread::finished, clogWorkThread, &CLog::deleteLater); - connect(this, &Cigarette::sengMsgToClog, clogWorkThread, &CLog::recMegFromCigarette); - hThread->start(); - - emit sengMsgToClog("Application Start."); - - g_save_queue = new SyncQueue>(Queue_Size); - g_save_queue->name = "save queue"; + ui.setupUi(this); + InitPtrMat(); + read_conf(g_conf_path); + + if (!g_conf_path.config_path.isEmpty()) { + // 濡傛灉闈炵┖ + QDir* dirinfo = new QDir(g_conf_path.config_path); + if (!dirinfo->exists()) { + // 濡傛灉鏂囦欢澶逛俊鎭笉瀛樺湪 + delete dirinfo, dirinfo = nullptr; + g_conf_path.config_path = "D:/conf"; + } + delete dirinfo, dirinfo = nullptr; + } + else + g_conf_path.config_path = "D:/conf"; + + bool update_rotate = false; + if (!read_rotate_message()) { + update_rotate = true; + } + + QThread* hThread = new QThread(); + CLog* clogWorkThread = new CLog(); + clogWorkThread->moveToThread(hThread); + connect(this, &Cigarette::destroyed, hThread, &QThread::quit); + connect(hThread, &QThread::finished, clogWorkThread, &CLog::deleteLater); + connect(this, &Cigarette::sengMsgToClog, clogWorkThread, &CLog::recMegFromCigarette); + hThread->start(); + + emit sengMsgToClog("Application Start."); + + g_save_queue = new SyncQueue>(Queue_Size); + g_save_queue->name = "save queue"; #ifdef __UDPSend - UDP_Info_queue = new SyncQueue<_UDPSendInfo>(Queue_Size); - UDP_Info_queue->name = "UDP Info queue"; + UDP_Info_queue = new SyncQueue<_UDPSendInfo>(Queue_Size); + UDP_Info_queue->name = "UDP Info queue"; #endif #ifdef __TCPSend - TCP_Info_queue = new SyncQueue<_TCPSendInfo>(Queue_Size); - TCP_Info_queue->name = "TCP Info queue"; + TCP_Info_queue = new SyncQueue<_TCPSendInfo>(Queue_Size); + TCP_Info_queue->name = "TCP Info queue"; #endif #ifdef __ExportData - export_XMLData_Info_queue = new SyncQueue<_XMLExportDataInfo>(Queue_Size); - export_XMLData_Info_queue->name = "Export Data Info queue"; + export_XMLData_Info_queue = new SyncQueue<_XMLExportDataInfo>(Queue_Size); + export_XMLData_Info_queue->name = "Export Data Info queue"; #endif - last_shift = 256; - work_camera_nums = 0; - + last_shift = 256; + work_camera_nums = 0; + #ifdef SYNC_CAMERA - g_image_sync_queue = new SyncQueue>>(Queue_Size); - g_image_sync_queue->name = format("sync_image"); + g_image_sync_queue = new SyncQueue>>(Queue_Size); + g_image_sync_queue->name = format("sync_image"); #endif - for(int i=0;i >(Queue_Size); - g_image_queue[i]->name = format("image_%d", i); -#endif - g_result_queue[i] = new ASyncQueue(Queue_Size); - g_result_queue[i]->name = format("result_%d", i); - g_result_wait_queue[i] = new ASyncQueue(Queue_Size); - g_result_wait_queue[i]->name = format("result_wait%d", i); - g_double_queue[i] = new ASyncQueue(Queue_Size); - g_double_queue[i]->name = format("double_wait%d", i); - g_shooted_queue[i] = new ASyncQueue(Queue_Size); - g_shooted_queue[i]->name = format("shooted_%d", i); - g_debug_queue[i] = new SyncQueue(Queue_Size); - g_debug_queue[i]->name = format("debug_%d", i); - if (update_rotate) { - rotationAngle[i] = cv::ROTATE_90_COUNTERCLOCKWISE + 1; - isNeedRotate[i] = false; - } - } - if (update_rotate) { - if (save_rotate_message()) { - printf("\nFail to write message to file.");; - } - } - - g_admin_mode = false; - g_admin_time = ADMIN_TIME; - g_admin_pswd = read_pswd(); - g_op_mode = false; - g_op_time = OP_TIME; - g_op_pswd = read_op_pswd(); - - g_working = false; - g_debug_mode = false; - - g_alarm_msg << QStringLiteral("无报警") /// 0 - << QStringLiteral("1#相机丢结果") /// 1 - << QStringLiteral("2#相机丢结果") /// 2 - << QStringLiteral("1#相机有剔除") /// 3 - << QStringLiteral("2#相机有剔除") /// 4 - << QStringLiteral("1#相机通讯故障") /// 5 - << QStringLiteral("2#相机通讯故障") /// 6 - << QStringLiteral("3#相机通讯故障") /// 7 - << QStringLiteral("4#相机通讯故障") /// 8 - << QStringLiteral("5#相机通讯故障") /// 9 - << QStringLiteral("6#相机通讯故障") /// 10 - << QStringLiteral("7#相机通讯故障") /// 11 - << QStringLiteral("8#相机通讯故障"); /// 12 - - g_last_alarm_code = 0; - - g_ts_start = QDateTime::currentDateTime(); - - for(int i=0;idisplay(production_number[i]); - ok[i] = 0; - ng[i] = 0; - g_display_label_conf[i].g_last_mat[0] = cv::Mat::zeros(20, 20, CV_8UC3); - g_display_label_conf[i].g_last_mat[1] = cv::Mat::zeros(20, 20, CV_8UC3); + g_image_queue[i] = new SyncQueue >(Queue_Size); + g_image_queue[i]->name = format("image_%d", i); +#endif + g_result_queue[i] = new ASyncQueue(Queue_Size); + g_result_queue[i]->name = format("result_%d", i); + g_result_wait_queue[i] = new ASyncQueue(Queue_Size); + g_result_wait_queue[i]->name = format("result_wait%d", i); + g_double_queue[i] = new ASyncQueue(Queue_Size); + g_double_queue[i]->name = format("double_wait%d", i); + g_shooted_queue[i] = new ASyncQueue(Queue_Size); + g_shooted_queue[i]->name = format("shooted_%d", i); + g_debug_queue[i] = new SyncQueue(Queue_Size); + g_debug_queue[i]->name = format("debug_%d", i); + if (update_rotate) { + rotationAngle[i] = cv::ROTATE_90_COUNTERCLOCKWISE + 1; + isNeedRotate[i] = false; + } + } + if (update_rotate) { + if (save_rotate_message()) { + printf("\nFail to write message to file.");; + } + } + + g_admin_mode = false; + g_admin_time = ADMIN_TIME; + g_admin_pswd = read_pswd(); + g_op_mode = false; + g_op_time = OP_TIME; + g_op_pswd = read_op_pswd(); + + g_working = false; + g_debug_mode = false; + + g_alarm_msg << QStringLiteral("鏃犳姤璀") /// 0 + << QStringLiteral("1#鐩告満涓㈢粨鏋") /// 1 + << QStringLiteral("2#鐩告満涓㈢粨鏋") /// 2 + << QStringLiteral("1#鐩告満鏈夊墧闄") /// 3 + << QStringLiteral("2#鐩告満鏈夊墧闄") /// 4 + << QStringLiteral("1#鐩告満閫氳鏁呴殰") /// 5 + << QStringLiteral("2#鐩告満閫氳鏁呴殰") /// 6 + << QStringLiteral("3#鐩告満閫氳鏁呴殰") /// 7 + << QStringLiteral("4#鐩告満閫氳鏁呴殰") /// 8 + << QStringLiteral("5#鐩告満閫氳鏁呴殰") /// 9 + << QStringLiteral("6#鐩告満閫氳鏁呴殰") /// 10 + << QStringLiteral("7#鐩告満閫氳鏁呴殰") /// 11 + << QStringLiteral("8#鐩告満閫氳鏁呴殰"); /// 12 + + g_last_alarm_code = 0; + + g_ts_start = QDateTime::currentDateTime(); + + for (int i = 0; i < NumberOfSupportedCameras; i++) + { + g_display_label_conf[i].g_max[0] = false; + g_display_label_conf[i].g_max[1] = false; + OpenWithUserID[i] = 0xff; + production_number[i] = 0; + lcdNumber_total_mat[i]->display(production_number[i]); + ok[i] = 0; + ng[i] = 0; + g_display_label_conf[i].g_last_mat[0] = cv::Mat::zeros(20, 20, CV_8UC3); + g_display_label_conf[i].g_last_mat[1] = cv::Mat::zeros(20, 20, CV_8UC3); #ifdef DRAW_RECT - DrawRect_init(i); + DrawRect_init(i); #endif - } - ui.lcdNumber_total_no->display(0); - ui.lcdNumber_total_no_last->display(0); + } + ui.lcdNumber_total_no->display(0); + ui.lcdNumber_total_no_last->display(0); - g_plc_dialog_open = false; + g_plc_dialog_open = false; - g_lst_quantiy = 0; - quantity_stop_count = 0; - g_seconds = 0; + g_lst_quantiy = 0; + quantity_stop_count = 0; + g_seconds = 0; - QString config_path = g_conf_path.config_path + "/conf.txt"; - read_sys_config(g_sys_conf, config_path); //初始化系统配置 + QString config_path = g_conf_path.config_path + "/conf.txt"; + read_sys_config(g_sys_conf, config_path); //鍒濆鍖栫郴缁熼厤缃 - for (int i = 0; i < NumberOfSupportedCameras; i++) { + for (int i = 0; i < NumberOfSupportedCameras; i++) { #if defined(NumberOfSupportedCameras) && (NumberOfSupportedCameras > i) - g_modbus_conf.kick[i] = 0; -#endif - } - g_modbus_conf.quantity = 0; - g_modbus_conf.shift = 0; - g_modbus_conf.work = 0; - g_modbus_conf.no_kick = 0; - g_modbus_conf.debug = 0; - g_modbus_conf.reset = 0; - g_modbus_conf.alarm = 0; - read_modbus_config(g_modbus_conf); //初始化modbus地址 - - //保存图片线程 - saveThread.init(); + g_modbus_conf.kick[i] = 0; +#endif + } + g_modbus_conf.quantity = 0; + g_modbus_conf.shift = 0; + g_modbus_conf.work = 0; + g_modbus_conf.no_kick = 0; + g_modbus_conf.debug = 0; + g_modbus_conf.reset = 0; + g_modbus_conf.alarm = 0; + read_modbus_config(g_modbus_conf); //鍒濆鍖杕odbus鍦板潃 + + //淇濆瓨鍥剧墖绾跨▼ + saveThread.init(); #ifdef __ExportData - connect(&saveThread, &SaveThread::sendDataToExport, &exportDataThread, &ExportDataThread::GetDataFromSaveThread); + connect(&saveThread, &SaveThread::sendDataToExport, &exportDataThread, &ExportDataThread::GetDataFromSaveThread); #endif - saveThread.start_work(); + saveThread.start_work(); #ifdef __UDPSend - sThread.init(UDP_Info_queue, g_sys_conf.MonitorIP, g_sys_conf.MonitorPort); - sThread.start_work(); + sThread.init(UDP_Info_queue, g_sys_conf.MonitorIP, g_sys_conf.MonitorPort); + sThread.start_work(); - rThread = new threadReceive(); - rThread->init(g_sys_conf.MonitorIP, g_sys_conf.MonitorPort); - connect(rThread, &threadReceive::sendMsgToCigratte, this, &Cigarette::recMsgFromUdp); - rThread->start_work(); + rThread = new threadReceive(); + rThread->init(g_sys_conf.MonitorIP, g_sys_conf.MonitorPort); + connect(rThread, &threadReceive::sendMsgToCigratte, this, &Cigarette::recMsgFromUdp); + rThread->start_work(); #endif #ifdef __TCPSend - std::string serverIp = "192.168.1.120"; - int serverPort = 8888; - tcpSendThread.init(TCP_Info_queue, serverIp, serverPort); - tcpSendThread.start_work(); + std::string serverIp = "192.168.1.120"; + int serverPort = 8888; + tcpSendThread.init(TCP_Info_queue, serverIp, serverPort); + tcpSendThread.start_work(); #endif #ifdef __ExportData - exportDataThread.init(); - connect(this, &Cigarette::sendMsgToExportData, &exportDataThread, &ExportDataThread::EDrecMsgFromCigarette); - exportDataThread.start_work(); -#endif - - m_PLCDevice = new PLCDevice; - PLCDevice::init_plc(m_PLCDevice); - if(m_PLCDevice->g_plc_ok) - { - printf("Connected to dev!\n"); - ui.label_plc->setText(QStringLiteral("PLC正常")); - ui.label_plc->setStyleSheet(tr("background-color: rgb(0, 170, 0);")); - m_PLCDevice->g_plc_status|=(0x01); - uint8_t Data8; - m_PLCDevice->read_bits_from_plc( g_modbus_conf.no_kick, 1 ,&Data8); - ui.checkBox_unkick->setChecked(Data8); + exportDataThread.init(); + connect(this, &Cigarette::sendMsgToExportData, &exportDataThread, &ExportDataThread::EDrecMsgFromCigarette); + exportDataThread.start_work(); +#endif + + m_PLCDevice = new PLCDevice; + PLCDevice::init_plc(m_PLCDevice); + if (m_PLCDevice->g_plc_ok) + { + printf("Connected to dev!\n"); + ui.label_plc->setText(QStringLiteral("PLC姝e父")); + ui.label_plc->setStyleSheet(tr("background-color: rgb(0, 170, 0);")); + m_PLCDevice->g_plc_status |= (0x01); + uint8_t Data8; + m_PLCDevice->read_bits_from_plc(g_modbus_conf.no_kick, 1, &Data8); + ui.checkBox_unkick->setChecked(Data8); #ifdef __UDPSend - if(Data8)sThread.sendData("UnKickOk", g_sys_conf.FeedbackPort); - else sThread.sendData("UnKickFail", g_sys_conf.FeedbackPort); + if (Data8)sThread.sendData("UnKickOk", g_sys_conf.FeedbackPort); + else sThread.sendData("UnKickFail", g_sys_conf.FeedbackPort); #endif - //初始化PLC的寄存器值 - read_plc_items(); - init_plc_value(); - } - else - { - printf("\nSorry,fail to connect ttyS0,please check your device's state.\n"); - ui.label_plc->setText(QStringLiteral("PLC断开")); - ui.label_plc->setStyleSheet(tr("background-color: rgb(255, 255, 0);")); - m_PLCDevice->g_plc_status&=~(0x01); - } - std::cout << " Enumerate Cameras..."<< std::endl; + //鍒濆鍖朠LC鐨勫瘎瀛樺櫒鍊 + read_plc_items(); + init_plc_value(); + } + else + { + printf("\nSorry,fail to connect ttyS0,please check your device's state.\n"); + ui.label_plc->setText(QStringLiteral("PLC鏂紑")); + ui.label_plc->setStyleSheet(tr("background-color: rgb(255, 255, 0);")); + m_PLCDevice->g_plc_status &= ~(0x01); + } + std::cout << " Enumerate Cameras..." << std::endl; - EnumerateCameras((SingleCamInfoStruct*)&SingleCamInfo, true, g_sys_conf); + EnumerateCameras((SingleCamInfoStruct*)&SingleCamInfo, true, g_sys_conf); - // 剔除值清0 - int ret = m_PLCDevice->write_bit_2_plc(g_modbus_conf.shift, 1);//给PLC发送换班消息 + // 鍓旈櫎鍊兼竻0 + int ret = m_PLCDevice->write_bit_2_plc(g_modbus_conf.shift, 1);//缁橮LC鍙戦佹崲鐝秷鎭 #ifdef SYNC_CAMERA - CreatWorkThread(0, 0, this); -#endif - - //创建相机工作线程 - for (int i = 0; i < NumberOfSupportedCameras; i++) - { - if(SingleCamInfo[i].Detect){ - work_camera_nums++; - cam_status_mat[i]->setStyleSheet(tr("background-color: rgb(0, 170, 0);")); - QString model_path, model_name; - if (g_sys_conf.model_path.isEmpty()) { - model_path = "D:/model"; - g_sys_conf.model_path = "D:/model"; - } - else - model_path = g_sys_conf.model_path; - - if (g_sys_conf.model_name.isEmpty()) { - model_name = "jd.weights"; - g_sys_conf.model_name = "jd.weights"; - } - else - model_name = g_sys_conf.model_name; - - if (!alg_jd[i].init(model_path, model_name)) - { - QMessageBox::information(NULL, QStringLiteral("系统自检失败"), QStringLiteral("AI模型1初始化失败,请检查程序完整性"), QMessageBox::Ok); - exit(-1); - } + CreatWorkThread(0, 0, this); +#endif + + //鍒涘缓鐩告満宸ヤ綔绾跨▼ + for (int i = 0; i < NumberOfSupportedCameras; i++) + { + if (SingleCamInfo[i].Detect) { + work_camera_nums++; + cam_status_mat[i]->setStyleSheet(tr("background-color: rgb(0, 170, 0);")); + QString model_path, model_name; + if (g_sys_conf.model_path.isEmpty()) { + model_path = "D:/model"; + g_sys_conf.model_path = "D:/model"; + } + else + model_path = g_sys_conf.model_path; + + if (g_sys_conf.model_name.isEmpty()) { + model_name = "jd.weights"; + g_sys_conf.model_name = "jd.weights"; + } + else + model_name = g_sys_conf.model_name; + + if (!alg_jd[i].init(model_path, model_name)) + { + QMessageBox::information(NULL, QStringLiteral("绯荤粺鑷澶辫触"), QStringLiteral("AI妯″瀷1鍒濆鍖栧け璐ワ紝璇锋鏌ョ▼搴忓畬鏁存"), QMessageBox::Ok); + exit(-1); + } #ifdef SYNC_CAMERA - debug_thread[i].init(g_debug_queue[i],i); - connect(&debug_thread[i], SIGNAL(notify(int,int,cv::Mat)), this, SLOT(OnNotifyHub(int,int,cv::Mat))); - debug_thread[i].start_work(); + debug_thread[i].init(g_debug_queue[i], i); + connect(&debug_thread[i], SIGNAL(notify(int, int, cv::Mat)), this, SLOT(OnNotifyHub(int, int, cv::Mat))); + debug_thread[i].start_work(); #else - CreatWorkThread(SingleCamInfo[i].CamClass, i, this); -#endif - } - else { - QDateTime ts_start = QDateTime::currentDateTime(); - QTime time = QTime::currentTime(); - QDateTime local(ts_start); - QString localTime = local.toString("yyyy-MM-dd hh:mm:ss"); - - if (g_modbus_conf.alarm > 0) - { - uint16_t dest16[2] = { 5+i,0 }; - int ret = m_PLCDevice->write_short_2_plc(g_modbus_conf.alarm, 2, dest16); - //if (ret > 0) SingleCamInfo[0].OffLine = false; - - if (ret > 0) - { - AlarmInfo alarm_info; - alarm_info.alarm_code = dest16[0]; - if ((alarm_info.alarm_code > 0) && (alarm_info.alarm_code <= 12)) - { - alarm_info.alarm_msg = (g_alarm_msg[alarm_info.alarm_code]).toStdString(); - alarm_info.alarm_start = localTime.toStdString(); - ui.label_alarm->setText(g_alarm_msg[alarm_info.alarm_code]); - ui.label_alarm->setStyleSheet(tr("background-color: rgb(255, 0, 0);")); - if (g_last_alarm_code != alarm_info.alarm_code) - { - g_vec_alarm.push_back(alarm_info); - g_last_alarm_code = alarm_info.alarm_code; - } - } - else if (alarm_info.alarm_code == 0) { - ui.label_alarm->setStyleSheet(tr("background-color: rgb(0, 170, 0);")); - ui.label_alarm->setText(QStringLiteral("无报警")); - } + CreatWorkThread(SingleCamInfo[i].CamClass, i, this); +#endif + } + else { + QDateTime ts_start = QDateTime::currentDateTime(); + QTime time = QTime::currentTime(); + QDateTime local(ts_start); + QString localTime = local.toString("yyyy-MM-dd hh:mm:ss"); + + if (g_modbus_conf.alarm > 0) + { + uint16_t dest16[2] = { 5 + i,0 }; + int ret = m_PLCDevice->write_short_2_plc(g_modbus_conf.alarm, 2, dest16); + //if (ret > 0) SingleCamInfo[0].OffLine = false; + + if (ret > 0) + { + AlarmInfo alarm_info; + alarm_info.alarm_code = dest16[0]; + if ((alarm_info.alarm_code > 0) && (alarm_info.alarm_code <= 12)) + { + alarm_info.alarm_msg = (g_alarm_msg[alarm_info.alarm_code]).toStdString(); + alarm_info.alarm_start = localTime.toStdString(); + ui.label_alarm->setText(g_alarm_msg[alarm_info.alarm_code]); + ui.label_alarm->setStyleSheet(tr("background-color: rgb(255, 0, 0);")); + if (g_last_alarm_code != alarm_info.alarm_code) + { + g_vec_alarm.push_back(alarm_info); + g_last_alarm_code = alarm_info.alarm_code; + } + } + else if (alarm_info.alarm_code == 0) { + ui.label_alarm->setStyleSheet(tr("background-color: rgb(0, 170, 0);")); + ui.label_alarm->setText(QStringLiteral("鏃犳姤璀")); + } #ifdef __UDPSend - QString str; - str = QString("alarm") + '_' + QString::number(alarm_info.alarm_code); - sThread.sendData(str, g_sys_conf.FeedbackPort); + QString str; + str = QString("alarm") + '_' + QString::number(alarm_info.alarm_code); + sThread.sendData(str, g_sys_conf.FeedbackPort); #endif - } - } - } + } + } + } + + } - } - #ifdef __DEBUG - alg_test.init(g_sys_conf.model_path, g_sys_conf.model_name);//test AI算法 -#endif - - //自动打开所有相机 - if (g_sys_conf.auto_open == 1) - { - for (int i = 0; i < NumberOfSupportedCameras; i++) - { - if(SingleCamInfo[i].Detect){ - if(ControlCamOpenOrClose(i,OPEN)) - { - cam_work_mat[i]->setStyleSheet(tr("background-color: rgb(0, 170, 0);")); - QString str = QString("border-image: url(:/Cigarette/Resources/cam%1_yes.png);").arg(i+1); - QByteArray ba = str.toLatin1(); - cam_toolButton_mat[i]->setStyleSheet(tr(ba.data())); - } - } - } - } + alg_test.init(g_sys_conf.model_path, g_sys_conf.model_name);//test AI绠楁硶 +#endif + + //鑷姩鎵撳紑鎵鏈夌浉鏈 + if (g_sys_conf.auto_open == 1) + { + for (int i = 0; i < NumberOfSupportedCameras; i++) + { + if (SingleCamInfo[i].Detect) { + if (ControlCamOpenOrClose(i, OPEN)) + { + cam_work_mat[i]->setStyleSheet(tr("background-color: rgb(0, 170, 0);")); + QString str = QString("border-image: url(:/Cigarette/Resources/cam%1_yes.png);").arg(i + 1); + QByteArray ba = str.toLatin1(); + cam_toolButton_mat[i]->setStyleSheet(tr(ba.data())); + } + } + } + } #ifdef __UDPSend - sThread.sendData("ReStartOk", g_sys_conf.FeedbackPort); - sThread.sendData("DebugDis", g_sys_conf.FeedbackPort); - sThread.sendData("LockOk", g_sys_conf.FeedbackPort); + sThread.sendData("ReStartOk", g_sys_conf.FeedbackPort); + sThread.sendData("DebugDis", g_sys_conf.FeedbackPort); + sThread.sendData("LockOk", g_sys_conf.FeedbackPort); #endif - DisableDebugMode(); + DisableDebugMode(); - m_pTimer = new QTimer(this); - connect(m_pTimer, SIGNAL(timeout()), this, SLOT(handleTimeout())); - m_pTimer->start(1000); + m_pTimer = new QTimer(this); + connect(m_pTimer, SIGNAL(timeout()), this, SLOT(handleTimeout())); + m_pTimer->start(1000); - m_delay = new QTimer(this);//换班防连击 - connect(m_delay, SIGNAL(timeout()), this, SLOT(enable_shift())); + m_delay = new QTimer(this);//鎹㈢彮闃茶繛鍑 + connect(m_delay, SIGNAL(timeout()), this, SLOT(enable_shift())); #ifdef __UDPSend - m_sendMsg_delay = new QTimer(this); - connect(m_sendMsg_delay, SIGNAL(timeout()), this, SLOT(sendLatestData())); -#endif - - m_op_delay = new QTimer(this); - connect(m_op_delay, SIGNAL(timeout()), this, SLOT(op_timeout())); - - m_admin_delay = new QTimer(this); - connect(m_admin_delay, SIGNAL(timeout()), this, SLOT(admin_timeout())); - - clean_pTimer = new QTimer(this); - connect(clean_pTimer,SIGNAL(timeout()), this, SLOT(CleanThreadStartAuto())); - clean_pTimer->start(3600000); - - connect(ui.label_alarm, SIGNAL(QlabelDoubleClick()), this, SLOT(OnCancelAlarm()));//报警标签双击消警 - - image_lable_DBsignalMapper0 = new QSignalMapper(this); - image_lable_DBsignalMapper1 = new QSignalMapper(this); - image_lable_TPsignalMapper0 = new QSignalMapper(this); - image_lable_TPsignalMapper1 = new QSignalMapper(this); - label_ng_signalMapper = new QSignalMapper(this); - pTimer_Cam_signalMapper = new QSignalMapper(this); - toolButton_cam_signalMapper = new QSignalMapper(this); - RotateReleased_signalMapper = new QSignalMapper(this); - for (int i = 0; i < NumberOfSupportedCameras; i++) - { - m_pTimer_Cam_mat[i] = new QTimer(this); - connect(m_pTimer_Cam_mat[i], SIGNAL(timeout()), pTimer_Cam_signalMapper, SLOT(map())); - pTimer_Cam_signalMapper->setMapping(m_pTimer_Cam_mat[i], i); - - connect(display_lable_mat[i][0], SIGNAL(QlabelDoubleClick()), image_lable_DBsignalMapper0, SLOT(map())); - image_lable_DBsignalMapper0->setMapping(display_lable_mat[i][0], i << 4 | 0); - - connect(display_lable_mat[i][1], SIGNAL(QlabelDoubleClick()), image_lable_DBsignalMapper1, SLOT(map())); - image_lable_DBsignalMapper1->setMapping(display_lable_mat[i][1], i << 4 | 1); - - connect(display_lable_mat[i][0], SIGNAL(QlabelTripleClick()), image_lable_TPsignalMapper0, SLOT(map())); - image_lable_TPsignalMapper0->setMapping(display_lable_mat[i][0], i << 4 | 0); - - connect(display_lable_mat[i][1], SIGNAL(QlabelTripleClick()), image_lable_TPsignalMapper1, SLOT(map())); - image_lable_TPsignalMapper1->setMapping(display_lable_mat[i][1], i << 4 | 1); - - connect(label_ng_mat[i], SIGNAL(QlabelDoubleClick()), label_ng_signalMapper, SLOT(map())); - label_ng_signalMapper->setMapping(label_ng_mat[i], i); - - connect(cam_toolButton_mat[i], SIGNAL(released()), toolButton_cam_signalMapper, SLOT(map())); - toolButton_cam_signalMapper->setMapping(cam_toolButton_mat[i], i); - - connect(rotate_mat[i], SIGNAL(released()), RotateReleased_signalMapper, SLOT(map())); - RotateReleased_signalMapper->setMapping(rotate_mat[i], i); - - } - connect(toolButton_cam_signalMapper, SIGNAL(mapped(int)), this, SLOT(OnToolButtonCamReleasedHub(int))); - //connect(pTimer_Cam_signalMapper, SIGNAL(mapped(int)), this, SLOT(OpenCamTimeoutHub(int))); - connect(image_lable_DBsignalMapper0, SIGNAL(mapped(int)), this, SLOT(OnDBClickHub(int))); - connect(image_lable_DBsignalMapper1, SIGNAL(mapped(int)), this, SLOT(OnDBClickHub(int))); + m_sendMsg_delay = new QTimer(this); + connect(m_sendMsg_delay, SIGNAL(timeout()), this, SLOT(sendLatestData())); +#endif + + m_op_delay = new QTimer(this); + connect(m_op_delay, SIGNAL(timeout()), this, SLOT(op_timeout())); + + m_admin_delay = new QTimer(this); + connect(m_admin_delay, SIGNAL(timeout()), this, SLOT(admin_timeout())); + + clean_pTimer = new QTimer(this); + connect(clean_pTimer, SIGNAL(timeout()), this, SLOT(CleanThreadStartAuto())); + clean_pTimer->start(3600000); + + connect(ui.label_alarm, SIGNAL(QlabelDoubleClick()), this, SLOT(OnCancelAlarm()));//鎶ヨ鏍囩鍙屽嚮娑堣 + + image_lable_DBsignalMapper0 = new QSignalMapper(this); + image_lable_DBsignalMapper1 = new QSignalMapper(this); + image_lable_TPsignalMapper0 = new QSignalMapper(this); + image_lable_TPsignalMapper1 = new QSignalMapper(this); + label_ng_signalMapper = new QSignalMapper(this); + pTimer_Cam_signalMapper = new QSignalMapper(this); + toolButton_cam_signalMapper = new QSignalMapper(this); + RotateReleased_signalMapper = new QSignalMapper(this); + for (int i = 0; i < NumberOfSupportedCameras; i++) + { + m_pTimer_Cam_mat[i] = new QTimer(this); + connect(m_pTimer_Cam_mat[i], SIGNAL(timeout()), pTimer_Cam_signalMapper, SLOT(map())); + pTimer_Cam_signalMapper->setMapping(m_pTimer_Cam_mat[i], i); + + connect(display_lable_mat[i][0], SIGNAL(QlabelDoubleClick()), image_lable_DBsignalMapper0, SLOT(map())); + image_lable_DBsignalMapper0->setMapping(display_lable_mat[i][0], i << 4 | 0); + + connect(display_lable_mat[i][1], SIGNAL(QlabelDoubleClick()), image_lable_DBsignalMapper1, SLOT(map())); + image_lable_DBsignalMapper1->setMapping(display_lable_mat[i][1], i << 4 | 1); + + connect(display_lable_mat[i][0], SIGNAL(QlabelTripleClick()), image_lable_TPsignalMapper0, SLOT(map())); + image_lable_TPsignalMapper0->setMapping(display_lable_mat[i][0], i << 4 | 0); + + connect(display_lable_mat[i][1], SIGNAL(QlabelTripleClick()), image_lable_TPsignalMapper1, SLOT(map())); + image_lable_TPsignalMapper1->setMapping(display_lable_mat[i][1], i << 4 | 1); + + connect(label_ng_mat[i], SIGNAL(QlabelDoubleClick()), label_ng_signalMapper, SLOT(map())); + label_ng_signalMapper->setMapping(label_ng_mat[i], i); + + connect(cam_toolButton_mat[i], SIGNAL(released()), toolButton_cam_signalMapper, SLOT(map())); + toolButton_cam_signalMapper->setMapping(cam_toolButton_mat[i], i); + + connect(rotate_mat[i], SIGNAL(released()), RotateReleased_signalMapper, SLOT(map())); + RotateReleased_signalMapper->setMapping(rotate_mat[i], i); + + } + connect(toolButton_cam_signalMapper, SIGNAL(mapped(int)), this, SLOT(OnToolButtonCamReleasedHub(int))); + //connect(pTimer_Cam_signalMapper, SIGNAL(mapped(int)), this, SLOT(OpenCamTimeoutHub(int))); + connect(image_lable_DBsignalMapper0, SIGNAL(mapped(int)), this, SLOT(OnDBClickHub(int))); + connect(image_lable_DBsignalMapper1, SIGNAL(mapped(int)), this, SLOT(OnDBClickHub(int))); #ifdef DRAW_RECT - connect(image_lable_TPsignalMapper0, SIGNAL(mapped(int)), this, SLOT(OnTPClickHub(int))); - connect(image_lable_TPsignalMapper1, SIGNAL(mapped(int)), this, SLOT(OnTPClickHub(int))); -#endif - connect(label_ng_signalMapper, SIGNAL(mapped(int)), this, SLOT(OnDBClickNGHub(int))); - connect(RotateReleased_signalMapper, SIGNAL(mapped(int)), this, SLOT(OnRotateReleasedHub(int))); - - //禁用调试按钮 - ui.checkBox_debug->setEnabled(false); - //隐藏OK/NG按钮 - for (int i = 0; i < NumberOfSupportedCameras; i++) - { - label_reslut_mat[i]->setVisible(false); - } - ui.label_role->setText(QStringLiteral("未登录")); - - //自动开始工作 - if (g_sys_conf.auto_work == 1) - { - for (int i = 0; i < NumberOfSupportedCameras; i++) - { - if(SingleCamInfo[i].Detect && SingleCamInfo[i].IsOpen){ - if(SingleCamInfo[i].CamClass == BalluffClassID){ - if(pCaptureThread[i]) - while(!pCaptureThread[i]->Ready)Sleep(10); - }else if(SingleCamInfo[i].CamClass == BaslerClassID){ - if(pBaslerCaptureThread[i]) - while(!pBaslerCaptureThread[i]->Ready)Sleep(10); - }else if(SingleCamInfo[i].CamClass == HIKClassID){ - if(pHIKCaptureThread[i]) - while(!pHIKCaptureThread[i]->Ready)Sleep(10); - } - } - } - - if (m_PLCDevice->g_plc_ok) { - BeforeWork(g_sys_conf.shoot); - int ret = m_PLCDevice->write_bit_2_plc( g_modbus_conf.work, 1); - ui.label_title->setStyleSheet(tr("background-color: rgb(0, 170, 0);")); -#ifdef __UDPSend - sThread.sendData("Work", g_sys_conf.FeedbackPort); + connect(image_lable_TPsignalMapper0, SIGNAL(mapped(int)), this, SLOT(OnTPClickHub(int))); + connect(image_lable_TPsignalMapper1, SIGNAL(mapped(int)), this, SLOT(OnTPClickHub(int))); #endif - g_working = true; - ui.checkBox_debug->setChecked(false); //锁定调试不可用 - ui.checkBox_debug->setEnabled(false); //锁定调试不可用 - for (int i = 0; i < NumberOfSupportedCameras; i++) - { - //显示OK/NG按钮 - label_reslut_mat[i]->setVisible(true); - } - } - } - //connect(ui.btn_pause, SIGNAL(clicked()), this, SLOT(sendLatestData())); + connect(label_ng_signalMapper, SIGNAL(mapped(int)), this, SLOT(OnDBClickNGHub(int))); + connect(RotateReleased_signalMapper, SIGNAL(mapped(int)), this, SLOT(OnRotateReleasedHub(int))); + + //绂佺敤璋冭瘯鎸夐挳 + ui.checkBox_debug->setEnabled(false); + //闅愯棌OK/NG鎸夐挳 + for (int i = 0; i < NumberOfSupportedCameras; i++) + { + label_reslut_mat[i]->setVisible(false); + } + ui.label_role->setText(QStringLiteral("鏈櫥褰")); + + //鑷姩寮濮嬪伐浣 + if (g_sys_conf.auto_work == 1) + { + for (int i = 0; i < NumberOfSupportedCameras; i++) + { + if (SingleCamInfo[i].Detect && SingleCamInfo[i].IsOpen) { + if (SingleCamInfo[i].CamClass == BalluffClassID) { + if (pCaptureThread[i]) + while (!pCaptureThread[i]->Ready)Sleep(10); + } + else if (SingleCamInfo[i].CamClass == BaslerClassID) { + if (pBaslerCaptureThread[i]) + while (!pBaslerCaptureThread[i]->Ready)Sleep(10); + } + else if (SingleCamInfo[i].CamClass == HIKClassID) { + if (pHIKCaptureThread[i]) + while (!pHIKCaptureThread[i]->Ready)Sleep(10); + } + } + } + + if (m_PLCDevice->g_plc_ok) { + BeforeWork(g_sys_conf.shoot); + int ret = m_PLCDevice->write_bit_2_plc(g_modbus_conf.work, 1); + ui.label_title->setStyleSheet(tr("background-color: rgb(0, 170, 0);")); +#ifdef __UDPSend + sThread.sendData("Work", g_sys_conf.FeedbackPort); +#endif + g_working = true; + ui.checkBox_debug->setChecked(false); //閿佸畾璋冭瘯涓嶅彲鐢 + ui.checkBox_debug->setEnabled(false); //閿佸畾璋冭瘯涓嶅彲鐢 + for (int i = 0; i < NumberOfSupportedCameras; i++) + { + //鏄剧ずOK/NG鎸夐挳 + label_reslut_mat[i]->setVisible(true); + } + } + } + //connect(ui.btn_pause, SIGNAL(clicked()), this, SLOT(sendLatestData())); } Cigarette::~Cigarette() { - emit sengMsgToClog("Application exited."); - Exit(); - exit(-1); + emit sengMsgToClog("Application exited."); + Exit(); + exit(-1); } void Cigarette::start_work() { - //清除采集临时队列缓存 - for (int i = 0; i < NumberOfSupportedCameras; i++) - { - if(SingleCamInfo[i].Detect && SingleCamInfo[i].IsOpen){ - if(SingleCamInfo[i].CamClass == BalluffClassID){ - if(pCaptureThread[i]) - { - pCaptureThread[i]->p_result_queue->clear(); - pCaptureThread[i]->p_unit_queue->clear(); - pCaptureThread[i]->p_result_wait_queue->clear(); - pCaptureThread[i]->p_shooted_queue->clear(); - } - } - else if (SingleCamInfo[i].CamClass == BaslerClassID) { - if(pBaslerCaptureThread[i]) - { - pBaslerCaptureThread[i]->p_result_queue->clear(); - pBaslerCaptureThread[i]->p_unit_queue->clear(); - pBaslerCaptureThread[i]->p_result_wait_queue->clear(); - pBaslerCaptureThread[i]->p_shooted_queue->clear(); - } - } - else if (SingleCamInfo[i].CamClass == HIKClassID) { - if(pHIKCaptureThread[i]) - { - pHIKCaptureThread[i]->p_result_queue->clear(); - pHIKCaptureThread[i]->p_unit_queue->clear(); - pHIKCaptureThread[i]->p_result_wait_queue->clear(); - pHIKCaptureThread[i]->p_shooted_queue->clear(); - } - } - } - } - - BeforeWork(g_sys_conf.shoot); - int ret = m_PLCDevice->write_bit_2_plc( g_modbus_conf.work, 1); - /*::Sleep(5000); - ret = m_PLCDevice->write_bit_2_plc( g_modbus_conf.work, 0); - ::Sleep(5000); - ret = m_PLCDevice->write_bit_2_plc( g_modbus_conf.work, 1);*/ - //printf("write:\t%d\n", ret); - ui.label_title->setStyleSheet(tr("background-color: rgb(0, 170, 0);")); + //娓呴櫎閲囬泦涓存椂闃熷垪缂撳瓨 + for (int i = 0; i < NumberOfSupportedCameras; i++) + { + if (SingleCamInfo[i].Detect && SingleCamInfo[i].IsOpen) { + if (SingleCamInfo[i].CamClass == BalluffClassID) { + if (pCaptureThread[i]) + { + pCaptureThread[i]->p_result_queue->clear(); + pCaptureThread[i]->p_unit_queue->clear(); + pCaptureThread[i]->p_result_wait_queue->clear(); + pCaptureThread[i]->p_shooted_queue->clear(); + } + } + else if (SingleCamInfo[i].CamClass == BaslerClassID) { + if (pBaslerCaptureThread[i]) + { + pBaslerCaptureThread[i]->p_result_queue->clear(); + pBaslerCaptureThread[i]->p_unit_queue->clear(); + pBaslerCaptureThread[i]->p_result_wait_queue->clear(); + pBaslerCaptureThread[i]->p_shooted_queue->clear(); + } + } + else if (SingleCamInfo[i].CamClass == HIKClassID) { + if (pHIKCaptureThread[i]) + { + pHIKCaptureThread[i]->p_result_queue->clear(); + pHIKCaptureThread[i]->p_unit_queue->clear(); + pHIKCaptureThread[i]->p_result_wait_queue->clear(); + pHIKCaptureThread[i]->p_shooted_queue->clear(); + } + } + } + } + + BeforeWork(g_sys_conf.shoot); + int ret = m_PLCDevice->write_bit_2_plc(g_modbus_conf.work, 1); + /*::Sleep(5000); + ret = m_PLCDevice->write_bit_2_plc( g_modbus_conf.work, 0); + ::Sleep(5000); + ret = m_PLCDevice->write_bit_2_plc( g_modbus_conf.work, 1);*/ + //printf("write:\t%d\n", ret); + ui.label_title->setStyleSheet(tr("background-color: rgb(0, 170, 0);")); #ifdef __UDPSend - sThread.sendData("Work", g_sys_conf.FeedbackPort); -#endif - g_working = true; - ui.checkBox_debug->setChecked(false); //取消调试模式 - ui.checkBox_debug->setEnabled(false); //锁定调试不可用 - //显示OK/NG按钮 - for (int i = 0; i < NumberOfSupportedCameras; i++) - { - //显示OK/NG按钮 - label_reslut_mat[i]->setVisible(true); - } -} -//开始按钮 + sThread.sendData("Work", g_sys_conf.FeedbackPort); +#endif + g_working = true; + ui.checkBox_debug->setChecked(false); //鍙栨秷璋冭瘯妯″紡 + ui.checkBox_debug->setEnabled(false); //閿佸畾璋冭瘯涓嶅彲鐢 + //鏄剧ずOK/NG鎸夐挳 + for (int i = 0; i < NumberOfSupportedCameras; i++) + { + //鏄剧ずOK/NG鎸夐挳 + label_reslut_mat[i]->setVisible(true); + } +} +//寮濮嬫寜閽 void Cigarette::on_btn_start_released() { - emit sengMsgToClog("Start to work."); - if (!g_admin_mode) - { - if (!g_op_mode) - { - emit sengMsgToClog("Start to login in."); - dialogin = new Dialogin(this); - connect(dialogin, SIGNAL(enter_op()), this, SLOT(OnOp())); - dialogin->setModal(true); - dialogin->show(); - dialogin->move((this->width() - dialogin->width()) / 2, (this->height() - dialogin->height()) / 2); - return; - } - } - if (m_PLCDevice->g_plc_ok) { - if (g_debug_mode) - { - QMessageBox::information(NULL, QStringLiteral("操作顺序检查"), QStringLiteral("请先点击“调试模式”复选框,取消调试模式,才可以开始工作"), QMessageBox::Ok); - return; - } - if (!g_working) - { - start_work(); - } - } - g_op_time = OP_TIME; - //ui.checkBox_debug->setEnabled(true); //使能相机调试checkBox + emit sengMsgToClog("Start to work."); + if (!g_admin_mode) + { + if (!g_op_mode) + { + emit sengMsgToClog("Start to login in."); + dialogin = new Dialogin(this); + connect(dialogin, SIGNAL(enter_op()), this, SLOT(OnOp())); + dialogin->setModal(true); + dialogin->show(); + dialogin->move((this->width() - dialogin->width()) / 2, (this->height() - dialogin->height()) / 2); + return; + } + } + if (m_PLCDevice->g_plc_ok) { + if (g_debug_mode) + { + QMessageBox::information(NULL, QStringLiteral("鎿嶄綔椤哄簭妫鏌"), QStringLiteral("璇峰厛鐐瑰嚮鈥滆皟璇曟ā寮忊濆閫夋锛屽彇娑堣皟璇曟ā寮忥紝鎵嶅彲浠ュ紑濮嬪伐浣"), QMessageBox::Ok); + return; + } + if (!g_working) + { + start_work(); + } + } + g_op_time = OP_TIME; + //ui.checkBox_debug->setEnabled(true); //浣胯兘鐩告満璋冭瘯checkBox } void Cigarette::pause_work() { - int ret = m_PLCDevice->write_bit_2_plc( g_modbus_conf.work, 0 ); - //printf("write:\t%d\n", ret); - ui.label_title->setStyleSheet(tr("background-color: rgb(255, 255, 0);")); + int ret = m_PLCDevice->write_bit_2_plc(g_modbus_conf.work, 0); + //printf("write:\t%d\n", ret); + ui.label_title->setStyleSheet(tr("background-color: rgb(255, 255, 0);")); #ifdef __UDPSend - sThread.sendData("NoWork", g_sys_conf.FeedbackPort); + sThread.sendData("NoWork", g_sys_conf.FeedbackPort); #endif - g_working = false; - ui.checkBox_debug->setEnabled(true); //使能相机调试checkBox - //隐藏OK/NG按钮 - for (int i = 0; i < NumberOfSupportedCameras; i++) - { - //显示OK/NG按钮 - label_reslut_mat[i]->setVisible(false); - } + g_working = false; + ui.checkBox_debug->setEnabled(true); //浣胯兘鐩告満璋冭瘯checkBox + //闅愯棌OK/NG鎸夐挳 + for (int i = 0; i < NumberOfSupportedCameras; i++) + { + //鏄剧ずOK/NG鎸夐挳 + label_reslut_mat[i]->setVisible(false); + } #ifdef __UDPSend - m_sendMsg_delay->setSingleShot(true); - m_sendMsg_delay->start(1000); + m_sendMsg_delay->setSingleShot(true); + m_sendMsg_delay->start(1000); #endif } void Cigarette::Exit() { - this->on_btn_pause_released(); + this->on_btn_pause_released(); #ifdef SYNC_CAMERA - sync_work_thread.stop(); - delete g_image_sync_queue; -#endif - for(int i=0;isetStyleSheet(tr("background-color: rgb(255, 255, 0);")); - } - } - debug_thread[i].stop(); + sync_work_thread.stop(); + delete g_image_sync_queue; +#endif + for (int i = 0; i < NumberOfSupportedCameras; i++) + { + if (SingleCamInfo[i].Detect) { + if (ControlCamOpenOrClose(i, CLOSE)) + { + qDebug() << "Close device " << i; + cam_work_mat[i]->setStyleSheet(tr("background-color: rgb(255, 255, 0);")); + } + } + debug_thread[i].stop(); #ifdef SYNC_CAMERA #else - work_thread[i].stop(); - delete g_image_queue[i]; -#endif - delete g_result_queue[i]; - delete g_result_wait_queue[i]; - delete g_double_queue[i]; - delete g_shooted_queue[i]; - delete g_debug_queue[i]; - qDebug() << "Close capture thread " << i; - } - saveThread.stop(); - delete g_save_queue; + work_thread[i].stop(); + delete g_image_queue[i]; +#endif + delete g_result_queue[i]; + delete g_result_wait_queue[i]; + delete g_double_queue[i]; + delete g_shooted_queue[i]; + delete g_debug_queue[i]; + qDebug() << "Close capture thread " << i; + } + saveThread.stop(); + delete g_save_queue; #ifdef __UDPSend - sThread.stop(); - rThread->stop(); - delete rThread; + sThread.stop(); + rThread->stop(); + delete rThread; #endif #ifdef __TCPSend - tcpSendThread.stop(); + tcpSendThread.stop(); #endif #ifdef __ExportData - exportDataThread.stop(); - // delete export_Data_Info_queue; + exportDataThread.stop(); + // delete export_Data_Info_queue; #endif - qDebug() << "Close thread "; - - if(m_PLCDevice) { - m_PLCDevice->disconnect_plc(); - delete m_PLCDevice; - } - qApp->quit(); - this->close(); + qDebug() << "Close thread "; + + if (m_PLCDevice) { + m_PLCDevice->disconnect_plc(); + delete m_PLCDevice; + } + qApp->quit(); + this->close(); + + Pylon::PylonTerminate(); - Pylon::PylonTerminate(); - } -//停止工作按钮 +//鍋滄宸ヤ綔鎸夐挳 void Cigarette::on_btn_pause_released() { - emit sengMsgToClog("Pause the application."); - if (!g_admin_mode) - { - if (!g_op_mode) - { - emit sengMsgToClog("Start to login in."); - dialogin = new Dialogin(this); - connect(dialogin, SIGNAL(enter_op()), this, SLOT(OnOp())); - dialogin->setModal(true); - dialogin->show(); - dialogin->move((this->width() - dialogin->width()) / 2, (this->height() - dialogin->height()) / 2); - return; - } - } - if (m_PLCDevice->g_plc_ok) { - if (g_working){ - pause_work(); - } - } - g_op_time = OP_TIME; -} - -//锁定/解锁按钮 + emit sengMsgToClog("Pause the application."); + if (!g_admin_mode) + { + if (!g_op_mode) + { + emit sengMsgToClog("Start to login in."); + dialogin = new Dialogin(this); + connect(dialogin, SIGNAL(enter_op()), this, SLOT(OnOp())); + dialogin->setModal(true); + dialogin->show(); + dialogin->move((this->width() - dialogin->width()) / 2, (this->height() - dialogin->height()) / 2); + return; + } + } + if (m_PLCDevice->g_plc_ok) { + if (g_working) { + pause_work(); + } + } + g_op_time = OP_TIME; +} + +//閿佸畾/瑙i攣鎸夐挳 void Cigarette::on_btn_lock_released() { - if (!g_admin_mode) - { - emit sengMsgToClog("Unlock the application."); - dialog_setup_passwd = new DialogSetupPasswd(this); - connect(dialog_setup_passwd, SIGNAL(enter_admin()), this, SLOT(OnAdmin())); - dialog_setup_passwd->setModal(true); - dialog_setup_passwd->show(); - dialog_setup_passwd->move((this->width() - dialog_setup_passwd->width()) / 2, (this->height() - dialog_setup_passwd->height()) / 2); - } - else - { - emit sengMsgToClog("Lock the application."); - g_admin_mode = false; - g_op_mode = false; - ui.label_12->setText(QStringLiteral("登录用户:")); - ui.label_role->setText(QStringLiteral("未登录")); - ui.btn_lock->setStyleSheet(tr("border-image: url(:/Cigarette/Resources/unlock.png);")); - ui.checkBox_debug->setEnabled(false); - if (m_op_delay->isActive()) - { - m_op_delay->stop(); - } - if (m_admin_delay->isActive()) - { - m_admin_delay->stop(); - } + if (!g_admin_mode) + { + emit sengMsgToClog("Unlock the application."); + dialog_setup_passwd = new DialogSetupPasswd(this); + connect(dialog_setup_passwd, SIGNAL(enter_admin()), this, SLOT(OnAdmin())); + dialog_setup_passwd->setModal(true); + dialog_setup_passwd->show(); + dialog_setup_passwd->move((this->width() - dialog_setup_passwd->width()) / 2, (this->height() - dialog_setup_passwd->height()) / 2); + } + else + { + emit sengMsgToClog("Lock the application."); + g_admin_mode = false; + g_op_mode = false; + ui.label_12->setText(QStringLiteral("鐧诲綍鐢ㄦ埛锛")); + ui.label_role->setText(QStringLiteral("鏈櫥褰")); + ui.btn_lock->setStyleSheet(tr("border-image: url(:/Cigarette/Resources/unlock.png);")); + ui.checkBox_debug->setEnabled(false); + if (m_op_delay->isActive()) + { + m_op_delay->stop(); + } + if (m_admin_delay->isActive()) + { + m_admin_delay->stop(); + } #ifdef __UDPSend - sThread.sendData("LockOk", g_sys_conf.FeedbackPort); + sThread.sendData("LockOk", g_sys_conf.FeedbackPort); #endif - } + } } -//设置按钮 +//璁剧疆鎸夐挳 void Cigarette::on_btn_setup_released() { - emit sengMsgToClog("Start to set the application."); - if (g_admin_mode) - { - dialog_setup = new DialogSetup(this); - connect(dialog_setup, SIGNAL(system_exit()), this, SLOT(OnExit())); + emit sengMsgToClog("Start to set the application."); + if (g_admin_mode) + { + dialog_setup = new DialogSetup(this); + connect(dialog_setup, SIGNAL(system_exit()), this, SLOT(OnExit())); #ifdef __DEBUG - connect(dialog_setup, SIGNAL(_testimg()), this, SLOT(TestImg())); - connect(dialog_setup, SIGNAL(_testimgs()), this, SLOT(TestImgs())); -#endif - dialog_setup->setModal(true); - dialog_setup->show(); - dialog_setup->move((this->width() - dialog_setup->width()) / 2, (this->height() - dialog_setup->height()) / 2); - - } - else { - QMessageBox::information(NULL, QStringLiteral("权限检查"), QStringLiteral("请先点击解锁按钮,进入管理员模式"), QMessageBox::Ok); - } + connect(dialog_setup, SIGNAL(_testimg()), this, SLOT(TestImg())); + connect(dialog_setup, SIGNAL(_testimgs()), this, SLOT(TestImgs())); +#endif + dialog_setup->setModal(true); + dialog_setup->show(); + dialog_setup->move((this->width() - dialog_setup->width()) / 2, (this->height() - dialog_setup->height()) / 2); + + } + else { + QMessageBox::information(NULL, QStringLiteral("鏉冮檺妫鏌"), QStringLiteral("璇峰厛鐐瑰嚮瑙i攣鎸夐挳锛岃繘鍏ョ鐞嗗憳妯″紡"), QMessageBox::Ok); + } } #ifdef __DEBUG void Cigarette::TestImg() { - QString srcDirPath = QString::fromStdString(SelectFileOFN()); + QString srcDirPath = QString::fromStdString(SelectFileOFN()); - //输入图像 + //杈撳叆鍥惧儚 std::cout << "open file------ " << srcDirPath.toStdString() << std::endl; cv::Mat imagein = cv::imread(srcDirPath.toStdString(), cv::IMREAD_COLOR); if (!imagein.data) @@ -820,34 +822,34 @@ void Cigarette::TestImg() } std::vector > results; cv::Mat output; - alg_test.detect(imagein, output,results); - std::string WindowName = "TestImg"; - cv::namedWindow(WindowName, cv::WINDOW_NORMAL); - cv::imshow(WindowName, output); + alg_test.detect(imagein, output, results); + std::string WindowName = "TestImg"; + cv::namedWindow(WindowName, cv::WINDOW_NORMAL); + cv::imshow(WindowName, output); cv::waitKeyEx(1); #ifdef __ExportData - alg_test.analyse(imagein, results); + alg_test.analyse(imagein, results); #endif } void Cigarette::TestImgs() { - QString srcDirPath = QString::fromStdString(SelectDirIFD()); + QString srcDirPath = QString::fromStdString(SelectDirIFD()); vector files; std::cout << "srcDirPath=" << srcDirPath.toStdString() << std::endl; srcDirPath += "/"; - //获取该路径下的所有文件 + //鑾峰彇璇ヨ矾寰勪笅鐨勬墍鏈夋枃浠 getFiles(srcDirPath.toStdString() + "*.bmp", files); if (files.size() == 0) { - QMessageBox::StandardButton result = QMessageBox::information(NULL, QStringLiteral("提示"), QStringLiteral("没有找到图片")); + QMessageBox::StandardButton result = QMessageBox::information(NULL, QStringLiteral("鎻愮ず"), QStringLiteral("娌℃湁鎵惧埌鍥剧墖")); return; } for (int index = 0; index < files.size(); index++) { - //输入图像 + //杈撳叆鍥惧儚 std::cout << "open file------ " << files[index] << std::endl; cv::Mat imagein = cv::imread(srcDirPath.toStdString() + files[index], cv::IMREAD_COLOR); if (!imagein.data) @@ -856,1974 +858,1982 @@ void Cigarette::TestImgs() } cv::Mat output; - std::vector > results; - alg_test.detect(imagein, output,results); - std::string WindowName = "TestImg"; - cv::namedWindow(WindowName, cv::WINDOW_NORMAL); - cv::imshow(WindowName, output); + std::vector > results; + alg_test.detect(imagein, output, results); + std::string WindowName = "TestImg"; + cv::namedWindow(WindowName, cv::WINDOW_NORMAL); + cv::imshow(WindowName, output); int k = cv::waitKeyEx(1); - if (k == 27)break;//ESC键 + if (k == 27)break;//ESC閿 #ifdef __ExportData - alg_test.analyse(imagein, results); + alg_test.analyse(imagein, results); #endif QCoreApplication::processEvents(); } } #endif -//管理员登陆 +//绠$悊鍛樼櫥闄 void Cigarette::OnAdmin() { - emit sengMsgToClog("Administrator is login in."); - g_admin_mode = true; - ui.label_12->setText(QStringLiteral("登录用户:")); - ui.label_role->setText(QStringLiteral("管理员")); - ui.btn_lock->setStyleSheet(tr("border-image: url(:/Cigarette/Resources/lock.png);")); - ui.checkBox_debug->setEnabled(true); - g_admin_time = ADMIN_TIME; - m_admin_delay->start(1000); - if (m_op_delay->isActive()) - { - m_op_delay->stop(); - } + emit sengMsgToClog("Administrator is login in."); + g_admin_mode = true; + ui.label_12->setText(QStringLiteral("鐧诲綍鐢ㄦ埛锛")); + ui.label_role->setText(QStringLiteral("绠$悊鍛")); + ui.btn_lock->setStyleSheet(tr("border-image: url(:/Cigarette/Resources/lock.png);")); + ui.checkBox_debug->setEnabled(true); + g_admin_time = ADMIN_TIME; + m_admin_delay->start(1000); + if (m_op_delay->isActive()) + { + m_op_delay->stop(); + } #ifdef __UDPSend - sThread.sendData("UnlockOk", g_sys_conf.FeedbackPort); + sThread.sendData("UnlockOk", g_sys_conf.FeedbackPort); #endif } -//操作员登陆 +//鎿嶄綔鍛樼櫥闄 void Cigarette::OnOp() { - emit sengMsgToClog("Operator is login in."); - g_op_mode = true; - g_op_time = OP_TIME; - ui.label_role->setText(QStringLiteral("操作员")); - m_op_delay->start(1000); + emit sengMsgToClog("Operator is login in."); + g_op_mode = true; + g_op_time = OP_TIME; + ui.label_role->setText(QStringLiteral("鎿嶄綔鍛")); + m_op_delay->start(1000); } -//退出前执行 +//閫鍑哄墠鎵ц void Cigarette::OnExit() { - emit sengMsgToClog("Close the Application."); - Exit(); - exit(-1); + emit sengMsgToClog("Close the Application."); + Exit(); + exit(-1); } void Cigarette::OnRestart() { - Exit(); - QProcess::startDetached(qApp->applicationFilePath(), QStringList()); + Exit(); + QProcess::startDetached(qApp->applicationFilePath(), QStringList()); } -//换班防连击 +//鎹㈢彮闃茶繛鍑 void Cigarette::enable_shift() { - ui.pushButton_clear->setEnabled(true); + ui.pushButton_clear->setEnabled(true); } #ifdef __UDPSend void Cigarette::sendLatestData() { - // 连接UDP发送最新的数据 - int dataport = g_sys_conf.MonitorPort; - - _UDPSendInfo UDPSendInfo; - for (int i = 0; i < NumberOfSupportedCameras; i++) - { - UDPSendInfo.index = i; - UDPSendInfo.FrameID = ok_frame; - UDPSendInfo.ok[i] = ok[i]; - UDP_Info_queue->put(UDPSendInfo); - UDPSendInfo.FrameID = ng_frame; - UDPSendInfo.ng[i] = ng[i]; - UDP_Info_queue->put(UDPSendInfo); - UDPSendInfo.FrameID = total_frame; - UDPSendInfo.Total = production_number[i]; - UDP_Info_queue->put(UDPSendInfo); - } -} -#endif - -void Cigarette::OnRotateReleasedHub(int Num)//旋转按钮 + // 杩炴帴UDP鍙戦佹渶鏂扮殑鏁版嵁 + int dataport = g_sys_conf.MonitorPort; + + _UDPSendInfo UDPSendInfo; + for (int i = 0; i < NumberOfSupportedCameras; i++) + { + UDPSendInfo.index = i; + UDPSendInfo.FrameID = ok_frame; + UDPSendInfo.ok[i] = ok[i]; + UDP_Info_queue->put(UDPSendInfo); + UDPSendInfo.FrameID = ng_frame; + UDPSendInfo.ng[i] = ng[i]; + UDP_Info_queue->put(UDPSendInfo); + UDPSendInfo.FrameID = total_frame; + UDPSendInfo.Total = production_number[i]; + UDP_Info_queue->put(UDPSendInfo); + } +} +#endif + +void Cigarette::OnRotateReleasedHub(int Num)//鏃嬭浆鎸夐挳 { - QString str = "Start to rotate picture " + QString::number(90 * ((rotationAngle[Num] + 1) % 4)) + " degrees of camera " + QString::number(Num) + "."; - emit sengMsgToClog(str); - if( isNeedRotate[Num] == true) - { - rotationAngle[Num] = (rotationAngle[Num] + 1) % 4; - save_rotate_message(); - } + QString str = "Start to rotate picture " + QString::number(90 * ((rotationAngle[Num] + 1) % 4)) + " degrees of camera " + QString::number(Num) + "."; + emit sengMsgToClog(str); + if (isNeedRotate[Num] == true) + { + rotationAngle[Num] = (rotationAngle[Num] + 1) % 4; + save_rotate_message(); + } } -//打开/关闭相机 +//鎵撳紑/鍏抽棴鐩告満 void Cigarette::OnToolButtonCamReleasedHub(int Num) { - if (g_admin_mode) - { - if(SingleCamInfo[Num].Detect) - { - if (!SingleCamInfo[Num].IsOpen) - { - emit sengMsgToClog("Start open camera " + QString::number(Num) + "."); - if(ControlCamOpenOrClose(Num, OPEN)) - { - cam_work_mat[Num]->setStyleSheet(tr("background-color: rgb(0, 170, 0);"));//相机工作提示 - cam_status_mat[Num]->setStyleSheet(tr("background-color: rgb(0,170,0);"));//相机联机指示 - QString str = QString("border-image: url(:/Cigarette/Resources/cam%1_yes.png);").arg(Num+1); - QByteArray ba = str.toLatin1(); - cam_toolButton_mat[Num]->setStyleSheet(tr(ba.data())); - } - } - else - { - emit sengMsgToClog("Start close camera " + QString::number(Num) + "."); - if(ControlCamOpenOrClose(Num, CLOSE)) - { - cam_work_mat[Num]->setStyleSheet(tr("background-color: rgb(255, 255, 0);")); - QString str = QString("border-image: url(:/Cigarette/Resources/cam%1_no.png);").arg(Num+1); - QByteArray ba = str.toLatin1(); - cam_toolButton_mat[Num]->setStyleSheet(tr(ba.data())); - } - } - } - else - { - emit sengMsgToClog("Close or open camera " + QString::number(Num) + " fail, there is no camera in potision 0."); - QMessageBox::information(NULL, QStringLiteral("操作失败"), QStringLiteral("该机位没有检测到相机"), QMessageBox::Ok); - } - } - else { - emit sengMsgToClog("Close or open camera " + QString::number(Num) + " fail, because of authorization check fail."); - QMessageBox::information(NULL, QStringLiteral("权限检查"), QStringLiteral("请先点击解锁按钮,进入管理员模式"), QMessageBox::Ok); - } + if (g_admin_mode) + { + if (SingleCamInfo[Num].Detect) + { + if (!SingleCamInfo[Num].IsOpen) + { + emit sengMsgToClog("Start open camera " + QString::number(Num) + "."); + if (ControlCamOpenOrClose(Num, OPEN)) + { + cam_work_mat[Num]->setStyleSheet(tr("background-color: rgb(0, 170, 0);"));//鐩告満宸ヤ綔鎻愮ず + cam_status_mat[Num]->setStyleSheet(tr("background-color: rgb(0,170,0);"));//鐩告満鑱旀満鎸囩ず + QString str = QString("border-image: url(:/Cigarette/Resources/cam%1_yes.png);").arg(Num + 1); + QByteArray ba = str.toLatin1(); + cam_toolButton_mat[Num]->setStyleSheet(tr(ba.data())); + } + } + else + { + emit sengMsgToClog("Start close camera " + QString::number(Num) + "."); + if (ControlCamOpenOrClose(Num, CLOSE)) + { + cam_work_mat[Num]->setStyleSheet(tr("background-color: rgb(255, 255, 0);")); + QString str = QString("border-image: url(:/Cigarette/Resources/cam%1_no.png);").arg(Num + 1); + QByteArray ba = str.toLatin1(); + cam_toolButton_mat[Num]->setStyleSheet(tr(ba.data())); + } + } + } + else + { + emit sengMsgToClog("Close or open camera " + QString::number(Num) + " fail, there is no camera in potision 0."); + QMessageBox::information(NULL, QStringLiteral("鎿嶄綔澶辫触"), QStringLiteral("璇ユ満浣嶆病鏈夋娴嬪埌鐩告満"), QMessageBox::Ok); + } + } + else { + emit sengMsgToClog("Close or open camera " + QString::number(Num) + " fail, because of authorization check fail."); + QMessageBox::information(NULL, QStringLiteral("鏉冮檺妫鏌"), QStringLiteral("璇峰厛鐐瑰嚮瑙i攣鎸夐挳锛岃繘鍏ョ鐞嗗憳妯″紡"), QMessageBox::Ok); + } } void Cigarette::ReconnectCamHub(int Num) { - //close - if(SingleCamInfo[Num].Detect) - { - if(ControlCamOpenOrClose(Num,CLOSE)) - { - m_pTimer_Cam_mat[Num]->setSingleShot(true); - m_pTimer_Cam_mat[Num]->start(2000); - } - } -} - -void Cigarette::OpenCamTimeoutHub(int Num) //重新打开相机 + //close + if (SingleCamInfo[Num].Detect) + { + if (ControlCamOpenOrClose(Num, CLOSE)) + { + m_pTimer_Cam_mat[Num]->setSingleShot(true); + m_pTimer_Cam_mat[Num]->start(2000); + } + } +} + +void Cigarette::OpenCamTimeoutHub(int Num) //閲嶆柊鎵撳紑鐩告満 { - //open - if(ControlCamOpenOrClose(Num,OPEN)) - { - cam_work_mat[Num]->setStyleSheet(tr("background-color: rgb(0, 170, 0);")); - cam_toolButton_mat[Num]->setStyleSheet(tr("border-image: url(:/Cigarette/Resources/cam1_yes.png);")); - } + //open + if (ControlCamOpenOrClose(Num, OPEN)) + { + cam_work_mat[Num]->setStyleSheet(tr("background-color: rgb(0, 170, 0);")); + cam_toolButton_mat[Num]->setStyleSheet(tr("border-image: url(:/Cigarette/Resources/cam1_yes.png);")); + } } void Cigarette::OnKey(QKeyEvent* event) { - int Num = CurOpLabel >> 4; - int Cnt = CurOpLabel & 0x0f; - - std::lock_guard locker(g_display_label_conf[Num].lock); - if (event->key() == Qt::Key_Escape && event->isAutoRepeat()==false) - { - if (g_display_label_conf[Num].RectVet[Cnt].size()) - { - g_display_label_conf[Num].RectVet[Cnt].pop_back(); - } - } - else if (event->key() == Qt::Key_Return && event->isAutoRepeat()==false) - { - std::fstream cfg_file; - char buf[256]; - memset(buf, 0, 256); - sprintf(buf, SELECT_RECTS_FILE, Num,Cnt); - QString rects_file = g_conf_path.config_path + "/" + buf; - cfg_file.open(rects_file.toLocal8Bit().constData(), ios::trunc | ofstream::out); - if (!cfg_file.is_open()) - { - std::cout << "Error: Open config file SelectRects.txt" << std::endl; - return; - } - for (int i = 0; i < g_display_label_conf[Num].RectVet[Cnt].size(); i++) - { - char buf[256]; - memset(buf, 0, 256); - sprintf(buf, - "%03f,%03f,%03f,%03f\n", - g_display_label_conf[Num].RectVet[Cnt][i].TL.x, - g_display_label_conf[Num].RectVet[Cnt][i].TL.y, - g_display_label_conf[Num].RectVet[Cnt][i].BR.x, - g_display_label_conf[Num].RectVet[Cnt][i].BR.y - ); - cfg_file.write(buf, strlen(buf)); - } - } -} -//鼠标回调函数 + int Num = CurOpLabel >> 4; + int Cnt = CurOpLabel & 0x0f; + + std::lock_guard locker(g_display_label_conf[Num].lock); + if (event->key() == Qt::Key_Escape && event->isAutoRepeat() == false) + { + if (g_display_label_conf[Num].RectVet[Cnt].size()) + { + g_display_label_conf[Num].RectVet[Cnt].pop_back(); + } + } + else if (event->key() == Qt::Key_Return && event->isAutoRepeat() == false) + { + std::fstream cfg_file; + char buf[256]; + memset(buf, 0, 256); + sprintf(buf, SELECT_RECTS_FILE, Num, Cnt); + QString rects_file = g_conf_path.config_path + "/" + buf; + cfg_file.open(rects_file.toLocal8Bit().constData(), ios::trunc | ofstream::out); + if (!cfg_file.is_open()) + { + std::cout << "Error: Open config file SelectRects.txt" << std::endl; + return; + } + for (int i = 0; i < g_display_label_conf[Num].RectVet[Cnt].size(); i++) + { + char buf[256]; + memset(buf, 0, 256); + sprintf(buf, + "%03f,%03f,%03f,%03f\n", + g_display_label_conf[Num].RectVet[Cnt][i].TL.x, + g_display_label_conf[Num].RectVet[Cnt][i].TL.y, + g_display_label_conf[Num].RectVet[Cnt][i].BR.x, + g_display_label_conf[Num].RectVet[Cnt][i].BR.y + ); + cfg_file.write(buf, strlen(buf)); + } + } +} +//榧犳爣鍥炶皟鍑芥暟 void Cigarette::OnMouse(QMouseEvent* event) { - int Num = CurOpLabel>>4; - int Cnt = CurOpLabel&0x0f; + int Num = CurOpLabel >> 4; + int Cnt = CurOpLabel & 0x0f; - int CurWidgetWidth = display_lable_mat[Num][Cnt]->width(); - int CurWidgetHeight = display_lable_mat[Num][Cnt]->height(); + int CurWidgetWidth = display_lable_mat[Num][Cnt]->width(); + int CurWidgetHeight = display_lable_mat[Num][Cnt]->height(); - std::lock_guard locker(g_display_label_conf[Num].lock); + std::lock_guard locker(g_display_label_conf[Num].lock); if (event->type() == QEvent::MouseButtonPress) { - g_display_label_conf[Num].leftButtonDownFlag = true; //标志位 + g_display_label_conf[Num].leftButtonDownFlag = true; //鏍囧織浣 g_display_label_conf[Num].originalPoint = cv::Point2f( - event->x() * 1.0 / CurWidgetWidth, - event->y() * 1.0 / CurWidgetHeight - ); //设置左键按下点的矩形起点 + event->x() * 1.0 / CurWidgetWidth, + event->y() * 1.0 / CurWidgetHeight + ); //璁剧疆宸﹂敭鎸変笅鐐圭殑鐭╁舰璧风偣 g_display_label_conf[Num].processPoint = g_display_label_conf[Num].originalPoint; } if (event->type() == QEvent::MouseMove && g_display_label_conf[Num].leftButtonDownFlag) { - g_display_label_conf[Num].processPoint = cv::Point2f( - event->x() * 1.0 / CurWidgetWidth, - event->y() * 1.0 / CurWidgetHeight - ); + g_display_label_conf[Num].processPoint = cv::Point2f( + event->x() * 1.0 / CurWidgetWidth, + event->y() * 1.0 / CurWidgetHeight + ); } if (event->type() == QEvent::MouseButtonRelease) { - g_display_label_conf[Num].leftButtonDownFlag = false; - RectRatio m_RectRatio = RectRatio( - cv::Point2f(g_display_label_conf[Num].originalPoint.x * 1.0, - g_display_label_conf[Num].originalPoint.y * 1.0 - ), - cv::Point2f(event->x() * 1.0 / CurWidgetWidth, - event->y() * 1.0 / CurWidgetHeight - ) - ); - float tempx = abs((m_RectRatio.TL - m_RectRatio.BR).x); - float tempy = abs((m_RectRatio.TL - m_RectRatio.BR).y); - if(tempx >0.05) - g_display_label_conf[Num].RectVet[Cnt].push_back(m_RectRatio); + g_display_label_conf[Num].leftButtonDownFlag = false; + RectRatio m_RectRatio = RectRatio( + cv::Point2f(g_display_label_conf[Num].originalPoint.x * 1.0, + g_display_label_conf[Num].originalPoint.y * 1.0 + ), + cv::Point2f(event->x() * 1.0 / CurWidgetWidth, + event->y() * 1.0 / CurWidgetHeight + ) + ); + float tempx = abs((m_RectRatio.TL - m_RectRatio.BR).x); + float tempy = abs((m_RectRatio.TL - m_RectRatio.BR).y); + if (tempx > 0.05) + g_display_label_conf[Num].RectVet[Cnt].push_back(m_RectRatio); } } -//双击视图1 +//鍙屽嚮瑙嗗浘1 void Cigarette::OnDBClickHub(int Num_Cnt) { - int Num = Num_Cnt>>4; - int Cnt = Num_Cnt&0x0f; - - CurOpLabel = Num_Cnt; - std::lock_guard locker(g_display_label_conf[Num].lock); - if (g_display_label_conf[Num].g_max[Cnt]) - { /// 全屏状态下 双击取消全屏 - emit sengMsgToClog("Cancel the picture of camera " + QString::number(Num) + " to full screen."); - g_display_label_conf[Num].g_max[Cnt] = false; - display_lable_mat[Num][Cnt]->setGeometry( - display_lable_info[Num][Cnt].x, - display_lable_info[Num][Cnt].y, - display_lable_info[Num][Cnt].width, - display_lable_info[Num][Cnt].height - ); - rotate_mat[Num]->setGeometry( - rotate_info[Num].x, - rotate_info[Num].y, - rotate_info[Num].width, - rotate_info[Num].height - ); - if(g_display_label_conf[Num].Flag[Cnt] & DisplayLabel_Type_Bit) - { - g_display_label_conf[Num].Flag[Cnt] &= ~DisplayLabel_Conf_Bit; - disconnect(display_lable_mat[Num][Cnt], SIGNAL(SignalmousePressEvent(QMouseEvent*)), this, SLOT(OnMouse(QMouseEvent*))); - disconnect(display_lable_mat[Num][Cnt], SIGNAL(SignalmouseMoveEvent(QMouseEvent*)), this, SLOT(OnMouse(QMouseEvent*))); - disconnect(display_lable_mat[Num][Cnt], SIGNAL(SignalmouseReleaseEvent(QMouseEvent*)), this, SLOT(OnMouse(QMouseEvent*))); - disconnect(display_lable_mat[Num][Cnt], SIGNAL(SignalkeyReleaseEvent(QKeyEvent*)), this, SLOT(OnKey(QKeyEvent*))); - } - } - else - { // 双击全屏 - emit sengMsgToClog("Set the picture of camera " + QString::number(Num) + " to full screen."); - g_display_label_conf[Num].g_max[Cnt] = true; - display_lable_mat[Num][Cnt]->setGeometry(0, 0, 1280, 800); - - //rotate_mat[Num]->setGeometry(1230, 10, 40, 40); - - if (g_debug_mode)//是否为调试模式 - { - rotate_mat[Num]->setGeometry(1230, 10, 40, 40); - } - else - { - rotate_mat[Num]->setGeometry(1230, 10, 0, 0); - } - - display_lable_mat[Num][Cnt]->raise(); - rotate_mat[Num]->raise(); - - if(g_display_label_conf[Num].Flag[Cnt] & DisplayLabel_Type_Bit) - { - g_display_label_conf[Num].Flag[Cnt] |= DisplayLabel_Conf_Bit; - connect(display_lable_mat[Num][Cnt], SIGNAL(SignalmousePressEvent(QMouseEvent*)), this, SLOT(OnMouse(QMouseEvent*))); - connect(display_lable_mat[Num][Cnt], SIGNAL(SignalmouseMoveEvent(QMouseEvent*)), this, SLOT(OnMouse(QMouseEvent*))); - connect(display_lable_mat[Num][Cnt], SIGNAL(SignalmouseReleaseEvent(QMouseEvent*)), this, SLOT(OnMouse(QMouseEvent*))); - connect(display_lable_mat[Num][Cnt], SIGNAL(SignalkeyReleaseEvent(QKeyEvent*)), this, SLOT(OnKey(QKeyEvent*))); - } - } - OnNotifyHub(Num,Cnt,g_display_label_conf[Num].g_last_mat[Cnt]); + int Num = Num_Cnt >> 4; + int Cnt = Num_Cnt & 0x0f; + + CurOpLabel = Num_Cnt; + std::lock_guard locker(g_display_label_conf[Num].lock); + if (g_display_label_conf[Num].g_max[Cnt]) + { /// 鍏ㄥ睆鐘舵佷笅 鍙屽嚮鍙栨秷鍏ㄥ睆 + emit sengMsgToClog("Cancel the picture of camera " + QString::number(Num) + " to full screen."); + g_display_label_conf[Num].g_max[Cnt] = false; + display_lable_mat[Num][Cnt]->setGeometry( + display_lable_info[Num][Cnt].x, + display_lable_info[Num][Cnt].y, + display_lable_info[Num][Cnt].width, + display_lable_info[Num][Cnt].height + ); + rotate_mat[Num]->setGeometry( + rotate_info[Num].x, + rotate_info[Num].y, + rotate_info[Num].width, + rotate_info[Num].height + ); + if (g_display_label_conf[Num].Flag[Cnt] & DisplayLabel_Type_Bit) + { + g_display_label_conf[Num].Flag[Cnt] &= ~DisplayLabel_Conf_Bit; + disconnect(display_lable_mat[Num][Cnt], SIGNAL(SignalmousePressEvent(QMouseEvent*)), this, SLOT(OnMouse(QMouseEvent*))); + disconnect(display_lable_mat[Num][Cnt], SIGNAL(SignalmouseMoveEvent(QMouseEvent*)), this, SLOT(OnMouse(QMouseEvent*))); + disconnect(display_lable_mat[Num][Cnt], SIGNAL(SignalmouseReleaseEvent(QMouseEvent*)), this, SLOT(OnMouse(QMouseEvent*))); + disconnect(display_lable_mat[Num][Cnt], SIGNAL(SignalkeyReleaseEvent(QKeyEvent*)), this, SLOT(OnKey(QKeyEvent*))); + } + } + else + { // 鍙屽嚮鍏ㄥ睆 + emit sengMsgToClog("Set the picture of camera " + QString::number(Num) + " to full screen."); + g_display_label_conf[Num].g_max[Cnt] = true; + display_lable_mat[Num][Cnt]->setGeometry(0, 0, 1280, 800); + + //rotate_mat[Num]->setGeometry(1230, 10, 40, 40); + + if (g_debug_mode)//鏄惁涓鸿皟璇曟ā寮 + { + rotate_mat[Num]->setGeometry(1230, 10, 40, 40); + } + else + { + rotate_mat[Num]->setGeometry(1230, 10, 0, 0); + } + + display_lable_mat[Num][Cnt]->raise(); + rotate_mat[Num]->raise(); + + if (g_display_label_conf[Num].Flag[Cnt] & DisplayLabel_Type_Bit) + { + g_display_label_conf[Num].Flag[Cnt] |= DisplayLabel_Conf_Bit; + connect(display_lable_mat[Num][Cnt], SIGNAL(SignalmousePressEvent(QMouseEvent*)), this, SLOT(OnMouse(QMouseEvent*))); + connect(display_lable_mat[Num][Cnt], SIGNAL(SignalmouseMoveEvent(QMouseEvent*)), this, SLOT(OnMouse(QMouseEvent*))); + connect(display_lable_mat[Num][Cnt], SIGNAL(SignalmouseReleaseEvent(QMouseEvent*)), this, SLOT(OnMouse(QMouseEvent*))); + connect(display_lable_mat[Num][Cnt], SIGNAL(SignalkeyReleaseEvent(QKeyEvent*)), this, SLOT(OnKey(QKeyEvent*))); + } + } + OnNotifyHub(Num, Cnt, g_display_label_conf[Num].g_last_mat[Cnt]); } void Cigarette::DrawRect_init(int Num_Cnt) { - //int Num = Num_Cnt >> 4; - //int Cnt = Num_Cnt & 0x0f; - - int Num = Num_Cnt & 0x0f; - int Cnt = Num_Cnt >> 4; - if (g_display_label_conf[Num].Flag[Cnt] & DisplayLabel_Type_Bit) - { - g_display_label_conf[Num].Flag[Cnt] &= ~DisplayLabel_Type_Bit; - g_display_label_conf[Num].Flag[Cnt] &= ~DisplayLabel_Conf_Bit; - } - else { - g_display_label_conf[Num].Flag[Cnt] |= DisplayLabel_Type_Bit; - std::fstream cfg_file; - char buf[256]; - memset(buf, 0, 256); - sprintf(buf, SELECT_RECTS_FILE, Num, Cnt); - QString rects_file = g_conf_path.config_path + "/" + buf; - cfg_file.open(rects_file.toLocal8Bit().constData()); - if (!cfg_file.is_open()) - { - std::cout << "Error: Open config file SelectRects"<> 4; + //int Cnt = Num_Cnt & 0x0f; + + int Num = Num_Cnt & 0x0f; + int Cnt = Num_Cnt >> 4; + if (g_display_label_conf[Num].Flag[Cnt] & DisplayLabel_Type_Bit) + { + g_display_label_conf[Num].Flag[Cnt] &= ~DisplayLabel_Type_Bit; + g_display_label_conf[Num].Flag[Cnt] &= ~DisplayLabel_Conf_Bit; + } + else { + g_display_label_conf[Num].Flag[Cnt] |= DisplayLabel_Type_Bit; + std::fstream cfg_file; + char buf[256]; + memset(buf, 0, 256); + sprintf(buf, SELECT_RECTS_FILE, Num, Cnt); + QString rects_file = g_conf_path.config_path + "/" + buf; + cfg_file.open(rects_file.toLocal8Bit().constData()); + if (!cfg_file.is_open()) + { + std::cout << "Error: Open config file SelectRects" << Num << Cnt << ".txt" << std::endl; + return; + } + while (!cfg_file.eof()) + { + char tmp[256] = ""; + cfg_file.getline(tmp, 256); + QString line = QString::fromStdString(std::string(tmp)); + QStringList dataList = line.split(','); + if (dataList.length() == 4) + { + RectRatio m_RectRatio = RectRatio( + cv::Point2f(dataList[0].toFloat(), dataList[1].toFloat()), + cv::Point2f(dataList[2].toFloat(), dataList[3].toFloat()) + ); + g_display_label_conf[Num].RectVet[Cnt].push_back(m_RectRatio); + } + } + } } void Cigarette::OnTPClickHub(int Num_Cnt) { - int Num = Num_Cnt >> 4; - int Cnt = Num_Cnt & 0x0f; - - std::lock_guard locker(g_display_label_conf[Num].lock); - if (g_display_label_conf[Num].Flag[Cnt] & DisplayLabel_Type_Bit) - { - g_display_label_conf[Num].Flag[Cnt] &= ~DisplayLabel_Type_Bit; - g_display_label_conf[Num].Flag[Cnt] &= ~DisplayLabel_Conf_Bit; - disconnect(display_lable_mat[Num][Cnt], SIGNAL(SignalmousePressEvent(QMouseEvent*)), this, SLOT(OnMouse(QMouseEvent*))); - disconnect(display_lable_mat[Num][Cnt], SIGNAL(SignalmouseMoveEvent(QMouseEvent*)), this, SLOT(OnMouse(QMouseEvent*))); - disconnect(display_lable_mat[Num][Cnt], SIGNAL(SignalmouseReleaseEvent(QMouseEvent*)), this, SLOT(OnMouse(QMouseEvent*))); - disconnect(display_lable_mat[Num][Cnt], SIGNAL(SignalkeyReleaseEvent(QKeyEvent*)), this, SLOT(OnKey(QKeyEvent*))); - } - else - { - g_display_label_conf[Num].Flag[Cnt] |= DisplayLabel_Type_Bit; - std::fstream cfg_file; - char buf[256]; - memset(buf, 0, 256); - sprintf(buf, SELECT_RECTS_FILE, Num, Cnt); - QString rects_file = g_conf_path.config_path + "/" + buf; - cfg_file.open(rects_file.toLocal8Bit().constData()); - if (!cfg_file.is_open()) - { - std::cout << "Error: Open config file SelectRects.txt" << std::endl; - return; - } - while (!cfg_file.eof()) - { - char tmp[256] = ""; - cfg_file.getline(tmp, 256); - QString line = QString::fromStdString(std::string(tmp)); - QStringList dataList = line.split(','); - if (dataList.length() == 4) - { - RectRatio m_RectRatio = RectRatio( - cv::Point2f(dataList[0].toFloat(),dataList[1].toFloat()), - cv::Point2f(dataList[2].toFloat(),dataList[3].toFloat()) - ); - g_display_label_conf[Num].RectVet[Cnt].push_back(m_RectRatio); - } - } - } -} -//双击NG + int Num = Num_Cnt >> 4; + int Cnt = Num_Cnt & 0x0f; + + std::lock_guard locker(g_display_label_conf[Num].lock); + if (g_display_label_conf[Num].Flag[Cnt] & DisplayLabel_Type_Bit) + { + g_display_label_conf[Num].Flag[Cnt] &= ~DisplayLabel_Type_Bit; + g_display_label_conf[Num].Flag[Cnt] &= ~DisplayLabel_Conf_Bit; + disconnect(display_lable_mat[Num][Cnt], SIGNAL(SignalmousePressEvent(QMouseEvent*)), this, SLOT(OnMouse(QMouseEvent*))); + disconnect(display_lable_mat[Num][Cnt], SIGNAL(SignalmouseMoveEvent(QMouseEvent*)), this, SLOT(OnMouse(QMouseEvent*))); + disconnect(display_lable_mat[Num][Cnt], SIGNAL(SignalmouseReleaseEvent(QMouseEvent*)), this, SLOT(OnMouse(QMouseEvent*))); + disconnect(display_lable_mat[Num][Cnt], SIGNAL(SignalkeyReleaseEvent(QKeyEvent*)), this, SLOT(OnKey(QKeyEvent*))); + } + else + { + g_display_label_conf[Num].Flag[Cnt] |= DisplayLabel_Type_Bit; + std::fstream cfg_file; + char buf[256]; + memset(buf, 0, 256); + sprintf(buf, SELECT_RECTS_FILE, Num, Cnt); + QString rects_file = g_conf_path.config_path + "/" + buf; + cfg_file.open(rects_file.toLocal8Bit().constData()); + if (!cfg_file.is_open()) + { + std::cout << "Error: Open config file SelectRects.txt" << std::endl; + return; + } + while (!cfg_file.eof()) + { + char tmp[256] = ""; + cfg_file.getline(tmp, 256); + QString line = QString::fromStdString(std::string(tmp)); + QStringList dataList = line.split(','); + if (dataList.length() == 4) + { + RectRatio m_RectRatio = RectRatio( + cv::Point2f(dataList[0].toFloat(), dataList[1].toFloat()), + cv::Point2f(dataList[2].toFloat(), dataList[3].toFloat()) + ); + g_display_label_conf[Num].RectVet[Cnt].push_back(m_RectRatio); + } + } + } +} +//鍙屽嚮NG void Cigarette::OnDBClickNGHub(int Num) { - emit sengMsgToClog("Double click NG."); - QDateTime now_ts = QDateTime::currentDateTime(); - std::ostringstream ostr; - QString file_path = g_conf_path.save_pics_path; + emit sengMsgToClog("Double click NG."); + QDateTime now_ts = QDateTime::currentDateTime(); + std::ostringstream ostr; + QString file_path = g_conf_path.save_pics_path; - std::replace(file_path.begin(), file_path.end(), '/', '\\'); - ostr << "explorer "<< file_path.toLocal8Bit().constData() << "\\ng\\" << (now_ts.toString("yyyy-MM-dd")).toStdString()<< "\\" << Num+1; - std::string str = ostr.str(); - //std::cout << "===>" << str << std::endl; - system(str.c_str()); + std::replace(file_path.begin(), file_path.end(), '/', '\\'); + ostr << "explorer " << file_path.toLocal8Bit().constData() << "\\ng\\" << (now_ts.toString("yyyy-MM-dd")).toStdString() << "\\" << Num + 1; + std::string str = ostr.str(); + //std::cout << "===>" << str << std::endl; + system(str.c_str()); } -void Cigarette::OnNotifyHub(int Num, int Cnt,cv::Mat m) +void Cigarette::OnNotifyHub(int Num, int Cnt, cv::Mat m) { - //将图像大小缩放为显示窗口大小 - cv::Size display_size = cv::Size(display_lable_mat[Num][Cnt]->width(), display_lable_mat[Num][Cnt]->height()); - cv::resize(m, m, display_size); + //灏嗗浘鍍忓ぇ灏忕缉鏀句负鏄剧ず绐楀彛澶у皬 + cv::Size display_size = cv::Size(display_lable_mat[Num][Cnt]->width(), display_lable_mat[Num][Cnt]->height()); + cv::resize(m, m, display_size); - QImage tempImage = Cigarette::cvMatToQImage(m); - display_lable_mat[Num][Cnt]->setPixmap(QPixmap::fromImage(tempImage)); - g_display_label_conf[Num].g_last_mat[Cnt] = m; + QImage tempImage = Cigarette::cvMatToQImage(m); + display_lable_mat[Num][Cnt]->setPixmap(QPixmap::fromImage(tempImage)); + g_display_label_conf[Num].g_last_mat[Cnt] = m; #ifdef __UDPSend - _UDPSendInfo UDPSendInfo; - UDPSendInfo.FrameID = image_frame; - UDPSendInfo.index = Num; - UDPSendInfo.cnt = Cnt; - UDPSendInfo.image = m.clone(); - UDP_Info_queue->put(UDPSendInfo); + _UDPSendInfo UDPSendInfo; + UDPSendInfo.FrameID = image_frame; + UDPSendInfo.index = Num; + UDPSendInfo.cnt = Cnt; + UDPSendInfo.image = m.clone(); + UDP_Info_queue->put(UDPSendInfo); #endif } void Cigarette::OnDisplayTimeCostHub(int Num, int ms) { - label_timecost_mat[Num]->setText(QString::number(ms) + "ms"); + label_timecost_mat[Num]->setText(QString::number(ms) + "ms"); #ifdef __ExportData - exportData[Num].detectTime = QString::number(ms) + "ms"; + exportData[Num].detectTime = QString::number(ms) + "ms"; #endif } void Cigarette::OnDisplayCheckNumberHub(int Num, long no) { - production_number[Num]++; - lcdNumber_total_mat[Num]->display(production_number[Num]); - //lcdNumber_total_mat[Num]->display(no); + production_number[Num]++; + lcdNumber_total_mat[Num]->display(production_number[Num]); + //lcdNumber_total_mat[Num]->display(no); #ifdef __UDPSend - _UDPSendInfo UDPSendInfo; - UDPSendInfo.FrameID = total_frame; - UDPSendInfo.index = Num; - UDPSendInfo.Total = production_number[Num]; - UDP_Info_queue->put(UDPSendInfo); + _UDPSendInfo UDPSendInfo; + UDPSendInfo.FrameID = total_frame; + UDPSendInfo.index = Num; + UDPSendInfo.Total = production_number[Num]; + UDP_Info_queue->put(UDPSendInfo); #endif #ifdef __ExportData - exportData[Num].checkNum = production_number[Num]; + exportData[Num].checkNum = production_number[Num]; #endif } void Cigarette::OnDisplayJdNoHub(int Num, QString jd_no) { - label_jd_no_mat[Num]->setText(jd_no); + label_jd_no_mat[Num]->setText(jd_no); #ifdef __ExportData - exportData[Num].cameraId = Num; - exportData[Num].jdNum = jd_no; + exportData[Num].cameraId = Num; + exportData[Num].jdNum = jd_no; #endif } void Cigarette::OnOKHub(int Num) { - ok[Num]++; + ok[Num]++; #ifdef __UDPSend - _UDPSendInfo UDPSendInfo; - UDPSendInfo.FrameID = ok_frame; - UDPSendInfo.index = Num; - UDPSendInfo.ok[Num] = ok[Num]; - UDP_Info_queue->put(UDPSendInfo); -#endif - lcdNumber_ok_mat[Num]->display(ok[Num]); - label_reslut_mat[Num]->setText("OK"); - label_reslut_mat[Num]->setStyleSheet(tr("background-color: rgb(0, 255, 0);")); + _UDPSendInfo UDPSendInfo; + UDPSendInfo.FrameID = ok_frame; + UDPSendInfo.index = Num; + UDPSendInfo.ok[Num] = ok[Num]; + UDP_Info_queue->put(UDPSendInfo); +#endif + lcdNumber_ok_mat[Num]->display(ok[Num]); + label_reslut_mat[Num]->setText("OK"); + label_reslut_mat[Num]->setStyleSheet(tr("background-color: rgb(0, 255, 0);")); #ifdef __ExportData - exportData[Num].okNum = ok[Num]; + exportData[Num].okNum = ok[Num]; #endif } void Cigarette::OnNGHub(int Num) { - ng[Num]++; + ng[Num]++; #ifdef __UDPSend - _UDPSendInfo UDPSendInfo; - UDPSendInfo.FrameID = ng_frame; - UDPSendInfo.index = Num; - UDPSendInfo.ng[Num] = ng[Num]; - UDP_Info_queue->put(UDPSendInfo); -#endif - lcdNumber_ng_mat[Num]->display(ng[Num]); - label_reslut_mat[Num]->setText("NG"); - label_reslut_mat[Num]->setStyleSheet(tr("background-color: rgb(255, 0, 0);")); + _UDPSendInfo UDPSendInfo; + UDPSendInfo.FrameID = ng_frame; + UDPSendInfo.index = Num; + UDPSendInfo.ng[Num] = ng[Num]; + UDP_Info_queue->put(UDPSendInfo); +#endif + lcdNumber_ng_mat[Num]->display(ng[Num]); + label_reslut_mat[Num]->setText("NG"); + label_reslut_mat[Num]->setStyleSheet(tr("background-color: rgb(255, 0, 0);")); #ifdef __ExportData - exportData[Num].ngNum = ng[Num]; + exportData[Num].ngNum = ng[Num]; #endif } void Cigarette::updateStatisticsHub(const QString& statisticalData, int Num) { - label_cap_speed_mat[Num]->setText(statisticalData + QStringLiteral("个/秒")); + label_cap_speed_mat[Num]->setText(statisticalData + QStringLiteral("涓/绉")); #ifdef __UDPSend - _UDPSendInfo UDPSendInfo; - UDPSendInfo.FrameID = speed_frame; - UDPSendInfo.index = Num; - UDPSendInfo.speed = statisticalData; - UDP_Info_queue->put(UDPSendInfo); + _UDPSendInfo UDPSendInfo; + UDPSendInfo.FrameID = speed_frame; + UDPSendInfo.index = Num; + UDPSendInfo.speed = statisticalData; + UDP_Info_queue->put(UDPSendInfo); #endif #ifdef __ExportData - exportData[Num].acquisitionTime = statisticalData + QStringLiteral("个/秒"); + exportData[Num].acquisitionTime = statisticalData + QStringLiteral("涓/绉"); #endif } -//不剔除模式 +//涓嶅墧闄ゆā寮 void Cigarette::on_checkBox_unkick_clicked(bool checked) { - if (!g_admin_mode) - { - if (!g_op_mode) - { - emit sengMsgToClog("Start to login in."); - dialogin = new Dialogin(this); - connect(dialogin, SIGNAL(enter_op()), this, SLOT(OnOp())); - dialogin->setModal(true); - dialogin->show(); - dialogin->move((this->width() - dialogin->width()) / 2, (this->height() - dialogin->height()) / 2); - ui.checkBox_unkick->setChecked(false); - int ret = m_PLCDevice->write_bit_2_plc( g_modbus_conf.no_kick, 0); + if (!g_admin_mode) + { + if (!g_op_mode) + { + emit sengMsgToClog("Start to login in."); + dialogin = new Dialogin(this); + connect(dialogin, SIGNAL(enter_op()), this, SLOT(OnOp())); + dialogin->setModal(true); + dialogin->show(); + dialogin->move((this->width() - dialogin->width()) / 2, (this->height() - dialogin->height()) / 2); + ui.checkBox_unkick->setChecked(false); + int ret = m_PLCDevice->write_bit_2_plc(g_modbus_conf.no_kick, 0); #ifdef __UDPSend - sThread.sendData("UnKickOk", g_sys_conf.FeedbackPort); -#endif - return; - } - ui.checkBox_unkick->setChecked(false); - } - if (m_PLCDevice->g_plc_ok) { - if (checked) - { - emit sengMsgToClog("Enter unkick mode."); - int ret = m_PLCDevice->write_bit_2_plc( g_modbus_conf.no_kick, 1); + sThread.sendData("UnKickOk", g_sys_conf.FeedbackPort); +#endif + return; + } + ui.checkBox_unkick->setChecked(false); + } + if (m_PLCDevice->g_plc_ok) { + if (checked) + { + emit sengMsgToClog("Enter unkick mode."); + int ret = m_PLCDevice->write_bit_2_plc(g_modbus_conf.no_kick, 1); #ifdef __UDPSend - sThread.sendData("UnKickOk", g_sys_conf.FeedbackPort); + sThread.sendData("UnKickOk", g_sys_conf.FeedbackPort); #endif - } - else - { - emit sengMsgToClog("Exit unkick mode."); - int ret = m_PLCDevice->write_bit_2_plc( g_modbus_conf.no_kick, 0); + } + else + { + emit sengMsgToClog("Exit unkick mode."); + int ret = m_PLCDevice->write_bit_2_plc(g_modbus_conf.no_kick, 0); #ifdef __UDPSend - sThread.sendData("KickOk", g_sys_conf.FeedbackPort); -#endif - } - ui.checkBox_unkick->setChecked(checked); - } - else { - ui.checkBox_unkick->setChecked(false); - emit sengMsgToClog("Enter or exit unkick mode fail."); + sThread.sendData("KickOk", g_sys_conf.FeedbackPort); +#endif + } + ui.checkBox_unkick->setChecked(checked); + } + else { + ui.checkBox_unkick->setChecked(false); + emit sengMsgToClog("Enter or exit unkick mode fail."); #ifdef __UDPSend - sThread.sendData("UnKickFail", g_sys_conf.FeedbackPort); + sThread.sendData("UnKickFail", g_sys_conf.FeedbackPort); #endif - } + } } -//调试模式 +//璋冭瘯妯″紡 void Cigarette::on_checkBox_debug_clicked(bool checked) { - if (!g_admin_mode) - { - QMessageBox::information(NULL, QStringLiteral("权限检查 "), QStringLiteral("请先点击解锁按钮,进入管理员模式"), QMessageBox::Ok); - ui.checkBox_debug->setChecked(false); - return; - } - if (checked) //启用相机调试模式 - { - if (g_working) - { - QMessageBox::information(NULL, QStringLiteral("操作顺序检查 "), QStringLiteral("请先点击‘停止工作’按钮,才能进入调试模式"), QMessageBox::Ok); - ui.checkBox_debug->setChecked(false); - //return; - } - else - { - emit sengMsgToClog("Enter debug mode."); - EnableDebugMode(); - ui.checkBox_debug->setChecked(true); + if (!g_admin_mode) + { + QMessageBox::information(NULL, QStringLiteral("鏉冮檺妫鏌 "), QStringLiteral("璇峰厛鐐瑰嚮瑙i攣鎸夐挳锛岃繘鍏ョ鐞嗗憳妯″紡"), QMessageBox::Ok); + ui.checkBox_debug->setChecked(false); + return; + } + if (checked) //鍚敤鐩告満璋冭瘯妯″紡 + { + if (g_working) + { + QMessageBox::information(NULL, QStringLiteral("鎿嶄綔椤哄簭妫鏌 "), QStringLiteral("璇峰厛鐐瑰嚮鈥樺仠姝㈠伐浣溾欐寜閽紝鎵嶈兘杩涘叆璋冭瘯妯″紡"), QMessageBox::Ok); + ui.checkBox_debug->setChecked(false); + //return; + } + else + { + emit sengMsgToClog("Enter debug mode."); + EnableDebugMode(); + ui.checkBox_debug->setChecked(true); #ifdef __UDPSend - sThread.sendData("DebugEn", g_sys_conf.FeedbackPort); -#endif - } - } - else //关闭相机调试 - { - emit sengMsgToClog("Exit debug mode."); - DisableDebugMode(); - //on_pushButton_clear_released(); //换班 - ui.checkBox_debug->setChecked(false); - //ui.checkBox_debug->setEnabled(true); + sThread.sendData("DebugEn", g_sys_conf.FeedbackPort); +#endif + } + } + else //鍏抽棴鐩告満璋冭瘯 + { + emit sengMsgToClog("Exit debug mode."); + DisableDebugMode(); + //on_pushButton_clear_released(); //鎹㈢彮 + ui.checkBox_debug->setChecked(false); + //ui.checkBox_debug->setEnabled(true); #ifdef __UDPSend - sThread.sendData("DebugDis", g_sys_conf.FeedbackPort); + sThread.sendData("DebugDis", g_sys_conf.FeedbackPort); #endif - } + } } void Cigarette::on_pushButton_wintab_clicked(bool checked) { - INPUT inputs[4] = {}; - ZeroMemory(inputs, sizeof(inputs)); + INPUT inputs[4] = {}; + ZeroMemory(inputs, sizeof(inputs)); - inputs[0].type = INPUT_KEYBOARD; - inputs[0].ki.wVk = VK_LWIN; + inputs[0].type = INPUT_KEYBOARD; + inputs[0].ki.wVk = VK_LWIN; - inputs[1].type = INPUT_KEYBOARD; - inputs[1].ki.wVk = VK_TAB; + inputs[1].type = INPUT_KEYBOARD; + inputs[1].ki.wVk = VK_TAB; - inputs[2].type = INPUT_KEYBOARD; - inputs[2].ki.wVk = VK_TAB; - inputs[2].ki.dwFlags = KEYEVENTF_KEYUP; + inputs[2].type = INPUT_KEYBOARD; + inputs[2].ki.wVk = VK_TAB; + inputs[2].ki.dwFlags = KEYEVENTF_KEYUP; - inputs[3].type = INPUT_KEYBOARD; - inputs[3].ki.wVk = VK_LWIN; - inputs[3].ki.dwFlags = KEYEVENTF_KEYUP; + inputs[3].type = INPUT_KEYBOARD; + inputs[3].ki.wVk = VK_LWIN; + inputs[3].ki.dwFlags = KEYEVENTF_KEYUP; - UINT uSent = SendInput(ARRAYSIZE(inputs), inputs, sizeof(INPUT)); - if (uSent != ARRAYSIZE(inputs)) - { - qDebug() << "SendInput failed" << HRESULT_FROM_WIN32(GetLastError()); - } + UINT uSent = SendInput(ARRAYSIZE(inputs), inputs, sizeof(INPUT)); + if (uSent != ARRAYSIZE(inputs)) + { + qDebug() << "SendInput failed" << HRESULT_FROM_WIN32(GetLastError()); + } } -//打开PLC配置对话框 +//鎵撳紑PLC閰嶇疆瀵硅瘽妗 void Cigarette::on_toolButton_plc_released() { - emit sengMsgToClog("Open PLC setting."); - if (m_PLCDevice->g_plc_ok) - { - if (g_admin_mode) - { - g_plc_dialog_open = true; - dialog_plc_setup = new PlcSetup(this); - dialog_plc_setup->setModal(true); - dialog_plc_setup->show(); - dialog_plc_setup->move((this->width() - dialog_plc_setup->width()) / 2, (this->height() - dialog_plc_setup->height()) / 2); - } - else { - QMessageBox::information(NULL, QStringLiteral("权限检查"), QStringLiteral("请先点击解锁按钮,进入管理员模式"), QMessageBox::Ok); - } - } - else { - QMessageBox::information(NULL, QStringLiteral("硬件问题"), QStringLiteral("请先确保PLC连接成功,再进入PLC设置"), QMessageBox::Ok); - } -} - -//操作员权限剩余时间 + emit sengMsgToClog("Open PLC setting."); + if (m_PLCDevice->g_plc_ok) + { + if (g_admin_mode) + { + g_plc_dialog_open = true; + dialog_plc_setup = new PlcSetup(this); + dialog_plc_setup->setModal(true); + dialog_plc_setup->show(); + dialog_plc_setup->move((this->width() - dialog_plc_setup->width()) / 2, (this->height() - dialog_plc_setup->height()) / 2); + } + else { + QMessageBox::information(NULL, QStringLiteral("鏉冮檺妫鏌"), QStringLiteral("璇峰厛鐐瑰嚮瑙i攣鎸夐挳锛岃繘鍏ョ鐞嗗憳妯″紡"), QMessageBox::Ok); + } + } + else { + QMessageBox::information(NULL, QStringLiteral("纭欢闂"), QStringLiteral("璇峰厛纭繚PLC杩炴帴鎴愬姛锛屽啀杩涘叆PLC璁剧疆"), QMessageBox::Ok); + } +} + +//鎿嶄綔鍛樻潈闄愬墿浣欐椂闂 void Cigarette::op_timeout() { - g_op_time--; - ui.label_12->setText(QString::number(g_op_time)); - if (0 == g_op_time) - { - g_op_mode = false; - ui.label_12->setText(QStringLiteral("登录用户:")); - ui.label_role->setText(QStringLiteral("未登录")); - m_op_delay->stop(); - } -} - -//管理员权限剩余时间 + g_op_time--; + ui.label_12->setText(QString::number(g_op_time)); + if (0 == g_op_time) + { + g_op_mode = false; + ui.label_12->setText(QStringLiteral("鐧诲綍鐢ㄦ埛锛")); + ui.label_role->setText(QStringLiteral("鏈櫥褰")); + m_op_delay->stop(); + } +} + +//绠$悊鍛樻潈闄愬墿浣欐椂闂 void Cigarette::admin_timeout() { - g_admin_time--; - ui.label_12->setText(QString::number(g_admin_time)); - if (0 == g_admin_time) - { - on_btn_lock_released(); - } + g_admin_time--; + ui.label_12->setText(QString::number(g_admin_time)); + if (0 == g_admin_time) + { + on_btn_lock_released(); + } } void Cigarette::handleTimeout() { - QDateTime ts_start = QDateTime::currentDateTime(); - QTime time = QTime::currentTime(); - QDateTime local(ts_start); - QString localTime = local.toString("yyyy-MM-dd hh:mm:ss"); - ui.label_cur_time->setText(localTime); - - qint64 intervalTime = g_ts_start.secsTo(ts_start); - int days = (intervalTime) / (24 * 3600); - int hours = (intervalTime) % (24 * 3600) / 3600; - int minutes = (intervalTime) % 3600 / 60; - int second = (intervalTime) % 60; - - QString run_stat = QString(QStringLiteral("运行%1天%2时%3分%4秒")) - .arg(days).arg(hours).arg(minutes).arg(second); - ui.label_run_stat->setText(run_stat); - int Kick[NumberOfSupportedCameras] = { 0 }; - - if (m_PLCDevice->g_plc_ok) - { - if (!g_plc_dialog_open) //PLC配置对话框没有打开 - { - //当班产量(从配置的PLC地址中读取) - if (g_modbus_conf.quantity > 0) - { - // 读取剔除值 - for (int i = 0; i < NumberOfSupportedCameras; i++) { + QDateTime ts_start = QDateTime::currentDateTime(); + QTime time = QTime::currentTime(); + QDateTime local(ts_start); + QString localTime = local.toString("yyyy-MM-dd hh:mm:ss"); + ui.label_cur_time->setText(localTime); + + qint64 intervalTime = g_ts_start.secsTo(ts_start); + int days = (intervalTime) / (24 * 3600); + int hours = (intervalTime) % (24 * 3600) / 3600; + int minutes = (intervalTime) % 3600 / 60; + int second = (intervalTime) % 60; + + QString run_stat = QString(QStringLiteral("杩愯%1澶%2鏃%3鍒%4绉")) + .arg(days).arg(hours).arg(minutes).arg(second); + ui.label_run_stat->setText(run_stat); + int Kick[NumberOfSupportedCameras] = { 0 }; + + if (m_PLCDevice->g_plc_ok) + { + if (!g_plc_dialog_open) //PLC閰嶇疆瀵硅瘽妗嗘病鏈夋墦寮 + { + //褰撶彮浜ч噺锛堜粠閰嶇疆鐨凱LC鍦板潃涓鍙栵級 + if (g_modbus_conf.quantity > 0) + { + // 璇诲彇鍓旈櫎鍊 + for (int i = 0; i < NumberOfSupportedCameras; i++) { #if defined(NumberOfSupportedCameras) && (NumberOfSupportedCameras > i) - if (g_modbus_conf.kick[i] > 0) { - uint16_t dest16[2]; - int ret = m_PLCDevice->read_short_from_plc(g_modbus_conf.kick[i], 2, dest16); - if (ret == 2) { - Kick[i] = dest16[0] + (dest16[1] << 16); - lcdNumber_kick_mat[i]->display(dest16[0] + (dest16[1] << 16)); + if (g_modbus_conf.kick[i] > 0) { + uint16_t dest16[2]; + int ret = m_PLCDevice->read_short_from_plc(g_modbus_conf.kick[i], 2, dest16); + if (ret == 2) { + Kick[i] = dest16[0] + (dest16[1] << 16); + lcdNumber_kick_mat[i]->display(dest16[0] + (dest16[1] << 16)); #ifdef __UDPSend - _UDPSendInfo UDPSendInfo; - UDPSendInfo.FrameID = kick_frame; - UDPSendInfo.index = i; - UDPSendInfo.Kick[UDPSendInfo.index] = dest16[0] + (dest16[1] << 16); - UDP_Info_queue->put(UDPSendInfo); + _UDPSendInfo UDPSendInfo; + UDPSendInfo.FrameID = kick_frame; + UDPSendInfo.index = i; + UDPSendInfo.Kick[UDPSendInfo.index] = dest16[0] + (dest16[1] << 16); + UDP_Info_queue->put(UDPSendInfo); #endif #ifdef __ExportData - exportData[i].kick = dest16[0] + (dest16[1] << 16); + exportData[i].kick = dest16[0] + (dest16[1] << 16); #endif - } - } + } + } #endif - } + } - // 读取产量值 - uint16_t dest16[2]; - int ret = m_PLCDevice->read_short_from_plc(g_modbus_conf.quantity, 2, dest16); - if (ret == 2) - { - int cur_quantity = dest16[0] + (dest16[1] << 16); - ui.lcdNumber_total_no->display(cur_quantity); + // 璇诲彇浜ч噺鍊 + uint16_t dest16[2]; + int ret = m_PLCDevice->read_short_from_plc(g_modbus_conf.quantity, 2, dest16); + if (ret == 2) + { + int cur_quantity = dest16[0] + (dest16[1] << 16); + ui.lcdNumber_total_no->display(cur_quantity); #ifdef __UDPSend - sThread.sendData("total_" + QString::number(cur_quantity), g_sys_conf.FeedbackPort); - sThread.sendData("totallast_" + QString::number(ui.lcdNumber_total_no_last->intValue()), g_sys_conf.FeedbackPort); -#endif - ui.label_plc->setText(QStringLiteral("PLC在线")); - ui.label_plc->setStyleSheet(tr("background-color: rgb(0, 170, 0);")); - if (!(m_PLCDevice->g_plc_status & 0x01)) - { - init_plc_value(); - if (g_working) - { - if (g_debug_mode) - { - QMessageBox::information(NULL, QStringLiteral("操作顺序检查"), QStringLiteral("请先点击“调试模式”复选框,取消调试模式,才可以开始工作"), QMessageBox::Ok); - return; - } - start_work(); - } - else if (!g_working) - { - pause_work(); - } - m_PLCDevice->g_plc_status |= (0x01); - } - //自动换班 - if (g_sys_conf.auto_shift && g_working) - { - g_seconds++; - if (g_seconds % 10 == 0) - { - if (cur_quantity == g_lst_quantiy) - { - quantity_stop_count++; - } - else { - quantity_stop_count = 0; - } - if (quantity_stop_count == STOP_SECONDS) //触发一次换班 - { - g_op_mode = true; //激活操作员模式 - on_btn_pause_released(); //停止工作 - on_pushButton_clear_released(); //换班 - on_btn_start_released(); //开始 - g_op_mode = false; //退出操作员模式 - } - g_lst_quantiy = cur_quantity; - } - } - else if (g_sys_conf.timing_shift && g_working) - { - qint64 secA = time.secsTo(g_sys_conf.shiftA); - qint64 secB = time.secsTo(g_sys_conf.shiftB); - qint64 secC = time.secsTo(g_sys_conf.shiftC); - if (secA == 0) - { - g_op_mode = true; //激活操作员模式 - on_btn_pause_released(); //停止工作 - record_output_statistic(cur_quantity, Kick, 0); - on_pushButton_clear_released(); //换班 - on_btn_start_released(); //开始 - g_op_mode = false; //退出操作员模式 - } - else if (secB == 0) - { - g_op_mode = true; //激活操作员模式 - on_btn_pause_released(); //停止工作 - record_output_statistic(cur_quantity, Kick, 1); - on_pushButton_clear_released(); //换班 - on_btn_start_released(); //开始 - g_op_mode = false; //退出操作员模式 - } - else if (secC == 0) - { - g_op_mode = true; //激活操作员模式 - on_btn_pause_released(); //停止工作 - record_output_statistic(cur_quantity, Kick, 2); - on_pushButton_clear_released(); //换班 - on_btn_start_released(); //开始 - g_op_mode = false; //退出操作员模式 - } - } - } - else - { - ui.label_plc->setText(QStringLiteral("PLC断开")); - ui.label_plc->setStyleSheet(tr("background-color: rgb(255, 255, 0);")); - m_PLCDevice->g_plc_status &= ~(0x01); - } - } - } - } - //相机掉线检测 + sThread.sendData("total_" + QString::number(cur_quantity), g_sys_conf.FeedbackPort); + sThread.sendData("totallast_" + QString::number(ui.lcdNumber_total_no_last->intValue()), g_sys_conf.FeedbackPort); +#endif + ui.label_plc->setText(QStringLiteral("PLC鍦ㄧ嚎")); + ui.label_plc->setStyleSheet(tr("background-color: rgb(0, 170, 0);")); + if (!(m_PLCDevice->g_plc_status & 0x01)) + { + init_plc_value(); + if (g_working) + { + if (g_debug_mode) + { + QMessageBox::information(NULL, QStringLiteral("鎿嶄綔椤哄簭妫鏌"), QStringLiteral("璇峰厛鐐瑰嚮鈥滆皟璇曟ā寮忊濆閫夋锛屽彇娑堣皟璇曟ā寮忥紝鎵嶅彲浠ュ紑濮嬪伐浣"), QMessageBox::Ok); + return; + } + start_work(); + } + else if (!g_working) + { + pause_work(); + } + m_PLCDevice->g_plc_status |= (0x01); + } + //鑷姩鎹㈢彮 + if (g_sys_conf.auto_shift && g_working) + { + g_seconds++; + if (g_seconds % 10 == 0) + { + if (cur_quantity == g_lst_quantiy) + { + quantity_stop_count++; + } + else { + quantity_stop_count = 0; + } + if (quantity_stop_count == STOP_SECONDS) //瑙﹀彂涓娆℃崲鐝 + { + g_op_mode = true; //婵娲绘搷浣滃憳妯″紡 + on_btn_pause_released(); //鍋滄宸ヤ綔 + on_pushButton_clear_released(); //鎹㈢彮 + on_btn_start_released(); //寮濮 + g_op_mode = false; //閫鍑烘搷浣滃憳妯″紡 + } + g_lst_quantiy = cur_quantity; + } + } + else if (g_sys_conf.timing_shift && g_working) + { + qint64 secA = time.secsTo(g_sys_conf.shiftA); + qint64 secB = time.secsTo(g_sys_conf.shiftB); + qint64 secC = time.secsTo(g_sys_conf.shiftC); + if (secA == 0) + { + g_op_mode = true; //婵娲绘搷浣滃憳妯″紡 + on_btn_pause_released(); //鍋滄宸ヤ綔 + record_output_statistic(cur_quantity, Kick, 0); + on_pushButton_clear_released(); //鎹㈢彮 + on_btn_start_released(); //寮濮 + g_op_mode = false; //閫鍑烘搷浣滃憳妯″紡 + } + else if (secB == 0) + { + g_op_mode = true; //婵娲绘搷浣滃憳妯″紡 + on_btn_pause_released(); //鍋滄宸ヤ綔 + record_output_statistic(cur_quantity, Kick, 1); + on_pushButton_clear_released(); //鎹㈢彮 + on_btn_start_released(); //寮濮 + g_op_mode = false; //閫鍑烘搷浣滃憳妯″紡 + } + else if (secC == 0) + { + g_op_mode = true; //婵娲绘搷浣滃憳妯″紡 + on_btn_pause_released(); //鍋滄宸ヤ綔 + record_output_statistic(cur_quantity, Kick, 2); + on_pushButton_clear_released(); //鎹㈢彮 + on_btn_start_released(); //寮濮 + g_op_mode = false; //閫鍑烘搷浣滃憳妯″紡 + } + } + } + else + { + ui.label_plc->setText(QStringLiteral("PLC鏂紑")); + ui.label_plc->setStyleSheet(tr("background-color: rgb(255, 255, 0);")); + m_PLCDevice->g_plc_status &= ~(0x01); + } + } + } + } + //鐩告満鎺夌嚎妫娴 #if defined(NumberOfSupportedCameras) && (NumberOfSupportedCameras>0) - if (SingleCamInfo[0].OffLine) //1#相机掉线 - { - //SingleCamInfo[0] = false; - ui.cam_status_1->setStyleSheet(tr("background-color: rgb(255, 255, 0);")); - ui.cam_work_1->setStyleSheet(tr("background-color: rgb(255, 255, 0);")); - ui.toolButton_cam_1->setStyleSheet(tr("border-image: url(:/Cigarette/Resources/cam1_no.png);")); - ui.label_reslut_1->setVisible(true); - if (g_modbus_conf.alarm > 0) - { - uint16_t dest16[2] = {5,0}; - int ret = m_PLCDevice->write_short_2_plc(g_modbus_conf.alarm, 2, dest16); - if (ret > 0) SingleCamInfo[0].OffLine = false; - } - } + if (SingleCamInfo[0].OffLine) //1#鐩告満鎺夌嚎 + { + //SingleCamInfo[0] = false; + ui.cam_status_1->setStyleSheet(tr("background-color: rgb(255, 255, 0);")); + ui.cam_work_1->setStyleSheet(tr("background-color: rgb(255, 255, 0);")); + ui.toolButton_cam_1->setStyleSheet(tr("border-image: url(:/Cigarette/Resources/cam1_no.png);")); + ui.label_reslut_1->setVisible(true); + if (g_modbus_conf.alarm > 0) + { + uint16_t dest16[2] = { 5,0 }; + int ret = m_PLCDevice->write_short_2_plc(g_modbus_conf.alarm, 2, dest16); + if (ret > 0) SingleCamInfo[0].OffLine = false; + } + work_camera_nums--; + } #endif #if defined(NumberOfSupportedCameras) && (NumberOfSupportedCameras>1) - if (SingleCamInfo[1].OffLine) //2#相机掉线 - { - //SingleCamInfo[1] = false; - ui.cam_status_2->setStyleSheet(tr("background-color: rgb(255, 255, 0);")); - ui.cam_work_2->setStyleSheet(tr("background-color: rgb(255, 255, 0);")); - ui.toolButton_cam_2->setStyleSheet(tr("border-image: url(:/Cigarette/Resources/cam2_no.png);")); - ui.label_reslut_2->setVisible(true); - if (g_modbus_conf.alarm > 0) - { - uint16_t dest16[2] = {6,0}; - int ret = m_PLCDevice->write_short_2_plc(g_modbus_conf.alarm, 2, dest16); - if(ret > 0) SingleCamInfo[1].OffLine = false; - } - } + if (SingleCamInfo[1].OffLine) //2#鐩告満鎺夌嚎 + { + //SingleCamInfo[1] = false; + ui.cam_status_2->setStyleSheet(tr("background-color: rgb(255, 255, 0);")); + ui.cam_work_2->setStyleSheet(tr("background-color: rgb(255, 255, 0);")); + ui.toolButton_cam_2->setStyleSheet(tr("border-image: url(:/Cigarette/Resources/cam2_no.png);")); + ui.label_reslut_2->setVisible(true); + if (g_modbus_conf.alarm > 0) + { + uint16_t dest16[2] = { 6,0 }; + int ret = m_PLCDevice->write_short_2_plc(g_modbus_conf.alarm, 2, dest16); + if (ret > 0) SingleCamInfo[1].OffLine = false; + } + work_camera_nums--; + } #endif #if defined(NumberOfSupportedCameras) && (NumberOfSupportedCameras>2) - if (SingleCamInfo[2].OffLine) //3#相机掉线 - { - //SingleCamInfo[2] = false; - ui.cam_status_3->setStyleSheet(tr("background-color: rgb(255, 255, 0);")); - ui.cam_work_3->setStyleSheet(tr("background-color: rgb(255, 255, 0);")); - ui.toolButton_cam_3->setStyleSheet(tr("border-image: url(:/Cigarette/Resources/cam3_no.png);")); - ui.label_reslut_3->setVisible(true); - if (g_modbus_conf.alarm > 0) - { - uint16_t dest16[2] = { 7,0 }; - int ret = m_PLCDevice->write_short_2_plc(g_modbus_conf.alarm, 2, dest16); - if (ret > 0) SingleCamInfo[2].OffLine = false; - } - } + if (SingleCamInfo[2].OffLine) //3#鐩告満鎺夌嚎 + { + //SingleCamInfo[2] = false; + ui.cam_status_3->setStyleSheet(tr("background-color: rgb(255, 255, 0);")); + ui.cam_work_3->setStyleSheet(tr("background-color: rgb(255, 255, 0);")); + ui.toolButton_cam_3->setStyleSheet(tr("border-image: url(:/Cigarette/Resources/cam3_no.png);")); + ui.label_reslut_3->setVisible(true); + if (g_modbus_conf.alarm > 0) + { + uint16_t dest16[2] = { 7,0 }; + int ret = m_PLCDevice->write_short_2_plc(g_modbus_conf.alarm, 2, dest16); + if (ret > 0) SingleCamInfo[2].OffLine = false; + } + work_camera_nums--; + } #endif #if defined(NumberOfSupportedCameras) && (NumberOfSupportedCameras>3) - if (SingleCamInfo[3].OffLine) //4#相机掉线 - { - //SingleCamInfo[3] = false; - ui.cam_status_4->setStyleSheet(tr("background-color: rgb(255, 255, 0);")); - ui.cam_work_4->setStyleSheet(tr("background-color: rgb(255, 255, 0);")); - ui.toolButton_cam_4->setStyleSheet(tr("border-image: url(:/Cigarette/Resources/cam4_no.png);")); - ui.label_reslut_4->setVisible(true); - if (g_modbus_conf.alarm > 0) - { - uint16_t dest16[2] = { 8,0 }; - int ret = m_PLCDevice->write_short_2_plc(g_modbus_conf.alarm, 2, dest16); - if (ret > 0) SingleCamInfo[3].OffLine = false; - } - } + if (SingleCamInfo[3].OffLine) //4#鐩告満鎺夌嚎 + { + //SingleCamInfo[3] = false; + ui.cam_status_4->setStyleSheet(tr("background-color: rgb(255, 255, 0);")); + ui.cam_work_4->setStyleSheet(tr("background-color: rgb(255, 255, 0);")); + ui.toolButton_cam_4->setStyleSheet(tr("border-image: url(:/Cigarette/Resources/cam4_no.png);")); + ui.label_reslut_4->setVisible(true); + if (g_modbus_conf.alarm > 0) + { + uint16_t dest16[2] = { 8,0 }; + int ret = m_PLCDevice->write_short_2_plc(g_modbus_conf.alarm, 2, dest16); + if (ret > 0) SingleCamInfo[3].OffLine = false; + } + work_camera_nums--; + } #endif #if defined(NumberOfSupportedCameras) && (NumberOfSupportedCameras>4) - if (SingleCamInfo[4].OffLine) //5#相机掉线 - { - //SingleCamInfo[4] = false; - ui.cam_status_5->setStyleSheet(tr("background-color: rgb(255, 255, 0);")); - ui.cam_work_5->setStyleSheet(tr("background-color: rgb(255, 255, 0);")); - ui.toolButton_cam_5->setStyleSheet(tr("border-image: url(:/Cigarette/Resources/cam5_no.png);")); - ui.label_reslut_5->setVisible(true); - if (g_modbus_conf.alarm > 0) - { - uint16_t dest16[2] = { 9,0 }; - int ret = m_PLCDevice->write_short_2_plc(g_modbus_conf.alarm, 2, dest16); - if (ret > 0) SingleCamInfo[4].OffLine = false; - } - } + if (SingleCamInfo[4].OffLine) //5#鐩告満鎺夌嚎 + { + //SingleCamInfo[4] = false; + ui.cam_status_5->setStyleSheet(tr("background-color: rgb(255, 255, 0);")); + ui.cam_work_5->setStyleSheet(tr("background-color: rgb(255, 255, 0);")); + ui.toolButton_cam_5->setStyleSheet(tr("border-image: url(:/Cigarette/Resources/cam5_no.png);")); + ui.label_reslut_5->setVisible(true); + if (g_modbus_conf.alarm > 0) + { + uint16_t dest16[2] = { 9,0 }; + int ret = m_PLCDevice->write_short_2_plc(g_modbus_conf.alarm, 2, dest16); + if (ret > 0) SingleCamInfo[4].OffLine = false; + } + work_camera_nums--; + } #endif #if defined(NumberOfSupportedCameras) && (NumberOfSupportedCameras>5) - if (SingleCamInfo[5].OffLine) //6#相机掉线 - { - //SingleCamInfo[5] = false; - ui.cam_status_6->setStyleSheet(tr("background-color: rgb(255, 255, 0);")); - ui.cam_work_6->setStyleSheet(tr("background-color: rgb(255, 255, 0);")); - ui.toolButton_cam_6->setStyleSheet(tr("border-image: url(:/Cigarette/Resources/cam6_no.png);")); - ui.label_reslut_6->setVisible(true); - if (g_modbus_conf.alarm > 0) - { - uint16_t dest16[2] = { 10,0 }; - int ret = m_PLCDevice->write_short_2_plc(g_modbus_conf.alarm, 2, dest16); - if (ret > 0) SingleCamInfo[5].OffLine = false; - } - } + if (SingleCamInfo[5].OffLine) //6#鐩告満鎺夌嚎 + { + //SingleCamInfo[5] = false; + ui.cam_status_6->setStyleSheet(tr("background-color: rgb(255, 255, 0);")); + ui.cam_work_6->setStyleSheet(tr("background-color: rgb(255, 255, 0);")); + ui.toolButton_cam_6->setStyleSheet(tr("border-image: url(:/Cigarette/Resources/cam6_no.png);")); + ui.label_reslut_6->setVisible(true); + if (g_modbus_conf.alarm > 0) + { + uint16_t dest16[2] = { 10,0 }; + int ret = m_PLCDevice->write_short_2_plc(g_modbus_conf.alarm, 2, dest16); + if (ret > 0) SingleCamInfo[5].OffLine = false; + } + work_camera_nums--; + } #endif #if defined(NumberOfSupportedCameras) && (NumberOfSupportedCameras>6) - if (SingleCamInfo[6].OffLine) //7#相机掉线 - { - //SingleCamInfo[6] = false; - ui.cam_status_7->setStyleSheet(tr("background-color: rgb(255, 255, 0);")); - ui.cam_work_7->setStyleSheet(tr("background-color: rgb(255, 255, 0);")); - ui.toolButton_cam_7->setStyleSheet(tr("border-image: url(:/Cigarette/Resources/cam7_no.png);")); - ui.label_reslut_7->setVisible(true); - if (g_modbus_conf.alarm > 0) - { - uint16_t dest16[2] = { 11,0 }; - int ret = m_PLCDevice->write_short_2_plc(g_modbus_conf.alarm, 2, dest16); - if (ret > 0) SingleCamInfo[6].OffLine = false; - } - } -#endif -#if defined(NumberOfSupportedCameras) && (NumberOfSupportedCameras>7) - if (SingleCamInfo[7].OffLine) //8#相机掉线 - { - //SingleCamInfo[7] = false; - ui.cam_status_8->setStyleSheet(tr("background-color: rgb(255, 255, 0);")); - ui.cam_work_8->setStyleSheet(tr("background-color: rgb(255, 255, 0);")); - ui.toolButton_cam_8->setStyleSheet(tr("border-image: url(:/Cigarette/Resources/cam8_no.png);")); - ui.label_reslut_8->setVisible(true); - if (g_modbus_conf.alarm > 0) - { - uint16_t dest16[2] = { 12,0 }; - int ret = m_PLCDevice->write_short_2_plc(g_modbus_conf.alarm, 2, dest16); - if (ret > 0) SingleCamInfo[7].OffLine = false; - } - } -#endif - - //读取报警信息 - if (m_PLCDevice->g_plc_ok) - { - if (!g_plc_dialog_open) //PLC配置对话框没有打开 - { - if (g_modbus_conf.alarm > 0) - { - uint16_t dest16[2]; - int ret = m_PLCDevice->read_short_from_plc( g_modbus_conf.alarm, 2, dest16); - if (ret>0) - { - AlarmInfo alarm_info; - alarm_info.alarm_code = dest16[0]; - if ((alarm_info.alarm_code > 0) && (alarm_info.alarm_code <= 12)) - { - alarm_info.alarm_msg = (g_alarm_msg[alarm_info.alarm_code]).toStdString(); - alarm_info.alarm_start = localTime.toStdString(); - ui.label_alarm->setText(g_alarm_msg[alarm_info.alarm_code]); - ui.label_alarm->setStyleSheet(tr("background-color: rgb(255, 0, 0);")); - if (g_last_alarm_code != alarm_info.alarm_code) - { - g_vec_alarm.push_back(alarm_info); - g_last_alarm_code = alarm_info.alarm_code; - } - else { - if (g_vec_alarm.empty()) { - g_vec_alarm.push_back(alarm_info); - g_last_alarm_code = alarm_info.alarm_code; - } - } - } - else if (alarm_info.alarm_code == 0) { - ui.label_alarm->setStyleSheet(tr("background-color: rgb(0, 170, 0);")); - ui.label_alarm->setText(QStringLiteral("无报警")); - } + if (SingleCamInfo[6].OffLine) //7#鐩告満鎺夌嚎 + { + //SingleCamInfo[6] = false; + ui.cam_status_7->setStyleSheet(tr("background-color: rgb(255, 255, 0);")); + ui.cam_work_7->setStyleSheet(tr("background-color: rgb(255, 255, 0);")); + ui.toolButton_cam_7->setStyleSheet(tr("border-image: url(:/Cigarette/Resources/cam7_no.png);")); + ui.label_reslut_7->setVisible(true); + if (g_modbus_conf.alarm > 0) + { + uint16_t dest16[2] = { 11,0 }; + int ret = m_PLCDevice->write_short_2_plc(g_modbus_conf.alarm, 2, dest16); + if (ret > 0) SingleCamInfo[6].OffLine = false; + } + work_camera_nums--; + } +#endif +#if defined(NumberOfSupportedCameras) && (NumberOfSupportedCameras>7) + if (SingleCamInfo[7].OffLine) //8#鐩告満鎺夌嚎 + { + //SingleCamInfo[7] = false; + ui.cam_status_8->setStyleSheet(tr("background-color: rgb(255, 255, 0);")); + ui.cam_work_8->setStyleSheet(tr("background-color: rgb(255, 255, 0);")); + ui.toolButton_cam_8->setStyleSheet(tr("border-image: url(:/Cigarette/Resources/cam8_no.png);")); + ui.label_reslut_8->setVisible(true); + if (g_modbus_conf.alarm > 0) + { + uint16_t dest16[2] = { 12,0 }; + int ret = m_PLCDevice->write_short_2_plc(g_modbus_conf.alarm, 2, dest16); + if (ret > 0) SingleCamInfo[7].OffLine = false; + } + work_camera_nums--; + } +#endif + + //璇诲彇鎶ヨ淇℃伅 + if (m_PLCDevice->g_plc_ok) + { + if (!g_plc_dialog_open) //PLC閰嶇疆瀵硅瘽妗嗘病鏈夋墦寮 + { + if (g_modbus_conf.alarm > 0) + { + uint16_t dest16[2]; + int ret = m_PLCDevice->read_short_from_plc(g_modbus_conf.alarm, 2, dest16); + if (ret > 0) + { + AlarmInfo alarm_info; + alarm_info.alarm_code = dest16[0]; + if ((alarm_info.alarm_code > 0) && (alarm_info.alarm_code <= 12)) + { + alarm_info.alarm_msg = (g_alarm_msg[alarm_info.alarm_code]).toStdString(); + alarm_info.alarm_start = localTime.toStdString(); + ui.label_alarm->setText(g_alarm_msg[alarm_info.alarm_code]); + ui.label_alarm->setStyleSheet(tr("background-color: rgb(255, 0, 0);")); + if (g_last_alarm_code != alarm_info.alarm_code) + { + g_vec_alarm.push_back(alarm_info); + g_last_alarm_code = alarm_info.alarm_code; + } + else { + if (g_vec_alarm.empty()) { + g_vec_alarm.push_back(alarm_info); + g_last_alarm_code = alarm_info.alarm_code; + } + } + } + else if (alarm_info.alarm_code == 0) { + ui.label_alarm->setStyleSheet(tr("background-color: rgb(0, 170, 0);")); + ui.label_alarm->setText(QStringLiteral("鏃犳姤璀")); + } #ifdef __UDPSend - QString str; - str = QString("alarm") + '_' + QString::number(alarm_info.alarm_code); - sThread.sendData(str, g_sys_conf.FeedbackPort); + QString str; + str = QString("alarm") + '_' + QString::number(alarm_info.alarm_code); + sThread.sendData(str, g_sys_conf.FeedbackPort); #endif - } - } - } - } + } + } + } + } } -void Cigarette::on_pushButton_reset_released()///复位按钮 +void Cigarette::on_pushButton_reset_released()///澶嶄綅鎸夐挳 { - int ret = m_PLCDevice->write_bit_2_plc(g_modbus_conf.reset, 1); - //Sleep(1000); - if (g_modbus_conf.reset > 0) - int ret = m_PLCDevice->write_bit_2_plc(g_modbus_conf.reset, 0); + int ret = m_PLCDevice->write_bit_2_plc(g_modbus_conf.reset, 1); + //Sleep(1000); + if (g_modbus_conf.reset > 0) + int ret = m_PLCDevice->write_bit_2_plc(g_modbus_conf.reset, 0); } -void Cigarette::OnCancelAlarm() //双击消警 +void Cigarette::OnCancelAlarm() //鍙屽嚮娑堣 { - emit sengMsgToClog("Cancel alarm mode."); - if (!g_admin_mode) - { - if (!g_op_mode) - { - dialogin = new Dialogin(this); - connect(dialogin, SIGNAL(enter_op()), this, SLOT(OnOp())); - dialogin->setModal(true); - dialogin->show(); - dialogin->move((this->width() - dialogin->width()) / 2, (this->height() - dialogin->height()) / 2); - return; - } - } - if (g_modbus_conf.alarm > 0) - { - uint16_t dest16[2] = {0,0}; - int ret = m_PLCDevice->write_short_2_plc(g_modbus_conf.alarm, 2, dest16); - if (ret > 0) - { - ui.label_alarm->setStyleSheet(tr("background-color: rgb(0, 170, 0);")); - ui.label_alarm->setText(QStringLiteral("无报警")); - QDateTime ts_start = QDateTime::currentDateTime(); - QDateTime local(ts_start); - QString localTime = local.toString("yyyy-MM-dd hh:mm:ss"); - int n = g_vec_alarm.size(); - if (n>0) - { - g_vec_alarm[n - 1].alarm_handle = localTime.toStdString(); - } + emit sengMsgToClog("Cancel alarm mode."); + if (!g_admin_mode) + { + if (!g_op_mode) + { + dialogin = new Dialogin(this); + connect(dialogin, SIGNAL(enter_op()), this, SLOT(OnOp())); + dialogin->setModal(true); + dialogin->show(); + dialogin->move((this->width() - dialogin->width()) / 2, (this->height() - dialogin->height()) / 2); + return; + } + } + if (g_modbus_conf.alarm > 0) + { + uint16_t dest16[2] = { 0,0 }; + int ret = m_PLCDevice->write_short_2_plc(g_modbus_conf.alarm, 2, dest16); + if (ret > 0) + { + ui.label_alarm->setStyleSheet(tr("background-color: rgb(0, 170, 0);")); + ui.label_alarm->setText(QStringLiteral("鏃犳姤璀")); + QDateTime ts_start = QDateTime::currentDateTime(); + QDateTime local(ts_start); + QString localTime = local.toString("yyyy-MM-dd hh:mm:ss"); + int n = g_vec_alarm.size(); + if (n > 0) + { + g_vec_alarm[n - 1].alarm_handle = localTime.toStdString(); + } #ifdef __UDPSend - QString str; - str = QString("alarm") + '_' + QString::number(0); - sThread.sendData(str, g_sys_conf.FeedbackPort); + QString str; + str = QString("alarm") + '_' + QString::number(0); + sThread.sendData(str, g_sys_conf.FeedbackPort); #endif - } - } - g_op_time = OP_TIME; + } + } + g_op_time = OP_TIME; } void Cigarette::on_toolButton_alarm_released() { - emit sengMsgToClog("Open alarm dialog."); - if (!g_admin_mode) - { - if (!g_op_mode) - { - emit sengMsgToClog("Start to login in."); - dialogin = new Dialogin(this); - connect(dialogin, SIGNAL(enter_op()), this, SLOT(OnOp())); - dialogin->setModal(true); - dialogin->show(); - dialogin->move((this->width() - dialogin->width()) / 2, (this->height() - dialogin->height()) / 2); - return; - } - } - AlarmDialog *alarm_dialog = new AlarmDialog(this); - alarm_dialog->setModal(true); - alarm_dialog->show(); - alarm_dialog->move((this->width() - alarm_dialog->width()) / 2, (this->height() - alarm_dialog->height()) / 2); - g_op_time = OP_TIME; -} -void Cigarette::on_pushButton_clear_released()//换班 + emit sengMsgToClog("Open alarm dialog."); + if (!g_admin_mode) + { + if (!g_op_mode) + { + emit sengMsgToClog("Start to login in."); + dialogin = new Dialogin(this); + connect(dialogin, SIGNAL(enter_op()), this, SLOT(OnOp())); + dialogin->setModal(true); + dialogin->show(); + dialogin->move((this->width() - dialogin->width()) / 2, (this->height() - dialogin->height()) / 2); + return; + } + } + AlarmDialog* alarm_dialog = new AlarmDialog(this); + alarm_dialog->setModal(true); + alarm_dialog->show(); + alarm_dialog->move((this->width() - alarm_dialog->width()) / 2, (this->height() - alarm_dialog->height()) / 2); + g_op_time = OP_TIME; +} +void Cigarette::on_pushButton_clear_released()//鎹㈢彮 { - emit sengMsgToClog("Change shift."); - emit sendMsgToExportData(); - - if (!g_admin_mode) - { - if (!g_op_mode) - { - dialogin = new Dialogin(this); - connect(dialogin, SIGNAL(enter_op()), this, SLOT(OnOp())); - dialogin->setModal(true); - dialogin->show(); - dialogin->move((this->width() - dialogin->width()) / 2, (this->height() - dialogin->height()) / 2); - return; - } - } - if(g_working) - { - QMessageBox::information(NULL, QStringLiteral("状态检查"), QStringLiteral("请先点击“停止工作”按钮,才可以进行换班操作 "), QMessageBox::Ok); - return; - } - - //通过PLC读取当班产量,显示在上班产量中 - if (m_PLCDevice->g_plc_ok) - { - if (!g_plc_dialog_open) //PLC配置对话框没有打开 - { - if (g_modbus_conf.quantity > 0) - { - uint16_t dest16[2]; - int ret = m_PLCDevice->read_short_from_plc(g_modbus_conf.quantity, 2, dest16); - //std::cout << ret << std::endl; - if (ret > 0) - { - int cur_quantity = dest16[0] + (dest16[1] << 16); - ui.lcdNumber_total_no_last->display(cur_quantity); + emit sengMsgToClog("Change shift."); + emit sendMsgToExportData(); + + if (!g_admin_mode) + { + if (!g_op_mode) + { + dialogin = new Dialogin(this); + connect(dialogin, SIGNAL(enter_op()), this, SLOT(OnOp())); + dialogin->setModal(true); + dialogin->show(); + dialogin->move((this->width() - dialogin->width()) / 2, (this->height() - dialogin->height()) / 2); + return; + } + } + if (g_working) + { + QMessageBox::information(NULL, QStringLiteral("鐘舵佹鏌"), QStringLiteral("璇峰厛鐐瑰嚮鈥滃仠姝㈠伐浣溾濇寜閽紝鎵嶅彲浠ヨ繘琛屾崲鐝搷浣 "), QMessageBox::Ok); + return; + } + + //閫氳繃PLC璇诲彇褰撶彮浜ч噺锛屾樉绀哄湪涓婄彮浜ч噺涓 + if (m_PLCDevice->g_plc_ok) + { + if (!g_plc_dialog_open) //PLC閰嶇疆瀵硅瘽妗嗘病鏈夋墦寮 + { + if (g_modbus_conf.quantity > 0) + { + uint16_t dest16[2]; + int ret = m_PLCDevice->read_short_from_plc(g_modbus_conf.quantity, 2, dest16); + //std::cout << ret << std::endl; + if (ret > 0) + { + int cur_quantity = dest16[0] + (dest16[1] << 16); + ui.lcdNumber_total_no_last->display(cur_quantity); #ifdef __ExportData - exportData->totalCheckNum = cur_quantity; + exportData->totalCheckNum = cur_quantity; #endif #ifdef __UDPSend - sThread.sendData("totallast_" + QString::number(cur_quantity), g_sys_conf.FeedbackPort); + sThread.sendData("totallast_" + QString::number(cur_quantity), g_sys_conf.FeedbackPort); #endif - } - } + } + } #ifdef __ExportData - for (int i = 0; i < NumberOfSupportedCameras; i++) { - _XMLExportDataInfo exportXMLDataInfo; - exportXMLDataInfo.cameraTotal = NumberOfSupportedCameras; - exportXMLDataInfo.cameraId = exportData[i].cameraId; - exportXMLDataInfo.TotalCheckNum = exportData->totalCheckNum; - exportXMLDataInfo.shotCounts = g_sys_conf.shoot[i]; - exportXMLDataInfo.DetectSpeed = exportData[i].detectTime; - exportXMLDataInfo.AcquisitionSpeed = exportData[i].acquisitionTime; - exportXMLDataInfo.checkNum = exportData[i].checkNum; - exportXMLDataInfo.jdNum = exportData[i].jdNum; - exportXMLDataInfo.okNum = exportData[i].okNum; - exportXMLDataInfo.ngNum = exportData[i].ngNum; - exportXMLDataInfo.kickNum = exportData[i].kick; - if (exportXMLDataInfo.kickNum == 0) - exportXMLDataInfo.KickRate = 0; - else - exportXMLDataInfo.KickRate = (double)exportXMLDataInfo.kickNum / exportXMLDataInfo.checkNum; - double ng_rate; - if (exportData[i].ngNum > 0) - ng_rate = double(exportData[i].ngNum) / exportData[i].checkNum; - else - ng_rate = 0; - exportXMLDataInfo.PassRate = 1.0 - ng_rate; - - int f = 0; - for (int i = 1; i < NumberOfSupportedCameras; i++) { - if (exportData[i].kick != exportData[0].kick) { - f = 1; - break; - } - } - if (f == 1) { - // Kick值不一致 - for (int i = 0; i < NumberOfSupportedCameras; i++) { - exportXMLDataInfo.TotalKickNum += exportData[i].kick; - } - } - else - exportXMLDataInfo.TotalKickNum = exportData[0].kick; - - export_XMLData_Info_queue->put(exportXMLDataInfo); - } - //flag = false; -#endif - //发送换班消息给PLC - if (g_modbus_conf.shift > 0) - { - int ret = m_PLCDevice->write_bit_2_plc( g_modbus_conf.shift, 1); - if (g_modbus_conf.alarm >0)///给报警地址(alarm对应的PLC地址)清零 - { - uint16_t dest16[2] = { 0,0 }; - int ret = m_PLCDevice->write_short_2_plc(g_modbus_conf.alarm, 2, dest16); - } - } - } - } - g_op_time = OP_TIME; - - ui.pushButton_clear->setEnabled(false); - m_delay->setSingleShot(true); - m_delay->start(5000); - Sleep(500); - for (int i = 0; i < NumberOfSupportedCameras; i++) - { - production_number[i] = 0; - lcdNumber_total_mat[i]->display(production_number[i]); - ok[i] = 0; - lcdNumber_ok_mat[i]->display(ok[i]); - ng[i] = 0; - lcdNumber_ng_mat[i]->display(ng[i]); + for (int i = 0; i < NumberOfSupportedCameras; i++) { + _XMLExportDataInfo exportXMLDataInfo; + exportXMLDataInfo.cameraTotal = NumberOfSupportedCameras; + exportXMLDataInfo.cameraId = exportData[i].cameraId; + exportXMLDataInfo.TotalCheckNum = exportData->totalCheckNum; + exportXMLDataInfo.shotCounts = g_sys_conf.shoot[i]; + exportXMLDataInfo.DetectSpeed = exportData[i].detectTime; + exportXMLDataInfo.AcquisitionSpeed = exportData[i].acquisitionTime; + exportXMLDataInfo.checkNum = exportData[i].checkNum; + exportXMLDataInfo.jdNum = exportData[i].jdNum; + exportXMLDataInfo.okNum = exportData[i].okNum; + exportXMLDataInfo.ngNum = exportData[i].ngNum; + exportXMLDataInfo.kickNum = exportData[i].kick; + if (exportXMLDataInfo.kickNum == 0) + exportXMLDataInfo.KickRate = 0; + else + exportXMLDataInfo.KickRate = (double)exportXMLDataInfo.kickNum / exportXMLDataInfo.checkNum; + double ng_rate; + if (exportData[i].ngNum > 0) + ng_rate = double(exportData[i].ngNum) / exportData[i].checkNum; + else + ng_rate = 0; + exportXMLDataInfo.PassRate = 1.0 - ng_rate; + + int f = 0; + for (int i = 1; i < NumberOfSupportedCameras; i++) { + if (exportData[i].kick != exportData[0].kick) { + f = 1; + break; + } + } + if (f == 1) { + // Kick鍊间笉涓鑷 + for (int i = 0; i < NumberOfSupportedCameras; i++) { + exportXMLDataInfo.TotalKickNum += exportData[i].kick; + } + } + else + exportXMLDataInfo.TotalKickNum = exportData[0].kick; + + export_XMLData_Info_queue->put(exportXMLDataInfo); + } + //flag = false; +#endif + //鍙戦佹崲鐝秷鎭粰PLC + if (g_modbus_conf.shift > 0) + { + int ret = m_PLCDevice->write_bit_2_plc(g_modbus_conf.shift, 1); + if (g_modbus_conf.alarm > 0)///缁欐姤璀﹀湴鍧锛坅larm瀵瑰簲鐨凱LC鍦板潃锛夋竻闆 + { + uint16_t dest16[2] = { 0,0 }; + int ret = m_PLCDevice->write_short_2_plc(g_modbus_conf.alarm, 2, dest16); + } + } + } + } + g_op_time = OP_TIME; + + ui.pushButton_clear->setEnabled(false); + m_delay->setSingleShot(true); + m_delay->start(5000); + Sleep(500); + for (int i = 0; i < NumberOfSupportedCameras; i++) + { + production_number[i] = 0; + lcdNumber_total_mat[i]->display(production_number[i]); + ok[i] = 0; + lcdNumber_ok_mat[i]->display(ok[i]); + ng[i] = 0; + lcdNumber_ng_mat[i]->display(ng[i]); #ifdef __UDPSend - _UDPSendInfo UDPSendInfo; + _UDPSendInfo UDPSendInfo; - UDPSendInfo.index = i; - UDPSendInfo.FrameID = ok_frame; - UDPSendInfo.ok[i] = ok[i]; - UDP_Info_queue->put(UDPSendInfo); + UDPSendInfo.index = i; + UDPSendInfo.FrameID = ok_frame; + UDPSendInfo.ok[i] = ok[i]; + UDP_Info_queue->put(UDPSendInfo); - UDPSendInfo.FrameID = ng_frame; - UDPSendInfo.ng[i] = ng[i]; - UDP_Info_queue->put(UDPSendInfo); + UDPSendInfo.FrameID = ng_frame; + UDPSendInfo.ng[i] = ng[i]; + UDP_Info_queue->put(UDPSendInfo); - UDPSendInfo.FrameID = info_frame; - UDPSendInfo.timecost = QString::number(0); - UDPSendInfo.JD = QString("0,0,0"); - UDP_Info_queue->put(UDPSendInfo); + UDPSendInfo.FrameID = info_frame; + UDPSendInfo.timecost = QString::number(0); + UDPSendInfo.JD = QString("0,0,0"); + UDP_Info_queue->put(UDPSendInfo); - UDPSendInfo.FrameID = total_frame; - UDPSendInfo.Total = 0; - UDP_Info_queue->put(UDPSendInfo); + UDPSendInfo.FrameID = total_frame; + UDPSendInfo.Total = 0; + UDP_Info_queue->put(UDPSendInfo); #endif - } - ui.lcdNumber_total_no->display(0); + } + ui.lcdNumber_total_no->display(0); #ifdef __UDPSend - sThread.sendData("total_" + QString::number(0), g_sys_conf.FeedbackPort); + sThread.sendData("total_" + QString::number(0), g_sys_conf.FeedbackPort); #endif } -//读取系统管理员密码 +//璇诲彇绯荤粺绠$悊鍛樺瘑鐮 QString Cigarette::read_pswd() { - std::fstream cfg_file; - cfg_file.open("D:/Release/pswd.txt"); - if (!cfg_file.is_open()) - { - std::cout << "Error: Open config file pswd.txt"<< std::endl; - return "81dc9bdb52d04dc20036dbd8313ed055"; - } - if (!cfg_file.eof()) - { - char tmp[256]; - memset(tmp, 0, 256); - cfg_file.getline(tmp, 256); - QString pswd = QString(QLatin1String(tmp)); - if (pswd.length() > 0) - { - return pswd; - } - else - { - return "81dc9bdb52d04dc20036dbd8313ed055"; - } - } - else - { - return "81dc9bdb52d04dc20036dbd8313ed055"; - } - cfg_file.close(); -} - -//读取系统操作员密码 + std::fstream cfg_file; + cfg_file.open("D:/Release/pswd.txt"); + if (!cfg_file.is_open()) + { + std::cout << "Error: Open config file pswd.txt" << std::endl; + return "81dc9bdb52d04dc20036dbd8313ed055"; + } + if (!cfg_file.eof()) + { + char tmp[256]; + memset(tmp, 0, 256); + cfg_file.getline(tmp, 256); + QString pswd = QString(QLatin1String(tmp)); + if (pswd.length() > 0) + { + return pswd; + } + else + { + return "81dc9bdb52d04dc20036dbd8313ed055"; + } + } + else + { + return "81dc9bdb52d04dc20036dbd8313ed055"; + } + cfg_file.close(); +} + +//璇诲彇绯荤粺鎿嶄綔鍛樺瘑鐮 QString Cigarette::read_op_pswd() { - std::fstream cfg_file; - cfg_file.open("D:/Release/pswd_op.txt"); - if (!cfg_file.is_open()) - { - std::cout << "Error: Open config file pswd_op.txt" << std::endl; - return "81dc9bdb52d04dc20036dbd8313ed055"; - } - if (!cfg_file.eof()) - { - char tmp[256]; - memset(tmp, 0, 256); - cfg_file.getline(tmp, 256); - QString pswd = QString(QLatin1String(tmp)); - if (pswd.length() > 0) - { - return pswd; - } - else - { - return "81dc9bdb52d04dc20036dbd8313ed055"; - } - } - else - { - return "81dc9bdb52d04dc20036dbd8313ed055"; - } - cfg_file.close(); -} - -bool Cigarette::read_conf(ConfPath &conf_path) { - std::fstream conf_file; - conf_file.open(CONFPATH); - if (!conf_file.is_open()) { - std::cout << "Error: Open conf path file " << CONFPATH << std::endl; - return false; - } - while (!conf_file.eof()) { - char tmp[256] = ""; - conf_file.getline(tmp, 256); - std::string line(tmp); - if (line.length() > 0) { - size_t pos = line.find('='); - std::string tmp_key = line.substr(0, pos); - if (tmp_key == "CONF_PATH") { - std::string str = line.substr(pos + 1).c_str(); - std::wstring w_str = String2WString(str); - conf_path.config_path = QString::fromStdWString(w_str); - } - //else if (tmp_key == "CONF_NAME") { - // conf_path.config_name = line.substr(pos + 1).c_str(); - //} - else if (tmp_key == "SAVE_PICS_PATH") { - std::string str = line.substr(pos + 1).c_str(); - std::wstring w_str = String2WString(str); - conf_path.save_pics_path = QString::fromStdWString(w_str); - } - } - } - conf_file.close(); - return true; -} - -bool Cigarette::read_sys_config(SysConf &conf, QString conf_path) + std::fstream cfg_file; + cfg_file.open("D:/Release/pswd_op.txt"); + if (!cfg_file.is_open()) + { + std::cout << "Error: Open config file pswd_op.txt" << std::endl; + return "81dc9bdb52d04dc20036dbd8313ed055"; + } + if (!cfg_file.eof()) + { + char tmp[256]; + memset(tmp, 0, 256); + cfg_file.getline(tmp, 256); + QString pswd = QString(QLatin1String(tmp)); + if (pswd.length() > 0) + { + return pswd; + } + else + { + return "81dc9bdb52d04dc20036dbd8313ed055"; + } + } + else + { + return "81dc9bdb52d04dc20036dbd8313ed055"; + } + cfg_file.close(); +} + +bool Cigarette::read_conf(ConfPath& conf_path) { + std::fstream conf_file; + conf_file.open(CONFPATH); + if (!conf_file.is_open()) { + std::cout << "Error: Open conf path file " << CONFPATH << std::endl; + return false; + } + while (!conf_file.eof()) { + char tmp[256] = ""; + conf_file.getline(tmp, 256); + std::string line(tmp); + if (line.length() > 0) { + size_t pos = line.find('='); + std::string tmp_key = line.substr(0, pos); + if (tmp_key == "CONF_PATH") { + std::string str = line.substr(pos + 1).c_str(); + std::wstring w_str = String2WString(str); + conf_path.config_path = QString::fromStdWString(w_str); + } + //else if (tmp_key == "CONF_NAME") { + // conf_path.config_name = line.substr(pos + 1).c_str(); + //} + else if (tmp_key == "SAVE_PICS_PATH") { + std::string str = line.substr(pos + 1).c_str(); + std::wstring w_str = String2WString(str); + conf_path.save_pics_path = QString::fromStdWString(w_str); + } + } + } + conf_file.close(); + return true; +} + +bool Cigarette::read_sys_config(SysConf& conf, QString conf_path) { - std::fstream cfg_file; - cfg_file.open(conf_path.toLocal8Bit().constData()); - if (!cfg_file.is_open()) - { - std::cout << "Error: Open config file " << conf_path.toStdString() << std::endl; - return false; - } - while (!cfg_file.eof()) - { - char tmp[256] = ""; - cfg_file.getline(tmp, 256); - std::string line(tmp); - if (line.length() > 0) - { - /// atoi返回整数值;substr返回子串;c_str()指向字符串首地址 - size_t pos = line.find('='); - std::string tmp_key = line.substr(0, pos); - - if (tmp_key == "SAVE") - { /// 存图设置:0不保存;1保存NG;2全存 - conf.save = atoi(line.substr(pos + 1).c_str()); - } - else if (tmp_key == "MISMATCHACT") - { /// 错位行为:1NG;0OK - conf.MisMatchAct = atoi(line.substr(pos + 1).c_str()); - } - else if (tmp_key == "SAVE_DAYS") - { /// 照片保存天数 - conf.save_days = atoi(line.substr(pos + 1).c_str()); - } - else if (tmp_key == "FREESIZE") - { - /// 清理图片设定最小空间值 - conf.freesize = atoi(line.substr(pos + 1).c_str()); - } - else if (tmp_key == "ComPort") - { /// COM口 - conf.ComPort = line.substr(pos + 1); - } - else if (tmp_key == "CONFTHRESHOLD") - { ///相似度 - conf.ConfThreshold = atoi(line.substr(pos + 1).c_str()); - } - else if (tmp_key == "AUTO_OPEN") - { /// 是否自动打开相机:0否;1是 - conf.auto_open = atoi(line.substr(pos + 1).c_str()); - } - else if (tmp_key == "AUTO_WORK") - { /// 是否自动开始工作:0否;1是 - conf.auto_work = atoi(line.substr(pos + 1).c_str()); - } - else if (tmp_key == "AUTO_SHIFT") - { /// 是否自动换班:0否;1是 - conf.auto_shift = atoi(line.substr(pos + 1).c_str()); - } - else if (tmp_key == "TIMING_SHIFT") - { /// 是否定时换班:0否;1是 - conf.timing_shift = atoi(line.substr(pos + 1).c_str()); - } - else if (tmp_key == "SHIFT_A") - { - std::vector vec_info; - string_split(line.substr(pos + 1), "|",vec_info); - if (vec_info.size() == 2) - { - conf.shiftA.setHMS(atoi(vec_info[0].c_str())%24, atoi(vec_info[1].c_str()), 0);/// - } - } - else if (tmp_key == "SHIFT_B") - { - std::vector vec_info; - string_split(line.substr(pos + 1), "|",vec_info); - if (vec_info.size() == 2) - { - conf.shiftB.setHMS(atoi(vec_info[0].c_str())%24, atoi(vec_info[1].c_str()), 0);/// - } - } - else if (tmp_key == "SHIFT_C") - { - std::vector vec_info; - string_split(line.substr(pos + 1), "|",vec_info); - if (vec_info.size() == 2) - { - conf.shiftC.setHMS(atoi(vec_info[0].c_str())%24, atoi(vec_info[1].c_str()), 0);/// - } - } - else if (tmp_key == "LOCATION") - { - conf.location = line.substr(pos + 1).c_str(); - } - else if (tmp_key == "MODELPATH") - { - conf.model_path = line.substr(pos + 1).c_str(); - } - else if (tmp_key == "MODELNAME") - { - conf.model_name = line.substr(pos + 1).c_str(); - } - else if (tmp_key == "JPGPATH") - { - conf.model_jpg_path = line.substr(pos + 1).c_str(); - } + std::fstream cfg_file; + cfg_file.open(conf_path.toLocal8Bit().constData()); + if (!cfg_file.is_open()) + { + std::cout << "Error: Open config file " << conf_path.toStdString() << std::endl; + return false; + } + while (!cfg_file.eof()) + { + char tmp[256] = ""; + cfg_file.getline(tmp, 256); + std::string line(tmp); + if (line.length() > 0) + { + /// atoi杩斿洖鏁存暟鍊硷紱substr杩斿洖瀛愪覆锛沜_str()鎸囧悜瀛楃涓查鍦板潃 + size_t pos = line.find('='); + std::string tmp_key = line.substr(0, pos); + + if (tmp_key == "SAVE") + { /// 瀛樺浘璁剧疆锛0涓嶄繚瀛橈紱1淇濆瓨NG锛2鍏ㄥ瓨 + conf.save = atoi(line.substr(pos + 1).c_str()); + } + else if (tmp_key == "MISMATCHACT") + { /// 閿欎綅琛屼负锛1NG锛0OK + conf.MisMatchAct = atoi(line.substr(pos + 1).c_str()); + } + else if (tmp_key == "SAVE_DAYS") + { /// 鐓х墖淇濆瓨澶╂暟 + conf.save_days = atoi(line.substr(pos + 1).c_str()); + } + else if (tmp_key == "FREESIZE") + { + /// 娓呯悊鍥剧墖璁惧畾鏈灏忕┖闂村 + conf.freesize = atoi(line.substr(pos + 1).c_str()); + } + else if (tmp_key == "ComPort") + { /// COM鍙 + conf.ComPort = line.substr(pos + 1); + } + else if (tmp_key == "CONFTHRESHOLD") + { ///鐩镐技搴 + conf.ConfThreshold = atoi(line.substr(pos + 1).c_str()); + } + else if (tmp_key == "AUTO_OPEN") + { /// 鏄惁鑷姩鎵撳紑鐩告満锛0鍚︼紱1鏄 + conf.auto_open = atoi(line.substr(pos + 1).c_str()); + } + else if (tmp_key == "AUTO_WORK") + { /// 鏄惁鑷姩寮濮嬪伐浣滐細0鍚︼紱1鏄 + conf.auto_work = atoi(line.substr(pos + 1).c_str()); + } + else if (tmp_key == "AUTO_SHIFT") + { /// 鏄惁鑷姩鎹㈢彮锛0鍚︼紱1鏄 + conf.auto_shift = atoi(line.substr(pos + 1).c_str()); + } + else if (tmp_key == "TIMING_SHIFT") + { /// 鏄惁瀹氭椂鎹㈢彮锛0鍚︼紱1鏄 + conf.timing_shift = atoi(line.substr(pos + 1).c_str()); + } + else if (tmp_key == "SHIFT_A") + { + std::vector vec_info; + string_split(line.substr(pos + 1), "|", vec_info); + if (vec_info.size() == 2) + { + conf.shiftA.setHMS(atoi(vec_info[0].c_str()) % 24, atoi(vec_info[1].c_str()), 0);/// + } + } + else if (tmp_key == "SHIFT_B") + { + std::vector vec_info; + string_split(line.substr(pos + 1), "|", vec_info); + if (vec_info.size() == 2) + { + conf.shiftB.setHMS(atoi(vec_info[0].c_str()) % 24, atoi(vec_info[1].c_str()), 0);/// + } + } + else if (tmp_key == "SHIFT_C") + { + std::vector vec_info; + string_split(line.substr(pos + 1), "|", vec_info); + if (vec_info.size() == 2) + { + conf.shiftC.setHMS(atoi(vec_info[0].c_str()) % 24, atoi(vec_info[1].c_str()), 0);/// + } + } + else if (tmp_key == "LOCATION") + { + conf.location = line.substr(pos + 1).c_str(); + } + else if (tmp_key == "MODELPATH") + { + conf.model_path = line.substr(pos + 1).c_str(); + } + else if (tmp_key == "MODELNAME") + { + conf.model_name = line.substr(pos + 1).c_str(); + } + else if (tmp_key == "JPGPATH") + { + conf.model_jpg_path = line.substr(pos + 1).c_str(); + } #if defined(NumberOfSupportedCameras) && (NumberOfSupportedCameras>0) - else if (tmp_key == "EXPO1") - { - conf.expo[0] = atoi(line.substr(pos + 1).c_str()); - } - else if (tmp_key == "GAIN1") - { - conf.gain[0] = atoi(line.substr(pos + 1).c_str()); - } - else if (tmp_key == "FILTER1") - { - conf.filter[0] = atoi(line.substr(pos + 1).c_str()); - } - else if (tmp_key == "USERID1") - { - conf.UserID[0] = atoi(line.substr(pos + 1).c_str()); - } - else if (tmp_key == "NO1") - { - std::vector vec_info; - string_split(line.substr(pos + 1), "|",vec_info); - if (vec_info.size() == 3) - { - conf.no[0][0] = atoi(vec_info[0].c_str()); - conf.no[0][1] = atoi(vec_info[1].c_str()); - conf.no[0][2] = atoi(vec_info[2].c_str()); - } - } - else if (tmp_key == "SHOOT1") - { - conf.shoot[0] = atoi(line.substr(pos + 1).c_str()); - } + else if (tmp_key == "EXPO1") + { + conf.expo[0] = atoi(line.substr(pos + 1).c_str()); + } + else if (tmp_key == "GAIN1") + { + conf.gain[0] = atoi(line.substr(pos + 1).c_str()); + } + else if (tmp_key == "FILTER1") + { + conf.filter[0] = atoi(line.substr(pos + 1).c_str()); + } + else if (tmp_key == "USERID1") + { + conf.UserID[0] = atoi(line.substr(pos + 1).c_str()); + } + else if (tmp_key == "NO1") + { + std::vector vec_info; + string_split(line.substr(pos + 1), "|", vec_info); + if (vec_info.size() == 3) + { + conf.no[0][0] = atoi(vec_info[0].c_str()); + conf.no[0][1] = atoi(vec_info[1].c_str()); + conf.no[0][2] = atoi(vec_info[2].c_str()); + } + } + else if (tmp_key == "SHOOT1") + { + conf.shoot[0] = atoi(line.substr(pos + 1).c_str()); + } #endif #if defined(NumberOfSupportedCameras) && (NumberOfSupportedCameras>1) - else if (tmp_key == "EXPO2") - { - conf.expo[1] = atoi(line.substr(pos + 1).c_str()); - } - else if (tmp_key == "GAIN2") - { - conf.gain[1] = atoi(line.substr(pos + 1).c_str()); - } - else if (tmp_key == "FILTER2") - { - conf.filter[1] = atoi(line.substr(pos + 1).c_str()); - } - else if (tmp_key == "USERID2") - { - conf.UserID[1] = atoi(line.substr(pos + 1).c_str()); - } - else if (tmp_key == "NO2") - { - std::vector vec_info; - string_split(line.substr(pos + 1), "|",vec_info); - if (vec_info.size() == 3) - { - conf.no[1][0] = atoi(vec_info[0].c_str()); - conf.no[1][1] = atoi(vec_info[1].c_str()); - conf.no[1][2] = atoi(vec_info[2].c_str()); - } - } - else if (tmp_key == "SHOOT2") - { - conf.shoot[1] = atoi(line.substr(pos + 1).c_str()); - } + else if (tmp_key == "EXPO2") + { + conf.expo[1] = atoi(line.substr(pos + 1).c_str()); + } + else if (tmp_key == "GAIN2") + { + conf.gain[1] = atoi(line.substr(pos + 1).c_str()); + } + else if (tmp_key == "FILTER2") + { + conf.filter[1] = atoi(line.substr(pos + 1).c_str()); + } + else if (tmp_key == "USERID2") + { + conf.UserID[1] = atoi(line.substr(pos + 1).c_str()); + } + else if (tmp_key == "NO2") + { + std::vector vec_info; + string_split(line.substr(pos + 1), "|", vec_info); + if (vec_info.size() == 3) + { + conf.no[1][0] = atoi(vec_info[0].c_str()); + conf.no[1][1] = atoi(vec_info[1].c_str()); + conf.no[1][2] = atoi(vec_info[2].c_str()); + } + } + else if (tmp_key == "SHOOT2") + { + conf.shoot[1] = atoi(line.substr(pos + 1).c_str()); + } #endif #if defined(NumberOfSupportedCameras) && (NumberOfSupportedCameras>2) - else if (tmp_key == "EXPO3") - { - conf.expo[2] = atoi(line.substr(pos + 1).c_str()); - } - else if (tmp_key == "GAIN3") - { - conf.gain[2] = atoi(line.substr(pos + 1).c_str()); - } - else if (tmp_key == "FILTER3") - { - conf.filter[2] = atoi(line.substr(pos + 1).c_str()); - } - else if (tmp_key == "USERID3") - { - conf.UserID[2] = atoi(line.substr(pos + 1).c_str()); - } - else if (tmp_key == "NO3") - { - std::vector vec_info; - string_split(line.substr(pos + 1), "|",vec_info); - if (vec_info.size() == 3) - { - conf.no[2][0] = atoi(vec_info[0].c_str()); - conf.no[2][1] = atoi(vec_info[1].c_str()); - conf.no[2][2] = atoi(vec_info[2].c_str()); - } - } - else if (tmp_key == "SHOOT3") - { - conf.shoot[2] = atoi(line.substr(pos + 1).c_str()); - } + else if (tmp_key == "EXPO3") + { + conf.expo[2] = atoi(line.substr(pos + 1).c_str()); + } + else if (tmp_key == "GAIN3") + { + conf.gain[2] = atoi(line.substr(pos + 1).c_str()); + } + else if (tmp_key == "FILTER3") + { + conf.filter[2] = atoi(line.substr(pos + 1).c_str()); + } + else if (tmp_key == "USERID3") + { + conf.UserID[2] = atoi(line.substr(pos + 1).c_str()); + } + else if (tmp_key == "NO3") + { + std::vector vec_info; + string_split(line.substr(pos + 1), "|", vec_info); + if (vec_info.size() == 3) + { + conf.no[2][0] = atoi(vec_info[0].c_str()); + conf.no[2][1] = atoi(vec_info[1].c_str()); + conf.no[2][2] = atoi(vec_info[2].c_str()); + } + } + else if (tmp_key == "SHOOT3") + { + conf.shoot[2] = atoi(line.substr(pos + 1).c_str()); + } #endif #if defined(NumberOfSupportedCameras) && (NumberOfSupportedCameras>3) - else if (tmp_key == "EXPO4") - { - conf.expo[3] = atoi(line.substr(pos + 1).c_str()); - } - else if (tmp_key == "GAIN4") - { - conf.gain[3] = atoi(line.substr(pos + 1).c_str()); - } - else if (tmp_key == "FILTER4") - { - conf.filter[3] = atoi(line.substr(pos + 1).c_str()); - } - else if (tmp_key == "USERID4") - { - conf.UserID[3] = atoi(line.substr(pos + 1).c_str()); - } - else if (tmp_key == "NO4") - { - std::vector vec_info; - string_split(line.substr(pos + 1), "|",vec_info); - if (vec_info.size() == 3) - { - conf.no[3][0] = atoi(vec_info[0].c_str()); - conf.no[3][1] = atoi(vec_info[1].c_str()); - conf.no[3][2] = atoi(vec_info[2].c_str()); - } - } - else if (tmp_key == "SHOOT4") - { - conf.shoot[3] = atoi(line.substr(pos + 1).c_str()); - } + else if (tmp_key == "EXPO4") + { + conf.expo[3] = atoi(line.substr(pos + 1).c_str()); + } + else if (tmp_key == "GAIN4") + { + conf.gain[3] = atoi(line.substr(pos + 1).c_str()); + } + else if (tmp_key == "FILTER4") + { + conf.filter[3] = atoi(line.substr(pos + 1).c_str()); + } + else if (tmp_key == "USERID4") + { + conf.UserID[3] = atoi(line.substr(pos + 1).c_str()); + } + else if (tmp_key == "NO4") + { + std::vector vec_info; + string_split(line.substr(pos + 1), "|", vec_info); + if (vec_info.size() == 3) + { + conf.no[3][0] = atoi(vec_info[0].c_str()); + conf.no[3][1] = atoi(vec_info[1].c_str()); + conf.no[3][2] = atoi(vec_info[2].c_str()); + } + } + else if (tmp_key == "SHOOT4") + { + conf.shoot[3] = atoi(line.substr(pos + 1).c_str()); + } #endif #if defined(NumberOfSupportedCameras) && (NumberOfSupportedCameras>4) - else if (tmp_key == "EXPO5") - { - conf.expo[4] = atoi(line.substr(pos + 1).c_str()); - } - else if (tmp_key == "GAIN5") - { - conf.gain[4] = atoi(line.substr(pos + 1).c_str()); - } - else if (tmp_key == "FILTER5") - { - conf.filter[4] = atoi(line.substr(pos + 1).c_str()); - } - else if (tmp_key == "USERID5") - { - conf.UserID[4] = atoi(line.substr(pos + 1).c_str()); - } - else if (tmp_key == "NO5") - { - std::vector vec_info; - string_split(line.substr(pos + 1), "|", vec_info); - if (vec_info.size() == 3) - { - conf.no[4][0] = atoi(vec_info[0].c_str()); - conf.no[4][1] = atoi(vec_info[1].c_str()); - conf.no[4][2] = atoi(vec_info[2].c_str()); - } - } - else if (tmp_key == "SHOOT5") - { - conf.shoot[4] = atoi(line.substr(pos + 1).c_str()); - } + else if (tmp_key == "EXPO5") + { + conf.expo[4] = atoi(line.substr(pos + 1).c_str()); + } + else if (tmp_key == "GAIN5") + { + conf.gain[4] = atoi(line.substr(pos + 1).c_str()); + } + else if (tmp_key == "FILTER5") + { + conf.filter[4] = atoi(line.substr(pos + 1).c_str()); + } + else if (tmp_key == "USERID5") + { + conf.UserID[4] = atoi(line.substr(pos + 1).c_str()); + } + else if (tmp_key == "NO5") + { + std::vector vec_info; + string_split(line.substr(pos + 1), "|", vec_info); + if (vec_info.size() == 3) + { + conf.no[4][0] = atoi(vec_info[0].c_str()); + conf.no[4][1] = atoi(vec_info[1].c_str()); + conf.no[4][2] = atoi(vec_info[2].c_str()); + } + } + else if (tmp_key == "SHOOT5") + { + conf.shoot[4] = atoi(line.substr(pos + 1).c_str()); + } #endif #if defined(NumberOfSupportedCameras) && (NumberOfSupportedCameras>5) - else if (tmp_key == "EXPO6") - { - conf.expo[5] = atoi(line.substr(pos + 1).c_str()); - } - else if (tmp_key == "GAIN6") - { - conf.gain[5] = atoi(line.substr(pos + 1).c_str()); - } - else if (tmp_key == "FILTER6") - { - conf.filter[5] = atoi(line.substr(pos + 1).c_str()); - } - else if (tmp_key == "USERID6") - { - conf.UserID[5] = atoi(line.substr(pos + 1).c_str()); - } - else if (tmp_key == "NO6") - { - std::vector vec_info; - string_split(line.substr(pos + 1), "|", vec_info); - if (vec_info.size() == 3) - { - conf.no[5][0] = atoi(vec_info[0].c_str()); - conf.no[5][1] = atoi(vec_info[1].c_str()); - conf.no[5][2] = atoi(vec_info[2].c_str()); - } - } - else if (tmp_key == "SHOOT6") - { - conf.shoot[5] = atoi(line.substr(pos + 1).c_str()); - } + else if (tmp_key == "EXPO6") + { + conf.expo[5] = atoi(line.substr(pos + 1).c_str()); + } + else if (tmp_key == "GAIN6") + { + conf.gain[5] = atoi(line.substr(pos + 1).c_str()); + } + else if (tmp_key == "FILTER6") + { + conf.filter[5] = atoi(line.substr(pos + 1).c_str()); + } + else if (tmp_key == "USERID6") + { + conf.UserID[5] = atoi(line.substr(pos + 1).c_str()); + } + else if (tmp_key == "NO6") + { + std::vector vec_info; + string_split(line.substr(pos + 1), "|", vec_info); + if (vec_info.size() == 3) + { + conf.no[5][0] = atoi(vec_info[0].c_str()); + conf.no[5][1] = atoi(vec_info[1].c_str()); + conf.no[5][2] = atoi(vec_info[2].c_str()); + } + } + else if (tmp_key == "SHOOT6") + { + conf.shoot[5] = atoi(line.substr(pos + 1).c_str()); + } #endif #if defined(NumberOfSupportedCameras) && (NumberOfSupportedCameras>6) - else if (tmp_key == "EXPO7") - { - conf.expo[6] = atoi(line.substr(pos + 1).c_str()); - } - else if (tmp_key == "GAIN7") - { - conf.gain[6] = atoi(line.substr(pos + 1).c_str()); - } - else if (tmp_key == "FILTER7") - { - conf.filter[6] = atoi(line.substr(pos + 1).c_str()); - } - else if (tmp_key == "USERID7") - { - conf.UserID[6] = atoi(line.substr(pos + 1).c_str()); - } - else if (tmp_key == "NO7") - { - std::vector vec_info; - string_split(line.substr(pos + 1), "|", vec_info); - if (vec_info.size() == 3) - { - conf.no[6][0] = atoi(vec_info[0].c_str()); - conf.no[6][1] = atoi(vec_info[1].c_str()); - conf.no[6][2] = atoi(vec_info[2].c_str()); - } - } - else if (tmp_key == "SHOOT7") - { - conf.shoot[6] = atoi(line.substr(pos + 1).c_str()); - } + else if (tmp_key == "EXPO7") + { + conf.expo[6] = atoi(line.substr(pos + 1).c_str()); + } + else if (tmp_key == "GAIN7") + { + conf.gain[6] = atoi(line.substr(pos + 1).c_str()); + } + else if (tmp_key == "FILTER7") + { + conf.filter[6] = atoi(line.substr(pos + 1).c_str()); + } + else if (tmp_key == "USERID7") + { + conf.UserID[6] = atoi(line.substr(pos + 1).c_str()); + } + else if (tmp_key == "NO7") + { + std::vector vec_info; + string_split(line.substr(pos + 1), "|", vec_info); + if (vec_info.size() == 3) + { + conf.no[6][0] = atoi(vec_info[0].c_str()); + conf.no[6][1] = atoi(vec_info[1].c_str()); + conf.no[6][2] = atoi(vec_info[2].c_str()); + } + } + else if (tmp_key == "SHOOT7") + { + conf.shoot[6] = atoi(line.substr(pos + 1).c_str()); + } #endif #if defined(NumberOfSupportedCameras) && (NumberOfSupportedCameras>7) - else if (tmp_key == "EXPO8") - { - conf.expo[7] = atoi(line.substr(pos + 1).c_str()); - } - else if (tmp_key == "GAIN8") - { - conf.gain[7] = atoi(line.substr(pos + 1).c_str()); - } - else if (tmp_key == "FILTER8") - { - conf.filter[7] = atoi(line.substr(pos + 1).c_str()); - } - else if (tmp_key == "USERID8") - { - conf.UserID[7] = atoi(line.substr(pos + 1).c_str()); - } - else if (tmp_key == "NO8") - { - std::vector vec_info; - string_split(line.substr(pos + 1), "|", vec_info); - if (vec_info.size() == 3) - { - conf.no[7][0] = atoi(vec_info[0].c_str()); - conf.no[7][1] = atoi(vec_info[1].c_str()); - conf.no[7][2] = atoi(vec_info[2].c_str()); - } - } - else if (tmp_key == "SHOOT8") - { - conf.shoot[7] = atoi(line.substr(pos + 1).c_str()); - } -#endif - else if (tmp_key == "MonitorIP") - { - conf.MonitorIP = line.substr(pos + 1); - } - else if (tmp_key == "MonitorPort") - { - conf.MonitorPort = atoi(line.substr(pos + 1).c_str()); - conf.FeedbackPort = conf.MonitorPort + NumberOfSupportedCameras*2; - conf.FilePort = conf.MonitorPort + NumberOfSupportedCameras*2+2; - } - } - } - - cfg_file.close(); - ui.location->setText(g_sys_conf.location); - return true; -} - -bool Cigarette::read_modbus_config(ModbusConf &conf) + else if (tmp_key == "EXPO8") + { + conf.expo[7] = atoi(line.substr(pos + 1).c_str()); + } + else if (tmp_key == "GAIN8") + { + conf.gain[7] = atoi(line.substr(pos + 1).c_str()); + } + else if (tmp_key == "FILTER8") + { + conf.filter[7] = atoi(line.substr(pos + 1).c_str()); + } + else if (tmp_key == "USERID8") + { + conf.UserID[7] = atoi(line.substr(pos + 1).c_str()); + } + else if (tmp_key == "NO8") + { + std::vector vec_info; + string_split(line.substr(pos + 1), "|", vec_info); + if (vec_info.size() == 3) + { + conf.no[7][0] = atoi(vec_info[0].c_str()); + conf.no[7][1] = atoi(vec_info[1].c_str()); + conf.no[7][2] = atoi(vec_info[2].c_str()); + } + } + else if (tmp_key == "SHOOT8") + { + conf.shoot[7] = atoi(line.substr(pos + 1).c_str()); + } +#endif + else if (tmp_key == "MonitorIP") + { + conf.MonitorIP = line.substr(pos + 1); + } + else if (tmp_key == "MonitorPort") + { + conf.MonitorPort = atoi(line.substr(pos + 1).c_str()); + conf.FeedbackPort = conf.MonitorPort + NumberOfSupportedCameras * 2; + conf.FilePort = conf.MonitorPort + NumberOfSupportedCameras * 2 + 2; + } + } + } + + cfg_file.close(); + ui.location->setText(g_sys_conf.location); + return true; +} + +bool Cigarette::read_modbus_config(ModbusConf& conf) { - QString str_kick; - std::fstream cfg_file; - QString modbus_file = g_conf_path.config_path + "/" + MODBUS_CONFIGURE_FILE; - cfg_file.open(modbus_file.toLocal8Bit().constData()); - if (!cfg_file.is_open()) - { - std::cout << "Error: Open config file " << MODBUS_CONFIGURE_FILE << std::endl; - return false; - } - while (!cfg_file.eof()) - { - char tmp[256] = ""; - cfg_file.getline(tmp, 256); - std::string line(tmp); - if (line.length() > 0) - { - size_t pos = line.find('='); - std::string tmp_key = line.substr(0, pos); - for (int i = 0; i < NumberOfSupportedCameras; i++) { - str_kick = QString("KICK%1").arg(i+1); - if (tmp_key == str_kick.toStdString()) - conf.kick[i] = atoi(line.substr(pos + 1).c_str()); - } - if (tmp_key == "QUANTITY") - { - conf.quantity = atoi(line.substr(pos + 1).c_str()); - } - else if (tmp_key == "SHIFT") - { - conf.shift = atoi(line.substr(pos + 1).c_str()); - } - else if (tmp_key == "WORK") - { - conf.work = atoi(line.substr(pos + 1).c_str()); - } - else if (tmp_key == "NO_KICK") - { - conf.no_kick = atoi(line.substr(pos + 1).c_str()); - } - else if (tmp_key == "DEBUG") - { - conf.debug = atoi(line.substr(pos + 1).c_str()); - } - else if (tmp_key == "RESET") - { - conf.reset = atoi(line.substr(pos + 1).c_str()); - } - else if (tmp_key == "ALARM") - { - conf.alarm = atoi(line.substr(pos + 1).c_str()); - } - } - } - cfg_file.close(); - return true; -} - -//读取相机图像旋转参数 + QString str_kick; + std::fstream cfg_file; + QString modbus_file = g_conf_path.config_path + "/" + MODBUS_CONFIGURE_FILE; + cfg_file.open(modbus_file.toLocal8Bit().constData()); + if (!cfg_file.is_open()) + { + std::cout << "Error: Open config file " << MODBUS_CONFIGURE_FILE << std::endl; + return false; + } + while (!cfg_file.eof()) + { + char tmp[256] = ""; + cfg_file.getline(tmp, 256); + std::string line(tmp); + if (line.length() > 0) + { + size_t pos = line.find('='); + std::string tmp_key = line.substr(0, pos); + for (int i = 0; i < NumberOfSupportedCameras; i++) { + str_kick = QString("KICK%1").arg(i + 1); + if (tmp_key == str_kick.toStdString()) + conf.kick[i] = atoi(line.substr(pos + 1).c_str()); + } + if (tmp_key == "QUANTITY") + { + conf.quantity = atoi(line.substr(pos + 1).c_str()); + } + else if (tmp_key == "SHIFT") + { + conf.shift = atoi(line.substr(pos + 1).c_str()); + } + else if (tmp_key == "WORK") + { + conf.work = atoi(line.substr(pos + 1).c_str()); + } + else if (tmp_key == "NO_KICK") + { + conf.no_kick = atoi(line.substr(pos + 1).c_str()); + } + else if (tmp_key == "DEBUG") + { + conf.debug = atoi(line.substr(pos + 1).c_str()); + } + else if (tmp_key == "RESET") + { + conf.reset = atoi(line.substr(pos + 1).c_str()); + } + else if (tmp_key == "ALARM") + { + conf.alarm = atoi(line.substr(pos + 1).c_str()); + } + } + } + cfg_file.close(); + return true; +} + +//璇诲彇鐩告満鍥惧儚鏃嬭浆鍙傛暟 bool Cigarette::read_rotate_message() { - std::fstream cfg_file; - QString rotate_file = g_conf_path.config_path + "/" + ROTATE_FILE; - cfg_file.open(rotate_file.toLocal8Bit().constData()); - if (!cfg_file.is_open()) - { - std::cout << "Error: Open config file rotate.txt" << std::endl; - return false; - } - if (!cfg_file.eof()) - { - char tmp[256]; - memset(tmp, 0, 256); - cfg_file.getline(tmp, 256); - QStringList rotate_message = QString(QLatin1String(tmp)).split(","); - if (rotate_message.length() > NumberOfSupportedCameras*2) - { - for (int i = 0; i < NumberOfSupportedCameras; i++) { - isNeedRotate[i] = rotate_message[i * 2].toInt(); - rotationAngle[i] = rotate_message[i * 2 + 1].toInt(); - } - } - else - { - return false; - } - } - else - { - return false; - } - cfg_file.close(); - return true; -} - -//保存相机图像旋转参数 + std::fstream cfg_file; + QString rotate_file = g_conf_path.config_path + "/" + ROTATE_FILE; + cfg_file.open(rotate_file.toLocal8Bit().constData()); + if (!cfg_file.is_open()) + { + std::cout << "Error: Open config file rotate.txt" << std::endl; + return false; + } + if (!cfg_file.eof()) + { + char tmp[256]; + memset(tmp, 0, 256); + cfg_file.getline(tmp, 256); + QStringList rotate_message = QString(QLatin1String(tmp)).split(","); + if (rotate_message.length() > NumberOfSupportedCameras * 2) + { + for (int i = 0; i < NumberOfSupportedCameras; i++) { + isNeedRotate[i] = rotate_message[i * 2].toInt(); + rotationAngle[i] = rotate_message[i * 2 + 1].toInt(); + } + } + else + { + return false; + } + } + else + { + return false; + } + cfg_file.close(); + return true; +} + +//淇濆瓨鐩告満鍥惧儚鏃嬭浆鍙傛暟 bool Cigarette::save_rotate_message() { - std::fstream cfg_file; - QString rotate_file = g_conf_path.config_path + "/" + ROTATE_FILE; - cfg_file.open(rotate_file.toLocal8Bit().constData(), ios::trunc | ofstream::out); - if (!cfg_file.is_open()) - { - std::cout << "Error: Open config file rotate.txt" << std::endl; - return false; - } - for (int i = 0; i < NumberOfSupportedCameras; i++) { - char tmp[8]; - memset(tmp, 0, 8); - itoa(isNeedRotate[i], tmp, 10); - cfg_file.write(tmp, 1); - cfg_file.write(",", 1); - memset(tmp, 0, 8); - itoa(rotationAngle[i], tmp, 10); - cfg_file.write(tmp, 1); - cfg_file.write(",", 1); - } - cfg_file.close(); - return true; -} - -//保存报警信息 -bool Cigarette::save_alarm_message(std::vector &AlarmInfo_vect) + std::fstream cfg_file; + QString rotate_file = g_conf_path.config_path + "/" + ROTATE_FILE; + cfg_file.open(rotate_file.toLocal8Bit().constData(), ios::trunc | ofstream::out); + if (!cfg_file.is_open()) + { + std::cout << "Error: Open config file rotate.txt" << std::endl; + return false; + } + for (int i = 0; i < NumberOfSupportedCameras; i++) { + char tmp[8]; + memset(tmp, 0, 8); + itoa(isNeedRotate[i], tmp, 10); + cfg_file.write(tmp, 1); + cfg_file.write(",", 1); + memset(tmp, 0, 8); + itoa(rotationAngle[i], tmp, 10); + cfg_file.write(tmp, 1); + cfg_file.write(",", 1); + } + cfg_file.close(); + return true; +} + +//淇濆瓨鎶ヨ淇℃伅 +bool Cigarette::save_alarm_message(std::vector& AlarmInfo_vect) { - std::fstream cfg_file; - cfg_file.open(ALARM_RECORD_FILE); - if (!cfg_file.is_open()) - { - std::cout << "Error: Open config file alarm.txt" << std::endl; - return false; - } - - for (int i = 0; i < AlarmInfo_vect.size(); i++) { - char buf[256]; - memset(buf, 0, 256); - sprintf(buf, "%s_%s_%s_%d\n", AlarmInfo_vect[i].alarm_start, AlarmInfo_vect[i].alarm_handle, AlarmInfo_vect[i].alarm_msg, AlarmInfo_vect[i].alarm_code); - cfg_file.write(buf, strlen(buf)); - } - cfg_file.close(); - return true; + std::fstream cfg_file; + cfg_file.open(ALARM_RECORD_FILE); + if (!cfg_file.is_open()) + { + std::cout << "Error: Open config file alarm.txt" << std::endl; + return false; + } + + for (int i = 0; i < AlarmInfo_vect.size(); i++) { + char buf[256]; + memset(buf, 0, 256); + sprintf(buf, "%s_%s_%s_%d\n", AlarmInfo_vect[i].alarm_start, AlarmInfo_vect[i].alarm_handle, AlarmInfo_vect[i].alarm_msg, AlarmInfo_vect[i].alarm_code); + cfg_file.write(buf, strlen(buf)); + } + cfg_file.close(); + return true; } QImage Cigarette::cvMatToQImage(const cv::Mat& mat) { - const unsigned char* data = mat.data; - int width = mat.cols; - int height = mat.rows; - int bytesPerLine = static_cast(mat.step); - switch (mat.type()) - { - // 8bit, ARGB - case CV_8UC4: - { - QImage image(data, width, height, bytesPerLine, - QImage::Format_ARGB32); - return image; - } - // 8bit, BGR - case CV_8UC3: - { - QImage image(data, width, height, bytesPerLine, - QImage::Format_RGB888); - //swap blue and red channel - return image.rgbSwapped(); - } - // 8bit, Grayshale - case CV_8UC1: - { - QImage image(data, width, height, bytesPerLine, - QImage::Format_Grayscale8); - return image; - } - default: - { - return QImage(); - } - } + const unsigned char* data = mat.data; + int width = mat.cols; + int height = mat.rows; + int bytesPerLine = static_cast(mat.step); + switch (mat.type()) + { + // 8bit, ARGB + case CV_8UC4: + { + QImage image(data, width, height, bytesPerLine, + QImage::Format_ARGB32); + return image; + } + // 8bit, BGR + case CV_8UC3: + { + QImage image(data, width, height, bytesPerLine, + QImage::Format_RGB888); + //swap blue and red channel + return image.rgbSwapped(); + } + // 8bit, Grayshale + case CV_8UC1: + { + QImage image(data, width, height, bytesPerLine, + QImage::Format_Grayscale8); + return image; + } + default: + { + return QImage(); + } + } } void Cigarette::read_plc_items() { - std::fstream cfg_file; - QString plc_file = g_conf_path.config_path + "/" + PLC_CONFIG_FILE; - cfg_file.open(plc_file.toLocal8Bit().constData()); - - if (!cfg_file.is_open()) - { - std::cout << "Error: Open production file " << PLC_CONFIG_FILE << std::endl; - return; - } - - while (!cfg_file.eof()) - { - char tmp[1024] = ""; - cfg_file.getline(tmp, 1024); - std::string line(tmp); - //std::cout << line << std::endl; - if (line.length() > 0) - { - std::vector vec_info; - string_split(line, "|",vec_info); - if (vec_info.size() == 4) - { - PlcItem plc_item; - plc_item.func_desc = vec_info[0]; - plc_item.address = atoi(vec_info[1].c_str()); - plc_item.value = atoi(vec_info[2].c_str()); - plc_item.memo = vec_info[3]; - m_plc_items.push_back(plc_item); - } - } - } - cfg_file.close(); + std::fstream cfg_file; + QString plc_file = g_conf_path.config_path + "/" + PLC_CONFIG_FILE; + cfg_file.open(plc_file.toLocal8Bit().constData()); + + if (!cfg_file.is_open()) + { + std::cout << "Error: Open production file " << PLC_CONFIG_FILE << std::endl; + return; + } + + while (!cfg_file.eof()) + { + char tmp[1024] = ""; + cfg_file.getline(tmp, 1024); + std::string line(tmp); + //std::cout << line << std::endl; + if (line.length() > 0) + { + std::vector vec_info; + string_split(line, "|", vec_info); + if (vec_info.size() == 4) + { + PlcItem plc_item; + plc_item.func_desc = vec_info[0]; + plc_item.address = atoi(vec_info[1].c_str()); + plc_item.value = atoi(vec_info[2].c_str()); + plc_item.memo = vec_info[3]; + m_plc_items.push_back(plc_item); + } + } + } + cfg_file.close(); } void Cigarette::init_plc_value() { - for (int i = 0; i < m_plc_items.size(); i++) - { - int addr = m_plc_items[i].address; - int data = m_plc_items[i].value; - if (addr > 0) - { - uint8_t dest[4]; - uint16_t * dest16 = (uint16_t *)dest; - memset(dest, 0, 4); - if (addr > 0) - { - if (addr < 40000) //写入线圈值 bit - { - if (data != 0) data = 1; - m_PLCDevice->write_bit_2_plc( addr, data); - } - else { //写入DWORD值,4字节 - dest16[0] = (data & 0xffff); - dest16[1] = (data >> 16); - m_PLCDevice->write_short_2_plc(addr, 2, dest16); - } - } - } - } -} - -void Cigarette::CreatWorkThread(int classid,int Num,Cigarette* classptr) + for (int i = 0; i < m_plc_items.size(); i++) + { + int addr = m_plc_items[i].address; + int data = m_plc_items[i].value; + if (addr > 0) + { + uint8_t dest[4]; + uint16_t* dest16 = (uint16_t*)dest; + memset(dest, 0, 4); + if (addr > 0) + { + if (addr < 40000) //鍐欏叆绾垮湀鍊 bit + { + if (data != 0) data = 1; + m_PLCDevice->write_bit_2_plc(addr, data); + } + else { //鍐欏叆DWORD鍊硷紝4瀛楄妭 + dest16[0] = (data & 0xffff); + dest16[1] = (data >> 16); + m_PLCDevice->write_short_2_plc(addr, 2, dest16); + } + } + } + } +} + +void Cigarette::CreatWorkThread(int classid, int Num, Cigarette* classptr) { #ifdef SYNC_CAMERA - sync_work_thread.init(g_image_sync_queue, g_result_queue[0]); - connect(&sync_work_thread, SIGNAL(notify(int,int,cv::Mat)), classptr, SLOT(OnNotifyHub(int,int,cv::Mat))); - connect(&sync_work_thread, SIGNAL(display_timecost(int,int)), classptr, SLOT(OnDisplayTimeCostHub(int,int))); - connect(&sync_work_thread, SIGNAL(display_check_total(int,long)), classptr, SLOT(OnDisplayCheckNumberHub(int,long))); - connect(&sync_work_thread, SIGNAL(display_jd_no(int,QString)), classptr, SLOT(OnDisplayJdNoHub(int,QString))); - connect(&sync_work_thread, SIGNAL(event_ok(int)), classptr, SLOT(OnOKHub(int))); - connect(&sync_work_thread, SIGNAL(event_ng(int)), classptr, SLOT(OnNGHub(int))); - sync_work_thread.start_work(); + sync_work_thread.init(g_image_sync_queue, g_result_queue[0]); + connect(&sync_work_thread, SIGNAL(notify(int, int, cv::Mat)), classptr, SLOT(OnNotifyHub(int, int, cv::Mat))); + connect(&sync_work_thread, SIGNAL(display_timecost(int, int)), classptr, SLOT(OnDisplayTimeCostHub(int, int))); + connect(&sync_work_thread, SIGNAL(display_check_total(int, long)), classptr, SLOT(OnDisplayCheckNumberHub(int, long))); + connect(&sync_work_thread, SIGNAL(display_jd_no(int, QString)), classptr, SLOT(OnDisplayJdNoHub(int, QString))); + connect(&sync_work_thread, SIGNAL(event_ok(int)), classptr, SLOT(OnOKHub(int))); + connect(&sync_work_thread, SIGNAL(event_ng(int)), classptr, SLOT(OnNGHub(int))); + sync_work_thread.start_work(); #else - work_thread[Num].init(g_image_queue[Num], g_result_queue[Num], classid, Num); - connect(&work_thread[Num], SIGNAL(notify(int,int,cv::Mat)), classptr, SLOT(OnNotifyHub(int,int,cv::Mat))); - connect(&work_thread[Num], SIGNAL(display_timecost(int,int)), classptr, SLOT(OnDisplayTimeCostHub(int,int))); - connect(&work_thread[Num], SIGNAL(display_check_total(int,long)), classptr, SLOT(OnDisplayCheckNumberHub(int,long))); - connect(&work_thread[Num], SIGNAL(display_jd_no(int,QString)), classptr, SLOT(OnDisplayJdNoHub(int,QString))); - connect(&work_thread[Num], SIGNAL(event_ok(int)), classptr, SLOT(OnOKHub(int))); - connect(&work_thread[Num], SIGNAL(event_ng(int)), classptr, SLOT(OnNGHub(int))); - work_thread[Num].start_work(); + work_thread[Num].init(g_image_queue[Num], g_result_queue[Num], classid, Num); + connect(&work_thread[Num], SIGNAL(notify(int, int, cv::Mat)), classptr, SLOT(OnNotifyHub(int, int, cv::Mat))); + connect(&work_thread[Num], SIGNAL(display_timecost(int, int)), classptr, SLOT(OnDisplayTimeCostHub(int, int))); + connect(&work_thread[Num], SIGNAL(display_check_total(int, long)), classptr, SLOT(OnDisplayCheckNumberHub(int, long))); + connect(&work_thread[Num], SIGNAL(display_jd_no(int, QString)), classptr, SLOT(OnDisplayJdNoHub(int, QString))); + connect(&work_thread[Num], SIGNAL(event_ok(int)), classptr, SLOT(OnOKHub(int))); + connect(&work_thread[Num], SIGNAL(event_ng(int)), classptr, SLOT(OnNGHub(int))); + work_thread[Num].start_work(); - debug_thread[Num].init(g_debug_queue[Num],Num); - connect(&debug_thread[Num], SIGNAL(notify(int,int,cv::Mat)), classptr, SLOT(OnNotifyHub(int,int,cv::Mat))); - debug_thread[Num].start_work(); + debug_thread[Num].init(g_debug_queue[Num], Num); + connect(&debug_thread[Num], SIGNAL(notify(int, int, cv::Mat)), classptr, SLOT(OnNotifyHub(int, int, cv::Mat))); + debug_thread[Num].start_work(); #endif } @@ -2846,1227 +2856,1227 @@ label_ng_mat[a]=ui.label_ng_##b; void Cigarette::InitPtrMat() { #if defined(NumberOfSupportedCameras) && (NumberOfSupportedCameras>0) - InitPtrMat_init(0,1) + InitPtrMat_init(0, 1) #endif #if defined(NumberOfSupportedCameras) && (NumberOfSupportedCameras>1) - InitPtrMat_init(1,2) + InitPtrMat_init(1, 2) #endif #if defined(NumberOfSupportedCameras) && (NumberOfSupportedCameras>2) - InitPtrMat_init(2,3) + InitPtrMat_init(2, 3) #endif #if defined(NumberOfSupportedCameras) && (NumberOfSupportedCameras>3) - InitPtrMat_init(3,4) + InitPtrMat_init(3, 4) #endif #if defined(NumberOfSupportedCameras) && (NumberOfSupportedCameras>4) - InitPtrMat_init(4,5) + InitPtrMat_init(4, 5) #endif #if defined(NumberOfSupportedCameras) && (NumberOfSupportedCameras>5) - InitPtrMat_init(5,6) + InitPtrMat_init(5, 6) #endif #if defined(NumberOfSupportedCameras) && (NumberOfSupportedCameras>6) - InitPtrMat_init(6,7) + InitPtrMat_init(6, 7) #endif #if defined(NumberOfSupportedCameras) && (NumberOfSupportedCameras>7) - InitPtrMat_init(7,8) -#endif - for(int i=0;igeometry().x(); - display_lable_info[i][j].y = display_lable_mat[i][j]->geometry().y(); - display_lable_info[i][j].width = display_lable_mat[i][j]->geometry().width(); - display_lable_info[i][j].height = display_lable_mat[i][j]->geometry().height(); - } - rotate_info[i].x = rotate_mat[i]->geometry().x(); - rotate_info[i].y = rotate_mat[i]->geometry().y(); - rotate_info[i].width = rotate_mat[i]->geometry().width(); - rotate_info[i].height = rotate_mat[i]->geometry().height(); - } - -} - -bool Cigarette::ControlCamOpenOrClose(int Num,bool OpenOrClose) + InitPtrMat_init(7, 8) +#endif + for (int i = 0; i < NumberOfSupportedCameras; i++) + { + for (int j = 0; j < 2; j++) + { + display_lable_info[i][j].x = display_lable_mat[i][j]->geometry().x(); + display_lable_info[i][j].y = display_lable_mat[i][j]->geometry().y(); + display_lable_info[i][j].width = display_lable_mat[i][j]->geometry().width(); + display_lable_info[i][j].height = display_lable_mat[i][j]->geometry().height(); + } + rotate_info[i].x = rotate_mat[i]->geometry().x(); + rotate_info[i].y = rotate_mat[i]->geometry().y(); + rotate_info[i].width = rotate_mat[i]->geometry().width(); + rotate_info[i].height = rotate_mat[i]->geometry().height(); + } + +} + +bool Cigarette::ControlCamOpenOrClose(int Num, bool OpenOrClose) { - if(OpenOrClose == OPEN && !SingleCamInfo[Num].IsOpen) - { - if (SingleCamInfo[Num].CamClass == BalluffClassID) - { - qDebug() << "open for balluff"; - try - { - Device* pDev = BalluffCamera::devMgr[SingleCamInfo[Num].unfiltered_num]; - conditionalSetProperty(pDev->interfaceLayout, dilGenICam); - pDev->open(); - // Configure timer1 - mvIMPACT::acquire::GenICam::CounterAndTimerControl mvCATC(pDev); - mvCATC.timerSelector.writeS("Timer1"); - mvCATC.timerTriggerSource.writeS("UserOutput0"); - mvCATC.timerDuration.write(StrobeLineTime); - mvCATC.timerTriggerActivation.writeS("AnyEdge"); - // Configure timer2 - mvCATC.timerSelector.writeS("Timer2"); - mvCATC.timerTriggerSource.writeS("UserOutput1"); - mvCATC.timerDuration.write(StrobeLineTime); - mvCATC.timerTriggerActivation.writeS("AnyEdge"); - - //Configure output1 - mvIMPACT::acquire::GenICam::DigitalIOControl mvDIOC(pDev); - mvDIOC.lineSelector.writeS("Line0"); - mvDIOC.lineSource.writeS("Timer1Active"); - //Configure output2 - mvDIOC.lineSelector.writeS("Line1"); - mvDIOC.lineSource.writeS("Timer2Active"); - - //设置滤波 - mvDIOC.lineSelector.writeS("Line4"); - mvDIOC.mvLineDebounceTimeRisingEdge.write(g_sys_conf.filter[Num]); - //设置滤波 - mvDIOC.lineSelector.writeS("Line5"); - mvDIOC.mvLineDebounceTimeRisingEdge.write(g_sys_conf.filter[Num]); - //设置binning - mvIMPACT::acquire::GenICam::ImageFormatControl ifc = mvIMPACT::acquire::GenICam::ImageFormatControl(pDev); - ifc.binningHorizontalMode.writeS("Sum"); - ifc.binningHorizontal.write(2); - ifc.binningVerticalMode.writeS("Sum"); - ifc.binningVertical.write(2); - - pFI[Num] = new FunctionInterface(pDev); - if (pDev->interfaceLayout.isValid() && (pDev->interfaceLayout.read() == dilGenICam)) - { - pAC[Num] = new mvIMPACT::acquire::GenICam::AcquisitionControl(pDev); - //设置外触发 - pAC[Num]->triggerMode.writeS("On"); - pAC[Num]->triggerSource.writeS("Line4"); - pAC[Num]->triggerActivation.writeS("RisingEdge"); - //设置曝光时间 - pAC[Num]->exposureTime.writeS(QString::number(g_sys_conf.expo[Num]).toStdString()); - //设置增益 - mvIMPACT::acquire::GenICam::AnalogControl *pac = new mvIMPACT::acquire::GenICam::AnalogControl(pDev); - pac->gain.write(g_sys_conf.gain[Num]); - } - pCaptureThread[Num] = new CaptureThread(BalluffCamera::devMgr[SingleCamInfo[Num].unfiltered_num], false, pFI[Num],Num); + if (OpenOrClose == OPEN && !SingleCamInfo[Num].IsOpen) + { + if (SingleCamInfo[Num].CamClass == BalluffClassID) + { + qDebug() << "open for balluff"; + try + { + Device* pDev = BalluffCamera::devMgr[SingleCamInfo[Num].unfiltered_num]; + conditionalSetProperty(pDev->interfaceLayout, dilGenICam); + pDev->open(); + // Configure timer1 + mvIMPACT::acquire::GenICam::CounterAndTimerControl mvCATC(pDev); + mvCATC.timerSelector.writeS("Timer1"); + mvCATC.timerTriggerSource.writeS("UserOutput0"); + mvCATC.timerDuration.write(StrobeLineTime); + mvCATC.timerTriggerActivation.writeS("AnyEdge"); + // Configure timer2 + mvCATC.timerSelector.writeS("Timer2"); + mvCATC.timerTriggerSource.writeS("UserOutput1"); + mvCATC.timerDuration.write(StrobeLineTime); + mvCATC.timerTriggerActivation.writeS("AnyEdge"); + + //Configure output1 + mvIMPACT::acquire::GenICam::DigitalIOControl mvDIOC(pDev); + mvDIOC.lineSelector.writeS("Line0"); + mvDIOC.lineSource.writeS("Timer1Active"); + //Configure output2 + mvDIOC.lineSelector.writeS("Line1"); + mvDIOC.lineSource.writeS("Timer2Active"); + + //璁剧疆婊ゆ尝 + mvDIOC.lineSelector.writeS("Line4"); + mvDIOC.mvLineDebounceTimeRisingEdge.write(g_sys_conf.filter[Num]); + //璁剧疆婊ゆ尝 + mvDIOC.lineSelector.writeS("Line5"); + mvDIOC.mvLineDebounceTimeRisingEdge.write(g_sys_conf.filter[Num]); + //璁剧疆binning + mvIMPACT::acquire::GenICam::ImageFormatControl ifc = mvIMPACT::acquire::GenICam::ImageFormatControl(pDev); + ifc.binningHorizontalMode.writeS("Sum"); + ifc.binningHorizontal.write(2); + ifc.binningVerticalMode.writeS("Sum"); + ifc.binningVertical.write(2); + + pFI[Num] = new FunctionInterface(pDev); + if (pDev->interfaceLayout.isValid() && (pDev->interfaceLayout.read() == dilGenICam)) + { + pAC[Num] = new mvIMPACT::acquire::GenICam::AcquisitionControl(pDev); + //璁剧疆澶栬Е鍙 + pAC[Num]->triggerMode.writeS("On"); + pAC[Num]->triggerSource.writeS("Line4"); + pAC[Num]->triggerActivation.writeS("RisingEdge"); + //璁剧疆鏇濆厜鏃堕棿 + pAC[Num]->exposureTime.writeS(QString::number(g_sys_conf.expo[Num]).toStdString()); + //璁剧疆澧炵泭 + mvIMPACT::acquire::GenICam::AnalogControl* pac = new mvIMPACT::acquire::GenICam::AnalogControl(pDev); + pac->gain.write(g_sys_conf.gain[Num]); + } + pCaptureThread[Num] = new CaptureThread(BalluffCamera::devMgr[SingleCamInfo[Num].unfiltered_num], false, pFI[Num], Num); #ifdef SYNC_CAMERA - pCaptureThread[Num]->p_image_sync_queue = g_image_sync_queue; - pCaptureThread[Num]->p_image_sync_arr = &g_image_sync_arr; + pCaptureThread[Num]->p_image_sync_queue = g_image_sync_queue; + pCaptureThread[Num]->p_image_sync_arr = &g_image_sync_arr; #else - pCaptureThread[Num]->p_image_queue = g_image_queue[Num]; -#endif - pCaptureThread[Num]->p_result_queue = g_result_queue[Num]; - pCaptureThread[Num]->p_result_wait_queue = g_result_wait_queue[Num]; - pCaptureThread[Num]->p_double_queue = g_double_queue[Num]; - pCaptureThread[Num]->p_shooted_queue = g_shooted_queue[Num]; - pCaptureThread[Num]->p_debug_queue = g_debug_queue[Num]; - - pThread[Num] = new QThread; - pCaptureThread[Num]->moveToThread(pThread[Num]); - - // Signal emitted in case of acquisition errors - connect(pThread[Num], SIGNAL(started()), pCaptureThread[Num], SLOT(process())); - //connect(pCaptureThread[Num], SIGNAL(error(QString)), this, SLOT(errorString(QString))); - connect(pCaptureThread[Num], SIGNAL(finished()), pThread[Num], SLOT(quit())); - connect(pCaptureThread[Num], SIGNAL(finished()), pCaptureThread[Num], SLOT(deleteLater())); - if(!g_debug_mode) - connect(pCaptureThread[Num], SIGNAL(updateStatistics(const QString&,int)), this, SLOT(updateStatisticsHub(const QString&,int))); - - pThread[Num]->start(); - if (pThread[Num]->isRunning()) - { - qDebug() << "balluff pThread OK"; - SingleCamInfo[Num].IsOpen =true; - return true; - } - } - catch (const ImpactAcquireException& e) - { - QString msg; - QTextStream(&msg) << "Error while opening device! Error message: " << QString::fromStdString(e.getErrorCodeAsString()) << "\nError Code: " << e.getErrorCode(); - QMessageBox::warning(this, "Error", msg, QMessageBox::Ok, QMessageBox::Ok); - } - return false; - } - else if (SingleCamInfo[Num].CamClass == BaslerClassID) - { - qDebug() << "open for basler"; - try - { - Pylon::CBaslerUniversalInstantCamera *baslerCamera = new Pylon::CBaslerUniversalInstantCamera(Pylon::CTlFactory::GetInstance().CreateDevice(BaslerCamera::devices[SingleCamInfo[Num].filtered_num])); - BaslerCamHandle[Num]=baslerCamera; - - // Camera event processing must be activated first, the default is off. - baslerCamera->GrabCameraEvents = true; - - baslerCamera->Open(); - baslerCamera->LineSelector.SetValue(Basler_UniversalCameraParams::LineSelector_Line1); - if (!baslerCamera->LineDebouncerTime.TrySetValue(g_sys_conf.filter[Num]/1.0)) - { - std::cout << "can not set LineDebouncerTime" << std::endl; - if(!baslerCamera->BslInputFilterTime.TrySetValue(g_sys_conf.filter[Num]/1.0)) - std::cout << "can not set BslInputFilterTime" << std::endl; - } - baslerCamera->LineSelector.SetValue(Basler_UniversalCameraParams::LineSelector_Line3); - baslerCamera->LineMode.SetValue(Basler_UniversalCameraParams::LineMode_Input); - if (!baslerCamera->LineDebouncerTime.TrySetValue(g_sys_conf.filter[Num]/1.0)) - { - std::cout << "can not set LineDebouncerTime" << std::endl; - if (!baslerCamera->BslInputFilterTime.TrySetValue(g_sys_conf.filter[Num]/1.0)) - std::cout << "can not set BslInputFilterTime" << std::endl; - } - if (baslerCamera->LineSelector.TrySetValue(Basler_UniversalCameraParams::LineSelector_Line4)) - { - baslerCamera->LineMode.SetValue(Basler_UniversalCameraParams::LineMode_Output); + pCaptureThread[Num]->p_image_queue = g_image_queue[Num]; +#endif + pCaptureThread[Num]->p_result_queue = g_result_queue[Num]; + pCaptureThread[Num]->p_result_wait_queue = g_result_wait_queue[Num]; + pCaptureThread[Num]->p_double_queue = g_double_queue[Num]; + pCaptureThread[Num]->p_shooted_queue = g_shooted_queue[Num]; + pCaptureThread[Num]->p_debug_queue = g_debug_queue[Num]; + + pThread[Num] = new QThread; + pCaptureThread[Num]->moveToThread(pThread[Num]); + + // Signal emitted in case of acquisition errors + connect(pThread[Num], SIGNAL(started()), pCaptureThread[Num], SLOT(process())); + //connect(pCaptureThread[Num], SIGNAL(error(QString)), this, SLOT(errorString(QString))); + connect(pCaptureThread[Num], SIGNAL(finished()), pThread[Num], SLOT(quit())); + connect(pCaptureThread[Num], SIGNAL(finished()), pCaptureThread[Num], SLOT(deleteLater())); + if (!g_debug_mode) + connect(pCaptureThread[Num], SIGNAL(updateStatistics(const QString&, int)), this, SLOT(updateStatisticsHub(const QString&, int))); + + pThread[Num]->start(); + if (pThread[Num]->isRunning()) + { + qDebug() << "balluff pThread OK"; + SingleCamInfo[Num].IsOpen = true; + return true; + } + } + catch (const ImpactAcquireException& e) + { + QString msg; + QTextStream(&msg) << "Error while opening device! Error message: " << QString::fromStdString(e.getErrorCodeAsString()) << "\nError Code: " << e.getErrorCode(); + QMessageBox::warning(this, "Error", msg, QMessageBox::Ok, QMessageBox::Ok); + } + return false; + } + else if (SingleCamInfo[Num].CamClass == BaslerClassID) + { + qDebug() << "open for basler"; + try + { + Pylon::CBaslerUniversalInstantCamera* baslerCamera = new Pylon::CBaslerUniversalInstantCamera(Pylon::CTlFactory::GetInstance().CreateDevice(BaslerCamera::devices[SingleCamInfo[Num].filtered_num])); + BaslerCamHandle[Num] = baslerCamera; + + // Camera event processing must be activated first, the default is off. + baslerCamera->GrabCameraEvents = true; + + baslerCamera->Open(); + baslerCamera->LineSelector.SetValue(Basler_UniversalCameraParams::LineSelector_Line1); + if (!baslerCamera->LineDebouncerTime.TrySetValue(g_sys_conf.filter[Num] / 1.0)) + { + std::cout << "can not set LineDebouncerTime" << std::endl; + if (!baslerCamera->BslInputFilterTime.TrySetValue(g_sys_conf.filter[Num] / 1.0)) + std::cout << "can not set BslInputFilterTime" << std::endl; + } + baslerCamera->LineSelector.SetValue(Basler_UniversalCameraParams::LineSelector_Line3); + baslerCamera->LineMode.SetValue(Basler_UniversalCameraParams::LineMode_Input); + if (!baslerCamera->LineDebouncerTime.TrySetValue(g_sys_conf.filter[Num] / 1.0)) + { + std::cout << "can not set LineDebouncerTime" << std::endl; + if (!baslerCamera->BslInputFilterTime.TrySetValue(g_sys_conf.filter[Num] / 1.0)) + std::cout << "can not set BslInputFilterTime" << std::endl; + } + if (baslerCamera->LineSelector.TrySetValue(Basler_UniversalCameraParams::LineSelector_Line4)) + { + baslerCamera->LineMode.SetValue(Basler_UniversalCameraParams::LineMode_Output); #ifdef USB_BASLER_NEW_FW - GENAPI_NAMESPACE::INodeMap& nodemap = baslerCamera->GetNodeMap(); - Pylon::CFloatParameter(nodemap, "UserOutputDuration").SetValue(StrobeLineTime); -#endif - if (baslerCamera->LineSource.TrySetValue(Basler_UniversalCameraParams::LineSource_UserOutput3)) - { - baslerCamera->UserOutputSelector.SetValue(Basler_UniversalCameraParams::UserOutputSelector_UserOutput3); - baslerCamera->UserOutputValue.SetValue(false); - } - else - { - std::cout << "can not set LineSource_UserOutput3" << std::endl; - } - } - else - { - std::cout << "can not set LineSelector_Line4" << std::endl; - } - - baslerCamera->LineSelector.SetValue(Basler_UniversalCameraParams::LineSelector_Line2); + GENAPI_NAMESPACE::INodeMap& nodemap = baslerCamera->GetNodeMap(); + Pylon::CFloatParameter(nodemap, "UserOutputDuration").SetValue(StrobeLineTime); +#endif + if (baslerCamera->LineSource.TrySetValue(Basler_UniversalCameraParams::LineSource_UserOutput3)) + { + baslerCamera->UserOutputSelector.SetValue(Basler_UniversalCameraParams::UserOutputSelector_UserOutput3); + baslerCamera->UserOutputValue.SetValue(false); + } + else + { + std::cout << "can not set LineSource_UserOutput3" << std::endl; + } + } + else + { + std::cout << "can not set LineSelector_Line4" << std::endl; + } + + baslerCamera->LineSelector.SetValue(Basler_UniversalCameraParams::LineSelector_Line2); #ifdef USB_BASLER_NEW_FW - GENAPI_NAMESPACE::INodeMap& nodemap = baslerCamera->GetNodeMap(); - Pylon::CFloatParameter(nodemap, "UserOutputDuration").SetValue(StrobeLineTime); -#endif - if (baslerCamera->LineSource.TrySetValue(Basler_UniversalCameraParams::LineSource_UserOutput1)) - { - baslerCamera->UserOutputSelector.SetValue(Basler_UniversalCameraParams::UserOutputSelector_UserOutput1); - baslerCamera->UserOutputValue.SetValue(false); - } - else - { - std::cout << "can not set LineSource_UserOutput1" << std::endl; - } - - baslerCamera->ExposureAuto.SetValue(Basler_UniversalCameraParams::ExposureAuto_Off); - baslerCamera->ExposureMode.SetValue(Basler_UniversalCameraParams::ExposureMode_Timed); - baslerCamera->ExposureTime.SetValue(g_sys_conf.expo[Num]); - - baslerCamera->GainSelector.SetValue(Basler_UniversalCameraParams::GainSelector_All); - baslerCamera->GainAuto.SetValue(Basler_UniversalCameraParams::GainAuto_Off); - baslerCamera->Gain.SetValue(g_sys_conf.gain[Num]); - - baslerCamera->TriggerSelector.SetValue(Basler_UniversalCameraParams::TriggerSelector_FrameStart); - baslerCamera->TriggerMode.SetValue(Basler_UniversalCameraParams::TriggerMode_On); - baslerCamera->TriggerSource.SetValue(Basler_UniversalCameraParams::TriggerSource_Line3); - baslerCamera->TriggerActivation.SetValue(Basler_UniversalCameraParams::TriggerActivation_RisingEdge); - - baslerCamera->BinningHorizontal.SetValue(2); - baslerCamera->BinningVertical.SetValue(2); - - pBaslerCaptureThread[Num] = new CaptureThreadBasler(baslerCamera, false, Num,g_sys_conf.shoot[Num]); + GENAPI_NAMESPACE::INodeMap& nodemap = baslerCamera->GetNodeMap(); + Pylon::CFloatParameter(nodemap, "UserOutputDuration").SetValue(StrobeLineTime); +#endif + if (baslerCamera->LineSource.TrySetValue(Basler_UniversalCameraParams::LineSource_UserOutput1)) + { + baslerCamera->UserOutputSelector.SetValue(Basler_UniversalCameraParams::UserOutputSelector_UserOutput1); + baslerCamera->UserOutputValue.SetValue(false); + } + else + { + std::cout << "can not set LineSource_UserOutput1" << std::endl; + } + + baslerCamera->ExposureAuto.SetValue(Basler_UniversalCameraParams::ExposureAuto_Off); + baslerCamera->ExposureMode.SetValue(Basler_UniversalCameraParams::ExposureMode_Timed); + baslerCamera->ExposureTime.SetValue(g_sys_conf.expo[Num]); + + baslerCamera->GainSelector.SetValue(Basler_UniversalCameraParams::GainSelector_All); + baslerCamera->GainAuto.SetValue(Basler_UniversalCameraParams::GainAuto_Off); + baslerCamera->Gain.SetValue(g_sys_conf.gain[Num]); + + baslerCamera->TriggerSelector.SetValue(Basler_UniversalCameraParams::TriggerSelector_FrameStart); + baslerCamera->TriggerMode.SetValue(Basler_UniversalCameraParams::TriggerMode_On); + baslerCamera->TriggerSource.SetValue(Basler_UniversalCameraParams::TriggerSource_Line3); + baslerCamera->TriggerActivation.SetValue(Basler_UniversalCameraParams::TriggerActivation_RisingEdge); + + baslerCamera->BinningHorizontal.SetValue(2); + baslerCamera->BinningVertical.SetValue(2); + + pBaslerCaptureThread[Num] = new CaptureThreadBasler(baslerCamera, false, Num, g_sys_conf.shoot[Num]); #ifdef SYNC_CAMERA - pBaslerCaptureThread[Num]->p_image_sync_queue = g_image_sync_queue; - pBaslerCaptureThread[Num]->p_image_sync_arr = &g_image_sync_arr; + pBaslerCaptureThread[Num]->p_image_sync_queue = g_image_sync_queue; + pBaslerCaptureThread[Num]->p_image_sync_arr = &g_image_sync_arr; #else - pBaslerCaptureThread[Num]->p_image_queue = g_image_queue[Num]; -#endif - pBaslerCaptureThread[Num]->p_result_queue = g_result_queue[Num]; - pBaslerCaptureThread[Num]->p_result_wait_queue = g_result_wait_queue[Num]; - pBaslerCaptureThread[Num]->p_double_queue = g_double_queue[Num]; - pBaslerCaptureThread[Num]->p_shooted_queue = g_shooted_queue[Num]; - - pBaslerCaptureThread[Num]->p_debug_queue = g_debug_queue[Num]; - - pThread[Num] = new QThread; - pBaslerCaptureThread[Num]->moveToThread(pThread[Num]); - - // Signal emitted in case of acquisition errors - connect(pThread[Num], SIGNAL(started()), pBaslerCaptureThread[Num], SLOT(process())); - //connect(pBaslerCaptureThread[Num], SIGNAL(error(QString)), this, SLOT(errorString(QString))); - connect(pBaslerCaptureThread[Num], SIGNAL(finished()), pThread[Num], SLOT(quit())); - connect(pBaslerCaptureThread[Num], SIGNAL(finished()), pBaslerCaptureThread[Num], SLOT(deleteLater())); - if(!g_debug_mode) - connect(pBaslerCaptureThread[Num], SIGNAL(updateStatistics(const QString&, int)), this, SLOT(updateStatisticsHub(const QString&, int))); - - pThread[Num]->start(); - if (pThread[Num]->isRunning()) - { - qDebug() << "basler pThread OK"; - SingleCamInfo[Num].IsOpen = true; - return true; - } - } - catch (const Pylon::GenericException& e) - { - QString msg; - QTextStream(&msg) << "Error while opening device! Error message: " << QString::fromStdString(e.GetDescription()) << "\nError" ; - QMessageBox::warning(this, "Error", msg, QMessageBox::Ok, QMessageBox::Ok); - } - return false; - } - else if (SingleCamInfo[Num].CamClass == HIKClassID) - { - qDebug() << "open for hik"; - int nRet = MV_OK; - void *camhandle; - nRet = MV_CC_CreateHandle(&camhandle, HIKCamera::stDeviceList.pDeviceInfo[SingleCamInfo[Num].unfiltered_num]); - HIKCamHandle[Num]=camhandle; - nRet = MV_CC_OpenDevice(camhandle); - if (nRet) - { - MV_CC_CloseDevice(camhandle); - if (MV_CC_OpenDevice(camhandle)) - { - qDebug() << "Failed to open camera"; - return false; - } - } - if (HIKCamera::stDeviceList.pDeviceInfo[SingleCamInfo[Num].unfiltered_num]->nTLayerType == MV_GIGE_DEVICE) - { - int nPacketSize = MV_CC_GetOptimalPacketSize(camhandle); - if (nPacketSize > 0) - { - int nRet = MV_CC_SetIntValue(camhandle, "GevSCPSPacketSize", nPacketSize); - if (nRet != MV_OK) - { - //printf("Warning: Set Packet Size fail nRet [0x%x]!", nRet); - } - } - } - int nnRet = MV_OK; - nRet = MV_CC_SetEnumValue(camhandle, "LineSelector", 1); //0:Line0 1:Line1 2:Line2 - if (nRet) { std::cout << "can not set LineSelector" << std::endl; nnRet = nRet;} - - nRet = MV_CC_SetEnumValue(camhandle, "LineMode", 8); //0:Input 1:Output 2:Trigger 8:Strobe - if (nRet) { std::cout << "can not set LineMode" << std::endl; nnRet = nRet; } - - //0:ExposureStartActive 5:SoftTriggerActive 6:HardTriggerActive - nRet = MV_CC_SetEnumValue(camhandle, "LineSource", 5); - if (nRet) { std::cout << "can not set LineSource" << std::endl; nnRet = nRet; } - - nRet = MV_CC_SetBoolValue(camhandle, "StrobeEnable",TRUE); - if (nRet) { std::cout << "can not set StrobeEnable" << std::endl; nnRet = nRet; } - - nRet = MV_CC_SetIntValueEx(camhandle, "StrobeLineDuration", StrobeLineTime); - if (nRet) { std::cout << "can not set StrobeLineDuration" << std::endl; nnRet = nRet; } - - nRet = MV_CC_SetEnumValue(camhandle, "LineSelector", 0); - if (nRet) { std::cout << "can not set LineSelector" << std::endl; nnRet = nRet; } - - nRet = MV_CC_SetIntValueEx(camhandle, "LineDebouncerTime", g_sys_conf.filter[Num]); - if (nRet) { std::cout << "can not set LineDebouncerTime" << std::endl; nnRet = nRet; } - - nRet = MV_CC_SetEnumValue(camhandle, "LineSelector", 2); - if (nRet) { std::cout << "can not set LineSelector" << std::endl; nnRet = nRet; } - - nRet = MV_CC_SetIntValueEx(camhandle, "LineDebouncerTime", g_sys_conf.filter[Num]); - if (nRet) { std::cout << "can not set LineDebouncerTime" << std::endl; nnRet = nRet; } - - nRet = MV_CC_SetEnumValue(camhandle, "TriggerMode", MV_TRIGGER_MODE_ON); - if (nRet) { std::cout << "can not set TriggerMode" << std::endl; nnRet = nRet; } - - nRet = MV_CC_SetEnumValue(camhandle, "TriggerSource", MV_TRIGGER_SOURCE_LINE2); - if (nRet) { std::cout << "can not set TriggerSource" << std::endl; nnRet = nRet; } - - nRet = MV_CC_SetEnumValue(camhandle, "TriggerActivation", 1);//1表示下降沿 - if (nRet) { std::cout << "can not set TriggerActivation" << std::endl; nnRet = nRet; } - - nRet = MV_CC_SetEnumValue(camhandle, "BinningHorizontal", 2);//设置binning - if (nRet) { std::cout << "can not set BinningHorizontal" << std::endl; nnRet = nRet; } - - nRet = MV_CC_SetEnumValue(camhandle, "BinningVertical", 2);//设置binning - if (nRet) { std::cout << "can not set BinningVertical" << std::endl; nnRet = nRet; } - - nRet = MV_CC_SetEnumValue(camhandle, "ExposureAuto", FALSE); - if (nRet) { std::cout << "can not set ExposureAuto" << std::endl; nnRet = nRet; } - - nRet = MV_CC_SetEnumValue(camhandle, "ExposureMode", 0);//timed - if (nRet) { std::cout << "can not set ExposureMode" << std::endl; nnRet = nRet; } - - nRet = MV_CC_SetFloatValue(camhandle, "ExposureTime", g_sys_conf.expo[Num]); - if (nRet) { std::cout << "can not set ExposureTime" << std::endl; nnRet = nRet; } - - nRet = MV_CC_SetEnumValue(camhandle, "GainAuto", FALSE); - if (nRet) { std::cout << "can not set GainAuto" << std::endl; nnRet = nRet; } - - nRet = MV_CC_SetFloatValue(camhandle, "Gain", g_sys_conf.gain[Num]); - if (nRet) { std::cout << "can not set Gain" << std::endl; nnRet = nRet; } - - pHIKCaptureThread[Num] = new CaptureThreadHIK(camhandle, false, Num); + pBaslerCaptureThread[Num]->p_image_queue = g_image_queue[Num]; +#endif + pBaslerCaptureThread[Num]->p_result_queue = g_result_queue[Num]; + pBaslerCaptureThread[Num]->p_result_wait_queue = g_result_wait_queue[Num]; + pBaslerCaptureThread[Num]->p_double_queue = g_double_queue[Num]; + pBaslerCaptureThread[Num]->p_shooted_queue = g_shooted_queue[Num]; + + pBaslerCaptureThread[Num]->p_debug_queue = g_debug_queue[Num]; + + pThread[Num] = new QThread; + pBaslerCaptureThread[Num]->moveToThread(pThread[Num]); + + // Signal emitted in case of acquisition errors + connect(pThread[Num], SIGNAL(started()), pBaslerCaptureThread[Num], SLOT(process())); + //connect(pBaslerCaptureThread[Num], SIGNAL(error(QString)), this, SLOT(errorString(QString))); + connect(pBaslerCaptureThread[Num], SIGNAL(finished()), pThread[Num], SLOT(quit())); + connect(pBaslerCaptureThread[Num], SIGNAL(finished()), pBaslerCaptureThread[Num], SLOT(deleteLater())); + if (!g_debug_mode) + connect(pBaslerCaptureThread[Num], SIGNAL(updateStatistics(const QString&, int)), this, SLOT(updateStatisticsHub(const QString&, int))); + + pThread[Num]->start(); + if (pThread[Num]->isRunning()) + { + qDebug() << "basler pThread OK"; + SingleCamInfo[Num].IsOpen = true; + return true; + } + } + catch (const Pylon::GenericException& e) + { + QString msg; + QTextStream(&msg) << "Error while opening device! Error message: " << QString::fromStdString(e.GetDescription()) << "\nError"; + QMessageBox::warning(this, "Error", msg, QMessageBox::Ok, QMessageBox::Ok); + } + return false; + } + else if (SingleCamInfo[Num].CamClass == HIKClassID) + { + qDebug() << "open for hik"; + int nRet = MV_OK; + void* camhandle; + nRet = MV_CC_CreateHandle(&camhandle, HIKCamera::stDeviceList.pDeviceInfo[SingleCamInfo[Num].unfiltered_num]); + HIKCamHandle[Num] = camhandle; + nRet = MV_CC_OpenDevice(camhandle); + if (nRet) + { + MV_CC_CloseDevice(camhandle); + if (MV_CC_OpenDevice(camhandle)) + { + qDebug() << "Failed to open camera"; + return false; + } + } + if (HIKCamera::stDeviceList.pDeviceInfo[SingleCamInfo[Num].unfiltered_num]->nTLayerType == MV_GIGE_DEVICE) + { + int nPacketSize = MV_CC_GetOptimalPacketSize(camhandle); + if (nPacketSize > 0) + { + int nRet = MV_CC_SetIntValue(camhandle, "GevSCPSPacketSize", nPacketSize); + if (nRet != MV_OK) + { + //printf("Warning: Set Packet Size fail nRet [0x%x]!", nRet); + } + } + } + int nnRet = MV_OK; + nRet = MV_CC_SetEnumValue(camhandle, "LineSelector", 1); //0:Line0 1:Line1 2:Line2 + if (nRet) { std::cout << "can not set LineSelector" << std::endl; nnRet = nRet; } + + nRet = MV_CC_SetEnumValue(camhandle, "LineMode", 8); //0:Input 1:Output 2:Trigger 8:Strobe + if (nRet) { std::cout << "can not set LineMode" << std::endl; nnRet = nRet; } + + //0:ExposureStartActive 5:SoftTriggerActive 6:HardTriggerActive + nRet = MV_CC_SetEnumValue(camhandle, "LineSource", 5); + if (nRet) { std::cout << "can not set LineSource" << std::endl; nnRet = nRet; } + + nRet = MV_CC_SetBoolValue(camhandle, "StrobeEnable", TRUE); + if (nRet) { std::cout << "can not set StrobeEnable" << std::endl; nnRet = nRet; } + + nRet = MV_CC_SetIntValueEx(camhandle, "StrobeLineDuration", StrobeLineTime); + if (nRet) { std::cout << "can not set StrobeLineDuration" << std::endl; nnRet = nRet; } + + nRet = MV_CC_SetEnumValue(camhandle, "LineSelector", 0); + if (nRet) { std::cout << "can not set LineSelector" << std::endl; nnRet = nRet; } + + nRet = MV_CC_SetIntValueEx(camhandle, "LineDebouncerTime", g_sys_conf.filter[Num]); + if (nRet) { std::cout << "can not set LineDebouncerTime" << std::endl; nnRet = nRet; } + + nRet = MV_CC_SetEnumValue(camhandle, "LineSelector", 2); + if (nRet) { std::cout << "can not set LineSelector" << std::endl; nnRet = nRet; } + + nRet = MV_CC_SetIntValueEx(camhandle, "LineDebouncerTime", g_sys_conf.filter[Num]); + if (nRet) { std::cout << "can not set LineDebouncerTime" << std::endl; nnRet = nRet; } + + nRet = MV_CC_SetEnumValue(camhandle, "TriggerMode", MV_TRIGGER_MODE_ON); + if (nRet) { std::cout << "can not set TriggerMode" << std::endl; nnRet = nRet; } + + nRet = MV_CC_SetEnumValue(camhandle, "TriggerSource", MV_TRIGGER_SOURCE_LINE2); + if (nRet) { std::cout << "can not set TriggerSource" << std::endl; nnRet = nRet; } + + nRet = MV_CC_SetEnumValue(camhandle, "TriggerActivation", 1);//1琛ㄧず涓嬮檷娌 + if (nRet) { std::cout << "can not set TriggerActivation" << std::endl; nnRet = nRet; } + + nRet = MV_CC_SetEnumValue(camhandle, "BinningHorizontal", 2);//璁剧疆binning + if (nRet) { std::cout << "can not set BinningHorizontal" << std::endl; nnRet = nRet; } + + nRet = MV_CC_SetEnumValue(camhandle, "BinningVertical", 2);//璁剧疆binning + if (nRet) { std::cout << "can not set BinningVertical" << std::endl; nnRet = nRet; } + + nRet = MV_CC_SetEnumValue(camhandle, "ExposureAuto", FALSE); + if (nRet) { std::cout << "can not set ExposureAuto" << std::endl; nnRet = nRet; } + + nRet = MV_CC_SetEnumValue(camhandle, "ExposureMode", 0);//timed + if (nRet) { std::cout << "can not set ExposureMode" << std::endl; nnRet = nRet; } + + nRet = MV_CC_SetFloatValue(camhandle, "ExposureTime", g_sys_conf.expo[Num]); + if (nRet) { std::cout << "can not set ExposureTime" << std::endl; nnRet = nRet; } + + nRet = MV_CC_SetEnumValue(camhandle, "GainAuto", FALSE); + if (nRet) { std::cout << "can not set GainAuto" << std::endl; nnRet = nRet; } + + nRet = MV_CC_SetFloatValue(camhandle, "Gain", g_sys_conf.gain[Num]); + if (nRet) { std::cout << "can not set Gain" << std::endl; nnRet = nRet; } + + pHIKCaptureThread[Num] = new CaptureThreadHIK(camhandle, false, Num); #ifdef SYNC_CAMERA - pHIKCaptureThread[Num]->p_image_sync_queue = g_image_sync_queue; - pHIKCaptureThread[Num]->p_image_sync_arr = &g_image_sync_arr; + pHIKCaptureThread[Num]->p_image_sync_queue = g_image_sync_queue; + pHIKCaptureThread[Num]->p_image_sync_arr = &g_image_sync_arr; #else - pHIKCaptureThread[Num]->p_image_queue = g_image_queue[Num]; -#endif - pHIKCaptureThread[Num]->p_result_queue = g_result_queue[Num]; - pHIKCaptureThread[Num]->p_debug_queue = g_debug_queue[Num]; - pHIKCaptureThread[Num]->p_result_wait_queue = g_result_wait_queue[Num]; - pHIKCaptureThread[Num]->p_double_queue = g_double_queue[Num]; - pHIKCaptureThread[Num]->p_shooted_queue = g_shooted_queue[Num]; - - pThread[Num] = new QThread; - pHIKCaptureThread[Num]->moveToThread(pThread[Num]); - - // Signal emitted in case of acquisition errors - connect(pThread[Num], SIGNAL(started()), pHIKCaptureThread[Num], SLOT(process())); - //connect(pHIKCaptureThread[Num], SIGNAL(error(QString)), this, SLOT(errorString(QString))); - connect(pHIKCaptureThread[Num], SIGNAL(finished()), pThread[Num], SLOT(quit())); - connect(pHIKCaptureThread[Num], SIGNAL(finished()), pHIKCaptureThread[Num], SLOT(deleteLater())); - if (!g_debug_mode) - connect(pHIKCaptureThread[Num], SIGNAL(updateStatistics(const QString&,int)), this, SLOT(updateStatisticsHub(const QString&,int))); - pThread[Num]->start(); - if (pThread[Num]->isRunning()) - { - qDebug() << "hik pThread OK"; - SingleCamInfo[Num].IsOpen =true; - return true; - } - return false; - } - } - else if(OpenOrClose == CLOSE && SingleCamInfo[Num].IsOpen) - { - if (SingleCamInfo[Num].CamClass == BalluffClassID) - { - qDebug() << "close for balluff"; - disconnect(pThread[Num], SIGNAL(started()), pCaptureThread[Num], SLOT(process())); - //disconnect(pCaptureThread[Num], SIGNAL(error(QString)), this, SLOT(errorString(QString))); - disconnect(pCaptureThread[Num], SIGNAL(finished()), pThread[Num], SLOT(quit())); - disconnect(pCaptureThread[Num], SIGNAL(finished()), pCaptureThread[Num], SLOT(deleteLater())); - disconnect(pCaptureThread[Num], SIGNAL(updateStatistics(const QString&,int)), this, SLOT(updateStatisticsHub(const QString&,int))); - if (pCaptureThread[Num]) - { - pCaptureThread[Num]->terminate(); - if (pThread[Num]) - { - pThread[Num]->quit(); - pThread[Num]->wait(); - } - } - Device* pDev = BalluffCamera::devMgr[SingleCamInfo[Num].unfiltered_num]; - if (pDev && pDev->isOpen()) - { - pDev->close(); - } - DeleteElement(pCaptureThread[Num]); - DeleteElement(pThread[Num]); - DeleteElement(pFI[Num]); - DeleteElement(pAC[Num]); - SingleCamInfo[Num].IsOpen = false; - return true; - } - else if (SingleCamInfo[Num].CamClass == BaslerClassID) - { - qDebug() << "close for basler"; - disconnect(pThread[Num], SIGNAL(started()), pBaslerCaptureThread[Num], SLOT(process())); - //disconnect(pBaslerCaptureThread[Num], SIGNAL(error(QString)), this, SLOT(errorString(QString))); - disconnect(pBaslerCaptureThread[Num], SIGNAL(finished()), pThread[Num], SLOT(quit())); - disconnect(pBaslerCaptureThread[Num], SIGNAL(finished()), pBaslerCaptureThread[Num], SLOT(deleteLater())); - disconnect(pBaslerCaptureThread[Num], SIGNAL(updateStatistics(const QString&, int)), this, SLOT(updateStatisticsHub(const QString&, int))); - if (pBaslerCaptureThread[Num]) - { - pBaslerCaptureThread[Num]->terminate(); - if (pThread[Num]) - { - pThread[Num]->quit(); - pThread[Num]->wait(); - } - } - Pylon::CBaslerUniversalInstantCamera* baslerCamera = BaslerCamHandle[Num]; - /*if(baslerCamera && baslerCamera->IsOpen()) - { - baslerCamera->Close(); - baslerCamera->GrabCameraEvents = false; - }*/ - DeleteElement(pBaslerCaptureThread[Num]); - DeleteElement(pThread[Num]); - SingleCamInfo[Num].IsOpen = false; - return true; - } - else if (SingleCamInfo[Num].CamClass == HIKClassID) - { - qDebug() << "close for hik"; - void* camhandle; - camhandle = pHIKCaptureThread[Num]->CamHandle; - disconnect(pThread[Num], SIGNAL(started()), pHIKCaptureThread[Num], SLOT(process())); - //disconnect(pCaptureThread[Num], SIGNAL(error(QString)), this, SLOT(errorString(QString))); - disconnect(pHIKCaptureThread[Num], SIGNAL(finished()), pThread[Num], SLOT(quit())); - disconnect(pHIKCaptureThread[Num], SIGNAL(finished()), pHIKCaptureThread[Num], SLOT(deleteLater())); - disconnect(pHIKCaptureThread[Num], SIGNAL(updateStatistics(const QString&, int)), this, SLOT(updateStatisticsHub(const QString&, int))); - if (pHIKCaptureThread[Num]) - { - pHIKCaptureThread[Num]->terminate(); - if (pThread[Num]) - { - pThread[Num]->quit(); - pThread[Num]->wait(); - } - } - if (camhandle) - { - MV_CC_CloseDevice(camhandle); - MV_CC_DestroyHandle(camhandle); - } - DeleteElement(pHIKCaptureThread[Num]); - DeleteElement(pThread[Num]); - SingleCamInfo[Num].IsOpen = false; - return true; - } - } - return false; -} - -void Cigarette::EnumerateCameras(SingleCamInfoStruct *TempSingleCamInfoStruct,bool showinfo,SysConf &conf) + pHIKCaptureThread[Num]->p_image_queue = g_image_queue[Num]; +#endif + pHIKCaptureThread[Num]->p_result_queue = g_result_queue[Num]; + pHIKCaptureThread[Num]->p_debug_queue = g_debug_queue[Num]; + pHIKCaptureThread[Num]->p_result_wait_queue = g_result_wait_queue[Num]; + pHIKCaptureThread[Num]->p_double_queue = g_double_queue[Num]; + pHIKCaptureThread[Num]->p_shooted_queue = g_shooted_queue[Num]; + + pThread[Num] = new QThread; + pHIKCaptureThread[Num]->moveToThread(pThread[Num]); + + // Signal emitted in case of acquisition errors + connect(pThread[Num], SIGNAL(started()), pHIKCaptureThread[Num], SLOT(process())); + //connect(pHIKCaptureThread[Num], SIGNAL(error(QString)), this, SLOT(errorString(QString))); + connect(pHIKCaptureThread[Num], SIGNAL(finished()), pThread[Num], SLOT(quit())); + connect(pHIKCaptureThread[Num], SIGNAL(finished()), pHIKCaptureThread[Num], SLOT(deleteLater())); + if (!g_debug_mode) + connect(pHIKCaptureThread[Num], SIGNAL(updateStatistics(const QString&, int)), this, SLOT(updateStatisticsHub(const QString&, int))); + pThread[Num]->start(); + if (pThread[Num]->isRunning()) + { + qDebug() << "hik pThread OK"; + SingleCamInfo[Num].IsOpen = true; + return true; + } + return false; + } + } + else if (OpenOrClose == CLOSE && SingleCamInfo[Num].IsOpen) + { + if (SingleCamInfo[Num].CamClass == BalluffClassID) + { + qDebug() << "close for balluff"; + disconnect(pThread[Num], SIGNAL(started()), pCaptureThread[Num], SLOT(process())); + //disconnect(pCaptureThread[Num], SIGNAL(error(QString)), this, SLOT(errorString(QString))); + disconnect(pCaptureThread[Num], SIGNAL(finished()), pThread[Num], SLOT(quit())); + disconnect(pCaptureThread[Num], SIGNAL(finished()), pCaptureThread[Num], SLOT(deleteLater())); + disconnect(pCaptureThread[Num], SIGNAL(updateStatistics(const QString&, int)), this, SLOT(updateStatisticsHub(const QString&, int))); + if (pCaptureThread[Num]) + { + pCaptureThread[Num]->terminate(); + if (pThread[Num]) + { + pThread[Num]->quit(); + pThread[Num]->wait(); + } + } + Device* pDev = BalluffCamera::devMgr[SingleCamInfo[Num].unfiltered_num]; + if (pDev && pDev->isOpen()) + { + pDev->close(); + } + DeleteElement(pCaptureThread[Num]); + DeleteElement(pThread[Num]); + DeleteElement(pFI[Num]); + DeleteElement(pAC[Num]); + SingleCamInfo[Num].IsOpen = false; + return true; + } + else if (SingleCamInfo[Num].CamClass == BaslerClassID) + { + qDebug() << "close for basler"; + disconnect(pThread[Num], SIGNAL(started()), pBaslerCaptureThread[Num], SLOT(process())); + //disconnect(pBaslerCaptureThread[Num], SIGNAL(error(QString)), this, SLOT(errorString(QString))); + disconnect(pBaslerCaptureThread[Num], SIGNAL(finished()), pThread[Num], SLOT(quit())); + disconnect(pBaslerCaptureThread[Num], SIGNAL(finished()), pBaslerCaptureThread[Num], SLOT(deleteLater())); + disconnect(pBaslerCaptureThread[Num], SIGNAL(updateStatistics(const QString&, int)), this, SLOT(updateStatisticsHub(const QString&, int))); + if (pBaslerCaptureThread[Num]) + { + pBaslerCaptureThread[Num]->terminate(); + if (pThread[Num]) + { + pThread[Num]->quit(); + pThread[Num]->wait(); + } + } + Pylon::CBaslerUniversalInstantCamera* baslerCamera = BaslerCamHandle[Num]; + /*if(baslerCamera && baslerCamera->IsOpen()) + { + baslerCamera->Close(); + baslerCamera->GrabCameraEvents = false; + }*/ + DeleteElement(pBaslerCaptureThread[Num]); + DeleteElement(pThread[Num]); + SingleCamInfo[Num].IsOpen = false; + return true; + } + else if (SingleCamInfo[Num].CamClass == HIKClassID) + { + qDebug() << "close for hik"; + void* camhandle; + camhandle = pHIKCaptureThread[Num]->CamHandle; + disconnect(pThread[Num], SIGNAL(started()), pHIKCaptureThread[Num], SLOT(process())); + //disconnect(pCaptureThread[Num], SIGNAL(error(QString)), this, SLOT(errorString(QString))); + disconnect(pHIKCaptureThread[Num], SIGNAL(finished()), pThread[Num], SLOT(quit())); + disconnect(pHIKCaptureThread[Num], SIGNAL(finished()), pHIKCaptureThread[Num], SLOT(deleteLater())); + disconnect(pHIKCaptureThread[Num], SIGNAL(updateStatistics(const QString&, int)), this, SLOT(updateStatisticsHub(const QString&, int))); + if (pHIKCaptureThread[Num]) + { + pHIKCaptureThread[Num]->terminate(); + if (pThread[Num]) + { + pThread[Num]->quit(); + pThread[Num]->wait(); + } + } + if (camhandle) + { + MV_CC_CloseDevice(camhandle); + MV_CC_DestroyHandle(camhandle); + } + DeleteElement(pHIKCaptureThread[Num]); + DeleteElement(pThread[Num]); + SingleCamInfo[Num].IsOpen = false; + return true; + } + } + return false; +} + +void Cigarette::EnumerateCameras(SingleCamInfoStruct* TempSingleCamInfoStruct, bool showinfo, SysConf& conf) { - std::vector TempSingleCamInfo; - //这些厂商相机枚举时候会过滤别的厂商相机,单独枚举 - int basler_cnt = 0; - int filtered = 0; - filtered = BaslerCamera::Enumerate(); - Pylon::CInstantCameraArray cameras(filtered); - Pylon::CTlFactory& tlFactory = Pylon::CTlFactory::GetInstance(); - - for (int i = 0; i < min(filtered, NumberOfSupportedCameras); i++) - { - SingleCamInfoStruct CamInfo; - //cameras[i].Attach(tlFactory.CreateDevice(BaslerCamera::devices[i])); - //Pylon::String_t selectedAction = ::GenICam::gcstring("Action"); - //std::string manufacture = cameras[i].GetDeviceInfo().GetVendorId(); - //if (!manufacture.compare(0, 6, "BASLER")) - //{ - // Print the UserDefined name of the camera. - //std::string UserID = cameras[i].GetDeviceInfo().GetUserDefinedName(); - Pylon::CBaslerUniversalInstantCamera* baslerCamera = new Pylon::CBaslerUniversalInstantCamera(tlFactory.CreateDevice(BaslerCamera::devices[i])); - baslerCamera->Open(); - std::string UserID = baslerCamera->DeviceUserID(); - baslerCamera->Close(); - delete baslerCamera; - if(showinfo)std::cout << "Basler user ID = " << UserID << std::endl; - CamInfo.UserID = atoi(UserID.c_str()); - CamInfo.CamClass = BaslerClassID; - CamInfo.filtered_num = i; - CamInfo.Detect = false; - CamInfo.IsOpen = false; - CamInfo.OffLine = false; - TempSingleCamInfo.push_back(CamInfo); - basler_cnt++; - //} - } - - //这些厂商相机可以互相枚举,但是Enumerate都要执行里面会初始化一些全局信息 - int hik_cnt = 0; - int unfiltered = 0; - unfiltered = HIKCamera::Enumerate(); - for (int i = 0; i < min(unfiltered, NumberOfSupportedCameras); i++) - { - MV_CC_DEVICE_INFO* pDeviceInfo = HIKCamera::stDeviceList.pDeviceInfo[i]; - std::string manufacture; - char chManufacturer[32]; - if (pDeviceInfo->nTLayerType == MV_GIGE_DEVICE) - { - MV_GIGE_DEVICE_INFO* TempPtr = &(pDeviceInfo->SpecialInfo.stGigEInfo); - memcpy(chManufacturer, TempPtr->chManufacturerName, 32); - manufacture = chManufacturer; - } - else if (pDeviceInfo->nTLayerType == MV_USB_DEVICE) - { - MV_USB3_DEVICE_INFO* TempPtr = &(pDeviceInfo->SpecialInfo.stUsb3VInfo); - memcpy(chManufacturer, TempPtr->chManufacturerName, 32); - manufacture = chManufacturer; - } - else - { - continue; - } - - if(showinfo)std::cout << "Camera:" << i << ",vendor = " << manufacture << std::endl; - transform(manufacture.begin(), manufacture.end(), manufacture.begin(), ::toupper); - SingleCamInfoStruct CamInfo; - if ((!manufacture.compare(0, 3, "HIK")) || (!manufacture.compare(0, 3, "U3V"))) - { - void* camhandle; - MVCC_STRINGVALUE UserID; - MVCC_STRINGVALUE YSXID; - MVCC_STRINGVALUE YSXID2; - string id; - MV_CC_CreateHandle(&camhandle, HIKCamera::stDeviceList.pDeviceInfo[i]); - if (!MV_CC_OpenDevice(camhandle)) - { - MV_CC_GetDeviceUserID(camhandle, &UserID); - MV_CC_GetStringValue(camhandle, "DeviceYSXID", &YSXID); - if(showinfo)std::cout << "Hikrobot user ID = " << UserID.chCurValue << std::endl; - id = YSXID.chCurValue; + std::vector TempSingleCamInfo; + //杩欎簺鍘傚晢鐩告満鏋氫妇鏃跺欎細杩囨护鍒殑鍘傚晢鐩告満锛屽崟鐙灇涓 + int basler_cnt = 0; + int filtered = 0; + filtered = BaslerCamera::Enumerate(); + Pylon::CInstantCameraArray cameras(filtered); + Pylon::CTlFactory& tlFactory = Pylon::CTlFactory::GetInstance(); + + for (int i = 0; i < min(filtered, NumberOfSupportedCameras); i++) + { + SingleCamInfoStruct CamInfo; + //cameras[i].Attach(tlFactory.CreateDevice(BaslerCamera::devices[i])); + //Pylon::String_t selectedAction = ::GenICam::gcstring("Action"); + //std::string manufacture = cameras[i].GetDeviceInfo().GetVendorId(); + //if (!manufacture.compare(0, 6, "BASLER")) + //{ + // Print the UserDefined name of the camera. + //std::string UserID = cameras[i].GetDeviceInfo().GetUserDefinedName(); + Pylon::CBaslerUniversalInstantCamera* baslerCamera = new Pylon::CBaslerUniversalInstantCamera(tlFactory.CreateDevice(BaslerCamera::devices[i])); + baslerCamera->Open(); + std::string UserID = baslerCamera->DeviceUserID(); + baslerCamera->Close(); + delete baslerCamera; + if (showinfo)std::cout << "Basler user ID = " << UserID << std::endl; + CamInfo.UserID = atoi(UserID.c_str()); + CamInfo.CamClass = BaslerClassID; + CamInfo.filtered_num = i; + CamInfo.Detect = false; + CamInfo.IsOpen = false; + CamInfo.OffLine = false; + TempSingleCamInfo.push_back(CamInfo); + basler_cnt++; + //} + } + + //杩欎簺鍘傚晢鐩告満鍙互浜掔浉鏋氫妇锛屼絾鏄疎numerate閮借鎵ц閲岄潰浼氬垵濮嬪寲涓浜涘叏灞淇℃伅 + int hik_cnt = 0; + int unfiltered = 0; + unfiltered = HIKCamera::Enumerate(); + for (int i = 0; i < min(unfiltered, NumberOfSupportedCameras); i++) + { + MV_CC_DEVICE_INFO* pDeviceInfo = HIKCamera::stDeviceList.pDeviceInfo[i]; + std::string manufacture; + char chManufacturer[32]; + if (pDeviceInfo->nTLayerType == MV_GIGE_DEVICE) + { + MV_GIGE_DEVICE_INFO* TempPtr = &(pDeviceInfo->SpecialInfo.stGigEInfo); + memcpy(chManufacturer, TempPtr->chManufacturerName, 32); + manufacture = chManufacturer; + } + else if (pDeviceInfo->nTLayerType == MV_USB_DEVICE) + { + MV_USB3_DEVICE_INFO* TempPtr = &(pDeviceInfo->SpecialInfo.stUsb3VInfo); + memcpy(chManufacturer, TempPtr->chManufacturerName, 32); + manufacture = chManufacturer; + } + else + { + continue; + } + + if (showinfo)std::cout << "Camera:" << i << ",vendor = " << manufacture << std::endl; + transform(manufacture.begin(), manufacture.end(), manufacture.begin(), ::toupper); + SingleCamInfoStruct CamInfo; + if ((!manufacture.compare(0, 3, "HIK")) || (!manufacture.compare(0, 3, "U3V"))) + { + void* camhandle; + MVCC_STRINGVALUE UserID; + MVCC_STRINGVALUE YSXID; + MVCC_STRINGVALUE YSXID2; + string id; + MV_CC_CreateHandle(&camhandle, HIKCamera::stDeviceList.pDeviceInfo[i]); + if (!MV_CC_OpenDevice(camhandle)) + { + MV_CC_GetDeviceUserID(camhandle, &UserID); + MV_CC_GetStringValue(camhandle, "DeviceYSXID", &YSXID); + if (showinfo)std::cout << "Hikrobot user ID = " << UserID.chCurValue << std::endl; + id = YSXID.chCurValue; #ifdef identify_Hik_YSXID - if (id!="YSX9256") - { - QMessageBox::information(NULL, QStringLiteral("系统自检失败"), QStringLiteral("相机匹配失败,请检查相机型号"), QMessageBox::Ok); - exit(-1); - } - YSXID = YSXID2;//清除数据 -#endif - MV_CC_CloseDevice(camhandle); - } - MV_CC_DestroyHandle(camhandle); - CamInfo.UserID = atoi(UserID.chCurValue); - CamInfo.CamClass = HIKClassID; - CamInfo.unfiltered_num = i; - CamInfo.Detect = false; - CamInfo.IsOpen = false; - CamInfo.OffLine = false; - TempSingleCamInfo.push_back(CamInfo); - hik_cnt++; - } - } - - int balluff_cnt = 0; - unfiltered = BalluffCamera::Enumerate(); - for (int i = 0; i < min(unfiltered, NumberOfSupportedCameras); i++) - { - Device* pDev = BalluffCamera::devMgr[i]; - if (!pDev->isInUse()) { - std::string manufacture = pDev->manufacturer.read(); - if (showinfo)std::cout << "Camera:" << i << ",vendor = " << manufacture << std::endl; - transform(manufacture.begin(), manufacture.end(), manufacture.begin(), ::toupper); - SingleCamInfoStruct CamInfo; - if ((!manufacture.compare(0, 7, "BALLUFF")) || (!manufacture.compare(0, 13, "MATRIX VISION"))) - { - mvIMPACT::acquire::GenICam::DeviceControl dc(pDev); - std::string UserID = dc.deviceUserID.read(); - pDev->close(); - if (showinfo)std::cout << "Balluff user ID = " << UserID << std::endl; - CamInfo.UserID = atoi(UserID.c_str()); - CamInfo.CamClass = BalluffClassID; - CamInfo.unfiltered_num = i; - CamInfo.Detect = false; - CamInfo.IsOpen = false; - CamInfo.OffLine = false; - TempSingleCamInfo.push_back(CamInfo); - balluff_cnt++; - } - } - } - - if (showinfo) { - std::cout << "Camera Count:\t" << TempSingleCamInfo.size() << std::endl; - if (balluff_cnt)std::cout << "Balluff Count:\t" << balluff_cnt << std::endl; - if (hik_cnt)std::cout << "Hikvision Count:\t" << hik_cnt << std::endl; - if (basler_cnt)std::cout << "Basler Count:\t" << basler_cnt << std::endl; - } - - //各个厂商相机按照userid打开的逻辑代码----start - for (int i = 0; i < NumberOfSupportedCameras; i++) - { - for (int j = 0; j < TempSingleCamInfo.size(); j++) - { - if ((TempSingleCamInfo[j].UserID == conf.UserID[i]) && (TempSingleCamInfo[j].Detect!= true)) - { - TempSingleCamInfo[j].Detect = true; - TempSingleCamInfoStruct[i].unfiltered_num = TempSingleCamInfo[j].unfiltered_num; - TempSingleCamInfoStruct[i].filtered_num = TempSingleCamInfo[j].filtered_num; - TempSingleCamInfoStruct[i].CamClass = TempSingleCamInfo[j].CamClass; - TempSingleCamInfoStruct[i].UserID = TempSingleCamInfo[j].UserID; - TempSingleCamInfoStruct[i].Detect = TempSingleCamInfo[j].Detect; - TempSingleCamInfoStruct[i].IsOpen = TempSingleCamInfo[j].IsOpen; - TempSingleCamInfoStruct[i].OffLine = TempSingleCamInfo[j].OffLine; - break; - } - } - } - //各个厂商相机按照userid打开的逻辑代码----end + if (id != "YSX9256") + { + QMessageBox::information(NULL, QStringLiteral("绯荤粺鑷澶辫触"), QStringLiteral("鐩告満鍖归厤澶辫触锛岃妫鏌ョ浉鏈哄瀷鍙"), QMessageBox::Ok); + exit(-1); + } + YSXID = YSXID2;//娓呴櫎鏁版嵁 +#endif + MV_CC_CloseDevice(camhandle); + } + MV_CC_DestroyHandle(camhandle); + CamInfo.UserID = atoi(UserID.chCurValue); + CamInfo.CamClass = HIKClassID; + CamInfo.unfiltered_num = i; + CamInfo.Detect = false; + CamInfo.IsOpen = false; + CamInfo.OffLine = false; + TempSingleCamInfo.push_back(CamInfo); + hik_cnt++; + } + } + + int balluff_cnt = 0; + unfiltered = BalluffCamera::Enumerate(); + for (int i = 0; i < min(unfiltered, NumberOfSupportedCameras); i++) + { + Device* pDev = BalluffCamera::devMgr[i]; + if (!pDev->isInUse()) { + std::string manufacture = pDev->manufacturer.read(); + if (showinfo)std::cout << "Camera:" << i << ",vendor = " << manufacture << std::endl; + transform(manufacture.begin(), manufacture.end(), manufacture.begin(), ::toupper); + SingleCamInfoStruct CamInfo; + if ((!manufacture.compare(0, 7, "BALLUFF")) || (!manufacture.compare(0, 13, "MATRIX VISION"))) + { + mvIMPACT::acquire::GenICam::DeviceControl dc(pDev); + std::string UserID = dc.deviceUserID.read(); + pDev->close(); + if (showinfo)std::cout << "Balluff user ID = " << UserID << std::endl; + CamInfo.UserID = atoi(UserID.c_str()); + CamInfo.CamClass = BalluffClassID; + CamInfo.unfiltered_num = i; + CamInfo.Detect = false; + CamInfo.IsOpen = false; + CamInfo.OffLine = false; + TempSingleCamInfo.push_back(CamInfo); + balluff_cnt++; + } + } + } + + if (showinfo) { + std::cout << "Camera Count:\t" << TempSingleCamInfo.size() << std::endl; + if (balluff_cnt)std::cout << "Balluff Count:\t" << balluff_cnt << std::endl; + if (hik_cnt)std::cout << "Hikvision Count:\t" << hik_cnt << std::endl; + if (basler_cnt)std::cout << "Basler Count:\t" << basler_cnt << std::endl; + } + + //鍚勪釜鍘傚晢鐩告満鎸夌収userid鎵撳紑鐨勯昏緫浠g爜----start + for (int i = 0; i < NumberOfSupportedCameras; i++) + { + for (int j = 0; j < TempSingleCamInfo.size(); j++) + { + if ((TempSingleCamInfo[j].UserID == conf.UserID[i]) && (TempSingleCamInfo[j].Detect != true)) + { + TempSingleCamInfo[j].Detect = true; + TempSingleCamInfoStruct[i].unfiltered_num = TempSingleCamInfo[j].unfiltered_num; + TempSingleCamInfoStruct[i].filtered_num = TempSingleCamInfo[j].filtered_num; + TempSingleCamInfoStruct[i].CamClass = TempSingleCamInfo[j].CamClass; + TempSingleCamInfoStruct[i].UserID = TempSingleCamInfo[j].UserID; + TempSingleCamInfoStruct[i].Detect = TempSingleCamInfo[j].Detect; + TempSingleCamInfoStruct[i].IsOpen = TempSingleCamInfo[j].IsOpen; + TempSingleCamInfoStruct[i].OffLine = TempSingleCamInfo[j].OffLine; + break; + } + } + } + //鍚勪釜鍘傚晢鐩告満鎸夌収userid鎵撳紑鐨勯昏緫浠g爜----end } void Cigarette::EnableDebugMode() { - for(int i=0;iacquisitionFrameRateEnable.write(bTrue); - pAC[i]->acquisitionFrameRate.write(10.0); - //关闭外触发 - pAC[i]->triggerMode.writeS("Off"); - } - else if(SingleCamInfo[i].CamClass == HIKClassID) - { - int nRet = MV_OK; - MV_CC_SetFrameRate(HIKCamHandle[i], 10.0); - nRet = MV_CC_SetBoolValue(HIKCamHandle[i], "AcquisitionFrameRateEnable",true); - if (nRet) { std::cout << "can not set Hik's AcquisitionFrameRateEnable" << std::endl;} - - nRet = MV_CC_SetEnumValue(HIKCamHandle[i], "TriggerMode", MV_TRIGGER_MODE_OFF); - if (nRet) { std::cout << "can not set Hik's TriggerMode" << std::endl;} - } - else if(SingleCamInfo[i].CamClass == BaslerClassID) - { - bool nRet = false; - nRet = BaslerCamHandle[i]->AcquisitionFrameRate.TrySetValue(10); - if (!nRet) { std::cout << "can not set Basler's AcquisitionFrameRate" << std::endl; } - nRet = BaslerCamHandle[i]->AcquisitionFrameRateEnable.TrySetValue(true); - if (!nRet) { std::cout << "can not set Basler's AcquisitionFrameRateEnable" << std::endl; } - nRet = BaslerCamHandle[i]->TriggerSelector.TrySetValue(Basler_UniversalCameraParams::TriggerSelector_FrameStart); - if (!nRet) { std::cout << "can not set Basler's TriggerSelector_FrameStart" << std::endl; } - nRet = BaslerCamHandle[i]->TriggerMode.TrySetValue(Basler_UniversalCameraParams::TriggerMode_Off); - if (!nRet) { std::cout << "can not set Basler's TriggerMode_Off" << std::endl; } + for (int i = 0; i < NumberOfSupportedCameras; i++) + { + if (SingleCamInfo[i].IsOpen && SingleCamInfo[i].Detect) + { + if (SingleCamInfo[i].CamClass == BalluffClassID) + { + //璁剧疆甯х巼=10fps + pAC[i]->acquisitionFrameRateEnable.write(bTrue); + pAC[i]->acquisitionFrameRate.write(10.0); + //鍏抽棴澶栬Е鍙 + pAC[i]->triggerMode.writeS("Off"); + } + else if (SingleCamInfo[i].CamClass == HIKClassID) + { + int nRet = MV_OK; + MV_CC_SetFrameRate(HIKCamHandle[i], 10.0); + nRet = MV_CC_SetBoolValue(HIKCamHandle[i], "AcquisitionFrameRateEnable", true); + if (nRet) { std::cout << "can not set Hik's AcquisitionFrameRateEnable" << std::endl; } + + nRet = MV_CC_SetEnumValue(HIKCamHandle[i], "TriggerMode", MV_TRIGGER_MODE_OFF); + if (nRet) { std::cout << "can not set Hik's TriggerMode" << std::endl; } + } + else if (SingleCamInfo[i].CamClass == BaslerClassID) + { + bool nRet = false; + nRet = BaslerCamHandle[i]->AcquisitionFrameRate.TrySetValue(10); + if (!nRet) { std::cout << "can not set Basler's AcquisitionFrameRate" << std::endl; } + nRet = BaslerCamHandle[i]->AcquisitionFrameRateEnable.TrySetValue(true); + if (!nRet) { std::cout << "can not set Basler's AcquisitionFrameRateEnable" << std::endl; } + nRet = BaslerCamHandle[i]->TriggerSelector.TrySetValue(Basler_UniversalCameraParams::TriggerSelector_FrameStart); + if (!nRet) { std::cout << "can not set Basler's TriggerSelector_FrameStart" << std::endl; } + nRet = BaslerCamHandle[i]->TriggerMode.TrySetValue(Basler_UniversalCameraParams::TriggerMode_Off); + if (!nRet) { std::cout << "can not set Basler's TriggerMode_Off" << std::endl; } #ifndef USB_BASLER_NEW_FW - nRet = BaslerCamHandle[i]->TriggerSelector.TrySetValue(Basler_UniversalCameraParams::TriggerSelector_FrameBurstStart); - if (!nRet) { std::cout << "can not set Basler's TriggerSelector_FrameBurstStart" << std::endl;} - nRet = BaslerCamHandle[i]->TriggerMode.TrySetValue(Basler_UniversalCameraParams::TriggerMode_Off); - if (!nRet) { std::cout << "can not set Basler's TriggerMode_Off" << std::endl;} + nRet = BaslerCamHandle[i]->TriggerSelector.TrySetValue(Basler_UniversalCameraParams::TriggerSelector_FrameBurstStart); + if (!nRet) { std::cout << "can not set Basler's TriggerSelector_FrameBurstStart" << std::endl; } + nRet = BaslerCamHandle[i]->TriggerMode.TrySetValue(Basler_UniversalCameraParams::TriggerMode_Off); + if (!nRet) { std::cout << "can not set Basler's TriggerMode_Off" << std::endl; } #endif - } - } - } - g_debug_mode = true; + } + } + } + g_debug_mode = true; } void Cigarette::DisableDebugMode() { - for(int i=0;iacquisitionFrameRateEnable.write(bFalse); - pAC[i]->triggerMode.writeS("On"); - pAC[i]->triggerSource.writeS("Line4"); - pAC[i]->triggerActivation.writeS("RisingEdge"); - } - else if(SingleCamInfo[i].CamClass == HIKClassID) - { - int nRet = MV_OK; - nRet = MV_CC_SetEnumValue(HIKCamHandle[i], "TriggerMode", MV_TRIGGER_MODE_ON); - if (nRet) { std::cout << "can not set Hik's TriggerMode" << std::endl;} - - nRet = MV_CC_SetEnumValue(HIKCamHandle[i], "TriggerSource", MV_TRIGGER_SOURCE_LINE2); - if (nRet) { std::cout << "can not set Hik's TriggerSource" << std::endl;} - - nRet = MV_CC_SetEnumValue(HIKCamHandle[i], "TriggerActivation", 1);//1表示下降沿 - if (nRet) { std::cout << "can not set Hik's TriggerActivation" << std::endl;} - - nRet = MV_CC_SetFrameRate(HIKCamHandle[i], 1000.0); - if (nRet) { std::cout << "can not set Hik's FrameInfo" << std::endl;} - nRet = MV_CC_SetBoolValue(HIKCamHandle[i], "AcquisitionFrameRateEnable",false); - if (nRet) { std::cout << "can not set Hik's AcquisitionFrameRateEnable" << std::endl;} - } - else if(SingleCamInfo[i].CamClass == BaslerClassID) - { - bool nRet = false; + for (int i = 0; i < NumberOfSupportedCameras; i++) + { + if (SingleCamInfo[i].IsOpen && SingleCamInfo[i].Detect) + { + if (SingleCamInfo[i].CamClass == BalluffClassID) + { + //璁剧疆甯х巼 + pAC[i]->acquisitionFrameRateEnable.write(bFalse); + pAC[i]->triggerMode.writeS("On"); + pAC[i]->triggerSource.writeS("Line4"); + pAC[i]->triggerActivation.writeS("RisingEdge"); + } + else if (SingleCamInfo[i].CamClass == HIKClassID) + { + int nRet = MV_OK; + nRet = MV_CC_SetEnumValue(HIKCamHandle[i], "TriggerMode", MV_TRIGGER_MODE_ON); + if (nRet) { std::cout << "can not set Hik's TriggerMode" << std::endl; } + + nRet = MV_CC_SetEnumValue(HIKCamHandle[i], "TriggerSource", MV_TRIGGER_SOURCE_LINE2); + if (nRet) { std::cout << "can not set Hik's TriggerSource" << std::endl; } + + nRet = MV_CC_SetEnumValue(HIKCamHandle[i], "TriggerActivation", 1);//1琛ㄧず涓嬮檷娌 + if (nRet) { std::cout << "can not set Hik's TriggerActivation" << std::endl; } + + nRet = MV_CC_SetFrameRate(HIKCamHandle[i], 1000.0); + if (nRet) { std::cout << "can not set Hik's FrameInfo" << std::endl; } + nRet = MV_CC_SetBoolValue(HIKCamHandle[i], "AcquisitionFrameRateEnable", false); + if (nRet) { std::cout << "can not set Hik's AcquisitionFrameRateEnable" << std::endl; } + } + else if (SingleCamInfo[i].CamClass == BaslerClassID) + { + bool nRet = false; #ifndef USB_BASLER_NEW_FW - nRet = BaslerCamHandle[i]->TriggerSelector.TrySetValue(Basler_UniversalCameraParams::TriggerSelector_FrameBurstStart); - if (!nRet) { std::cout << "can not set Basler's TriggerSelector_FrameBurstStart" << std::endl;} - nRet = BaslerCamHandle[i]->TriggerMode.TrySetValue(Basler_UniversalCameraParams::TriggerMode_On); - if (!nRet) { std::cout << "can not set Basler's TriggerMode_On" << std::endl; } -#endif - nRet = BaslerCamHandle[i]->TriggerSelector.TrySetValue(Basler_UniversalCameraParams::TriggerSelector_FrameStart); - if (!nRet) { std::cout << "can not set Basler's TriggerSelector_FrameStart" << std::endl;} - nRet = BaslerCamHandle[i]->TriggerMode.TrySetValue(Basler_UniversalCameraParams::TriggerMode_On); - if (!nRet) { std::cout << "can not set Basler's TriggerMode_On" << std::endl;} - nRet = BaslerCamHandle[i]->AcquisitionFrameRateEnable.TrySetValue(false); - if (!nRet) { std::cout << "can not set Basler's AcquisitionFrameRateEnable" << std::endl;} - } - } - } - g_debug_mode = false; + nRet = BaslerCamHandle[i]->TriggerSelector.TrySetValue(Basler_UniversalCameraParams::TriggerSelector_FrameBurstStart); + if (!nRet) { std::cout << "can not set Basler's TriggerSelector_FrameBurstStart" << std::endl; } + nRet = BaslerCamHandle[i]->TriggerMode.TrySetValue(Basler_UniversalCameraParams::TriggerMode_On); + if (!nRet) { std::cout << "can not set Basler's TriggerMode_On" << std::endl; } +#endif + nRet = BaslerCamHandle[i]->TriggerSelector.TrySetValue(Basler_UniversalCameraParams::TriggerSelector_FrameStart); + if (!nRet) { std::cout << "can not set Basler's TriggerSelector_FrameStart" << std::endl; } + nRet = BaslerCamHandle[i]->TriggerMode.TrySetValue(Basler_UniversalCameraParams::TriggerMode_On); + if (!nRet) { std::cout << "can not set Basler's TriggerMode_On" << std::endl; } + nRet = BaslerCamHandle[i]->AcquisitionFrameRateEnable.TrySetValue(false); + if (!nRet) { std::cout << "can not set Basler's AcquisitionFrameRateEnable" << std::endl; } + } + } + } + g_debug_mode = false; } void Cigarette::CleanThreadStart() { - QThread* handleThread = new QThread(); - CleanWorkThread* cleanWorkThread = new CleanWorkThread(); + QThread* handleThread = new QThread(); + CleanWorkThread* cleanWorkThread = new CleanWorkThread(); - cleanWorkThread->moveToThread(handleThread); + cleanWorkThread->moveToThread(handleThread); - connect(handleThread, &QThread::started, cleanWorkThread, &CleanWorkThread::startWork); - connect(cleanWorkThread, &CleanWorkThread::workStart, cleanWorkThread, &CleanWorkThread::setSel); - connect(cleanWorkThread, &CleanWorkThread::workFinished, cleanWorkThread, &CleanWorkThread::deleteLater); - connect(cleanWorkThread, &CleanWorkThread::destroyed, handleThread, &QThread::quit); - connect(handleThread, &QThread::finished, handleThread, &QThread::deleteLater); - handleThread->start(); + connect(handleThread, &QThread::started, cleanWorkThread, &CleanWorkThread::startWork); + connect(cleanWorkThread, &CleanWorkThread::workStart, cleanWorkThread, &CleanWorkThread::setSel); + connect(cleanWorkThread, &CleanWorkThread::workFinished, cleanWorkThread, &CleanWorkThread::deleteLater); + connect(cleanWorkThread, &CleanWorkThread::destroyed, handleThread, &QThread::quit); + connect(handleThread, &QThread::finished, handleThread, &QThread::deleteLater); + handleThread->start(); } void Cigarette::CleanThreadStartAuto() { - QThread* handleThread = new QThread(); - CleanWorkThread* cleanWorkThread = new CleanWorkThread(); + QThread* handleThread = new QThread(); + CleanWorkThread* cleanWorkThread = new CleanWorkThread(); - cleanWorkThread->moveToThread(handleThread); + cleanWorkThread->moveToThread(handleThread); - connect(handleThread, &QThread::started, cleanWorkThread, &CleanWorkThread::startWorkAuto); - connect(cleanWorkThread, &CleanWorkThread::workStart, cleanWorkThread, &CleanWorkThread::setSelAuto); - connect(cleanWorkThread, &CleanWorkThread::workFinished, cleanWorkThread, &CleanWorkThread::deleteLater); - connect(cleanWorkThread, &CleanWorkThread::destroyed, handleThread, &QThread::quit); - connect(handleThread, &QThread::finished, handleThread, &QThread::deleteLater); - handleThread->start(); + connect(handleThread, &QThread::started, cleanWorkThread, &CleanWorkThread::startWorkAuto); + connect(cleanWorkThread, &CleanWorkThread::workStart, cleanWorkThread, &CleanWorkThread::setSelAuto); + connect(cleanWorkThread, &CleanWorkThread::workFinished, cleanWorkThread, &CleanWorkThread::deleteLater); + connect(cleanWorkThread, &CleanWorkThread::destroyed, handleThread, &QThread::quit); + connect(handleThread, &QThread::finished, handleThread, &QThread::deleteLater); + handleThread->start(); } void Cigarette::record_output_statistic(qint64 quantity, int Kick[NumberOfSupportedCameras], int shift) { - QString file_name, file_path; - for (int i = 0; i < NumberOfSupportedCameras; i++) - { - if (SingleCamInfo[i].IsOpen && quantity > 0) { - std::fstream cfg_file; - file_name = QString(STATISTIC_FILE).arg(i); - file_path = g_conf_path.config_path + "/" + file_name; - - char buf[256]; - memset(buf, 0, 256); - sprintf(buf, "%s", file_path.toLocal8Bit().constData()); - - cfg_file.open(buf, std::ios::app); - if (cfg_file.good()) - { - if (last_shift == 2 || last_shift == 256) { - memset(buf, 0, 256); - sprintf(buf, "\n\n**************************************************************************************\n"); - cfg_file.write(buf, strlen(buf)); - //QDate date = QDate::currentDate(); - QDateTime date = QDateTime::currentDateTime(); - memset(buf, 0, 256); - sprintf(buf, "%s:\n", date.toString("yyyy-MM-dd_HH-mm-ss").toStdString().c_str()); - cfg_file.write(buf, strlen(buf)); - } - memset(buf, 0, 256); - double ng_rate; - if (ng[i] > 0) - ng_rate = double(ng[i]) / production_number[i]; - else - ng_rate = 0; - sprintf(buf, "%c 总产量:%010I64d 剔除率:%02.5f%% 合格率:%02.5f%% NG率:%02.5f%%\n", (shift == 0) ? 'A' : ((shift == 1) ? 'B' : 'C'), quantity, ((double)Kick[i] / quantity) * 100, (1.0 - ng_rate) * 100, ng_rate * 100); - cfg_file.write(buf, strlen(buf)); - memset(buf, 0, 256); - } - cfg_file.close(); - } - } - last_shift = shift; + QString file_name, file_path; + for (int i = 0; i < NumberOfSupportedCameras; i++) + { + if (SingleCamInfo[i].IsOpen && quantity > 0) { + std::fstream cfg_file; + file_name = QString(STATISTIC_FILE).arg(i); + file_path = g_conf_path.config_path + "/" + file_name; + + char buf[256]; + memset(buf, 0, 256); + sprintf(buf, "%s", file_path.toLocal8Bit().constData()); + + cfg_file.open(buf, std::ios::app); + if (cfg_file.good()) + { + if (last_shift == 2 || last_shift == 256) { + memset(buf, 0, 256); + sprintf(buf, "\n\n**************************************************************************************\n"); + cfg_file.write(buf, strlen(buf)); + //QDate date = QDate::currentDate(); + QDateTime date = QDateTime::currentDateTime(); + memset(buf, 0, 256); + sprintf(buf, "%s:\n", date.toString("yyyy-MM-dd_HH-mm-ss").toStdString().c_str()); + cfg_file.write(buf, strlen(buf)); + } + memset(buf, 0, 256); + double ng_rate; + if (ng[i] > 0) + ng_rate = double(ng[i]) / production_number[i]; + else + ng_rate = 0; + sprintf(buf, "%c 鎬讳骇閲:%010I64d 鍓旈櫎鐜:%02.5f%% 鍚堟牸鐜:%02.5f%% NG鐜:%02.5f%%\n", (shift == 0) ? 'A' : ((shift == 1) ? 'B' : 'C'), quantity, ((double)Kick[i] / quantity) * 100, (1.0 - ng_rate) * 100, ng_rate * 100); + cfg_file.write(buf, strlen(buf)); + memset(buf, 0, 256); + } + cfg_file.close(); + } + } + last_shift = shift; } #ifdef __UDPSend void Cigarette::recMsgFromUdp(QString data) { - //std::cout << data.toStdString() << std::endl; - if (data == "START") - { - if (!g_admin_mode) - { - if (!g_op_mode) - { - sThread.sendData("OpNoLogin", g_sys_conf.FeedbackPort); - return; - } - } - if (m_PLCDevice->g_plc_ok) { - if (g_debug_mode) - { - sThread.sendData("StillDebug", g_sys_conf.FeedbackPort); - } - else - { - on_btn_start_released(); - } - } - } - else if (data == "END") - { - if (!g_admin_mode) - { - if (!g_op_mode) - { - sThread.sendData("OpNoLogin", g_sys_conf.FeedbackPort); - return; - } - } - on_btn_pause_released(); - } - - else if (data == "0") - { - OnRotateReleasedHub(0); - } - else if (data == "1") - { - OnRotateReleasedHub(1); - } - else if (data == "2") - { - OnRotateReleasedHub(2); - } - else if (data == "3") - { - OnRotateReleasedHub(3); - } - else if (data == "4") - { - OnRotateReleasedHub(4); - } - else if (data == "5") - { - OnRotateReleasedHub(5); - } - else if (data == "6") - { - OnRotateReleasedHub(6); - } - else if (data == "7") - { - OnRotateReleasedHub(7); - } - else if (data == "LOCK") - { - if (!g_admin_mode) - { - sThread.sendData("AdminNoLogin", g_sys_conf.FeedbackPort); - return; - } - on_btn_lock_released(); - } - else if (data == "CHANGESHIFT") - { - if (!g_admin_mode) - { - if (!g_op_mode) - { - sThread.sendData("OpNoLogin", g_sys_conf.FeedbackPort); - return; - } - } - if (g_working) - { - sThread.sendData("CheckWorkState", g_sys_conf.FeedbackPort); - } - else - { - on_pushButton_clear_released(); - } - } - else if (data == "CLEARNIMAGE") - { - emit sengMsgToClog("Clean images."); - CleanThreadStart(); - } - else if (data == "DEBUGEN") - { - if (!g_admin_mode) - { - sThread.sendData("Need_Login", g_sys_conf.FeedbackPort); - sThread.sendData("DebugEnFail", g_sys_conf.FeedbackPort); - return; - } - if (g_working) - { - if (g_debug_mode) - { - sThread.sendData("DebugEnStillWork", g_sys_conf.FeedbackPort); - } - else - { - sThread.sendData("DebugDisStillWork", g_sys_conf.FeedbackPort); - } - } - else - { - on_checkBox_debug_clicked(true); - } - } - else if (data == "DEBUGDIS") - { - if (!g_admin_mode) - { - sThread.sendData("Need_Login", g_sys_conf.FeedbackPort); - sThread.sendData("DebugDisFail", g_sys_conf.FeedbackPort); - return; - } - on_checkBox_debug_clicked(false); - } - else if (data == "KICK") - { - if (!g_admin_mode) - { - if (!g_op_mode) - { - sThread.sendData("OpNoLogin", g_sys_conf.FeedbackPort); - sThread.sendData("KickFail", g_sys_conf.FeedbackPort); - return; - } - } - on_checkBox_unkick_clicked(false); - } - else if (data == "UNKICK") - { - if (!g_admin_mode) - { - if (!g_op_mode) - { - sThread.sendData("OpNoLogin", g_sys_conf.FeedbackPort); - sThread.sendData("UnKickFail", g_sys_conf.FeedbackPort); - return; - } - } - if (m_PLCDevice->g_plc_ok) - { - on_checkBox_unkick_clicked(true); - ui.checkBox_unkick->setChecked(true); - } - else - { - sThread.sendData("UnKickFail", g_sys_conf.FeedbackPort); - } - } - else if (data == "GETCONF") - { - QString file_name, file_path; - sThread.sendFile(g_conf_path.config_path, g_sys_conf.FilePort); - for(int i=0;iisChecked()) - { - msg += "UnKickOk"; - } - else - { - msg += "KickOk"; - } - sThread.sendData(msg, g_sys_conf.FeedbackPort); - } - else if (dataList[0] == "GETSETTINGPRO") - { - if (!g_admin_mode) - { - if (!g_op_mode) - { - sThread.sendData("OpNoLogin", g_sys_conf.FeedbackPort); - return; - } - } - int camcnt = dataList[1].toInt(); - QString str; - str = QString("getsetting") + '_' + \ - QString::number(g_sys_conf.auto_open) + '_' +\ - QString::number(g_sys_conf.auto_work) + '_' +\ - QString::number(g_sys_conf.save) + '_'; - for(int i = 0;i to UDP: " << str.toStdString() << std::endl; - } - else if (dataList[0] == "UPDSETTING") - { - // 参数比远程端多1 - int index =0; - int camcnt = atoi(dataList[1].toStdString().c_str()); - g_sys_conf.auto_open = dataList[2].toStdString() == "True" ? 1 : 0; - g_sys_conf.auto_work = dataList[3].toStdString() == "True" ? 1 : 0; - g_sys_conf.save = atoi(dataList[4].toStdString().c_str()); - for (; index < camcnt; index++) - { - g_sys_conf.expo[index] = atoi(dataList[5+index*3].toStdString().c_str()); - g_sys_conf.gain[index] = atoi(dataList[6+index*3].toStdString().c_str()); - g_sys_conf.filter[index] = atoi(dataList[7+index*3].toStdString().c_str()); - } - index = 5+camcnt*3; - g_sys_conf.shift_byhand = dataList[index].toInt(); - g_sys_conf.timing_shift = dataList[index + 1].toInt(); - index = index + 2; - g_sys_conf.shiftA.setHMS(atoi(dataList[index].toStdString().c_str()), atoi(dataList[index+1].toStdString().c_str()), 0); - g_sys_conf.shiftB.setHMS(atoi(dataList[index+2].toStdString().c_str()), atoi(dataList[index+3].toStdString().c_str()), 0); - g_sys_conf.shiftC.setHMS(atoi(dataList[index+4].toStdString().c_str()), atoi(dataList[index+5].toStdString().c_str()), 0); - index = index+6; - for (int i = 0; i < camcnt; i++) - { - g_sys_conf.no[i][0] = atoi(dataList[index+i*3].toStdString().c_str()); - g_sys_conf.no[i][1] = atoi(dataList[index+i*3+1].toStdString().c_str()); - g_sys_conf.no[i][2] = atoi(dataList[index+i*3+2].toStdString().c_str()); - } - - DialogSetup::write_config(); - sThread.sendData("UpSettingOk", g_sys_conf.FeedbackPort); - // QMessageBox::information(NULL, QStringLiteral("提示"), QStringLiteral("保存参数成功,部分配置需要重启程序后生效"), QMessageBox::Ok); - } - else if (dataList[0] == "OPERPWDCHANGE") - { - QString md5Str = QCryptographicHash::hash(dataList[1].toLatin1(), QCryptographicHash::Md5).toHex(); - if (md5Str.compare(g_op_pswd, Qt::CaseInsensitive) == 0) - { - QString pswd_new = dataList[2]; - QString pswd_confirm = dataList[3]; - if (pswd_new.compare(pswd_confirm, Qt::CaseInsensitive) == 0) - { - g_op_pswd = QCryptographicHash::hash(pswd_new.toLatin1(), QCryptographicHash::Md5).toHex(); - DialogSetup::write_pswd_op(); - // QMessageBox::information(NULL, QStringLiteral("提示"), QStringLiteral("操作员密码修改成功"), QMessageBox::Ok); - } - else { - // QMessageBox::information(NULL, QStringLiteral("提示消息"), QStringLiteral("新密码两次输入不一致,请重新输入"), QMessageBox::Ok); - } - } - else { - // QMessageBox::information(NULL, QStringLiteral("提示消息"), QStringLiteral("原密码错误,请重新输入"), QMessageBox::Ok); - } - } - else if (dataList[0] == "ADMINPWDCHANGE") - { - QString md5Str = QCryptographicHash::hash(dataList[1].toLatin1(), QCryptographicHash::Md5).toHex(); - if (md5Str.compare(g_admin_pswd, Qt::CaseInsensitive) == 0) - { - QString pswd_new = dataList[2]; - QString pswd_confirm = dataList[3]; - if (pswd_new.compare(pswd_confirm, Qt::CaseInsensitive) == 0) - { - g_admin_pswd = QCryptographicHash::hash(pswd_new.toLatin1(), QCryptographicHash::Md5).toHex(); - DialogSetup::write_pswd(); - // QMessageBox::information(NULL, QStringLiteral("提示"), QStringLiteral("管理员密码修改成功"), QMessageBox::Ok); - } - else { - // QMessageBox::information(NULL, QStringLiteral("提示消息"), QStringLiteral("新密码两次输入不一致,请重新输入"), QMessageBox::Ok); - } - } - else { - // QMessageBox::information(NULL, QStringLiteral("提示消息"), QStringLiteral("原密码错误,请重新输入"), QMessageBox::Ok); - } - } - } -} -#endif \ No newline at end of file + //std::cout << data.toStdString() << std::endl; + if (data == "START") + { + if (!g_admin_mode) + { + if (!g_op_mode) + { + sThread.sendData("OpNoLogin", g_sys_conf.FeedbackPort); + return; + } + } + if (m_PLCDevice->g_plc_ok) { + if (g_debug_mode) + { + sThread.sendData("StillDebug", g_sys_conf.FeedbackPort); + } + else + { + on_btn_start_released(); + } + } + } + else if (data == "END") + { + if (!g_admin_mode) + { + if (!g_op_mode) + { + sThread.sendData("OpNoLogin", g_sys_conf.FeedbackPort); + return; + } + } + on_btn_pause_released(); + } + + else if (data == "0") + { + OnRotateReleasedHub(0); + } + else if (data == "1") + { + OnRotateReleasedHub(1); + } + else if (data == "2") + { + OnRotateReleasedHub(2); + } + else if (data == "3") + { + OnRotateReleasedHub(3); + } + else if (data == "4") + { + OnRotateReleasedHub(4); + } + else if (data == "5") + { + OnRotateReleasedHub(5); + } + else if (data == "6") + { + OnRotateReleasedHub(6); + } + else if (data == "7") + { + OnRotateReleasedHub(7); + } + else if (data == "LOCK") + { + if (!g_admin_mode) + { + sThread.sendData("AdminNoLogin", g_sys_conf.FeedbackPort); + return; + } + on_btn_lock_released(); + } + else if (data == "CHANGESHIFT") + { + if (!g_admin_mode) + { + if (!g_op_mode) + { + sThread.sendData("OpNoLogin", g_sys_conf.FeedbackPort); + return; + } + } + if (g_working) + { + sThread.sendData("CheckWorkState", g_sys_conf.FeedbackPort); + } + else + { + on_pushButton_clear_released(); + } + } + else if (data == "CLEARNIMAGE") + { + emit sengMsgToClog("Clean images."); + CleanThreadStart(); + } + else if (data == "DEBUGEN") + { + if (!g_admin_mode) + { + sThread.sendData("Need_Login", g_sys_conf.FeedbackPort); + sThread.sendData("DebugEnFail", g_sys_conf.FeedbackPort); + return; + } + if (g_working) + { + if (g_debug_mode) + { + sThread.sendData("DebugEnStillWork", g_sys_conf.FeedbackPort); + } + else + { + sThread.sendData("DebugDisStillWork", g_sys_conf.FeedbackPort); + } + } + else + { + on_checkBox_debug_clicked(true); + } + } + else if (data == "DEBUGDIS") + { + if (!g_admin_mode) + { + sThread.sendData("Need_Login", g_sys_conf.FeedbackPort); + sThread.sendData("DebugDisFail", g_sys_conf.FeedbackPort); + return; + } + on_checkBox_debug_clicked(false); + } + else if (data == "KICK") + { + if (!g_admin_mode) + { + if (!g_op_mode) + { + sThread.sendData("OpNoLogin", g_sys_conf.FeedbackPort); + sThread.sendData("KickFail", g_sys_conf.FeedbackPort); + return; + } + } + on_checkBox_unkick_clicked(false); + } + else if (data == "UNKICK") + { + if (!g_admin_mode) + { + if (!g_op_mode) + { + sThread.sendData("OpNoLogin", g_sys_conf.FeedbackPort); + sThread.sendData("UnKickFail", g_sys_conf.FeedbackPort); + return; + } + } + if (m_PLCDevice->g_plc_ok) + { + on_checkBox_unkick_clicked(true); + ui.checkBox_unkick->setChecked(true); + } + else + { + sThread.sendData("UnKickFail", g_sys_conf.FeedbackPort); + } + } + else if (data == "GETCONF") + { + QString file_name, file_path; + sThread.sendFile(g_conf_path.config_path, g_sys_conf.FilePort); + for (int i = 0; i < NumberOfSupportedCameras; i++) + { + //char buf[256]; + //memset(buf, 0, 256); + //sprintf(buf, STATISTIC_FILE, i); + //QString str(buf); + + file_name = QString(STATISTIC_FILE).arg(i); + file_path = g_conf_path.config_path + "/" + file_name; + sThread.sendFile(file_path.toLocal8Bit().constData(), g_sys_conf.FilePort); + } + + } + else if (data == "SETCONF") + { + sThread.sendData("CanSetConf", g_sys_conf.FeedbackPort); + } + else if (data == "RESTART") + { + onrestart = true; + OnRestart(); + onrestart = false; + } + else if (data == "GETSETTING") + { + if (!g_admin_mode)///绠$悊鍛樻潈闄愯繘鍏ョ郴缁熻缃 + { + sThread.sendData("AdminNoLogin", g_sys_conf.FeedbackPort); + return; + } + else + { + sThread.sendData("CanGetSetting", g_sys_conf.FeedbackPort); + } + + } + else if (data == "RESET") + { + if (!g_admin_mode) + { + if (!g_op_mode) + { + sThread.sendData("OpNoLogin", g_sys_conf.FeedbackPort); + return; + } + } + on_pushButton_reset_released(); + } + else if (data == "CLEARALARM") + { + if (!g_admin_mode) + { + if (!g_op_mode) + { + sThread.sendData("OpNoLogin", g_sys_conf.FeedbackPort); + return; + } + } + OnCancelAlarm(); + } + else if (data == "GETALARMRECORD") + { + if (!g_admin_mode) + { + if (!g_op_mode) + { + sThread.sendData("OpNoLogin", g_sys_conf.FeedbackPort); + return; + } + } + sThread.sendFile(ALARM_RECORD_FILE, g_sys_conf.FilePort); + } + else { + QStringList dataList = data.split(':'); + if (dataList[0] == "OPLOGIN") { + QString md5Str = QCryptographicHash::hash(dataList[1].toLatin1(), QCryptographicHash::Md5).toHex(); + qDebug() << "m_pswd:" << dataList[1]; + qDebug() << "m_pswd md5:" << md5Str; + qDebug() << "g_op_pswd md5:" << g_op_pswd;/// + if (md5Str.compare(g_op_pswd, Qt::CaseInsensitive) == 0)/// + { + g_op_mode = true; + OnOp(); + sThread.sendData("LoginIn", g_sys_conf.FeedbackPort); + } + else { + sThread.sendData("PswError", g_sys_conf.FeedbackPort); + } + } + else if (dataList[0] == "ADMINLOGIN") { + QString md5Str = QCryptographicHash::hash(dataList[1].toLatin1(), QCryptographicHash::Md5).toHex(); + qDebug() << "m_pswd:" << dataList[1]; + qDebug() << "m_pswd md5:" << md5Str; + qDebug() << "g_admin_pswd md5:" << g_admin_pswd; + if (md5Str.compare(g_admin_pswd, Qt::CaseInsensitive) == 0)/// + { + g_admin_mode = true; + OnAdmin(); + sThread.sendData("LoginIn", g_sys_conf.FeedbackPort); + } + else { + sThread.sendData("PswError", g_sys_conf.FeedbackPort); + } + } + else if (dataList[0] == "CONNECTIONTEST") + { + QString msg = QString("HandShake") + '_'; + if (g_admin_mode) + { + msg += "UnlockOk"; + } + else + { + msg += "LockOk"; + } + msg += '_'; + if (g_debug_mode) + { + msg += "DebugEn"; + } + else + { + msg += "DebugDis"; + } + msg += '_'; + if (ui.checkBox_unkick->isChecked()) + { + msg += "UnKickOk"; + } + else + { + msg += "KickOk"; + } + sThread.sendData(msg, g_sys_conf.FeedbackPort); + } + else if (dataList[0] == "GETSETTINGPRO") + { + if (!g_admin_mode) + { + if (!g_op_mode) + { + sThread.sendData("OpNoLogin", g_sys_conf.FeedbackPort); + return; + } + } + int camcnt = dataList[1].toInt(); + QString str; + str = QString("getsetting") + '_' + \ + QString::number(g_sys_conf.auto_open) + '_' + \ + QString::number(g_sys_conf.auto_work) + '_' + \ + QString::number(g_sys_conf.save) + '_'; + for (int i = 0; i < camcnt; i++) { + str += QString::number(g_sys_conf.expo[i]) + '_' + QString::number(g_sys_conf.gain[i]) + '_' + QString::number(g_sys_conf.filter[i]) + '_'; + } + str += QString::number(g_sys_conf.shift_byhand) + '_' + \ + QString::number(g_sys_conf.timing_shift) + '_'; + str += QString::number(g_sys_conf.shiftA.hour()) + '_' + \ + QString::number(g_sys_conf.shiftA.minute()) + '_' + \ + QString::number(g_sys_conf.shiftB.hour()) + '_' + \ + QString::number(g_sys_conf.shiftB.minute()) + '_' + \ + QString::number(g_sys_conf.shiftC.hour()) + '_' + \ + QString::number(g_sys_conf.shiftC.minute()) + '_'; + for (int i = 0; i < camcnt; i++) { + str += QString::number(g_sys_conf.no[i][0]) + '_' + QString::number(g_sys_conf.no[i][1]) + '_' + QString::number(g_sys_conf.no[i][2]) + '_'; + } + sThread.sendData(str, g_sys_conf.FeedbackPort); + //std::cout << "=> to UDP: " << str.toStdString() << std::endl; + } + else if (dataList[0] == "UPDSETTING") + { + // 鍙傛暟姣旇繙绋嬬澶1 + int index = 0; + int camcnt = atoi(dataList[1].toStdString().c_str()); + g_sys_conf.auto_open = dataList[2].toStdString() == "True" ? 1 : 0; + g_sys_conf.auto_work = dataList[3].toStdString() == "True" ? 1 : 0; + g_sys_conf.save = atoi(dataList[4].toStdString().c_str()); + for (; index < camcnt; index++) + { + g_sys_conf.expo[index] = atoi(dataList[5 + index * 3].toStdString().c_str()); + g_sys_conf.gain[index] = atoi(dataList[6 + index * 3].toStdString().c_str()); + g_sys_conf.filter[index] = atoi(dataList[7 + index * 3].toStdString().c_str()); + } + index = 5 + camcnt * 3; + g_sys_conf.shift_byhand = dataList[index].toInt(); + g_sys_conf.timing_shift = dataList[index + 1].toInt(); + index = index + 2; + g_sys_conf.shiftA.setHMS(atoi(dataList[index].toStdString().c_str()), atoi(dataList[index + 1].toStdString().c_str()), 0); + g_sys_conf.shiftB.setHMS(atoi(dataList[index + 2].toStdString().c_str()), atoi(dataList[index + 3].toStdString().c_str()), 0); + g_sys_conf.shiftC.setHMS(atoi(dataList[index + 4].toStdString().c_str()), atoi(dataList[index + 5].toStdString().c_str()), 0); + index = index + 6; + for (int i = 0; i < camcnt; i++) + { + g_sys_conf.no[i][0] = atoi(dataList[index + i * 3].toStdString().c_str()); + g_sys_conf.no[i][1] = atoi(dataList[index + i * 3 + 1].toStdString().c_str()); + g_sys_conf.no[i][2] = atoi(dataList[index + i * 3 + 2].toStdString().c_str()); + } + + DialogSetup::write_config(); + sThread.sendData("UpSettingOk", g_sys_conf.FeedbackPort); + // QMessageBox::information(NULL, QStringLiteral("鎻愮ず"), QStringLiteral("淇濆瓨鍙傛暟鎴愬姛,閮ㄥ垎閰嶇疆闇瑕侀噸鍚▼搴忓悗鐢熸晥"), QMessageBox::Ok); + } + else if (dataList[0] == "OPERPWDCHANGE") + { + QString md5Str = QCryptographicHash::hash(dataList[1].toLatin1(), QCryptographicHash::Md5).toHex(); + if (md5Str.compare(g_op_pswd, Qt::CaseInsensitive) == 0) + { + QString pswd_new = dataList[2]; + QString pswd_confirm = dataList[3]; + if (pswd_new.compare(pswd_confirm, Qt::CaseInsensitive) == 0) + { + g_op_pswd = QCryptographicHash::hash(pswd_new.toLatin1(), QCryptographicHash::Md5).toHex(); + DialogSetup::write_pswd_op(); + // QMessageBox::information(NULL, QStringLiteral("鎻愮ず"), QStringLiteral("鎿嶄綔鍛樺瘑鐮佷慨鏀规垚鍔"), QMessageBox::Ok); + } + else { + // QMessageBox::information(NULL, QStringLiteral("鎻愮ず娑堟伅"), QStringLiteral("鏂板瘑鐮佷袱娆¤緭鍏ヤ笉涓鑷达紝璇烽噸鏂拌緭鍏"), QMessageBox::Ok); + } + } + else { + // QMessageBox::information(NULL, QStringLiteral("鎻愮ず娑堟伅"), QStringLiteral("鍘熷瘑鐮侀敊璇紝璇烽噸鏂拌緭鍏"), QMessageBox::Ok); + } + } + else if (dataList[0] == "ADMINPWDCHANGE") + { + QString md5Str = QCryptographicHash::hash(dataList[1].toLatin1(), QCryptographicHash::Md5).toHex(); + if (md5Str.compare(g_admin_pswd, Qt::CaseInsensitive) == 0) + { + QString pswd_new = dataList[2]; + QString pswd_confirm = dataList[3]; + if (pswd_new.compare(pswd_confirm, Qt::CaseInsensitive) == 0) + { + g_admin_pswd = QCryptographicHash::hash(pswd_new.toLatin1(), QCryptographicHash::Md5).toHex(); + DialogSetup::write_pswd(); + // QMessageBox::information(NULL, QStringLiteral("鎻愮ず"), QStringLiteral("绠$悊鍛樺瘑鐮佷慨鏀规垚鍔"), QMessageBox::Ok); + } + else { + // QMessageBox::information(NULL, QStringLiteral("鎻愮ず娑堟伅"), QStringLiteral("鏂板瘑鐮佷袱娆¤緭鍏ヤ笉涓鑷达紝璇烽噸鏂拌緭鍏"), QMessageBox::Ok); + } + } + else { + // QMessageBox::information(NULL, QStringLiteral("鎻愮ず娑堟伅"), QStringLiteral("鍘熷瘑鐮侀敊璇紝璇烽噸鏂拌緭鍏"), QMessageBox::Ok); + } + } + } +} +#endif diff --git a/Cigarette/cigarette.h b/Cigarette/cigarette.h index 20e37289..d911463f 100644 --- a/Cigarette/cigarette.h +++ b/Cigarette/cigarette.h @@ -56,179 +56,179 @@ class QTimer; #define CLOSE false class Cigarette : public QMainWindow { - Q_OBJECT + Q_OBJECT public: - Cigarette(QWidget *parent = 0); - ~Cigarette(); - - static QImage cvMatToQImage(const cv::Mat& mat); - - QString read_pswd(); - QString read_op_pswd(); - - bool read_conf(ConfPath &conf_path); - bool read_sys_config(SysConf &conf, QString conf_path); - bool read_modbus_config(ModbusConf &conf); - void read_plc_items(); - bool save_rotate_message(); - bool read_rotate_message(); - bool save_alarm_message(std::vector &AlarmInfo_vect); - void init_plc_value(); - void CreatWorkThread(int classid,int Num,Cigarette* classptr); - void InitPtrMat(); - bool ControlCamOpenOrClose(int Num,bool OpenOrClose); - void EnumerateCameras(SingleCamInfoStruct *TempSingleCamInfo,bool showinfo,SysConf &conf); - void start_work(); - void pause_work(); - void CleanThreadStart(); - void Exit(); -private slots : - void on_btn_start_released(); - void on_btn_pause_released(); - //void on_btn_pause_clicked(bool checked); - void on_btn_lock_released(); - void on_btn_setup_released(); - void on_checkBox_debug_clicked(bool checked); - void on_checkBox_unkick_clicked(bool checked); - void on_pushButton_wintab_clicked(bool checked); - void on_toolButton_plc_released(); - void on_toolButton_alarm_released(); - void on_pushButton_clear_released(); - void enable_shift(); + Cigarette(QWidget* parent = 0); + ~Cigarette(); + + static QImage cvMatToQImage(const cv::Mat& mat); + + QString read_pswd(); + QString read_op_pswd(); + + bool read_conf(ConfPath& conf_path); + bool read_sys_config(SysConf& conf, QString conf_path); + bool read_modbus_config(ModbusConf& conf); + void read_plc_items(); + bool save_rotate_message(); + bool read_rotate_message(); + bool save_alarm_message(std::vector& AlarmInfo_vect); + void init_plc_value(); + void CreatWorkThread(int classid, int Num, Cigarette* classptr); + void InitPtrMat(); + bool ControlCamOpenOrClose(int Num, bool OpenOrClose); + void EnumerateCameras(SingleCamInfoStruct* TempSingleCamInfo, bool showinfo, SysConf& conf); + void start_work(); + void pause_work(); + void CleanThreadStart(); + void Exit(); +private slots: + void on_btn_start_released(); + void on_btn_pause_released(); + //void on_btn_pause_clicked(bool checked); + void on_btn_lock_released(); + void on_btn_setup_released(); + void on_checkBox_debug_clicked(bool checked); + void on_checkBox_unkick_clicked(bool checked); + void on_pushButton_wintab_clicked(bool checked); + void on_toolButton_plc_released(); + void on_toolButton_alarm_released(); + void on_pushButton_clear_released(); + void enable_shift(); #ifdef __UDPSend - void sendLatestData(); + void sendLatestData(); #endif - void OnNotifyHub(int Num, int Cnt, cv::Mat m); - void OnDisplayTimeCostHub(int Num, int ms); - void OnDisplayCheckNumberHub(int Num, long no); - void OnDisplayJdNoHub(int Num, QString jd_no); - void OnOKHub(int Num); - void OnNGHub(int Num); - void updateStatisticsHub(const QString& statisticalData, int Num); - void OnRotateReleasedHub(int Num); - void OnToolButtonCamReleasedHub(int Num); - void OpenCamTimeoutHub(int Num); - void OnDBClickHub(int Num_Cnt); - void DrawRect_init(int Num_Cnt); - void OnTPClickHub(int Num_Cnt); - void OnDBClickNGHub(int Num); - void ReconnectCamHub(int Num); - void OnMouse(QMouseEvent* event); - void OnKey(QKeyEvent* event); - void handleTimeout(); //瀹氭椂浠诲姟锛屾瘡绉掕繍琛屼竴娆 - void op_timeout(); //鎿嶄綔鍛樺墿浣欐椂闂 - void admin_timeout(); //绠$悊鍛樻潈闄愬墿浣欐椂闂 - void EnableDebugMode(); - void DisableDebugMode(); - - void OnCancelAlarm(); //鍙屽嚮娑堣 - void on_pushButton_reset_released();//澶嶄綅 - - void OnOp(); - void OnExit(); - void OnRestart(); - void OnAdmin(); + void OnNotifyHub(int Num, int Cnt, cv::Mat m); + void OnDisplayTimeCostHub(int Num, int ms); + void OnDisplayCheckNumberHub(int Num, long no); + void OnDisplayJdNoHub(int Num, QString jd_no); + void OnOKHub(int Num); + void OnNGHub(int Num); + void updateStatisticsHub(const QString& statisticalData, int Num); + void OnRotateReleasedHub(int Num); + void OnToolButtonCamReleasedHub(int Num); + void OpenCamTimeoutHub(int Num); + void OnDBClickHub(int Num_Cnt); + void DrawRect_init(int Num_Cnt); + void OnTPClickHub(int Num_Cnt); + void OnDBClickNGHub(int Num); + void ReconnectCamHub(int Num); + void OnMouse(QMouseEvent* event); + void OnKey(QKeyEvent* event); + void handleTimeout(); //瀹氭椂浠诲姟锛屾瘡绉掕繍琛屼竴娆 + void op_timeout(); //鎿嶄綔鍛樺墿浣欐椂闂 + void admin_timeout(); //绠$悊鍛樻潈闄愬墿浣欐椂闂 + void EnableDebugMode(); + void DisableDebugMode(); + + void OnCancelAlarm(); //鍙屽嚮娑堣 + void on_pushButton_reset_released();//澶嶄綅 + + void OnOp(); + void OnExit(); + void OnRestart(); + void OnAdmin(); #ifdef __DEBUG - void TestImg(); - void TestImgs(); + void TestImg(); + void TestImgs(); #endif private: - Ui::CigaretteClass ui; - DialogSetupPasswd *dialog_setup_passwd; - Dialogin *dialogin; - DialogSetup *dialog_setup; - PlcSetup * dialog_plc_setup; - std::vector m_plc_items; + Ui::CigaretteClass ui; + DialogSetupPasswd* dialog_setup_passwd; + Dialogin* dialogin; + DialogSetup* dialog_setup; + PlcSetup* dialog_plc_setup; + std::vector m_plc_items; public: - QTimer *m_pTimer_Cam_mat[NumberOfSupportedCameras]; //鐩告満閲嶅惎瀹氭椂鍣 - QLabel *label_cap_speed_mat[NumberOfSupportedCameras]; - QLabel *cam_status_mat[NumberOfSupportedCameras]; - QLabel *cam_work_mat[NumberOfSupportedCameras]; - QToolButton *cam_toolButton_mat[NumberOfSupportedCameras]; - db_label * display_lable_mat[NumberOfSupportedCameras][2]; - QLabel *label_timecost_mat[NumberOfSupportedCameras]; - QLCDNumber *lcdNumber_total_mat[NumberOfSupportedCameras]; - QLabel *label_jd_no_mat[NumberOfSupportedCameras]; - QLCDNumber *lcdNumber_ok_mat[NumberOfSupportedCameras]; - QLCDNumber *lcdNumber_ng_mat[NumberOfSupportedCameras]; - QLCDNumber* lcdNumber_kick_mat[NumberOfSupportedCameras]; - QLabel *label_reslut_mat[NumberOfSupportedCameras]; - QToolButton *rotate_mat[NumberOfSupportedCameras]; - QLabel *label_ng_mat[NumberOfSupportedCameras]; - - struct widget_info - { - UINT32 x; - UINT32 y; - UINT32 width; - UINT32 height; - }; - widget_info display_lable_info[NumberOfSupportedCameras][2]; - widget_info rotate_info[NumberOfSupportedCameras]; + QTimer* m_pTimer_Cam_mat[NumberOfSupportedCameras]; //鐩告満閲嶅惎瀹氭椂鍣 + QLabel* label_cap_speed_mat[NumberOfSupportedCameras]; + QLabel* cam_status_mat[NumberOfSupportedCameras]; + QLabel* cam_work_mat[NumberOfSupportedCameras]; + QToolButton* cam_toolButton_mat[NumberOfSupportedCameras]; + db_label* display_lable_mat[NumberOfSupportedCameras][2]; + QLabel* label_timecost_mat[NumberOfSupportedCameras]; + QLCDNumber* lcdNumber_total_mat[NumberOfSupportedCameras]; + QLabel* label_jd_no_mat[NumberOfSupportedCameras]; + QLCDNumber* lcdNumber_ok_mat[NumberOfSupportedCameras]; + QLCDNumber* lcdNumber_ng_mat[NumberOfSupportedCameras]; + QLCDNumber* lcdNumber_kick_mat[NumberOfSupportedCameras]; + QLabel* label_reslut_mat[NumberOfSupportedCameras]; + QToolButton* rotate_mat[NumberOfSupportedCameras]; + QLabel* label_ng_mat[NumberOfSupportedCameras]; + + struct widget_info + { + UINT32 x; + UINT32 y; + UINT32 width; + UINT32 height; + }; + widget_info display_lable_info[NumberOfSupportedCameras][2]; + widget_info rotate_info[NumberOfSupportedCameras]; #ifdef SYNC_CAMERA - SyncWorkThread sync_work_thread; + SyncWorkThread sync_work_thread; #else - WorkThread work_thread[NumberOfSupportedCameras]; + WorkThread work_thread[NumberOfSupportedCameras]; #endif - DebugThread debug_thread[NumberOfSupportedCameras]; - - struct export_info { - int cameraId = -1; - int totalCheckNum = 0; - int totalKickNum = 0; - int kick = 0; - int checkNum = 0; - QString detectTime = "0"; - QString acquisitionTime = "0"; - QString jdNum = QString("0,0,0"); - int okNum = 0; - int ngNum = 0; - }; - export_info exportData[NumberOfSupportedCameras]; - - SaveThread saveThread; - void record_output_statistic(qint64 cur_quantity, int Kick[NumberOfSupportedCameras], int shift); - - QTimer *m_pTimer; - QTimer *m_delay; //鎹㈢彮闃叉杩炲嚮 - QTimer* m_sendMsg_delay; // 鍋滄宸ヤ綔鍚庡彂閫佹渶鏂版暟鎹粰杩滅▼绔 - QTimer *m_op_delay; //鎿嶄綔鍛樻潈闄愬墿浣欐椂闂 - QTimer *m_admin_delay; //鎿嶄綔鍛樻潈闄愬墿浣欐椂闂 - QTimer *clean_pTimer; //瀹氭椂娓呯悊浠诲姟 - - QSignalMapper *image_lable_DBsignalMapper0; - QSignalMapper *image_lable_DBsignalMapper1; - QSignalMapper *image_lable_TPsignalMapper0; - QSignalMapper *image_lable_TPsignalMapper1; - QSignalMapper *label_ng_signalMapper; - QSignalMapper *pTimer_Cam_signalMapper; - QSignalMapper *toolButton_cam_signalMapper; - QSignalMapper *RotateReleased_signalMapper; - int total_production_number; - int production_number[NumberOfSupportedCameras]; - int OpenWithUserID[NumberOfSupportedCameras]; - int ok[NumberOfSupportedCameras], ng[NumberOfSupportedCameras]; + DebugThread debug_thread[NumberOfSupportedCameras]; + + struct export_info { + int cameraId = -1; + int totalCheckNum = 0; + int totalKickNum = 0; + int kick = 0; + int checkNum = 0; + QString detectTime = "0"; + QString acquisitionTime = "0"; + QString jdNum = QString("0,0,0"); + int okNum = 0; + int ngNum = 0; + }; + export_info exportData[NumberOfSupportedCameras]; + + SaveThread saveThread; + void record_output_statistic(qint64 cur_quantity, int Kick[NumberOfSupportedCameras], int shift); + + QTimer* m_pTimer; + QTimer* m_delay; //鎹㈢彮闃叉杩炲嚮 + QTimer* m_sendMsg_delay; // 鍋滄宸ヤ綔鍚庡彂閫佹渶鏂版暟鎹粰杩滅▼绔 + QTimer* m_op_delay; //鎿嶄綔鍛樻潈闄愬墿浣欐椂闂 + QTimer* m_admin_delay; //鎿嶄綔鍛樻潈闄愬墿浣欐椂闂 + QTimer* clean_pTimer; //瀹氭椂娓呯悊浠诲姟 + + QSignalMapper* image_lable_DBsignalMapper0; + QSignalMapper* image_lable_DBsignalMapper1; + QSignalMapper* image_lable_TPsignalMapper0; + QSignalMapper* image_lable_TPsignalMapper1; + QSignalMapper* label_ng_signalMapper; + QSignalMapper* pTimer_Cam_signalMapper; + QSignalMapper* toolButton_cam_signalMapper; + QSignalMapper* RotateReleased_signalMapper; + int total_production_number; + int production_number[NumberOfSupportedCameras]; + int OpenWithUserID[NumberOfSupportedCameras]; + int ok[NumberOfSupportedCameras], ng[NumberOfSupportedCameras]; #ifdef __UDPSend - private: - threadSend sThread; - threadReceive *rThread; +private: + threadSend sThread; + threadReceive* rThread; #endif #ifdef __TCPSend - private: - threadSendTCP tcpSendThread; +private: + threadSendTCP tcpSendThread; #endif public slots: - void CleanThreadStartAuto(); + void CleanThreadStartAuto(); #ifdef __UDPSend - void recMsgFromUdp(QString data); + void recMsgFromUdp(QString data); #endif - //void ClogThreadStart(); + //void ClogThreadStart(); signals: - void sengMsgToClog(QString); - void sendMsgToExportData(); + void sengMsgToClog(QString); + void sendMsgToExportData(); }; #endif // CIGARETTE_H diff --git a/Cigarette/common.cpp b/Cigarette/common.cpp index cffa1042..852bfcad 100644 --- a/Cigarette/common.cpp +++ b/Cigarette/common.cpp @@ -7,28 +7,28 @@ #include #include -int string_split(std::string str, std::string pattern,std::vector &out) +int string_split(std::string str, std::string pattern, std::vector& out) { - std::string::size_type pos; - int cnt = 0; - str += pattern; - int size = str.size(); - - for (int i = 0; i > > &VecRects, - int VecCnt, - DisplayLabelConf &t_DisplayLabelConf, - int LabelCnt + cv::Mat input, + std::vector > >& VecRects, + int VecCnt, + DisplayLabelConf& t_DisplayLabelConf, + int LabelCnt ) { - bool find; - if (!(t_DisplayLabelConf.Flag[LabelCnt] & DisplayLabel_Type_Bit)) - { - return false; - } - if (VecCnt < VecRects.size()) - { - for (int i = 0; i < VecRects[VecCnt].size(); i++) - { - find = false; - for(int j = 0; j < t_DisplayLabelConf.RectVet[LabelCnt].size(); j++) - { - cv::Rect LocalRect = VecRects[VecCnt][i].second; - cv::Rect CheckRect = cv::Rect( - cv::Point( - t_DisplayLabelConf.RectVet[LabelCnt][j].TL.x* input.cols, - t_DisplayLabelConf.RectVet[LabelCnt][j].TL.y* input.rows - ), - cv::Point( - t_DisplayLabelConf.RectVet[LabelCnt][j].BR.x* input.cols, - t_DisplayLabelConf.RectVet[LabelCnt][j].BR.y* input.rows - ) - ); - - cv::Rect tempRect = (LocalRect & CheckRect); - if(LocalRect == tempRect) - { - find = true; - } - } - if(!find) - { - return true; - } - } - } - return false; + bool find; + if (!(t_DisplayLabelConf.Flag[LabelCnt] & DisplayLabel_Type_Bit)) + { + return false; + } + if (VecCnt < VecRects.size()) + { + for (int i = 0; i < VecRects[VecCnt].size(); i++) + { + find = false; + for (int j = 0; j < t_DisplayLabelConf.RectVet[LabelCnt].size(); j++) + { + cv::Rect LocalRect = VecRects[VecCnt][i].second; + cv::Rect CheckRect = cv::Rect( + cv::Point( + t_DisplayLabelConf.RectVet[LabelCnt][j].TL.x * input.cols, + t_DisplayLabelConf.RectVet[LabelCnt][j].TL.y * input.rows + ), + cv::Point( + t_DisplayLabelConf.RectVet[LabelCnt][j].BR.x * input.cols, + t_DisplayLabelConf.RectVet[LabelCnt][j].BR.y * input.rows + ) + ); + + cv::Rect tempRect = (LocalRect & CheckRect); + if (LocalRect == tempRect) + { + find = true; + } + } + if (!find) + { + return true; + } + } + } + return false; } void getFiles(std::string path, std::vector& files) { - //鏂囦欢鍙ユ焺 - intptr_t hFile = 0; - //鏂囦欢淇℃伅 - struct _finddata_t fileinfo; - std::string p; - if ((hFile = _findfirst(p.assign(path).c_str(), &fileinfo)) != -1) - { - do - { - if (!(fileinfo.attrib & _A_SUBDIR)) - { - files.push_back(fileinfo.name); - } - } while (_findnext(hFile, &fileinfo) == 0); - _findclose(hFile); - } + //鏂囦欢鍙ユ焺 + intptr_t hFile = 0; + //鏂囦欢淇℃伅 + struct _finddata_t fileinfo; + std::string p; + if ((hFile = _findfirst(p.assign(path).c_str(), &fileinfo)) != -1) + { + do + { + if (!(fileinfo.attrib & _A_SUBDIR)) + { + files.push_back(fileinfo.name); + } + } while (_findnext(hFile, &fileinfo) == 0); + _findclose(hFile); + } } std::string WstringToString(std::wstring wstr) { - int nLen = wcslen(wstr.c_str()); - std::string str; - str.resize(nLen * 2, ' '); - int nResult = WideCharToMultiByte(CP_ACP, 0, (LPCWSTR)wstr.c_str(), -1, (LPSTR)str.c_str(), nLen * 2, NULL, NULL); - return str; + int nLen = wcslen(wstr.c_str()); + std::string str; + str.resize(nLen * 2, ' '); + int nResult = WideCharToMultiByte(CP_ACP, 0, (LPCWSTR)wstr.c_str(), -1, (LPSTR)str.c_str(), nLen * 2, NULL, NULL); + return str; } /* @@ -171,255 +171,255 @@ char* LPWSTR2LPSTR(LPWSTR lpwszStrIn) //浠巗tring s鐨勪綅缃畃os寮濮嬶紝鍚戝悗鎵撅紝鎵惧埌绗竴涓瓑浜巟鐨勪綅缃繑鍥炲叾浣嶇疆 //鎵惧埌锛岃繑鍥炴壘鍒扮殑浣嶇疆锛屾壘涓嶅埌杩斿洖-1 int __find(const std::string s, const int start, const char x) { - if (start >= s.length())return -1; - for (int i = start; i < s.length(); ++i) { - if (s[i] == x) return i; - } - return -1; + if (start >= s.length())return -1; + for (int i = start; i < s.length(); ++i) { + if (s[i] == x) return i; + } + return -1; } //鍙屾枩鏉犺浆鍗曟枩鏉 void pathConvert_Double2Single(std::string& s) { - int start = 0; - while (start < s.length()) { - int pos = s.find('\\', start); - if (pos == -1)break; - s.replace(pos, 1,"/"); - start = pos + 1; - } + int start = 0; + while (start < s.length()) { + int pos = s.find('\\', start); + if (pos == -1)break; + s.replace(pos, 1, "/"); + start = pos + 1; + } } int CALLBACK BrowseCallbackProc( - HWND hwnd, UINT uMsg, LPARAM /*lParam*/, LPARAM lpData) + HWND hwnd, UINT uMsg, LPARAM /*lParam*/, LPARAM lpData) { - LPWSTR buf[1000]; - GetCurrentDirectory(1000, (LPWSTR)buf); - if (uMsg == BFFM_INITIALIZED) - { - SendMessage(hwnd, BFFM_SETSELECTION, (WPARAM)TRUE, (LPARAM)buf); - } - - return 0; + LPWSTR buf[1000]; + GetCurrentDirectory(1000, (LPWSTR)buf); + if (uMsg == BFFM_INITIALIZED) + { + SendMessage(hwnd, BFFM_SETSELECTION, (WPARAM)TRUE, (LPARAM)buf); + } + + return 0; } std::string SelectDirBRI() { - BROWSEINFO bi; - bi.hwndOwner = NULL; - bi.pidlRoot = CSIDL_DESKTOP; - bi.pszDisplayName = NULL; - bi.lpszTitle = NULL;//鏄?浣嶄簬瀵硅瘽妗嗗乏涓婇儴鐨勬彁?淇℃伅 - bi.ulFlags = BIF_DONTGOBELOWDOMAIN | BIF_RETURNONLYFSDIRS | BIF_NEWDIALOGSTYLE;//鏈夋柊寤?浠跺す鎸夐挳 - bi.lpfn = BrowseCallbackProc; - bi.iImage = 0; - LPITEMIDLIST pidl = SHBrowseForFolder(&bi);//璋?閫夋嫨瀵硅瘽妗 - if (pidl == NULL) - { - std::cout << "娌℃湁閫夋嫨鐩綍" << std::endl; - return ""; - } - TCHAR strFolder[MAX_PATH]; - SHGetPathFromIDList(pidl, strFolder); - std::string sFolder = ""; - sFolder = WstringToString(strFolder); - int pos = sFolder.find('\0'); - if (pos) - { - sFolder = sFolder.substr(0, pos); - } - return sFolder; + BROWSEINFO bi; + bi.hwndOwner = NULL; + bi.pidlRoot = CSIDL_DESKTOP; + bi.pszDisplayName = NULL; + bi.lpszTitle = NULL;//鏄?浣嶄簬瀵硅瘽妗嗗乏涓婇儴鐨勬彁?淇℃伅 + bi.ulFlags = BIF_DONTGOBELOWDOMAIN | BIF_RETURNONLYFSDIRS | BIF_NEWDIALOGSTYLE;//鏈夋柊寤?浠跺す鎸夐挳 + bi.lpfn = BrowseCallbackProc; + bi.iImage = 0; + LPITEMIDLIST pidl = SHBrowseForFolder(&bi);//璋?閫夋嫨瀵硅瘽妗 + if (pidl == NULL) + { + std::cout << "娌℃湁閫夋嫨鐩綍" << std::endl; + return ""; + } + TCHAR strFolder[MAX_PATH]; + SHGetPathFromIDList(pidl, strFolder); + std::string sFolder = ""; + sFolder = WstringToString(strFolder); + int pos = sFolder.find('\0'); + if (pos) + { + sFolder = sFolder.substr(0, pos); + } + return sFolder; } std::string SelectFileOFN() { - OPENFILENAME ofn;//#include - TCHAR szOpenFileNames[80 * MAX_PATH] = { 0 }; - TCHAR szPath[MAX_PATH]; - TCHAR szFileName[80 * MAX_PATH]; - - int nLen = 0; - TCHAR* p = NULL; - ZeroMemory(&ofn, sizeof(ofn)); - - // 缁撴瀯浣撳ぇ灏 - ofn.lStructSize = sizeof(ofn); - // 鎷ユ湁鐫绐楀彛鍙ユ焺 - ofn.hwndOwner = NULL; - // 鎺ユ敹杩斿洖鐨勬枃浠跺悕锛屾敞鎰忕涓涓瓧绗﹂渶瑕佷负NULL - ofn.lpstrFile = szOpenFileNames; - // 缂撳啿鍖洪暱搴 - ofn.nMaxFile = sizeof(szOpenFileNames); - // _T鍙浛鎹负TEXT锛屼娇鐢╛T闇瑕佸紩tchar.h - ofn.lpstrFile[0] = _T('\0'); - // 璁剧疆杩囨护 - ofn.lpstrFilter = _T("All\0*.*\0.mp4\0*.mp4\0.avi\0*.avi\0.mkv\0*.mkv\0.rmvb\0*.rmvb\0.f4v\0*.f4v\0.flv\0*.flv\0.m4v\0*.m4v\0.mpg\0*.mpg\0\0"); - // 杩囨护鍣ㄧ储寮 - ofn.nFilterIndex = 1; - // 绐楀彛鏍囬 - ofn.lpstrTitle = _T("璇烽夋嫨鍥剧墖"); - - // 鏂囦欢蹇呴』瀛樺湪銆佸厑璁稿閫夈侀殣钘忓彧璇婚夐」銆佸璇濇浣跨敤璧勬簮绠$悊鍣ㄩ鏍肩殑鐢ㄦ埛鐣岄潰 - // 瀹樻柟鏂囨。锛歨ttps://docs.microsoft.com/en-us/windows/win32/api/commdlg/ns-commdlg-openfilenamea - ofn.Flags = OFN_FILEMUSTEXIST | OFN_ALLOWMULTISELECT | OFN_HIDEREADONLY | OFN_EXPLORER; - - // 濡傛灉鎵撳紑鏂囦欢澶辫触锛屽垯涓嶆搷浣 - if (!::GetOpenFileName(&ofn)) { - return ""; - } - - // 鎶婄涓涓枃浠跺悕鍓嶇殑澶嶅埗鍒皊zPath,鍗: - // 濡傛灉鍙変簡涓涓枃浠,灏卞鍒跺埌鏈鍚庝竴涓'/' - // 濡傛灉閫変簡澶氫釜鏂囦欢,灏卞鍒跺埌绗竴涓狽ULL瀛楃 - lstrcpyn(szPath, szOpenFileNames, ofn.nFileOffset); - - // 褰撳彧閫変簡涓涓枃浠舵椂,涓嬮潰杩欎釜NULL瀛楃鏄繀闇鐨. - // 杩欓噷涓嶅尯鍒寰呴変簡涓涓拰澶氫釜鏂囦欢鐨勬儏鍐 - szPath[ofn.nFileOffset] = '\0'; - nLen = lstrlen(szPath); - - // 濡傛灉閫変簡澶氫釜鏂囦欢,鍒欏繀椤诲姞涓'//' - if (szPath[nLen - 1] != '\\') { - lstrcat(szPath, _T("\\")); - } - - // 鎶婃寚閽堢Щ鍒扮涓涓枃浠 - p = szOpenFileNames + ofn.nFileOffset; - - // 瀵箂zFileName杩涜娓呴浂 - ZeroMemory(szFileName, sizeof(szFileName)); - - // 瀹氫箟瀛楃涓诧紝鐢ㄤ簬鎷兼帴鎵閫夌殑鎵鏈夋枃浠剁殑瀹屾暣璺緞 - std::string str = ""; - - while (*p) { - // 璇诲彇鏂囦欢鍚 - std::string fileName = LPWSTR2LPSTR(p); - // 璇诲彇鏂囦欢鎵鍦ㄦ枃浠跺す璺緞 - std::string filePath = LPWSTR2LPSTR(szPath); - // 鎷兼帴鏂囦欢瀹屾暣璺緞 - std::string completePath = filePath + fileName; - // 鎷兼帴瀛楃涓 - str += completePath; - //绉昏嚦涓嬩竴涓枃浠 - p += lstrlen(p) + 1; - } - - return str; - // 灏唖tring杞负char* - //char* strc = new char[strlen(str.c_str()) + 1]; - //const char* cc = str.c_str(); - //strcpy_s(strc, str.size() + 1, cc); + OPENFILENAME ofn;//#include + TCHAR szOpenFileNames[80 * MAX_PATH] = { 0 }; + TCHAR szPath[MAX_PATH]; + TCHAR szFileName[80 * MAX_PATH]; + + int nLen = 0; + TCHAR* p = NULL; + ZeroMemory(&ofn, sizeof(ofn)); + + // 缁撴瀯浣撳ぇ灏 + ofn.lStructSize = sizeof(ofn); + // 鎷ユ湁鐫绐楀彛鍙ユ焺 + ofn.hwndOwner = NULL; + // 鎺ユ敹杩斿洖鐨勬枃浠跺悕锛屾敞鎰忕涓涓瓧绗﹂渶瑕佷负NULL + ofn.lpstrFile = szOpenFileNames; + // 缂撳啿鍖洪暱搴 + ofn.nMaxFile = sizeof(szOpenFileNames); + // _T鍙浛鎹负TEXT锛屼娇鐢╛T闇瑕佸紩tchar.h + ofn.lpstrFile[0] = _T('\0'); + // 璁剧疆杩囨护 + ofn.lpstrFilter = _T("All\0*.*\0.mp4\0*.mp4\0.avi\0*.avi\0.mkv\0*.mkv\0.rmvb\0*.rmvb\0.f4v\0*.f4v\0.flv\0*.flv\0.m4v\0*.m4v\0.mpg\0*.mpg\0\0"); + // 杩囨护鍣ㄧ储寮 + ofn.nFilterIndex = 1; + // 绐楀彛鏍囬 + ofn.lpstrTitle = _T("璇烽夋嫨鍥剧墖"); + + // 鏂囦欢蹇呴』瀛樺湪銆佸厑璁稿閫夈侀殣钘忓彧璇婚夐」銆佸璇濇浣跨敤璧勬簮绠$悊鍣ㄩ鏍肩殑鐢ㄦ埛鐣岄潰 + // 瀹樻柟鏂囨。锛歨ttps://docs.microsoft.com/en-us/windows/win32/api/commdlg/ns-commdlg-openfilenamea + ofn.Flags = OFN_FILEMUSTEXIST | OFN_ALLOWMULTISELECT | OFN_HIDEREADONLY | OFN_EXPLORER; + + // 濡傛灉鎵撳紑鏂囦欢澶辫触锛屽垯涓嶆搷浣 + if (!::GetOpenFileName(&ofn)) { + return ""; + } + + // 鎶婄涓涓枃浠跺悕鍓嶇殑澶嶅埗鍒皊zPath,鍗: + // 濡傛灉鍙変簡涓涓枃浠,灏卞鍒跺埌鏈鍚庝竴涓'/' + // 濡傛灉閫変簡澶氫釜鏂囦欢,灏卞鍒跺埌绗竴涓狽ULL瀛楃 + lstrcpyn(szPath, szOpenFileNames, ofn.nFileOffset); + + // 褰撳彧閫変簡涓涓枃浠舵椂,涓嬮潰杩欎釜NULL瀛楃鏄繀闇鐨. + // 杩欓噷涓嶅尯鍒寰呴変簡涓涓拰澶氫釜鏂囦欢鐨勬儏鍐 + szPath[ofn.nFileOffset] = '\0'; + nLen = lstrlen(szPath); + + // 濡傛灉閫変簡澶氫釜鏂囦欢,鍒欏繀椤诲姞涓'//' + if (szPath[nLen - 1] != '\\') { + lstrcat(szPath, _T("\\")); + } + + // 鎶婃寚閽堢Щ鍒扮涓涓枃浠 + p = szOpenFileNames + ofn.nFileOffset; + + // 瀵箂zFileName杩涜娓呴浂 + ZeroMemory(szFileName, sizeof(szFileName)); + + // 瀹氫箟瀛楃涓诧紝鐢ㄤ簬鎷兼帴鎵閫夌殑鎵鏈夋枃浠剁殑瀹屾暣璺緞 + std::string str = ""; + + while (*p) { + // 璇诲彇鏂囦欢鍚 + std::string fileName = LPWSTR2LPSTR(p); + // 璇诲彇鏂囦欢鎵鍦ㄦ枃浠跺す璺緞 + std::string filePath = LPWSTR2LPSTR(szPath); + // 鎷兼帴鏂囦欢瀹屾暣璺緞 + std::string completePath = filePath + fileName; + // 鎷兼帴瀛楃涓 + str += completePath; + //绉昏嚦涓嬩竴涓枃浠 + p += lstrlen(p) + 1; + } + + return str; + // 灏唖tring杞负char* + //char* strc = new char[strlen(str.c_str()) + 1]; + //const char* cc = str.c_str(); + //strcpy_s(strc, str.size() + 1, cc); } //https://learn.microsoft.com/en-us/windows/win32/shell/common-file-dialog?redirectedfrom=MSDN std::string SelectDirIFD() { - std::string folderpath = ""; - // CoCreate the File Open Dialog object. - IFileDialog* pfd = NULL; - HRESULT hr = CoCreateInstance(CLSID_FileOpenDialog, - NULL, - CLSCTX_INPROC_SERVER, - IID_PPV_ARGS(&pfd)); - if (SUCCEEDED(hr)) - { - // Set the options on the dialog. - DWORD dwFlags; - - // Before setting, always get the options first in order - // not to override existing options. - hr = pfd->GetOptions(&dwFlags); - if (SUCCEEDED(hr)) - { - // In this case, get shell items only for file system items. - hr = pfd->SetOptions(dwFlags | FOS_PICKFOLDERS); - if (SUCCEEDED(hr)) - { - // Show the dialog - hr = pfd->Show(NULL); - if (SUCCEEDED(hr)) - { - // Obtain the result once the user clicks - // the 'Open' button. - // The result is an IShellItem object. - IShellItem* psiResult; - hr = pfd->GetResult(&psiResult); - if (SUCCEEDED(hr)) - { - // We are just going to print out the - // name of the file for sample sake. - PWSTR pszFilePath = NULL; - hr = psiResult->GetDisplayName(SIGDN_FILESYSPATH,&pszFilePath); - if (SUCCEEDED(hr)) - { - folderpath = LPWSTR2LPSTR(pszFilePath); - CoTaskMemFree(pszFilePath); - } - psiResult->Release(); - } - } - } - } - pfd->Release(); - } - return folderpath; + std::string folderpath = ""; + // CoCreate the File Open Dialog object. + IFileDialog* pfd = NULL; + HRESULT hr = CoCreateInstance(CLSID_FileOpenDialog, + NULL, + CLSCTX_INPROC_SERVER, + IID_PPV_ARGS(&pfd)); + if (SUCCEEDED(hr)) + { + // Set the options on the dialog. + DWORD dwFlags; + + // Before setting, always get the options first in order + // not to override existing options. + hr = pfd->GetOptions(&dwFlags); + if (SUCCEEDED(hr)) + { + // In this case, get shell items only for file system items. + hr = pfd->SetOptions(dwFlags | FOS_PICKFOLDERS); + if (SUCCEEDED(hr)) + { + // Show the dialog + hr = pfd->Show(NULL); + if (SUCCEEDED(hr)) + { + // Obtain the result once the user clicks + // the 'Open' button. + // The result is an IShellItem object. + IShellItem* psiResult; + hr = pfd->GetResult(&psiResult); + if (SUCCEEDED(hr)) + { + // We are just going to print out the + // name of the file for sample sake. + PWSTR pszFilePath = NULL; + hr = psiResult->GetDisplayName(SIGDN_FILESYSPATH, &pszFilePath); + if (SUCCEEDED(hr)) + { + folderpath = LPWSTR2LPSTR(pszFilePath); + CoTaskMemFree(pszFilePath); + } + psiResult->Release(); + } + } + } + } + pfd->Release(); + } + return folderpath; } std::string UTF8ToGBK(std::string utf8_str) { - // 鑾峰緱涓存椂鍙橀噺鐨勫ぇ灏 - int wchar_len = MultiByteToWideChar(CP_UTF8, 0, utf8_str.c_str(), -1, NULL, 0); - wchar_t *wchar_buf = new wchar_t[wchar_len]; - MultiByteToWideChar(CP_UTF8, 0, utf8_str.c_str(), -1, wchar_buf, wchar_len); - - // 鑾峰緱涓存椂鍙橀噺鐨勫ぇ灏 - int char_len = WideCharToMultiByte(CP_ACP, 0, wchar_buf, -1, NULL, 0, NULL, NULL); - char* char_buf = new char[char_len]; - WideCharToMultiByte(CP_ACP, 0, wchar_buf, -1, char_buf, char_len, NULL, NULL); - - std::string gbk_str(char_buf); - delete[] wchar_buf; - delete[] char_buf; - - return gbk_str; + // 鑾峰緱涓存椂鍙橀噺鐨勫ぇ灏 + int wchar_len = MultiByteToWideChar(CP_UTF8, 0, utf8_str.c_str(), -1, NULL, 0); + wchar_t* wchar_buf = new wchar_t[wchar_len]; + MultiByteToWideChar(CP_UTF8, 0, utf8_str.c_str(), -1, wchar_buf, wchar_len); + + // 鑾峰緱涓存椂鍙橀噺鐨勫ぇ灏 + int char_len = WideCharToMultiByte(CP_ACP, 0, wchar_buf, -1, NULL, 0, NULL, NULL); + char* char_buf = new char[char_len]; + WideCharToMultiByte(CP_ACP, 0, wchar_buf, -1, char_buf, char_len, NULL, NULL); + + std::string gbk_str(char_buf); + delete[] wchar_buf; + delete[] char_buf; + + return gbk_str; } void stdString2QString(std::string str, QString& qs) { - qs = QString::fromLocal8Bit(QByteArray::fromRawData(str.c_str(), str.size())); + qs = QString::fromLocal8Bit(QByteArray::fromRawData(str.c_str(), str.size())); } void QString2stdString(QString qs, std::string& str) { - str = qs.toLocal8Bit().constData(); + str = qs.toLocal8Bit().constData(); } std::string WString2String(const std::wstring& ws) { - // 杩涜鍦板煙璁剧疆锛"" 琛ㄧず褰撳墠OS榛樿鐨勫湴鍩熻缃紝鎴愬姛鍒欒繑鍥炲綋鍓嶅湴鍩熻缃殑鍚嶇О - std::string strLocate = setlocale(LC_ALL, ""); - const wchar_t* wchSrc = ws.c_str(); - size_t nDestSize = wcstombs(NULL, wchSrc, 0) + 1; - char* chDest = new char[nDestSize]; - memset(chDest, 0, nDestSize); - wcstombs(chDest, wchSrc, nDestSize); - std::string strResult = chDest; - delete[] chDest; - setlocale(LC_ALL, strLocate.c_str()); - return strResult; + // 杩涜鍦板煙璁剧疆锛"" 琛ㄧず褰撳墠OS榛樿鐨勫湴鍩熻缃紝鎴愬姛鍒欒繑鍥炲綋鍓嶅湴鍩熻缃殑鍚嶇О + std::string strLocate = setlocale(LC_ALL, ""); + const wchar_t* wchSrc = ws.c_str(); + size_t nDestSize = wcstombs(NULL, wchSrc, 0) + 1; + char* chDest = new char[nDestSize]; + memset(chDest, 0, nDestSize); + wcstombs(chDest, wchSrc, nDestSize); + std::string strResult = chDest; + delete[] chDest; + setlocale(LC_ALL, strLocate.c_str()); + return strResult; } std::wstring String2WString(const std::string& str) { - std::wstring wContext = L""; - int len = MultiByteToWideChar(CP_ACP, 0, str.c_str(), str.size(), NULL, 0); - WCHAR* buffer = new WCHAR[len + 1]; - MultiByteToWideChar(CP_ACP, 0, str.c_str(), str.size(), buffer, len); - buffer[len] = '\0'; - wContext.append(buffer); - delete[] buffer; - return wContext; + std::wstring wContext = L""; + int len = MultiByteToWideChar(CP_ACP, 0, str.c_str(), str.size(), NULL, 0); + WCHAR* buffer = new WCHAR[len + 1]; + MultiByteToWideChar(CP_ACP, 0, str.c_str(), str.size(), buffer, len); + buffer[len] = '\0'; + wContext.append(buffer); + delete[] buffer; + return wContext; } std::vector SpiteStringCharacter(std::string context) { - std::vector res; - std::wstring wContext = String2WString(context); - for (int i = 0; i < wContext.length(); i++) { - std::wstring tmp = wContext.substr(i, 1); - res.push_back(WString2String(tmp)); - } - return res; -} \ No newline at end of file + std::vector res; + std::wstring wContext = String2WString(context); + for (int i = 0; i < wContext.length(); i++) { + std::wstring tmp = wContext.substr(i, 1); + res.push_back(WString2String(tmp)); + } + return res; +} diff --git a/Cigarette/common.h b/Cigarette/common.h index f1d5e0e1..c95e8acd 100644 --- a/Cigarette/common.h +++ b/Cigarette/common.h @@ -5,24 +5,24 @@ #include "basecamera.h" #include "QtCore\qdatetime.h" -//#define __DEBUG //debug信息输出功能 -//#define __UDPSend //网络发送功能 -#define __TCPSend // TCP发送 -#define USB_BASLER_NEW_FW //使用basler定制固件 -//#define IMM_PROCESS //拍照后立马处理,不等校验信号 -//#define IMM_FEED_BACK //处理完后立马反馈,不等校验信号 -#define ONE_TIME_SHIFT //错开一拍发送反馈(默认错开两次) -#define AI_WARM_UP //AI识别开始前的热身动作 -//#define LICENSE_VERIFY //开启license文件校验 -//CAP_FEED_BACK和DOUBLE_FEED_BACK不要一起开 +//#define __DEBUG //debug淇℃伅杈撳嚭鍔熻兘 +//#define __UDPSend //缃戠粶鍙戦佸姛鑳 +#define __TCPSend // TCP鍙戦 +#define USB_BASLER_NEW_FW //浣跨敤basler瀹氬埗鍥轰欢 +//#define IMM_PROCESS //鎷嶇収鍚庣珛椹鐞嗭紝涓嶇瓑鏍¢獙淇″彿 +//#define IMM_FEED_BACK //澶勭悊瀹屽悗绔嬮┈鍙嶉锛屼笉绛夋牎楠屼俊鍙 +#define ONE_TIME_SHIFT //閿欏紑涓鎷嶅彂閫佸弽棣(榛樿閿欏紑涓ゆ) +#define AI_WARM_UP //AI璇嗗埆寮濮嬪墠鐨勭儹韬姩浣 +//#define LICENSE_VERIFY //寮鍚痩icense鏂囦欢鏍¢獙 +//CAP_FEED_BACK鍜孌OUBLE_FEED_BACK涓嶈涓璧峰紑 #if defined (ONE_TIME_SHIFT) - //#define CAP_FEED_BACK //拍照时也检测有没有测试结果,有的话就反馈 - //#define DOUBLE_FEED_BACK //一次ng,两次反馈ng信号 + //#define CAP_FEED_BACK //鎷嶇収鏃朵篃妫娴嬫湁娌℃湁娴嬭瘯缁撴灉锛屾湁鐨勮瘽灏卞弽棣 + //#define DOUBLE_FEED_BACK //涓娆g锛屼袱娆″弽棣坣g淇″彿 #endif -//#define identify_Hik_YSXID//识别海康相机YSXID -//#define __ExportData // 输出检测数据到XML文档 -#define DRAW_RECT // 鼠标画框功能 -#define SYNC_CAMERA //相机同步处理图片 +//#define identify_Hik_YSXID//璇嗗埆娴峰悍鐩告満YSXID +//#define __ExportData // 杈撳嚭妫娴嬫暟鎹埌XML鏂囨。 +#define DRAW_RECT // 榧犳爣鐢绘鍔熻兘 +#define SYNC_CAMERA //鐩告満鍚屾澶勭悊鍥剧墖 #define Queue_Size 15 #define Unit_Queue_Size Queue_Size*3 @@ -34,24 +34,24 @@ #define DEBUG(format, ...) #endif -// 主界面基本参数配置文件 +// 涓荤晫闈㈠熀鏈弬鏁伴厤缃枃浠 #define CONFPATH "D:/conf/conf_path.txt" //#define CONFIGURE_FILE "D:/conf/conf.txt" -// 相机旋转角度配置文件 +// 鐩告満鏃嬭浆瑙掑害閰嶇疆鏂囦欢 #define ROTATE_FILE "rotate.txt" #define MODBUS_CONFIGURE_FILE "modbus.txt" #define PLC_CONFIG_FILE "plc.txt" #define SELECT_RECTS_FILE "SelectRects%d%d.txt" #define STATISTIC_FILE "camera%1_statistic.txt" #define ALARM_RECORD_FILE "alarm.txt" -#define OUTPUT_HIGH_WIDTH 20000 //输出信号的脉冲宽度,微秒 +#define OUTPUT_HIGH_WIDTH 20000 //杈撳嚭淇″彿鐨勮剦鍐插搴︼紝寰 -#define OP_TIME 300 //OP权限时长(默认300秒) -#define ADMIN_TIME 600 //ADMIN权限时长(默认300秒) -#define STOP_SECONDS 3 //检查多少次不变触发自动换班 +#define OP_TIME 300 //OP鏉冮檺鏃堕暱锛堥粯璁300绉掞級 +#define ADMIN_TIME 600 //ADMIN鏉冮檺鏃堕暱锛堥粯璁300绉掞級 +#define STOP_SECONDS 3 //妫鏌ュ灏戞涓嶅彉瑙﹀彂鑷姩鎹㈢彮 -int string_split(std::string str, std::string pattern,std::vector &out); -std::string format(const char *pszFmt, ...); +int string_split(std::string str, std::string pattern, std::vector& out); +std::string format(const char* pszFmt, ...); void getFiles(std::string path, std::vector& files); std::string SelectDirBRI(); std::string SelectFileOFN(); @@ -63,156 +63,156 @@ std::vector SpiteStringCharacter(std::string context); class ConfPath { public: - QString config_path; // 配置文件路径 - //QString config_name; // 配置文件名 - QString save_pics_path; // 保存图片存储路径 - - ConfPath(){ - config_path = ""; - //config_name = ""; - save_pics_path = ""; - } + QString config_path; // 閰嶇疆鏂囦欢璺緞 + //QString config_name; // 閰嶇疆鏂囦欢鍚 + QString save_pics_path; // 淇濆瓨鍥剧墖瀛樺偍璺緞 + + ConfPath() { + config_path = ""; + //config_name = ""; + save_pics_path = ""; + } }; class SysConf { public: - std::mutex lock; - int save; //图片是否保存,0不保存,1保存NG, 2全部保存 - int MisMatchAct; //错位行为,1:NG,0:ok - int save_days; ///照片保存天数 - int freesize; /// 设定清理图片最小空间 - std::string ComPort; ///COM口 - int ConfThreshold; //识别率 - int auto_open; //是否自动打开相机,0否,1是 - int auto_work; //是否自动开始工作,0否,1是 - int auto_shift; //是否自动换班,0否,1是 - int shift_byhand; // 是否手动换班,0否,1是 - QTime shiftA; //A换班时间 - QTime shiftB; //B换班时间 - QTime shiftC; //C换班时间 - QString location; // 所在地 - QString model_path; // 模型文件夹路径 - QString model_name; // 模型名 - QString model_jpg_path; // 模型图片路径 - int timing_shift; //是否定时换班,0否,1是 - int expo[NumberOfSupportedCameras]; //相机曝光时间,单位微秒 - int gain[NumberOfSupportedCameras]; //相机模拟增益,范围0~64 - int filter[NumberOfSupportedCameras];//相机滤波时间 - int UserID[NumberOfSupportedCameras]; - int no[NumberOfSupportedCameras][3];//拍摄图片最少合格胶点数 - int shoot[NumberOfSupportedCameras];//拍摄次数 - std::string MonitorIP; //远程监控端的IP - int MonitorPort; - int FeedbackPort; - int FilePort; - //MonitorPort为数据端口 - //MonitorPort+NumberOfSupportedCameras为图像端口 - //MonitorPort+NumberOfSupportedCameras*2为发送命令端口,也就是FeedbackPort - //MonitorPort+NumberOfSupportedCameras*2+1为接受命令端口 - - SysConf() - { - save=0; //图片是否保存,0不保存,1保存NG, 2全部保存 - MisMatchAct=1; //错位行为,1:NG,0:ok - save_days = 1; ///照片保存天数 - freesize = 10; /// 设定清理图片最小空间 - ComPort = "COM1"; ///COM口 - ConfThreshold = 1; ///百分比识别率 - auto_open=1; //是否自动打开相机,0否,1是 - auto_work=1; //是否自动开始工作,0否,1是 - auto_shift=0; //是否自动换班,0否,1是 - shift_byhand = 1; //是否手动换班,0否,1是 - timing_shift = 0; //是否定时换班,0否,1是 - location = ""; - model_path = ""; - model_name = ""; - model_jpg_path = ""; - shiftA.setHMS(0, 0, 0); - shiftB.setHMS(0, 0, 0); - shiftC.setHMS(0, 0, 0); - for(int i=0;i> image_sync_arr = std::vector>(NumberOfSupportedCameras); - uint8_t collect_cnt; - - ImageSyncArr() - { - collect_cnt = 0; - } + std::mutex lock; + std::vector> image_sync_arr = std::vector>(NumberOfSupportedCameras); + uint8_t collect_cnt; + + ImageSyncArr() + { + collect_cnt = 0; + } }; #endif -//Modbus地址设置 +//Modbus鍦板潃璁剧疆 class ModbusConf { public: - int kick[NumberOfSupportedCameras]; - int quantity; //当班产量地址 - int shift; //换班地址 - int work; //开始/停止 - int no_kick; //只拍照不剔除模式 - int debug; //调试模式,PLC产生模拟的line4信号 - int reset; //复位 - int alarm; //报警 - - ModbusConf() - { - for (int i = 0; i < NumberOfSupportedCameras; i++) { + int kick[NumberOfSupportedCameras]; + int quantity; //褰撶彮浜ч噺鍦板潃 + int shift; //鎹㈢彮鍦板潃 + int work; //寮濮/鍋滄 + int no_kick; //鍙媿鐓т笉鍓旈櫎妯″紡 + int debug; //璋冭瘯妯″紡锛孭LC浜х敓妯℃嫙鐨刲ine4淇″彿 + int reset; //澶嶄綅 + int alarm; //鎶ヨ + + ModbusConf() + { + for (int i = 0; i < NumberOfSupportedCameras; i++) { #if defined(NumberOfSupportedCameras) && (NumberOfSupportedCameras > i) - kick[i] = 0; + kick[i] = 0; #endif - } - quantity=0; //当班产量地址 - shift=0; //换班地址 - work=0; //开始/停止 - no_kick=0; //只拍照不剔除模式 - debug=0; //调试模式,PLC产生模拟的line4信号 - reset=0; //复位 - alarm=0; //报警 - } + } + quantity = 0; //褰撶彮浜ч噺鍦板潃 + shift = 0; //鎹㈢彮鍦板潃 + work = 0; //寮濮/鍋滄 + no_kick = 0; //鍙媿鐓т笉鍓旈櫎妯″紡 + debug = 0; //璋冭瘯妯″紡锛孭LC浜х敓妯℃嫙鐨刲ine4淇″彿 + reset = 0; //澶嶄綅 + alarm = 0; //鎶ヨ + } }; -#define DisplayLabel_Type_Bit 0x01 //1:打开范围识别功能,0:关闭范围识别功能 -#define DisplayLabel_Conf_Bit 0x02 //1:可以绘制矩形框,0:不能绘制矩形框 +#define DisplayLabel_Type_Bit 0x01 //1:鎵撳紑鑼冨洿璇嗗埆鍔熻兘锛0:鍏抽棴鑼冨洿璇嗗埆鍔熻兘 +#define DisplayLabel_Conf_Bit 0x02 //1:鍙互缁樺埗鐭╁舰妗嗭紝0:涓嶈兘缁樺埗鐭╁舰妗 class RectRatio { public: - RectRatio(cv::Point2f tl, cv::Point2f br) :TL(tl), BR(br) {}; - cv::Point2f TL; - cv::Point2f BR; + RectRatio(cv::Point2f tl, cv::Point2f br) :TL(tl), BR(br) {}; + cv::Point2f TL; + cv::Point2f BR; }; class DisplayLabelConf { public: - std::mutex lock; - bool leftButtonDownFlag = false; //左键单击后视频暂停播放的标志位 - cv::Point2f originalPoint; //矩形框起点 - cv::Point2f processPoint; //矩形框终点 - - cv::Mat g_last_mat[2]; - bool g_max[2] = {false}; //视图是否最大化 - uint8_t Flag[2] = {0}; - std::vector RectVet[2]; + std::mutex lock; + bool leftButtonDownFlag = false; //宸﹂敭鍗曞嚮鍚庤棰戞殏鍋滄挱鏀剧殑鏍囧織浣 + cv::Point2f originalPoint; //鐭╁舰妗嗚捣鐐 + cv::Point2f processPoint; //鐭╁舰妗嗙粓鐐 + + cv::Mat g_last_mat[2]; + bool g_max[2] = { false }; //瑙嗗浘鏄惁鏈澶у寲 + uint8_t Flag[2] = { 0 }; + std::vector RectVet[2]; }; void DrawSelectRects(cv::Mat input, DisplayLabelConf& t_DisplayLabelConf, int Cnt); bool CheckSelectRects(cv::Mat input, std::vector > >& VecRects, int VecCnt, DisplayLabelConf& t_DisplayLabelConf, int LabelCnt); diff --git a/Cigarette/db_label.cpp b/Cigarette/db_label.cpp index d6eaad25..86832718 100644 --- a/Cigarette/db_label.cpp +++ b/Cigarette/db_label.cpp @@ -1,12 +1,12 @@ //qlabel_doubleclick.cpp #include "db_label.h" #include -db_label::db_label(QWidget *parent) : QLabel(parent){ +db_label::db_label(QWidget* parent) : QLabel(parent) { setFocusPolicy(Qt::StrongFocus); connect(&timer, SIGNAL(timeout()), this, SLOT(TimeOutNotify())); } -db_label::~db_label(){} +db_label::~db_label() {} void db_label::mouseDoubleClickEvent(QMouseEvent* event) { emit SignalmouseDoubleClickEvent(event); @@ -34,11 +34,11 @@ void db_label::keyReleaseEvent(QKeyEvent* event) void db_label::TimeOutNotify(void) { timer.stop(); - switch(cnt) { - case 1:emit QlabelClick(); break; - case 2:emit QlabelDoubleClick(); break; - case 3:emit QlabelTripleClick(); break; - default:break; + switch (cnt) { + case 1:emit QlabelClick(); break; + case 2:emit QlabelDoubleClick(); break; + case 3:emit QlabelTripleClick(); break; + default:break; } cnt = 0; } diff --git a/Cigarette/db_label.h b/Cigarette/db_label.h index db3d3486..1c7f5dad 100644 --- a/Cigarette/db_label.h +++ b/Cigarette/db_label.h @@ -12,10 +12,10 @@ class db_label : public QLabel Q_OBJECT public: - db_label(QWidget *parent = 0); + db_label(QWidget* parent = 0); ~db_label(); - void mouseDoubleClickEvent(QMouseEvent *event); + void mouseDoubleClickEvent(QMouseEvent* event); void mousePressEvent(QMouseEvent* event); void mouseReleaseEvent(QMouseEvent* event); void mouseMoveEvent(QMouseEvent* event); @@ -35,4 +35,4 @@ private slots: void TimeOutNotify(); }; -#endif // QLABEL_DOUBLECLICK_H_ \ No newline at end of file +#endif // QLABEL_DOUBLECLICK_H_ diff --git a/Cigarette/debugthread.h b/Cigarette/debugthread.h index cdf31afc..08ea750e 100644 --- a/Cigarette/debugthread.h +++ b/Cigarette/debugthread.h @@ -11,85 +11,84 @@ #include "balluffcamera.h" #include "hikcamera.h" -extern SyncQueue *g_debug_queue[NumberOfSupportedCameras]; //鐩告満璋冭瘯妯″紡鍥惧儚闃熷垪 +extern SyncQueue* g_debug_queue[NumberOfSupportedCameras]; //鐩告満璋冭瘯妯″紡鍥惧儚闃熷垪 extern DisplayLabelConf g_display_label_conf[NumberOfSupportedCameras]; extern SingleCamInfoStruct SingleCamInfo[NumberOfSupportedCameras]; - extern int rotationAngle[NumberOfSupportedCameras]; //鍥剧墖鏃嬭浆瑙掑害 extern bool isNeedRotate[NumberOfSupportedCameras]; class DebugThread : public QThread { - Q_OBJECT + Q_OBJECT signals: - void notify(int Num,int Cnt,cv::Mat); + void notify(int Num, int Cnt, cv::Mat); public: - DebugThread(QObject *parent = 0): QThread(parent) - { + DebugThread(QObject* parent = 0) : QThread(parent) + { - } - ~DebugThread() - { - stop(); - p_debug_queue->put(cv::Mat()); - quit(); - wait(); - } - void init(SyncQueue *ptr,int Num) - { - local_camera_number = Num; - b_quit = false; - p_debug_queue = ptr; - } - void start_work() - { - start(HighestPriority); - } - void stop() - { - b_quit = true; - } + } + ~DebugThread() + { + stop(); + p_debug_queue->put(cv::Mat()); + quit(); + wait(); + } + void init(SyncQueue* ptr, int Num) + { + local_camera_number = Num; + b_quit = false; + p_debug_queue = ptr; + } + void start_work() + { + start(HighestPriority); + } + void stop() + { + b_quit = true; + } protected: void run() - { - while (!b_quit) { - cv::Mat image; - p_debug_queue->take(image); - if (image.data) + { + while (!b_quit) { + cv::Mat image; + p_debug_queue->take(image); + if (image.data) + { + //cv::cvtColor(image, image, CV_BGR2RGB); //鐏板害鍥惧儚杞负褰╄壊鍥惧儚 + // 瑙e喅杩涘叆璋冭瘯妯″紡娴峰悍褰╄壊鐩告満鍙樿壊锛屽叧闂壊褰╄皟鏁村反椴佸か鐩告満鍙橀粦鐨勯棶棰 + if (image.channels() == 1) { - //cv::cvtColor(image, image, CV_BGR2RGB); //鐏板害鍥惧儚杞负褰╄壊鍥惧儚 - // 瑙e喅杩涘叆璋冭瘯妯″紡娴峰悍褰╄壊鐩告満鍙樿壊锛屽叧闂壊褰╄皟鏁村反椴佸か鐩告満鍙橀粦鐨勯棶棰 - if (image.channels() == 1) + cv::cvtColor(image, image, CV_BGR2RGB); //鐏板害鍥惧儚杞负褰╄壊鍥惧儚 + } + if (isNeedRotate[local_camera_number]) { + if (rotationAngle[local_camera_number] != (cv::ROTATE_90_COUNTERCLOCKWISE + 1)) { - cv::cvtColor(image, image, CV_BGR2RGB); //鐏板害鍥惧儚杞负褰╄壊鍥惧儚 - } - if (isNeedRotate[local_camera_number]) { - if(rotationAngle[local_camera_number] != (cv::ROTATE_90_COUNTERCLOCKWISE + 1)) - { - cv::rotate(image, image, rotationAngle[local_camera_number]); - } + cv::rotate(image, image, rotationAngle[local_camera_number]); } - //sleep(100); - emit notify(local_camera_number,0,image); } + //sleep(100); + emit notify(local_camera_number, 0, image); + } #ifdef DRAW_RECT - std::lock_guard locker2(g_display_label_conf[local_camera_number].lock); - local_DisplayLabelConf.leftButtonDownFlag = g_display_label_conf[local_camera_number].leftButtonDownFlag; - local_DisplayLabelConf.Flag[0] = g_display_label_conf[local_camera_number].Flag[0]; - local_DisplayLabelConf.Flag[1] = g_display_label_conf[local_camera_number].Flag[1]; - local_DisplayLabelConf.originalPoint = g_display_label_conf[local_camera_number].originalPoint; - local_DisplayLabelConf.processPoint = g_display_label_conf[local_camera_number].processPoint; - local_DisplayLabelConf.RectVet[0] = g_display_label_conf[local_camera_number].RectVet[0]; - local_DisplayLabelConf.RectVet[1] = g_display_label_conf[local_camera_number].RectVet[1]; + std::lock_guard locker2(g_display_label_conf[local_camera_number].lock); + local_DisplayLabelConf.leftButtonDownFlag = g_display_label_conf[local_camera_number].leftButtonDownFlag; + local_DisplayLabelConf.Flag[0] = g_display_label_conf[local_camera_number].Flag[0]; + local_DisplayLabelConf.Flag[1] = g_display_label_conf[local_camera_number].Flag[1]; + local_DisplayLabelConf.originalPoint = g_display_label_conf[local_camera_number].originalPoint; + local_DisplayLabelConf.processPoint = g_display_label_conf[local_camera_number].processPoint; + local_DisplayLabelConf.RectVet[0] = g_display_label_conf[local_camera_number].RectVet[0]; + local_DisplayLabelConf.RectVet[1] = g_display_label_conf[local_camera_number].RectVet[1]; - DrawSelectRects(image, local_DisplayLabelConf, 0); + DrawSelectRects(image, local_DisplayLabelConf, 0); #endif - } } + } public: int local_camera_number; int local_classid; bool b_quit; - SyncQueue *p_debug_queue; + SyncQueue* p_debug_queue; DisplayLabelConf local_DisplayLabelConf; }; diff --git a/Cigarette/dialogin.cpp b/Cigarette/dialogin.cpp index da8adf40..23cdfbad 100644 --- a/Cigarette/dialogin.cpp +++ b/Cigarette/dialogin.cpp @@ -1,99 +1,96 @@ -锘#include "dialogin.hpp" - +#include "dialogin.hpp" #include - #include - #include extern bool g_op_mode; //鏄惁鎿嶄綔鍛樻ā寮 extern QString g_op_pswd; //鎿嶄綔鍛樺瘑鐮 -Dialogin::Dialogin(QWidget * parent) : QDialog(parent) { - ui.setupUi(this); - m_pswd = ""; - this->setWindowFlags(Qt::FramelessWindowHint); +Dialogin::Dialogin(QWidget* parent) : QDialog(parent) { + ui.setupUi(this); + m_pswd = ""; + this->setWindowFlags(Qt::FramelessWindowHint); } Dialogin::~Dialogin() { - + } void Dialogin::on_pushButton_close_released() { - this->close(); + this->close(); } void Dialogin::on_pushButton_clr_released() { - m_pswd = ""; - ui.lineEdit->setText(""); + m_pswd = ""; + ui.lineEdit->setText(""); } void Dialogin::on_pushButton_ok_released() { - QString md5Str = QCryptographicHash::hash(m_pswd.toLatin1(), QCryptographicHash::Md5).toHex(); - qDebug() << "m_pswd_op:" << m_pswd; - qDebug() << "m_pswd_op md5:" << md5Str; - qDebug() << "g_admin_pswd_op md5:" << g_op_pswd; - if (md5Str.compare(g_op_pswd, Qt::CaseInsensitive) == 0) - { - g_op_mode = true; - //QMessageBox::information(NULL, QStringLiteral("鎻愮ず娑堟伅"), QStringLiteral("楠岃瘉閫氳繃锛岃繘鍏ョ鐞嗗憳妯″紡"), QMessageBox::Ok); - emit enter_op(); - this->close(); - } - else { - QMessageBox::information(NULL, QStringLiteral("鎻愮ず娑堟伅"), QStringLiteral("瀵嗙爜閿欒锛岃閲嶆柊杈撳叆"), QMessageBox::Ok); - on_pushButton_clr_released(); - } + QString md5Str = QCryptographicHash::hash(m_pswd.toLatin1(), QCryptographicHash::Md5).toHex(); + qDebug() << "m_pswd_op:" << m_pswd; + qDebug() << "m_pswd_op md5:" << md5Str; + qDebug() << "g_admin_pswd_op md5:" << g_op_pswd; + if (md5Str.compare(g_op_pswd, Qt::CaseInsensitive) == 0) + { + g_op_mode = true; + //QMessageBox::information(NULL, QStringLiteral("鎻愮ず娑堟伅"), QStringLiteral("楠岃瘉閫氳繃锛岃繘鍏ョ鐞嗗憳妯″紡"), QMessageBox::Ok); + emit enter_op(); + this->close(); + } + else { + QMessageBox::information(NULL, QStringLiteral("鎻愮ず娑堟伅"), QStringLiteral("瀵嗙爜閿欒锛岃閲嶆柊杈撳叆"), QMessageBox::Ok); + on_pushButton_clr_released(); + } } void Dialogin::on_pushButton_0_released() { - m_pswd += "0"; - ui.lineEdit->setText(ui.lineEdit->text() + "*"); + m_pswd += "0"; + ui.lineEdit->setText(ui.lineEdit->text() + "*"); } void Dialogin::on_pushButton_1_released() { - m_pswd += "1"; - ui.lineEdit->setText(ui.lineEdit->text() + "*"); + m_pswd += "1"; + ui.lineEdit->setText(ui.lineEdit->text() + "*"); } void Dialogin::on_pushButton_2_released() { - m_pswd += "2"; - ui.lineEdit->setText(ui.lineEdit->text() + "*"); + m_pswd += "2"; + ui.lineEdit->setText(ui.lineEdit->text() + "*"); } void Dialogin::on_pushButton_3_released() { - m_pswd += "3"; - ui.lineEdit->setText(ui.lineEdit->text() + "*"); + m_pswd += "3"; + ui.lineEdit->setText(ui.lineEdit->text() + "*"); } void Dialogin::on_pushButton_4_released() { - m_pswd += "4"; - ui.lineEdit->setText(ui.lineEdit->text() + "*"); + m_pswd += "4"; + ui.lineEdit->setText(ui.lineEdit->text() + "*"); } void Dialogin::on_pushButton_5_released() { - m_pswd += "5"; - ui.lineEdit->setText(ui.lineEdit->text() + "*"); + m_pswd += "5"; + ui.lineEdit->setText(ui.lineEdit->text() + "*"); } void Dialogin::on_pushButton_6_released() { - m_pswd += "6"; - ui.lineEdit->setText(ui.lineEdit->text() + "*"); + m_pswd += "6"; + ui.lineEdit->setText(ui.lineEdit->text() + "*"); } void Dialogin::on_pushButton_7_released() { - m_pswd += "7"; - ui.lineEdit->setText(ui.lineEdit->text() + "*"); + m_pswd += "7"; + ui.lineEdit->setText(ui.lineEdit->text() + "*"); } void Dialogin::on_pushButton_8_released() { - m_pswd += "8"; - ui.lineEdit->setText(ui.lineEdit->text() + "*"); + m_pswd += "8"; + ui.lineEdit->setText(ui.lineEdit->text() + "*"); } void Dialogin::on_pushButton_9_released() { - m_pswd += "9"; - ui.lineEdit->setText(ui.lineEdit->text() + "*"); + m_pswd += "9"; + ui.lineEdit->setText(ui.lineEdit->text() + "*"); } diff --git a/Cigarette/dialogin.hpp b/Cigarette/dialogin.hpp index 53178988..ce75fd03 100644 --- a/Cigarette/dialogin.hpp +++ b/Cigarette/dialogin.hpp @@ -1,34 +1,34 @@ -锘#pragma once +#pragma once #include #include "ui_dialogin.h" class Dialogin : public QDialog { - Q_OBJECT -signals : - void enter_op(); + Q_OBJECT +signals: + void enter_op(); public: - Dialogin(QWidget * parent = Q_NULLPTR); - ~Dialogin(); + Dialogin(QWidget* parent = Q_NULLPTR); + ~Dialogin(); -private slots : - void on_pushButton_close_released(); - void on_pushButton_clr_released(); - void on_pushButton_ok_released(); - void on_pushButton_0_released(); - void on_pushButton_1_released(); - void on_pushButton_2_released(); - void on_pushButton_3_released(); - void on_pushButton_4_released(); - void on_pushButton_5_released(); - void on_pushButton_6_released(); - void on_pushButton_7_released(); - void on_pushButton_8_released(); - void on_pushButton_9_released(); +private slots: + void on_pushButton_close_released(); + void on_pushButton_clr_released(); + void on_pushButton_ok_released(); + void on_pushButton_0_released(); + void on_pushButton_1_released(); + void on_pushButton_2_released(); + void on_pushButton_3_released(); + void on_pushButton_4_released(); + void on_pushButton_5_released(); + void on_pushButton_6_released(); + void on_pushButton_7_released(); + void on_pushButton_8_released(); + void on_pushButton_9_released(); public: - QString m_pswd; + QString m_pswd; private: - Ui::Dialogin ui; + Ui::Dialogin ui; }; diff --git a/Cigarette/dialogsetup.cpp b/Cigarette/dialogsetup.cpp index 02f02530..bbad535d 100644 --- a/Cigarette/dialogsetup.cpp +++ b/Cigarette/dialogsetup.cpp @@ -23,746 +23,746 @@ extern QString g_op_pswd; //鎿嶄綔鍛樺瘑鐮 void task_osk() { - system("start /b C:\\Windows\\system32\\osk.exe"); -} - -DialogSetup::DialogSetup(QWidget * parent) : QDialog(parent) { - ui.setupUi(this); - InitPtrMat(); - this->setWindowFlags(Qt::FramelessWindowHint);//绐楀彛鍙Щ鍔 - - for(int i=0;isetValidator(new QIntValidator(0, 1000000, this)); - lineEdit_expo_mat[i]->setText(QString::number(g_sys_conf.expo[i])); - lineEdit_gain_mat[i]->setValidator(new QIntValidator(0, 64, this)); - lineEdit_gain_mat[i]->setText(QString::number(g_sys_conf.gain[i])); - lineEdit_filter_mat[i]->setValidator(new QIntValidator(0, 1000000, this)); - lineEdit_filter_mat[i]->setText(QString::number(g_sys_conf.filter[i])); - } - - if (g_sys_conf.auto_open == 1) - { - ui.checkBox_auto_open->setChecked(true); - } - else { - ui.checkBox_auto_open->setChecked(false); - } - if (g_sys_conf.auto_work == 1) - { - ui.checkBox_auto_work->setChecked(true); - } - else { - ui.checkBox_auto_work->setChecked(false); - } - - if (!g_conf_path.config_path.isEmpty()) { - // 濡傛灉閰嶇疆鏂囦欢瀛樺偍璺緞闈炵┖ - QDir* dirinfo = new QDir(g_conf_path.config_path); - if (!dirinfo->exists()) { - // 濡傛灉鏂囦欢澶逛俊鎭笉瀛樺湪 - delete dirinfo, dirinfo = nullptr; - g_conf_path.config_path = "D:/conf"; - } - dirinfo->setNameFilters(QStringList("conf.txt")); - QStringList fileList = dirinfo->entryList(QDir::Files); - fileList.removeOne("."); - fileList.removeOne(".."); - delete dirinfo, dirinfo = nullptr; - } - else { - // 濡傛灉璺緞绌 - g_conf_path.config_path = "D:/conf"; - } - ui.comboBox_config_path->addItem(g_conf_path.config_path); - // 鏇存崲閫夋嫨鏂囦欢 - connect(ui.comboBox_config_path, SIGNAL(currentIndexChanged(int)), this, SLOT(onComboBoxConfSelect(int))); - - if (!g_sys_conf.model_path.isEmpty()) { - // 濡傛灉鏇剧粡閫夋嫨杩囨ā鍨嬫枃浠跺す - // 鏌ョ湅model_path璺緞涓嬫枃浠跺す璇︽儏 - QDir* dirinfo = new QDir(g_sys_conf.model_path); - if (!dirinfo->exists()) - delete dirinfo, dirinfo = nullptr; - dirinfo->setNameFilters(QStringList("*.weights")); // 璁剧疆杩囨护鍣 - QStringList fileList = dirinfo->entryList(QDir::Files); - fileList.removeOne("."); - fileList.removeOne(".."); - ui.comboBox_model_path->clear(); - ui.comboBox_model_path->addItems(fileList); - if (!g_sys_conf.model_name.isEmpty()) { - // 濡傛灉鏇鹃夋嫨杩囨ā鍨嬶紝鍒欏湪comboBox鏄剧ず閫夋嫨妯″瀷鐨勬枃浠跺悕 - ui.comboBox_model_path->setCurrentText(g_sys_conf.model_name); - } - delete dirinfo, dirinfo = nullptr; - } - else { - // 濡傛灉鏈浘閫夋嫨杩囨ā鍨嬫枃浠跺す - if (!g_sys_conf.model_name.isEmpty()) { - // 濡傛灉鏇剧粡閫夋嫨杩囨ā鍨嬫枃浠 - ui.comboBox_model_path->addItem(g_sys_conf.model_name); - } - } - // 鏇存崲妯″瀷浜嬩欢 - connect(ui.comboBox_model_path, SIGNAL(currentIndexChanged(int)), this, SLOT(onComboBoxSelect(int))); - - if (!g_conf_path.save_pics_path.isEmpty()) { - // 濡傛灉閰嶇疆鏂囦欢閲屼繚瀛樺浘鐗囪矾寰勯潪绌 - QDir* dirinfo = new QDir(g_conf_path.save_pics_path); - if (!dirinfo->exists()) { - //delete dirinfo, dirinfo = nullptr; - dirinfo->mkdir(g_conf_path.save_pics_path); - } - - //ui.comboBox_save_pics_path->clear(); - ui.comboBox_save_pics_path->addItem(g_conf_path.save_pics_path); - delete dirinfo, dirinfo = nullptr; - } - else { - QString dirPath = "D:/image"; - QDir *dirinfo = new QDir(dirPath); - if (!dirinfo->exists()) - delete dirinfo, dirinfo = nullptr; - //ui.comboBox_save_pics_path->clear(); - ui.comboBox_save_pics_path->setCurrentText(dirPath); - g_conf_path.save_pics_path = dirPath; - } - // 鏇存崲閫夋嫨鏂囦欢 - connect(ui.comboBox_save_pics_path, SIGNAL(currentIndexChanged(int)), this, SLOT(onComboBoxPicsPathSelect(int))); - - - switch (g_sys_conf.save) - { - case 0: - ui.radioButton_none->setChecked(true); - break; - case 1: - ui.radioButton_ng->setChecked(true); - break; - case 2: - ui.radioButton_all->setChecked(true); - break; - default: - break; - } - // + system("start /b C:\\Windows\\system32\\osk.exe"); +} + +DialogSetup::DialogSetup(QWidget* parent) : QDialog(parent) { + ui.setupUi(this); + InitPtrMat(); + this->setWindowFlags(Qt::FramelessWindowHint);//绐楀彛鍙Щ鍔 + + for (int i = 0; i < NumberOfSupportedCameras; i++) + { + lineEdit_expo_mat[i]->setValidator(new QIntValidator(0, 1000000, this)); + lineEdit_expo_mat[i]->setText(QString::number(g_sys_conf.expo[i])); + lineEdit_gain_mat[i]->setValidator(new QIntValidator(0, 64, this)); + lineEdit_gain_mat[i]->setText(QString::number(g_sys_conf.gain[i])); + lineEdit_filter_mat[i]->setValidator(new QIntValidator(0, 1000000, this)); + lineEdit_filter_mat[i]->setText(QString::number(g_sys_conf.filter[i])); + } + + if (g_sys_conf.auto_open == 1) + { + ui.checkBox_auto_open->setChecked(true); + } + else { + ui.checkBox_auto_open->setChecked(false); + } + if (g_sys_conf.auto_work == 1) + { + ui.checkBox_auto_work->setChecked(true); + } + else { + ui.checkBox_auto_work->setChecked(false); + } + + if (!g_conf_path.config_path.isEmpty()) { + // 濡傛灉閰嶇疆鏂囦欢瀛樺偍璺緞闈炵┖ + QDir* dirinfo = new QDir(g_conf_path.config_path); + if (!dirinfo->exists()) { + // 濡傛灉鏂囦欢澶逛俊鎭笉瀛樺湪 + delete dirinfo, dirinfo = nullptr; + g_conf_path.config_path = "D:/conf"; + } + dirinfo->setNameFilters(QStringList("conf.txt")); + QStringList fileList = dirinfo->entryList(QDir::Files); + fileList.removeOne("."); + fileList.removeOne(".."); + delete dirinfo, dirinfo = nullptr; + } + else { + // 濡傛灉璺緞绌 + g_conf_path.config_path = "D:/conf"; + } + ui.comboBox_config_path->addItem(g_conf_path.config_path); + // 鏇存崲閫夋嫨鏂囦欢 + connect(ui.comboBox_config_path, SIGNAL(currentIndexChanged(int)), this, SLOT(onComboBoxConfSelect(int))); + + if (!g_sys_conf.model_path.isEmpty()) { + // 濡傛灉鏇剧粡閫夋嫨杩囨ā鍨嬫枃浠跺す + // 鏌ョ湅model_path璺緞涓嬫枃浠跺す璇︽儏 + QDir* dirinfo = new QDir(g_sys_conf.model_path); + if (!dirinfo->exists()) + delete dirinfo, dirinfo = nullptr; + dirinfo->setNameFilters(QStringList("*.weights")); // 璁剧疆杩囨护鍣 + QStringList fileList = dirinfo->entryList(QDir::Files); + fileList.removeOne("."); + fileList.removeOne(".."); + ui.comboBox_model_path->clear(); + ui.comboBox_model_path->addItems(fileList); + if (!g_sys_conf.model_name.isEmpty()) { + // 濡傛灉鏇鹃夋嫨杩囨ā鍨嬶紝鍒欏湪comboBox鏄剧ず閫夋嫨妯″瀷鐨勬枃浠跺悕 + ui.comboBox_model_path->setCurrentText(g_sys_conf.model_name); + } + delete dirinfo, dirinfo = nullptr; + } + else { + // 濡傛灉鏈浘閫夋嫨杩囨ā鍨嬫枃浠跺す + if (!g_sys_conf.model_name.isEmpty()) { + // 濡傛灉鏇剧粡閫夋嫨杩囨ā鍨嬫枃浠 + ui.comboBox_model_path->addItem(g_sys_conf.model_name); + } + } + // 鏇存崲妯″瀷浜嬩欢 + connect(ui.comboBox_model_path, SIGNAL(currentIndexChanged(int)), this, SLOT(onComboBoxSelect(int))); + + if (!g_conf_path.save_pics_path.isEmpty()) { + // 濡傛灉閰嶇疆鏂囦欢閲屼繚瀛樺浘鐗囪矾寰勯潪绌 + QDir* dirinfo = new QDir(g_conf_path.save_pics_path); + if (!dirinfo->exists()) { + //delete dirinfo, dirinfo = nullptr; + dirinfo->mkdir(g_conf_path.save_pics_path); + } + + //ui.comboBox_save_pics_path->clear(); + ui.comboBox_save_pics_path->addItem(g_conf_path.save_pics_path); + delete dirinfo, dirinfo = nullptr; + } + else { + QString dirPath = "D:/image"; + QDir* dirinfo = new QDir(dirPath); + if (!dirinfo->exists()) + delete dirinfo, dirinfo = nullptr; + //ui.comboBox_save_pics_path->clear(); + ui.comboBox_save_pics_path->setCurrentText(dirPath); + g_conf_path.save_pics_path = dirPath; + } + // 鏇存崲閫夋嫨鏂囦欢 + connect(ui.comboBox_save_pics_path, SIGNAL(currentIndexChanged(int)), this, SLOT(onComboBoxPicsPathSelect(int))); + + + switch (g_sys_conf.save) + { + case 0: + ui.radioButton_none->setChecked(true); + break; + case 1: + ui.radioButton_ng->setChecked(true); + break; + case 2: + ui.radioButton_all->setChecked(true); + break; + default: + break; + } + // #ifndef __DEBUG - ui.pushButton_testimg->setVisible(false); - ui.pushButton_testimgs->setVisible(false); + ui.pushButton_testimg->setVisible(false); + ui.pushButton_testimgs->setVisible(false); #endif } DialogSetup::~DialogSetup() { - + } void DialogSetup::onComboBoxPicsPathSelect(int index) { - QString cp = ui.comboBox_save_pics_path->currentText(); - //QMessageBox::information(this, QStringLiteral("鎻愮ず"), QStringLiteral("鎮ㄩ夋嫨鐨勯」涓") + cp, NULL); - g_conf_path.save_pics_path = cp; - write_conf_path(); + QString cp = ui.comboBox_save_pics_path->currentText(); + //QMessageBox::information(this, QStringLiteral("鎻愮ず"), QStringLiteral("鎮ㄩ夋嫨鐨勯」涓") + cp, NULL); + g_conf_path.save_pics_path = cp; + write_conf_path(); } void DialogSetup::onComboBoxConfSelect(int index) { - QString cp = ui.comboBox_config_path->currentText(); - //QMessageBox::information(this, QStringLiteral("鎻愮ず"), QStringLiteral("鎮ㄩ夋嫨鐨勯」涓") + cp, NULL); - g_conf_path.config_path = cp; - write_conf_path(); + QString cp = ui.comboBox_config_path->currentText(); + //QMessageBox::information(this, QStringLiteral("鎻愮ず"), QStringLiteral("鎮ㄩ夋嫨鐨勯」涓") + cp, NULL); + g_conf_path.config_path = cp; + write_conf_path(); } void DialogSetup::onComboBoxSelect(int index) { - // 鑾峰彇comboBox褰撳墠鍐呭 - QString ct = ui.comboBox_model_path->currentText(); - // 淇濆瓨鍒伴厤缃枃浠朵腑 - g_sys_conf.model_name = ct; + // 鑾峰彇comboBox褰撳墠鍐呭 + QString ct = ui.comboBox_model_path->currentText(); + // 淇濆瓨鍒伴厤缃枃浠朵腑 + g_sys_conf.model_name = ct; } void DialogSetup::on_toolButton_keyboard_released() { - std::thread osk_thread = std::thread(task_osk); - osk_thread.detach(); + std::thread osk_thread = std::thread(task_osk); + osk_thread.detach(); } void DialogSetup::on_pushButton_exit_released() { - if (QMessageBox::Yes == QMessageBox::critical(NULL, QStringLiteral("閫鍑虹郴缁"), QStringLiteral("纭畾閫鍑虹郴缁?"), QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes)) - { - emit system_exit(); - this->close(); - } + if (QMessageBox::Yes == QMessageBox::critical(NULL, QStringLiteral("閫鍑虹郴缁"), QStringLiteral("纭畾閫鍑虹郴缁?"), QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes)) + { + emit system_exit(); + this->close(); + } } void DialogSetup::on_pushButton_desktop_released() { - CoInitialize(0); - IShellDispatch4 * pdisp = NULL; - CoCreateInstance(CLSID_Shell, NULL, CLSCTX_ALL, __uuidof(IShellDispatch4), (void **)&pdisp); - pdisp->ToggleDesktop(); // 杩欏彞鏄敤鏉ュ垏鎹㈡闈㈢殑 - pdisp->Release(); - CoUninitialize(); + CoInitialize(0); + IShellDispatch4* pdisp = NULL; + CoCreateInstance(CLSID_Shell, NULL, CLSCTX_ALL, __uuidof(IShellDispatch4), (void**)&pdisp); + pdisp->ToggleDesktop(); // 杩欏彞鏄敤鏉ュ垏鎹㈡闈㈢殑 + pdisp->Release(); + CoUninitialize(); } void DialogSetup::on_pushButton_expo_released() { - for(int i=0;itext()).toInt(); - g_sys_conf.gain[i] = (lineEdit_gain_mat[i]->text()).toInt(); - } - QMessageBox::information(NULL, QStringLiteral("鎻愮ず"), QStringLiteral("璁剧疆鎴愬姛"), QMessageBox::Ok); + for (int i = 0; i < NumberOfSupportedCameras; i++) + { + g_sys_conf.expo[i] = (lineEdit_expo_mat[i]->text()).toInt(); + g_sys_conf.gain[i] = (lineEdit_gain_mat[i]->text()).toInt(); + } + QMessageBox::information(NULL, QStringLiteral("鎻愮ず"), QStringLiteral("璁剧疆鎴愬姛"), QMessageBox::Ok); } void DialogSetup::on_checkBox_auto_open_clicked(bool checked) { - if (checked) - { - g_sys_conf.auto_open = 1; - } - else - { - g_sys_conf.auto_open = 0; - } + if (checked) + { + g_sys_conf.auto_open = 1; + } + else + { + g_sys_conf.auto_open = 0; + } } void DialogSetup::on_checkBox_auto_work_clicked(bool checked) { - if (checked) - { - g_sys_conf.auto_work = 1; - } - else - { - g_sys_conf.auto_work = 0; - } + if (checked) + { + g_sys_conf.auto_work = 1; + } + else + { + g_sys_conf.auto_work = 0; + } } void DialogSetup::on_pushButton_filter_released() { - for(int i=0;itext()).toInt(); - } - QMessageBox::information(NULL, QStringLiteral("鎻愮ず"), QStringLiteral("璁剧疆鎴愬姛"), QMessageBox::Ok); + for (int i = 0; i < NumberOfSupportedCameras; i++) + { + g_sys_conf.filter[i] = (lineEdit_filter_mat[i]->text()).toInt(); + } + QMessageBox::information(NULL, QStringLiteral("鎻愮ず"), QStringLiteral("璁剧疆鎴愬姛"), QMessageBox::Ok); } void DialogSetup::on_pushButton_image_released() { - if (ui.radioButton_none->isChecked()) - { - g_sys_conf.save = 0; - } - if (ui.radioButton_ng->isChecked()) - { - g_sys_conf.save = 1; - } - if (ui.radioButton_all->isChecked()) - { - g_sys_conf.save = 2; - } - QMessageBox::information(NULL, QStringLiteral("鎻愮ず"), QStringLiteral("璁剧疆鎴愬姛"), QMessageBox::Ok); + if (ui.radioButton_none->isChecked()) + { + g_sys_conf.save = 0; + } + if (ui.radioButton_ng->isChecked()) + { + g_sys_conf.save = 1; + } + if (ui.radioButton_all->isChecked()) + { + g_sys_conf.save = 2; + } + QMessageBox::information(NULL, QStringLiteral("鎻愮ず"), QStringLiteral("璁剧疆鎴愬姛"), QMessageBox::Ok); } void DialogSetup::on_pushButton_pswd_released() { - QString md5Str = QCryptographicHash::hash((ui.lineEdit_old->text()).toLatin1(), QCryptographicHash::Md5).toHex(); - if (md5Str.compare(g_admin_pswd, Qt::CaseInsensitive) == 0) - { - QString pswd_new = ui.lineEdit_new->text(); - QString pswd_confirm = ui.lineEdit_confirm->text(); - if (pswd_new.compare(pswd_confirm, Qt::CaseInsensitive) == 0) - { - g_admin_pswd = QCryptographicHash::hash(pswd_new.toLatin1(), QCryptographicHash::Md5).toHex(); - write_pswd(); - QMessageBox::information(NULL, QStringLiteral("鎻愮ず"), QStringLiteral("绠$悊鍛樺瘑鐮佷慨鏀规垚鍔"), QMessageBox::Ok); - } - else { - QMessageBox::information(NULL, QStringLiteral("鎻愮ず娑堟伅"), QStringLiteral("鏂板瘑鐮佷袱娆¤緭鍏ヤ笉涓鑷达紝璇烽噸鏂拌緭鍏"), QMessageBox::Ok); - } - } - else { - QMessageBox::information(NULL, QStringLiteral("鎻愮ず娑堟伅"), QStringLiteral("鍘熷瘑鐮侀敊璇紝璇烽噸鏂拌緭鍏"), QMessageBox::Ok); - } + QString md5Str = QCryptographicHash::hash((ui.lineEdit_old->text()).toLatin1(), QCryptographicHash::Md5).toHex(); + if (md5Str.compare(g_admin_pswd, Qt::CaseInsensitive) == 0) + { + QString pswd_new = ui.lineEdit_new->text(); + QString pswd_confirm = ui.lineEdit_confirm->text(); + if (pswd_new.compare(pswd_confirm, Qt::CaseInsensitive) == 0) + { + g_admin_pswd = QCryptographicHash::hash(pswd_new.toLatin1(), QCryptographicHash::Md5).toHex(); + write_pswd(); + QMessageBox::information(NULL, QStringLiteral("鎻愮ず"), QStringLiteral("绠$悊鍛樺瘑鐮佷慨鏀规垚鍔"), QMessageBox::Ok); + } + else { + QMessageBox::information(NULL, QStringLiteral("鎻愮ず娑堟伅"), QStringLiteral("鏂板瘑鐮佷袱娆¤緭鍏ヤ笉涓鑷达紝璇烽噸鏂拌緭鍏"), QMessageBox::Ok); + } + } + else { + QMessageBox::information(NULL, QStringLiteral("鎻愮ず娑堟伅"), QStringLiteral("鍘熷瘑鐮侀敊璇紝璇烽噸鏂拌緭鍏"), QMessageBox::Ok); + } } void DialogSetup::on_pushButton_pswd_op_released() { - QString md5Str = QCryptographicHash::hash((ui.lineEdit_old_op->text()).toLatin1(), QCryptographicHash::Md5).toHex(); - if (md5Str.compare(g_op_pswd, Qt::CaseInsensitive) == 0) - { - QString pswd_new = ui.lineEdit_new_op->text(); - QString pswd_confirm = ui.lineEdit_confirm_op->text(); - if (pswd_new.compare(pswd_confirm, Qt::CaseInsensitive) == 0) - { - g_op_pswd = QCryptographicHash::hash(pswd_new.toLatin1(), QCryptographicHash::Md5).toHex(); - write_pswd_op(); - QMessageBox::information(NULL, QStringLiteral("鎻愮ず"), QStringLiteral("鎿嶄綔鍛樺瘑鐮佷慨鏀规垚鍔"), QMessageBox::Ok); - } - else { - QMessageBox::information(NULL, QStringLiteral("鎻愮ず娑堟伅"), QStringLiteral("鏂板瘑鐮佷袱娆¤緭鍏ヤ笉涓鑷达紝璇烽噸鏂拌緭鍏"), QMessageBox::Ok); - } - } - else { - QMessageBox::information(NULL, QStringLiteral("鎻愮ず娑堟伅"), QStringLiteral("鍘熷瘑鐮侀敊璇紝璇烽噸鏂拌緭鍏"), QMessageBox::Ok); - } + QString md5Str = QCryptographicHash::hash((ui.lineEdit_old_op->text()).toLatin1(), QCryptographicHash::Md5).toHex(); + if (md5Str.compare(g_op_pswd, Qt::CaseInsensitive) == 0) + { + QString pswd_new = ui.lineEdit_new_op->text(); + QString pswd_confirm = ui.lineEdit_confirm_op->text(); + if (pswd_new.compare(pswd_confirm, Qt::CaseInsensitive) == 0) + { + g_op_pswd = QCryptographicHash::hash(pswd_new.toLatin1(), QCryptographicHash::Md5).toHex(); + write_pswd_op(); + QMessageBox::information(NULL, QStringLiteral("鎻愮ず"), QStringLiteral("鎿嶄綔鍛樺瘑鐮佷慨鏀规垚鍔"), QMessageBox::Ok); + } + else { + QMessageBox::information(NULL, QStringLiteral("鎻愮ず娑堟伅"), QStringLiteral("鏂板瘑鐮佷袱娆¤緭鍏ヤ笉涓鑷达紝璇烽噸鏂拌緭鍏"), QMessageBox::Ok); + } + } + else { + QMessageBox::information(NULL, QStringLiteral("鎻愮ず娑堟伅"), QStringLiteral("鍘熷瘑鐮侀敊璇紝璇烽噸鏂拌緭鍏"), QMessageBox::Ok); + } } void DialogSetup::on_pushButton_save_released() { - //瀛樺浘璁剧疆 - if (ui.radioButton_none->isChecked()) - { - g_sys_conf.save = 0; - } - if (ui.radioButton_ng->isChecked()) - { - g_sys_conf.save = 1; - } - if (ui.radioButton_all->isChecked()) - { - g_sys_conf.save = 2; - } - for(int i=0;itext()).toInt(); - g_sys_conf.gain[i] = (lineEdit_gain_mat[i]->text()).toInt(); - g_sys_conf.filter[i] = (lineEdit_filter_mat[i]->text()).toInt(); - } - - write_config(); - QMessageBox::information(NULL, QStringLiteral("鎻愮ず"), QStringLiteral("淇濆瓨鍙傛暟鎴愬姛,閮ㄥ垎閰嶇疆闇瑕侀噸鍚▼搴忓悗鐢熸晥"), QMessageBox::Ok); + //瀛樺浘璁剧疆 + if (ui.radioButton_none->isChecked()) + { + g_sys_conf.save = 0; + } + if (ui.radioButton_ng->isChecked()) + { + g_sys_conf.save = 1; + } + if (ui.radioButton_all->isChecked()) + { + g_sys_conf.save = 2; + } + for (int i = 0; i < NumberOfSupportedCameras; i++) + { + g_sys_conf.expo[i] = (lineEdit_expo_mat[i]->text()).toInt(); + g_sys_conf.gain[i] = (lineEdit_gain_mat[i]->text()).toInt(); + g_sys_conf.filter[i] = (lineEdit_filter_mat[i]->text()).toInt(); + } + + write_config(); + QMessageBox::information(NULL, QStringLiteral("鎻愮ず"), QStringLiteral("淇濆瓨鍙傛暟鎴愬姛,閮ㄥ垎閰嶇疆闇瑕侀噸鍚▼搴忓悗鐢熸晥"), QMessageBox::Ok); } void DialogSetup::on_pushButton_close_released() { - this->close(); + this->close(); } void DialogSetup::on_pushButton_clear_pic_released() { - QThread* handleThread = new QThread(); - CleanWorkThread* cleanWorkThread = new CleanWorkThread(); + QThread* handleThread = new QThread(); + CleanWorkThread* cleanWorkThread = new CleanWorkThread(); - cleanWorkThread->moveToThread(handleThread); + cleanWorkThread->moveToThread(handleThread); - connect(handleThread, &QThread::started, cleanWorkThread, &CleanWorkThread::startWork); - connect(cleanWorkThread, &CleanWorkThread::workStart, cleanWorkThread, &CleanWorkThread::setSel); - connect(cleanWorkThread, &CleanWorkThread::workFinished, cleanWorkThread, &CleanWorkThread::deleteLater); - connect(cleanWorkThread, &CleanWorkThread::destroyed, handleThread, &QThread::quit); - connect(handleThread, &QThread::finished, handleThread, &QThread::deleteLater); - handleThread->start(); + connect(handleThread, &QThread::started, cleanWorkThread, &CleanWorkThread::startWork); + connect(cleanWorkThread, &CleanWorkThread::workStart, cleanWorkThread, &CleanWorkThread::setSel); + connect(cleanWorkThread, &CleanWorkThread::workFinished, cleanWorkThread, &CleanWorkThread::deleteLater); + connect(cleanWorkThread, &CleanWorkThread::destroyed, handleThread, &QThread::quit); + connect(handleThread, &QThread::finished, handleThread, &QThread::deleteLater); + handleThread->start(); } void DialogSetup::on_toolButton_choose_config_path_released() { - QString dirName = QFileDialog::getExistingDirectory(this, QStringLiteral("璇烽夋嫨閰嶇疆鏂囦欢鎵鍦ㄦ枃浠跺す"), "./"); - if (dirName.isEmpty()) { - // 鐐瑰嚮鍙栨秷鎸夐挳 - if (g_conf_path.config_path.isEmpty()) - dirName = "D:/conf"; - else - dirName = g_conf_path.config_path; - } - - QDir* dirinfo = new QDir(dirName); - if (!dirinfo->exists()) - delete dirinfo, dirinfo = nullptr; - - dirinfo->setNameFilters(QStringList("conf.txt")); - QStringList fileList = dirinfo->entryList(QDir::Files); - - if (fileList.count() == 0) { - dirName = "D:/conf"; - } - - //fileList.removeOne("."); - //fileList.removeOne(".."); - - QFileInfo fileInfo(dirName); - - if (fileInfo.isDir() && ui.comboBox_config_path->findText(fileInfo.absoluteFilePath())) { - ui.comboBox_config_path->addItem(fileInfo.absoluteFilePath()); - ui.comboBox_config_path->setCurrentText(fileInfo.absoluteFilePath()); - } - - g_conf_path.config_path = dirName; - connect(ui.comboBox_config_path, SIGNAL(currentIndexChanged(int)), this, SLOT(onComboBoxConfSelect(int))); - write_conf_path(); - delete dirinfo, dirinfo = nullptr; + QString dirName = QFileDialog::getExistingDirectory(this, QStringLiteral("璇烽夋嫨閰嶇疆鏂囦欢鎵鍦ㄦ枃浠跺す"), "./"); + if (dirName.isEmpty()) { + // 鐐瑰嚮鍙栨秷鎸夐挳 + if (g_conf_path.config_path.isEmpty()) + dirName = "D:/conf"; + else + dirName = g_conf_path.config_path; + } + + QDir* dirinfo = new QDir(dirName); + if (!dirinfo->exists()) + delete dirinfo, dirinfo = nullptr; + + dirinfo->setNameFilters(QStringList("conf.txt")); + QStringList fileList = dirinfo->entryList(QDir::Files); + + if (fileList.count() == 0) { + dirName = "D:/conf"; + } + + //fileList.removeOne("."); + //fileList.removeOne(".."); + + QFileInfo fileInfo(dirName); + + if (fileInfo.isDir() && ui.comboBox_config_path->findText(fileInfo.absoluteFilePath())) { + ui.comboBox_config_path->addItem(fileInfo.absoluteFilePath()); + ui.comboBox_config_path->setCurrentText(fileInfo.absoluteFilePath()); + } + + g_conf_path.config_path = dirName; + connect(ui.comboBox_config_path, SIGNAL(currentIndexChanged(int)), this, SLOT(onComboBoxConfSelect(int))); + write_conf_path(); + delete dirinfo, dirinfo = nullptr; } void DialogSetup::on_toolButton_choose_model_path_released() { - // 鐐瑰嚮娴忚鏂囦欢鎸夐挳鍚庤Е鍙戠殑浜嬩欢 - QString dirName = QFileDialog::getExistingDirectory(this, QStringLiteral("璇烽夋嫨妯″瀷鎵鍦ㄦ枃浠跺す"), "./"); - //std::cout << "dirName is " << dirName.toStdString().c_str() << std::endl; - //std::cout << "g_sys_conf.dir_path is " << g_sys_conf.dir_path.toStdString().c_str() << std::endl; - //std::cout << "g_sys_conf.model_name is " << g_sys_conf.model_name.toStdString().c_str() << std::endl; - - if (dirName.isEmpty()) { - if (g_sys_conf.model_path.isEmpty()) - dirName = "D:/model"; - else - dirName = g_sys_conf.model_path; - - ui.comboBox_model_path->addItem(dirName); - g_sys_conf.model_path = dirName; - g_sys_conf.model_name = "jd.weights"; - } - QDir* dirinfo = new QDir(dirName); - if (!dirinfo->exists()) - delete dirinfo, dirinfo = nullptr; - dirinfo->setNameFilters(QStringList("*.weights")); - QStringList fileList = dirinfo->entryList(QDir::Files); - if (fileList.count() == 0) { - g_sys_conf.model_path = "D:/model"; - g_sys_conf.model_name = "jd.weights"; - } - else - g_sys_conf.model_path = dirName; - - fileList.removeOne("."); - fileList.removeOne(".."); - - ui.comboBox_model_path->clear(); - ui.comboBox_model_path->addItems(fileList); - //g_sys_conf.model_name = ui.comboBox_model_path->currentText(); - connect(ui.comboBox_model_path, SIGNAL(currentIndexChanged(int)), this, SLOT(onComboBoxSelect(int))); - - delete dirinfo, dirinfo = nullptr; + // 鐐瑰嚮娴忚鏂囦欢鎸夐挳鍚庤Е鍙戠殑浜嬩欢 + QString dirName = QFileDialog::getExistingDirectory(this, QStringLiteral("璇烽夋嫨妯″瀷鎵鍦ㄦ枃浠跺す"), "./"); + //std::cout << "dirName is " << dirName.toStdString().c_str() << std::endl; + //std::cout << "g_sys_conf.dir_path is " << g_sys_conf.dir_path.toStdString().c_str() << std::endl; + //std::cout << "g_sys_conf.model_name is " << g_sys_conf.model_name.toStdString().c_str() << std::endl; + + if (dirName.isEmpty()) { + if (g_sys_conf.model_path.isEmpty()) + dirName = "D:/model"; + else + dirName = g_sys_conf.model_path; + + ui.comboBox_model_path->addItem(dirName); + g_sys_conf.model_path = dirName; + g_sys_conf.model_name = "jd.weights"; + } + QDir* dirinfo = new QDir(dirName); + if (!dirinfo->exists()) + delete dirinfo, dirinfo = nullptr; + dirinfo->setNameFilters(QStringList("*.weights")); + QStringList fileList = dirinfo->entryList(QDir::Files); + if (fileList.count() == 0) { + g_sys_conf.model_path = "D:/model"; + g_sys_conf.model_name = "jd.weights"; + } + else + g_sys_conf.model_path = dirName; + + fileList.removeOne("."); + fileList.removeOne(".."); + + ui.comboBox_model_path->clear(); + ui.comboBox_model_path->addItems(fileList); + //g_sys_conf.model_name = ui.comboBox_model_path->currentText(); + connect(ui.comboBox_model_path, SIGNAL(currentIndexChanged(int)), this, SLOT(onComboBoxSelect(int))); + + delete dirinfo, dirinfo = nullptr; } void DialogSetup::on_toolButton_choose_save_pics_path_released() { - // 鏀瑰彉鍥剧墖鐨勫瓨鍌ㄨ矾寰 - QString dirName = QFileDialog::getExistingDirectory(this, QStringLiteral("璇烽夋嫨鍥剧墖瀛樺偍璺緞"), "./"); - // 濡傛灉娌℃湁閫夋嫨璺緞 - if (dirName.isEmpty()) { - if (g_conf_path.save_pics_path.isEmpty()) - dirName = "D:/image"; - else - dirName = g_conf_path.save_pics_path; - //ui.comboBox_save_pics_path->addItem(dirName); - //return; - } - - QDir* dirinfo = new QDir(dirName); - if (!dirinfo->exists()) - delete dirinfo, dirinfo = nullptr; - - QFileInfo fileInfo(dirName); - if (fileInfo.isDir() && ui.comboBox_save_pics_path->findText(fileInfo.absoluteFilePath())) { - ui.comboBox_save_pics_path->addItem(fileInfo.absoluteFilePath()); - ui.comboBox_save_pics_path->setCurrentText(fileInfo.absoluteFilePath()); - } - - g_conf_path.save_pics_path = dirName; - - connect(ui.comboBox_save_pics_path, SIGNAL(currentIndexChanged(int)), this, SLOT(onComboBoxPicsPathSelect(int))); - write_conf_path(); - delete dirinfo, dirinfo = nullptr; + // 鏀瑰彉鍥剧墖鐨勫瓨鍌ㄨ矾寰 + QString dirName = QFileDialog::getExistingDirectory(this, QStringLiteral("璇烽夋嫨鍥剧墖瀛樺偍璺緞"), "./"); + // 濡傛灉娌℃湁閫夋嫨璺緞 + if (dirName.isEmpty()) { + if (g_conf_path.save_pics_path.isEmpty()) + dirName = "D:/image"; + else + dirName = g_conf_path.save_pics_path; + //ui.comboBox_save_pics_path->addItem(dirName); + //return; + } + + QDir* dirinfo = new QDir(dirName); + if (!dirinfo->exists()) + delete dirinfo, dirinfo = nullptr; + + QFileInfo fileInfo(dirName); + if (fileInfo.isDir() && ui.comboBox_save_pics_path->findText(fileInfo.absoluteFilePath())) { + ui.comboBox_save_pics_path->addItem(fileInfo.absoluteFilePath()); + ui.comboBox_save_pics_path->setCurrentText(fileInfo.absoluteFilePath()); + } + + g_conf_path.save_pics_path = dirName; + + connect(ui.comboBox_save_pics_path, SIGNAL(currentIndexChanged(int)), this, SLOT(onComboBoxPicsPathSelect(int))); + write_conf_path(); + delete dirinfo, dirinfo = nullptr; } void DialogSetup::on_toolButton_choose_path_jpg_released() { - QString JpgPath = QFileDialog::getOpenFileName(this, "閫夋嫨jpg鏂囦欢", "/", "jpg files(*.jpg)"); - if (JpgPath.isEmpty()) { - return; - } - else { - if (ui.comboBox_2->findText(JpgPath) == -1) { - ui.comboBox_2->addItem(JpgPath); // 鍦╟omboBox涓樉绀烘枃浠惰矾寰 - g_sys_conf.model_jpg_path = JpgPath; // 灏嗛夋嫨鐨勮矾寰勫啓鍏onf閰嶇疆鏂囦欢涓 - } - } + QString JpgPath = QFileDialog::getOpenFileName(this, "閫夋嫨jpg鏂囦欢", "/", "jpg files(*.jpg)"); + if (JpgPath.isEmpty()) { + return; + } + else { + if (ui.comboBox_2->findText(JpgPath) == -1) { + ui.comboBox_2->addItem(JpgPath); // 鍦╟omboBox涓樉绀烘枃浠惰矾寰 + g_sys_conf.model_jpg_path = JpgPath; // 灏嗛夋嫨鐨勮矾寰勫啓鍏onf閰嶇疆鏂囦欢涓 + } + } } void DialogSetup::write_pswd() { - std::fstream cfg_file; - cfg_file.open("D:/Release/pswd.txt", std::ios::out | std::ios::trunc); - if (cfg_file.good()) - { - char buf[256]; - memset(buf, 0, 256); - sprintf(buf, "%s", g_admin_pswd.toStdString().c_str()); - cfg_file.write(buf, strlen(buf)); - } - cfg_file.close(); + std::fstream cfg_file; + cfg_file.open("D:/Release/pswd.txt", std::ios::out | std::ios::trunc); + if (cfg_file.good()) + { + char buf[256]; + memset(buf, 0, 256); + sprintf(buf, "%s", g_admin_pswd.toStdString().c_str()); + cfg_file.write(buf, strlen(buf)); + } + cfg_file.close(); } void DialogSetup::write_pswd_op() { - std::fstream cfg_file; - cfg_file.open("D:/Release/pswd_op.txt", std::ios::out | std::ios::trunc); - if (cfg_file.good()) - { - char buf[256]; - memset(buf, 0, 256); - sprintf(buf, "%s", g_op_pswd.toStdString().c_str()); - cfg_file.write(buf, strlen(buf)); - } - cfg_file.close(); + std::fstream cfg_file; + cfg_file.open("D:/Release/pswd_op.txt", std::ios::out | std::ios::trunc); + if (cfg_file.good()) + { + char buf[256]; + memset(buf, 0, 256); + sprintf(buf, "%s", g_op_pswd.toStdString().c_str()); + cfg_file.write(buf, strlen(buf)); + } + cfg_file.close(); } void DialogSetup::write_conf_path() { - std::fstream cfg_file; - cfg_file.open(CONFPATH, std::ios::out | std::ios::trunc); - if (cfg_file.good()) { - char buf[256]; - memset(buf, 0, 256); - sprintf(buf, "CONF_PATH=%s\n", g_conf_path.config_path.toLocal8Bit().constData()); - cfg_file.write(buf, strlen(buf)); - //memset(buf, 0, 256); - //sprintf(buf, "CONF_NAME=%s\n", g_conf_path.config_name.toStdString().c_str()); - //cfg_file.write(buf, strlen(buf)); - memset(buf, 0, 256); - sprintf(buf, "SAVE_PICS_PATH=%s\n", g_conf_path.save_pics_path.toLocal8Bit().constData()); - cfg_file.write(buf, strlen(buf)); - } - cfg_file.close(); + std::fstream cfg_file; + cfg_file.open(CONFPATH, std::ios::out | std::ios::trunc); + if (cfg_file.good()) { + char buf[256]; + memset(buf, 0, 256); + sprintf(buf, "CONF_PATH=%s\n", g_conf_path.config_path.toLocal8Bit().constData()); + cfg_file.write(buf, strlen(buf)); + //memset(buf, 0, 256); + //sprintf(buf, "CONF_NAME=%s\n", g_conf_path.config_name.toStdString().c_str()); + //cfg_file.write(buf, strlen(buf)); + memset(buf, 0, 256); + sprintf(buf, "SAVE_PICS_PATH=%s\n", g_conf_path.save_pics_path.toLocal8Bit().constData()); + cfg_file.write(buf, strlen(buf)); + } + cfg_file.close(); } void DialogSetup::write_config() { - std::fstream cfg_file; - QString cfg_path = g_conf_path.config_path + "/conf.txt"; - cfg_file.open(cfg_path.toLocal8Bit().constData(), std::ios::out | std::ios::trunc); - if (cfg_file.good()) - { - char buf[256]; - memset(buf, 0, 256); - sprintf(buf, "SAVE=%d\n", g_sys_conf.save); - cfg_file.write(buf, strlen(buf)); - memset(buf, 0, 256); - sprintf(buf, "MISMATCHACT=%d\n", g_sys_conf.MisMatchAct); - cfg_file.write(buf, strlen(buf)); - memset(buf, 0, 256);/// - sprintf(buf, "SAVE_DAYS=%d\n", g_sys_conf.save_days); - cfg_file.write(buf, strlen(buf)); - memset(buf, 0, 256);/// - sprintf(buf, "FREESIZE=%d\n", g_sys_conf.freesize); - cfg_file.write(buf, strlen(buf)); - memset(buf, 0, 256);/// - sprintf(buf, "ComPort=%s\n", g_sys_conf.ComPort); - cfg_file.write(buf, strlen(buf)); - memset(buf, 0, 256);/// - sprintf(buf, "CONFTHRESHOLD=%d\n", g_sys_conf.ConfThreshold); - cfg_file.write(buf, strlen(buf)); - memset(buf, 0, 256); - sprintf(buf, "AUTO_OPEN=%d\n", g_sys_conf.auto_open); - cfg_file.write(buf, strlen(buf)); - memset(buf, 0, 256); - sprintf(buf, "AUTO_WORK=%d\n", g_sys_conf.auto_work); - cfg_file.write(buf, strlen(buf)); - memset(buf, 0, 256); - sprintf(buf, "AUTO_SHIFT=%d\n", g_sys_conf.auto_shift); - cfg_file.write(buf, strlen(buf)); - memset(buf, 0, 256); - sprintf(buf, "TIMING_SHIFT=%d\n", g_sys_conf.timing_shift); - cfg_file.write(buf, strlen(buf)); - memset(buf, 0, 256); - sprintf(buf, "SHIFT_BYHAND=%d\n", g_sys_conf.shift_byhand); - cfg_file.write(buf, strlen(buf)); - memset(buf, 0, 256); - sprintf(buf, "SHIFT_A=%d|%d\n", g_sys_conf.shiftA.hour(), g_sys_conf.shiftA.minute()); - cfg_file.write(buf, strlen(buf)); - memset(buf, 0, 256); - sprintf(buf, "SHIFT_B=%d|%d\n", g_sys_conf.shiftB.hour(), g_sys_conf.shiftB.minute()); - cfg_file.write(buf, strlen(buf)); - memset(buf, 0, 256); - sprintf(buf, "SHIFT_C=%d|%d\n", g_sys_conf.shiftC.hour(), g_sys_conf.shiftC.minute()); - cfg_file.write(buf, strlen(buf)); - memset(buf, 0, 256); - sprintf(buf, "LOCATION=%s\n", g_sys_conf.location.toStdString().c_str()); - cfg_file.write(buf, strlen(buf)); - memset(buf, 0, 256); - sprintf(buf, "MODELPATH=%s\n", g_sys_conf.model_path.toStdString().c_str()); - cfg_file.write(buf, strlen(buf)); - memset(buf, 0, 256); - sprintf(buf, "MODELNAME=%s\n", g_sys_conf.model_name.toStdString().c_str()); - cfg_file.write(buf, strlen(buf)); - memset(buf, 0, 256); - sprintf(buf, "JPGPATH=%s\n", g_sys_conf.model_jpg_path.toStdString().c_str()); - cfg_file.write(buf, strlen(buf)); - memset(buf, 0, 256); - sprintf(buf, "*****************************************\n"); - cfg_file.write(buf, strlen(buf)); + std::fstream cfg_file; + QString cfg_path = g_conf_path.config_path + "/conf.txt"; + cfg_file.open(cfg_path.toLocal8Bit().constData(), std::ios::out | std::ios::trunc); + if (cfg_file.good()) + { + char buf[256]; + memset(buf, 0, 256); + sprintf(buf, "SAVE=%d\n", g_sys_conf.save); + cfg_file.write(buf, strlen(buf)); + memset(buf, 0, 256); + sprintf(buf, "MISMATCHACT=%d\n", g_sys_conf.MisMatchAct); + cfg_file.write(buf, strlen(buf)); + memset(buf, 0, 256);/// + sprintf(buf, "SAVE_DAYS=%d\n", g_sys_conf.save_days); + cfg_file.write(buf, strlen(buf)); + memset(buf, 0, 256);/// + sprintf(buf, "FREESIZE=%d\n", g_sys_conf.freesize); + cfg_file.write(buf, strlen(buf)); + memset(buf, 0, 256);/// + sprintf(buf, "ComPort=%s\n", g_sys_conf.ComPort); + cfg_file.write(buf, strlen(buf)); + memset(buf, 0, 256);/// + sprintf(buf, "CONFTHRESHOLD=%d\n", g_sys_conf.ConfThreshold); + cfg_file.write(buf, strlen(buf)); + memset(buf, 0, 256); + sprintf(buf, "AUTO_OPEN=%d\n", g_sys_conf.auto_open); + cfg_file.write(buf, strlen(buf)); + memset(buf, 0, 256); + sprintf(buf, "AUTO_WORK=%d\n", g_sys_conf.auto_work); + cfg_file.write(buf, strlen(buf)); + memset(buf, 0, 256); + sprintf(buf, "AUTO_SHIFT=%d\n", g_sys_conf.auto_shift); + cfg_file.write(buf, strlen(buf)); + memset(buf, 0, 256); + sprintf(buf, "TIMING_SHIFT=%d\n", g_sys_conf.timing_shift); + cfg_file.write(buf, strlen(buf)); + memset(buf, 0, 256); + sprintf(buf, "SHIFT_BYHAND=%d\n", g_sys_conf.shift_byhand); + cfg_file.write(buf, strlen(buf)); + memset(buf, 0, 256); + sprintf(buf, "SHIFT_A=%d|%d\n", g_sys_conf.shiftA.hour(), g_sys_conf.shiftA.minute()); + cfg_file.write(buf, strlen(buf)); + memset(buf, 0, 256); + sprintf(buf, "SHIFT_B=%d|%d\n", g_sys_conf.shiftB.hour(), g_sys_conf.shiftB.minute()); + cfg_file.write(buf, strlen(buf)); + memset(buf, 0, 256); + sprintf(buf, "SHIFT_C=%d|%d\n", g_sys_conf.shiftC.hour(), g_sys_conf.shiftC.minute()); + cfg_file.write(buf, strlen(buf)); + memset(buf, 0, 256); + sprintf(buf, "LOCATION=%s\n", g_sys_conf.location.toStdString().c_str()); + cfg_file.write(buf, strlen(buf)); + memset(buf, 0, 256); + sprintf(buf, "MODELPATH=%s\n", g_sys_conf.model_path.toStdString().c_str()); + cfg_file.write(buf, strlen(buf)); + memset(buf, 0, 256); + sprintf(buf, "MODELNAME=%s\n", g_sys_conf.model_name.toStdString().c_str()); + cfg_file.write(buf, strlen(buf)); + memset(buf, 0, 256); + sprintf(buf, "JPGPATH=%s\n", g_sys_conf.model_jpg_path.toStdString().c_str()); + cfg_file.write(buf, strlen(buf)); + memset(buf, 0, 256); + sprintf(buf, "*****************************************\n"); + cfg_file.write(buf, strlen(buf)); #if defined(NumberOfSupportedCameras) && (NumberOfSupportedCameras>0) - memset(buf, 0, 256); - sprintf(buf, "EXPO1=%d\n", g_sys_conf.expo[0]); - cfg_file.write(buf, strlen(buf)); - memset(buf, 0, 256); - sprintf(buf, "GAIN1=%d\n", g_sys_conf.gain[0]); - cfg_file.write(buf, strlen(buf)); - sprintf(buf, "FILTER1=%d\n", g_sys_conf.filter[0]); - cfg_file.write(buf, strlen(buf)); - memset(buf, 0, 256); - sprintf(buf, "USERID1=%d\n", g_sys_conf.UserID[0]); - cfg_file.write(buf, strlen(buf)); - memset(buf, 0, 256); - sprintf(buf, "NO1=%d|%d|%d\n", g_sys_conf.no[0][0],g_sys_conf.no[0][1],g_sys_conf.no[0][2]); - cfg_file.write(buf, strlen(buf)); - memset(buf, 0, 256); - sprintf(buf, "SHOOT1=%d\n", g_sys_conf.shoot[0]); - cfg_file.write(buf, strlen(buf)); - memset(buf, 0, 256); - sprintf(buf, "*****************************************\n"); - cfg_file.write(buf, strlen(buf)); + memset(buf, 0, 256); + sprintf(buf, "EXPO1=%d\n", g_sys_conf.expo[0]); + cfg_file.write(buf, strlen(buf)); + memset(buf, 0, 256); + sprintf(buf, "GAIN1=%d\n", g_sys_conf.gain[0]); + cfg_file.write(buf, strlen(buf)); + sprintf(buf, "FILTER1=%d\n", g_sys_conf.filter[0]); + cfg_file.write(buf, strlen(buf)); + memset(buf, 0, 256); + sprintf(buf, "USERID1=%d\n", g_sys_conf.UserID[0]); + cfg_file.write(buf, strlen(buf)); + memset(buf, 0, 256); + sprintf(buf, "NO1=%d|%d|%d\n", g_sys_conf.no[0][0], g_sys_conf.no[0][1], g_sys_conf.no[0][2]); + cfg_file.write(buf, strlen(buf)); + memset(buf, 0, 256); + sprintf(buf, "SHOOT1=%d\n", g_sys_conf.shoot[0]); + cfg_file.write(buf, strlen(buf)); + memset(buf, 0, 256); + sprintf(buf, "*****************************************\n"); + cfg_file.write(buf, strlen(buf)); #endif #if defined(NumberOfSupportedCameras) && (NumberOfSupportedCameras>1) - memset(buf, 0, 256); - sprintf(buf, "EXPO2=%d\n", g_sys_conf.expo[1]); - cfg_file.write(buf, strlen(buf)); - memset(buf, 0, 256); - sprintf(buf, "GAIN2=%d\n", g_sys_conf.gain[1]); - cfg_file.write(buf, strlen(buf)); - memset(buf, 0, 256); - sprintf(buf, "FILTER2=%d\n", g_sys_conf.filter[1]); - cfg_file.write(buf, strlen(buf)); - sprintf(buf, "USERID2=%d\n", g_sys_conf.UserID[1]); - cfg_file.write(buf, strlen(buf)); - memset(buf, 0, 256); - sprintf(buf, "NO2=%d|%d|%d\n", g_sys_conf.no[1][0],g_sys_conf.no[1][1],g_sys_conf.no[1][2]); - cfg_file.write(buf, strlen(buf)); - memset(buf, 0, 256); - sprintf(buf, "SHOOT2=%d\n", g_sys_conf.shoot[1]); - cfg_file.write(buf, strlen(buf)); - memset(buf, 0, 256); - sprintf(buf, "*****************************************\n"); - cfg_file.write(buf, strlen(buf)); + memset(buf, 0, 256); + sprintf(buf, "EXPO2=%d\n", g_sys_conf.expo[1]); + cfg_file.write(buf, strlen(buf)); + memset(buf, 0, 256); + sprintf(buf, "GAIN2=%d\n", g_sys_conf.gain[1]); + cfg_file.write(buf, strlen(buf)); + memset(buf, 0, 256); + sprintf(buf, "FILTER2=%d\n", g_sys_conf.filter[1]); + cfg_file.write(buf, strlen(buf)); + sprintf(buf, "USERID2=%d\n", g_sys_conf.UserID[1]); + cfg_file.write(buf, strlen(buf)); + memset(buf, 0, 256); + sprintf(buf, "NO2=%d|%d|%d\n", g_sys_conf.no[1][0], g_sys_conf.no[1][1], g_sys_conf.no[1][2]); + cfg_file.write(buf, strlen(buf)); + memset(buf, 0, 256); + sprintf(buf, "SHOOT2=%d\n", g_sys_conf.shoot[1]); + cfg_file.write(buf, strlen(buf)); + memset(buf, 0, 256); + sprintf(buf, "*****************************************\n"); + cfg_file.write(buf, strlen(buf)); #endif #if defined(NumberOfSupportedCameras) && (NumberOfSupportedCameras>2) - memset(buf, 0, 256); - sprintf(buf, "EXPO3=%d\n", g_sys_conf.expo[2]); - cfg_file.write(buf, strlen(buf)); - memset(buf, 0, 256); - sprintf(buf, "GAIN3=%d\n", g_sys_conf.gain[2]); - cfg_file.write(buf, strlen(buf)); - memset(buf, 0, 256); - sprintf(buf, "FILTER3=%d\n", g_sys_conf.filter[2]); - cfg_file.write(buf, strlen(buf)); - sprintf(buf, "USERID3=%d\n", g_sys_conf.UserID[2]); - cfg_file.write(buf, strlen(buf)); - memset(buf, 0, 256); - sprintf(buf, "NO3=%d|%d|%d\n", g_sys_conf.no[2][0],g_sys_conf.no[2][1],g_sys_conf.no[2][2]); - cfg_file.write(buf, strlen(buf)); - memset(buf, 0, 256); - sprintf(buf, "SHOOT3=%d\n", g_sys_conf.shoot[2]); - cfg_file.write(buf, strlen(buf)); - memset(buf, 0, 256); - sprintf(buf, "*****************************************\n"); - cfg_file.write(buf, strlen(buf)); + memset(buf, 0, 256); + sprintf(buf, "EXPO3=%d\n", g_sys_conf.expo[2]); + cfg_file.write(buf, strlen(buf)); + memset(buf, 0, 256); + sprintf(buf, "GAIN3=%d\n", g_sys_conf.gain[2]); + cfg_file.write(buf, strlen(buf)); + memset(buf, 0, 256); + sprintf(buf, "FILTER3=%d\n", g_sys_conf.filter[2]); + cfg_file.write(buf, strlen(buf)); + sprintf(buf, "USERID3=%d\n", g_sys_conf.UserID[2]); + cfg_file.write(buf, strlen(buf)); + memset(buf, 0, 256); + sprintf(buf, "NO3=%d|%d|%d\n", g_sys_conf.no[2][0], g_sys_conf.no[2][1], g_sys_conf.no[2][2]); + cfg_file.write(buf, strlen(buf)); + memset(buf, 0, 256); + sprintf(buf, "SHOOT3=%d\n", g_sys_conf.shoot[2]); + cfg_file.write(buf, strlen(buf)); + memset(buf, 0, 256); + sprintf(buf, "*****************************************\n"); + cfg_file.write(buf, strlen(buf)); #endif #if defined(NumberOfSupportedCameras) && (NumberOfSupportedCameras>3) - memset(buf, 0, 256); - sprintf(buf, "EXPO4=%d\n", g_sys_conf.expo[3]); - cfg_file.write(buf, strlen(buf)); - memset(buf, 0, 256); - sprintf(buf, "GAIN4=%d\n", g_sys_conf.gain[3]); - cfg_file.write(buf, strlen(buf)); - memset(buf, 0, 256); - sprintf(buf, "FILTER4=%d\n", g_sys_conf.filter[3]); - cfg_file.write(buf, strlen(buf)); - sprintf(buf, "USERID4=%d\n", g_sys_conf.UserID[3]); - cfg_file.write(buf, strlen(buf)); - memset(buf, 0, 256); - sprintf(buf, "NO4=%d|%d|%d\n", g_sys_conf.no[3][0],g_sys_conf.no[3][1],g_sys_conf.no[3][2]); - cfg_file.write(buf, strlen(buf)); - memset(buf, 0, 256); - sprintf(buf, "SHOOT4=%d\n", g_sys_conf.shoot[3]); - cfg_file.write(buf, strlen(buf)); - memset(buf, 0, 256); - sprintf(buf, "*****************************************\n"); - cfg_file.write(buf, strlen(buf)); + memset(buf, 0, 256); + sprintf(buf, "EXPO4=%d\n", g_sys_conf.expo[3]); + cfg_file.write(buf, strlen(buf)); + memset(buf, 0, 256); + sprintf(buf, "GAIN4=%d\n", g_sys_conf.gain[3]); + cfg_file.write(buf, strlen(buf)); + memset(buf, 0, 256); + sprintf(buf, "FILTER4=%d\n", g_sys_conf.filter[3]); + cfg_file.write(buf, strlen(buf)); + sprintf(buf, "USERID4=%d\n", g_sys_conf.UserID[3]); + cfg_file.write(buf, strlen(buf)); + memset(buf, 0, 256); + sprintf(buf, "NO4=%d|%d|%d\n", g_sys_conf.no[3][0], g_sys_conf.no[3][1], g_sys_conf.no[3][2]); + cfg_file.write(buf, strlen(buf)); + memset(buf, 0, 256); + sprintf(buf, "SHOOT4=%d\n", g_sys_conf.shoot[3]); + cfg_file.write(buf, strlen(buf)); + memset(buf, 0, 256); + sprintf(buf, "*****************************************\n"); + cfg_file.write(buf, strlen(buf)); #endif #if defined(NumberOfSupportedCameras) && (NumberOfSupportedCameras>4) - memset(buf, 0, 256); - sprintf(buf, "EXPO5=%d\n", g_sys_conf.expo[4]); - cfg_file.write(buf, strlen(buf)); - memset(buf, 0, 256); - sprintf(buf, "GAIN5=%d\n", g_sys_conf.gain[4]); - cfg_file.write(buf, strlen(buf)); - sprintf(buf, "FILTER5=%d\n", g_sys_conf.filter[4]); - cfg_file.write(buf, strlen(buf)); - memset(buf, 0, 256); - sprintf(buf, "USERID5=%d\n", g_sys_conf.UserID[4]); - cfg_file.write(buf, strlen(buf)); - memset(buf, 0, 256); - sprintf(buf, "NO5=%d|%d|%d\n", g_sys_conf.no[4][0],g_sys_conf.no[4][1],g_sys_conf.no[4][2]); - cfg_file.write(buf, strlen(buf)); - memset(buf, 0, 256); - sprintf(buf, "SHOOT5=%d\n", g_sys_conf.shoot[4]); - cfg_file.write(buf, strlen(buf)); - memset(buf, 0, 256); - sprintf(buf, "*****************************************\n"); - cfg_file.write(buf, strlen(buf)); + memset(buf, 0, 256); + sprintf(buf, "EXPO5=%d\n", g_sys_conf.expo[4]); + cfg_file.write(buf, strlen(buf)); + memset(buf, 0, 256); + sprintf(buf, "GAIN5=%d\n", g_sys_conf.gain[4]); + cfg_file.write(buf, strlen(buf)); + sprintf(buf, "FILTER5=%d\n", g_sys_conf.filter[4]); + cfg_file.write(buf, strlen(buf)); + memset(buf, 0, 256); + sprintf(buf, "USERID5=%d\n", g_sys_conf.UserID[4]); + cfg_file.write(buf, strlen(buf)); + memset(buf, 0, 256); + sprintf(buf, "NO5=%d|%d|%d\n", g_sys_conf.no[4][0], g_sys_conf.no[4][1], g_sys_conf.no[4][2]); + cfg_file.write(buf, strlen(buf)); + memset(buf, 0, 256); + sprintf(buf, "SHOOT5=%d\n", g_sys_conf.shoot[4]); + cfg_file.write(buf, strlen(buf)); + memset(buf, 0, 256); + sprintf(buf, "*****************************************\n"); + cfg_file.write(buf, strlen(buf)); #endif #if defined(NumberOfSupportedCameras) && (NumberOfSupportedCameras>5) - memset(buf, 0, 256); - sprintf(buf, "EXPO6=%d\n", g_sys_conf.expo[5]); - cfg_file.write(buf, strlen(buf)); - memset(buf, 0, 256); - sprintf(buf, "GAIN6=%d\n", g_sys_conf.gain[5]); - cfg_file.write(buf, strlen(buf)); - memset(buf, 0, 256); - sprintf(buf, "FILTER6=%d\n", g_sys_conf.filter[5]); - cfg_file.write(buf, strlen(buf)); - sprintf(buf, "USERID6=%d\n", g_sys_conf.UserID[5]); - cfg_file.write(buf, strlen(buf)); - memset(buf, 0, 256); - sprintf(buf, "NO6=%d|%d|%d\n", g_sys_conf.no[5][0],g_sys_conf.no[5][1],g_sys_conf.no[5][2]); - cfg_file.write(buf, strlen(buf)); - memset(buf, 0, 256); - sprintf(buf, "SHOOT6=%d\n", g_sys_conf.shoot[5]); - cfg_file.write(buf, strlen(buf)); - memset(buf, 0, 256); - sprintf(buf, "*****************************************\n"); - cfg_file.write(buf, strlen(buf)); + memset(buf, 0, 256); + sprintf(buf, "EXPO6=%d\n", g_sys_conf.expo[5]); + cfg_file.write(buf, strlen(buf)); + memset(buf, 0, 256); + sprintf(buf, "GAIN6=%d\n", g_sys_conf.gain[5]); + cfg_file.write(buf, strlen(buf)); + memset(buf, 0, 256); + sprintf(buf, "FILTER6=%d\n", g_sys_conf.filter[5]); + cfg_file.write(buf, strlen(buf)); + sprintf(buf, "USERID6=%d\n", g_sys_conf.UserID[5]); + cfg_file.write(buf, strlen(buf)); + memset(buf, 0, 256); + sprintf(buf, "NO6=%d|%d|%d\n", g_sys_conf.no[5][0], g_sys_conf.no[5][1], g_sys_conf.no[5][2]); + cfg_file.write(buf, strlen(buf)); + memset(buf, 0, 256); + sprintf(buf, "SHOOT6=%d\n", g_sys_conf.shoot[5]); + cfg_file.write(buf, strlen(buf)); + memset(buf, 0, 256); + sprintf(buf, "*****************************************\n"); + cfg_file.write(buf, strlen(buf)); #endif #if defined(NumberOfSupportedCameras) && (NumberOfSupportedCameras>6) - memset(buf, 0, 256); - sprintf(buf, "EXPO7=%d\n", g_sys_conf.expo[6]); - cfg_file.write(buf, strlen(buf)); - memset(buf, 0, 256); - sprintf(buf, "GAIN7=%d\n", g_sys_conf.gain[6]); - cfg_file.write(buf, strlen(buf)); - memset(buf, 0, 256); - sprintf(buf, "FILTER7=%d\n", g_sys_conf.filter[6]); - cfg_file.write(buf, strlen(buf)); - sprintf(buf, "USERID7=%d\n", g_sys_conf.UserID[6]); - cfg_file.write(buf, strlen(buf)); - memset(buf, 0, 256); - sprintf(buf, "NO7=%d|%d|%d\n", g_sys_conf.no[6][0],g_sys_conf.no[6][1],g_sys_conf.no[6][2]); - cfg_file.write(buf, strlen(buf)); - memset(buf, 0, 256); - sprintf(buf, "SHOOT7=%d\n", g_sys_conf.shoot[6]); - cfg_file.write(buf, strlen(buf)); - memset(buf, 0, 256); - sprintf(buf, "*****************************************\n"); - cfg_file.write(buf, strlen(buf)); + memset(buf, 0, 256); + sprintf(buf, "EXPO7=%d\n", g_sys_conf.expo[6]); + cfg_file.write(buf, strlen(buf)); + memset(buf, 0, 256); + sprintf(buf, "GAIN7=%d\n", g_sys_conf.gain[6]); + cfg_file.write(buf, strlen(buf)); + memset(buf, 0, 256); + sprintf(buf, "FILTER7=%d\n", g_sys_conf.filter[6]); + cfg_file.write(buf, strlen(buf)); + sprintf(buf, "USERID7=%d\n", g_sys_conf.UserID[6]); + cfg_file.write(buf, strlen(buf)); + memset(buf, 0, 256); + sprintf(buf, "NO7=%d|%d|%d\n", g_sys_conf.no[6][0], g_sys_conf.no[6][1], g_sys_conf.no[6][2]); + cfg_file.write(buf, strlen(buf)); + memset(buf, 0, 256); + sprintf(buf, "SHOOT7=%d\n", g_sys_conf.shoot[6]); + cfg_file.write(buf, strlen(buf)); + memset(buf, 0, 256); + sprintf(buf, "*****************************************\n"); + cfg_file.write(buf, strlen(buf)); #endif #if defined(NumberOfSupportedCameras) && (NumberOfSupportedCameras>7) - memset(buf, 0, 256); - sprintf(buf, "EXPO8=%d\n", g_sys_conf.expo[7]); - cfg_file.write(buf, strlen(buf)); - memset(buf, 0, 256); - sprintf(buf, "GAIN8=%d\n", g_sys_conf.gain[7]); - cfg_file.write(buf, strlen(buf)); - memset(buf, 0, 256); - sprintf(buf, "FILTER8=%d\n", g_sys_conf.filter[7]); - cfg_file.write(buf, strlen(buf)); - sprintf(buf, "USERID8=%d\n", g_sys_conf.UserID[7]); - cfg_file.write(buf, strlen(buf)); - memset(buf, 0, 256); - sprintf(buf, "NO8=%d|%d|%d\n", g_sys_conf.no[7][0],g_sys_conf.no[7][1],g_sys_conf.no[7][2]); - cfg_file.write(buf, strlen(buf)); - memset(buf, 0, 256); - sprintf(buf, "SHOOT8=%d\n", g_sys_conf.shoot[7]); - cfg_file.write(buf, strlen(buf)); - memset(buf, 0, 256); - sprintf(buf, "*****************************************\n"); - cfg_file.write(buf, strlen(buf)); + memset(buf, 0, 256); + sprintf(buf, "EXPO8=%d\n", g_sys_conf.expo[7]); + cfg_file.write(buf, strlen(buf)); + memset(buf, 0, 256); + sprintf(buf, "GAIN8=%d\n", g_sys_conf.gain[7]); + cfg_file.write(buf, strlen(buf)); + memset(buf, 0, 256); + sprintf(buf, "FILTER8=%d\n", g_sys_conf.filter[7]); + cfg_file.write(buf, strlen(buf)); + sprintf(buf, "USERID8=%d\n", g_sys_conf.UserID[7]); + cfg_file.write(buf, strlen(buf)); + memset(buf, 0, 256); + sprintf(buf, "NO8=%d|%d|%d\n", g_sys_conf.no[7][0], g_sys_conf.no[7][1], g_sys_conf.no[7][2]); + cfg_file.write(buf, strlen(buf)); + memset(buf, 0, 256); + sprintf(buf, "SHOOT8=%d\n", g_sys_conf.shoot[7]); + cfg_file.write(buf, strlen(buf)); + memset(buf, 0, 256); + sprintf(buf, "*****************************************\n"); + cfg_file.write(buf, strlen(buf)); #endif - memset(buf, 0, 256); - sprintf(buf, "MonitorIP=%s\n", g_sys_conf.MonitorIP.c_str()); - cfg_file.write(buf, strlen(buf)); + memset(buf, 0, 256); + sprintf(buf, "MonitorIP=%s\n", g_sys_conf.MonitorIP.c_str()); + cfg_file.write(buf, strlen(buf)); - memset(buf, 0, 256); - cfg_file.write(buf, strlen(buf)); - sprintf(buf, "MonitorPort=%d\n", g_sys_conf.MonitorPort); - cfg_file.write(buf, strlen(buf)); - } - cfg_file.close(); + memset(buf, 0, 256); + cfg_file.write(buf, strlen(buf)); + sprintf(buf, "MonitorPort=%d\n", g_sys_conf.MonitorPort); + cfg_file.write(buf, strlen(buf)); + } + cfg_file.close(); } #define InitPtrMatDef(a,b)\ @@ -772,79 +772,79 @@ void DialogSetup::write_config() void DialogSetup::InitPtrMat() { #if defined(NumberOfSupportedCameras) && (NumberOfSupportedCameras>0) - InitPtrMatDef(0, 1); + InitPtrMatDef(0, 1); #endif #if defined(NumberOfSupportedCameras) && (NumberOfSupportedCameras>1) - InitPtrMatDef(1, 2); + InitPtrMatDef(1, 2); #endif #if defined(NumberOfSupportedCameras) && (NumberOfSupportedCameras>2) - InitPtrMatDef(2, 3); + InitPtrMatDef(2, 3); #endif #if defined(NumberOfSupportedCameras) && (NumberOfSupportedCameras>3) - InitPtrMatDef(3, 4); + InitPtrMatDef(3, 4); #endif #if defined(NumberOfSupportedCameras) && (NumberOfSupportedCameras>4) - InitPtrMatDef(4, 5); + InitPtrMatDef(4, 5); #endif #if defined(NumberOfSupportedCameras) && (NumberOfSupportedCameras>5) - InitPtrMatDef(5, 6); + InitPtrMatDef(5, 6); #endif #if defined(NumberOfSupportedCameras) && (NumberOfSupportedCameras>6) - InitPtrMatDef(6, 7); + InitPtrMatDef(6, 7); #endif #if defined(NumberOfSupportedCameras) && (NumberOfSupportedCameras>7) - InitPtrMatDef(7, 8); + InitPtrMatDef(7, 8); #endif } void DialogSetup::on_pushButton_config_released() { - if (m_camera_glue)delete m_camera_glue; - m_camera_glue = new camera_glue(this); - connect(m_camera_glue, &camera_glue::sendMsgToDialogSetup,this, &DialogSetup::recMsgFromDialogConfig); - connect(this, &DialogSetup::sendMsgToConfig,m_camera_glue, &camera_glue::recMsgFromDialogSetup); - m_camera_glue->show(); - m_camera_glue->move(this->geometry().center() - m_camera_glue->rect().center());//绉诲姩鐖剁獥鍙d腑蹇冧綅缃 - emit sendMsgToConfig(g_sys_conf.no); + if (m_camera_glue)delete m_camera_glue; + m_camera_glue = new camera_glue(this); + connect(m_camera_glue, &camera_glue::sendMsgToDialogSetup, this, &DialogSetup::recMsgFromDialogConfig); + connect(this, &DialogSetup::sendMsgToConfig, m_camera_glue, &camera_glue::recMsgFromDialogSetup); + m_camera_glue->show(); + m_camera_glue->move(this->geometry().center() - m_camera_glue->rect().center());//绉诲姩鐖剁獥鍙d腑蹇冧綅缃 + emit sendMsgToConfig(g_sys_conf.no); } void DialogSetup::recMsgFromDialogConfig(int ptr[][3]) { - for(int i=0;ishow(); - m_change_shift->move(this->geometry().center() - m_change_shift->rect().center()); - emit sendMsgToShift (g_sys_conf.shiftA, g_sys_conf.shiftB, g_sys_conf.shiftC); + if (m_change_shift)delete m_change_shift; + m_change_shift = new change_shift(this); + connect(m_change_shift, &change_shift::sendMsgToDialogSetup, this, &DialogSetup::recMsgFromChangeShift); + connect(this, &DialogSetup::sendMsgToShift, m_change_shift, &change_shift::recMsgFromDialogSetup); + m_change_shift->show(); + m_change_shift->move(this->geometry().center() - m_change_shift->rect().center()); + emit sendMsgToShift(g_sys_conf.shiftA, g_sys_conf.shiftB, g_sys_conf.shiftC); } void DialogSetup::on_pushButton_statistic_released() { - if (m_output_statistic)delete m_output_statistic; - m_output_statistic = new output_statistic(this); - connect(this, &DialogSetup::sendMsgToOutput, m_output_statistic, &output_statistic::recMsgFromDialogSetup); - m_output_statistic->show(); - m_output_statistic->move(this->geometry().center() - m_output_statistic->rect().center()); - emit sendMsgToOutput(); + if (m_output_statistic)delete m_output_statistic; + m_output_statistic = new output_statistic(this); + connect(this, &DialogSetup::sendMsgToOutput, m_output_statistic, &output_statistic::recMsgFromDialogSetup); + m_output_statistic->show(); + m_output_statistic->move(this->geometry().center() - m_output_statistic->rect().center()); + emit sendMsgToOutput(); } void DialogSetup::recMsgFromChangeShift(QTime timeA, QTime timeB, QTime timeC) { - g_sys_conf.shiftA.setHMS(timeA.hour(), timeA.minute(), 0); - g_sys_conf.shiftB.setHMS(timeB.hour(), timeB.minute(), 0); - g_sys_conf.shiftC.setHMS(timeC.hour(), timeC.minute(), 0); + g_sys_conf.shiftA.setHMS(timeA.hour(), timeA.minute(), 0); + g_sys_conf.shiftB.setHMS(timeB.hour(), timeB.minute(), 0); + g_sys_conf.shiftC.setHMS(timeC.hour(), timeC.minute(), 0); } #ifdef __DEBUG void DialogSetup::on_pushButton_testimg_released() { - emit _testimg(); + emit _testimg(); } void DialogSetup::on_pushButton_testimgs_released() { - emit _testimgs(); + emit _testimgs(); } -#endif \ No newline at end of file +#endif diff --git a/Cigarette/dialogsetup.hpp b/Cigarette/dialogsetup.hpp index 960b6a33..34dc481f 100644 --- a/Cigarette/dialogsetup.hpp +++ b/Cigarette/dialogsetup.hpp @@ -1,73 +1,73 @@ -锘#pragma once +#pragma once #include #include "ui_dialogsetup.h" #include "basecamera.h" #include -#include -#include -#include -#include +#include "common.h" +#include "camera_glue.h" +#include "output_statistic.h" +#include "change_shift.h" class DialogSetup : public QDialog { - Q_OBJECT -signals : - void system_exit(); - void sendMsgToShift(QTime timeA, QTime timeB, QTime timeC); - void sendMsgToOutput(); - void sendMsgToConfig(int ptr[][3]); + Q_OBJECT +signals: + void system_exit(); + void sendMsgToShift(QTime timeA, QTime timeB, QTime timeC); + void sendMsgToOutput(); + void sendMsgToConfig(int ptr[][3]); #ifdef __DEBUG - void _testimg(); - void _testimgs(); + void _testimg(); + void _testimgs(); #endif -private slots : - void on_toolButton_keyboard_released(); - void on_pushButton_exit_released(); - void on_pushButton_save_released(); - void on_pushButton_close_released(); - void on_toolButton_choose_config_path_released(); - void on_toolButton_choose_model_path_released(); - void on_toolButton_choose_path_jpg_released(); - void on_toolButton_choose_save_pics_path_released(); - void on_pushButton_desktop_released(); - void on_pushButton_image_released(); - void on_pushButton_pswd_released(); - void on_pushButton_pswd_op_released(); - void on_pushButton_expo_released(); - void on_pushButton_filter_released(); - void on_pushButton_clear_pic_released(); +private slots: + void on_toolButton_keyboard_released(); + void on_pushButton_exit_released(); + void on_pushButton_save_released(); + void on_pushButton_close_released(); + void on_toolButton_choose_config_path_released(); + void on_toolButton_choose_model_path_released(); + void on_toolButton_choose_path_jpg_released(); + void on_toolButton_choose_save_pics_path_released(); + void on_pushButton_desktop_released(); + void on_pushButton_image_released(); + void on_pushButton_pswd_released(); + void on_pushButton_pswd_op_released(); + void on_pushButton_expo_released(); + void on_pushButton_filter_released(); + void on_pushButton_clear_pic_released(); - void on_pushButton_config_released(); - void on_pushButton_change_released(); - void on_pushButton_statistic_released(); + void on_pushButton_config_released(); + void on_pushButton_change_released(); + void on_pushButton_statistic_released(); - void on_checkBox_auto_open_clicked(bool checked); - void on_checkBox_auto_work_clicked(bool checked); + void on_checkBox_auto_open_clicked(bool checked); + void on_checkBox_auto_work_clicked(bool checked); - void recMsgFromDialogConfig(int ptr[][3]); - void recMsgFromChangeShift(QTime timeA, QTime timeB, QTime timeC); - void onComboBoxSelect(int index); - void onComboBoxConfSelect(int index); - void onComboBoxPicsPathSelect(int index); + void recMsgFromDialogConfig(int ptr[][3]); + void recMsgFromChangeShift(QTime timeA, QTime timeB, QTime timeC); + void onComboBoxSelect(int index); + void onComboBoxConfSelect(int index); + void onComboBoxPicsPathSelect(int index); #ifdef __DEBUG - void on_pushButton_testimg_released(); - void on_pushButton_testimgs_released(); + void on_pushButton_testimg_released(); + void on_pushButton_testimgs_released(); #endif public: - DialogSetup(QWidget * parent = Q_NULLPTR); - ~DialogSetup(); - QLineEdit *lineEdit_expo_mat[NumberOfSupportedCameras]; - QLineEdit *lineEdit_gain_mat[NumberOfSupportedCameras]; - QLineEdit *lineEdit_filter_mat[NumberOfSupportedCameras]; - void InitPtrMat(); - static void write_pswd(); - static void write_pswd_op(); - static void write_config(); - static void write_conf_path(); + DialogSetup(QWidget* parent = Q_NULLPTR); + ~DialogSetup(); + QLineEdit* lineEdit_expo_mat[NumberOfSupportedCameras]; + QLineEdit* lineEdit_gain_mat[NumberOfSupportedCameras]; + QLineEdit* lineEdit_filter_mat[NumberOfSupportedCameras]; + void InitPtrMat(); + static void write_pswd(); + static void write_pswd_op(); + static void write_config(); + static void write_conf_path(); public: - camera_glue *m_camera_glue=NULL; - change_shift *m_change_shift=NULL; - output_statistic *m_output_statistic=NULL; + camera_glue* m_camera_glue = NULL; + change_shift* m_change_shift = NULL; + output_statistic* m_output_statistic = NULL; private: - Ui::DialogSetup ui; + Ui::DialogSetup ui; }; diff --git a/Cigarette/dialogsetuppasswd.cpp b/Cigarette/dialogsetuppasswd.cpp index fa068332..959ae4b1 100644 --- a/Cigarette/dialogsetuppasswd.cpp +++ b/Cigarette/dialogsetuppasswd.cpp @@ -1,4 +1,4 @@ -锘#include "dialogsetuppasswd.hpp" +#include "dialogsetuppasswd.hpp" #include @@ -9,90 +9,90 @@ extern bool g_admin_mode; //鏄惁绠$悊鍛樻ā寮 extern QString g_admin_pswd; //绠$悊鍛樺瘑鐮 -DialogSetupPasswd::DialogSetupPasswd(QWidget * parent) : QDialog(parent) { - ui.setupUi(this); - m_pswd = ""; - this->setWindowFlags(Qt::FramelessWindowHint); +DialogSetupPasswd::DialogSetupPasswd(QWidget* parent) : QDialog(parent) { + ui.setupUi(this); + m_pswd = ""; + this->setWindowFlags(Qt::FramelessWindowHint); } DialogSetupPasswd::~DialogSetupPasswd() { - + } void DialogSetupPasswd::on_pushButton_close_released() { - this->close(); + this->close(); } void DialogSetupPasswd::on_pushButton_clr_released() { - m_pswd = ""; - ui.lineEdit->setText(""); + m_pswd = ""; + ui.lineEdit->setText(""); } void DialogSetupPasswd::on_pushButton_ok_released() { - QString md5Str = QCryptographicHash::hash(m_pswd.toLatin1(), QCryptographicHash::Md5).toHex(); - qDebug() << "m_pswd:" << m_pswd; - qDebug() << "m_pswd md5:" << md5Str; - qDebug() << "g_admin_pswd md5:" << g_admin_pswd; - if (md5Str.compare(g_admin_pswd, Qt::CaseInsensitive) == 0) - { - g_admin_mode = true; - //QMessageBox::information(NULL, QStringLiteral("鎻愮ず娑堟伅"), QStringLiteral("楠岃瘉閫氳繃锛岃繘鍏ョ鐞嗗憳妯″紡"), QMessageBox::Ok); - emit enter_admin(); - this->close(); - } - else { - QMessageBox::information(NULL, QStringLiteral("鎻愮ず娑堟伅"), QStringLiteral("瀵嗙爜閿欒锛岃閲嶆柊杈撳叆"), QMessageBox::Ok); - on_pushButton_clr_released(); - } + QString md5Str = QCryptographicHash::hash(m_pswd.toLatin1(), QCryptographicHash::Md5).toHex(); + qDebug() << "m_pswd:" << m_pswd; + qDebug() << "m_pswd md5:" << md5Str; + qDebug() << "g_admin_pswd md5:" << g_admin_pswd; + if (md5Str.compare(g_admin_pswd, Qt::CaseInsensitive) == 0) + { + g_admin_mode = true; + //QMessageBox::information(NULL, QStringLiteral("鎻愮ず娑堟伅"), QStringLiteral("楠岃瘉閫氳繃锛岃繘鍏ョ鐞嗗憳妯″紡"), QMessageBox::Ok); + emit enter_admin(); + this->close(); + } + else { + QMessageBox::information(NULL, QStringLiteral("鎻愮ず娑堟伅"), QStringLiteral("瀵嗙爜閿欒锛岃閲嶆柊杈撳叆"), QMessageBox::Ok); + on_pushButton_clr_released(); + } } void DialogSetupPasswd::on_pushButton_0_released() { - m_pswd += "0"; - ui.lineEdit->setText(ui.lineEdit->text() + "*"); + m_pswd += "0"; + ui.lineEdit->setText(ui.lineEdit->text() + "*"); } void DialogSetupPasswd::on_pushButton_1_released() { - m_pswd += "1"; - ui.lineEdit->setText(ui.lineEdit->text() + "*"); + m_pswd += "1"; + ui.lineEdit->setText(ui.lineEdit->text() + "*"); } void DialogSetupPasswd::on_pushButton_2_released() { - m_pswd += "2"; - ui.lineEdit->setText(ui.lineEdit->text() + "*"); + m_pswd += "2"; + ui.lineEdit->setText(ui.lineEdit->text() + "*"); } void DialogSetupPasswd::on_pushButton_3_released() { - m_pswd += "3"; - ui.lineEdit->setText(ui.lineEdit->text() + "*"); + m_pswd += "3"; + ui.lineEdit->setText(ui.lineEdit->text() + "*"); } void DialogSetupPasswd::on_pushButton_4_released() { - m_pswd += "4"; - ui.lineEdit->setText(ui.lineEdit->text() + "*"); + m_pswd += "4"; + ui.lineEdit->setText(ui.lineEdit->text() + "*"); } void DialogSetupPasswd::on_pushButton_5_released() { - m_pswd += "5"; - ui.lineEdit->setText(ui.lineEdit->text() + "*"); + m_pswd += "5"; + ui.lineEdit->setText(ui.lineEdit->text() + "*"); } void DialogSetupPasswd::on_pushButton_6_released() { - m_pswd += "6"; - ui.lineEdit->setText(ui.lineEdit->text() + "*"); + m_pswd += "6"; + ui.lineEdit->setText(ui.lineEdit->text() + "*"); } void DialogSetupPasswd::on_pushButton_7_released() { - m_pswd += "7"; - ui.lineEdit->setText(ui.lineEdit->text() + "*"); + m_pswd += "7"; + ui.lineEdit->setText(ui.lineEdit->text() + "*"); } void DialogSetupPasswd::on_pushButton_8_released() { - m_pswd += "8"; - ui.lineEdit->setText(ui.lineEdit->text() + "*"); + m_pswd += "8"; + ui.lineEdit->setText(ui.lineEdit->text() + "*"); } void DialogSetupPasswd::on_pushButton_9_released() { - m_pswd += "9"; - ui.lineEdit->setText(ui.lineEdit->text() + "*"); + m_pswd += "9"; + ui.lineEdit->setText(ui.lineEdit->text() + "*"); } diff --git a/Cigarette/dialogsetuppasswd.hpp b/Cigarette/dialogsetuppasswd.hpp index 9ca27aab..f19c26ee 100644 --- a/Cigarette/dialogsetuppasswd.hpp +++ b/Cigarette/dialogsetuppasswd.hpp @@ -1,35 +1,35 @@ -锘#pragma once +#pragma once #include #include "ui_dialogsetuppasswd.h" class DialogSetupPasswd : public QDialog { - Q_OBJECT -signals : - void enter_admin(); + Q_OBJECT +signals: + void enter_admin(); public: - DialogSetupPasswd(QWidget * parent = Q_NULLPTR); - ~DialogSetupPasswd(); + DialogSetupPasswd(QWidget* parent = Q_NULLPTR); + ~DialogSetupPasswd(); -private slots : - void on_pushButton_close_released(); - void on_pushButton_clr_released(); - void on_pushButton_ok_released(); - void on_pushButton_0_released(); - void on_pushButton_1_released(); - void on_pushButton_2_released(); - void on_pushButton_3_released(); - void on_pushButton_4_released(); - void on_pushButton_5_released(); - void on_pushButton_6_released(); - void on_pushButton_7_released(); - void on_pushButton_8_released(); - void on_pushButton_9_released(); +private slots: + void on_pushButton_close_released(); + void on_pushButton_clr_released(); + void on_pushButton_ok_released(); + void on_pushButton_0_released(); + void on_pushButton_1_released(); + void on_pushButton_2_released(); + void on_pushButton_3_released(); + void on_pushButton_4_released(); + void on_pushButton_5_released(); + void on_pushButton_6_released(); + void on_pushButton_7_released(); + void on_pushButton_8_released(); + void on_pushButton_9_released(); public: - QString m_pswd; + QString m_pswd; private: - Ui::DialogSetupPasswd ui; + Ui::DialogSetupPasswd ui; }; diff --git a/Cigarette/exportData.cpp b/Cigarette/exportData.cpp index a83fba58..f192d524 100644 --- a/Cigarette/exportData.cpp +++ b/Cigarette/exportData.cpp @@ -16,347 +16,347 @@ extern bool flag; ExportDataThread::ExportDataThread(QObject* parent) : QThread(parent) { - cg->read_conf(g_conf_path); - for (int index = 0; index < NumberOfSupportedCameras; index++) - { - XMLError error; - pDocument[index] = new tinyxml2::XMLDocument(); - QString xmlPath = QString(EXPORTDATA_FILE).arg(index); - QString filePath = g_conf_path.config_path + "/" + xmlPath; - - error = pDocument[index]->LoadFile(filePath.toLocal8Bit().constData()); - if (error != XML_SUCCESS) { - XMLDeclaration* declaration = pDocument[index]->NewDeclaration(); - pDocument[index]->InsertFirstChild(declaration); - } - } - - hint = InternetOpen(0, INTERNET_OPEN_TYPE_PRECONFIG, 0, 0, 0); - if (hint == NULL) { - return; - } - if (!ConnectFtp()) - qDebug() << "First connect FTP failed because " << GetLastError(); + cg->read_conf(g_conf_path); + for (int index = 0; index < NumberOfSupportedCameras; index++) + { + XMLError error; + pDocument[index] = new tinyxml2::XMLDocument(); + QString xmlPath = QString(EXPORTDATA_FILE).arg(index); + QString filePath = g_conf_path.config_path + "/" + xmlPath; + + error = pDocument[index]->LoadFile(filePath.toLocal8Bit().constData()); + if (error != XML_SUCCESS) { + XMLDeclaration* declaration = pDocument[index]->NewDeclaration(); + pDocument[index]->InsertFirstChild(declaration); + } + } + + hint = InternetOpen(0, INTERNET_OPEN_TYPE_PRECONFIG, 0, 0, 0); + if (hint == NULL) { + return; + } + if (!ConnectFtp()) + qDebug() << "First connect FTP failed because " << GetLastError(); } void ExportDataThread::init() { - b_quit = false; - flag = false; + b_quit = false; + flag = false; } void ExportDataThread::start_work() { - start(HighestPriority); + start(HighestPriority); } void ExportDataThread::stop() { - b_quit = true; - _XMLExportDataInfo data; - export_XMLData_Info_queue->put(data); - InternetCloseHandle(hftp); - InternetCloseHandle(hint); + b_quit = true; + _XMLExportDataInfo data; + export_XMLData_Info_queue->put(data); + InternetCloseHandle(hftp); + InternetCloseHandle(hint); } bool ExportDataThread::ConnectFtp() { - // FTP地址 - string ftpServer = "192.168.1.170"; - /* 端口号,一般为21 */ - int port = 666; - /* 用户名 */ - string userName = "FTP2"; - /* 密码 */ - string pwd = "123"; - - if (hftp != NULL) { - InternetCloseHandle(hftp); - hftp = NULL; - } - // 创建ftp连接 - hftp = InternetConnectA(hint, ftpServer.c_str(), port, userName.c_str(), pwd.c_str(), INTERNET_SERVICE_FTP, 0, 0); - if (hftp == NULL) { - qDebug() << "ftp connect failed because " << GetLastError(); - return false; - } - else - qDebug() << "ftp reconnect success"; - return true; + // FTP鍦板潃 + string ftpServer = "192.168.1.170"; + /* 绔彛鍙凤紝涓鑸负21 */ + int port = 666; + /* 鐢ㄦ埛鍚 */ + string userName = "FTP2"; + /* 瀵嗙爜 */ + string pwd = "123"; + + if (hftp != NULL) { + InternetCloseHandle(hftp); + hftp = NULL; + } + // 鍒涘缓ftp杩炴帴 + hftp = InternetConnectA(hint, ftpServer.c_str(), port, userName.c_str(), pwd.c_str(), INTERNET_SERVICE_FTP, 0, 0); + if (hftp == NULL) { + qDebug() << "ftp connect failed because " << GetLastError(); + return false; + } + else + qDebug() << "ftp reconnect success"; + return true; } -bool _ExportDataInfo::getAverageData(map &averageData, int index) +bool _ExportDataInfo::getAverageData(map& averageData, int index) { - tinyxml2::XMLDocument doc; - //char xmlPath[256]; - XMLError error; - map data; - //memset(xmlPath, 0, 256); - QString xmlPath = QString(EXPORTDATA_FILE).arg(index); - //sprintf(xmlPath, EXPORTDATA_FILE, index); - QString filePath = g_conf_path.config_path + "/" + xmlPath; - error = doc.LoadFile(filePath.toLocal8Bit().constData()); - if (error != XML_SUCCESS) - if (doc.LoadFile(filePath.toLocal8Bit().constData()) != 0) - { - cout << "load xml file failed" << endl; - return false; - } - XMLElement* root = doc.RootElement(); - XMLElement* userNode = root->FirstChildElement("Camera"); - data["CameraId"] = index; - data["IsNG"] = 0; - data["IsJdExist"] = 0; - data["Total"] = 0; - while (userNode != NULL) - { - if (atoi(userNode->Attribute("Id")) == index) { - data["IsNG"]++; - data["IsJdExist"]++; - data["Total"]++; - XMLElement* IsNgNode = userNode->FirstChildElement("IsNG"); - data["IsNg"] = strcmp(IsNgNode->GetText(), "TRUE"); - XMLElement* IsJdExistNode = userNode->FirstChildElement("IsJdExist"); - if (strcmp(IsJdExistNode->GetText(), "TRUE") == 0) - data["IsJdExist"]++; - XMLElement* TimeCostNode = userNode->FirstChildElement("TimeCost"); - data["TimeCost"] += stof(TimeCostNode->GetText()); - } - userNode = userNode->NextSiblingElement();//下一个兄弟节点 - } - if (data["Total"] == 0) - return false; - data["TimeCost"] = data["TimeCost"] / data["Total"]; - - averageData = data; - - return true; + tinyxml2::XMLDocument doc; + //char xmlPath[256]; + XMLError error; + map data; + //memset(xmlPath, 0, 256); + QString xmlPath = QString(EXPORTDATA_FILE).arg(index); + //sprintf(xmlPath, EXPORTDATA_FILE, index); + QString filePath = g_conf_path.config_path + "/" + xmlPath; + error = doc.LoadFile(filePath.toLocal8Bit().constData()); + if (error != XML_SUCCESS) + if (doc.LoadFile(filePath.toLocal8Bit().constData()) != 0) + { + cout << "load xml file failed" << endl; + return false; + } + XMLElement* root = doc.RootElement(); + XMLElement* userNode = root->FirstChildElement("Camera"); + data["CameraId"] = index; + data["IsNG"] = 0; + data["IsJdExist"] = 0; + data["Total"] = 0; + while (userNode != NULL) + { + if (atoi(userNode->Attribute("Id")) == index) { + data["IsNG"]++; + data["IsJdExist"]++; + data["Total"]++; + XMLElement* IsNgNode = userNode->FirstChildElement("IsNG"); + data["IsNg"] = strcmp(IsNgNode->GetText(), "TRUE"); + XMLElement* IsJdExistNode = userNode->FirstChildElement("IsJdExist"); + if (strcmp(IsJdExistNode->GetText(), "TRUE") == 0) + data["IsJdExist"]++; + XMLElement* TimeCostNode = userNode->FirstChildElement("TimeCost"); + data["TimeCost"] += stof(TimeCostNode->GetText()); + } + userNode = userNode->NextSiblingElement();//涓嬩竴涓厔寮熻妭鐐 + } + if (data["Total"] == 0) + return false; + data["TimeCost"] = data["TimeCost"] / data["Total"]; + + averageData = data; + + return true; } int ExportDataThread::insertXMLNode(const char* xmlPath, _XMLExportDataInfo& data) { - XMLElement* root = pDocument[data.cameraId]->RootElement(); - - if (root == NULL) { - root = pDocument[data.cameraId]->NewElement("Root"); - pDocument[data.cameraId]->InsertEndChild(root); - pDocument[data.cameraId]->SaveFile(xmlPath); - //return 0; - } - - /// 总统计数据 - // 总检测数量 - XMLElement* Total= pDocument[data.cameraId]->NewElement("TotalDatas"); - - XMLElement* time = pDocument[data.cameraId]->NewElement("CurrentTime"); - QString currentTime = QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss"); - time->InsertEndChild(pDocument[data.cameraId]->NewText(currentTime.toStdString().c_str())); - Total->InsertEndChild(time); - - XMLElement* TotalCheckNum = pDocument[data.cameraId]->NewElement("TotalCheckNum"); - char s[20]; - TotalCheckNum->InsertEndChild(pDocument[data.cameraId]->NewText(itoa(data.TotalCheckNum, s, 10))); - Total->InsertEndChild(TotalCheckNum); - - // 总剔除数量 - XMLElement* TotalKickNum = pDocument[data.cameraId]->NewElement("TotalKickNum"); - TotalKickNum->InsertEndChild(pDocument[data.cameraId]->NewText(itoa(data.TotalKickNum, s, 10))); - Total->InsertEndChild(TotalKickNum); - - root->InsertEndChild(Total); - - /// 各相机数据 - // 相机id & 总数 - XMLElement* CameraNode = pDocument[data.cameraId]->NewElement("Camera"); - CameraNode->SetAttribute("Count ", data.cameraTotal); - CameraNode->SetAttribute("Id", data.cameraId); - - XMLElement* JudgeNum = pDocument[data.cameraId]->NewElement("JudgeNum"); - // 各相机检测数量 - XMLElement* checkNum = pDocument[data.cameraId]->NewElement("CheckNum"); - checkNum->InsertEndChild(pDocument[data.cameraId]->NewText(itoa(data.checkNum, s, 10))); - JudgeNum->InsertEndChild(checkNum); - // 各相机ok数量 - XMLElement* okNum = pDocument[data.cameraId]->NewElement("OkNum"); - okNum->InsertEndChild(pDocument[data.cameraId]->NewText(itoa(data.okNum, s, 10))); - JudgeNum->InsertEndChild(okNum); - // 各相机ng数量 - XMLElement* ngNum = pDocument[data.cameraId]->NewElement("NgNum"); - ngNum->InsertEndChild(pDocument[data.cameraId]->NewText(itoa(data.ngNum, s, 10))); - JudgeNum->InsertEndChild(ngNum); - // 各相机实际剔除数量(单通道剔除时为总剔除数量) - XMLElement* kickNum = pDocument[data.cameraId]->NewElement("KickNum"); - kickNum->InsertEndChild(pDocument[data.cameraId]->NewText(itoa(data.kickNum, s, 10))); - JudgeNum->InsertEndChild(kickNum); - - // 合格率 - XMLElement* PassRate = pDocument[data.cameraId]->NewElement("PassRate"); - std::string temp_str = std::to_string(data.PassRate * 100 ) + "%"; - const char* temp_char = temp_str.c_str(); - PassRate->InsertEndChild(pDocument[data.cameraId]->NewText(temp_char)); - JudgeNum->InsertEndChild(PassRate); - - // 剔除率 - XMLElement* KickRate = pDocument[data.cameraId]->NewElement("KickRate"); - temp_str = std::to_string(data.KickRate * 100) + "%"; - temp_char = temp_str.c_str(); - KickRate->InsertEndChild(pDocument[data.cameraId]->NewText(temp_char)); - JudgeNum->InsertEndChild(KickRate); - - // 各相机胶点识别个数 - XMLElement* JdNum = pDocument[data.cameraId]->NewElement("JdNum"); - JdNum->InsertEndChild(pDocument[data.cameraId]->NewText(data.jdNum.toStdString().c_str())); - JudgeNum->InsertEndChild(JdNum); - - XMLElement* shotCounts = pDocument[data.cameraId]->NewElement("ShotCounts"); - shotCounts->InsertEndChild(pDocument[data.cameraId]->NewText(itoa(data.shotCounts, s, 10))); - JudgeNum->InsertEndChild(shotCounts); - - CameraNode->InsertEndChild(JudgeNum); - - // 各相机采集速度 - XMLElement* speed = pDocument[data.cameraId]->NewElement("Speed"); - - XMLElement* AcquisitionSpeed = pDocument[data.cameraId]->NewElement("AcquisitionSpeed"); - AcquisitionSpeed->InsertEndChild(pDocument[data.cameraId]->NewText(data.AcquisitionSpeed.toStdString().c_str())); - speed->InsertEndChild(AcquisitionSpeed); - // 各相机检测速度 - XMLElement* DetectSpeed = pDocument[data.cameraId]->NewElement("DetectSpeed"); - DetectSpeed->InsertEndChild(pDocument[data.cameraId]->NewText(data.DetectSpeed.toStdString().c_str())); - speed->InsertEndChild(DetectSpeed); - CameraNode->InsertEndChild(speed); - - root->InsertEndChild(CameraNode); - - return pDocument[data.cameraId]->SaveFile(xmlPath); + XMLElement* root = pDocument[data.cameraId]->RootElement(); + + if (root == NULL) { + root = pDocument[data.cameraId]->NewElement("Root"); + pDocument[data.cameraId]->InsertEndChild(root); + pDocument[data.cameraId]->SaveFile(xmlPath); + //return 0; + } + + /// 鎬荤粺璁℃暟鎹 + // 鎬绘娴嬫暟閲 + XMLElement* Total = pDocument[data.cameraId]->NewElement("TotalDatas"); + + XMLElement* time = pDocument[data.cameraId]->NewElement("CurrentTime"); + QString currentTime = QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss"); + time->InsertEndChild(pDocument[data.cameraId]->NewText(currentTime.toStdString().c_str())); + Total->InsertEndChild(time); + + XMLElement* TotalCheckNum = pDocument[data.cameraId]->NewElement("TotalCheckNum"); + char s[20]; + TotalCheckNum->InsertEndChild(pDocument[data.cameraId]->NewText(itoa(data.TotalCheckNum, s, 10))); + Total->InsertEndChild(TotalCheckNum); + + // 鎬诲墧闄ゆ暟閲 + XMLElement* TotalKickNum = pDocument[data.cameraId]->NewElement("TotalKickNum"); + TotalKickNum->InsertEndChild(pDocument[data.cameraId]->NewText(itoa(data.TotalKickNum, s, 10))); + Total->InsertEndChild(TotalKickNum); + + root->InsertEndChild(Total); + + /// 鍚勭浉鏈烘暟鎹 + // 鐩告満id & 鎬绘暟 + XMLElement* CameraNode = pDocument[data.cameraId]->NewElement("Camera"); + CameraNode->SetAttribute("Count ", data.cameraTotal); + CameraNode->SetAttribute("Id", data.cameraId); + + XMLElement* JudgeNum = pDocument[data.cameraId]->NewElement("JudgeNum"); + // 鍚勭浉鏈烘娴嬫暟閲 + XMLElement* checkNum = pDocument[data.cameraId]->NewElement("CheckNum"); + checkNum->InsertEndChild(pDocument[data.cameraId]->NewText(itoa(data.checkNum, s, 10))); + JudgeNum->InsertEndChild(checkNum); + // 鍚勭浉鏈簅k鏁伴噺 + XMLElement* okNum = pDocument[data.cameraId]->NewElement("OkNum"); + okNum->InsertEndChild(pDocument[data.cameraId]->NewText(itoa(data.okNum, s, 10))); + JudgeNum->InsertEndChild(okNum); + // 鍚勭浉鏈簄g鏁伴噺 + XMLElement* ngNum = pDocument[data.cameraId]->NewElement("NgNum"); + ngNum->InsertEndChild(pDocument[data.cameraId]->NewText(itoa(data.ngNum, s, 10))); + JudgeNum->InsertEndChild(ngNum); + // 鍚勭浉鏈哄疄闄呭墧闄ゆ暟閲忥紙鍗曢氶亾鍓旈櫎鏃朵负鎬诲墧闄ゆ暟閲忥級 + XMLElement* kickNum = pDocument[data.cameraId]->NewElement("KickNum"); + kickNum->InsertEndChild(pDocument[data.cameraId]->NewText(itoa(data.kickNum, s, 10))); + JudgeNum->InsertEndChild(kickNum); + + // 鍚堟牸鐜 + XMLElement* PassRate = pDocument[data.cameraId]->NewElement("PassRate"); + std::string temp_str = std::to_string(data.PassRate * 100) + "%"; + const char* temp_char = temp_str.c_str(); + PassRate->InsertEndChild(pDocument[data.cameraId]->NewText(temp_char)); + JudgeNum->InsertEndChild(PassRate); + + // 鍓旈櫎鐜 + XMLElement* KickRate = pDocument[data.cameraId]->NewElement("KickRate"); + temp_str = std::to_string(data.KickRate * 100) + "%"; + temp_char = temp_str.c_str(); + KickRate->InsertEndChild(pDocument[data.cameraId]->NewText(temp_char)); + JudgeNum->InsertEndChild(KickRate); + + // 鍚勭浉鏈鸿兌鐐硅瘑鍒釜鏁 + XMLElement* JdNum = pDocument[data.cameraId]->NewElement("JdNum"); + JdNum->InsertEndChild(pDocument[data.cameraId]->NewText(data.jdNum.toStdString().c_str())); + JudgeNum->InsertEndChild(JdNum); + + XMLElement* shotCounts = pDocument[data.cameraId]->NewElement("ShotCounts"); + shotCounts->InsertEndChild(pDocument[data.cameraId]->NewText(itoa(data.shotCounts, s, 10))); + JudgeNum->InsertEndChild(shotCounts); + + CameraNode->InsertEndChild(JudgeNum); + + // 鍚勭浉鏈洪噰闆嗛熷害 + XMLElement* speed = pDocument[data.cameraId]->NewElement("Speed"); + + XMLElement* AcquisitionSpeed = pDocument[data.cameraId]->NewElement("AcquisitionSpeed"); + AcquisitionSpeed->InsertEndChild(pDocument[data.cameraId]->NewText(data.AcquisitionSpeed.toStdString().c_str())); + speed->InsertEndChild(AcquisitionSpeed); + // 鍚勭浉鏈烘娴嬮熷害 + XMLElement* DetectSpeed = pDocument[data.cameraId]->NewElement("DetectSpeed"); + DetectSpeed->InsertEndChild(pDocument[data.cameraId]->NewText(data.DetectSpeed.toStdString().c_str())); + speed->InsertEndChild(DetectSpeed); + CameraNode->InsertEndChild(speed); + + root->InsertEndChild(CameraNode); + + return pDocument[data.cameraId]->SaveFile(xmlPath); } void ExportDataThread::run() { - while (!b_quit) { - _XMLExportDataInfo element; - export_XMLData_Info_queue->take(element); - - if (element.cameraId != -1 && flag) { - char buf[256]; - memset(buf, 0, 256); - QString xmlPath = QString(EXPORTDATA_FILE).arg(element.cameraId); - QString filePath = g_conf_path.config_path + "/" + xmlPath; - sprintf(buf, filePath.toLocal8Bit().constData(), element.cameraId); - insertXMLNode(buf, element); - QString remotePath = "/tmp/" + xmlPath; - ConnectServer(filePath, remotePath); - } - } - flag = false; - - for (int index = 0; index < NumberOfSupportedCameras; index++) { - pDocument[index]->~XMLDocument(); - } + while (!b_quit) { + _XMLExportDataInfo element; + export_XMLData_Info_queue->take(element); + + if (element.cameraId != -1 && flag) { + char buf[256]; + memset(buf, 0, 256); + QString xmlPath = QString(EXPORTDATA_FILE).arg(element.cameraId); + QString filePath = g_conf_path.config_path + "/" + xmlPath; + sprintf(buf, filePath.toLocal8Bit().constData(), element.cameraId); + insertXMLNode(buf, element); + QString remotePath = "/tmp/" + xmlPath; + ConnectServer(filePath, remotePath); + } + } + flag = false; + + for (int index = 0; index < NumberOfSupportedCameras; index++) { + pDocument[index]->~XMLDocument(); + } } -//*****************************************已经调试好,没有理清逻辑前不要动********************** +//*****************************************宸茬粡璋冭瘯濂斤紝娌℃湁鐞嗘竻閫昏緫鍓嶄笉瑕佸姩********************** void ExportDataThread::check_save_dir(std::string dir_path) { - // 如果目的路径不存在,一级一级创建 - // 目的路径格式为:"./dir/dir1/.../" - - if (FALSE == FtpSetCurrentDirectoryA(hftp, dir_path.c_str())) { - FtpSetCurrentDirectoryA(hftp, "/"); - int pos = 1; - while (pos > 0) { - // 从第二个“/”开始依次找到目的路径中的“/”位置 - pos = dir_path.find_first_of('/', pos + 1); - if (pos == -1) - break; - string tempPath = dir_path.substr(0, pos + 1); - FtpCreateDirectoryA(hftp, tempPath.c_str()); - } - //FtpSetCurrentDirectoryA(hftp, dir_path.c_str()); - } + // 濡傛灉鐩殑璺緞涓嶅瓨鍦紝涓绾т竴绾у垱寤 + // 鐩殑璺緞鏍煎紡涓:"./dir/dir1/.../" + + if (FALSE == FtpSetCurrentDirectoryA(hftp, dir_path.c_str())) { + FtpSetCurrentDirectoryA(hftp, "/"); + int pos = 1; + while (pos > 0) { + // 浠庣浜屼釜鈥/鈥濆紑濮嬩緷娆℃壘鍒扮洰鐨勮矾寰勪腑鐨勨/鈥濅綅缃 + pos = dir_path.find_first_of('/', pos + 1); + if (pos == -1) + break; + string tempPath = dir_path.substr(0, pos + 1); + FtpCreateDirectoryA(hftp, tempPath.c_str()); + } + //FtpSetCurrentDirectoryA(hftp, dir_path.c_str()); + } } -void ExportDataThread::EDrecMsgFromCigarette(){ - flag = true; +void ExportDataThread::EDrecMsgFromCigarette() { + flag = true; } void ExportDataThread::ConnectServer(QString srcPath, QString destPath) { - string filePath = srcPath.toLocal8Bit().constData(); - string remotePath = destPath.toLocal8Bit().constData(); - - std::vector files; - // 判断上传的是文件还是文件夹标识 - int size = 0; - struct stat st; - stat(filePath.c_str(), &st); - if (st.st_mode & S_IFDIR) { - //qDebug() << "filePath is Directory"; - // 获取文件夹下所有文件名 - GetFiles(filePath, files); - size = files.size(); - } - - // 上传文件源为一个文件 - if (size == 0) { - int pos = remotePath.find_last_of('/'); - string destFileName = remotePath.substr(pos + 1); - string tempPath = remotePath.substr(0, pos + 1); - check_save_dir(tempPath); - - if (!InternetGetConnectedState(NULL, 0)) { - qDebug() << "计算机未连接到互联网"; - } - else { - while (!FtpPutFileA(hftp, filePath.c_str(), remotePath.c_str(), FTP_TRANSFER_TYPE_BINARY, 0)) { - qDebug() << "ftp put file "<< filePath.c_str() << "failed because" << GetLastError(); - if (!ConnectFtp()) - qDebug() << "connect FTP failed because " << GetLastError(); - } - } - } - // 上传源为一个文件夹 - else{ - for (int i = 0; i < size; i++) { - string tempFilePath = (string(files[i]).erase(0, filePath.length() + 1)).c_str(); - // 获取上传路径中的文件名 - int pos = tempFilePath.find_last_of('/'); - string destFileName = tempFilePath.substr(pos + 1); - check_save_dir(remotePath + tempFilePath.substr(0, pos + 1)); - if(!FtpPutFileA(hftp, files[i].c_str(), destFileName.c_str(), FTP_TRANSFER_TYPE_BINARY, 0)) - qDebug() << "ftp put files failed because " << GetLastError(); - } - } + string filePath = srcPath.toLocal8Bit().constData(); + string remotePath = destPath.toLocal8Bit().constData(); + + std::vector files; + // 鍒ゆ柇涓婁紶鐨勬槸鏂囦欢杩樻槸鏂囦欢澶规爣璇 + int size = 0; + struct stat st; + stat(filePath.c_str(), &st); + if (st.st_mode & S_IFDIR) { + //qDebug() << "filePath is Directory"; + // 鑾峰彇鏂囦欢澶逛笅鎵鏈夋枃浠跺悕 + GetFiles(filePath, files); + size = files.size(); + } + + // 涓婁紶鏂囦欢婧愪负涓涓枃浠 + if (size == 0) { + int pos = remotePath.find_last_of('/'); + string destFileName = remotePath.substr(pos + 1); + string tempPath = remotePath.substr(0, pos + 1); + check_save_dir(tempPath); + + if (!InternetGetConnectedState(NULL, 0)) { + qDebug() << "璁$畻鏈烘湭杩炴帴鍒颁簰鑱旂綉"; + } + else { + while (!FtpPutFileA(hftp, filePath.c_str(), remotePath.c_str(), FTP_TRANSFER_TYPE_BINARY, 0)) { + qDebug() << "ftp put file " << filePath.c_str() << "failed because" << GetLastError(); + if (!ConnectFtp()) + qDebug() << "connect FTP failed because " << GetLastError(); + } + } + } + // 涓婁紶婧愪负涓涓枃浠跺す + else { + for (int i = 0; i < size; i++) { + string tempFilePath = (string(files[i]).erase(0, filePath.length() + 1)).c_str(); + // 鑾峰彇涓婁紶璺緞涓殑鏂囦欢鍚 + int pos = tempFilePath.find_last_of('/'); + string destFileName = tempFilePath.substr(pos + 1); + check_save_dir(remotePath + tempFilePath.substr(0, pos + 1)); + if (!FtpPutFileA(hftp, files[i].c_str(), destFileName.c_str(), FTP_TRANSFER_TYPE_BINARY, 0)) + qDebug() << "ftp put files failed because " << GetLastError(); + } + } } void ExportDataThread::GetDataFromSaveThread(QString filePath) { - QString remotePath; - remotePath = filePath.mid(filePath.indexOf("image") - 1); - ConnectServer(filePath, remotePath); + QString remotePath; + remotePath = filePath.mid(filePath.indexOf("image") - 1); + ConnectServer(filePath, remotePath); } -//*****************************************已经调试好,没有理清逻辑前不要动********************** +//*****************************************宸茬粡璋冭瘯濂斤紝娌℃湁鐞嗘竻閫昏緫鍓嶄笉瑕佸姩********************** void ExportDataThread::GetFiles(string path, std::vector& files) { - //文件句柄 - intptr_t hFile = 0; - //文件信息的结构体 - struct _finddata_t fileinfo; - string p; - if ((hFile = _findfirst(p.assign(path).append("\\*").c_str(), &fileinfo)) != -1) - { - // "\\*"是指读取文件夹下的所有类型的文件 - do - { - //如果是目录,迭代之 - //如果不是,加入列表 - if ((fileinfo.attrib & _A_SUBDIR)) - { - if (strcmp(fileinfo.name, ".") != 0 && strcmp(fileinfo.name, "..") != 0) - GetFiles(p.assign(path).append("/").append(fileinfo.name), files); - } - else - { - files.push_back(p.assign(path).append("/").append(fileinfo.name)); - } - } while (_findnext(hFile, &fileinfo) == 0); - _findclose(hFile); - } -} \ No newline at end of file + //鏂囦欢鍙ユ焺 + intptr_t hFile = 0; + //鏂囦欢淇℃伅鐨勭粨鏋勪綋 + struct _finddata_t fileinfo; + string p; + if ((hFile = _findfirst(p.assign(path).append("\\*").c_str(), &fileinfo)) != -1) + { + // "\\*"鏄寚璇诲彇鏂囦欢澶逛笅鐨勬墍鏈夌被鍨嬬殑鏂囦欢 + do + { + //濡傛灉鏄洰褰,杩唬涔 + //濡傛灉涓嶆槸,鍔犲叆鍒楄〃 + if ((fileinfo.attrib & _A_SUBDIR)) + { + if (strcmp(fileinfo.name, ".") != 0 && strcmp(fileinfo.name, "..") != 0) + GetFiles(p.assign(path).append("/").append(fileinfo.name), files); + } + else + { + files.push_back(p.assign(path).append("/").append(fileinfo.name)); + } + } while (_findnext(hFile, &fileinfo) == 0); + _findclose(hFile); + } +} diff --git a/Cigarette/exportData.h b/Cigarette/exportData.h index 5b67c4d2..925cc92f 100644 --- a/Cigarette/exportData.h +++ b/Cigarette/exportData.h @@ -18,81 +18,81 @@ using namespace tinyxml2; class _XMLExportDataInfo { public: - // 总的统计数据 - long long cameraTotal; - int TotalCheckNum; // 总检测数量 - int TotalKickNum; // 总剔除数量 - double PassRate; // 合格率 - double KickRate; // 剔除率 - // 各相机数据 - int cameraId; - int shotCounts; // 拍摄张数 - int checkNum; // 各相机检测个数 - int okNum; // 各相机ok数量 - int ngNum; // 各相机ng数量 - int kickNum; // 各相机实际剔除数量(单通道剔除时为总剔除数量) - QString AcquisitionSpeed; // 各相机采集速度 - QString jdNum; // 各相机胶点识别个数 - QString DetectSpeed; // 各相机检测速度(识别时间) - - _XMLExportDataInfo() { - // 总的统计数据 - TotalCheckNum = 0; // 总检测数量 - TotalKickNum = 0; // 总剔除数量 - PassRate = 0.0; // 合格率 - KickRate = 0.0; // 剔除率 - cameraId = -1; - jdNum = QString("0,0,0"); - // 各相机数据 - shotCounts = 0; - checkNum = 0; - okNum = 0; - ngNum = 0; - kickNum = 0; // 各相机实际剔除数量(单通道剔除时为总剔除数量) - AcquisitionSpeed = "0"; // 各相机采集速度 - DetectSpeed = "0"; // 各相机检测速度 - } + // 鎬荤殑缁熻鏁版嵁 + long long cameraTotal; + int TotalCheckNum; // 鎬绘娴嬫暟閲 + int TotalKickNum; // 鎬诲墧闄ゆ暟閲 + double PassRate; // 鍚堟牸鐜 + double KickRate; // 鍓旈櫎鐜 + // 鍚勭浉鏈烘暟鎹 + int cameraId; + int shotCounts; // 鎷嶆憚寮犳暟 + int checkNum; // 鍚勭浉鏈烘娴嬩釜鏁 + int okNum; // 鍚勭浉鏈簅k鏁伴噺 + int ngNum; // 鍚勭浉鏈簄g鏁伴噺 + int kickNum; // 鍚勭浉鏈哄疄闄呭墧闄ゆ暟閲忥紙鍗曢氶亾鍓旈櫎鏃朵负鎬诲墧闄ゆ暟閲忥級 + QString AcquisitionSpeed; // 鍚勭浉鏈洪噰闆嗛熷害 + QString jdNum; // 鍚勭浉鏈鸿兌鐐硅瘑鍒釜鏁 + QString DetectSpeed; // 鍚勭浉鏈烘娴嬮熷害(璇嗗埆鏃堕棿) + + _XMLExportDataInfo() { + // 鎬荤殑缁熻鏁版嵁 + TotalCheckNum = 0; // 鎬绘娴嬫暟閲 + TotalKickNum = 0; // 鎬诲墧闄ゆ暟閲 + PassRate = 0.0; // 鍚堟牸鐜 + KickRate = 0.0; // 鍓旈櫎鐜 + cameraId = -1; + jdNum = QString("0,0,0"); + // 鍚勭浉鏈烘暟鎹 + shotCounts = 0; + checkNum = 0; + okNum = 0; + ngNum = 0; + kickNum = 0; // 鍚勭浉鏈哄疄闄呭墧闄ゆ暟閲忥紙鍗曢氶亾鍓旈櫎鏃朵负鎬诲墧闄ゆ暟閲忥級 + AcquisitionSpeed = "0"; // 鍚勭浉鏈洪噰闆嗛熷害 + DetectSpeed = "0"; // 鍚勭浉鏈烘娴嬮熷害 + } }; class _ExportDataInfo { - struct JdPoint //创建点的数据 - { - string x; - string y; - }; + struct JdPoint //鍒涘缓鐐圭殑鏁版嵁 + { + string x; + string y; + }; public: - int cameraId; - int shotCounts; - int jd[20]; - string timeCost; - float jdInterval; - bool isNg; - bool isJdExist[20]; - long long cameraTotal; - std::vector jdPointsLocation; - float jdSize[20]; - - bool getAverageData(map& averageData, int index); - - string getPoint(int index) { - string point = "("; - point += jdPointsLocation.at(index).x + ',' + jdPointsLocation.at(index).y + ')'; - return point; - } - - _ExportDataInfo() - { - cameraId = -1; - jdInterval = 0.0; - isNg = false; - for (int i = 0; i < 20; i++)isJdExist[i] = false; - for (int i = 0; i < 20; i++)jd[i] = 0; - timeCost = "0ms"; - for (int i = 0; i < 20; i++)jdSize[i] = 0.0; - shotCounts = 0; - } + int cameraId; + int shotCounts; + int jd[20]; + string timeCost; + float jdInterval; + bool isNg; + bool isJdExist[20]; + long long cameraTotal; + std::vector jdPointsLocation; + float jdSize[20]; + + bool getAverageData(map& averageData, int index); + + string getPoint(int index) { + string point = "("; + point += jdPointsLocation.at(index).x + ',' + jdPointsLocation.at(index).y + ')'; + return point; + } + + _ExportDataInfo() + { + cameraId = -1; + jdInterval = 0.0; + isNg = false; + for (int i = 0; i < 20; i++)isJdExist[i] = false; + for (int i = 0; i < 20; i++)jd[i] = 0; + timeCost = "0ms"; + for (int i = 0; i < 20; i++)jdSize[i] = 0.0; + shotCounts = 0; + } }; //extern SyncQueue<_ExportDataInfo>* export_Data_Info_queue; @@ -100,41 +100,41 @@ extern SyncQueue<_XMLExportDataInfo>* export_XMLData_Info_queue; class ExportDataThread : public QThread { - Q_OBJECT + Q_OBJECT signals: public: - ExportDataThread(QObject* parent = 0); - ~ExportDataThread() - { - stop(); - //export_Data_Info_queue->put(data); - quit(); - wait(); - } - - void init(); - void start_work(); - void stop(); - //int insertXMLNode(const char* xmlPath, _ExportDataInfo& data); - int insertXMLNode(const char* xmlPath, _XMLExportDataInfo& data); - bool ConnectFtp(); - void ConnectServer(QString srcPath, QString destPath); - void GetFiles(string path, std::vector& files); + ExportDataThread(QObject* parent = 0); + ~ExportDataThread() + { + stop(); + //export_Data_Info_queue->put(data); + quit(); + wait(); + } + + void init(); + void start_work(); + void stop(); + //int insertXMLNode(const char* xmlPath, _ExportDataInfo& data); + int insertXMLNode(const char* xmlPath, _XMLExportDataInfo& data); + bool ConnectFtp(); + void ConnectServer(QString srcPath, QString destPath); + void GetFiles(string path, std::vector& files); protected: - void run(); - void check_save_dir(std::string dir_path); + void run(); + void check_save_dir(std::string dir_path); public: - bool b_quit; - tinyxml2::XMLDocument *pDocument[NumberOfSupportedCameras]; - //int flag; + bool b_quit; + tinyxml2::XMLDocument* pDocument[NumberOfSupportedCameras]; + //int flag; - HINTERNET hint = NULL; - HINTERNET hftp = NULL; + HINTERNET hint = NULL; + HINTERNET hftp = NULL; public slots: - void EDrecMsgFromCigarette(); - void GetDataFromSaveThread(QString filePath); + void EDrecMsgFromCigarette(); + void GetDataFromSaveThread(QString filePath); }; diff --git a/Cigarette/hikcamera.cpp b/Cigarette/hikcamera.cpp index 1405ba55..5a2aafb0 100644 --- a/Cigarette/hikcamera.cpp +++ b/Cigarette/hikcamera.cpp @@ -18,21 +18,21 @@ HIKCamera::~HIKCamera() int HIKCamera::Enumerate() { - int status = 0; - - // ch:鏋氫妇璁惧 | Enum device - - memset(&stDeviceList, 0, sizeof(MV_CC_DEVICE_INFO_LIST)); - - status = MV_CC_EnumDevices(MV_GIGE_DEVICE| MV_USB_DEVICE, &stDeviceList); - - if (MV_OK == status) - { - return stDeviceList.nDeviceNum; - } - else - { - return 0; - } - + int status = 0; + + // ch:鏋氫妇璁惧 | Enum device + + memset(&stDeviceList, 0, sizeof(MV_CC_DEVICE_INFO_LIST)); + + status = MV_CC_EnumDevices(MV_GIGE_DEVICE | MV_USB_DEVICE, &stDeviceList); + + if (MV_OK == status) + { + return stDeviceList.nDeviceNum; + } + else + { + return 0; + } + } diff --git a/Cigarette/hikcamera.h b/Cigarette/hikcamera.h index de998ad5..286e8632 100644 --- a/Cigarette/hikcamera.h +++ b/Cigarette/hikcamera.h @@ -6,15 +6,15 @@ #define HIKClassID 0x03 -class HIKCamera: public BaseCamera +class HIKCamera : public BaseCamera { public: - HIKCamera(int DeviceNum); - ~HIKCamera(); + HIKCamera(int DeviceNum); + ~HIKCamera(); - static int Enumerate(); + static int Enumerate(); public: - static MV_CC_DEVICE_INFO_LIST stDeviceList; + static MV_CC_DEVICE_INFO_LIST stDeviceList; }; diff --git a/Cigarette/main.cpp b/Cigarette/main.cpp index 49f2e49c..72dd525d 100644 --- a/Cigarette/main.cpp +++ b/Cigarette/main.cpp @@ -7,23 +7,23 @@ #include "CryptoToolLib.h" #endif -int main(int argc, char *argv[]) +int main(int argc, char* argv[]) { #if defined LICENSE_VERIFY - if(!VerifyLicense()) - { - exit(0); - } + if (!VerifyLicense()) + { + exit(0); + } #endif - qRegisterMetaType("cv::Mat"); - QApplication a(argc, argv); - QPixmap pixmap("D:/Release/splash.jpg"); - QSplashScreen splash(pixmap); - splash.show(); - a.processEvents(); - Cigarette w; - w.show(); - //w.showFullScreen(); - splash.finish(&w); - return a.exec(); + qRegisterMetaType("cv::Mat"); + QApplication a(argc, argv); + QPixmap pixmap("D:/Release/splash.jpg"); + QSplashScreen splash(pixmap); + splash.show(); + a.processEvents(); + Cigarette w; + w.show(); + //w.showFullScreen(); + splash.finish(&w); + return a.exec(); } diff --git a/Cigarette/output_statistic.cpp b/Cigarette/output_statistic.cpp index c0981d91..bdbb0fbb 100644 --- a/Cigarette/output_statistic.cpp +++ b/Cigarette/output_statistic.cpp @@ -9,35 +9,35 @@ extern ConfPath g_conf_path; #define output_init(a, b)\ textBrowser_mat[a] = ui.textBrowser_##b; -output_statistic::output_statistic(QDialog *parent) - : QDialog(parent) +output_statistic::output_statistic(QDialog* parent) + : QDialog(parent) { - ui.setupUi(this); - this->setWindowFlags(windowFlags()&~Qt::WindowContextHelpButtonHint); + ui.setupUi(this); + this->setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint); #if defined(NumberOfSupportedCameras) && (NumberOfSupportedCameras > 0) - output_init(0, 1); + output_init(0, 1); #endif #if defined(NumberOfSupportedCameras) && (NumberOfSupportedCameras > 1) - output_init(1, 2); + output_init(1, 2); #endif #if defined(NumberOfSupportedCameras) && (NumberOfSupportedCameras > 2) - output_init(2, 3); + output_init(2, 3); #endif #if defined(NumberOfSupportedCameras) && (NumberOfSupportedCameras > 3) - output_init(3, 4); + output_init(3, 4); #endif #if defined(NumberOfSupportedCameras) && (NumberOfSupportedCameras > 4) - output_init(4, 5); + output_init(4, 5); #endif #if defined(NumberOfSupportedCameras) && (NumberOfSupportedCameras > 5) - output_init(5, 6); + output_init(5, 6); #endif #if defined(NumberOfSupportedCameras) && (NumberOfSupportedCameras > 6) - output_init(6, 7); + output_init(6, 7); #endif #if defined(NumberOfSupportedCameras) && (NumberOfSupportedCameras > 7) - output_init(7, 8); + output_init(7, 8); #endif } @@ -47,23 +47,23 @@ output_statistic::~output_statistic() void output_statistic::recMsgFromDialogSetup() { - QString file_path, file_name; - QFile file; - for (int i = 0; i < NumberOfSupportedCameras; i++) { - file_name = QString(STATISTIC_FILE).arg(i); - file_path = g_conf_path.config_path + "/" + file_name; - file.setFileName(file_path); - if (file.open(QIODevice::ReadOnly | QIODevice::Text)) - { - QTextStream in(&file); - //in.setCodec("UTF-8"); - textBrowser_mat[i]->setText(in.readAll()); - } - else { - std::cout << "can not open statistic file" << std::endl; - } - file.close(); - this->show(); - } - //this->show(); -} \ No newline at end of file + QString file_path, file_name; + QFile file; + for (int i = 0; i < NumberOfSupportedCameras; i++) { + file_name = QString(STATISTIC_FILE).arg(i); + file_path = g_conf_path.config_path + "/" + file_name; + file.setFileName(file_path); + if (file.open(QIODevice::ReadOnly | QIODevice::Text)) + { + QTextStream in(&file); + //in.setCodec("UTF-8"); + textBrowser_mat[i]->setText(in.readAll()); + } + else { + std::cout << "can not open statistic file" << std::endl; + } + file.close(); + this->show(); + } + //this->show(); +} diff --git a/Cigarette/output_statistic.h b/Cigarette/output_statistic.h index 3738d3db..9f7c4b61 100644 --- a/Cigarette/output_statistic.h +++ b/Cigarette/output_statistic.h @@ -6,16 +6,16 @@ class output_statistic : public QDialog { - Q_OBJECT + Q_OBJECT public: - output_statistic(QDialog *parent = Q_NULLPTR); - ~output_statistic(); + output_statistic(QDialog* parent = Q_NULLPTR); + ~output_statistic(); private: - Ui::output_statistic ui; - QTextBrowser* textBrowser_mat[NumberOfSupportedCameras]; + Ui::output_statistic ui; + QTextBrowser* textBrowser_mat[NumberOfSupportedCameras]; public slots: - void recMsgFromDialogSetup(); + void recMsgFromDialogSetup(); }; diff --git a/Cigarette/plc_item.h b/Cigarette/plc_item.h index 163b5940..1e66905b 100644 --- a/Cigarette/plc_item.h +++ b/Cigarette/plc_item.h @@ -4,12 +4,12 @@ class PlcItem { public: - PlcItem(); - ~PlcItem(); + PlcItem(); + ~PlcItem(); public: - std::string func_desc; //功能描述 - int address; //modbus地址 - std::string memo; //备注 - int value; //初始值 + std::string func_desc; //鍔熻兘鎻忚堪 + int address; //modbus鍦板潃 + std::string memo; //澶囨敞 + int value; //鍒濆鍊 }; diff --git a/Cigarette/plcsetup.cpp b/Cigarette/plcsetup.cpp index 1d4928c0..37166aca 100644 --- a/Cigarette/plcsetup.cpp +++ b/Cigarette/plcsetup.cpp @@ -10,288 +10,288 @@ #include "PLCDevice.h" #define PLC_ITEM_FILE "plc.txt" -extern PLCDevice * m_PLCDevice; +extern PLCDevice* m_PLCDevice; extern ConfPath g_conf_path; extern bool g_plc_dialog_open; //鏄惁鎵撳紑plc閰嶇疆瀵硅瘽妗 void task_osk_() { - system("start /b C:\\Windows\\system32\\osk.exe"); + system("start /b C:\\Windows\\system32\\osk.exe"); } -PlcSetup::PlcSetup(QWidget * parent) : QDialog(parent) { - ui.setupUi(this); - this->setWindowFlags(Qt::FramelessWindowHint); - read_plc_items(); - ui.tableWidget->setColumnCount(7); - ui.tableWidget->setRowCount(m_plc_items.size()); - QStringList header_list; - header_list << QStringLiteral("鍔熻兘鎻忚堪") << QStringLiteral("璇绘暟鍊") - << QStringLiteral("璇绘搷浣") << QStringLiteral("鍐欐暟鍊") << QStringLiteral("鍐欐搷浣") << QStringLiteral("淇濆瓨") << QStringLiteral("澶囨敞") ; - ui.tableWidget->setHorizontalHeaderLabels(header_list); - ui.tableWidget->setColumnWidth(0, 200); - ui.tableWidget->setColumnWidth(1, 100); - ui.tableWidget->setColumnWidth(2, 50); - ui.tableWidget->setColumnWidth(3, 100); - ui.tableWidget->setColumnWidth(4, 50); - ui.tableWidget->setColumnWidth(5, 50); - ui.tableWidget->setColumnWidth(6, 390); - ui.tableWidget->setEditTriggers(QAbstractItemView::NoEditTriggers); //绂佹缂栬緫 - for (int i = 0; i < m_plc_items.size(); i++) - { - ui.tableWidget->setItem(i, 0, new QTableWidgetItem(QString::fromLocal8Bit(m_plc_items[i].func_desc.c_str()))); - //ui.tableWidget->setItem(i, 1, new QTableWidgetItem(QString::number(m_plc_items[i].address))); - QPushButton * pBtnR = new QPushButton(); - pBtnR->setText(QStringLiteral("璇")); - connect(pBtnR, SIGNAL(clicked(bool)), this, SLOT(click_read())); - ui.tableWidget->setCellWidget(i, 2, pBtnR); +PlcSetup::PlcSetup(QWidget* parent) : QDialog(parent) { + ui.setupUi(this); + this->setWindowFlags(Qt::FramelessWindowHint); + read_plc_items(); + ui.tableWidget->setColumnCount(7); + ui.tableWidget->setRowCount(m_plc_items.size()); + QStringList header_list; + header_list << QStringLiteral("鍔熻兘鎻忚堪") << QStringLiteral("璇绘暟鍊") + << QStringLiteral("璇绘搷浣") << QStringLiteral("鍐欐暟鍊") << QStringLiteral("鍐欐搷浣") << QStringLiteral("淇濆瓨") << QStringLiteral("澶囨敞"); + ui.tableWidget->setHorizontalHeaderLabels(header_list); + ui.tableWidget->setColumnWidth(0, 200); + ui.tableWidget->setColumnWidth(1, 100); + ui.tableWidget->setColumnWidth(2, 50); + ui.tableWidget->setColumnWidth(3, 100); + ui.tableWidget->setColumnWidth(4, 50); + ui.tableWidget->setColumnWidth(5, 50); + ui.tableWidget->setColumnWidth(6, 390); + ui.tableWidget->setEditTriggers(QAbstractItemView::NoEditTriggers); //绂佹缂栬緫 + for (int i = 0; i < m_plc_items.size(); i++) + { + ui.tableWidget->setItem(i, 0, new QTableWidgetItem(QString::fromLocal8Bit(m_plc_items[i].func_desc.c_str()))); + //ui.tableWidget->setItem(i, 1, new QTableWidgetItem(QString::number(m_plc_items[i].address))); + QPushButton* pBtnR = new QPushButton(); + pBtnR->setText(QStringLiteral("璇")); + connect(pBtnR, SIGNAL(clicked(bool)), this, SLOT(click_read())); + ui.tableWidget->setCellWidget(i, 2, pBtnR); - QLineEdit *edit = new QLineEdit(); - edit->setValidator(new QIntValidator(0, 100000, this)); - ui.tableWidget->setCellWidget(i, 3, edit); + QLineEdit* edit = new QLineEdit(); + edit->setValidator(new QIntValidator(0, 100000, this)); + ui.tableWidget->setCellWidget(i, 3, edit); - QPushButton * pBtnW = new QPushButton(); - pBtnW->setText(QStringLiteral("鍐")); - connect(pBtnW, SIGNAL(clicked(bool)), this, SLOT(click_write())); - ui.tableWidget->setCellWidget(i, 4, pBtnW); + QPushButton* pBtnW = new QPushButton(); + pBtnW->setText(QStringLiteral("鍐")); + connect(pBtnW, SIGNAL(clicked(bool)), this, SLOT(click_write())); + ui.tableWidget->setCellWidget(i, 4, pBtnW); - QPushButton * pBtnS = new QPushButton(); - pBtnS->setText(QStringLiteral("淇濆瓨")); - connect(pBtnS, SIGNAL(clicked(bool)), this, SLOT(click_save())); - ui.tableWidget->setCellWidget(i, 5, pBtnS); + QPushButton* pBtnS = new QPushButton(); + pBtnS->setText(QStringLiteral("淇濆瓨")); + connect(pBtnS, SIGNAL(clicked(bool)), this, SLOT(click_save())); + ui.tableWidget->setCellWidget(i, 5, pBtnS); - ui.tableWidget->setItem(i, 6, new QTableWidgetItem(QString::fromLocal8Bit(m_plc_items[i].memo.c_str()))); - } - m_pTimer = new QTimer(this); - connect(m_pTimer, SIGNAL(timeout()), this, SLOT(handleTimeout())); - m_pTimer->setSingleShot(true); - m_pTimer->start(1000); + ui.tableWidget->setItem(i, 6, new QTableWidgetItem(QString::fromLocal8Bit(m_plc_items[i].memo.c_str()))); + } + m_pTimer = new QTimer(this); + connect(m_pTimer, SIGNAL(timeout()), this, SLOT(handleTimeout())); + m_pTimer->setSingleShot(true); + m_pTimer->start(1000); } PlcSetup::~PlcSetup() { - + } void PlcSetup::click_read() { - QPushButton *pushButton_ = dynamic_cast(this->sender()); - if (NULL == pushButton_) - { - return; - } - int x = pushButton_->frameGeometry().x(); - int y = pushButton_->frameGeometry().y(); - QModelIndex index = ui.tableWidget->indexAt(QPoint(x, y)); - int row = index.row(); - int column = index.column(); + QPushButton* pushButton_ = dynamic_cast(this->sender()); + if (NULL == pushButton_) + { + return; + } + int x = pushButton_->frameGeometry().x(); + int y = pushButton_->frameGeometry().y(); + QModelIndex index = ui.tableWidget->indexAt(QPoint(x, y)); + int row = index.row(); + int column = index.column(); - int addr = m_plc_items[row].address; + int addr = m_plc_items[row].address; - uint8_t dest[4]; - uint16_t * dest16 = (uint16_t *)dest; - memset(dest, 0, 4); - if (addr > 0) - { - if (addr < 40000) //璇诲彇绾垮湀鍊 bit - { - int ret = m_PLCDevice->read_bits_from_plc(addr, 1, dest); - ui.tableWidget->setItem(row, 1, new QTableWidgetItem(QString::number(dest[0]))); - } - else { //璇诲彇DWORD鍊硷紝4瀛楄妭 - int ret = m_PLCDevice->read_short_from_plc( addr, 2, dest16); - //printf("%x ", dest16[0]); - //printf("%x \n", dest16[1]); - //printf("%d \n", dest16[0] + (dest16[1] << 16)); - ui.tableWidget->setItem(row, 1, new QTableWidgetItem(QString::number(dest16[0] + (dest16[1] << 16)))); - } - } + uint8_t dest[4]; + uint16_t* dest16 = (uint16_t*)dest; + memset(dest, 0, 4); + if (addr > 0) + { + if (addr < 40000) //璇诲彇绾垮湀鍊 bit + { + int ret = m_PLCDevice->read_bits_from_plc(addr, 1, dest); + ui.tableWidget->setItem(row, 1, new QTableWidgetItem(QString::number(dest[0]))); + } + else { //璇诲彇DWORD鍊硷紝4瀛楄妭 + int ret = m_PLCDevice->read_short_from_plc(addr, 2, dest16); + //printf("%x ", dest16[0]); + //printf("%x \n", dest16[1]); + //printf("%d \n", dest16[0] + (dest16[1] << 16)); + ui.tableWidget->setItem(row, 1, new QTableWidgetItem(QString::number(dest16[0] + (dest16[1] << 16)))); + } + } } void PlcSetup::click_write() { - QPushButton *pushButton_ = dynamic_cast(this->sender()); - if (NULL == pushButton_) - { - return; - } - int x = pushButton_->frameGeometry().x(); - int y = pushButton_->frameGeometry().y(); - QModelIndex index = ui.tableWidget->indexAt(QPoint(x, y)); - int row = index.row(); - int column = index.column(); - //std::cout << "row:" << row << "\tcol:" << column << std::endl; - - int addr = m_plc_items[row].address; - QWidget *widget=ui.tableWidget->cellWidget(row,3); - QLineEdit *edit=(QLineEdit*)widget; - QString d = edit->text(); - uint8_t dest[4]; - uint16_t * dest16 = (uint16_t *)dest; - memset(dest, 0, 4); - if (d.length() > 0) - { - int data = d.toInt(); - if (addr > 0) - { - if (addr < 40000) //鍐欏叆绾垮湀鍊 bit - { - if (data != 0) data = 1; - int ret = m_PLCDevice->write_bit_2_plc( addr, data); - } - else { //鍐欏叆DWORD鍊硷紝4瀛楄妭 - dest16[0] = (data & 0xffff); - dest16[1] = (data>>16); - int ret = m_PLCDevice->write_short_2_plc(addr, 2, dest16); - } - } - QMessageBox::information(NULL, QStringLiteral("鎻愮ず"), QStringLiteral("鍐欏叆鎴愬姛"), QMessageBox::Ok); - } + QPushButton* pushButton_ = dynamic_cast(this->sender()); + if (NULL == pushButton_) + { + return; + } + int x = pushButton_->frameGeometry().x(); + int y = pushButton_->frameGeometry().y(); + QModelIndex index = ui.tableWidget->indexAt(QPoint(x, y)); + int row = index.row(); + int column = index.column(); + //std::cout << "row:" << row << "\tcol:" << column << std::endl; + + int addr = m_plc_items[row].address; + QWidget* widget = ui.tableWidget->cellWidget(row, 3); + QLineEdit* edit = (QLineEdit*)widget; + QString d = edit->text(); + uint8_t dest[4]; + uint16_t* dest16 = (uint16_t*)dest; + memset(dest, 0, 4); + if (d.length() > 0) + { + int data = d.toInt(); + if (addr > 0) + { + if (addr < 40000) //鍐欏叆绾垮湀鍊 bit + { + if (data != 0) data = 1; + int ret = m_PLCDevice->write_bit_2_plc(addr, data); + } + else { //鍐欏叆DWORD鍊硷紝4瀛楄妭 + dest16[0] = (data & 0xffff); + dest16[1] = (data >> 16); + int ret = m_PLCDevice->write_short_2_plc(addr, 2, dest16); + } + } + QMessageBox::information(NULL, QStringLiteral("鎻愮ず"), QStringLiteral("鍐欏叆鎴愬姛"), QMessageBox::Ok); + } } void PlcSetup::click_save() { - QPushButton *pushButton_ = dynamic_cast(this->sender()); - if (NULL == pushButton_) - { - return; - } - int x = pushButton_->frameGeometry().x(); - int y = pushButton_->frameGeometry().y(); - QModelIndex index = ui.tableWidget->indexAt(QPoint(x, y)); - int row = index.row(); - int column = index.column(); - //std::cout << "row:" << row << "\tcol:" << column << std::endl; + QPushButton* pushButton_ = dynamic_cast(this->sender()); + if (NULL == pushButton_) + { + return; + } + int x = pushButton_->frameGeometry().x(); + int y = pushButton_->frameGeometry().y(); + QModelIndex index = ui.tableWidget->indexAt(QPoint(x, y)); + int row = index.row(); + int column = index.column(); + //std::cout << "row:" << row << "\tcol:" << column << std::endl; - int addr = m_plc_items[row].address; - QWidget *widget = ui.tableWidget->cellWidget(row, 3); - QLineEdit *edit = (QLineEdit*)widget; - QString d = edit->text(); - uint8_t dest[4]; - uint16_t * dest16 = (uint16_t *)dest; - memset(dest, 0, 4); - if (d.length() > 0) - { - int data = d.toInt(); - if (addr > 0) - { - if (addr < 40000) //鍐欏叆绾垮湀鍊 bit - { - if (data != 0) data = 1; - int ret = m_PLCDevice->write_bit_2_plc( addr, data); - } - else { //鍐欏叆DWORD鍊硷紝4瀛楄妭 - dest16[0] = (data & 0xffff); - dest16[1] = (data >> 16); - int ret = m_PLCDevice->write_short_2_plc(addr, 2, dest16); - } - } - //int data = d.toInt(); - for (int i = 0; i < m_plc_items.size(); i++) - { - //std::cout << m_plc_items[i].address << std::endl; - if (m_plc_items[i].address == addr) - { - //std::cout << "Hit" << addr << std::endl; - m_plc_items[i].value = data; - //std::cout << "SAVE start" << std::endl; - save_plc_items(); - //std::cout << "SAVE END" << std::endl; - QMessageBox::information(NULL, QStringLiteral("鎻愮ず"), QStringLiteral("鍐欏叆骞朵笖淇濆瓨鎴愬姛"), QMessageBox::Ok); - break; - } - } - } + int addr = m_plc_items[row].address; + QWidget* widget = ui.tableWidget->cellWidget(row, 3); + QLineEdit* edit = (QLineEdit*)widget; + QString d = edit->text(); + uint8_t dest[4]; + uint16_t* dest16 = (uint16_t*)dest; + memset(dest, 0, 4); + if (d.length() > 0) + { + int data = d.toInt(); + if (addr > 0) + { + if (addr < 40000) //鍐欏叆绾垮湀鍊 bit + { + if (data != 0) data = 1; + int ret = m_PLCDevice->write_bit_2_plc(addr, data); + } + else { //鍐欏叆DWORD鍊硷紝4瀛楄妭 + dest16[0] = (data & 0xffff); + dest16[1] = (data >> 16); + int ret = m_PLCDevice->write_short_2_plc(addr, 2, dest16); + } + } + //int data = d.toInt(); + for (int i = 0; i < m_plc_items.size(); i++) + { + //std::cout << m_plc_items[i].address << std::endl; + if (m_plc_items[i].address == addr) + { + //std::cout << "Hit" << addr << std::endl; + m_plc_items[i].value = data; + //std::cout << "SAVE start" << std::endl; + save_plc_items(); + //std::cout << "SAVE END" << std::endl; + QMessageBox::information(NULL, QStringLiteral("鎻愮ず"), QStringLiteral("鍐欏叆骞朵笖淇濆瓨鎴愬姛"), QMessageBox::Ok); + break; + } + } + } } void PlcSetup::on_toolButton_batch_read_released() { - for (int i = 0; i < m_plc_items.size(); i++) - { - int addr = m_plc_items[i].address; - uint8_t dest[4]; - uint16_t * dest16 = (uint16_t *)dest; - memset(dest, 0, 4); - if (addr > 0) - { - if (addr < 40000) //璇诲彇绾垮湀鍊 bit - { - int ret = m_PLCDevice->read_bits_from_plc(addr, 1, dest); - ui.tableWidget->setItem(i, 1, new QTableWidgetItem(QString::number(dest[0]))); - } - else { //璇诲彇DWORD鍊硷紝4瀛楄妭 - int ret = m_PLCDevice->read_short_from_plc( addr, 2, dest16); - ui.tableWidget->setItem(i, 1, new QTableWidgetItem(QString::number(dest16[0] + (dest16[1] << 16)))); - } - } - } + for (int i = 0; i < m_plc_items.size(); i++) + { + int addr = m_plc_items[i].address; + uint8_t dest[4]; + uint16_t* dest16 = (uint16_t*)dest; + memset(dest, 0, 4); + if (addr > 0) + { + if (addr < 40000) //璇诲彇绾垮湀鍊 bit + { + int ret = m_PLCDevice->read_bits_from_plc(addr, 1, dest); + ui.tableWidget->setItem(i, 1, new QTableWidgetItem(QString::number(dest[0]))); + } + else { //璇诲彇DWORD鍊硷紝4瀛楄妭 + int ret = m_PLCDevice->read_short_from_plc(addr, 2, dest16); + ui.tableWidget->setItem(i, 1, new QTableWidgetItem(QString::number(dest16[0] + (dest16[1] << 16)))); + } + } + } } void PlcSetup::on_toolButton_keyboard_released() { - std::thread osk_thread = std::thread(task_osk_); - osk_thread.detach(); + std::thread osk_thread = std::thread(task_osk_); + osk_thread.detach(); } void PlcSetup::on_toolButton_close_released() { - g_plc_dialog_open = false; - this->close(); + g_plc_dialog_open = false; + this->close(); } void PlcSetup::handleTimeout() { - on_toolButton_batch_read_released(); + on_toolButton_batch_read_released(); } void PlcSetup::read_plc_items() { - std::fstream cfg_file; - QString plc_file = g_conf_path.config_path + "/" + PLC_CONFIG_FILE; + std::fstream cfg_file; + QString plc_file = g_conf_path.config_path + "/" + PLC_CONFIG_FILE; - cfg_file.open(plc_file.toLocal8Bit().constData()); + cfg_file.open(plc_file.toLocal8Bit().constData()); - if (!cfg_file.is_open()) - { - std::cout << "Error: Open production file " << PLC_ITEM_FILE << std::endl; - return; - } - while (!cfg_file.eof()) - { - char tmp[1024] = ""; - cfg_file.getline(tmp, 1024); - std::string line(tmp); - std::cout << line << std::endl; - if (line.length() > 0) - { - std::vector vec_info; - string_split(line, "|", vec_info); - if (vec_info.size() == 4) - { - PlcItem plc_item; - plc_item.func_desc = vec_info[0]; - plc_item.address = atoi(vec_info[1].c_str()); - plc_item.value = atoi(vec_info[2].c_str()); - plc_item.memo = vec_info[3]; - m_plc_items.push_back(plc_item); - } - } - } - cfg_file.close(); + if (!cfg_file.is_open()) + { + std::cout << "Error: Open production file " << PLC_ITEM_FILE << std::endl; + return; + } + while (!cfg_file.eof()) + { + char tmp[1024] = ""; + cfg_file.getline(tmp, 1024); + std::string line(tmp); + std::cout << line << std::endl; + if (line.length() > 0) + { + std::vector vec_info; + string_split(line, "|", vec_info); + if (vec_info.size() == 4) + { + PlcItem plc_item; + plc_item.func_desc = vec_info[0]; + plc_item.address = atoi(vec_info[1].c_str()); + plc_item.value = atoi(vec_info[2].c_str()); + plc_item.memo = vec_info[3]; + m_plc_items.push_back(plc_item); + } + } + } + cfg_file.close(); } void PlcSetup::save_plc_items() { - std::fstream cfg_file; - QString plc_file = g_conf_path.config_path + "/" + PLC_CONFIG_FILE; - cfg_file.open(plc_file.toLocal8Bit().constData(), std::ios::out | std::ios::trunc); - if (cfg_file.good()) - { - for (int i = 0; i < m_plc_items.size(); i++) - { - char buf[512]; - memset(buf, 0, 512); - sprintf(buf, "%s|%d|%d|%s\n", m_plc_items[i].func_desc.c_str(), - m_plc_items[i].address, m_plc_items[i].value, m_plc_items[i].memo.c_str()); - cfg_file.write(buf, strlen(buf)); - } - cfg_file.close(); - } + std::fstream cfg_file; + QString plc_file = g_conf_path.config_path + "/" + PLC_CONFIG_FILE; + cfg_file.open(plc_file.toLocal8Bit().constData(), std::ios::out | std::ios::trunc); + if (cfg_file.good()) + { + for (int i = 0; i < m_plc_items.size(); i++) + { + char buf[512]; + memset(buf, 0, 512); + sprintf(buf, "%s|%d|%d|%s\n", m_plc_items[i].func_desc.c_str(), + m_plc_items[i].address, m_plc_items[i].value, m_plc_items[i].memo.c_str()); + cfg_file.write(buf, strlen(buf)); + } + cfg_file.close(); + } } diff --git a/Cigarette/plcsetup.hpp b/Cigarette/plcsetup.hpp index 530d370a..dee8dc88 100644 --- a/Cigarette/plcsetup.hpp +++ b/Cigarette/plcsetup.hpp @@ -1,4 +1,4 @@ -锘#pragma once +#pragma once #include #include #include "ui_plcsetup.h" @@ -11,29 +11,29 @@ class QTimer; class PlcSetup : public QDialog { - Q_OBJECT + Q_OBJECT public: - PlcSetup(QWidget * parent = Q_NULLPTR); - ~PlcSetup(); + PlcSetup(QWidget* parent = Q_NULLPTR); + ~PlcSetup(); - QTimer *m_pTimer; + QTimer* m_pTimer; - void read_plc_items(); - void save_plc_items(); + void read_plc_items(); + void save_plc_items(); private slots: - void click_read(); - void click_write(); - void click_save(); - - void on_toolButton_batch_read_released(); - void on_toolButton_keyboard_released(); - void on_toolButton_close_released(); + void click_read(); + void click_write(); + void click_save(); - void handleTimeout(); //绐楀彛鍔犺浇鏃舵墽琛屼竴娆★紝鎵瑰鐞嗚鍙栨墍鏈夊湴鍧 + void on_toolButton_batch_read_released(); + void on_toolButton_keyboard_released(); + void on_toolButton_close_released(); + + void handleTimeout(); //绐楀彛鍔犺浇鏃舵墽琛屼竴娆★紝鎵瑰鐞嗚鍙栨墍鏈夊湴鍧 private: - Ui::PlcSetup ui; + Ui::PlcSetup ui; - std::vector m_plc_items; + std::vector m_plc_items; }; diff --git a/Cigarette/savethread.h b/Cigarette/savethread.h index 1ced71d2..945c2b9c 100644 --- a/Cigarette/savethread.h +++ b/Cigarette/savethread.h @@ -12,89 +12,89 @@ #include #include -extern SyncQueue>* g_save_queue; //图像保存队列 +extern SyncQueue>* g_save_queue; //鍥惧儚淇濆瓨闃熷垪 class SaveThread : public QThread { - Q_OBJECT + Q_OBJECT signals: - void sendDataToExport(QString filePath); - + void sendDataToExport(QString filePath); + public: - SaveThread(QObject *parent = 0): QThread(parent) - { + SaveThread(QObject* parent = 0) : QThread(parent) + { - } - ~SaveThread() - { - stop(); - g_save_queue->put(std::make_pair("", cv::Mat())); - quit(); - wait(); - } + } + ~SaveThread() + { + stop(); + g_save_queue->put(std::make_pair("", cv::Mat())); + quit(); + wait(); + } + + void init() + { + b_quit = false; + } + void start_work() + { + start(HighestPriority); + } + void stop() + { + b_quit = true; + } - void init() - { - b_quit = false; - } - void start_work() - { - start(HighestPriority); - } - void stop() - { - b_quit = true; - } - protected: void run() + { + while (!b_quit) { + cv::Mat image; + std::pair element; + g_save_queue->take(element); + std::string file_name = element.first; + image = element.second; + if (image.data) + { + std::size_t found = file_name.find_last_of("/\\"); + std::string dir_path = file_name.substr(0, found); + check_save_dir(dir_path); + bool b_save = cv::imwrite(file_name, image); + if (b_save) + { + //sendDataToExport(QString::fromStdString(file_name)); + sendDataToExport(QString::fromLocal8Bit(QByteArray::fromRawData(file_name.c_str(), file_name.size()))); + //qDebug() << "Save pic successfully"; + } + } + } + } + void check_save_dir(std::string dir_path) + { + bool b_find = false; + for (int i = 0; i < vec_save_dirs.size(); i++) { - while (!b_quit) { - cv::Mat image; - std::pair element; - g_save_queue->take(element); - std::string file_name = element.first; - image = element.second; - if (image.data) - { - std::size_t found = file_name.find_last_of("/\\"); - std::string dir_path = file_name.substr(0, found); - check_save_dir(dir_path); - bool b_save = cv::imwrite(file_name, image); - if (b_save) - { - //sendDataToExport(QString::fromStdString(file_name)); - sendDataToExport(QString::fromLocal8Bit(QByteArray::fromRawData(file_name.c_str(), file_name.size()))); - //qDebug() << "Save pic successfully"; - } - } + if (dir_path == vec_save_dirs[i]) + { + b_find = true; } } - void check_save_dir(std::string dir_path) - { - bool b_find = false; - for (int i = 0; i < vec_save_dirs.size(); i++) - { - if (dir_path == vec_save_dirs[i]) - { - b_find = true; - } - } - if (!b_find) - { - //QString dir_str = QString::fromStdString(dir_path); - QString dir_str = QString::fromLocal8Bit(QByteArray::fromRawData(dir_path.c_str(), dir_path.size())); + if (!b_find) + { + //QString dir_str = QString::fromStdString(dir_path); + QString dir_str = QString::fromLocal8Bit(QByteArray::fromRawData(dir_path.c_str(), dir_path.size())); - QDir dir; - if (!dir.exists(dir_str)) - { - dir.mkpath(dir_str); - } - vec_save_dirs.push_back(dir_path); - } - } + QDir dir; + if (!dir.exists(dir_str)) + { + dir.mkpath(dir_str); + } + vec_save_dirs.push_back(dir_path); + } + } public: - bool b_quit; - std::vector vec_save_dirs; + bool b_quit; + std::vector vec_save_dirs; }; #endif diff --git a/Cigarette/syncworkthread.cpp b/Cigarette/syncworkthread.cpp index e9e5ade9..ad116a7e 100644 --- a/Cigarette/syncworkthread.cpp +++ b/Cigarette/syncworkthread.cpp @@ -8,17 +8,18 @@ #include "exportData.h" #include -extern AlgJd alg_jd[NumberOfSupportedCameras]; //检测胶点的AI算法 +extern AlgJd alg_jd[NumberOfSupportedCameras]; //妫娴嬭兌鐐圭殑AI绠楁硶 extern ConfPath g_conf_path; -extern SysConf g_sys_conf; //系统配置参数 +extern SysConf g_sys_conf; //绯荤粺閰嶇疆鍙傛暟 extern DisplayLabelConf g_display_label_conf[NumberOfSupportedCameras]; -extern int rotationAngle[NumberOfSupportedCameras]; //图片旋转角度 +extern int rotationAngle[NumberOfSupportedCameras]; //鍥剧墖鏃嬭浆瑙掑害 extern bool isNeedRotate[NumberOfSupportedCameras]; extern int work_camera_nums; +extern SingleCamInfoStruct SingleCamInfo[NumberOfSupportedCameras]; -extern SyncQueue >* g_save_queue; //图片保存队列 -extern SyncQueue>* g_image_queue[NumberOfSupportedCameras]; //int表示一个目标拍了几张 +extern SyncQueue >* g_save_queue; //鍥剧墖淇濆瓨闃熷垪 +extern SyncQueue>* g_image_queue[NumberOfSupportedCameras]; //int琛ㄧず涓涓洰鏍囨媿浜嗗嚑寮 #ifdef __UDPSend extern SyncQueue<_UDPSendInfo>* UDP_Info_queue; #endif @@ -33,315 +34,317 @@ extern bool g_debug_mode; SyncWorkThread::~SyncWorkThread() { - stop(); - std::vector> queue; - local_g_image_sync_queue->put(queue); - quit(); - wait(); + stop(); + std::vector> queue; + local_g_image_sync_queue->put(queue); + quit(); + wait(); } void SyncWorkThread::init(SyncQueue>>* image_ptr, ASyncQueue* result_ptr) { - local_g_image_sync_queue = image_ptr; - local_g_result_queue = result_ptr; - b_quit = false; - for (int i = 0; i < NumberOfSupportedCameras; i++) { - frame_total[i] = 0; - } + local_g_image_sync_queue = image_ptr; + local_g_result_queue = result_ptr; + b_quit = false; + for (int i = 0; i < NumberOfSupportedCameras; i++) { + frame_total[i] = 0; + } } void SyncWorkThread::start_work() { - start(HighestPriority); + start(HighestPriority); } void SyncWorkThread::stop() { - b_quit = true; + b_quit = true; } void SyncWorkThread::run() { - try { - uint32_t result_index[NumberOfSupportedCameras] = { 0 }; - while (!b_quit) { - QDateTime now_ts = QDateTime::currentDateTime(); - std::vector> element_vec; - local_g_image_sync_queue->take(element_vec); - bool IsNGForAll = false; - int merge_index; - cv::Rect roi; - int j = 0; // 实际工作的相机标识,element_vec中可能有相机没在工作 - for (int i = 0; i < element_vec.size(); i++)//每个相机的图轮流遍历 - { - local_camera_number = i; - int isWork = element_vec[i].first; - std::pair element; - element = element_vec[i]; - int unit_count = element.first; - cv::Mat image = element.second; - {//不要删掉这个括号,用来定义锁的作用域 - std::lock_guard locker(g_sys_conf.lock); - local_SysConf.save = g_sys_conf.save; - local_SysConf.shoot[local_camera_number] = g_sys_conf.shoot[local_camera_number]; - local_SysConf.MisMatchAct = g_sys_conf.MisMatchAct; - local_SysConf.ConfThreshold = g_sys_conf.ConfThreshold;// - for (int i = 0; i < 3; i++)local_SysConf.no[local_camera_number][i] = g_sys_conf.no[local_camera_number][i]; + try { + uint32_t result_index[NumberOfSupportedCameras] = { 0 }; + while (!b_quit) { + QDateTime now_ts = QDateTime::currentDateTime(); + std::vector> element_vec; + local_g_image_sync_queue->take(element_vec); + bool IsNGForAll = false; + int merge_index; + cv::Rect roi; + int j = 0; // 瀹為檯宸ヤ綔鐨勭浉鏈烘爣璇嗭紝element_vec涓彲鑳芥湁鐩告満娌″湪宸ヤ綔 + for (int i = 0; i < element_vec.size(); i++)//姣忎釜鐩告満鐨勫浘杞祦閬嶅巻 + { + if (!SingleCamInfo[i].Detect || !SingleCamInfo[i].IsOpen || SingleCamInfo[i].OffLine) + continue; + + local_camera_number = i; + int isWork = element_vec[i].first; + std::pair element; + element = element_vec[i]; + int unit_count = element.first; + cv::Mat image = element.second; + {//涓嶈鍒犳帀杩欎釜鎷彿锛岀敤鏉ュ畾涔夐攣鐨勪綔鐢ㄥ煙 + std::lock_guard locker(g_sys_conf.lock); + local_SysConf.save = g_sys_conf.save; + local_SysConf.shoot[local_camera_number] = g_sys_conf.shoot[local_camera_number]; + local_SysConf.MisMatchAct = g_sys_conf.MisMatchAct; + local_SysConf.ConfThreshold = g_sys_conf.ConfThreshold;// + for (int i = 0; i < 3; i++)local_SysConf.no[local_camera_number][i] = g_sys_conf.no[local_camera_number][i]; #ifdef DRAW_RECT - std::lock_guard locker2(g_display_label_conf[local_camera_number].lock); - local_DisplayLabelConf.leftButtonDownFlag = g_display_label_conf[local_camera_number].leftButtonDownFlag; - local_DisplayLabelConf.Flag[0] = g_display_label_conf[local_camera_number].Flag[0]; - local_DisplayLabelConf.Flag[1] = g_display_label_conf[local_camera_number].Flag[1]; - local_DisplayLabelConf.originalPoint = g_display_label_conf[local_camera_number].originalPoint; - local_DisplayLabelConf.processPoint = g_display_label_conf[local_camera_number].processPoint; - local_DisplayLabelConf.RectVet[0] = g_display_label_conf[local_camera_number].RectVet[0]; - local_DisplayLabelConf.RectVet[1] = g_display_label_conf[local_camera_number].RectVet[1]; + std::lock_guard locker2(g_display_label_conf[local_camera_number].lock); + local_DisplayLabelConf.leftButtonDownFlag = g_display_label_conf[local_camera_number].leftButtonDownFlag; + local_DisplayLabelConf.Flag[0] = g_display_label_conf[local_camera_number].Flag[0]; + local_DisplayLabelConf.Flag[1] = g_display_label_conf[local_camera_number].Flag[1]; + local_DisplayLabelConf.originalPoint = g_display_label_conf[local_camera_number].originalPoint; + local_DisplayLabelConf.processPoint = g_display_label_conf[local_camera_number].processPoint; + local_DisplayLabelConf.RectVet[0] = g_display_label_conf[local_camera_number].RectVet[0]; + local_DisplayLabelConf.RectVet[1] = g_display_label_conf[local_camera_number].RectVet[1]; #endif - } + } #ifdef __UDPSend - _UDPSendInfo UDPSendInfo; - UDPSendInfo.FrameID = info_frame; - UDPSendInfo.index = local_camera_number; + _UDPSendInfo UDPSendInfo; + UDPSendInfo.FrameID = info_frame; + UDPSendInfo.index = local_camera_number; #endif #ifdef __TCPSend - _TCPSendInfo TCPSendInfo; + _TCPSendInfo TCPSendInfo; #endif - if (!image.data) - { - continue; //图像为空,跳过 - } - cv::Mat merge_image = cv::Mat::zeros(512 * work_camera_nums, 640 * g_sys_conf.shoot[i], CV_8UC3); - if (image.channels() == 1) - { - cv::cvtColor(image, image, CV_BGR2RGB); //灰度图像转为彩色图像 - } - cv::resize(image, image, cv::Size(640, 512 * unit_count)); - if (local_SysConf.shoot[local_camera_number] == unit_count) - { - std::vector vec_in; - int w = image.cols; - int h = image.rows / unit_count; - for (int index = 0; index < unit_count; index++) { - cv::Rect temp_Rect(0, h * index, w, h); - cv::Mat temp_image = image(temp_Rect).clone(); - if (isNeedRotate[local_camera_number]) { - if (rotationAngle[local_camera_number] != (cv::ROTATE_90_COUNTERCLOCKWISE + 1)) - { - cv::rotate(temp_image, temp_image, rotationAngle[local_camera_number]); - } - } - vec_in.push_back(temp_image.clone()); - } + if (!image.data) + { + continue; //鍥惧儚涓虹┖锛岃烦杩 + } + cv::Mat merge_image = cv::Mat::zeros(512 * work_camera_nums, 640 * g_sys_conf.shoot[i], CV_8UC3); + if (image.channels() == 1) + { + cv::cvtColor(image, image, CV_BGR2RGB); //鐏板害鍥惧儚杞负褰╄壊鍥惧儚 + } + cv::resize(image, image, cv::Size(640, 512 * unit_count)); + if (local_SysConf.shoot[local_camera_number] == unit_count) + { + std::vector vec_in; + int w = image.cols; + int h = image.rows / unit_count; + for (int index = 0; index < unit_count; index++) { + cv::Rect temp_Rect(0, h * index, w, h); + cv::Mat temp_image = image(temp_Rect).clone(); + if (isNeedRotate[local_camera_number]) { + if (rotationAngle[local_camera_number] != (cv::ROTATE_90_COUNTERCLOCKWISE + 1)) + { + cv::rotate(temp_image, temp_image, rotationAngle[local_camera_number]); + } + } + vec_in.push_back(temp_image.clone()); + } - std::vector vec_out; - std::vector>> vec_results; - QDateTime ts_start = QDateTime::currentDateTime(); - if (unit_count == 1) { - std::vector> results; - cv::Mat imagein, imageout; - imagein = vec_in[0]; - alg_jd[local_camera_number].detect(imagein, imageout, results); - vec_out.push_back(imageout.clone()); - vec_results.push_back(results); - } - else { - alg_jd[local_camera_number].detect_batch(vec_in, vec_out, vec_results); - } - QDateTime ts_jd = QDateTime::currentDateTime(); - int time_process = ts_start.msecsTo(ts_jd); + std::vector vec_out; + std::vector>> vec_results; + QDateTime ts_start = QDateTime::currentDateTime(); + if (unit_count == 1) { + std::vector> results; + cv::Mat imagein, imageout; + imagein = vec_in[0]; + alg_jd[local_camera_number].detect(imagein, imageout, results); + vec_out.push_back(imageout.clone()); + vec_results.push_back(results); + } + else { + alg_jd[local_camera_number].detect_batch(vec_in, vec_out, vec_results); + } + QDateTime ts_jd = QDateTime::currentDateTime(); + int time_process = ts_start.msecsTo(ts_jd); #ifdef SYNC_CAMERA - emit display_timecost(local_camera_number, time_process); + emit display_timecost(local_camera_number, time_process); #endif #ifdef __UDPSend - UDPSendInfo.timecost = QString::number(time_process); + UDPSendInfo.timecost = QString::number(time_process); #endif - cv::Mat image1; - cv::Mat image2; - QString jd_no; - for (int index = 0; index < unit_count; index++) { - jd_no += QString::number(vec_results[index].size()) + ","; - } - jd_no.chop(1); + cv::Mat image1; + cv::Mat image2; + QString jd_no; + for (int index = 0; index < unit_count; index++) { + jd_no += QString::number(vec_results[index].size()) + ","; + } + jd_no.chop(1); #ifdef SYNC_CAMERA - emit display_jd_no(local_camera_number, jd_no); + emit display_jd_no(local_camera_number, jd_no); #endif #ifdef __UDPSend - UDPSendInfo.JD = jd_no; + UDPSendInfo.JD = jd_no; #endif - bool IsNG = false; - int ngReason = 0; - QMap ng_reason_maps; - ng_reason_maps[0] = "unknow"; - ng_reason_maps[1] = "less_than_setting"; - ng_reason_maps[2] = "too_diff_from_model"; - ng_reason_maps[3] = "out_of_setting_range"; - for (int index = 0; index < unit_count; index++){ - if (vec_results[index].size() < local_SysConf.no[local_camera_number][index]) - { - IsNG |= true; - ngReason = 1; - } - //if (vec_results[index].size() != 1)IsNG |= true;//反向训练 - if (local_SysConf.ConfThreshold == 0) - { - IsNG = false; - ngReason = 0; - } - if (local_SysConf.save == 2)//三张照片分别存储 - { - /// 合成element_vec.size() * unit_count 宫格图像 - cv::Mat m = vec_in[index].clone(); - QString file_name; - merge_index = j * unit_count + index + 1; - roi = cv::Rect(index * m.cols, j * m.rows, m.cols, m.rows); - m.copyTo(merge_image(roi)); + bool IsNG = false; + int ngReason = 0; + QMap ng_reason_maps; + ng_reason_maps[0] = "unknow"; + ng_reason_maps[1] = "less_than_setting"; + ng_reason_maps[2] = "too_diff_from_model"; + ng_reason_maps[3] = "out_of_setting_range"; + for (int index = 0; index < unit_count; index++) { + if (vec_results[index].size() < local_SysConf.no[local_camera_number][index]) + { + IsNG |= true; + ngReason = 1; + } + //if (vec_results[index].size() != 1)IsNG |= true;//鍙嶅悜璁粌 + if (local_SysConf.ConfThreshold == 0) + { + IsNG = false; + ngReason = 0; + } + if (local_SysConf.save == 2)//涓夊紶鐓х墖鍒嗗埆瀛樺偍 + { + /// 鍚堟垚element_vec.size() * unit_count 瀹牸鍥惧儚 + cv::Mat m = vec_in[index].clone(); + QString file_name; + merge_index = j * unit_count + index + 1; + roi = cv::Rect(index * m.cols, j * m.rows, m.cols, m.rows); + m.copyTo(merge_image(roi)); - if (merge_index == work_camera_nums * unit_count) { - file_name = g_conf_path.save_pics_path + "/" - + now_ts.toString("yyyy-MM-dd") + "/" - + now_ts.toString("yyyy-MM-dd_HH-mm-ss_zzz_") + ".jpg"; - g_save_queue->put(std::make_pair(file_name.toLocal8Bit().constData(), merge_image)); + if (merge_index == work_camera_nums * unit_count) { + file_name = g_conf_path.save_pics_path + "/" + + now_ts.toString("yyyy-MM-dd") + "/" + + now_ts.toString("yyyy-MM-dd_HH-mm-ss_zzz_") + ".jpg"; + g_save_queue->put(std::make_pair(file_name.toLocal8Bit().constData(), merge_image)); #ifdef __TCPSend - TCPSendInfo.pics_name = file_name.toLocal8Bit().constData(); - TCP_Info_queue->put(TCPSendInfo); + TCPSendInfo.pics_name = file_name.toLocal8Bit().constData(); + TCP_Info_queue->put(TCPSendInfo); #endif - } - } - } + } + } + } - if (unit_count >= 2) { - image1 = vec_out[(result_index[i]) % 2].clone(); + if (unit_count >= 2) { + image1 = vec_out[(result_index[i]) % 2].clone(); #ifdef DRAW_RECT - IsNG |= CheckSelectRects(image1, vec_results, (result_index[i]) % 2, local_DisplayLabelConf, 0); - if (IsNG) { - ngReason = 2; - } + IsNG |= CheckSelectRects(image1, vec_results, (result_index[i]) % 2, local_DisplayLabelConf, 0); + if (IsNG) { + ngReason = 2; + } #endif - } - else { - image1 = vec_out[0].clone(); + } + else { + image1 = vec_out[0].clone(); #ifdef DRAW_RECT - IsNG |= CheckSelectRects(image1, vec_results, 0, local_DisplayLabelConf, 0); - if (IsNG) { - ngReason = 2; - } + IsNG |= CheckSelectRects(image1, vec_results, 0, local_DisplayLabelConf, 0); + if (IsNG) { + ngReason = 2; + } #endif - } + } #ifdef DRAW_RECT - DrawSelectRects(image1, local_DisplayLabelConf, 0); + DrawSelectRects(image1, local_DisplayLabelConf, 0); #endif - if (unit_count >= 3) { - image2 = vec_out[2].clone(); + if (unit_count >= 3) { + image2 = vec_out[2].clone(); #ifdef DRAW_RECT - DrawSelectRects(image2, local_DisplayLabelConf, 1); - IsNG |= CheckSelectRects(image1, vec_results, 2, local_DisplayLabelConf, 1); - if (IsNG) { - ngReason = 3; - } + DrawSelectRects(image2, local_DisplayLabelConf, 1); + IsNG |= CheckSelectRects(image1, vec_results, 2, local_DisplayLabelConf, 1); + if (IsNG) { + ngReason = 3; + } #endif - } - result_index[i]++; + } + result_index[i]++; - if (!IsNG) - { - if (!g_debug_mode) - { + if (!IsNG) + { + if (!g_debug_mode) + { #ifdef SYNC_CAMERA - emit event_ok(local_camera_number); + emit event_ok(local_camera_number); #endif - local_g_result_queue->put(true); - } - } - else - { - if (!g_debug_mode) - { + local_g_result_queue->put(true); + } + } + else + { + if (!g_debug_mode) + { #ifdef SYNC_CAMERA - emit event_ng(local_camera_number); + emit event_ng(local_camera_number); #endif - local_g_result_queue->put(false); - IsNGForAll = TRUE; - } + local_g_result_queue->put(false); + IsNGForAll = TRUE; + } - if ((local_SysConf.save == 2) || (local_SysConf.save == 1)) - { - for (int index = 0; index < unit_count; index++) - { - cv::Mat m = vec_in[index].clone(); - QString file_name = g_conf_path.save_pics_path + "/ng/" + - now_ts.toString("yyyy-MM-dd") + "/" - + QString::number(local_camera_number + 1) + "/" + QString::number(index + 1) + "/" + - now_ts.toString("yyyy-MM-dd_HH-mm-ss_zzz_") + QString::number(local_camera_number + 1) + - "#" + "_" + QString::number(index + 1) + "_" + ng_reason_maps[ngReason] + - ".jpg"; - QString remotePath = "/image/ng/" + - now_ts.toString("yyyy-MM-dd_HH-mm-ss_zzz_") + QString::number(local_camera_number + 1) + - "#" + "_" + QString::number(index + 1) + "_" + ng_reason_maps[ngReason] + - ".jpg"; - //g_save_queue->put(std::make_pair(file_name.toLocal8Bit().constData(), m)); + if ((local_SysConf.save == 2) || (local_SysConf.save == 1)) + { + for (int index = 0; index < unit_count; index++) + { + cv::Mat m = vec_in[index].clone(); + QString file_name = g_conf_path.save_pics_path + "/ng/" + + now_ts.toString("yyyy-MM-dd") + "/" + + QString::number(local_camera_number + 1) + "/" + QString::number(index + 1) + "/" + + now_ts.toString("yyyy-MM-dd_HH-mm-ss_zzz_") + QString::number(local_camera_number + 1) + + "#" + "_" + QString::number(index + 1) + "_" + ng_reason_maps[ngReason] + + ".jpg"; + QString remotePath = "/image/ng/" + + now_ts.toString("yyyy-MM-dd_HH-mm-ss_zzz_") + QString::number(local_camera_number + 1) + + "#" + "_" + QString::number(index + 1) + "_" + ng_reason_maps[ngReason] + + ".jpg"; + //g_save_queue->put(std::make_pair(file_name.toLocal8Bit().constData(), m)); - m = vec_out[index].clone(); - file_name = g_conf_path.save_pics_path + "/ng_result/" + - now_ts.toString("yyyy-MM-dd") + "/" - + QString::number(local_camera_number + 1) + "/" + QString::number(index + 1) + "/" + - now_ts.toString("yyyy-MM-dd_HH-mm-ss_zzz_") + QString::number(local_camera_number + 1) + - "#" + "_" + QString::number(index + 1) + "_" + ng_reason_maps[ngReason] + - ".jpg"; - remotePath = "/image/ng_result/" + - now_ts.toString("yyyy-MM-dd_HH-mm-ss_zzz_") + QString::number(local_camera_number + 1) + - "#" + "_" + QString::number(index + 1) + "_" + ng_reason_maps[ngReason] + - ".jpg"; - //g_save_queue->put(std::make_pair(file_name.toStdString(), m)); - //g_save_queue->put(std::make_pair(file_name.toLocal8Bit().constData(), m)); - } - } - } + m = vec_out[index].clone(); + file_name = g_conf_path.save_pics_path + "/ng_result/" + + now_ts.toString("yyyy-MM-dd") + "/" + + QString::number(local_camera_number + 1) + "/" + QString::number(index + 1) + "/" + + now_ts.toString("yyyy-MM-dd_HH-mm-ss_zzz_") + QString::number(local_camera_number + 1) + + "#" + "_" + QString::number(index + 1) + "_" + ng_reason_maps[ngReason] + + ".jpg"; + remotePath = "/image/ng_result/" + + now_ts.toString("yyyy-MM-dd_HH-mm-ss_zzz_") + QString::number(local_camera_number + 1) + + "#" + "_" + QString::number(index + 1) + "_" + ng_reason_maps[ngReason] + + ".jpg"; + //g_save_queue->put(std::make_pair(file_name.toStdString(), m)); + //g_save_queue->put(std::make_pair(file_name.toLocal8Bit().constData(), m)); + } + } + } #ifdef SYNC_CAMERA - if (!g_debug_mode) - { - if(isWork != 0) - emit display_check_total(local_camera_number, ++frame_total[local_camera_number]); - //exportDataInfo.cameraTotal = frame_total; - emit notify(local_camera_number, 0, image1); - if (unit_count >= 3) - emit notify(local_camera_number, 1, image2); - } + if (!g_debug_mode) + { + emit display_check_total(local_camera_number, ++frame_total[local_camera_number]); + //exportDataInfo.cameraTotal = frame_total; + emit notify(local_camera_number, 0, image1); + if (unit_count >= 3) + emit notify(local_camera_number, 1, image2); + } #endif - } - else - { + } + else + { #ifdef SYNC_CAMERA - //保证不错位 - if (!g_debug_mode) - { - if (local_SysConf.MisMatchAct == 1)//as ng - emit event_ng(local_camera_number); - else if (local_SysConf.MisMatchAct == 0)//as ok - emit event_ok(local_camera_number); - emit display_check_total(local_camera_number, ++(frame_total[local_camera_number])); - qDebug() << local_camera_number << "#camera# " << now_ts.toString("yyyy-MM-dd_HH-mm-ss_zzz_") << "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx " << unit_count; - } + //淇濊瘉涓嶉敊浣 + if (!g_debug_mode) + { + if (local_SysConf.MisMatchAct == 1)//as ng + emit event_ng(local_camera_number); + else if (local_SysConf.MisMatchAct == 0)//as ok + emit event_ok(local_camera_number); + emit display_check_total(local_camera_number, ++(frame_total[local_camera_number])); + qDebug() << local_camera_number << "#camera# " << now_ts.toString("yyyy-MM-dd_HH-mm-ss_zzz_") << "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx " << unit_count; + } #endif - } + } #ifdef __UDPSend - UDP_Info_queue->put(UDPSendInfo); + UDP_Info_queue->put(UDPSendInfo); #endif - j++; - } - if (IsNGForAll) - { - /*to do something*/ - } - } - } - catch (cv::Exception& e) - { - const char* err_msg = e.what(); - std::cout << "exception caught: " << err_msg << std::endl; - } -} \ No newline at end of file + j++; + } + if (IsNGForAll) + { + /*to do something*/ + } + } + } + catch (cv::Exception& e) + { + const char* err_msg = e.what(); + std::cout << "exception caught: " << err_msg << std::endl; + } +} diff --git a/Cigarette/syncworkthread.h b/Cigarette/syncworkthread.h index c5217935..e2231ed0 100644 --- a/Cigarette/syncworkthread.h +++ b/Cigarette/syncworkthread.h @@ -14,33 +14,33 @@ class SyncWorkThread : #ifdef SYNC_CAMERA signals: - void notify(int Num, int Cnt, cv::Mat); - void display_timecost(int Num, int ms); - void display_check_total(int Num, long no); - void display_jd_no(int Num, QString jd_no); + void notify(int Num, int Cnt, cv::Mat); + void display_timecost(int Num, int ms); + void display_check_total(int Num, long no); + void display_jd_no(int Num, QString jd_no); - void event_ok(int Num); - void event_ng(int Num); + void event_ok(int Num); + void event_ng(int Num); #endif public: - SyncWorkThread(QObject* parent = 0) : QThread(parent) - { + SyncWorkThread(QObject* parent = 0) : QThread(parent) + { - } - ~SyncWorkThread(); + } + ~SyncWorkThread(); - void init(SyncQueue>>* image_ptr, ASyncQueue* result_ptr); - void start_work(); - void stop(); + void init(SyncQueue>>* image_ptr, ASyncQueue* result_ptr); + void start_work(); + void stop(); protected: - void run(); + void run(); public: - int local_camera_number; - SyncQueue>>* local_g_image_sync_queue; - ASyncQueue* local_g_result_queue; - bool b_quit; - long frame_total[NumberOfSupportedCameras]; - SysConf local_SysConf; - DisplayLabelConf local_DisplayLabelConf; -}; \ No newline at end of file + int local_camera_number; + SyncQueue>>* local_g_image_sync_queue; + ASyncQueue* local_g_result_queue; + bool b_quit; + long frame_total[NumberOfSupportedCameras]; + SysConf local_SysConf; + DisplayLabelConf local_DisplayLabelConf; +}; diff --git a/Cigarette/threadReceive.cpp b/Cigarette/threadReceive.cpp index 767cb588..54dab302 100644 --- a/Cigarette/threadReceive.cpp +++ b/Cigarette/threadReceive.cpp @@ -3,87 +3,87 @@ #include "basecamera.h" void threadReceive::start_work() { - //start(HighestPriority); - start(); + //start(HighestPriority); + start(); } void threadReceive::stop() { - isLoop = false; - BOOL bDontLinger = FALSE; - mSocket->abort(); - filemSocket->abort(); - // wait(); + isLoop = false; + BOOL bDontLinger = FALSE; + mSocket->abort(); + filemSocket->abort(); + // wait(); } -void threadReceive::init(std::string IP,int port) +void threadReceive::init(std::string IP, int port) { - ip = QString::fromStdString(IP); + ip = QString::fromStdString(IP); - mSocket = new QUdpSocket(this); - mSocket->bind(port + NumberOfSupportedCameras*2+1, QUdpSocket::ShareAddress); - connect(mSocket, &QUdpSocket::readyRead, this, &threadReceive::processPendingDatagram); + mSocket = new QUdpSocket(this); + mSocket->bind(port + NumberOfSupportedCameras * 2 + 1, QUdpSocket::ShareAddress); + connect(mSocket, &QUdpSocket::readyRead, this, &threadReceive::processPendingDatagram); - filemSocket = new QUdpSocket(this); - filemSocket->bind(port + NumberOfSupportedCameras*2+2, QUdpSocket::ShareAddress); - connect(filemSocket, &QUdpSocket::readyRead, this, &threadReceive::fileprocessPendingDatagram); + filemSocket = new QUdpSocket(this); + filemSocket->bind(port + NumberOfSupportedCameras * 2 + 2, QUdpSocket::ShareAddress); + connect(filemSocket, &QUdpSocket::readyRead, this, &threadReceive::fileprocessPendingDatagram); } void threadReceive::processPendingDatagram() { - // 拥有等待的数据报 - while (mSocket->hasPendingDatagrams()) - { - QByteArray datagram; + // 鎷ユ湁绛夊緟鐨勬暟鎹姤 + while (mSocket->hasPendingDatagrams()) + { + QByteArray datagram; - // 让datagram的大小为等待处理的数据报的大小,这样才能接收到完整的数据 - datagram.resize(mSocket->pendingDatagramSize()); + // 璁ヾatagram鐨勫ぇ灏忎负绛夊緟澶勭悊鐨勬暟鎹姤鐨勫ぇ灏忥紝杩欐牱鎵嶈兘鎺ユ敹鍒板畬鏁寸殑鏁版嵁 + datagram.resize(mSocket->pendingDatagramSize()); - // 接收数据报,将其存放到datagram中 - mSocket->readDatagram(datagram.data(), datagram.size()); - QString data = datagram; + // 鎺ユ敹鏁版嵁鎶ワ紝灏嗗叾瀛樻斁鍒癲atagram涓 + mSocket->readDatagram(datagram.data(), datagram.size()); + QString data = datagram; - emit sendMsgToCigratte(data); - } + emit sendMsgToCigratte(data); + } } void threadReceive::fileprocessPendingDatagram() { - QString filename; - std::fstream file; - // 拥有等待的数据报 - while (filemSocket->hasPendingDatagrams()) - { - QByteArray datagram; - // 让datagram的大小为等待处理的数据报的大小,这样才能接收到完整的数据 - datagram.resize(filemSocket->pendingDatagramSize()); + QString filename; + std::fstream file; + // 鎷ユ湁绛夊緟鐨勬暟鎹姤 + while (filemSocket->hasPendingDatagrams()) + { + QByteArray datagram; + // 璁ヾatagram鐨勫ぇ灏忎负绛夊緟澶勭悊鐨勬暟鎹姤鐨勫ぇ灏忥紝杩欐牱鎵嶈兘鎺ユ敹鍒板畬鏁寸殑鏁版嵁 + datagram.resize(filemSocket->pendingDatagramSize()); - // 接收数据报,将其存放到datagram中 - filemSocket->readDatagram(datagram.data(), datagram.size()); - QString data = datagram; + // 鎺ユ敹鏁版嵁鎶ワ紝灏嗗叾瀛樻斁鍒癲atagram涓 + filemSocket->readDatagram(datagram.data(), datagram.size()); + QString data = datagram; - QString str = data.mid(0, 4); - if (str == "SYNC") - { - str = data.mid(4, 3); - if (str == "str") - { - filename = data.mid(7, data.length() - 7); - file.open(("../conf/" + filename.toStdString()).c_str(), std::ios::out | std::ios::trunc | ios::binary); - } - else if (str == "con") - { - str = data.mid(7, data.length() - 7); - if (file.is_open()) - { - file.write(str.toStdString().c_str(), str.toStdString().size()); - } - } - else if (str == "end") - { - str = data.mid(7, data.length() - 7); - file.close(); - } - } - } -} \ No newline at end of file + QString str = data.mid(0, 4); + if (str == "SYNC") + { + str = data.mid(4, 3); + if (str == "str") + { + filename = data.mid(7, data.length() - 7); + file.open(("../conf/" + filename.toStdString()).c_str(), std::ios::out | std::ios::trunc | ios::binary); + } + else if (str == "con") + { + str = data.mid(7, data.length() - 7); + if (file.is_open()) + { + file.write(str.toStdString().c_str(), str.toStdString().size()); + } + } + else if (str == "end") + { + str = data.mid(7, data.length() - 7); + file.close(); + } + } + } +} diff --git a/Cigarette/threadReceive.h b/Cigarette/threadReceive.h index 15173bed..b6ffbb66 100644 --- a/Cigarette/threadReceive.h +++ b/Cigarette/threadReceive.h @@ -13,33 +13,33 @@ class threadReceive : public QThread { - Q_OBJECT + Q_OBJECT public: - QString ip; - threadReceive(QObject* o = nullptr) :QThread(o) - { - isLoop = true; - } + QString ip; + threadReceive(QObject* o = nullptr) :QThread(o) + { + isLoop = true; + } - ~threadReceive() - { - stop(); - quit(); - wait(); - } - void stop(); - void init(std::string IP,int port); - void start_work(); + ~threadReceive() + { + stop(); + quit(); + wait(); + } + void stop(); + void init(std::string IP, int port); + void start_work(); private slots: - void processPendingDatagram(); - void fileprocessPendingDatagram(); + void processPendingDatagram(); + void fileprocessPendingDatagram(); signals: - void sendMsgToCigratte(QString data); + void sendMsgToCigratte(QString data); public: - std::atomic_bool isLoop = { 0 }; - QUdpSocket *mSocket; - QUdpSocket *filemSocket; + std::atomic_bool isLoop = { 0 }; + QUdpSocket* mSocket; + QUdpSocket* filemSocket; }; diff --git a/Cigarette/threadSend.cpp b/Cigarette/threadSend.cpp index 4ea86e66..0ee3fdb6 100644 --- a/Cigarette/threadSend.cpp +++ b/Cigarette/threadSend.cpp @@ -3,13 +3,13 @@ #include "basecamera.h" #include #include -void threadSend::init(SyncQueue<_UDPSendInfo> *p_UDP_Info_queue,std::string IP,int port) +void threadSend::init(SyncQueue<_UDPSendInfo>* p_UDP_Info_queue, std::string IP, int port) { ip = QString::fromStdString(IP); dataport = port; - imageport = port+NumberOfSupportedCameras; + imageport = port + NumberOfSupportedCameras; Local_UDP_Info_queue = p_UDP_Info_queue; - qDebug() << "MonitorIP ip:"<take(UDPSendInfo); - switch(UDPSendInfo.FrameID){ - case info_frame:{ - sendData(&UDPSendInfo, dataport); - break; - } - case speed_frame:{ - sendSpeed(&UDPSendInfo, dataport); - break; - } - case kick_frame:{ - sendKick(&UDPSendInfo, dataport); - break; - } - case ok_frame:{ - sendOK(&UDPSendInfo, dataport); - break; - } - case ng_frame:{ - sendNG(&UDPSendInfo, dataport); - break; - } - case total_frame:{ - sendTotal(&UDPSendInfo, dataport); - break; - } - case image_frame:{ - sendImage(&UDPSendInfo,imageport); - break; - } + switch (UDPSendInfo.FrameID) { + case info_frame: { + sendData(&UDPSendInfo, dataport); + break; + } + case speed_frame: { + sendSpeed(&UDPSendInfo, dataport); + break; + } + case kick_frame: { + sendKick(&UDPSendInfo, dataport); + break; + } + case ok_frame: { + sendOK(&UDPSendInfo, dataport); + break; + } + case ng_frame: { + sendNG(&UDPSendInfo, dataport); + break; + } + case total_frame: { + sendTotal(&UDPSendInfo, dataport); + break; + } + case image_frame: { + sendImage(&UDPSendInfo, imageport); + break; + } } } } -void threadSend::sendData(_UDPSendInfo *UDPSendInfo,int port) +void threadSend::sendData(_UDPSendInfo* UDPSendInfo, int port) { QString res = QString("%1_%2_%3") .arg(QString::number(UDPSendInfo->FrameID)) @@ -76,26 +76,26 @@ void threadSend::sendData(QString data, int port) mSocket.writeDatagram(data.toUtf8(), QHostAddress(ip), port); } -void threadSend::sendImage(_UDPSendInfo *UDPSendInfo,int port) +void threadSend::sendImage(_UDPSendInfo* UDPSendInfo, int port) { cv::Mat mat = UDPSendInfo->image; char cnt = UDPSendInfo->cnt; //cv::resize(mat, mat, cv::Size(image_width, image_heigh)); - cv::resize(mat, mat, cv::Size(image_width, image_heigh),4,4,2); + cv::resize(mat, mat, cv::Size(image_width, image_heigh), 4, 4, 2); int length = image_width * image_heigh * 3; char* data = (char*)malloc(sizeof(char) * length + 1); if (data) { memcpy(data, &cnt, 1); - memcpy(data+1, mat.data, length); - int ret=mSocket.writeDatagram((char*)data, length+1, QHostAddress(ip), port + UDPSendInfo->index); + memcpy(data + 1, mat.data, length); + int ret = mSocket.writeDatagram((char*)data, length + 1, QHostAddress(ip), port + UDPSendInfo->index); free(data); } } -void threadSend::sendSpeed(_UDPSendInfo *UDPSendInfo,int port) +void threadSend::sendSpeed(_UDPSendInfo* UDPSendInfo, int port) { QString res = QString("%1_%2") .arg(QString::number(UDPSendInfo->FrameID)) @@ -103,7 +103,7 @@ void threadSend::sendSpeed(_UDPSendInfo *UDPSendInfo,int port) mSocket.writeDatagram(res.toUtf8(), QHostAddress(ip), port + UDPSendInfo->index); } -void threadSend::sendKick(_UDPSendInfo *UDPSendInfo,int port) +void threadSend::sendKick(_UDPSendInfo* UDPSendInfo, int port) { QString res = QString("%1_%2") .arg(QString::number(UDPSendInfo->FrameID)) @@ -111,7 +111,7 @@ void threadSend::sendKick(_UDPSendInfo *UDPSendInfo,int port) mSocket.writeDatagram(res.toUtf8(), QHostAddress(ip), port + UDPSendInfo->index); } -void threadSend::sendOK(_UDPSendInfo *UDPSendInfo,int port) +void threadSend::sendOK(_UDPSendInfo* UDPSendInfo, int port) { QString res = QString("%1_%2") .arg(QString::number(UDPSendInfo->FrameID)) @@ -119,7 +119,7 @@ void threadSend::sendOK(_UDPSendInfo *UDPSendInfo,int port) mSocket.writeDatagram(res.toUtf8(), QHostAddress(ip), port + UDPSendInfo->index); } -void threadSend::sendNG(_UDPSendInfo *UDPSendInfo,int port) +void threadSend::sendNG(_UDPSendInfo* UDPSendInfo, int port) { QString res = QString("%1_%2") .arg(QString::number(UDPSendInfo->FrameID)) @@ -127,7 +127,7 @@ void threadSend::sendNG(_UDPSendInfo *UDPSendInfo,int port) mSocket.writeDatagram(res.toUtf8(), QHostAddress(ip), port + UDPSendInfo->index); } -void threadSend::sendTotal(_UDPSendInfo *UDPSendInfo,int port) +void threadSend::sendTotal(_UDPSendInfo* UDPSendInfo, int port) { QString res = QString("%1_%2") .arg(QString::number(UDPSendInfo->FrameID)) @@ -143,11 +143,11 @@ void threadSend::sendFile(QString FilePath, int port) if (file.size() > 0) { bool isOk = file.open(QIODevice::ReadOnly); if (false == isOk) { - return ; + return; } } else { - return ; + return; } QString sync("SYNC"); if (!file.atEnd()) { @@ -157,7 +157,7 @@ void threadSend::sendFile(QString FilePath, int port) mSocket.writeDatagram(FileStartFrame.toLatin1(), QHostAddress(ip), port); } - msleep(10); + msleep(10); while (!file.atEnd()) {//鏂囦欢鎸囬拡 QString FileFrame(sync); FileFrame.append("con"); @@ -171,4 +171,4 @@ void threadSend::sendFile(QString FilePath, int port) FileEndFrame.append(QString::number(file.size()));//鏂囦欢澶у皬 mSocket.writeDatagram(FileEndFrame.toLatin1(), QHostAddress(ip), port); file.close(); -} \ No newline at end of file +} diff --git a/Cigarette/threadSend.h b/Cigarette/threadSend.h index ac4ff346..2c318d79 100644 --- a/Cigarette/threadSend.h +++ b/Cigarette/threadSend.h @@ -25,72 +25,72 @@ class _UDPSendInfo { public: - int FrameID; - int index; - cv::Mat image; - int cnt; - long Total; - QString JD; - QString timecost; - int ok[NumberOfSupportedCameras]; - int ng[NumberOfSupportedCameras]; - QString speed; - int Kick[NumberOfSupportedCameras]; + int FrameID; + int index; + cv::Mat image; + int cnt; + long Total; + QString JD; + QString timecost; + int ok[NumberOfSupportedCameras]; + int ng[NumberOfSupportedCameras]; + QString speed; + int Kick[NumberOfSupportedCameras]; - _UDPSendInfo() - { - FrameID = 0; - index = 0; - image = cv::Mat(image_width, image_heigh, CV_8UC3, cv::Scalar(0,0,0)); - Total = 0; - JD = QString("0,0,0"); - timecost = QString("0ms");; - for (int i = 0; i < NumberOfSupportedCameras; i++)ok[i] = 0; - for (int i = 0; i < NumberOfSupportedCameras; i++)ng[i] = 0; - speed = QString(" "); - for(int i=0;iput(UDPSendInfo); - quit(); - wait(); - } - void stop(); + ~threadSend() + { + stop(); + _UDPSendInfo UDPSendInfo; + Local_UDP_Info_queue->put(UDPSendInfo); + quit(); + wait(); + } + void stop(); protected: - void run(); + void run(); public: - void init(SyncQueue<_UDPSendInfo> *p_UDP_Info_queue,std::string IP,int port); - void start_work(); - - void sendData(_UDPSendInfo *UDPSendInfo,int port); - void sendData(QString data, int port); - void sendImage(_UDPSendInfo *UDPSendInfo,int port); - void sendSpeed(_UDPSendInfo *UDPSendInfo,int port); - void sendKick(_UDPSendInfo *UDPSendInfo,int port); - void sendOK(_UDPSendInfo *UDPSendInfo,int port); - void sendNG(_UDPSendInfo *UDPSendInfo,int port); - void sendTotal(_UDPSendInfo *UDPSendInfo,int port); - void sendFile(QString FilePath, int port); + void init(SyncQueue<_UDPSendInfo>* p_UDP_Info_queue, std::string IP, int port); + void start_work(); + + void sendData(_UDPSendInfo* UDPSendInfo, int port); + void sendData(QString data, int port); + void sendImage(_UDPSendInfo* UDPSendInfo, int port); + void sendSpeed(_UDPSendInfo* UDPSendInfo, int port); + void sendKick(_UDPSendInfo* UDPSendInfo, int port); + void sendOK(_UDPSendInfo* UDPSendInfo, int port); + void sendNG(_UDPSendInfo* UDPSendInfo, int port); + void sendTotal(_UDPSendInfo* UDPSendInfo, int port); + void sendFile(QString FilePath, int port); public: - SyncQueue<_UDPSendInfo> *Local_UDP_Info_queue; - std::atomic_bool isLoop = { 0 }; - QUdpSocket mSocket; + SyncQueue<_UDPSendInfo>* Local_UDP_Info_queue; + std::atomic_bool isLoop = { 0 }; + QUdpSocket mSocket; }; diff --git a/Cigarette/threadSendTCP.cpp b/Cigarette/threadSendTCP.cpp index 69f58054..88723aab 100644 --- a/Cigarette/threadSendTCP.cpp +++ b/Cigarette/threadSendTCP.cpp @@ -6,7 +6,6 @@ #pragma comment(lib, "ws2_32.lib") void threadSendTCP::init(SyncQueue<_TCPSendInfo>* p_TCP_Info_queue, std::string ip_, int port_) { - ip = QString::fromStdString(ip_); port = port_; qDebug() << "tcp ip:" << ip << "| tcp port:" << port; @@ -27,9 +26,9 @@ void threadSendTCP::stop() bool threadSendTCP::connectTCP() { mySocket = new QTcpSocket(); - // 取消已有的连接 + // 鍙栨秷宸叉湁鐨勮繛鎺 mySocket->abort(); - // 连接服务器 + // 杩炴帴鏈嶅姟鍣 mySocket->connectToHost(ip, port); if (!mySocket->waitForConnected(30000)) { qDebug() << "connect failed!"; @@ -58,4 +57,4 @@ void threadSendTCP::sendData(_TCPSendInfo* TCPSendInfo, int Num) { mySocket->write(fileName.c_str()); mySocket->write("\n"); mySocket->flush(); -} \ No newline at end of file +} diff --git a/Cigarette/threadSendTCP.h b/Cigarette/threadSendTCP.h index 760e9fb0..ee2e49a5 100644 --- a/Cigarette/threadSendTCP.h +++ b/Cigarette/threadSendTCP.h @@ -10,46 +10,46 @@ class _TCPSendInfo { public: - std::string pics_name; + std::string pics_name; - _TCPSendInfo() - { - pics_name = ""; - } + _TCPSendInfo() + { + pics_name = ""; + } }; class threadSendTCP : public QThread { public: - QString ip; - int port; - int num = 0; - - threadSendTCP(QObject* o = nullptr) :QThread(o) - { - isLoop = true; - } - - ~threadSendTCP() - { - stop(); - _TCPSendInfo TCPSendInfo; - Local_TCP_Info_queue->put(TCPSendInfo); - quit(); - wait(); - } - void stop(); - bool connectTCP(); + QString ip; + int port; + int num = 0; + + threadSendTCP(QObject* o = nullptr) :QThread(o) + { + isLoop = true; + } + + ~threadSendTCP() + { + stop(); + _TCPSendInfo TCPSendInfo; + Local_TCP_Info_queue->put(TCPSendInfo); + quit(); + wait(); + } + void stop(); + bool connectTCP(); protected: - void run(); + void run(); public: - void init(SyncQueue<_TCPSendInfo>* p_TCP_Info_queue, std::string ip_, int port_); - void start_work(); - void sendData(_TCPSendInfo* TCPSendInfo, int Num); + void init(SyncQueue<_TCPSendInfo>* p_TCP_Info_queue, std::string ip_, int port_); + void start_work(); + void sendData(_TCPSendInfo* TCPSendInfo, int Num); public: - SyncQueue<_TCPSendInfo>* Local_TCP_Info_queue; - std::atomic_bool isLoop = { 0 }; - QTcpSocket *mySocket; -}; \ No newline at end of file + SyncQueue<_TCPSendInfo>* Local_TCP_Info_queue; + std::atomic_bool isLoop = { 0 }; + QTcpSocket* mySocket; +}; diff --git a/Cigarette/tinyxml2.cpp b/Cigarette/tinyxml2.cpp index 05b0266f..41448ec4 100644 --- a/Cigarette/tinyxml2.cpp +++ b/Cigarette/tinyxml2.cpp @@ -33,102 +33,102 @@ distribution. #endif #if defined(_MSC_VER) && (_MSC_VER >= 1400 ) && (!defined WINCE) - // Microsoft Visual Studio, version 2005 and higher. Not WinCE. - /*int _snprintf_s( - char *buffer, - size_t sizeOfBuffer, - size_t count, - const char *format [, - argument] ... - );*/ - static inline int TIXML_SNPRINTF( char* buffer, size_t size, const char* format, ... ) - { - va_list va; - va_start( va, format ); - const int result = vsnprintf_s( buffer, size, _TRUNCATE, format, va ); - va_end( va ); - return result; - } - - static inline int TIXML_VSNPRINTF( char* buffer, size_t size, const char* format, va_list va ) - { - const int result = vsnprintf_s( buffer, size, _TRUNCATE, format, va ); - return result; - } - - #define TIXML_VSCPRINTF _vscprintf - #define TIXML_SSCANF sscanf_s +// Microsoft Visual Studio, version 2005 and higher. Not WinCE. +/*int _snprintf_s( + char *buffer, + size_t sizeOfBuffer, + size_t count, + const char *format [, + argument] ... +);*/ +static inline int TIXML_SNPRINTF(char* buffer, size_t size, const char* format, ...) +{ + va_list va; + va_start(va, format); + const int result = vsnprintf_s(buffer, size, _TRUNCATE, format, va); + va_end(va); + return result; +} + +static inline int TIXML_VSNPRINTF(char* buffer, size_t size, const char* format, va_list va) +{ + const int result = vsnprintf_s(buffer, size, _TRUNCATE, format, va); + return result; +} + +#define TIXML_VSCPRINTF _vscprintf +#define TIXML_SSCANF sscanf_s #elif defined _MSC_VER - // Microsoft Visual Studio 2003 and earlier or WinCE - #define TIXML_SNPRINTF _snprintf - #define TIXML_VSNPRINTF _vsnprintf - #define TIXML_SSCANF sscanf - #if (_MSC_VER < 1400 ) && (!defined WINCE) - // Microsoft Visual Studio 2003 and not WinCE. - #define TIXML_VSCPRINTF _vscprintf // VS2003's C runtime has this, but VC6 C runtime or WinCE SDK doesn't have. - #else - // Microsoft Visual Studio 2003 and earlier or WinCE. - static inline int TIXML_VSCPRINTF( const char* format, va_list va ) - { - int len = 512; - for (;;) { - len = len*2; - char* str = new char[len](); - const int required = _vsnprintf(str, len, format, va); - delete[] str; - if ( required != -1 ) { - TIXMLASSERT( required >= 0 ); - len = required; - break; - } - } - TIXMLASSERT( len >= 0 ); - return len; - } - #endif +// Microsoft Visual Studio 2003 and earlier or WinCE +#define TIXML_SNPRINTF _snprintf +#define TIXML_VSNPRINTF _vsnprintf +#define TIXML_SSCANF sscanf +#if (_MSC_VER < 1400 ) && (!defined WINCE) + // Microsoft Visual Studio 2003 and not WinCE. +#define TIXML_VSCPRINTF _vscprintf // VS2003's C runtime has this, but VC6 C runtime or WinCE SDK doesn't have. +#else + // Microsoft Visual Studio 2003 and earlier or WinCE. +static inline int TIXML_VSCPRINTF(const char* format, va_list va) +{ + int len = 512; + for (;;) { + len = len * 2; + char* str = new char[len](); + const int required = _vsnprintf(str, len, format, va); + delete[] str; + if (required != -1) { + TIXMLASSERT(required >= 0); + len = required; + break; + } + } + TIXMLASSERT(len >= 0); + return len; +} +#endif #else - // GCC version 3 and higher - //#warning( "Using sn* functions." ) - #define TIXML_SNPRINTF snprintf - #define TIXML_VSNPRINTF vsnprintf - static inline int TIXML_VSCPRINTF( const char* format, va_list va ) - { - int len = vsnprintf( 0, 0, format, va ); - TIXMLASSERT( len >= 0 ); - return len; - } - #define TIXML_SSCANF sscanf +// GCC version 3 and higher +//#warning( "Using sn* functions." ) +#define TIXML_SNPRINTF snprintf +#define TIXML_VSNPRINTF vsnprintf +static inline int TIXML_VSCPRINTF(const char* format, va_list va) +{ + int len = vsnprintf(0, 0, format, va); + TIXMLASSERT(len >= 0); + return len; +} +#define TIXML_SSCANF sscanf #endif #if defined(_WIN64) - #define TIXML_FSEEK _fseeki64 - #define TIXML_FTELL _ftelli64 +#define TIXML_FSEEK _fseeki64 +#define TIXML_FTELL _ftelli64 #elif defined(__APPLE__) || defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) || defined(__DragonFly__) || (__CYGWIN__) - #define TIXML_FSEEK fseeko - #define TIXML_FTELL ftello +#define TIXML_FSEEK fseeko +#define TIXML_FTELL ftello #elif defined(__ANDROID__) - #if __ANDROID_API__ > 24 - #define TIXML_FSEEK fseeko64 - #define TIXML_FTELL ftello64 - #else - #define TIXML_FSEEK fseeko - #define TIXML_FTELL ftello - #endif +#if __ANDROID_API__ > 24 +#define TIXML_FSEEK fseeko64 +#define TIXML_FTELL ftello64 +#else +#define TIXML_FSEEK fseeko +#define TIXML_FTELL ftello +#endif #elif defined(__unix__) && defined(__x86_64__) - #define TIXML_FSEEK fseeko64 - #define TIXML_FTELL ftello64 +#define TIXML_FSEEK fseeko64 +#define TIXML_FTELL ftello64 #else - #define TIXML_FSEEK fseek - #define TIXML_FTELL ftell +#define TIXML_FSEEK fseek +#define TIXML_FTELL ftell #endif -static const char LINE_FEED = static_cast(0x0a); // all line endings are normalized to LF +static const char LINE_FEED = static_cast(0x0a); // all line endings are normalized to LF static const char LF = LINE_FEED; -static const char CARRIAGE_RETURN = static_cast(0x0d); // CR gets filtered out +static const char CARRIAGE_RETURN = static_cast(0x0d); // CR gets filtered out static const char CR = CARRIAGE_RETURN; -static const char SINGLE_QUOTE = '\''; -static const char DOUBLE_QUOTE = '\"'; +static const char SINGLE_QUOTE = '\''; +static const char DOUBLE_QUOTE = '\"'; // Bunch of unicode info at: // http://www.unicode.org/faq/utf_bom.html @@ -141,315 +141,316 @@ static const unsigned char TIXML_UTF_LEAD_2 = 0xbfU; namespace tinyxml2 { -struct Entity { - const char* pattern; - int length; - char value; -}; + struct Entity { + const char* pattern; + int length; + char value; + }; -static const int NUM_ENTITIES = 5; -static const Entity entities[NUM_ENTITIES] = { - { "quot", 4, DOUBLE_QUOTE }, - { "amp", 3, '&' }, - { "apos", 4, SINGLE_QUOTE }, - { "lt", 2, '<' }, - { "gt", 2, '>' } -}; + static const int NUM_ENTITIES = 5; + static const Entity entities[NUM_ENTITIES] = { + { "quot", 4, DOUBLE_QUOTE }, + { "amp", 3, '&' }, + { "apos", 4, SINGLE_QUOTE }, + { "lt", 2, '<' }, + { "gt", 2, '>' } + }; -StrPair::~StrPair() -{ - Reset(); -} - - -void StrPair::TransferTo( StrPair* other ) -{ - if ( this == other ) { - return; + StrPair::~StrPair() + { + Reset(); } - // This in effect implements the assignment operator by "moving" - // ownership (as in auto_ptr). - TIXMLASSERT( other != 0 ); - TIXMLASSERT( other->_flags == 0 ); - TIXMLASSERT( other->_start == 0 ); - TIXMLASSERT( other->_end == 0 ); - other->Reset(); + void StrPair::TransferTo(StrPair* other) + { + if (this == other) { + return; + } + // This in effect implements the assignment operator by "moving" + // ownership (as in auto_ptr). - other->_flags = _flags; - other->_start = _start; - other->_end = _end; + TIXMLASSERT(other != 0); + TIXMLASSERT(other->_flags == 0); + TIXMLASSERT(other->_start == 0); + TIXMLASSERT(other->_end == 0); - _flags = 0; - _start = 0; - _end = 0; -} + other->Reset(); + other->_flags = _flags; + other->_start = _start; + other->_end = _end; -void StrPair::Reset() -{ - if ( _flags & NEEDS_DELETE ) { - delete [] _start; + _flags = 0; + _start = 0; + _end = 0; } - _flags = 0; - _start = 0; - _end = 0; -} - -void StrPair::SetStr( const char* str, int flags ) -{ - TIXMLASSERT( str ); - Reset(); - size_t len = strlen( str ); - TIXMLASSERT( _start == 0 ); - _start = new char[ len+1 ]; - memcpy( _start, str, len+1 ); - _end = _start + len; - _flags = flags | NEEDS_DELETE; -} - -char* StrPair::ParseText( char* p, const char* endTag, int strFlags, int* curLineNumPtr ) -{ - TIXMLASSERT( p ); - TIXMLASSERT( endTag && *endTag ); - TIXMLASSERT(curLineNumPtr); - - char* start = p; - const char endChar = *endTag; - size_t length = strlen( endTag ); - - // Inner loop of text parsing. - while ( *p ) { - if ( *p == endChar && strncmp( p, endTag, length ) == 0 ) { - Set( start, p, strFlags ); - return p + length; - } else if (*p == '\n') { - ++(*curLineNumPtr); + void StrPair::Reset() + { + if (_flags & NEEDS_DELETE) { + delete[] _start; } - ++p; - TIXMLASSERT( p ); + _flags = 0; + _start = 0; + _end = 0; } - return 0; -} -char* StrPair::ParseName( char* p ) -{ - if ( !p || !(*p) ) { - return 0; - } - if ( !XMLUtil::IsNameStartChar( (unsigned char) *p ) ) { - return 0; + void StrPair::SetStr(const char* str, int flags) + { + TIXMLASSERT(str); + Reset(); + size_t len = strlen(str); + TIXMLASSERT(_start == 0); + _start = new char[len + 1]; + memcpy(_start, str, len + 1); + _end = _start + len; + _flags = flags | NEEDS_DELETE; } - char* const start = p; - ++p; - while ( *p && XMLUtil::IsNameChar( (unsigned char) *p ) ) { - ++p; + + char* StrPair::ParseText(char* p, const char* endTag, int strFlags, int* curLineNumPtr) + { + TIXMLASSERT(p); + TIXMLASSERT(endTag && *endTag); + TIXMLASSERT(curLineNumPtr); + + char* start = p; + const char endChar = *endTag; + size_t length = strlen(endTag); + + // Inner loop of text parsing. + while (*p) { + if (*p == endChar && strncmp(p, endTag, length) == 0) { + Set(start, p, strFlags); + return p + length; + } + else if (*p == '\n') { + ++(*curLineNumPtr); + } + ++p; + TIXMLASSERT(p); + } + return 0; } - Set( start, p, 0 ); - return p; -} + char* StrPair::ParseName(char* p) + { + if (!p || !(*p)) { + return 0; + } + if (!XMLUtil::IsNameStartChar((unsigned char)*p)) { + return 0; + } -void StrPair::CollapseWhitespace() -{ - // Adjusting _start would cause undefined behavior on delete[] - TIXMLASSERT( ( _flags & NEEDS_DELETE ) == 0 ); - // Trim leading space. - _start = XMLUtil::SkipWhiteSpace( _start, 0 ); - - if ( *_start ) { - const char* p = _start; // the read pointer - char* q = _start; // the write pointer - - while( *p ) { - if ( XMLUtil::IsWhiteSpace( *p )) { - p = XMLUtil::SkipWhiteSpace( p, 0 ); - if ( *p == 0 ) { - break; // don't write to q; this trims the trailing space. - } - *q = ' '; - ++q; - } - *q = *p; - ++q; + char* const start = p; + ++p; + while (*p && XMLUtil::IsNameChar((unsigned char)*p)) { ++p; } - *q = 0; + + Set(start, p, 0); + return p; } -} -const char* StrPair::GetStr() -{ - TIXMLASSERT( _start ); - TIXMLASSERT( _end ); - if ( _flags & NEEDS_FLUSH ) { - *_end = 0; - _flags ^= NEEDS_FLUSH; + void StrPair::CollapseWhitespace() + { + // Adjusting _start would cause undefined behavior on delete[] + TIXMLASSERT((_flags & NEEDS_DELETE) == 0); + // Trim leading space. + _start = XMLUtil::SkipWhiteSpace(_start, 0); - if ( _flags ) { + if (*_start) { const char* p = _start; // the read pointer char* q = _start; // the write pointer - while( p < _end ) { - if ( (_flags & NEEDS_NEWLINE_NORMALIZATION) && *p == CR ) { - // CR-LF pair becomes LF - // CR alone becomes LF - // LF-CR becomes LF - if ( *(p+1) == LF ) { - p += 2; + while (*p) { + if (XMLUtil::IsWhiteSpace(*p)) { + p = XMLUtil::SkipWhiteSpace(p, 0); + if (*p == 0) { + break; // don't write to q; this trims the trailing space. } - else { - ++p; - } - *q = LF; - ++q; - } - else if ( (_flags & NEEDS_NEWLINE_NORMALIZATION) && *p == LF ) { - if ( *(p+1) == CR ) { - p += 2; - } - else { - ++p; - } - *q = LF; + *q = ' '; ++q; } - else if ( (_flags & NEEDS_ENTITY_PROCESSING) && *p == '&' ) { - // Entities handled by tinyXML2: - // - special entities in the entity table [in/out] - // - numeric character reference [in] - // 中 or 中 - - if ( *(p+1) == '#' ) { - const int buflen = 10; - char buf[buflen] = { 0 }; - int len = 0; - const char* adjusted = const_cast( XMLUtil::GetCharacterRef( p, buf, &len ) ); - if ( adjusted == 0 ) { - *q = *p; + *q = *p; + ++q; + ++p; + } + *q = 0; + } + } + + + const char* StrPair::GetStr() + { + TIXMLASSERT(_start); + TIXMLASSERT(_end); + if (_flags & NEEDS_FLUSH) { + *_end = 0; + _flags ^= NEEDS_FLUSH; + + if (_flags) { + const char* p = _start; // the read pointer + char* q = _start; // the write pointer + + while (p < _end) { + if ((_flags & NEEDS_NEWLINE_NORMALIZATION) && *p == CR) { + // CR-LF pair becomes LF + // CR alone becomes LF + // LF-CR becomes LF + if (*(p + 1) == LF) { + p += 2; + } + else { ++p; - ++q; + } + *q = LF; + ++q; + } + else if ((_flags & NEEDS_NEWLINE_NORMALIZATION) && *p == LF) { + if (*(p + 1) == CR) { + p += 2; } else { - TIXMLASSERT( 0 <= len && len <= buflen ); - TIXMLASSERT( q + len <= adjusted ); - p = adjusted; - memcpy( q, buf, len ); - q += len; + ++p; } + *q = LF; + ++q; } - else { - bool entityFound = false; - for( int i = 0; i < NUM_ENTITIES; ++i ) { - const Entity& entity = entities[i]; - if ( strncmp( p + 1, entity.pattern, entity.length ) == 0 - && *( p + entity.length + 1 ) == ';' ) { - // Found an entity - convert. - *q = entity.value; + else if ((_flags & NEEDS_ENTITY_PROCESSING) && *p == '&') { + // Entities handled by tinyXML2: + // - special entities in the entity table [in/out] + // - numeric character reference [in] + // 中 or 中 + + if (*(p + 1) == '#') { + const int buflen = 10; + char buf[buflen] = { 0 }; + int len = 0; + const char* adjusted = const_cast(XMLUtil::GetCharacterRef(p, buf, &len)); + if (adjusted == 0) { + *q = *p; + ++p; ++q; - p += entity.length + 2; - entityFound = true; - break; + } + else { + TIXMLASSERT(0 <= len && len <= buflen); + TIXMLASSERT(q + len <= adjusted); + p = adjusted; + memcpy(q, buf, len); + q += len; } } - if ( !entityFound ) { - // fixme: treat as error? - ++p; - ++q; + else { + bool entityFound = false; + for (int i = 0; i < NUM_ENTITIES; ++i) { + const Entity& entity = entities[i]; + if (strncmp(p + 1, entity.pattern, entity.length) == 0 + && *(p + entity.length + 1) == ';') { + // Found an entity - convert. + *q = entity.value; + ++q; + p += entity.length + 2; + entityFound = true; + break; + } + } + if (!entityFound) { + // fixme: treat as error? + ++p; + ++q; + } } } + else { + *q = *p; + ++p; + ++q; + } } - else { - *q = *p; - ++p; - ++q; - } + *q = 0; } - *q = 0; - } - // The loop below has plenty going on, and this - // is a less useful mode. Break it out. - if ( _flags & NEEDS_WHITESPACE_COLLAPSING ) { - CollapseWhitespace(); + // The loop below has plenty going on, and this + // is a less useful mode. Break it out. + if (_flags & NEEDS_WHITESPACE_COLLAPSING) { + CollapseWhitespace(); + } + _flags = (_flags & NEEDS_DELETE); } - _flags = (_flags & NEEDS_DELETE); + TIXMLASSERT(_start); + return _start; } - TIXMLASSERT( _start ); - return _start; -} -// --------- XMLUtil ----------- // + // --------- XMLUtil ----------- // -const char* XMLUtil::writeBoolTrue = "true"; -const char* XMLUtil::writeBoolFalse = "false"; + const char* XMLUtil::writeBoolTrue = "true"; + const char* XMLUtil::writeBoolFalse = "false"; -void XMLUtil::SetBoolSerialization(const char* writeTrue, const char* writeFalse) -{ - static const char* defTrue = "true"; - static const char* defFalse = "false"; + void XMLUtil::SetBoolSerialization(const char* writeTrue, const char* writeFalse) + { + static const char* defTrue = "true"; + static const char* defFalse = "false"; - writeBoolTrue = (writeTrue) ? writeTrue : defTrue; - writeBoolFalse = (writeFalse) ? writeFalse : defFalse; -} + writeBoolTrue = (writeTrue) ? writeTrue : defTrue; + writeBoolFalse = (writeFalse) ? writeFalse : defFalse; + } -const char* XMLUtil::ReadBOM( const char* p, bool* bom ) -{ - TIXMLASSERT( p ); - TIXMLASSERT( bom ); - *bom = false; - const unsigned char* pu = reinterpret_cast(p); - // Check for BOM: - if ( *(pu+0) == TIXML_UTF_LEAD_0 - && *(pu+1) == TIXML_UTF_LEAD_1 - && *(pu+2) == TIXML_UTF_LEAD_2 ) { - *bom = true; - p += 3; - } - TIXMLASSERT( p ); - return p; -} + const char* XMLUtil::ReadBOM(const char* p, bool* bom) + { + TIXMLASSERT(p); + TIXMLASSERT(bom); + *bom = false; + const unsigned char* pu = reinterpret_cast(p); + // Check for BOM: + if (*(pu + 0) == TIXML_UTF_LEAD_0 + && *(pu + 1) == TIXML_UTF_LEAD_1 + && *(pu + 2) == TIXML_UTF_LEAD_2) { + *bom = true; + p += 3; + } + TIXMLASSERT(p); + return p; + } -void XMLUtil::ConvertUTF32ToUTF8( unsigned long input, char* output, int* length ) -{ - const unsigned long BYTE_MASK = 0xBF; - const unsigned long BYTE_MARK = 0x80; - const unsigned long FIRST_BYTE_MARK[7] = { 0x00, 0x00, 0xC0, 0xE0, 0xF0, 0xF8, 0xFC }; + void XMLUtil::ConvertUTF32ToUTF8(unsigned long input, char* output, int* length) + { + const unsigned long BYTE_MASK = 0xBF; + const unsigned long BYTE_MARK = 0x80; + const unsigned long FIRST_BYTE_MARK[7] = { 0x00, 0x00, 0xC0, 0xE0, 0xF0, 0xF8, 0xFC }; - if (input < 0x80) { - *length = 1; - } - else if ( input < 0x800 ) { - *length = 2; - } - else if ( input < 0x10000 ) { - *length = 3; - } - else if ( input < 0x200000 ) { - *length = 4; - } - else { - *length = 0; // This code won't convert this correctly anyway. - return; - } + if (input < 0x80) { + *length = 1; + } + else if (input < 0x800) { + *length = 2; + } + else if (input < 0x10000) { + *length = 3; + } + else if (input < 0x200000) { + *length = 4; + } + else { + *length = 0; // This code won't convert this correctly anyway. + return; + } - output += *length; + output += *length; - // Scary scary fall throughs are annotated with carefully designed comments - // to suppress compiler warnings such as -Wimplicit-fallthrough in gcc - switch (*length) { + // Scary scary fall throughs are annotated with carefully designed comments + // to suppress compiler warnings such as -Wimplicit-fallthrough in gcc + switch (*length) { case 4: --output; *output = static_cast((input | BYTE_MARK) & BYTE_MASK); @@ -470,2525 +471,2526 @@ void XMLUtil::ConvertUTF32ToUTF8( unsigned long input, char* output, int* length *output = static_cast(input | FIRST_BYTE_MARK[*length]); break; default: - TIXMLASSERT( false ); + TIXMLASSERT(false); + } } -} - - -const char* XMLUtil::GetCharacterRef( const char* p, char* value, int* length ) -{ - // Presume an entity, and pull it out. - *length = 0; - - if ( *(p+1) == '#' && *(p+2) ) { - unsigned long ucs = 0; - TIXMLASSERT( sizeof( ucs ) >= 4 ); - ptrdiff_t delta = 0; - unsigned mult = 1; - static const char SEMICOLON = ';'; - - if ( *(p+2) == 'x' ) { - // Hexadecimal. - const char* q = p+3; - if ( !(*q) ) { - return 0; - } - q = strchr( q, SEMICOLON ); - - if ( !q ) { - return 0; - } - TIXMLASSERT( *q == SEMICOLON ); - delta = q-p; - --q; + const char* XMLUtil::GetCharacterRef(const char* p, char* value, int* length) + { + // Presume an entity, and pull it out. + *length = 0; + + if (*(p + 1) == '#' && *(p + 2)) { + unsigned long ucs = 0; + TIXMLASSERT(sizeof(ucs) >= 4); + ptrdiff_t delta = 0; + unsigned mult = 1; + static const char SEMICOLON = ';'; + + if (*(p + 2) == 'x') { + // Hexadecimal. + const char* q = p + 3; + if (!(*q)) { + return 0; + } - while ( *q != 'x' ) { - unsigned int digit = 0; + q = strchr(q, SEMICOLON); - if ( *q >= '0' && *q <= '9' ) { - digit = *q - '0'; - } - else if ( *q >= 'a' && *q <= 'f' ) { - digit = *q - 'a' + 10; - } - else if ( *q >= 'A' && *q <= 'F' ) { - digit = *q - 'A' + 10; - } - else { + if (!q) { return 0; } - TIXMLASSERT( digit < 16 ); - TIXMLASSERT( digit == 0 || mult <= UINT_MAX / digit ); - const unsigned int digitScaled = mult * digit; - TIXMLASSERT( ucs <= ULONG_MAX - digitScaled ); - ucs += digitScaled; - TIXMLASSERT( mult <= UINT_MAX / 16 ); - mult *= 16; - --q; - } - } - else { - // Decimal. - const char* q = p+2; - if ( !(*q) ) { - return 0; - } + TIXMLASSERT(*q == SEMICOLON); - q = strchr( q, SEMICOLON ); - - if ( !q ) { - return 0; - } - TIXMLASSERT( *q == SEMICOLON ); + delta = q - p; + --q; - delta = q-p; - --q; + while (*q != 'x') { + unsigned int digit = 0; - while ( *q != '#' ) { - if ( *q >= '0' && *q <= '9' ) { - const unsigned int digit = *q - '0'; - TIXMLASSERT( digit < 10 ); - TIXMLASSERT( digit == 0 || mult <= UINT_MAX / digit ); + if (*q >= '0' && *q <= '9') { + digit = *q - '0'; + } + else if (*q >= 'a' && *q <= 'f') { + digit = *q - 'a' + 10; + } + else if (*q >= 'A' && *q <= 'F') { + digit = *q - 'A' + 10; + } + else { + return 0; + } + TIXMLASSERT(digit < 16); + TIXMLASSERT(digit == 0 || mult <= UINT_MAX / digit); const unsigned int digitScaled = mult * digit; - TIXMLASSERT( ucs <= ULONG_MAX - digitScaled ); + TIXMLASSERT(ucs <= ULONG_MAX - digitScaled); ucs += digitScaled; + TIXMLASSERT(mult <= UINT_MAX / 16); + mult *= 16; + --q; } - else { + } + else { + // Decimal. + const char* q = p + 2; + if (!(*q)) { + return 0; + } + + q = strchr(q, SEMICOLON); + + if (!q) { return 0; } - TIXMLASSERT( mult <= UINT_MAX / 10 ); - mult *= 10; + TIXMLASSERT(*q == SEMICOLON); + + delta = q - p; --q; + + while (*q != '#') { + if (*q >= '0' && *q <= '9') { + const unsigned int digit = *q - '0'; + TIXMLASSERT(digit < 10); + TIXMLASSERT(digit == 0 || mult <= UINT_MAX / digit); + const unsigned int digitScaled = mult * digit; + TIXMLASSERT(ucs <= ULONG_MAX - digitScaled); + ucs += digitScaled; + } + else { + return 0; + } + TIXMLASSERT(mult <= UINT_MAX / 10); + mult *= 10; + --q; + } } + // convert the UCS to UTF-8 + ConvertUTF32ToUTF8(ucs, value, length); + return p + delta + 1; } - // convert the UCS to UTF-8 - ConvertUTF32ToUTF8( ucs, value, length ); - return p + delta + 1; + return p + 1; } - return p+1; -} - - -void XMLUtil::ToStr( int v, char* buffer, int bufferSize ) -{ - TIXML_SNPRINTF( buffer, bufferSize, "%d", v ); -} -void XMLUtil::ToStr( unsigned v, char* buffer, int bufferSize ) -{ - TIXML_SNPRINTF( buffer, bufferSize, "%u", v ); -} + void XMLUtil::ToStr(int v, char* buffer, int bufferSize) + { + TIXML_SNPRINTF(buffer, bufferSize, "%d", v); + } -void XMLUtil::ToStr( bool v, char* buffer, int bufferSize ) -{ - TIXML_SNPRINTF( buffer, bufferSize, "%s", v ? writeBoolTrue : writeBoolFalse); -} + void XMLUtil::ToStr(unsigned v, char* buffer, int bufferSize) + { + TIXML_SNPRINTF(buffer, bufferSize, "%u", v); + } -/* - ToStr() of a number is a very tricky topic. - https://github.com/leethomason/tinyxml2/issues/106 -*/ -void XMLUtil::ToStr( float v, char* buffer, int bufferSize ) -{ - TIXML_SNPRINTF( buffer, bufferSize, "%.8g", v ); -} + void XMLUtil::ToStr(bool v, char* buffer, int bufferSize) + { + TIXML_SNPRINTF(buffer, bufferSize, "%s", v ? writeBoolTrue : writeBoolFalse); + } -void XMLUtil::ToStr( double v, char* buffer, int bufferSize ) -{ - TIXML_SNPRINTF( buffer, bufferSize, "%.17g", v ); -} + /* + ToStr() of a number is a very tricky topic. + https://github.com/leethomason/tinyxml2/issues/106 + */ + void XMLUtil::ToStr(float v, char* buffer, int bufferSize) + { + TIXML_SNPRINTF(buffer, bufferSize, "%.8g", v); + } -void XMLUtil::ToStr( int64_t v, char* buffer, int bufferSize ) -{ - // horrible syntax trick to make the compiler happy about %lld - TIXML_SNPRINTF(buffer, bufferSize, "%lld", static_cast(v)); -} + void XMLUtil::ToStr(double v, char* buffer, int bufferSize) + { + TIXML_SNPRINTF(buffer, bufferSize, "%.17g", v); + } -void XMLUtil::ToStr( uint64_t v, char* buffer, int bufferSize ) -{ - // horrible syntax trick to make the compiler happy about %llu - TIXML_SNPRINTF(buffer, bufferSize, "%llu", (long long)v); -} -bool XMLUtil::ToInt(const char* str, int* value) -{ - if (IsPrefixHex(str)) { - unsigned v; - if (TIXML_SSCANF(str, "%x", &v) == 1) { - *value = static_cast(v); - return true; - } - } - else { - if (TIXML_SSCANF(str, "%d", value) == 1) { - return true; - } + void XMLUtil::ToStr(int64_t v, char* buffer, int bufferSize) + { + // horrible syntax trick to make the compiler happy about %lld + TIXML_SNPRINTF(buffer, bufferSize, "%lld", static_cast(v)); } - return false; -} -bool XMLUtil::ToUnsigned(const char* str, unsigned* value) -{ - if (TIXML_SSCANF(str, IsPrefixHex(str) ? "%x" : "%u", value) == 1) { - return true; + void XMLUtil::ToStr(uint64_t v, char* buffer, int bufferSize) + { + // horrible syntax trick to make the compiler happy about %llu + TIXML_SNPRINTF(buffer, bufferSize, "%llu", (long long)v); } - return false; -} -bool XMLUtil::ToBool( const char* str, bool* value ) -{ - int ival = 0; - if ( ToInt( str, &ival )) { - *value = (ival==0) ? false : true; - return true; + bool XMLUtil::ToInt(const char* str, int* value) + { + if (IsPrefixHex(str)) { + unsigned v; + if (TIXML_SSCANF(str, "%x", &v) == 1) { + *value = static_cast(v); + return true; + } + } + else { + if (TIXML_SSCANF(str, "%d", value) == 1) { + return true; + } + } + return false; } - static const char* TRUE_VALS[] = { "true", "True", "TRUE", 0 }; - static const char* FALSE_VALS[] = { "false", "False", "FALSE", 0 }; - for (int i = 0; TRUE_VALS[i]; ++i) { - if (StringEqual(str, TRUE_VALS[i])) { - *value = true; + bool XMLUtil::ToUnsigned(const char* str, unsigned* value) + { + if (TIXML_SSCANF(str, IsPrefixHex(str) ? "%x" : "%u", value) == 1) { return true; } + return false; } - for (int i = 0; FALSE_VALS[i]; ++i) { - if (StringEqual(str, FALSE_VALS[i])) { - *value = false; + + bool XMLUtil::ToBool(const char* str, bool* value) + { + int ival = 0; + if (ToInt(str, &ival)) { + *value = (ival == 0) ? false : true; return true; } - } - return false; -} + static const char* TRUE_VALS[] = { "true", "True", "TRUE", 0 }; + static const char* FALSE_VALS[] = { "false", "False", "FALSE", 0 }; - -bool XMLUtil::ToFloat( const char* str, float* value ) -{ - if ( TIXML_SSCANF( str, "%f", value ) == 1 ) { - return true; + for (int i = 0; TRUE_VALS[i]; ++i) { + if (StringEqual(str, TRUE_VALS[i])) { + *value = true; + return true; + } + } + for (int i = 0; FALSE_VALS[i]; ++i) { + if (StringEqual(str, FALSE_VALS[i])) { + *value = false; + return true; + } + } + return false; } - return false; -} -bool XMLUtil::ToDouble( const char* str, double* value ) -{ - if ( TIXML_SSCANF( str, "%lf", value ) == 1 ) { - return true; + bool XMLUtil::ToFloat(const char* str, float* value) + { + if (TIXML_SSCANF(str, "%f", value) == 1) { + return true; + } + return false; } - return false; -} -bool XMLUtil::ToInt64(const char* str, int64_t* value) -{ - if (IsPrefixHex(str)) { - unsigned long long v = 0; // horrible syntax trick to make the compiler happy about %llx - if (TIXML_SSCANF(str, "%llx", &v) == 1) { - *value = static_cast(v); + bool XMLUtil::ToDouble(const char* str, double* value) + { + if (TIXML_SSCANF(str, "%lf", value) == 1) { return true; } + return false; } - else { - long long v = 0; // horrible syntax trick to make the compiler happy about %lld - if (TIXML_SSCANF(str, "%lld", &v) == 1) { - *value = static_cast(v); - return true; + + + bool XMLUtil::ToInt64(const char* str, int64_t* value) + { + if (IsPrefixHex(str)) { + unsigned long long v = 0; // horrible syntax trick to make the compiler happy about %llx + if (TIXML_SSCANF(str, "%llx", &v) == 1) { + *value = static_cast(v); + return true; + } + } + else { + long long v = 0; // horrible syntax trick to make the compiler happy about %lld + if (TIXML_SSCANF(str, "%lld", &v) == 1) { + *value = static_cast(v); + return true; + } } + return false; } - return false; -} -bool XMLUtil::ToUnsigned64(const char* str, uint64_t* value) { - unsigned long long v = 0; // horrible syntax trick to make the compiler happy about %llu - if(TIXML_SSCANF(str, IsPrefixHex(str) ? "%llx" : "%llu", &v) == 1) { - *value = (uint64_t)v; - return true; + bool XMLUtil::ToUnsigned64(const char* str, uint64_t* value) { + unsigned long long v = 0; // horrible syntax trick to make the compiler happy about %llu + if (TIXML_SSCANF(str, IsPrefixHex(str) ? "%llx" : "%llu", &v) == 1) { + *value = (uint64_t)v; + return true; + } + return false; } - return false; -} -char* XMLDocument::Identify( char* p, XMLNode** node ) -{ - TIXMLASSERT( node ); - TIXMLASSERT( p ); - char* const start = p; - int const startLine = _parseCurLineNum; - p = XMLUtil::SkipWhiteSpace( p, &_parseCurLineNum ); - if( !*p ) { - *node = 0; - TIXMLASSERT( p ); + char* XMLDocument::Identify(char* p, XMLNode** node) + { + TIXMLASSERT(node); + TIXMLASSERT(p); + char* const start = p; + int const startLine = _parseCurLineNum; + p = XMLUtil::SkipWhiteSpace(p, &_parseCurLineNum); + if (!*p) { + *node = 0; + TIXMLASSERT(p); + return p; + } + + // These strings define the matching patterns: + static const char* xmlHeader = { "(_commentPool); + returnNode->_parseLineNum = _parseCurLineNum; + p += xmlHeaderLen; + } + else if (XMLUtil::StringEqual(p, commentHeader, commentHeaderLen)) { + returnNode = CreateUnlinkedNode(_commentPool); + returnNode->_parseLineNum = _parseCurLineNum; + p += commentHeaderLen; + } + else if (XMLUtil::StringEqual(p, cdataHeader, cdataHeaderLen)) { + XMLText* text = CreateUnlinkedNode(_textPool); + returnNode = text; + returnNode->_parseLineNum = _parseCurLineNum; + p += cdataHeaderLen; + text->SetCData(true); + } + else if (XMLUtil::StringEqual(p, dtdHeader, dtdHeaderLen)) { + returnNode = CreateUnlinkedNode(_commentPool); + returnNode->_parseLineNum = _parseCurLineNum; + p += dtdHeaderLen; + } + else if (XMLUtil::StringEqual(p, elementHeader, elementHeaderLen)) { + returnNode = CreateUnlinkedNode(_elementPool); + returnNode->_parseLineNum = _parseCurLineNum; + p += elementHeaderLen; + } + else { + returnNode = CreateUnlinkedNode(_textPool); + returnNode->_parseLineNum = _parseCurLineNum; // Report line of first non-whitespace character + p = start; // Back it up, all the text counts. + _parseCurLineNum = startLine; + } + + TIXMLASSERT(returnNode); + TIXMLASSERT(p); + *node = returnNode; return p; } - // These strings define the matching patterns: - static const char* xmlHeader = { "( _commentPool ); - returnNode->_parseLineNum = _parseCurLineNum; - p += xmlHeaderLen; - } - else if ( XMLUtil::StringEqual( p, commentHeader, commentHeaderLen ) ) { - returnNode = CreateUnlinkedNode( _commentPool ); - returnNode->_parseLineNum = _parseCurLineNum; - p += commentHeaderLen; - } - else if ( XMLUtil::StringEqual( p, cdataHeader, cdataHeaderLen ) ) { - XMLText* text = CreateUnlinkedNode( _textPool ); - returnNode = text; - returnNode->_parseLineNum = _parseCurLineNum; - p += cdataHeaderLen; - text->SetCData( true ); - } - else if ( XMLUtil::StringEqual( p, dtdHeader, dtdHeaderLen ) ) { - returnNode = CreateUnlinkedNode( _commentPool ); - returnNode->_parseLineNum = _parseCurLineNum; - p += dtdHeaderLen; - } - else if ( XMLUtil::StringEqual( p, elementHeader, elementHeaderLen ) ) { - returnNode = CreateUnlinkedNode( _elementPool ); - returnNode->_parseLineNum = _parseCurLineNum; - p += elementHeaderLen; - } - else { - returnNode = CreateUnlinkedNode( _textPool ); - returnNode->_parseLineNum = _parseCurLineNum; // Report line of first non-whitespace character - p = start; // Back it up, all the text counts. - _parseCurLineNum = startLine; - } - - TIXMLASSERT( returnNode ); - TIXMLASSERT( p ); - *node = returnNode; - return p; -} - -bool XMLDocument::Accept( XMLVisitor* visitor ) const -{ - TIXMLASSERT( visitor ); - if ( visitor->VisitEnter( *this ) ) { - for ( const XMLNode* node=FirstChild(); node; node=node->NextSibling() ) { - if ( !node->Accept( visitor ) ) { - break; + bool XMLDocument::Accept(XMLVisitor* visitor) const + { + TIXMLASSERT(visitor); + if (visitor->VisitEnter(*this)) { + for (const XMLNode* node = FirstChild(); node; node = node->NextSibling()) { + if (!node->Accept(visitor)) { + break; + } } } + return visitor->VisitExit(*this); } - return visitor->VisitExit( *this ); -} - - -// --------- XMLNode ----------- // -XMLNode::XMLNode( XMLDocument* doc ) : - _document( doc ), - _parent( 0 ), - _value(), - _parseLineNum( 0 ), - _firstChild( 0 ), _lastChild( 0 ), - _prev( 0 ), _next( 0 ), - _userData( 0 ), - _memPool( 0 ) -{ -} + // --------- XMLNode ----------- // -XMLNode::~XMLNode() -{ - DeleteChildren(); - if ( _parent ) { - _parent->Unlink( this ); + XMLNode::XMLNode(XMLDocument* doc) : + _document(doc), + _parent(0), + _value(), + _parseLineNum(0), + _firstChild(0), _lastChild(0), + _prev(0), _next(0), + _userData(0), + _memPool(0) + { } -} -const char* XMLNode::Value() const -{ - // Edge case: XMLDocuments don't have a Value. Return null. - if ( this->ToDocument() ) - return 0; - return _value.GetStr(); -} -void XMLNode::SetValue( const char* str, bool staticMem ) -{ - if ( staticMem ) { - _value.SetInternedStr( str ); - } - else { - _value.SetStr( str ); + XMLNode::~XMLNode() + { + DeleteChildren(); + if (_parent) { + _parent->Unlink(this); + } } -} -XMLNode* XMLNode::DeepClone(XMLDocument* target) const -{ - XMLNode* clone = this->ShallowClone(target); - if (!clone) return 0; - - for (const XMLNode* child = this->FirstChild(); child; child = child->NextSibling()) { - XMLNode* childClone = child->DeepClone(target); - TIXMLASSERT(childClone); - clone->InsertEndChild(childClone); - } - return clone; -} + const char* XMLNode::Value() const + { + // Edge case: XMLDocuments don't have a Value. Return null. + if (this->ToDocument()) + return 0; + return _value.GetStr(); + } -void XMLNode::DeleteChildren() -{ - while( _firstChild ) { - TIXMLASSERT( _lastChild ); - DeleteChild( _firstChild ); + void XMLNode::SetValue(const char* str, bool staticMem) + { + if (staticMem) { + _value.SetInternedStr(str); + } + else { + _value.SetStr(str); + } } - _firstChild = _lastChild = 0; -} + XMLNode* XMLNode::DeepClone(XMLDocument* target) const + { + XMLNode* clone = this->ShallowClone(target); + if (!clone) return 0; -void XMLNode::Unlink( XMLNode* child ) -{ - TIXMLASSERT( child ); - TIXMLASSERT( child->_document == _document ); - TIXMLASSERT( child->_parent == this ); - if ( child == _firstChild ) { - _firstChild = _firstChild->_next; - } - if ( child == _lastChild ) { - _lastChild = _lastChild->_prev; + for (const XMLNode* child = this->FirstChild(); child; child = child->NextSibling()) { + XMLNode* childClone = child->DeepClone(target); + TIXMLASSERT(childClone); + clone->InsertEndChild(childClone); + } + return clone; } - if ( child->_prev ) { - child->_prev->_next = child->_next; - } - if ( child->_next ) { - child->_next->_prev = child->_prev; + void XMLNode::DeleteChildren() + { + while (_firstChild) { + TIXMLASSERT(_lastChild); + DeleteChild(_firstChild); + } + _firstChild = _lastChild = 0; } - child->_next = 0; - child->_prev = 0; - child->_parent = 0; -} - -void XMLNode::DeleteChild( XMLNode* node ) -{ - TIXMLASSERT( node ); - TIXMLASSERT( node->_document == _document ); - TIXMLASSERT( node->_parent == this ); - Unlink( node ); - TIXMLASSERT(node->_prev == 0); - TIXMLASSERT(node->_next == 0); - TIXMLASSERT(node->_parent == 0); - DeleteNode( node ); -} + void XMLNode::Unlink(XMLNode* child) + { + TIXMLASSERT(child); + TIXMLASSERT(child->_document == _document); + TIXMLASSERT(child->_parent == this); + if (child == _firstChild) { + _firstChild = _firstChild->_next; + } + if (child == _lastChild) { + _lastChild = _lastChild->_prev; + } -XMLNode* XMLNode::InsertEndChild( XMLNode* addThis ) -{ - TIXMLASSERT( addThis ); - if ( addThis->_document != _document ) { - TIXMLASSERT( false ); - return 0; + if (child->_prev) { + child->_prev->_next = child->_next; + } + if (child->_next) { + child->_next->_prev = child->_prev; + } + child->_next = 0; + child->_prev = 0; + child->_parent = 0; } - InsertChildPreamble( addThis ); - - if ( _lastChild ) { - TIXMLASSERT( _firstChild ); - TIXMLASSERT( _lastChild->_next == 0 ); - _lastChild->_next = addThis; - addThis->_prev = _lastChild; - _lastChild = addThis; - addThis->_next = 0; - } - else { - TIXMLASSERT( _firstChild == 0 ); - _firstChild = _lastChild = addThis; - addThis->_prev = 0; - addThis->_next = 0; + void XMLNode::DeleteChild(XMLNode* node) + { + TIXMLASSERT(node); + TIXMLASSERT(node->_document == _document); + TIXMLASSERT(node->_parent == this); + Unlink(node); + TIXMLASSERT(node->_prev == 0); + TIXMLASSERT(node->_next == 0); + TIXMLASSERT(node->_parent == 0); + DeleteNode(node); } - addThis->_parent = this; - return addThis; -} -XMLNode* XMLNode::InsertFirstChild( XMLNode* addThis ) -{ - TIXMLASSERT( addThis ); - if ( addThis->_document != _document ) { - TIXMLASSERT( false ); - return 0; - } - InsertChildPreamble( addThis ); + XMLNode* XMLNode::InsertEndChild(XMLNode* addThis) + { + TIXMLASSERT(addThis); + if (addThis->_document != _document) { + TIXMLASSERT(false); + return 0; + } + InsertChildPreamble(addThis); - if ( _firstChild ) { - TIXMLASSERT( _lastChild ); - TIXMLASSERT( _firstChild->_prev == 0 ); + if (_lastChild) { + TIXMLASSERT(_firstChild); + TIXMLASSERT(_lastChild->_next == 0); + _lastChild->_next = addThis; + addThis->_prev = _lastChild; + _lastChild = addThis; - _firstChild->_prev = addThis; - addThis->_next = _firstChild; - _firstChild = addThis; + addThis->_next = 0; + } + else { + TIXMLASSERT(_firstChild == 0); + _firstChild = _lastChild = addThis; - addThis->_prev = 0; + addThis->_prev = 0; + addThis->_next = 0; + } + addThis->_parent = this; + return addThis; } - else { - TIXMLASSERT( _lastChild == 0 ); - _firstChild = _lastChild = addThis; - addThis->_prev = 0; - addThis->_next = 0; - } - addThis->_parent = this; - return addThis; -} + XMLNode* XMLNode::InsertFirstChild(XMLNode* addThis) + { + TIXMLASSERT(addThis); + if (addThis->_document != _document) { + TIXMLASSERT(false); + return 0; + } + InsertChildPreamble(addThis); + + if (_firstChild) { + TIXMLASSERT(_lastChild); + TIXMLASSERT(_firstChild->_prev == 0); -XMLNode* XMLNode::InsertAfterChild( XMLNode* afterThis, XMLNode* addThis ) -{ - TIXMLASSERT( addThis ); - if ( addThis->_document != _document ) { - TIXMLASSERT( false ); - return 0; - } + _firstChild->_prev = addThis; + addThis->_next = _firstChild; + _firstChild = addThis; - TIXMLASSERT( afterThis ); + addThis->_prev = 0; + } + else { + TIXMLASSERT(_lastChild == 0); + _firstChild = _lastChild = addThis; - if ( afterThis->_parent != this ) { - TIXMLASSERT( false ); - return 0; - } - if ( afterThis == addThis ) { - // Current state: BeforeThis -> AddThis -> OneAfterAddThis - // Now AddThis must disappear from it's location and then - // reappear between BeforeThis and OneAfterAddThis. - // So just leave it where it is. + addThis->_prev = 0; + addThis->_next = 0; + } + addThis->_parent = this; return addThis; } - if ( afterThis->_next == 0 ) { - // The last node or the only node. - return InsertEndChild( addThis ); - } - InsertChildPreamble( addThis ); - addThis->_prev = afterThis; - addThis->_next = afterThis->_next; - afterThis->_next->_prev = addThis; - afterThis->_next = addThis; - addThis->_parent = this; - return addThis; -} + XMLNode* XMLNode::InsertAfterChild(XMLNode* afterThis, XMLNode* addThis) + { + TIXMLASSERT(addThis); + if (addThis->_document != _document) { + TIXMLASSERT(false); + return 0; + } + TIXMLASSERT(afterThis); + if (afterThis->_parent != this) { + TIXMLASSERT(false); + return 0; + } + if (afterThis == addThis) { + // Current state: BeforeThis -> AddThis -> OneAfterAddThis + // Now AddThis must disappear from it's location and then + // reappear between BeforeThis and OneAfterAddThis. + // So just leave it where it is. + return addThis; + } -const XMLElement* XMLNode::FirstChildElement( const char* name ) const -{ - for( const XMLNode* node = _firstChild; node; node = node->_next ) { - const XMLElement* element = node->ToElementWithName( name ); - if ( element ) { - return element; + if (afterThis->_next == 0) { + // The last node or the only node. + return InsertEndChild(addThis); } + InsertChildPreamble(addThis); + addThis->_prev = afterThis; + addThis->_next = afterThis->_next; + afterThis->_next->_prev = addThis; + afterThis->_next = addThis; + addThis->_parent = this; + return addThis; } - return 0; -} -const XMLElement* XMLNode::LastChildElement( const char* name ) const -{ - for( const XMLNode* node = _lastChild; node; node = node->_prev ) { - const XMLElement* element = node->ToElementWithName( name ); - if ( element ) { - return element; + + + const XMLElement* XMLNode::FirstChildElement(const char* name) const + { + for (const XMLNode* node = _firstChild; node; node = node->_next) { + const XMLElement* element = node->ToElementWithName(name); + if (element) { + return element; + } } + return 0; } - return 0; -} -const XMLElement* XMLNode::NextSiblingElement( const char* name ) const -{ - for( const XMLNode* node = _next; node; node = node->_next ) { - const XMLElement* element = node->ToElementWithName( name ); - if ( element ) { - return element; + const XMLElement* XMLNode::LastChildElement(const char* name) const + { + for (const XMLNode* node = _lastChild; node; node = node->_prev) { + const XMLElement* element = node->ToElementWithName(name); + if (element) { + return element; + } } + return 0; } - return 0; -} -const XMLElement* XMLNode::PreviousSiblingElement( const char* name ) const -{ - for( const XMLNode* node = _prev; node; node = node->_prev ) { - const XMLElement* element = node->ToElementWithName( name ); - if ( element ) { - return element; + const XMLElement* XMLNode::NextSiblingElement(const char* name) const + { + for (const XMLNode* node = _next; node; node = node->_next) { + const XMLElement* element = node->ToElementWithName(name); + if (element) { + return element; + } } + return 0; } - return 0; -} - -char* XMLNode::ParseDeep( char* p, StrPair* parentEndTag, int* curLineNumPtr ) -{ - // This is a recursive method, but thinking about it "at the current level" - // it is a pretty simple flat list: - // - // - // - // With a special case: - // - // - // - // - // Where the closing element (/foo) *must* be the next thing after the opening - // element, and the names must match. BUT the tricky bit is that the closing - // element will be read by the child. - // - // 'endTag' is the end tag for this node, it is returned by a call to a child. - // 'parentEnd' is the end tag for the parent, which is filled in and returned. - XMLDocument::DepthTracker tracker(_document); - if (_document->Error()) - return 0; + const XMLElement* XMLNode::PreviousSiblingElement(const char* name) const + { + for (const XMLNode* node = _prev; node; node = node->_prev) { + const XMLElement* element = node->ToElementWithName(name); + if (element) { + return element; + } + } + return 0; + } - while( p && *p ) { - XMLNode* node = 0; - p = _document->Identify( p, &node ); - TIXMLASSERT( p ); - if ( node == 0 ) { - break; - } + char* XMLNode::ParseDeep(char* p, StrPair* parentEndTag, int* curLineNumPtr) + { + // This is a recursive method, but thinking about it "at the current level" + // it is a pretty simple flat list: + // + // + // + // With a special case: + // + // + // + // + // Where the closing element (/foo) *must* be the next thing after the opening + // element, and the names must match. BUT the tricky bit is that the closing + // element will be read by the child. + // + // 'endTag' is the end tag for this node, it is returned by a call to a child. + // 'parentEnd' is the end tag for the parent, which is filled in and returned. + + XMLDocument::DepthTracker tracker(_document); + if (_document->Error()) + return 0; - const int initialLineNum = node->_parseLineNum; + while (p && *p) { + XMLNode* node = 0; - StrPair endTag; - p = node->ParseDeep( p, &endTag, curLineNumPtr ); - if ( !p ) { - _document->DeleteNode( node ); - if ( !_document->Error() ) { - _document->SetError( XML_ERROR_PARSING, initialLineNum, 0); + p = _document->Identify(p, &node); + TIXMLASSERT(p); + if (node == 0) { + break; } - break; - } - const XMLDeclaration* const decl = node->ToDeclaration(); - if ( decl ) { - // Declarations are only allowed at document level - // - // Multiple declarations are allowed but all declarations - // must occur before anything else. - // - // Optimized due to a security test case. If the first node is - // a declaration, and the last node is a declaration, then only - // declarations have so far been added. - bool wellLocated = false; - - if (ToDocument()) { - if (FirstChild()) { - wellLocated = - FirstChild() && - FirstChild()->ToDeclaration() && - LastChild() && - LastChild()->ToDeclaration(); - } - else { - wellLocated = true; + const int initialLineNum = node->_parseLineNum; + + StrPair endTag; + p = node->ParseDeep(p, &endTag, curLineNumPtr); + if (!p) { + _document->DeleteNode(node); + if (!_document->Error()) { + _document->SetError(XML_ERROR_PARSING, initialLineNum, 0); } - } - if ( !wellLocated ) { - _document->SetError( XML_ERROR_PARSING_DECLARATION, initialLineNum, "XMLDeclaration value=%s", decl->Value()); - _document->DeleteNode( node ); break; } - } - XMLElement* ele = node->ToElement(); - if ( ele ) { - // We read the end tag. Return it to the parent. - if ( ele->ClosingType() == XMLElement::CLOSING ) { - if ( parentEndTag ) { - ele->_value.TransferTo( parentEndTag ); + const XMLDeclaration* const decl = node->ToDeclaration(); + if (decl) { + // Declarations are only allowed at document level + // + // Multiple declarations are allowed but all declarations + // must occur before anything else. + // + // Optimized due to a security test case. If the first node is + // a declaration, and the last node is a declaration, then only + // declarations have so far been added. + bool wellLocated = false; + + if (ToDocument()) { + if (FirstChild()) { + wellLocated = + FirstChild() && + FirstChild()->ToDeclaration() && + LastChild() && + LastChild()->ToDeclaration(); + } + else { + wellLocated = true; + } + } + if (!wellLocated) { + _document->SetError(XML_ERROR_PARSING_DECLARATION, initialLineNum, "XMLDeclaration value=%s", decl->Value()); + _document->DeleteNode(node); + break; } - node->_memPool->SetTracked(); // created and then immediately deleted. - DeleteNode( node ); - return p; } - // Handle an end tag returned to this level. - // And handle a bunch of annoying errors. - bool mismatch = false; - if ( endTag.Empty() ) { - if ( ele->ClosingType() == XMLElement::OPENED ) { - mismatch = true; + XMLElement* ele = node->ToElement(); + if (ele) { + // We read the end tag. Return it to the parent. + if (ele->ClosingType() == XMLElement::CLOSING) { + if (parentEndTag) { + ele->_value.TransferTo(parentEndTag); + } + node->_memPool->SetTracked(); // created and then immediately deleted. + DeleteNode(node); + return p; } - } - else { - if ( ele->ClosingType() != XMLElement::OPENED ) { - mismatch = true; + + // Handle an end tag returned to this level. + // And handle a bunch of annoying errors. + bool mismatch = false; + if (endTag.Empty()) { + if (ele->ClosingType() == XMLElement::OPENED) { + mismatch = true; + } + } + else { + if (ele->ClosingType() != XMLElement::OPENED) { + mismatch = true; + } + else if (!XMLUtil::StringEqual(endTag.GetStr(), ele->Name())) { + mismatch = true; + } } - else if ( !XMLUtil::StringEqual( endTag.GetStr(), ele->Name() ) ) { - mismatch = true; + if (mismatch) { + _document->SetError(XML_ERROR_MISMATCHED_ELEMENT, initialLineNum, "XMLElement name=%s", ele->Name()); + _document->DeleteNode(node); + break; } } - if ( mismatch ) { - _document->SetError( XML_ERROR_MISMATCHED_ELEMENT, initialLineNum, "XMLElement name=%s", ele->Name()); - _document->DeleteNode( node ); - break; - } + InsertEndChild(node); } - InsertEndChild( node ); + return 0; } - return 0; -} -/*static*/ void XMLNode::DeleteNode( XMLNode* node ) -{ - if ( node == 0 ) { - return; - } - TIXMLASSERT(node->_document); - if (!node->ToDocument()) { - node->_document->MarkInUse(node); - } + /*static*/ void XMLNode::DeleteNode(XMLNode* node) + { + if (node == 0) { + return; + } + TIXMLASSERT(node->_document); + if (!node->ToDocument()) { + node->_document->MarkInUse(node); + } - MemPool* pool = node->_memPool; - node->~XMLNode(); - pool->Free( node ); -} + MemPool* pool = node->_memPool; + node->~XMLNode(); + pool->Free(node); + } -void XMLNode::InsertChildPreamble( XMLNode* insertThis ) const -{ - TIXMLASSERT( insertThis ); - TIXMLASSERT( insertThis->_document == _document ); - - if (insertThis->_parent) { - insertThis->_parent->Unlink( insertThis ); - } - else { - insertThis->_document->MarkInUse(insertThis); - insertThis->_memPool->SetTracked(); - } -} + void XMLNode::InsertChildPreamble(XMLNode* insertThis) const + { + TIXMLASSERT(insertThis); + TIXMLASSERT(insertThis->_document == _document); -const XMLElement* XMLNode::ToElementWithName( const char* name ) const -{ - const XMLElement* element = this->ToElement(); - if ( element == 0 ) { - return 0; - } - if ( name == 0 ) { - return element; - } - if ( XMLUtil::StringEqual( element->Name(), name ) ) { - return element; + if (insertThis->_parent) { + insertThis->_parent->Unlink(insertThis); + } + else { + insertThis->_document->MarkInUse(insertThis); + insertThis->_memPool->SetTracked(); + } } - return 0; -} -// --------- XMLText ---------- // -char* XMLText::ParseDeep( char* p, StrPair*, int* curLineNumPtr ) -{ - if ( this->CData() ) { - p = _value.ParseText( p, "]]>", StrPair::NEEDS_NEWLINE_NORMALIZATION, curLineNumPtr ); - if ( !p ) { - _document->SetError( XML_ERROR_PARSING_CDATA, _parseLineNum, 0 ); + const XMLElement* XMLNode::ToElementWithName(const char* name) const + { + const XMLElement* element = this->ToElement(); + if (element == 0) { + return 0; } - return p; + if (name == 0) { + return element; + } + if (XMLUtil::StringEqual(element->Name(), name)) { + return element; + } + return 0; } - else { - int flags = _document->ProcessEntities() ? StrPair::TEXT_ELEMENT : StrPair::TEXT_ELEMENT_LEAVE_ENTITIES; - if ( _document->WhitespaceMode() == COLLAPSE_WHITESPACE ) { - flags |= StrPair::NEEDS_WHITESPACE_COLLAPSING; + + // --------- XMLText ---------- // + char* XMLText::ParseDeep(char* p, StrPair*, int* curLineNumPtr) + { + if (this->CData()) { + p = _value.ParseText(p, "]]>", StrPair::NEEDS_NEWLINE_NORMALIZATION, curLineNumPtr); + if (!p) { + _document->SetError(XML_ERROR_PARSING_CDATA, _parseLineNum, 0); + } + return p; } + else { + int flags = _document->ProcessEntities() ? StrPair::TEXT_ELEMENT : StrPair::TEXT_ELEMENT_LEAVE_ENTITIES; + if (_document->WhitespaceMode() == COLLAPSE_WHITESPACE) { + flags |= StrPair::NEEDS_WHITESPACE_COLLAPSING; + } - p = _value.ParseText( p, "<", flags, curLineNumPtr ); - if ( p && *p ) { - return p-1; + p = _value.ParseText(p, "<", flags, curLineNumPtr); + if (p && *p) { + return p - 1; + } + if (!p) { + _document->SetError(XML_ERROR_PARSING_TEXT, _parseLineNum, 0); + } } - if ( !p ) { - _document->SetError( XML_ERROR_PARSING_TEXT, _parseLineNum, 0 ); + return 0; + } + + + XMLNode* XMLText::ShallowClone(XMLDocument* doc) const + { + if (!doc) { + doc = _document; } + XMLText* text = doc->NewText(Value()); // fixme: this will always allocate memory. Intern? + text->SetCData(this->CData()); + return text; } - return 0; -} -XMLNode* XMLText::ShallowClone( XMLDocument* doc ) const -{ - if ( !doc ) { - doc = _document; + bool XMLText::ShallowEqual(const XMLNode* compare) const + { + TIXMLASSERT(compare); + const XMLText* text = compare->ToText(); + return (text && XMLUtil::StringEqual(text->Value(), Value())); } - XMLText* text = doc->NewText( Value() ); // fixme: this will always allocate memory. Intern? - text->SetCData( this->CData() ); - return text; -} -bool XMLText::ShallowEqual( const XMLNode* compare ) const -{ - TIXMLASSERT( compare ); - const XMLText* text = compare->ToText(); - return ( text && XMLUtil::StringEqual( text->Value(), Value() ) ); -} + bool XMLText::Accept(XMLVisitor* visitor) const + { + TIXMLASSERT(visitor); + return visitor->Visit(*this); + } -bool XMLText::Accept( XMLVisitor* visitor ) const -{ - TIXMLASSERT( visitor ); - return visitor->Visit( *this ); -} + // --------- XMLComment ---------- // + XMLComment::XMLComment(XMLDocument* doc) : XMLNode(doc) + { + } -// --------- XMLComment ---------- // -XMLComment::XMLComment( XMLDocument* doc ) : XMLNode( doc ) -{ -} + XMLComment::~XMLComment() + { + } -XMLComment::~XMLComment() -{ -} + char* XMLComment::ParseDeep(char* p, StrPair*, int* curLineNumPtr) + { + // Comment parses as text. + p = _value.ParseText(p, "-->", StrPair::COMMENT, curLineNumPtr); + if (p == 0) { + _document->SetError(XML_ERROR_PARSING_COMMENT, _parseLineNum, 0); + } + return p; + } -char* XMLComment::ParseDeep( char* p, StrPair*, int* curLineNumPtr ) -{ - // Comment parses as text. - p = _value.ParseText( p, "-->", StrPair::COMMENT, curLineNumPtr ); - if ( p == 0 ) { - _document->SetError( XML_ERROR_PARSING_COMMENT, _parseLineNum, 0 ); + XMLNode* XMLComment::ShallowClone(XMLDocument* doc) const + { + if (!doc) { + doc = _document; + } + XMLComment* comment = doc->NewComment(Value()); // fixme: this will always allocate memory. Intern? + return comment; } - return p; -} -XMLNode* XMLComment::ShallowClone( XMLDocument* doc ) const -{ - if ( !doc ) { - doc = _document; + bool XMLComment::ShallowEqual(const XMLNode* compare) const + { + TIXMLASSERT(compare); + const XMLComment* comment = compare->ToComment(); + return (comment && XMLUtil::StringEqual(comment->Value(), Value())); } - XMLComment* comment = doc->NewComment( Value() ); // fixme: this will always allocate memory. Intern? - return comment; -} -bool XMLComment::ShallowEqual( const XMLNode* compare ) const -{ - TIXMLASSERT( compare ); - const XMLComment* comment = compare->ToComment(); - return ( comment && XMLUtil::StringEqual( comment->Value(), Value() )); -} + bool XMLComment::Accept(XMLVisitor* visitor) const + { + TIXMLASSERT(visitor); + return visitor->Visit(*this); + } -bool XMLComment::Accept( XMLVisitor* visitor ) const -{ - TIXMLASSERT( visitor ); - return visitor->Visit( *this ); -} + // --------- XMLDeclaration ---------- // + XMLDeclaration::XMLDeclaration(XMLDocument* doc) : XMLNode(doc) + { + } -// --------- XMLDeclaration ---------- // -XMLDeclaration::XMLDeclaration( XMLDocument* doc ) : XMLNode( doc ) -{ -} + XMLDeclaration::~XMLDeclaration() + { + //printf( "~XMLDeclaration\n" ); + } -XMLDeclaration::~XMLDeclaration() -{ - //printf( "~XMLDeclaration\n" ); -} + char* XMLDeclaration::ParseDeep(char* p, StrPair*, int* curLineNumPtr) + { + // Declaration parses as text. + p = _value.ParseText(p, "?>", StrPair::NEEDS_NEWLINE_NORMALIZATION, curLineNumPtr); + if (p == 0) { + _document->SetError(XML_ERROR_PARSING_DECLARATION, _parseLineNum, 0); + } + return p; + } -char* XMLDeclaration::ParseDeep( char* p, StrPair*, int* curLineNumPtr ) -{ - // Declaration parses as text. - p = _value.ParseText( p, "?>", StrPair::NEEDS_NEWLINE_NORMALIZATION, curLineNumPtr ); - if ( p == 0 ) { - _document->SetError( XML_ERROR_PARSING_DECLARATION, _parseLineNum, 0 ); + XMLNode* XMLDeclaration::ShallowClone(XMLDocument* doc) const + { + if (!doc) { + doc = _document; + } + XMLDeclaration* dec = doc->NewDeclaration(Value()); // fixme: this will always allocate memory. Intern? + return dec; } - return p; -} -XMLNode* XMLDeclaration::ShallowClone( XMLDocument* doc ) const -{ - if ( !doc ) { - doc = _document; + bool XMLDeclaration::ShallowEqual(const XMLNode* compare) const + { + TIXMLASSERT(compare); + const XMLDeclaration* declaration = compare->ToDeclaration(); + return (declaration && XMLUtil::StringEqual(declaration->Value(), Value())); } - XMLDeclaration* dec = doc->NewDeclaration( Value() ); // fixme: this will always allocate memory. Intern? - return dec; -} -bool XMLDeclaration::ShallowEqual( const XMLNode* compare ) const -{ - TIXMLASSERT( compare ); - const XMLDeclaration* declaration = compare->ToDeclaration(); - return ( declaration && XMLUtil::StringEqual( declaration->Value(), Value() )); -} - - - -bool XMLDeclaration::Accept( XMLVisitor* visitor ) const -{ - TIXMLASSERT( visitor ); - return visitor->Visit( *this ); -} - -// --------- XMLUnknown ---------- // -XMLUnknown::XMLUnknown( XMLDocument* doc ) : XMLNode( doc ) -{ -} + bool XMLDeclaration::Accept(XMLVisitor* visitor) const + { + TIXMLASSERT(visitor); + return visitor->Visit(*this); + } + // --------- XMLUnknown ---------- // -XMLUnknown::~XMLUnknown() -{ -} + XMLUnknown::XMLUnknown(XMLDocument* doc) : XMLNode(doc) + { + } -char* XMLUnknown::ParseDeep( char* p, StrPair*, int* curLineNumPtr ) -{ - // Unknown parses as text. - p = _value.ParseText( p, ">", StrPair::NEEDS_NEWLINE_NORMALIZATION, curLineNumPtr ); - if ( !p ) { - _document->SetError( XML_ERROR_PARSING_UNKNOWN, _parseLineNum, 0 ); + XMLUnknown::~XMLUnknown() + { } - return p; -} -XMLNode* XMLUnknown::ShallowClone( XMLDocument* doc ) const -{ - if ( !doc ) { - doc = _document; + char* XMLUnknown::ParseDeep(char* p, StrPair*, int* curLineNumPtr) + { + // Unknown parses as text. + p = _value.ParseText(p, ">", StrPair::NEEDS_NEWLINE_NORMALIZATION, curLineNumPtr); + if (!p) { + _document->SetError(XML_ERROR_PARSING_UNKNOWN, _parseLineNum, 0); + } + return p; } - XMLUnknown* text = doc->NewUnknown( Value() ); // fixme: this will always allocate memory. Intern? - return text; -} -bool XMLUnknown::ShallowEqual( const XMLNode* compare ) const -{ - TIXMLASSERT( compare ); - const XMLUnknown* unknown = compare->ToUnknown(); - return ( unknown && XMLUtil::StringEqual( unknown->Value(), Value() )); -} + XMLNode* XMLUnknown::ShallowClone(XMLDocument* doc) const + { + if (!doc) { + doc = _document; + } + XMLUnknown* text = doc->NewUnknown(Value()); // fixme: this will always allocate memory. Intern? + return text; + } -bool XMLUnknown::Accept( XMLVisitor* visitor ) const -{ - TIXMLASSERT( visitor ); - return visitor->Visit( *this ); -} + bool XMLUnknown::ShallowEqual(const XMLNode* compare) const + { + TIXMLASSERT(compare); + const XMLUnknown* unknown = compare->ToUnknown(); + return (unknown && XMLUtil::StringEqual(unknown->Value(), Value())); + } -// --------- XMLAttribute ---------- // -const char* XMLAttribute::Name() const -{ - return _name.GetStr(); -} + bool XMLUnknown::Accept(XMLVisitor* visitor) const + { + TIXMLASSERT(visitor); + return visitor->Visit(*this); + } -const char* XMLAttribute::Value() const -{ - return _value.GetStr(); -} + // --------- XMLAttribute ---------- // -char* XMLAttribute::ParseDeep( char* p, bool processEntities, int* curLineNumPtr ) -{ - // Parse using the name rules: bug fix, was using ParseText before - p = _name.ParseName( p ); - if ( !p || !*p ) { - return 0; + const char* XMLAttribute::Name() const + { + return _name.GetStr(); } - // Skip white space before = - p = XMLUtil::SkipWhiteSpace( p, curLineNumPtr ); - if ( *p != '=' ) { - return 0; + const char* XMLAttribute::Value() const + { + return _value.GetStr(); } - ++p; // move up to opening quote - p = XMLUtil::SkipWhiteSpace( p, curLineNumPtr ); - if ( *p != '\"' && *p != '\'' ) { - return 0; - } + char* XMLAttribute::ParseDeep(char* p, bool processEntities, int* curLineNumPtr) + { + // Parse using the name rules: bug fix, was using ParseText before + p = _name.ParseName(p); + if (!p || !*p) { + return 0; + } - const char endTag[2] = { *p, 0 }; - ++p; // move past opening quote + // Skip white space before = + p = XMLUtil::SkipWhiteSpace(p, curLineNumPtr); + if (*p != '=') { + return 0; + } - p = _value.ParseText( p, endTag, processEntities ? StrPair::ATTRIBUTE_VALUE : StrPair::ATTRIBUTE_VALUE_LEAVE_ENTITIES, curLineNumPtr ); - return p; -} + ++p; // move up to opening quote + p = XMLUtil::SkipWhiteSpace(p, curLineNumPtr); + if (*p != '\"' && *p != '\'') { + return 0; + } + const char endTag[2] = { *p, 0 }; + ++p; // move past opening quote -void XMLAttribute::SetName( const char* n ) -{ - _name.SetStr( n ); -} + p = _value.ParseText(p, endTag, processEntities ? StrPair::ATTRIBUTE_VALUE : StrPair::ATTRIBUTE_VALUE_LEAVE_ENTITIES, curLineNumPtr); + return p; + } -XMLError XMLAttribute::QueryIntValue( int* value ) const -{ - if ( XMLUtil::ToInt( Value(), value )) { - return XML_SUCCESS; + void XMLAttribute::SetName(const char* n) + { + _name.SetStr(n); } - return XML_WRONG_ATTRIBUTE_TYPE; -} -XMLError XMLAttribute::QueryUnsignedValue( unsigned int* value ) const -{ - if ( XMLUtil::ToUnsigned( Value(), value )) { - return XML_SUCCESS; + XMLError XMLAttribute::QueryIntValue(int* value) const + { + if (XMLUtil::ToInt(Value(), value)) { + return XML_SUCCESS; + } + return XML_WRONG_ATTRIBUTE_TYPE; } - return XML_WRONG_ATTRIBUTE_TYPE; -} -XMLError XMLAttribute::QueryInt64Value(int64_t* value) const -{ - if (XMLUtil::ToInt64(Value(), value)) { - return XML_SUCCESS; - } - return XML_WRONG_ATTRIBUTE_TYPE; -} + XMLError XMLAttribute::QueryUnsignedValue(unsigned int* value) const + { + if (XMLUtil::ToUnsigned(Value(), value)) { + return XML_SUCCESS; + } + return XML_WRONG_ATTRIBUTE_TYPE; + } -XMLError XMLAttribute::QueryUnsigned64Value(uint64_t* value) const -{ - if(XMLUtil::ToUnsigned64(Value(), value)) { - return XML_SUCCESS; + XMLError XMLAttribute::QueryInt64Value(int64_t* value) const + { + if (XMLUtil::ToInt64(Value(), value)) { + return XML_SUCCESS; + } + return XML_WRONG_ATTRIBUTE_TYPE; } - return XML_WRONG_ATTRIBUTE_TYPE; -} -XMLError XMLAttribute::QueryBoolValue( bool* value ) const -{ - if ( XMLUtil::ToBool( Value(), value )) { - return XML_SUCCESS; + XMLError XMLAttribute::QueryUnsigned64Value(uint64_t* value) const + { + if (XMLUtil::ToUnsigned64(Value(), value)) { + return XML_SUCCESS; + } + return XML_WRONG_ATTRIBUTE_TYPE; } - return XML_WRONG_ATTRIBUTE_TYPE; -} -XMLError XMLAttribute::QueryFloatValue( float* value ) const -{ - if ( XMLUtil::ToFloat( Value(), value )) { - return XML_SUCCESS; + XMLError XMLAttribute::QueryBoolValue(bool* value) const + { + if (XMLUtil::ToBool(Value(), value)) { + return XML_SUCCESS; + } + return XML_WRONG_ATTRIBUTE_TYPE; } - return XML_WRONG_ATTRIBUTE_TYPE; -} -XMLError XMLAttribute::QueryDoubleValue( double* value ) const -{ - if ( XMLUtil::ToDouble( Value(), value )) { - return XML_SUCCESS; + XMLError XMLAttribute::QueryFloatValue(float* value) const + { + if (XMLUtil::ToFloat(Value(), value)) { + return XML_SUCCESS; + } + return XML_WRONG_ATTRIBUTE_TYPE; } - return XML_WRONG_ATTRIBUTE_TYPE; -} -void XMLAttribute::SetAttribute( const char* v ) -{ - _value.SetStr( v ); -} + XMLError XMLAttribute::QueryDoubleValue(double* value) const + { + if (XMLUtil::ToDouble(Value(), value)) { + return XML_SUCCESS; + } + return XML_WRONG_ATTRIBUTE_TYPE; + } -void XMLAttribute::SetAttribute( int v ) -{ - char buf[BUF_SIZE]; - XMLUtil::ToStr( v, buf, BUF_SIZE ); - _value.SetStr( buf ); -} + void XMLAttribute::SetAttribute(const char* v) + { + _value.SetStr(v); + } -void XMLAttribute::SetAttribute( unsigned v ) -{ - char buf[BUF_SIZE]; - XMLUtil::ToStr( v, buf, BUF_SIZE ); - _value.SetStr( buf ); -} + void XMLAttribute::SetAttribute(int v) + { + char buf[BUF_SIZE]; + XMLUtil::ToStr(v, buf, BUF_SIZE); + _value.SetStr(buf); + } -void XMLAttribute::SetAttribute(int64_t v) -{ - char buf[BUF_SIZE]; - XMLUtil::ToStr(v, buf, BUF_SIZE); - _value.SetStr(buf); -} + void XMLAttribute::SetAttribute(unsigned v) + { + char buf[BUF_SIZE]; + XMLUtil::ToStr(v, buf, BUF_SIZE); + _value.SetStr(buf); + } -void XMLAttribute::SetAttribute(uint64_t v) -{ - char buf[BUF_SIZE]; - XMLUtil::ToStr(v, buf, BUF_SIZE); - _value.SetStr(buf); -} + void XMLAttribute::SetAttribute(int64_t v) + { + char buf[BUF_SIZE]; + XMLUtil::ToStr(v, buf, BUF_SIZE); + _value.SetStr(buf); + } -void XMLAttribute::SetAttribute( bool v ) -{ - char buf[BUF_SIZE]; - XMLUtil::ToStr( v, buf, BUF_SIZE ); - _value.SetStr( buf ); -} + void XMLAttribute::SetAttribute(uint64_t v) + { + char buf[BUF_SIZE]; + XMLUtil::ToStr(v, buf, BUF_SIZE); + _value.SetStr(buf); + } -void XMLAttribute::SetAttribute( double v ) -{ - char buf[BUF_SIZE]; - XMLUtil::ToStr( v, buf, BUF_SIZE ); - _value.SetStr( buf ); -} -void XMLAttribute::SetAttribute( float v ) -{ - char buf[BUF_SIZE]; - XMLUtil::ToStr( v, buf, BUF_SIZE ); - _value.SetStr( buf ); -} + void XMLAttribute::SetAttribute(bool v) + { + char buf[BUF_SIZE]; + XMLUtil::ToStr(v, buf, BUF_SIZE); + _value.SetStr(buf); + } + void XMLAttribute::SetAttribute(double v) + { + char buf[BUF_SIZE]; + XMLUtil::ToStr(v, buf, BUF_SIZE); + _value.SetStr(buf); + } -// --------- XMLElement ---------- // -XMLElement::XMLElement( XMLDocument* doc ) : XMLNode( doc ), - _closingType( OPENED ), - _rootAttribute( 0 ) -{ -} + void XMLAttribute::SetAttribute(float v) + { + char buf[BUF_SIZE]; + XMLUtil::ToStr(v, buf, BUF_SIZE); + _value.SetStr(buf); + } -XMLElement::~XMLElement() -{ - while( _rootAttribute ) { - XMLAttribute* next = _rootAttribute->_next; - DeleteAttribute( _rootAttribute ); - _rootAttribute = next; + // --------- XMLElement ---------- // + XMLElement::XMLElement(XMLDocument* doc) : XMLNode(doc), + _closingType(OPENED), + _rootAttribute(0) + { } -} -const XMLAttribute* XMLElement::FindAttribute( const char* name ) const -{ - for( XMLAttribute* a = _rootAttribute; a; a = a->_next ) { - if ( XMLUtil::StringEqual( a->Name(), name ) ) { - return a; + XMLElement::~XMLElement() + { + while (_rootAttribute) { + XMLAttribute* next = _rootAttribute->_next; + DeleteAttribute(_rootAttribute); + _rootAttribute = next; } } - return 0; -} -const char* XMLElement::Attribute( const char* name, const char* value ) const -{ - const XMLAttribute* a = FindAttribute( name ); - if ( !a ) { + const XMLAttribute* XMLElement::FindAttribute(const char* name) const + { + for (XMLAttribute* a = _rootAttribute; a; a = a->_next) { + if (XMLUtil::StringEqual(a->Name(), name)) { + return a; + } + } return 0; } - if ( !value || XMLUtil::StringEqual( a->Value(), value )) { - return a->Value(); + + + const char* XMLElement::Attribute(const char* name, const char* value) const + { + const XMLAttribute* a = FindAttribute(name); + if (!a) { + return 0; + } + if (!value || XMLUtil::StringEqual(a->Value(), value)) { + return a->Value(); + } + return 0; } - return 0; -} -int XMLElement::IntAttribute(const char* name, int defaultValue) const -{ - int i = defaultValue; - QueryIntAttribute(name, &i); - return i; -} + int XMLElement::IntAttribute(const char* name, int defaultValue) const + { + int i = defaultValue; + QueryIntAttribute(name, &i); + return i; + } -unsigned XMLElement::UnsignedAttribute(const char* name, unsigned defaultValue) const -{ - unsigned i = defaultValue; - QueryUnsignedAttribute(name, &i); - return i; -} + unsigned XMLElement::UnsignedAttribute(const char* name, unsigned defaultValue) const + { + unsigned i = defaultValue; + QueryUnsignedAttribute(name, &i); + return i; + } -int64_t XMLElement::Int64Attribute(const char* name, int64_t defaultValue) const -{ - int64_t i = defaultValue; - QueryInt64Attribute(name, &i); - return i; -} + int64_t XMLElement::Int64Attribute(const char* name, int64_t defaultValue) const + { + int64_t i = defaultValue; + QueryInt64Attribute(name, &i); + return i; + } -uint64_t XMLElement::Unsigned64Attribute(const char* name, uint64_t defaultValue) const -{ - uint64_t i = defaultValue; - QueryUnsigned64Attribute(name, &i); - return i; -} + uint64_t XMLElement::Unsigned64Attribute(const char* name, uint64_t defaultValue) const + { + uint64_t i = defaultValue; + QueryUnsigned64Attribute(name, &i); + return i; + } -bool XMLElement::BoolAttribute(const char* name, bool defaultValue) const -{ - bool b = defaultValue; - QueryBoolAttribute(name, &b); - return b; -} + bool XMLElement::BoolAttribute(const char* name, bool defaultValue) const + { + bool b = defaultValue; + QueryBoolAttribute(name, &b); + return b; + } -double XMLElement::DoubleAttribute(const char* name, double defaultValue) const -{ - double d = defaultValue; - QueryDoubleAttribute(name, &d); - return d; -} + double XMLElement::DoubleAttribute(const char* name, double defaultValue) const + { + double d = defaultValue; + QueryDoubleAttribute(name, &d); + return d; + } -float XMLElement::FloatAttribute(const char* name, float defaultValue) const -{ - float f = defaultValue; - QueryFloatAttribute(name, &f); - return f; -} + float XMLElement::FloatAttribute(const char* name, float defaultValue) const + { + float f = defaultValue; + QueryFloatAttribute(name, &f); + return f; + } -const char* XMLElement::GetText() const -{ - /* skip comment node */ - const XMLNode* node = FirstChild(); - while (node) { - if (node->ToComment()) { - node = node->NextSibling(); - continue; + const char* XMLElement::GetText() const + { + /* skip comment node */ + const XMLNode* node = FirstChild(); + while (node) { + if (node->ToComment()) { + node = node->NextSibling(); + continue; + } + break; } - break; - } - if ( node && node->ToText() ) { - return node->Value(); + if (node && node->ToText()) { + return node->Value(); + } + return 0; } - return 0; -} -void XMLElement::SetText( const char* inText ) -{ - if ( FirstChild() && FirstChild()->ToText() ) - FirstChild()->SetValue( inText ); - else { - XMLText* theText = GetDocument()->NewText( inText ); - InsertFirstChild( theText ); - } -} + void XMLElement::SetText(const char* inText) + { + if (FirstChild() && FirstChild()->ToText()) + FirstChild()->SetValue(inText); + else { + XMLText* theText = GetDocument()->NewText(inText); + InsertFirstChild(theText); + } + } -void XMLElement::SetText( int v ) -{ - char buf[BUF_SIZE]; - XMLUtil::ToStr( v, buf, BUF_SIZE ); - SetText( buf ); -} + void XMLElement::SetText(int v) + { + char buf[BUF_SIZE]; + XMLUtil::ToStr(v, buf, BUF_SIZE); + SetText(buf); + } -void XMLElement::SetText( unsigned v ) -{ - char buf[BUF_SIZE]; - XMLUtil::ToStr( v, buf, BUF_SIZE ); - SetText( buf ); -} + void XMLElement::SetText(unsigned v) + { + char buf[BUF_SIZE]; + XMLUtil::ToStr(v, buf, BUF_SIZE); + SetText(buf); + } -void XMLElement::SetText(int64_t v) -{ - char buf[BUF_SIZE]; - XMLUtil::ToStr(v, buf, BUF_SIZE); - SetText(buf); -} + void XMLElement::SetText(int64_t v) + { + char buf[BUF_SIZE]; + XMLUtil::ToStr(v, buf, BUF_SIZE); + SetText(buf); + } -void XMLElement::SetText(uint64_t v) { - char buf[BUF_SIZE]; - XMLUtil::ToStr(v, buf, BUF_SIZE); - SetText(buf); -} + void XMLElement::SetText(uint64_t v) { + char buf[BUF_SIZE]; + XMLUtil::ToStr(v, buf, BUF_SIZE); + SetText(buf); + } -void XMLElement::SetText( bool v ) -{ - char buf[BUF_SIZE]; - XMLUtil::ToStr( v, buf, BUF_SIZE ); - SetText( buf ); -} + void XMLElement::SetText(bool v) + { + char buf[BUF_SIZE]; + XMLUtil::ToStr(v, buf, BUF_SIZE); + SetText(buf); + } -void XMLElement::SetText( float v ) -{ - char buf[BUF_SIZE]; - XMLUtil::ToStr( v, buf, BUF_SIZE ); - SetText( buf ); -} + void XMLElement::SetText(float v) + { + char buf[BUF_SIZE]; + XMLUtil::ToStr(v, buf, BUF_SIZE); + SetText(buf); + } -void XMLElement::SetText( double v ) -{ - char buf[BUF_SIZE]; - XMLUtil::ToStr( v, buf, BUF_SIZE ); - SetText( buf ); -} + void XMLElement::SetText(double v) + { + char buf[BUF_SIZE]; + XMLUtil::ToStr(v, buf, BUF_SIZE); + SetText(buf); + } -XMLError XMLElement::QueryIntText( int* ival ) const -{ - if ( FirstChild() && FirstChild()->ToText() ) { - const char* t = FirstChild()->Value(); - if ( XMLUtil::ToInt( t, ival ) ) { - return XML_SUCCESS; + XMLError XMLElement::QueryIntText(int* ival) const + { + if (FirstChild() && FirstChild()->ToText()) { + const char* t = FirstChild()->Value(); + if (XMLUtil::ToInt(t, ival)) { + return XML_SUCCESS; + } + return XML_CAN_NOT_CONVERT_TEXT; } - return XML_CAN_NOT_CONVERT_TEXT; + return XML_NO_TEXT_NODE; } - return XML_NO_TEXT_NODE; -} -XMLError XMLElement::QueryUnsignedText( unsigned* uval ) const -{ - if ( FirstChild() && FirstChild()->ToText() ) { - const char* t = FirstChild()->Value(); - if ( XMLUtil::ToUnsigned( t, uval ) ) { - return XML_SUCCESS; + XMLError XMLElement::QueryUnsignedText(unsigned* uval) const + { + if (FirstChild() && FirstChild()->ToText()) { + const char* t = FirstChild()->Value(); + if (XMLUtil::ToUnsigned(t, uval)) { + return XML_SUCCESS; + } + return XML_CAN_NOT_CONVERT_TEXT; } - return XML_CAN_NOT_CONVERT_TEXT; + return XML_NO_TEXT_NODE; } - return XML_NO_TEXT_NODE; -} -XMLError XMLElement::QueryInt64Text(int64_t* ival) const -{ - if (FirstChild() && FirstChild()->ToText()) { - const char* t = FirstChild()->Value(); - if (XMLUtil::ToInt64(t, ival)) { - return XML_SUCCESS; - } - return XML_CAN_NOT_CONVERT_TEXT; - } - return XML_NO_TEXT_NODE; -} + XMLError XMLElement::QueryInt64Text(int64_t* ival) const + { + if (FirstChild() && FirstChild()->ToText()) { + const char* t = FirstChild()->Value(); + if (XMLUtil::ToInt64(t, ival)) { + return XML_SUCCESS; + } + return XML_CAN_NOT_CONVERT_TEXT; + } + return XML_NO_TEXT_NODE; + } -XMLError XMLElement::QueryUnsigned64Text(uint64_t* uval) const -{ - if(FirstChild() && FirstChild()->ToText()) { - const char* t = FirstChild()->Value(); - if(XMLUtil::ToUnsigned64(t, uval)) { - return XML_SUCCESS; + XMLError XMLElement::QueryUnsigned64Text(uint64_t* uval) const + { + if (FirstChild() && FirstChild()->ToText()) { + const char* t = FirstChild()->Value(); + if (XMLUtil::ToUnsigned64(t, uval)) { + return XML_SUCCESS; + } + return XML_CAN_NOT_CONVERT_TEXT; } - return XML_CAN_NOT_CONVERT_TEXT; + return XML_NO_TEXT_NODE; } - return XML_NO_TEXT_NODE; -} -XMLError XMLElement::QueryBoolText( bool* bval ) const -{ - if ( FirstChild() && FirstChild()->ToText() ) { - const char* t = FirstChild()->Value(); - if ( XMLUtil::ToBool( t, bval ) ) { - return XML_SUCCESS; + XMLError XMLElement::QueryBoolText(bool* bval) const + { + if (FirstChild() && FirstChild()->ToText()) { + const char* t = FirstChild()->Value(); + if (XMLUtil::ToBool(t, bval)) { + return XML_SUCCESS; + } + return XML_CAN_NOT_CONVERT_TEXT; } - return XML_CAN_NOT_CONVERT_TEXT; + return XML_NO_TEXT_NODE; } - return XML_NO_TEXT_NODE; -} -XMLError XMLElement::QueryDoubleText( double* dval ) const -{ - if ( FirstChild() && FirstChild()->ToText() ) { - const char* t = FirstChild()->Value(); - if ( XMLUtil::ToDouble( t, dval ) ) { - return XML_SUCCESS; + XMLError XMLElement::QueryDoubleText(double* dval) const + { + if (FirstChild() && FirstChild()->ToText()) { + const char* t = FirstChild()->Value(); + if (XMLUtil::ToDouble(t, dval)) { + return XML_SUCCESS; + } + return XML_CAN_NOT_CONVERT_TEXT; } - return XML_CAN_NOT_CONVERT_TEXT; + return XML_NO_TEXT_NODE; } - return XML_NO_TEXT_NODE; -} -XMLError XMLElement::QueryFloatText( float* fval ) const -{ - if ( FirstChild() && FirstChild()->ToText() ) { - const char* t = FirstChild()->Value(); - if ( XMLUtil::ToFloat( t, fval ) ) { - return XML_SUCCESS; + XMLError XMLElement::QueryFloatText(float* fval) const + { + if (FirstChild() && FirstChild()->ToText()) { + const char* t = FirstChild()->Value(); + if (XMLUtil::ToFloat(t, fval)) { + return XML_SUCCESS; + } + return XML_CAN_NOT_CONVERT_TEXT; } - return XML_CAN_NOT_CONVERT_TEXT; + return XML_NO_TEXT_NODE; } - return XML_NO_TEXT_NODE; -} -int XMLElement::IntText(int defaultValue) const -{ - int i = defaultValue; - QueryIntText(&i); - return i; -} + int XMLElement::IntText(int defaultValue) const + { + int i = defaultValue; + QueryIntText(&i); + return i; + } -unsigned XMLElement::UnsignedText(unsigned defaultValue) const -{ - unsigned i = defaultValue; - QueryUnsignedText(&i); - return i; -} + unsigned XMLElement::UnsignedText(unsigned defaultValue) const + { + unsigned i = defaultValue; + QueryUnsignedText(&i); + return i; + } -int64_t XMLElement::Int64Text(int64_t defaultValue) const -{ - int64_t i = defaultValue; - QueryInt64Text(&i); - return i; -} + int64_t XMLElement::Int64Text(int64_t defaultValue) const + { + int64_t i = defaultValue; + QueryInt64Text(&i); + return i; + } -uint64_t XMLElement::Unsigned64Text(uint64_t defaultValue) const -{ - uint64_t i = defaultValue; - QueryUnsigned64Text(&i); - return i; -} + uint64_t XMLElement::Unsigned64Text(uint64_t defaultValue) const + { + uint64_t i = defaultValue; + QueryUnsigned64Text(&i); + return i; + } -bool XMLElement::BoolText(bool defaultValue) const -{ - bool b = defaultValue; - QueryBoolText(&b); - return b; -} + bool XMLElement::BoolText(bool defaultValue) const + { + bool b = defaultValue; + QueryBoolText(&b); + return b; + } -double XMLElement::DoubleText(double defaultValue) const -{ - double d = defaultValue; - QueryDoubleText(&d); - return d; -} + double XMLElement::DoubleText(double defaultValue) const + { + double d = defaultValue; + QueryDoubleText(&d); + return d; + } -float XMLElement::FloatText(float defaultValue) const -{ - float f = defaultValue; - QueryFloatText(&f); - return f; -} + float XMLElement::FloatText(float defaultValue) const + { + float f = defaultValue; + QueryFloatText(&f); + return f; + } -XMLAttribute* XMLElement::FindOrCreateAttribute( const char* name ) -{ - XMLAttribute* last = 0; - XMLAttribute* attrib = 0; - for( attrib = _rootAttribute; - attrib; - last = attrib, attrib = attrib->_next ) { - if ( XMLUtil::StringEqual( attrib->Name(), name ) ) { - break; - } - } - if ( !attrib ) { - attrib = CreateAttribute(); - TIXMLASSERT( attrib ); - if ( last ) { - TIXMLASSERT( last->_next == 0 ); - last->_next = attrib; + XMLAttribute* XMLElement::FindOrCreateAttribute(const char* name) + { + XMLAttribute* last = 0; + XMLAttribute* attrib = 0; + for (attrib = _rootAttribute; + attrib; + last = attrib, attrib = attrib->_next) { + if (XMLUtil::StringEqual(attrib->Name(), name)) { + break; + } } - else { - TIXMLASSERT( _rootAttribute == 0 ); - _rootAttribute = attrib; + if (!attrib) { + attrib = CreateAttribute(); + TIXMLASSERT(attrib); + if (last) { + TIXMLASSERT(last->_next == 0); + last->_next = attrib; + } + else { + TIXMLASSERT(_rootAttribute == 0); + _rootAttribute = attrib; + } + attrib->SetName(name); } - attrib->SetName( name ); + return attrib; } - return attrib; -} -void XMLElement::DeleteAttribute( const char* name ) -{ - XMLAttribute* prev = 0; - for( XMLAttribute* a=_rootAttribute; a; a=a->_next ) { - if ( XMLUtil::StringEqual( name, a->Name() ) ) { - if ( prev ) { - prev->_next = a->_next; - } - else { - _rootAttribute = a->_next; + void XMLElement::DeleteAttribute(const char* name) + { + XMLAttribute* prev = 0; + for (XMLAttribute* a = _rootAttribute; a; a = a->_next) { + if (XMLUtil::StringEqual(name, a->Name())) { + if (prev) { + prev->_next = a->_next; + } + else { + _rootAttribute = a->_next; + } + DeleteAttribute(a); + break; } - DeleteAttribute( a ); - break; + prev = a; } - prev = a; } -} -char* XMLElement::ParseAttributes( char* p, int* curLineNumPtr ) -{ - XMLAttribute* prevAttribute = 0; + char* XMLElement::ParseAttributes(char* p, int* curLineNumPtr) + { + XMLAttribute* prevAttribute = 0; - // Read the attributes. - while( p ) { - p = XMLUtil::SkipWhiteSpace( p, curLineNumPtr ); - if ( !(*p) ) { - _document->SetError( XML_ERROR_PARSING_ELEMENT, _parseLineNum, "XMLElement name=%s", Name() ); - return 0; - } + // Read the attributes. + while (p) { + p = XMLUtil::SkipWhiteSpace(p, curLineNumPtr); + if (!(*p)) { + _document->SetError(XML_ERROR_PARSING_ELEMENT, _parseLineNum, "XMLElement name=%s", Name()); + return 0; + } - // attribute. - if (XMLUtil::IsNameStartChar( (unsigned char) *p ) ) { - XMLAttribute* attrib = CreateAttribute(); - TIXMLASSERT( attrib ); - attrib->_parseLineNum = _document->_parseCurLineNum; + // attribute. + if (XMLUtil::IsNameStartChar((unsigned char)*p)) { + XMLAttribute* attrib = CreateAttribute(); + TIXMLASSERT(attrib); + attrib->_parseLineNum = _document->_parseCurLineNum; - const int attrLineNum = attrib->_parseLineNum; + const int attrLineNum = attrib->_parseLineNum; - p = attrib->ParseDeep( p, _document->ProcessEntities(), curLineNumPtr ); - if ( !p || Attribute( attrib->Name() ) ) { - DeleteAttribute( attrib ); - _document->SetError( XML_ERROR_PARSING_ATTRIBUTE, attrLineNum, "XMLElement name=%s", Name() ); - return 0; + p = attrib->ParseDeep(p, _document->ProcessEntities(), curLineNumPtr); + if (!p || Attribute(attrib->Name())) { + DeleteAttribute(attrib); + _document->SetError(XML_ERROR_PARSING_ATTRIBUTE, attrLineNum, "XMLElement name=%s", Name()); + return 0; + } + // There is a minor bug here: if the attribute in the source xml + // document is duplicated, it will not be detected and the + // attribute will be doubly added. However, tracking the 'prevAttribute' + // avoids re-scanning the attribute list. Preferring performance for + // now, may reconsider in the future. + if (prevAttribute) { + TIXMLASSERT(prevAttribute->_next == 0); + prevAttribute->_next = attrib; + } + else { + TIXMLASSERT(_rootAttribute == 0); + _rootAttribute = attrib; + } + prevAttribute = attrib; + } + // end of the tag + else if (*p == '>') { + ++p; + break; } - // There is a minor bug here: if the attribute in the source xml - // document is duplicated, it will not be detected and the - // attribute will be doubly added. However, tracking the 'prevAttribute' - // avoids re-scanning the attribute list. Preferring performance for - // now, may reconsider in the future. - if ( prevAttribute ) { - TIXMLASSERT( prevAttribute->_next == 0 ); - prevAttribute->_next = attrib; + // end of the tag + else if (*p == '/' && *(p + 1) == '>') { + _closingType = CLOSED; + return p + 2; // done; sealed element. } else { - TIXMLASSERT( _rootAttribute == 0 ); - _rootAttribute = attrib; + _document->SetError(XML_ERROR_PARSING_ELEMENT, _parseLineNum, 0); + return 0; } - prevAttribute = attrib; - } - // end of the tag - else if ( *p == '>' ) { - ++p; - break; - } - // end of the tag - else if ( *p == '/' && *(p+1) == '>' ) { - _closingType = CLOSED; - return p+2; // done; sealed element. } - else { - _document->SetError( XML_ERROR_PARSING_ELEMENT, _parseLineNum, 0 ); - return 0; + return p; + } + + void XMLElement::DeleteAttribute(XMLAttribute* attribute) + { + if (attribute == 0) { + return; } + MemPool* pool = attribute->_memPool; + attribute->~XMLAttribute(); + pool->Free(attribute); } - return p; -} -void XMLElement::DeleteAttribute( XMLAttribute* attribute ) -{ - if ( attribute == 0 ) { - return; + XMLAttribute* XMLElement::CreateAttribute() + { + TIXMLASSERT(sizeof(XMLAttribute) == _document->_attributePool.ItemSize()); + XMLAttribute* attrib = new (_document->_attributePool.Alloc()) XMLAttribute(); + TIXMLASSERT(attrib); + attrib->_memPool = &_document->_attributePool; + attrib->_memPool->SetTracked(); + return attrib; } - MemPool* pool = attribute->_memPool; - attribute->~XMLAttribute(); - pool->Free( attribute ); -} -XMLAttribute* XMLElement::CreateAttribute() -{ - TIXMLASSERT( sizeof( XMLAttribute ) == _document->_attributePool.ItemSize() ); - XMLAttribute* attrib = new (_document->_attributePool.Alloc() ) XMLAttribute(); - TIXMLASSERT( attrib ); - attrib->_memPool = &_document->_attributePool; - attrib->_memPool->SetTracked(); - return attrib; -} + XMLElement* XMLElement::InsertNewChildElement(const char* name) + { + XMLElement* node = _document->NewElement(name); + return InsertEndChild(node) ? node : 0; + } -XMLElement* XMLElement::InsertNewChildElement(const char* name) -{ - XMLElement* node = _document->NewElement(name); - return InsertEndChild(node) ? node : 0; -} + XMLComment* XMLElement::InsertNewComment(const char* comment) + { + XMLComment* node = _document->NewComment(comment); + return InsertEndChild(node) ? node : 0; + } -XMLComment* XMLElement::InsertNewComment(const char* comment) -{ - XMLComment* node = _document->NewComment(comment); - return InsertEndChild(node) ? node : 0; -} + XMLText* XMLElement::InsertNewText(const char* text) + { + XMLText* node = _document->NewText(text); + return InsertEndChild(node) ? node : 0; + } -XMLText* XMLElement::InsertNewText(const char* text) -{ - XMLText* node = _document->NewText(text); - return InsertEndChild(node) ? node : 0; -} + XMLDeclaration* XMLElement::InsertNewDeclaration(const char* text) + { + XMLDeclaration* node = _document->NewDeclaration(text); + return InsertEndChild(node) ? node : 0; + } -XMLDeclaration* XMLElement::InsertNewDeclaration(const char* text) -{ - XMLDeclaration* node = _document->NewDeclaration(text); - return InsertEndChild(node) ? node : 0; -} + XMLUnknown* XMLElement::InsertNewUnknown(const char* text) + { + XMLUnknown* node = _document->NewUnknown(text); + return InsertEndChild(node) ? node : 0; + } -XMLUnknown* XMLElement::InsertNewUnknown(const char* text) -{ - XMLUnknown* node = _document->NewUnknown(text); - return InsertEndChild(node) ? node : 0; -} + // + // + // foobar + // + char* XMLElement::ParseDeep(char* p, StrPair* parentEndTag, int* curLineNumPtr) + { + // Read the element name. + p = XMLUtil::SkipWhiteSpace(p, curLineNumPtr); + + // The closing element is the form. It is + // parsed just like a regular element then deleted from + // the DOM. + if (*p == '/') { + _closingType = CLOSING; + ++p; + } -// -// -// foobar -// -char* XMLElement::ParseDeep( char* p, StrPair* parentEndTag, int* curLineNumPtr ) -{ - // Read the element name. - p = XMLUtil::SkipWhiteSpace( p, curLineNumPtr ); - - // The closing element is the form. It is - // parsed just like a regular element then deleted from - // the DOM. - if ( *p == '/' ) { - _closingType = CLOSING; - ++p; - } + p = _value.ParseName(p); + if (_value.Empty()) { + return 0; + } - p = _value.ParseName( p ); - if ( _value.Empty() ) { - return 0; - } + p = ParseAttributes(p, curLineNumPtr); + if (!p || !*p || _closingType != OPENED) { + return p; + } - p = ParseAttributes( p, curLineNumPtr ); - if ( !p || !*p || _closingType != OPENED ) { + p = XMLNode::ParseDeep(p, parentEndTag, curLineNumPtr); return p; } - p = XMLNode::ParseDeep( p, parentEndTag, curLineNumPtr ); - return p; -} - -XMLNode* XMLElement::ShallowClone( XMLDocument* doc ) const -{ - if ( !doc ) { - doc = _document; - } - XMLElement* element = doc->NewElement( Value() ); // fixme: this will always allocate memory. Intern? - for( const XMLAttribute* a=FirstAttribute(); a; a=a->Next() ) { - element->SetAttribute( a->Name(), a->Value() ); // fixme: this will always allocate memory. Intern? + XMLNode* XMLElement::ShallowClone(XMLDocument* doc) const + { + if (!doc) { + doc = _document; + } + XMLElement* element = doc->NewElement(Value()); // fixme: this will always allocate memory. Intern? + for (const XMLAttribute* a = FirstAttribute(); a; a = a->Next()) { + element->SetAttribute(a->Name(), a->Value()); // fixme: this will always allocate memory. Intern? + } + return element; } - return element; -} -bool XMLElement::ShallowEqual( const XMLNode* compare ) const -{ - TIXMLASSERT( compare ); - const XMLElement* other = compare->ToElement(); - if ( other && XMLUtil::StringEqual( other->Name(), Name() )) { + bool XMLElement::ShallowEqual(const XMLNode* compare) const + { + TIXMLASSERT(compare); + const XMLElement* other = compare->ToElement(); + if (other && XMLUtil::StringEqual(other->Name(), Name())) { - const XMLAttribute* a=FirstAttribute(); - const XMLAttribute* b=other->FirstAttribute(); + const XMLAttribute* a = FirstAttribute(); + const XMLAttribute* b = other->FirstAttribute(); - while ( a && b ) { - if ( !XMLUtil::StringEqual( a->Value(), b->Value() ) ) { + while (a && b) { + if (!XMLUtil::StringEqual(a->Value(), b->Value())) { + return false; + } + a = a->Next(); + b = b->Next(); + } + if (a || b) { + // different count return false; } - a = a->Next(); - b = b->Next(); - } - if ( a || b ) { - // different count - return false; + return true; } - return true; + return false; } - return false; -} -bool XMLElement::Accept( XMLVisitor* visitor ) const -{ - TIXMLASSERT( visitor ); - if ( visitor->VisitEnter( *this, _rootAttribute ) ) { - for ( const XMLNode* node=FirstChild(); node; node=node->NextSibling() ) { - if ( !node->Accept( visitor ) ) { - break; + bool XMLElement::Accept(XMLVisitor* visitor) const + { + TIXMLASSERT(visitor); + if (visitor->VisitEnter(*this, _rootAttribute)) { + for (const XMLNode* node = FirstChild(); node; node = node->NextSibling()) { + if (!node->Accept(visitor)) { + break; + } } } + return visitor->VisitExit(*this); + } + + + // --------- XMLDocument ----------- // + + // Warning: List must match 'enum XMLError' + const char* XMLDocument::_errorNames[XML_ERROR_COUNT] = { + "XML_SUCCESS", + "XML_NO_ATTRIBUTE", + "XML_WRONG_ATTRIBUTE_TYPE", + "XML_ERROR_FILE_NOT_FOUND", + "XML_ERROR_FILE_COULD_NOT_BE_OPENED", + "XML_ERROR_FILE_READ_ERROR", + "XML_ERROR_PARSING_ELEMENT", + "XML_ERROR_PARSING_ATTRIBUTE", + "XML_ERROR_PARSING_TEXT", + "XML_ERROR_PARSING_CDATA", + "XML_ERROR_PARSING_COMMENT", + "XML_ERROR_PARSING_DECLARATION", + "XML_ERROR_PARSING_UNKNOWN", + "XML_ERROR_EMPTY_DOCUMENT", + "XML_ERROR_MISMATCHED_ELEMENT", + "XML_ERROR_PARSING", + "XML_CAN_NOT_CONVERT_TEXT", + "XML_NO_TEXT_NODE", + "XML_ELEMENT_DEPTH_EXCEEDED" + }; + + + XMLDocument::XMLDocument(bool processEntities, Whitespace whitespaceMode) : + XMLNode(0), + _writeBOM(false), + _processEntities(processEntities), + _errorID(XML_SUCCESS), + _whitespaceMode(whitespaceMode), + _errorStr(), + _errorLineNum(0), + _charBuffer(0), + _parseCurLineNum(0), + _parsingDepth(0), + _unlinked(), + _elementPool(), + _attributePool(), + _textPool(), + _commentPool() + { + // avoid VC++ C4355 warning about 'this' in initializer list (C4355 is off by default in VS2012+) + _document = this; } - return visitor->VisitExit( *this ); -} - -// --------- XMLDocument ----------- // - -// Warning: List must match 'enum XMLError' -const char* XMLDocument::_errorNames[XML_ERROR_COUNT] = { - "XML_SUCCESS", - "XML_NO_ATTRIBUTE", - "XML_WRONG_ATTRIBUTE_TYPE", - "XML_ERROR_FILE_NOT_FOUND", - "XML_ERROR_FILE_COULD_NOT_BE_OPENED", - "XML_ERROR_FILE_READ_ERROR", - "XML_ERROR_PARSING_ELEMENT", - "XML_ERROR_PARSING_ATTRIBUTE", - "XML_ERROR_PARSING_TEXT", - "XML_ERROR_PARSING_CDATA", - "XML_ERROR_PARSING_COMMENT", - "XML_ERROR_PARSING_DECLARATION", - "XML_ERROR_PARSING_UNKNOWN", - "XML_ERROR_EMPTY_DOCUMENT", - "XML_ERROR_MISMATCHED_ELEMENT", - "XML_ERROR_PARSING", - "XML_CAN_NOT_CONVERT_TEXT", - "XML_NO_TEXT_NODE", - "XML_ELEMENT_DEPTH_EXCEEDED" -}; - - -XMLDocument::XMLDocument( bool processEntities, Whitespace whitespaceMode ) : - XMLNode( 0 ), - _writeBOM( false ), - _processEntities( processEntities ), - _errorID(XML_SUCCESS), - _whitespaceMode( whitespaceMode ), - _errorStr(), - _errorLineNum( 0 ), - _charBuffer( 0 ), - _parseCurLineNum( 0 ), - _parsingDepth(0), - _unlinked(), - _elementPool(), - _attributePool(), - _textPool(), - _commentPool() -{ - // avoid VC++ C4355 warning about 'this' in initializer list (C4355 is off by default in VS2012+) - _document = this; -} + XMLDocument::~XMLDocument() + { + Clear(); + } -XMLDocument::~XMLDocument() -{ - Clear(); -} + void XMLDocument::MarkInUse(const XMLNode* const node) + { + TIXMLASSERT(node); + TIXMLASSERT(node->_parent == 0); -void XMLDocument::MarkInUse(const XMLNode* const node) -{ - TIXMLASSERT(node); - TIXMLASSERT(node->_parent == 0); - - for (int i = 0; i < _unlinked.Size(); ++i) { - if (node == _unlinked[i]) { - _unlinked.SwapRemove(i); - break; - } - } -} + for (int i = 0; i < _unlinked.Size(); ++i) { + if (node == _unlinked[i]) { + _unlinked.SwapRemove(i); + break; + } + } + } -void XMLDocument::Clear() -{ - DeleteChildren(); - while( _unlinked.Size()) { - DeleteNode(_unlinked[0]); // Will remove from _unlinked as part of delete. - } + void XMLDocument::Clear() + { + DeleteChildren(); + while (_unlinked.Size()) { + DeleteNode(_unlinked[0]); // Will remove from _unlinked as part of delete. + } #ifdef TINYXML2_DEBUG - const bool hadError = Error(); + const bool hadError = Error(); #endif - ClearError(); + ClearError(); - delete [] _charBuffer; - _charBuffer = 0; - _parsingDepth = 0; + delete[] _charBuffer; + _charBuffer = 0; + _parsingDepth = 0; #if 0 - _textPool.Trace( "text" ); - _elementPool.Trace( "element" ); - _commentPool.Trace( "comment" ); - _attributePool.Trace( "attribute" ); + _textPool.Trace("text"); + _elementPool.Trace("element"); + _commentPool.Trace("comment"); + _attributePool.Trace("attribute"); #endif #ifdef TINYXML2_DEBUG - if ( !hadError ) { - TIXMLASSERT( _elementPool.CurrentAllocs() == _elementPool.Untracked() ); - TIXMLASSERT( _attributePool.CurrentAllocs() == _attributePool.Untracked() ); - TIXMLASSERT( _textPool.CurrentAllocs() == _textPool.Untracked() ); - TIXMLASSERT( _commentPool.CurrentAllocs() == _commentPool.Untracked() ); - } + if (!hadError) { + TIXMLASSERT(_elementPool.CurrentAllocs() == _elementPool.Untracked()); + TIXMLASSERT(_attributePool.CurrentAllocs() == _attributePool.Untracked()); + TIXMLASSERT(_textPool.CurrentAllocs() == _textPool.Untracked()); + TIXMLASSERT(_commentPool.CurrentAllocs() == _commentPool.Untracked()); + } #endif -} + } -void XMLDocument::DeepCopy(XMLDocument* target) const -{ - TIXMLASSERT(target); - if (target == this) { - return; // technically success - a no-op. - } + void XMLDocument::DeepCopy(XMLDocument* target) const + { + TIXMLASSERT(target); + if (target == this) { + return; // technically success - a no-op. + } - target->Clear(); - for (const XMLNode* node = this->FirstChild(); node; node = node->NextSibling()) { - target->InsertEndChild(node->DeepClone(target)); - } -} + target->Clear(); + for (const XMLNode* node = this->FirstChild(); node; node = node->NextSibling()) { + target->InsertEndChild(node->DeepClone(target)); + } + } -XMLElement* XMLDocument::NewElement( const char* name ) -{ - XMLElement* ele = CreateUnlinkedNode( _elementPool ); - ele->SetName( name ); - return ele; -} + XMLElement* XMLDocument::NewElement(const char* name) + { + XMLElement* ele = CreateUnlinkedNode(_elementPool); + ele->SetName(name); + return ele; + } -XMLComment* XMLDocument::NewComment( const char* str ) -{ - XMLComment* comment = CreateUnlinkedNode( _commentPool ); - comment->SetValue( str ); - return comment; -} + XMLComment* XMLDocument::NewComment(const char* str) + { + XMLComment* comment = CreateUnlinkedNode(_commentPool); + comment->SetValue(str); + return comment; + } -XMLText* XMLDocument::NewText( const char* str ) -{ - XMLText* text = CreateUnlinkedNode( _textPool ); - text->SetValue( str ); - return text; -} + XMLText* XMLDocument::NewText(const char* str) + { + XMLText* text = CreateUnlinkedNode(_textPool); + text->SetValue(str); + return text; + } -XMLDeclaration* XMLDocument::NewDeclaration( const char* str ) -{ - XMLDeclaration* dec = CreateUnlinkedNode( _commentPool ); - dec->SetValue( str ? str : "xml version=\"1.0\" encoding=\"UTF-8\"" ); - return dec; -} + XMLDeclaration* XMLDocument::NewDeclaration(const char* str) + { + XMLDeclaration* dec = CreateUnlinkedNode(_commentPool); + dec->SetValue(str ? str : "xml version=\"1.0\" encoding=\"UTF-8\""); + return dec; + } -XMLUnknown* XMLDocument::NewUnknown( const char* str ) -{ - XMLUnknown* unk = CreateUnlinkedNode( _commentPool ); - unk->SetValue( str ); - return unk; -} + XMLUnknown* XMLDocument::NewUnknown(const char* str) + { + XMLUnknown* unk = CreateUnlinkedNode(_commentPool); + unk->SetValue(str); + return unk; + } -static FILE* callfopen( const char* filepath, const char* mode ) -{ - TIXMLASSERT( filepath ); - TIXMLASSERT( mode ); + static FILE* callfopen(const char* filepath, const char* mode) + { + TIXMLASSERT(filepath); + TIXMLASSERT(mode); #if defined(_MSC_VER) && (_MSC_VER >= 1400 ) && (!defined WINCE) - FILE* fp = 0; - const errno_t err = fopen_s( &fp, filepath, mode ); - if ( err ) { - return 0; - } + FILE* fp = 0; + const errno_t err = fopen_s(&fp, filepath, mode); + if (err) { + return 0; + } #else - FILE* fp = fopen( filepath, mode ); + FILE* fp = fopen(filepath, mode); #endif - return fp; -} - -void XMLDocument::DeleteNode( XMLNode* node ) { - TIXMLASSERT( node ); - TIXMLASSERT(node->_document == this ); - if (node->_parent) { - node->_parent->DeleteChild( node ); - } - else { - // Isn't in the tree. - // Use the parent delete. - // Also, we need to mark it tracked: we 'know' - // it was never used. - node->_memPool->SetTracked(); - // Call the static XMLNode version: - XMLNode::DeleteNode(node); + return fp; } -} - -XMLError XMLDocument::LoadFile( const char* filename ) -{ - if ( !filename ) { - TIXMLASSERT( false ); - SetError( XML_ERROR_FILE_COULD_NOT_BE_OPENED, 0, "filename=" ); - return _errorID; + void XMLDocument::DeleteNode(XMLNode* node) { + TIXMLASSERT(node); + TIXMLASSERT(node->_document == this); + if (node->_parent) { + node->_parent->DeleteChild(node); + } + else { + // Isn't in the tree. + // Use the parent delete. + // Also, we need to mark it tracked: we 'know' + // it was never used. + node->_memPool->SetTracked(); + // Call the static XMLNode version: + XMLNode::DeleteNode(node); + } } - Clear(); - FILE* fp = callfopen( filename, "rb" ); - if ( !fp ) { - SetError( XML_ERROR_FILE_NOT_FOUND, 0, "filename=%s", filename ); - return _errorID; - } - LoadFile( fp ); - fclose( fp ); - return _errorID; -} -XMLError XMLDocument::LoadFile( FILE* fp ) -{ - Clear(); + XMLError XMLDocument::LoadFile(const char* filename) + { + if (!filename) { + TIXMLASSERT(false); + SetError(XML_ERROR_FILE_COULD_NOT_BE_OPENED, 0, "filename="); + return _errorID; + } - TIXML_FSEEK( fp, 0, SEEK_SET ); - if ( fgetc( fp ) == EOF && ferror( fp ) != 0 ) { - SetError( XML_ERROR_FILE_READ_ERROR, 0, 0 ); + Clear(); + FILE* fp = callfopen(filename, "rb"); + if (!fp) { + SetError(XML_ERROR_FILE_NOT_FOUND, 0, "filename=%s", filename); + return _errorID; + } + LoadFile(fp); + fclose(fp); return _errorID; } - TIXML_FSEEK( fp, 0, SEEK_END ); - - unsigned long long filelength; + XMLError XMLDocument::LoadFile(FILE* fp) { - const long long fileLengthSigned = TIXML_FTELL( fp ); - TIXML_FSEEK( fp, 0, SEEK_SET ); - if ( fileLengthSigned == -1L ) { - SetError( XML_ERROR_FILE_READ_ERROR, 0, 0 ); + Clear(); + + TIXML_FSEEK(fp, 0, SEEK_SET); + if (fgetc(fp) == EOF && ferror(fp) != 0) { + SetError(XML_ERROR_FILE_READ_ERROR, 0, 0); return _errorID; } - TIXMLASSERT( fileLengthSigned >= 0 ); - filelength = static_cast(fileLengthSigned); - } - const size_t maxSizeT = static_cast(-1); - // We'll do the comparison as an unsigned long long, because that's guaranteed to be at - // least 8 bytes, even on a 32-bit platform. - if ( filelength >= static_cast(maxSizeT) ) { - // Cannot handle files which won't fit in buffer together with null terminator - SetError( XML_ERROR_FILE_READ_ERROR, 0, 0 ); - return _errorID; - } + TIXML_FSEEK(fp, 0, SEEK_END); - if ( filelength == 0 ) { - SetError( XML_ERROR_EMPTY_DOCUMENT, 0, 0 ); - return _errorID; - } + unsigned long long filelength; + { + const long long fileLengthSigned = TIXML_FTELL(fp); + TIXML_FSEEK(fp, 0, SEEK_SET); + if (fileLengthSigned == -1L) { + SetError(XML_ERROR_FILE_READ_ERROR, 0, 0); + return _errorID; + } + TIXMLASSERT(fileLengthSigned >= 0); + filelength = static_cast(fileLengthSigned); + } - const size_t size = static_cast(filelength); - TIXMLASSERT( _charBuffer == 0 ); - _charBuffer = new char[size+1]; - const size_t read = fread( _charBuffer, 1, size, fp ); - if ( read != size ) { - SetError( XML_ERROR_FILE_READ_ERROR, 0, 0 ); - return _errorID; - } + const size_t maxSizeT = static_cast(-1); + // We'll do the comparison as an unsigned long long, because that's guaranteed to be at + // least 8 bytes, even on a 32-bit platform. + if (filelength >= static_cast(maxSizeT)) { + // Cannot handle files which won't fit in buffer together with null terminator + SetError(XML_ERROR_FILE_READ_ERROR, 0, 0); + return _errorID; + } - _charBuffer[size] = 0; + if (filelength == 0) { + SetError(XML_ERROR_EMPTY_DOCUMENT, 0, 0); + return _errorID; + } - Parse(); - return _errorID; -} + const size_t size = static_cast(filelength); + TIXMLASSERT(_charBuffer == 0); + _charBuffer = new char[size + 1]; + const size_t read = fread(_charBuffer, 1, size, fp); + if (read != size) { + SetError(XML_ERROR_FILE_READ_ERROR, 0, 0); + return _errorID; + } + _charBuffer[size] = 0; -XMLError XMLDocument::SaveFile( const char* filename, bool compact ) -{ - if ( !filename ) { - TIXMLASSERT( false ); - SetError( XML_ERROR_FILE_COULD_NOT_BE_OPENED, 0, "filename=" ); + Parse(); return _errorID; } - FILE* fp = callfopen( filename, "w" ); - if ( !fp ) { - SetError( XML_ERROR_FILE_COULD_NOT_BE_OPENED, 0, "filename=%s", filename ); + + XMLError XMLDocument::SaveFile(const char* filename, bool compact) + { + if (!filename) { + TIXMLASSERT(false); + SetError(XML_ERROR_FILE_COULD_NOT_BE_OPENED, 0, "filename="); + return _errorID; + } + + FILE* fp = callfopen(filename, "w"); + if (!fp) { + SetError(XML_ERROR_FILE_COULD_NOT_BE_OPENED, 0, "filename=%s", filename); + return _errorID; + } + SaveFile(fp, compact); + fclose(fp); return _errorID; } - SaveFile(fp, compact); - fclose( fp ); - return _errorID; -} -XMLError XMLDocument::SaveFile( FILE* fp, bool compact ) -{ - // Clear any error from the last save, otherwise it will get reported - // for *this* call. - ClearError(); - XMLPrinter stream( fp, compact ); - Print( &stream ); - return _errorID; -} + XMLError XMLDocument::SaveFile(FILE* fp, bool compact) + { + // Clear any error from the last save, otherwise it will get reported + // for *this* call. + ClearError(); + XMLPrinter stream(fp, compact); + Print(&stream); + return _errorID; + } -XMLError XMLDocument::Parse( const char* xml, size_t nBytes ) -{ - Clear(); + XMLError XMLDocument::Parse(const char* xml, size_t nBytes) + { + Clear(); - if ( nBytes == 0 || !xml || !*xml ) { - SetError( XML_ERROR_EMPTY_DOCUMENT, 0, 0 ); + if (nBytes == 0 || !xml || !*xml) { + SetError(XML_ERROR_EMPTY_DOCUMENT, 0, 0); + return _errorID; + } + if (nBytes == static_cast(-1)) { + nBytes = strlen(xml); + } + TIXMLASSERT(_charBuffer == 0); + _charBuffer = new char[nBytes + 1]; + memcpy(_charBuffer, xml, nBytes); + _charBuffer[nBytes] = 0; + + Parse(); + if (Error()) { + // clean up now essentially dangling memory. + // and the parse fail can put objects in the + // pools that are dead and inaccessible. + DeleteChildren(); + _elementPool.Clear(); + _attributePool.Clear(); + _textPool.Clear(); + _commentPool.Clear(); + } return _errorID; } - if ( nBytes == static_cast(-1) ) { - nBytes = strlen( xml ); - } - TIXMLASSERT( _charBuffer == 0 ); - _charBuffer = new char[ nBytes+1 ]; - memcpy( _charBuffer, xml, nBytes ); - _charBuffer[nBytes] = 0; - - Parse(); - if ( Error() ) { - // clean up now essentially dangling memory. - // and the parse fail can put objects in the - // pools that are dead and inaccessible. - DeleteChildren(); - _elementPool.Clear(); - _attributePool.Clear(); - _textPool.Clear(); - _commentPool.Clear(); - } - return _errorID; -} -void XMLDocument::Print( XMLPrinter* streamer ) const -{ - if ( streamer ) { - Accept( streamer ); - } - else { - XMLPrinter stdoutStreamer( stdout ); - Accept( &stdoutStreamer ); + void XMLDocument::Print(XMLPrinter* streamer) const + { + if (streamer) { + Accept(streamer); + } + else { + XMLPrinter stdoutStreamer(stdout); + Accept(&stdoutStreamer); + } } -} -void XMLDocument::ClearError() { - _errorID = XML_SUCCESS; - _errorLineNum = 0; - _errorStr.Reset(); -} + void XMLDocument::ClearError() { + _errorID = XML_SUCCESS; + _errorLineNum = 0; + _errorStr.Reset(); + } -void XMLDocument::SetError( XMLError error, int lineNum, const char* format, ... ) -{ - TIXMLASSERT( error >= 0 && error < XML_ERROR_COUNT ); - _errorID = error; - _errorLineNum = lineNum; - _errorStr.Reset(); - - const size_t BUFFER_SIZE = 1000; - char* buffer = new char[BUFFER_SIZE]; - - TIXMLASSERT(sizeof(error) <= sizeof(int)); - TIXML_SNPRINTF(buffer, BUFFER_SIZE, "Error=%s ErrorID=%d (0x%x) Line number=%d", ErrorIDToName(error), int(error), int(error), lineNum); - - if (format) { - size_t len = strlen(buffer); - TIXML_SNPRINTF(buffer + len, BUFFER_SIZE - len, ": "); - len = strlen(buffer); - - va_list va; - va_start(va, format); - TIXML_VSNPRINTF(buffer + len, BUFFER_SIZE - len, format, va); - va_end(va); - } - _errorStr.SetStr(buffer); - delete[] buffer; -} + void XMLDocument::SetError(XMLError error, int lineNum, const char* format, ...) + { + TIXMLASSERT(error >= 0 && error < XML_ERROR_COUNT); + _errorID = error; + _errorLineNum = lineNum; + _errorStr.Reset(); + + const size_t BUFFER_SIZE = 1000; + char* buffer = new char[BUFFER_SIZE]; + + TIXMLASSERT(sizeof(error) <= sizeof(int)); + TIXML_SNPRINTF(buffer, BUFFER_SIZE, "Error=%s ErrorID=%d (0x%x) Line number=%d", ErrorIDToName(error), int(error), int(error), lineNum); + + if (format) { + size_t len = strlen(buffer); + TIXML_SNPRINTF(buffer + len, BUFFER_SIZE - len, ": "); + len = strlen(buffer); + + va_list va; + va_start(va, format); + TIXML_VSNPRINTF(buffer + len, BUFFER_SIZE - len, format, va); + va_end(va); + } + _errorStr.SetStr(buffer); + delete[] buffer; + } -/*static*/ const char* XMLDocument::ErrorIDToName(XMLError errorID) -{ - TIXMLASSERT( errorID >= 0 && errorID < XML_ERROR_COUNT ); - const char* errorName = _errorNames[errorID]; - TIXMLASSERT( errorName && errorName[0] ); - return errorName; -} + /*static*/ const char* XMLDocument::ErrorIDToName(XMLError errorID) + { + TIXMLASSERT(errorID >= 0 && errorID < XML_ERROR_COUNT); + const char* errorName = _errorNames[errorID]; + TIXMLASSERT(errorName && errorName[0]); + return errorName; + } -const char* XMLDocument::ErrorStr() const -{ - return _errorStr.Empty() ? "" : _errorStr.GetStr(); -} + const char* XMLDocument::ErrorStr() const + { + return _errorStr.Empty() ? "" : _errorStr.GetStr(); + } -void XMLDocument::PrintError() const -{ - printf("%s\n", ErrorStr()); -} + void XMLDocument::PrintError() const + { + printf("%s\n", ErrorStr()); + } -const char* XMLDocument::ErrorName() const -{ - return ErrorIDToName(_errorID); -} + const char* XMLDocument::ErrorName() const + { + return ErrorIDToName(_errorID); + } -void XMLDocument::Parse() -{ - TIXMLASSERT( NoChildren() ); // Clear() must have been called previously - TIXMLASSERT( _charBuffer ); - _parseCurLineNum = 1; - _parseLineNum = 1; - char* p = _charBuffer; - p = XMLUtil::SkipWhiteSpace( p, &_parseCurLineNum ); - p = const_cast( XMLUtil::ReadBOM( p, &_writeBOM ) ); - if ( !*p ) { - SetError( XML_ERROR_EMPTY_DOCUMENT, 0, 0 ); - return; - } - ParseDeep(p, 0, &_parseCurLineNum ); -} + void XMLDocument::Parse() + { + TIXMLASSERT(NoChildren()); // Clear() must have been called previously + TIXMLASSERT(_charBuffer); + _parseCurLineNum = 1; + _parseLineNum = 1; + char* p = _charBuffer; + p = XMLUtil::SkipWhiteSpace(p, &_parseCurLineNum); + p = const_cast(XMLUtil::ReadBOM(p, &_writeBOM)); + if (!*p) { + SetError(XML_ERROR_EMPTY_DOCUMENT, 0, 0); + return; + } + ParseDeep(p, 0, &_parseCurLineNum); + } -void XMLDocument::PushDepth() -{ - _parsingDepth++; - if (_parsingDepth == TINYXML2_MAX_ELEMENT_DEPTH) { - SetError(XML_ELEMENT_DEPTH_EXCEEDED, _parseCurLineNum, "Element nesting is too deep." ); - } -} + void XMLDocument::PushDepth() + { + _parsingDepth++; + if (_parsingDepth == TINYXML2_MAX_ELEMENT_DEPTH) { + SetError(XML_ELEMENT_DEPTH_EXCEEDED, _parseCurLineNum, "Element nesting is too deep."); + } + } -void XMLDocument::PopDepth() -{ - TIXMLASSERT(_parsingDepth > 0); - --_parsingDepth; -} + void XMLDocument::PopDepth() + { + TIXMLASSERT(_parsingDepth > 0); + --_parsingDepth; + } + + XMLPrinter::XMLPrinter(FILE* file, bool compact, int depth) : + _elementJustOpened(false), + _stack(), + _firstElement(true), + _fp(file), + _depth(depth), + _textDepth(-1), + _processEntities(true), + _compactMode(compact), + _buffer() + { + for (int i = 0; i < ENTITY_RANGE; ++i) { + _entityFlag[i] = false; + _restrictedEntityFlag[i] = false; + } + for (int i = 0; i < NUM_ENTITIES; ++i) { + const char entityValue = entities[i].value; + const unsigned char flagIndex = static_cast(entityValue); + TIXMLASSERT(flagIndex < ENTITY_RANGE); + _entityFlag[flagIndex] = true; + } + _restrictedEntityFlag[static_cast('&')] = true; + _restrictedEntityFlag[static_cast('<')] = true; + _restrictedEntityFlag[static_cast('>')] = true; // not required, but consistency is nice + _buffer.Push(0); + } -XMLPrinter::XMLPrinter( FILE* file, bool compact, int depth ) : - _elementJustOpened( false ), - _stack(), - _firstElement( true ), - _fp( file ), - _depth( depth ), - _textDepth( -1 ), - _processEntities( true ), - _compactMode( compact ), - _buffer() -{ - for( int i=0; i(entityValue); - TIXMLASSERT( flagIndex < ENTITY_RANGE ); - _entityFlag[flagIndex] = true; - } - _restrictedEntityFlag[static_cast('&')] = true; - _restrictedEntityFlag[static_cast('<')] = true; - _restrictedEntityFlag[static_cast('>')] = true; // not required, but consistency is nice - _buffer.Push( 0 ); -} + void XMLPrinter::Print(const char* format, ...) + { + va_list va; + va_start(va, format); -void XMLPrinter::Print( const char* format, ... ) -{ - va_list va; - va_start( va, format ); - - if ( _fp ) { - vfprintf( _fp, format, va ); - } - else { - const int len = TIXML_VSCPRINTF( format, va ); - // Close out and re-start the va-args - va_end( va ); - TIXMLASSERT( len >= 0 ); - va_start( va, format ); - TIXMLASSERT( _buffer.Size() > 0 && _buffer[_buffer.Size() - 1] == 0 ); - char* p = _buffer.PushArr( len ) - 1; // back up over the null terminator. - TIXML_VSNPRINTF( p, len+1, format, va ); - } - va_end( va ); -} + if (_fp) { + vfprintf(_fp, format, va); + } + else { + const int len = TIXML_VSCPRINTF(format, va); + // Close out and re-start the va-args + va_end(va); + TIXMLASSERT(len >= 0); + va_start(va, format); + TIXMLASSERT(_buffer.Size() > 0 && _buffer[_buffer.Size() - 1] == 0); + char* p = _buffer.PushArr(len) - 1; // back up over the null terminator. + TIXML_VSNPRINTF(p, len + 1, format, va); + } + va_end(va); + } -void XMLPrinter::Write( const char* data, size_t size ) -{ - if ( _fp ) { - fwrite ( data , sizeof(char), size, _fp); - } - else { - char* p = _buffer.PushArr( static_cast(size) ) - 1; // back up over the null terminator. - memcpy( p, data, size ); - p[size] = 0; + void XMLPrinter::Write(const char* data, size_t size) + { + if (_fp) { + fwrite(data, sizeof(char), size, _fp); + } + else { + char* p = _buffer.PushArr(static_cast(size)) - 1; // back up over the null terminator. + memcpy(p, data, size); + p[size] = 0; + } } -} -void XMLPrinter::Putc( char ch ) -{ - if ( _fp ) { - fputc ( ch, _fp); - } - else { - char* p = _buffer.PushArr( sizeof(char) ) - 1; // back up over the null terminator. - p[0] = ch; - p[1] = 0; + void XMLPrinter::Putc(char ch) + { + if (_fp) { + fputc(ch, _fp); + } + else { + char* p = _buffer.PushArr(sizeof(char)) - 1; // back up over the null terminator. + p[0] = ch; + p[1] = 0; + } } -} -void XMLPrinter::PrintSpace( int depth ) -{ - for( int i=0; i 0 && *q < ENTITY_RANGE ) { - // Check for entities. If one is found, flush - // the stream up until the entity, write the - // entity, and keep looking. - if ( flag[static_cast(*q)] ) { - while ( p < q ) { - const size_t delta = q - p; - const int toPrint = ( INT_MAX < delta ) ? INT_MAX : static_cast(delta); - Write( p, toPrint ); - p += toPrint; - } - bool entityPatternPrinted = false; - for( int i=0; i 0 && *q < ENTITY_RANGE) { + // Check for entities. If one is found, flush + // the stream up until the entity, write the + // entity, and keep looking. + if (flag[static_cast(*q)]) { + while (p < q) { + const size_t delta = q - p; + const int toPrint = (INT_MAX < delta) ? INT_MAX : static_cast(delta); + Write(p, toPrint); + p += toPrint; } + bool entityPatternPrinted = false; + for (int i = 0; i < NUM_ENTITIES; ++i) { + if (entities[i].value == *q) { + Putc('&'); + Write(entities[i].pattern, entities[i].length); + Putc(';'); + entityPatternPrinted = true; + break; + } + } + if (!entityPatternPrinted) { + // TIXMLASSERT( entityPatternPrinted ) causes gcc -Wunused-but-set-variable in release + TIXMLASSERT(false); + } + ++p; } - if ( !entityPatternPrinted ) { - // TIXMLASSERT( entityPatternPrinted ) causes gcc -Wunused-but-set-variable in release - TIXMLASSERT( false ); - } - ++p; } + ++q; + TIXMLASSERT(p <= q); + } + // Flush the remaining string. This will be the entire + // string if an entity wasn't found. + if (p < q) { + const size_t delta = q - p; + const int toPrint = (INT_MAX < delta) ? INT_MAX : static_cast(delta); + Write(p, toPrint); } - ++q; - TIXMLASSERT( p <= q ); } - // Flush the remaining string. This will be the entire - // string if an entity wasn't found. - if ( p < q ) { - const size_t delta = q - p; - const int toPrint = ( INT_MAX < delta ) ? INT_MAX : static_cast(delta); - Write( p, toPrint ); + else { + Write(p); } } - else { - Write( p ); - } -} -void XMLPrinter::PushHeader( bool writeBOM, bool writeDec ) -{ - if ( writeBOM ) { - static const unsigned char bom[] = { TIXML_UTF_LEAD_0, TIXML_UTF_LEAD_1, TIXML_UTF_LEAD_2, 0 }; - Write( reinterpret_cast< const char* >( bom ) ); - } - if ( writeDec ) { - PushDeclaration( "xml version=\"1.0\"" ); + void XMLPrinter::PushHeader(bool writeBOM, bool writeDec) + { + if (writeBOM) { + static const unsigned char bom[] = { TIXML_UTF_LEAD_0, TIXML_UTF_LEAD_1, TIXML_UTF_LEAD_2, 0 }; + Write(reinterpret_cast(bom)); + } + if (writeDec) { + PushDeclaration("xml version=\"1.0\""); + } } -} -void XMLPrinter::PrepareForNewNode( bool compactMode ) -{ - SealElementIfJustOpened(); + void XMLPrinter::PrepareForNewNode(bool compactMode) + { + SealElementIfJustOpened(); - if ( compactMode ) { - return; - } + if (compactMode) { + return; + } - if ( _firstElement ) { - PrintSpace (_depth); - } else if ( _textDepth < 0) { - Putc( '\n' ); - PrintSpace( _depth ); - } + if (_firstElement) { + PrintSpace(_depth); + } + else if (_textDepth < 0) { + Putc('\n'); + PrintSpace(_depth); + } - _firstElement = false; -} + _firstElement = false; + } -void XMLPrinter::OpenElement( const char* name, bool compactMode ) -{ - PrepareForNewNode( compactMode ); - _stack.Push( name ); + void XMLPrinter::OpenElement(const char* name, bool compactMode) + { + PrepareForNewNode(compactMode); + _stack.Push(name); - Write ( "<" ); - Write ( name ); + Write("<"); + Write(name); - _elementJustOpened = true; - ++_depth; -} + _elementJustOpened = true; + ++_depth; + } -void XMLPrinter::PushAttribute( const char* name, const char* value ) -{ - TIXMLASSERT( _elementJustOpened ); - Putc ( ' ' ); - Write( name ); - Write( "=\"" ); - PrintString( value, false ); - Putc ( '\"' ); -} + void XMLPrinter::PushAttribute(const char* name, const char* value) + { + TIXMLASSERT(_elementJustOpened); + Putc(' '); + Write(name); + Write("=\""); + PrintString(value, false); + Putc('\"'); + } -void XMLPrinter::PushAttribute( const char* name, int v ) -{ - char buf[BUF_SIZE]; - XMLUtil::ToStr( v, buf, BUF_SIZE ); - PushAttribute( name, buf ); -} + void XMLPrinter::PushAttribute(const char* name, int v) + { + char buf[BUF_SIZE]; + XMLUtil::ToStr(v, buf, BUF_SIZE); + PushAttribute(name, buf); + } -void XMLPrinter::PushAttribute( const char* name, unsigned v ) -{ - char buf[BUF_SIZE]; - XMLUtil::ToStr( v, buf, BUF_SIZE ); - PushAttribute( name, buf ); -} + void XMLPrinter::PushAttribute(const char* name, unsigned v) + { + char buf[BUF_SIZE]; + XMLUtil::ToStr(v, buf, BUF_SIZE); + PushAttribute(name, buf); + } -void XMLPrinter::PushAttribute(const char* name, int64_t v) -{ - char buf[BUF_SIZE]; - XMLUtil::ToStr(v, buf, BUF_SIZE); - PushAttribute(name, buf); -} + void XMLPrinter::PushAttribute(const char* name, int64_t v) + { + char buf[BUF_SIZE]; + XMLUtil::ToStr(v, buf, BUF_SIZE); + PushAttribute(name, buf); + } -void XMLPrinter::PushAttribute(const char* name, uint64_t v) -{ - char buf[BUF_SIZE]; - XMLUtil::ToStr(v, buf, BUF_SIZE); - PushAttribute(name, buf); -} + void XMLPrinter::PushAttribute(const char* name, uint64_t v) + { + char buf[BUF_SIZE]; + XMLUtil::ToStr(v, buf, BUF_SIZE); + PushAttribute(name, buf); + } -void XMLPrinter::PushAttribute( const char* name, bool v ) -{ - char buf[BUF_SIZE]; - XMLUtil::ToStr( v, buf, BUF_SIZE ); - PushAttribute( name, buf ); -} + void XMLPrinter::PushAttribute(const char* name, bool v) + { + char buf[BUF_SIZE]; + XMLUtil::ToStr(v, buf, BUF_SIZE); + PushAttribute(name, buf); + } -void XMLPrinter::PushAttribute( const char* name, double v ) -{ - char buf[BUF_SIZE]; - XMLUtil::ToStr( v, buf, BUF_SIZE ); - PushAttribute( name, buf ); -} + void XMLPrinter::PushAttribute(const char* name, double v) + { + char buf[BUF_SIZE]; + XMLUtil::ToStr(v, buf, BUF_SIZE); + PushAttribute(name, buf); + } -void XMLPrinter::CloseElement( bool compactMode ) -{ - --_depth; - const char* name = _stack.Pop(); + void XMLPrinter::CloseElement(bool compactMode) + { + --_depth; + const char* name = _stack.Pop(); - if ( _elementJustOpened ) { - Write( "/>" ); - } - else { - if ( _textDepth < 0 && !compactMode) { - Putc( '\n' ); - PrintSpace( _depth ); + if (_elementJustOpened) { + Write("/>"); + } + else { + if (_textDepth < 0 && !compactMode) { + Putc('\n'); + PrintSpace(_depth); + } + Write(""); } - Write ( "" ); - } - if ( _textDepth == _depth ) { - _textDepth = -1; - } - if ( _depth == 0 && !compactMode) { - Putc( '\n' ); + if (_textDepth == _depth) { + _textDepth = -1; + } + if (_depth == 0 && !compactMode) { + Putc('\n'); + } + _elementJustOpened = false; } - _elementJustOpened = false; -} -void XMLPrinter::SealElementIfJustOpened() -{ - if ( !_elementJustOpened ) { - return; + void XMLPrinter::SealElementIfJustOpened() + { + if (!_elementJustOpened) { + return; + } + _elementJustOpened = false; + Putc('>'); } - _elementJustOpened = false; - Putc( '>' ); -} -void XMLPrinter::PushText( const char* text, bool cdata ) -{ - _textDepth = _depth-1; + void XMLPrinter::PushText(const char* text, bool cdata) + { + _textDepth = _depth - 1; - SealElementIfJustOpened(); - if ( cdata ) { - Write( "" ); - } - else { - PrintString( text, true ); + SealElementIfJustOpened(); + if (cdata) { + Write(""); + } + else { + PrintString(text, true); + } } -} -void XMLPrinter::PushText( int64_t value ) -{ - char buf[BUF_SIZE]; - XMLUtil::ToStr( value, buf, BUF_SIZE ); - PushText( buf, false ); -} + void XMLPrinter::PushText(int64_t value) + { + char buf[BUF_SIZE]; + XMLUtil::ToStr(value, buf, BUF_SIZE); + PushText(buf, false); + } -void XMLPrinter::PushText( uint64_t value ) -{ - char buf[BUF_SIZE]; - XMLUtil::ToStr(value, buf, BUF_SIZE); - PushText(buf, false); -} + void XMLPrinter::PushText(uint64_t value) + { + char buf[BUF_SIZE]; + XMLUtil::ToStr(value, buf, BUF_SIZE); + PushText(buf, false); + } -void XMLPrinter::PushText( int value ) -{ - char buf[BUF_SIZE]; - XMLUtil::ToStr( value, buf, BUF_SIZE ); - PushText( buf, false ); -} + void XMLPrinter::PushText(int value) + { + char buf[BUF_SIZE]; + XMLUtil::ToStr(value, buf, BUF_SIZE); + PushText(buf, false); + } -void XMLPrinter::PushText( unsigned value ) -{ - char buf[BUF_SIZE]; - XMLUtil::ToStr( value, buf, BUF_SIZE ); - PushText( buf, false ); -} + void XMLPrinter::PushText(unsigned value) + { + char buf[BUF_SIZE]; + XMLUtil::ToStr(value, buf, BUF_SIZE); + PushText(buf, false); + } -void XMLPrinter::PushText( bool value ) -{ - char buf[BUF_SIZE]; - XMLUtil::ToStr( value, buf, BUF_SIZE ); - PushText( buf, false ); -} + void XMLPrinter::PushText(bool value) + { + char buf[BUF_SIZE]; + XMLUtil::ToStr(value, buf, BUF_SIZE); + PushText(buf, false); + } -void XMLPrinter::PushText( float value ) -{ - char buf[BUF_SIZE]; - XMLUtil::ToStr( value, buf, BUF_SIZE ); - PushText( buf, false ); -} + void XMLPrinter::PushText(float value) + { + char buf[BUF_SIZE]; + XMLUtil::ToStr(value, buf, BUF_SIZE); + PushText(buf, false); + } -void XMLPrinter::PushText( double value ) -{ - char buf[BUF_SIZE]; - XMLUtil::ToStr( value, buf, BUF_SIZE ); - PushText( buf, false ); -} + void XMLPrinter::PushText(double value) + { + char buf[BUF_SIZE]; + XMLUtil::ToStr(value, buf, BUF_SIZE); + PushText(buf, false); + } -void XMLPrinter::PushComment( const char* comment ) -{ - PrepareForNewNode( _compactMode ); + void XMLPrinter::PushComment(const char* comment) + { + PrepareForNewNode(_compactMode); - Write( "" ); -} + Write(""); + } -void XMLPrinter::PushDeclaration( const char* value ) -{ - PrepareForNewNode( _compactMode ); + void XMLPrinter::PushDeclaration(const char* value) + { + PrepareForNewNode(_compactMode); - Write( "" ); -} + Write(""); + } -void XMLPrinter::PushUnknown( const char* value ) -{ - PrepareForNewNode( _compactMode ); + void XMLPrinter::PushUnknown(const char* value) + { + PrepareForNewNode(_compactMode); - Write( "' ); -} + Write("'); + } -bool XMLPrinter::VisitEnter( const XMLDocument& doc ) -{ - _processEntities = doc.ProcessEntities(); - if ( doc.HasBOM() ) { - PushHeader( true, false ); + bool XMLPrinter::VisitEnter(const XMLDocument& doc) + { + _processEntities = doc.ProcessEntities(); + if (doc.HasBOM()) { + PushHeader(true, false); + } + return true; } - return true; -} -bool XMLPrinter::VisitEnter( const XMLElement& element, const XMLAttribute* attribute ) -{ - const XMLElement* parentElem = 0; - if ( element.Parent() ) { - parentElem = element.Parent()->ToElement(); - } - const bool compactMode = parentElem ? CompactMode( *parentElem ) : _compactMode; - OpenElement( element.Name(), compactMode ); - while ( attribute ) { - PushAttribute( attribute->Name(), attribute->Value() ); - attribute = attribute->Next(); + bool XMLPrinter::VisitEnter(const XMLElement& element, const XMLAttribute* attribute) + { + const XMLElement* parentElem = 0; + if (element.Parent()) { + parentElem = element.Parent()->ToElement(); + } + const bool compactMode = parentElem ? CompactMode(*parentElem) : _compactMode; + OpenElement(element.Name(), compactMode); + while (attribute) { + PushAttribute(attribute->Name(), attribute->Value()); + attribute = attribute->Next(); + } + return true; } - return true; -} -bool XMLPrinter::VisitExit( const XMLElement& element ) -{ - CloseElement( CompactMode(element) ); - return true; -} + bool XMLPrinter::VisitExit(const XMLElement& element) + { + CloseElement(CompactMode(element)); + return true; + } -bool XMLPrinter::Visit( const XMLText& text ) -{ - PushText( text.Value(), text.CData() ); - return true; -} + bool XMLPrinter::Visit(const XMLText& text) + { + PushText(text.Value(), text.CData()); + return true; + } -bool XMLPrinter::Visit( const XMLComment& comment ) -{ - PushComment( comment.Value() ); - return true; -} + bool XMLPrinter::Visit(const XMLComment& comment) + { + PushComment(comment.Value()); + return true; + } -bool XMLPrinter::Visit( const XMLDeclaration& declaration ) -{ - PushDeclaration( declaration.Value() ); - return true; -} + bool XMLPrinter::Visit(const XMLDeclaration& declaration) + { + PushDeclaration(declaration.Value()); + return true; + } -bool XMLPrinter::Visit( const XMLUnknown& unknown ) -{ - PushUnknown( unknown.Value() ); - return true; -} + bool XMLPrinter::Visit(const XMLUnknown& unknown) + { + PushUnknown(unknown.Value()); + return true; + } } // namespace tinyxml2 diff --git a/Cigarette/tinyxml2.h b/Cigarette/tinyxml2.h index 02c0d40a..37b9eabf 100644 --- a/Cigarette/tinyxml2.h +++ b/Cigarette/tinyxml2.h @@ -46,7 +46,7 @@ distribution. TODO: intern strings instead of allocation. */ /* - gcc: + gcc: g++ -Wall -DTINYXML2_DEBUG tinyxml2.cpp xmltest.cpp -o gccxmltest.exe Formatting, Artistic Style: @@ -97,7 +97,7 @@ distribution. #endif /* Versioning, past 1.0.14: - http://semver.org/ + http://semver.org/ */ static const int TIXML2_MAJOR_VERSION = 9; static const int TIXML2_MINOR_VERSION = 0; @@ -116,2259 +116,2259 @@ static const int TINYXML2_MAX_ELEMENT_DEPTH = 500; namespace tinyxml2 { -class XMLDocument; -class XMLElement; -class XMLAttribute; -class XMLComment; -class XMLText; -class XMLDeclaration; -class XMLUnknown; -class XMLPrinter; - -/* - A class that wraps strings. Normally stores the start and end - pointers into the XML file itself, and will apply normalization - and entity translation if actually read. Can also store (and memory - manage) a traditional char[] - - Isn't clear why TINYXML2_LIB is needed; but seems to fix #719 -*/ -class TINYXML2_LIB StrPair -{ -public: - enum Mode { - NEEDS_ENTITY_PROCESSING = 0x01, - NEEDS_NEWLINE_NORMALIZATION = 0x02, - NEEDS_WHITESPACE_COLLAPSING = 0x04, - - TEXT_ELEMENT = NEEDS_ENTITY_PROCESSING | NEEDS_NEWLINE_NORMALIZATION, - TEXT_ELEMENT_LEAVE_ENTITIES = NEEDS_NEWLINE_NORMALIZATION, - ATTRIBUTE_NAME = 0, - ATTRIBUTE_VALUE = NEEDS_ENTITY_PROCESSING | NEEDS_NEWLINE_NORMALIZATION, - ATTRIBUTE_VALUE_LEAVE_ENTITIES = NEEDS_NEWLINE_NORMALIZATION, - COMMENT = NEEDS_NEWLINE_NORMALIZATION - }; + class XMLDocument; + class XMLElement; + class XMLAttribute; + class XMLComment; + class XMLText; + class XMLDeclaration; + class XMLUnknown; + class XMLPrinter; + + /* + A class that wraps strings. Normally stores the start and end + pointers into the XML file itself, and will apply normalization + and entity translation if actually read. Can also store (and memory + manage) a traditional char[] + + Isn't clear why TINYXML2_LIB is needed; but seems to fix #719 + */ + class TINYXML2_LIB StrPair + { + public: + enum Mode { + NEEDS_ENTITY_PROCESSING = 0x01, + NEEDS_NEWLINE_NORMALIZATION = 0x02, + NEEDS_WHITESPACE_COLLAPSING = 0x04, + + TEXT_ELEMENT = NEEDS_ENTITY_PROCESSING | NEEDS_NEWLINE_NORMALIZATION, + TEXT_ELEMENT_LEAVE_ENTITIES = NEEDS_NEWLINE_NORMALIZATION, + ATTRIBUTE_NAME = 0, + ATTRIBUTE_VALUE = NEEDS_ENTITY_PROCESSING | NEEDS_NEWLINE_NORMALIZATION, + ATTRIBUTE_VALUE_LEAVE_ENTITIES = NEEDS_NEWLINE_NORMALIZATION, + COMMENT = NEEDS_NEWLINE_NORMALIZATION + }; + + StrPair() : _flags(0), _start(0), _end(0) {} + ~StrPair(); + + void Set(char* start, char* end, int flags) { + TIXMLASSERT(start); + TIXMLASSERT(end); + Reset(); + _start = start; + _end = end; + _flags = flags | NEEDS_FLUSH; + } - StrPair() : _flags( 0 ), _start( 0 ), _end( 0 ) {} - ~StrPair(); + const char* GetStr(); - void Set( char* start, char* end, int flags ) { - TIXMLASSERT( start ); - TIXMLASSERT( end ); - Reset(); - _start = start; - _end = end; - _flags = flags | NEEDS_FLUSH; - } + bool Empty() const { + return _start == _end; + } - const char* GetStr(); + void SetInternedStr(const char* str) { + Reset(); + _start = const_cast(str); + } - bool Empty() const { - return _start == _end; - } + void SetStr(const char* str, int flags = 0); - void SetInternedStr( const char* str ) { - Reset(); - _start = const_cast(str); - } + char* ParseText(char* in, const char* endTag, int strFlags, int* curLineNumPtr); + char* ParseName(char* in); - void SetStr( const char* str, int flags=0 ); + void TransferTo(StrPair* other); + void Reset(); - char* ParseText( char* in, const char* endTag, int strFlags, int* curLineNumPtr ); - char* ParseName( char* in ); + private: + void CollapseWhitespace(); - void TransferTo( StrPair* other ); - void Reset(); + enum { + NEEDS_FLUSH = 0x100, + NEEDS_DELETE = 0x200 + }; -private: - void CollapseWhitespace(); + int _flags; + char* _start; + char* _end; - enum { - NEEDS_FLUSH = 0x100, - NEEDS_DELETE = 0x200 + StrPair(const StrPair& other); // not supported + void operator=(const StrPair& other); // not supported, use TransferTo() }; - int _flags; - char* _start; - char* _end; - - StrPair( const StrPair& other ); // not supported - void operator=( const StrPair& other ); // not supported, use TransferTo() -}; - -/* - A dynamic array of Plain Old Data. Doesn't support constructors, etc. - Has a small initial memory pool, so that low or no usage will not - cause a call to new/delete -*/ -template -class DynArray -{ -public: - DynArray() : - _mem( _pool ), - _allocated( INITIAL_SIZE ), - _size( 0 ) + /* + A dynamic array of Plain Old Data. Doesn't support constructors, etc. + Has a small initial memory pool, so that low or no usage will not + cause a call to new/delete + */ + template + class DynArray { - } + public: + DynArray() : + _mem(_pool), + _allocated(INITIAL_SIZE), + _size(0) + { + } - ~DynArray() { - if ( _mem != _pool ) { - delete [] _mem; + ~DynArray() { + if (_mem != _pool) { + delete[] _mem; + } } - } - void Clear() { - _size = 0; - } + void Clear() { + _size = 0; + } - void Push( T t ) { - TIXMLASSERT( _size < INT_MAX ); - EnsureCapacity( _size+1 ); - _mem[_size] = t; - ++_size; - } + void Push(T t) { + TIXMLASSERT(_size < INT_MAX); + EnsureCapacity(_size + 1); + _mem[_size] = t; + ++_size; + } - T* PushArr( int count ) { - TIXMLASSERT( count >= 0 ); - TIXMLASSERT( _size <= INT_MAX - count ); - EnsureCapacity( _size+count ); - T* ret = &_mem[_size]; - _size += count; - return ret; - } + T* PushArr(int count) { + TIXMLASSERT(count >= 0); + TIXMLASSERT(_size <= INT_MAX - count); + EnsureCapacity(_size + count); + T* ret = &_mem[_size]; + _size += count; + return ret; + } - T Pop() { - TIXMLASSERT( _size > 0 ); - --_size; - return _mem[_size]; - } + T Pop() { + TIXMLASSERT(_size > 0); + --_size; + return _mem[_size]; + } - void PopArr( int count ) { - TIXMLASSERT( _size >= count ); - _size -= count; - } + void PopArr(int count) { + TIXMLASSERT(_size >= count); + _size -= count; + } - bool Empty() const { - return _size == 0; - } + bool Empty() const { + return _size == 0; + } - T& operator[](int i) { - TIXMLASSERT( i>= 0 && i < _size ); - return _mem[i]; - } + T& operator[](int i) { + TIXMLASSERT(i >= 0 && i < _size); + return _mem[i]; + } - const T& operator[](int i) const { - TIXMLASSERT( i>= 0 && i < _size ); - return _mem[i]; - } + const T& operator[](int i) const { + TIXMLASSERT(i >= 0 && i < _size); + return _mem[i]; + } - const T& PeekTop() const { - TIXMLASSERT( _size > 0 ); - return _mem[ _size - 1]; - } + const T& PeekTop() const { + TIXMLASSERT(_size > 0); + return _mem[_size - 1]; + } - int Size() const { - TIXMLASSERT( _size >= 0 ); - return _size; - } + int Size() const { + TIXMLASSERT(_size >= 0); + return _size; + } - int Capacity() const { - TIXMLASSERT( _allocated >= INITIAL_SIZE ); - return _allocated; - } + int Capacity() const { + TIXMLASSERT(_allocated >= INITIAL_SIZE); + return _allocated; + } - void SwapRemove(int i) { - TIXMLASSERT(i >= 0 && i < _size); - TIXMLASSERT(_size > 0); - _mem[i] = _mem[_size - 1]; - --_size; - } + void SwapRemove(int i) { + TIXMLASSERT(i >= 0 && i < _size); + TIXMLASSERT(_size > 0); + _mem[i] = _mem[_size - 1]; + --_size; + } - const T* Mem() const { - TIXMLASSERT( _mem ); - return _mem; - } + const T* Mem() const { + TIXMLASSERT(_mem); + return _mem; + } - T* Mem() { - TIXMLASSERT( _mem ); - return _mem; - } + T* Mem() { + TIXMLASSERT(_mem); + return _mem; + } -private: - DynArray( const DynArray& ); // not supported - void operator=( const DynArray& ); // not supported - - void EnsureCapacity( int cap ) { - TIXMLASSERT( cap > 0 ); - if ( cap > _allocated ) { - TIXMLASSERT( cap <= INT_MAX / 2 ); - const int newAllocated = cap * 2; - T* newMem = new T[newAllocated]; - TIXMLASSERT( newAllocated >= _size ); - memcpy( newMem, _mem, sizeof(T)*_size ); // warning: not using constructors, only works for PODs - if ( _mem != _pool ) { - delete [] _mem; + private: + DynArray(const DynArray&); // not supported + void operator=(const DynArray&); // not supported + + void EnsureCapacity(int cap) { + TIXMLASSERT(cap > 0); + if (cap > _allocated) { + TIXMLASSERT(cap <= INT_MAX / 2); + const int newAllocated = cap * 2; + T* newMem = new T[newAllocated]; + TIXMLASSERT(newAllocated >= _size); + memcpy(newMem, _mem, sizeof(T) * _size); // warning: not using constructors, only works for PODs + if (_mem != _pool) { + delete[] _mem; + } + _mem = newMem; + _allocated = newAllocated; } - _mem = newMem; - _allocated = newAllocated; } - } - - T* _mem; - T _pool[INITIAL_SIZE]; - int _allocated; // objects allocated - int _size; // number objects in use -}; - - -/* - Parent virtual class of a pool for fast allocation - and deallocation of objects. -*/ -class MemPool -{ -public: - MemPool() {} - virtual ~MemPool() {} - - virtual int ItemSize() const = 0; - virtual void* Alloc() = 0; - virtual void Free( void* ) = 0; - virtual void SetTracked() = 0; -}; + T* _mem; + T _pool[INITIAL_SIZE]; + int _allocated; // objects allocated + int _size; // number objects in use + }; -/* - Template child class to create pools of the correct type. -*/ -template< int ITEM_SIZE > -class MemPoolT : public MemPool -{ -public: - MemPoolT() : _blockPtrs(), _root(0), _currentAllocs(0), _nAllocs(0), _maxAllocs(0), _nUntracked(0) {} - ~MemPoolT() { - MemPoolT< ITEM_SIZE >::Clear(); - } - void Clear() { - // Delete the blocks. - while( !_blockPtrs.Empty()) { - Block* lastBlock = _blockPtrs.Pop(); - delete lastBlock; - } - _root = 0; - _currentAllocs = 0; - _nAllocs = 0; - _maxAllocs = 0; - _nUntracked = 0; - } + /* + Parent virtual class of a pool for fast allocation + and deallocation of objects. + */ + class MemPool + { + public: + MemPool() {} + virtual ~MemPool() {} + + virtual int ItemSize() const = 0; + virtual void* Alloc() = 0; + virtual void Free(void*) = 0; + virtual void SetTracked() = 0; + }; - virtual int ItemSize() const { - return ITEM_SIZE; - } - int CurrentAllocs() const { - return _currentAllocs; - } - virtual void* Alloc() { - if ( !_root ) { - // Need a new block. - Block* block = new Block; - _blockPtrs.Push( block ); + /* + Template child class to create pools of the correct type. + */ + template< int ITEM_SIZE > + class MemPoolT : public MemPool + { + public: + MemPoolT() : _blockPtrs(), _root(0), _currentAllocs(0), _nAllocs(0), _maxAllocs(0), _nUntracked(0) {} + ~MemPoolT() { + MemPoolT< ITEM_SIZE >::Clear(); + } - Item* blockItems = block->items; - for( int i = 0; i < ITEMS_PER_BLOCK - 1; ++i ) { - blockItems[i].next = &(blockItems[i + 1]); + void Clear() { + // Delete the blocks. + while (!_blockPtrs.Empty()) { + Block* lastBlock = _blockPtrs.Pop(); + delete lastBlock; } - blockItems[ITEMS_PER_BLOCK - 1].next = 0; - _root = blockItems; + _root = 0; + _currentAllocs = 0; + _nAllocs = 0; + _maxAllocs = 0; + _nUntracked = 0; } - Item* const result = _root; - TIXMLASSERT( result != 0 ); - _root = _root->next; - ++_currentAllocs; - if ( _currentAllocs > _maxAllocs ) { - _maxAllocs = _currentAllocs; + virtual int ItemSize() const { + return ITEM_SIZE; } - ++_nAllocs; - ++_nUntracked; - return result; - } + int CurrentAllocs() const { + return _currentAllocs; + } + + virtual void* Alloc() { + if (!_root) { + // Need a new block. + Block* block = new Block; + _blockPtrs.Push(block); + + Item* blockItems = block->items; + for (int i = 0; i < ITEMS_PER_BLOCK - 1; ++i) { + blockItems[i].next = &(blockItems[i + 1]); + } + blockItems[ITEMS_PER_BLOCK - 1].next = 0; + _root = blockItems; + } + Item* const result = _root; + TIXMLASSERT(result != 0); + _root = _root->next; - virtual void Free( void* mem ) { - if ( !mem ) { - return; + ++_currentAllocs; + if (_currentAllocs > _maxAllocs) { + _maxAllocs = _currentAllocs; + } + ++_nAllocs; + ++_nUntracked; + return result; } - --_currentAllocs; - Item* item = static_cast( mem ); + + virtual void Free(void* mem) { + if (!mem) { + return; + } + --_currentAllocs; + Item* item = static_cast(mem); #ifdef TINYXML2_DEBUG - memset( item, 0xfe, sizeof( *item ) ); + memset(item, 0xfe, sizeof(*item)); #endif - item->next = _root; - _root = item; - } - void Trace( const char* name ) { - printf( "Mempool %s watermark=%d [%dk] current=%d size=%d nAlloc=%d blocks=%d\n", - name, _maxAllocs, _maxAllocs * ITEM_SIZE / 1024, _currentAllocs, - ITEM_SIZE, _nAllocs, _blockPtrs.Size() ); - } + item->next = _root; + _root = item; + } + void Trace(const char* name) { + printf("Mempool %s watermark=%d [%dk] current=%d size=%d nAlloc=%d blocks=%d\n", + name, _maxAllocs, _maxAllocs * ITEM_SIZE / 1024, _currentAllocs, + ITEM_SIZE, _nAllocs, _blockPtrs.Size()); + } - void SetTracked() { - --_nUntracked; - } + void SetTracked() { + --_nUntracked; + } - int Untracked() const { - return _nUntracked; - } + int Untracked() const { + return _nUntracked; + } - // This number is perf sensitive. 4k seems like a good tradeoff on my machine. - // The test file is large, 170k. - // Release: VS2010 gcc(no opt) - // 1k: 4000 - // 2k: 4000 - // 4k: 3900 21000 - // 16k: 5200 - // 32k: 4300 - // 64k: 4000 21000 - // Declared public because some compilers do not accept to use ITEMS_PER_BLOCK - // in private part if ITEMS_PER_BLOCK is private - enum { ITEMS_PER_BLOCK = (4 * 1024) / ITEM_SIZE }; - -private: - MemPoolT( const MemPoolT& ); // not supported - void operator=( const MemPoolT& ); // not supported - - union Item { - Item* next; - char itemData[ITEM_SIZE]; + // This number is perf sensitive. 4k seems like a good tradeoff on my machine. + // The test file is large, 170k. + // Release: VS2010 gcc(no opt) + // 1k: 4000 + // 2k: 4000 + // 4k: 3900 21000 + // 16k: 5200 + // 32k: 4300 + // 64k: 4000 21000 + // Declared public because some compilers do not accept to use ITEMS_PER_BLOCK + // in private part if ITEMS_PER_BLOCK is private + enum { ITEMS_PER_BLOCK = (4 * 1024) / ITEM_SIZE }; + + private: + MemPoolT(const MemPoolT&); // not supported + void operator=(const MemPoolT&); // not supported + + union Item { + Item* next; + char itemData[ITEM_SIZE]; + }; + struct Block { + Item items[ITEMS_PER_BLOCK]; + }; + DynArray< Block*, 10 > _blockPtrs; + Item* _root; + + int _currentAllocs; + int _nAllocs; + int _maxAllocs; + int _nUntracked; }; - struct Block { - Item items[ITEMS_PER_BLOCK]; - }; - DynArray< Block*, 10 > _blockPtrs; - Item* _root; - - int _currentAllocs; - int _nAllocs; - int _maxAllocs; - int _nUntracked; -}; -/** - Implements the interface to the "Visitor pattern" (see the Accept() method.) - If you call the Accept() method, it requires being passed a XMLVisitor - class to handle callbacks. For nodes that contain other nodes (Document, Element) - you will get called with a VisitEnter/VisitExit pair. Nodes that are always leafs - are simply called with Visit(). + /** + Implements the interface to the "Visitor pattern" (see the Accept() method.) + If you call the Accept() method, it requires being passed a XMLVisitor + class to handle callbacks. For nodes that contain other nodes (Document, Element) + you will get called with a VisitEnter/VisitExit pair. Nodes that are always leafs + are simply called with Visit(). - If you return 'true' from a Visit method, recursive parsing will continue. If you return - false, no children of this node or its siblings will be visited. + If you return 'true' from a Visit method, recursive parsing will continue. If you return + false, no children of this node or its siblings will be visited. - All flavors of Visit methods have a default implementation that returns 'true' (continue - visiting). You need to only override methods that are interesting to you. + All flavors of Visit methods have a default implementation that returns 'true' (continue + visiting). You need to only override methods that are interesting to you. - Generally Accept() is called on the XMLDocument, although all nodes support visiting. + Generally Accept() is called on the XMLDocument, although all nodes support visiting. - You should never change the document from a callback. + You should never change the document from a callback. - @sa XMLNode::Accept() -*/ -class TINYXML2_LIB XMLVisitor -{ -public: - virtual ~XMLVisitor() {} + @sa XMLNode::Accept() + */ + class TINYXML2_LIB XMLVisitor + { + public: + virtual ~XMLVisitor() {} - /// Visit a document. - virtual bool VisitEnter( const XMLDocument& /*doc*/ ) { - return true; - } - /// Visit a document. - virtual bool VisitExit( const XMLDocument& /*doc*/ ) { - return true; - } + /// Visit a document. + virtual bool VisitEnter(const XMLDocument& /*doc*/) { + return true; + } + /// Visit a document. + virtual bool VisitExit(const XMLDocument& /*doc*/) { + return true; + } - /// Visit an element. - virtual bool VisitEnter( const XMLElement& /*element*/, const XMLAttribute* /*firstAttribute*/ ) { - return true; - } - /// Visit an element. - virtual bool VisitExit( const XMLElement& /*element*/ ) { - return true; - } + /// Visit an element. + virtual bool VisitEnter(const XMLElement& /*element*/, const XMLAttribute* /*firstAttribute*/) { + return true; + } + /// Visit an element. + virtual bool VisitExit(const XMLElement& /*element*/) { + return true; + } - /// Visit a declaration. - virtual bool Visit( const XMLDeclaration& /*declaration*/ ) { - return true; - } - /// Visit a text node. - virtual bool Visit( const XMLText& /*text*/ ) { - return true; - } - /// Visit a comment node. - virtual bool Visit( const XMLComment& /*comment*/ ) { - return true; - } - /// Visit an unknown node. - virtual bool Visit( const XMLUnknown& /*unknown*/ ) { - return true; - } -}; - -// WARNING: must match XMLDocument::_errorNames[] -enum XMLError { - XML_SUCCESS = 0, - XML_NO_ATTRIBUTE, - XML_WRONG_ATTRIBUTE_TYPE, - XML_ERROR_FILE_NOT_FOUND, - XML_ERROR_FILE_COULD_NOT_BE_OPENED, - XML_ERROR_FILE_READ_ERROR, - XML_ERROR_PARSING_ELEMENT, - XML_ERROR_PARSING_ATTRIBUTE, - XML_ERROR_PARSING_TEXT, - XML_ERROR_PARSING_CDATA, - XML_ERROR_PARSING_COMMENT, - XML_ERROR_PARSING_DECLARATION, - XML_ERROR_PARSING_UNKNOWN, - XML_ERROR_EMPTY_DOCUMENT, - XML_ERROR_MISMATCHED_ELEMENT, - XML_ERROR_PARSING, - XML_CAN_NOT_CONVERT_TEXT, - XML_NO_TEXT_NODE, - XML_ELEMENT_DEPTH_EXCEEDED, - - XML_ERROR_COUNT -}; + /// Visit a declaration. + virtual bool Visit(const XMLDeclaration& /*declaration*/) { + return true; + } + /// Visit a text node. + virtual bool Visit(const XMLText& /*text*/) { + return true; + } + /// Visit a comment node. + virtual bool Visit(const XMLComment& /*comment*/) { + return true; + } + /// Visit an unknown node. + virtual bool Visit(const XMLUnknown& /*unknown*/) { + return true; + } + }; + // WARNING: must match XMLDocument::_errorNames[] + enum XMLError { + XML_SUCCESS = 0, + XML_NO_ATTRIBUTE, + XML_WRONG_ATTRIBUTE_TYPE, + XML_ERROR_FILE_NOT_FOUND, + XML_ERROR_FILE_COULD_NOT_BE_OPENED, + XML_ERROR_FILE_READ_ERROR, + XML_ERROR_PARSING_ELEMENT, + XML_ERROR_PARSING_ATTRIBUTE, + XML_ERROR_PARSING_TEXT, + XML_ERROR_PARSING_CDATA, + XML_ERROR_PARSING_COMMENT, + XML_ERROR_PARSING_DECLARATION, + XML_ERROR_PARSING_UNKNOWN, + XML_ERROR_EMPTY_DOCUMENT, + XML_ERROR_MISMATCHED_ELEMENT, + XML_ERROR_PARSING, + XML_CAN_NOT_CONVERT_TEXT, + XML_NO_TEXT_NODE, + XML_ELEMENT_DEPTH_EXCEEDED, + + XML_ERROR_COUNT + }; -/* - Utility functionality. -*/ -class TINYXML2_LIB XMLUtil -{ -public: - static const char* SkipWhiteSpace( const char* p, int* curLineNumPtr ) { - TIXMLASSERT( p ); - while( IsWhiteSpace(*p) ) { - if (curLineNumPtr && *p == '\n') { - ++(*curLineNumPtr); + /* + Utility functionality. + */ + class TINYXML2_LIB XMLUtil + { + public: + static const char* SkipWhiteSpace(const char* p, int* curLineNumPtr) { + TIXMLASSERT(p); + + while (IsWhiteSpace(*p)) { + if (curLineNumPtr && *p == '\n') { + ++(*curLineNumPtr); + } + ++p; } - ++p; + TIXMLASSERT(p); + return p; + } + static char* SkipWhiteSpace(char* const p, int* curLineNumPtr) { + return const_cast(SkipWhiteSpace(const_cast(p), curLineNumPtr)); } - TIXMLASSERT( p ); - return p; - } - static char* SkipWhiteSpace( char* const p, int* curLineNumPtr ) { - return const_cast( SkipWhiteSpace( const_cast(p), curLineNumPtr ) ); - } - // Anything in the high order range of UTF-8 is assumed to not be whitespace. This isn't - // correct, but simple, and usually works. - static bool IsWhiteSpace( char p ) { - return !IsUTF8Continuation(p) && isspace( static_cast(p) ); - } + // Anything in the high order range of UTF-8 is assumed to not be whitespace. This isn't + // correct, but simple, and usually works. + static bool IsWhiteSpace(char p) { + return !IsUTF8Continuation(p) && isspace(static_cast(p)); + } - inline static bool IsNameStartChar( unsigned char ch ) { - if ( ch >= 128 ) { - // This is a heuristic guess in attempt to not implement Unicode-aware isalpha() - return true; + inline static bool IsNameStartChar(unsigned char ch) { + if (ch >= 128) { + // This is a heuristic guess in attempt to not implement Unicode-aware isalpha() + return true; + } + if (isalpha(ch)) { + return true; + } + return ch == ':' || ch == '_'; } - if ( isalpha( ch ) ) { - return true; + + inline static bool IsNameChar(unsigned char ch) { + return IsNameStartChar(ch) + || isdigit(ch) + || ch == '.' + || ch == '-'; } - return ch == ':' || ch == '_'; - } - inline static bool IsNameChar( unsigned char ch ) { - return IsNameStartChar( ch ) - || isdigit( ch ) - || ch == '.' - || ch == '-'; - } + inline static bool IsPrefixHex(const char* p) { + p = SkipWhiteSpace(p, 0); + return p && *p == '0' && (*(p + 1) == 'x' || *(p + 1) == 'X'); + } - inline static bool IsPrefixHex( const char* p) { - p = SkipWhiteSpace(p, 0); - return p && *p == '0' && ( *(p + 1) == 'x' || *(p + 1) == 'X'); - } + inline static bool StringEqual(const char* p, const char* q, int nChar = INT_MAX) { + if (p == q) { + return true; + } + TIXMLASSERT(p); + TIXMLASSERT(q); + TIXMLASSERT(nChar >= 0); + return strncmp(p, q, nChar) == 0; + } - inline static bool StringEqual( const char* p, const char* q, int nChar=INT_MAX ) { - if ( p == q ) { - return true; + inline static bool IsUTF8Continuation(const char p) { + return (p & 0x80) != 0; } - TIXMLASSERT( p ); - TIXMLASSERT( q ); - TIXMLASSERT( nChar >= 0 ); - return strncmp( p, q, nChar ) == 0; - } - inline static bool IsUTF8Continuation( const char p ) { - return ( p & 0x80 ) != 0; - } + static const char* ReadBOM(const char* p, bool* hasBOM); + // p is the starting location, + // the UTF-8 value of the entity will be placed in value, and length filled in. + static const char* GetCharacterRef(const char* p, char* value, int* length); + static void ConvertUTF32ToUTF8(unsigned long input, char* output, int* length); + + // converts primitive types to strings + static void ToStr(int v, char* buffer, int bufferSize); + static void ToStr(unsigned v, char* buffer, int bufferSize); + static void ToStr(bool v, char* buffer, int bufferSize); + static void ToStr(float v, char* buffer, int bufferSize); + static void ToStr(double v, char* buffer, int bufferSize); + static void ToStr(int64_t v, char* buffer, int bufferSize); + static void ToStr(uint64_t v, char* buffer, int bufferSize); + + // converts strings to primitive types + static bool ToInt(const char* str, int* value); + static bool ToUnsigned(const char* str, unsigned* value); + static bool ToBool(const char* str, bool* value); + static bool ToFloat(const char* str, float* value); + static bool ToDouble(const char* str, double* value); + static bool ToInt64(const char* str, int64_t* value); + static bool ToUnsigned64(const char* str, uint64_t* value); + // Changes what is serialized for a boolean value. + // Default to "true" and "false". Shouldn't be changed + // unless you have a special testing or compatibility need. + // Be careful: static, global, & not thread safe. + // Be sure to set static const memory as parameters. + static void SetBoolSerialization(const char* writeTrue, const char* writeFalse); + + private: + static const char* writeBoolTrue; + static const char* writeBoolFalse; + }; - static const char* ReadBOM( const char* p, bool* hasBOM ); - // p is the starting location, - // the UTF-8 value of the entity will be placed in value, and length filled in. - static const char* GetCharacterRef( const char* p, char* value, int* length ); - static void ConvertUTF32ToUTF8( unsigned long input, char* output, int* length ); - - // converts primitive types to strings - static void ToStr( int v, char* buffer, int bufferSize ); - static void ToStr( unsigned v, char* buffer, int bufferSize ); - static void ToStr( bool v, char* buffer, int bufferSize ); - static void ToStr( float v, char* buffer, int bufferSize ); - static void ToStr( double v, char* buffer, int bufferSize ); - static void ToStr(int64_t v, char* buffer, int bufferSize); - static void ToStr(uint64_t v, char* buffer, int bufferSize); - - // converts strings to primitive types - static bool ToInt( const char* str, int* value ); - static bool ToUnsigned( const char* str, unsigned* value ); - static bool ToBool( const char* str, bool* value ); - static bool ToFloat( const char* str, float* value ); - static bool ToDouble( const char* str, double* value ); - static bool ToInt64(const char* str, int64_t* value); - static bool ToUnsigned64(const char* str, uint64_t* value); - // Changes what is serialized for a boolean value. - // Default to "true" and "false". Shouldn't be changed - // unless you have a special testing or compatibility need. - // Be careful: static, global, & not thread safe. - // Be sure to set static const memory as parameters. - static void SetBoolSerialization(const char* writeTrue, const char* writeFalse); - -private: - static const char* writeBoolTrue; - static const char* writeBoolFalse; -}; - - -/** XMLNode is a base class for every object that is in the - XML Document Object Model (DOM), except XMLAttributes. - Nodes have siblings, a parent, and children which can - be navigated. A node is always in a XMLDocument. - The type of a XMLNode can be queried, and it can - be cast to its more defined type. - - A XMLDocument allocates memory for all its Nodes. - When the XMLDocument gets deleted, all its Nodes - will also be deleted. - - @verbatim - A Document can contain: Element (container or leaf) - Comment (leaf) - Unknown (leaf) - Declaration( leaf ) - - An Element can contain: Element (container or leaf) - Text (leaf) - Attributes (not on tree) - Comment (leaf) - Unknown (leaf) - - @endverbatim -*/ -class TINYXML2_LIB XMLNode -{ - friend class XMLDocument; - friend class XMLElement; -public: - - /// Get the XMLDocument that owns this XMLNode. - const XMLDocument* GetDocument() const { - TIXMLASSERT( _document ); - return _document; - } - /// Get the XMLDocument that owns this XMLNode. - XMLDocument* GetDocument() { - TIXMLASSERT( _document ); - return _document; - } - /// Safely cast to an Element, or null. - virtual XMLElement* ToElement() { - return 0; - } - /// Safely cast to Text, or null. - virtual XMLText* ToText() { - return 0; - } - /// Safely cast to a Comment, or null. - virtual XMLComment* ToComment() { - return 0; - } - /// Safely cast to a Document, or null. - virtual XMLDocument* ToDocument() { - return 0; - } - /// Safely cast to a Declaration, or null. - virtual XMLDeclaration* ToDeclaration() { - return 0; - } - /// Safely cast to an Unknown, or null. - virtual XMLUnknown* ToUnknown() { - return 0; - } + /** XMLNode is a base class for every object that is in the + XML Document Object Model (DOM), except XMLAttributes. + Nodes have siblings, a parent, and children which can + be navigated. A node is always in a XMLDocument. + The type of a XMLNode can be queried, and it can + be cast to its more defined type. - virtual const XMLElement* ToElement() const { - return 0; - } - virtual const XMLText* ToText() const { - return 0; - } - virtual const XMLComment* ToComment() const { - return 0; - } - virtual const XMLDocument* ToDocument() const { - return 0; - } - virtual const XMLDeclaration* ToDeclaration() const { - return 0; - } - virtual const XMLUnknown* ToUnknown() const { - return 0; - } + A XMLDocument allocates memory for all its Nodes. + When the XMLDocument gets deleted, all its Nodes + will also be deleted. - /** The meaning of 'value' changes for the specific type. - @verbatim - Document: empty (NULL is returned, not an empty string) - Element: name of the element - Comment: the comment text - Unknown: the tag contents - Text: the text string - @endverbatim - */ - const char* Value() const; + @verbatim + A Document can contain: Element (container or leaf) + Comment (leaf) + Unknown (leaf) + Declaration( leaf ) + + An Element can contain: Element (container or leaf) + Text (leaf) + Attributes (not on tree) + Comment (leaf) + Unknown (leaf) - /** Set the Value of an XML node. - @sa Value() + @endverbatim */ - void SetValue( const char* val, bool staticMem=false ); + class TINYXML2_LIB XMLNode + { + friend class XMLDocument; + friend class XMLElement; + public: + + /// Get the XMLDocument that owns this XMLNode. + const XMLDocument* GetDocument() const { + TIXMLASSERT(_document); + return _document; + } + /// Get the XMLDocument that owns this XMLNode. + XMLDocument* GetDocument() { + TIXMLASSERT(_document); + return _document; + } - /// Gets the line number the node is in, if the document was parsed from a file. - int GetLineNum() const { return _parseLineNum; } + /// Safely cast to an Element, or null. + virtual XMLElement* ToElement() { + return 0; + } + /// Safely cast to Text, or null. + virtual XMLText* ToText() { + return 0; + } + /// Safely cast to a Comment, or null. + virtual XMLComment* ToComment() { + return 0; + } + /// Safely cast to a Document, or null. + virtual XMLDocument* ToDocument() { + return 0; + } + /// Safely cast to a Declaration, or null. + virtual XMLDeclaration* ToDeclaration() { + return 0; + } + /// Safely cast to an Unknown, or null. + virtual XMLUnknown* ToUnknown() { + return 0; + } - /// Get the parent of this node on the DOM. - const XMLNode* Parent() const { - return _parent; - } + virtual const XMLElement* ToElement() const { + return 0; + } + virtual const XMLText* ToText() const { + return 0; + } + virtual const XMLComment* ToComment() const { + return 0; + } + virtual const XMLDocument* ToDocument() const { + return 0; + } + virtual const XMLDeclaration* ToDeclaration() const { + return 0; + } + virtual const XMLUnknown* ToUnknown() const { + return 0; + } - XMLNode* Parent() { - return _parent; - } + /** The meaning of 'value' changes for the specific type. + @verbatim + Document: empty (NULL is returned, not an empty string) + Element: name of the element + Comment: the comment text + Unknown: the tag contents + Text: the text string + @endverbatim + */ + const char* Value() const; + + /** Set the Value of an XML node. + @sa Value() + */ + void SetValue(const char* val, bool staticMem = false); + + /// Gets the line number the node is in, if the document was parsed from a file. + int GetLineNum() const { return _parseLineNum; } + + /// Get the parent of this node on the DOM. + const XMLNode* Parent() const { + return _parent; + } - /// Returns true if this node has no children. - bool NoChildren() const { - return !_firstChild; - } + XMLNode* Parent() { + return _parent; + } - /// Get the first child node, or null if none exists. - const XMLNode* FirstChild() const { - return _firstChild; - } + /// Returns true if this node has no children. + bool NoChildren() const { + return !_firstChild; + } - XMLNode* FirstChild() { - return _firstChild; - } + /// Get the first child node, or null if none exists. + const XMLNode* FirstChild() const { + return _firstChild; + } - /** Get the first child element, or optionally the first child - element with the specified name. - */ - const XMLElement* FirstChildElement( const char* name = 0 ) const; + XMLNode* FirstChild() { + return _firstChild; + } - XMLElement* FirstChildElement( const char* name = 0 ) { - return const_cast(const_cast(this)->FirstChildElement( name )); - } + /** Get the first child element, or optionally the first child + element with the specified name. + */ + const XMLElement* FirstChildElement(const char* name = 0) const; - /// Get the last child node, or null if none exists. - const XMLNode* LastChild() const { - return _lastChild; - } + XMLElement* FirstChildElement(const char* name = 0) { + return const_cast(const_cast(this)->FirstChildElement(name)); + } - XMLNode* LastChild() { - return _lastChild; - } + /// Get the last child node, or null if none exists. + const XMLNode* LastChild() const { + return _lastChild; + } - /** Get the last child element or optionally the last child - element with the specified name. - */ - const XMLElement* LastChildElement( const char* name = 0 ) const; + XMLNode* LastChild() { + return _lastChild; + } - XMLElement* LastChildElement( const char* name = 0 ) { - return const_cast(const_cast(this)->LastChildElement(name) ); - } + /** Get the last child element or optionally the last child + element with the specified name. + */ + const XMLElement* LastChildElement(const char* name = 0) const; - /// Get the previous (left) sibling node of this node. - const XMLNode* PreviousSibling() const { - return _prev; - } + XMLElement* LastChildElement(const char* name = 0) { + return const_cast(const_cast(this)->LastChildElement(name)); + } - XMLNode* PreviousSibling() { - return _prev; - } + /// Get the previous (left) sibling node of this node. + const XMLNode* PreviousSibling() const { + return _prev; + } - /// Get the previous (left) sibling element of this node, with an optionally supplied name. - const XMLElement* PreviousSiblingElement( const char* name = 0 ) const ; + XMLNode* PreviousSibling() { + return _prev; + } - XMLElement* PreviousSiblingElement( const char* name = 0 ) { - return const_cast(const_cast(this)->PreviousSiblingElement( name ) ); - } + /// Get the previous (left) sibling element of this node, with an optionally supplied name. + const XMLElement* PreviousSiblingElement(const char* name = 0) const; - /// Get the next (right) sibling node of this node. - const XMLNode* NextSibling() const { - return _next; - } + XMLElement* PreviousSiblingElement(const char* name = 0) { + return const_cast(const_cast(this)->PreviousSiblingElement(name)); + } - XMLNode* NextSibling() { - return _next; - } + /// Get the next (right) sibling node of this node. + const XMLNode* NextSibling() const { + return _next; + } - /// Get the next (right) sibling element of this node, with an optionally supplied name. - const XMLElement* NextSiblingElement( const char* name = 0 ) const; + XMLNode* NextSibling() { + return _next; + } - XMLElement* NextSiblingElement( const char* name = 0 ) { - return const_cast(const_cast(this)->NextSiblingElement( name ) ); - } + /// Get the next (right) sibling element of this node, with an optionally supplied name. + const XMLElement* NextSiblingElement(const char* name = 0) const; - /** - Add a child node as the last (right) child. - If the child node is already part of the document, - it is moved from its old location to the new location. - Returns the addThis argument or 0 if the node does not - belong to the same document. - */ - XMLNode* InsertEndChild( XMLNode* addThis ); + XMLElement* NextSiblingElement(const char* name = 0) { + return const_cast(const_cast(this)->NextSiblingElement(name)); + } - XMLNode* LinkEndChild( XMLNode* addThis ) { - return InsertEndChild( addThis ); - } - /** - Add a child node as the first (left) child. - If the child node is already part of the document, - it is moved from its old location to the new location. - Returns the addThis argument or 0 if the node does not - belong to the same document. - */ - XMLNode* InsertFirstChild( XMLNode* addThis ); - /** - Add a node after the specified child node. - If the child node is already part of the document, - it is moved from its old location to the new location. - Returns the addThis argument or 0 if the afterThis node - is not a child of this node, or if the node does not - belong to the same document. - */ - XMLNode* InsertAfterChild( XMLNode* afterThis, XMLNode* addThis ); + /** + Add a child node as the last (right) child. + If the child node is already part of the document, + it is moved from its old location to the new location. + Returns the addThis argument or 0 if the node does not + belong to the same document. + */ + XMLNode* InsertEndChild(XMLNode* addThis); + + XMLNode* LinkEndChild(XMLNode* addThis) { + return InsertEndChild(addThis); + } + /** + Add a child node as the first (left) child. + If the child node is already part of the document, + it is moved from its old location to the new location. + Returns the addThis argument or 0 if the node does not + belong to the same document. + */ + XMLNode* InsertFirstChild(XMLNode* addThis); + /** + Add a node after the specified child node. + If the child node is already part of the document, + it is moved from its old location to the new location. + Returns the addThis argument or 0 if the afterThis node + is not a child of this node, or if the node does not + belong to the same document. + */ + XMLNode* InsertAfterChild(XMLNode* afterThis, XMLNode* addThis); + + /** + Delete all the children of this node. + */ + void DeleteChildren(); + + /** + Delete a child of this node. + */ + void DeleteChild(XMLNode* node); + + /** + Make a copy of this node, but not its children. + You may pass in a Document pointer that will be + the owner of the new Node. If the 'document' is + null, then the node returned will be allocated + from the current Document. (this->GetDocument()) + + Note: if called on a XMLDocument, this will return null. + */ + virtual XMLNode* ShallowClone(XMLDocument* document) const = 0; + + /** + Make a copy of this node and all its children. + + If the 'target' is null, then the nodes will + be allocated in the current document. If 'target' + is specified, the memory will be allocated is the + specified XMLDocument. + + NOTE: This is probably not the correct tool to + copy a document, since XMLDocuments can have multiple + top level XMLNodes. You probably want to use + XMLDocument::DeepCopy() + */ + XMLNode* DeepClone(XMLDocument* target) const; + + /** + Test if 2 nodes are the same, but don't test children. + The 2 nodes do not need to be in the same Document. + + Note: if called on a XMLDocument, this will return false. + */ + virtual bool ShallowEqual(const XMLNode* compare) const = 0; + + /** Accept a hierarchical visit of the nodes in the TinyXML-2 DOM. Every node in the + XML tree will be conditionally visited and the host will be called back + via the XMLVisitor interface. + + This is essentially a SAX interface for TinyXML-2. (Note however it doesn't re-parse + the XML for the callbacks, so the performance of TinyXML-2 is unchanged by using this + interface versus any other.) + + The interface has been based on ideas from: + + - http://www.saxproject.org/ + - http://c2.com/cgi/wiki?HierarchicalVisitorPattern + + Which are both good references for "visiting". + + An example of using Accept(): + @verbatim + XMLPrinter printer; + tinyxmlDoc.Accept( &printer ); + const char* xmlcstr = printer.CStr(); + @endverbatim + */ + virtual bool Accept(XMLVisitor* visitor) const = 0; + + /** + Set user data into the XMLNode. TinyXML-2 in + no way processes or interprets user data. + It is initially 0. + */ + void SetUserData(void* userData) { _userData = userData; } + + /** + Get user data set into the XMLNode. TinyXML-2 in + no way processes or interprets user data. + It is initially 0. + */ + void* GetUserData() const { return _userData; } + + protected: + explicit XMLNode(XMLDocument*); + virtual ~XMLNode(); + + virtual char* ParseDeep(char* p, StrPair* parentEndTag, int* curLineNumPtr); + + XMLDocument* _document; + XMLNode* _parent; + mutable StrPair _value; + int _parseLineNum; + + XMLNode* _firstChild; + XMLNode* _lastChild; + + XMLNode* _prev; + XMLNode* _next; + + void* _userData; + + private: + MemPool* _memPool; + void Unlink(XMLNode* child); + static void DeleteNode(XMLNode* node); + void InsertChildPreamble(XMLNode* insertThis) const; + const XMLElement* ToElementWithName(const char* name) const; + + XMLNode(const XMLNode&); // not supported + XMLNode& operator=(const XMLNode&); // not supported + }; - /** - Delete all the children of this node. - */ - void DeleteChildren(); - /** - Delete a child of this node. - */ - void DeleteChild( XMLNode* node ); + /** XML text. - /** - Make a copy of this node, but not its children. - You may pass in a Document pointer that will be - the owner of the new Node. If the 'document' is - null, then the node returned will be allocated - from the current Document. (this->GetDocument()) + Note that a text node can have child element nodes, for example: + @verbatim + This is bold + @endverbatim - Note: if called on a XMLDocument, this will return null. + A text node can have 2 ways to output the next. "normal" output + and CDATA. It will default to the mode it was parsed from the XML file and + you generally want to leave it alone, but you can change the output mode with + SetCData() and query it with CData(). */ - virtual XMLNode* ShallowClone( XMLDocument* document ) const = 0; + class TINYXML2_LIB XMLText : public XMLNode + { + friend class XMLDocument; + public: + virtual bool Accept(XMLVisitor* visitor) const; - /** - Make a copy of this node and all its children. + virtual XMLText* ToText() { + return this; + } + virtual const XMLText* ToText() const { + return this; + } - If the 'target' is null, then the nodes will - be allocated in the current document. If 'target' - is specified, the memory will be allocated is the - specified XMLDocument. + /// Declare whether this should be CDATA or standard text. + void SetCData(bool isCData) { + _isCData = isCData; + } + /// Returns true if this is a CDATA text element. + bool CData() const { + return _isCData; + } - NOTE: This is probably not the correct tool to - copy a document, since XMLDocuments can have multiple - top level XMLNodes. You probably want to use - XMLDocument::DeepCopy() - */ - XMLNode* DeepClone( XMLDocument* target ) const; + virtual XMLNode* ShallowClone(XMLDocument* document) const; + virtual bool ShallowEqual(const XMLNode* compare) const; - /** - Test if 2 nodes are the same, but don't test children. - The 2 nodes do not need to be in the same Document. + protected: + explicit XMLText(XMLDocument* doc) : XMLNode(doc), _isCData(false) {} + virtual ~XMLText() {} - Note: if called on a XMLDocument, this will return false. - */ - virtual bool ShallowEqual( const XMLNode* compare ) const = 0; + char* ParseDeep(char* p, StrPair* parentEndTag, int* curLineNumPtr); - /** Accept a hierarchical visit of the nodes in the TinyXML-2 DOM. Every node in the - XML tree will be conditionally visited and the host will be called back - via the XMLVisitor interface. + private: + bool _isCData; - This is essentially a SAX interface for TinyXML-2. (Note however it doesn't re-parse - the XML for the callbacks, so the performance of TinyXML-2 is unchanged by using this - interface versus any other.) + XMLText(const XMLText&); // not supported + XMLText& operator=(const XMLText&); // not supported + }; - The interface has been based on ideas from: - - http://www.saxproject.org/ - - http://c2.com/cgi/wiki?HierarchicalVisitorPattern + /** An XML Comment. */ + class TINYXML2_LIB XMLComment : public XMLNode + { + friend class XMLDocument; + public: + virtual XMLComment* ToComment() { + return this; + } + virtual const XMLComment* ToComment() const { + return this; + } - Which are both good references for "visiting". + virtual bool Accept(XMLVisitor* visitor) const; - An example of using Accept(): - @verbatim - XMLPrinter printer; - tinyxmlDoc.Accept( &printer ); - const char* xmlcstr = printer.CStr(); - @endverbatim - */ - virtual bool Accept( XMLVisitor* visitor ) const = 0; + virtual XMLNode* ShallowClone(XMLDocument* document) const; + virtual bool ShallowEqual(const XMLNode* compare) const; - /** - Set user data into the XMLNode. TinyXML-2 in - no way processes or interprets user data. - It is initially 0. - */ - void SetUserData(void* userData) { _userData = userData; } + protected: + explicit XMLComment(XMLDocument* doc); + virtual ~XMLComment(); - /** - Get user data set into the XMLNode. TinyXML-2 in - no way processes or interprets user data. - It is initially 0. - */ - void* GetUserData() const { return _userData; } + char* ParseDeep(char* p, StrPair* parentEndTag, int* curLineNumPtr); -protected: - explicit XMLNode( XMLDocument* ); - virtual ~XMLNode(); + private: + XMLComment(const XMLComment&); // not supported + XMLComment& operator=(const XMLComment&); // not supported + }; - virtual char* ParseDeep( char* p, StrPair* parentEndTag, int* curLineNumPtr); - XMLDocument* _document; - XMLNode* _parent; - mutable StrPair _value; - int _parseLineNum; + /** In correct XML the declaration is the first entry in the file. + @verbatim + + @endverbatim - XMLNode* _firstChild; - XMLNode* _lastChild; + TinyXML-2 will happily read or write files without a declaration, + however. - XMLNode* _prev; - XMLNode* _next; + The text of the declaration isn't interpreted. It is parsed + and written as a string. + */ + class TINYXML2_LIB XMLDeclaration : public XMLNode + { + friend class XMLDocument; + public: + virtual XMLDeclaration* ToDeclaration() { + return this; + } + virtual const XMLDeclaration* ToDeclaration() const { + return this; + } - void* _userData; + virtual bool Accept(XMLVisitor* visitor) const; -private: - MemPool* _memPool; - void Unlink( XMLNode* child ); - static void DeleteNode( XMLNode* node ); - void InsertChildPreamble( XMLNode* insertThis ) const; - const XMLElement* ToElementWithName( const char* name ) const; + virtual XMLNode* ShallowClone(XMLDocument* document) const; + virtual bool ShallowEqual(const XMLNode* compare) const; - XMLNode( const XMLNode& ); // not supported - XMLNode& operator=( const XMLNode& ); // not supported -}; + protected: + explicit XMLDeclaration(XMLDocument* doc); + virtual ~XMLDeclaration(); + char* ParseDeep(char* p, StrPair* parentEndTag, int* curLineNumPtr); -/** XML text. + private: + XMLDeclaration(const XMLDeclaration&); // not supported + XMLDeclaration& operator=(const XMLDeclaration&); // not supported + }; - Note that a text node can have child element nodes, for example: - @verbatim - This is bold - @endverbatim - A text node can have 2 ways to output the next. "normal" output - and CDATA. It will default to the mode it was parsed from the XML file and - you generally want to leave it alone, but you can change the output mode with - SetCData() and query it with CData(). -*/ -class TINYXML2_LIB XMLText : public XMLNode -{ - friend class XMLDocument; -public: - virtual bool Accept( XMLVisitor* visitor ) const; + /** Any tag that TinyXML-2 doesn't recognize is saved as an + unknown. It is a tag of text, but should not be modified. + It will be written back to the XML, unchanged, when the file + is saved. - virtual XMLText* ToText() { - return this; - } - virtual const XMLText* ToText() const { - return this; - } + DTD tags get thrown into XMLUnknowns. + */ + class TINYXML2_LIB XMLUnknown : public XMLNode + { + friend class XMLDocument; + public: + virtual XMLUnknown* ToUnknown() { + return this; + } + virtual const XMLUnknown* ToUnknown() const { + return this; + } - /// Declare whether this should be CDATA or standard text. - void SetCData( bool isCData ) { - _isCData = isCData; - } - /// Returns true if this is a CDATA text element. - bool CData() const { - return _isCData; - } + virtual bool Accept(XMLVisitor* visitor) const; - virtual XMLNode* ShallowClone( XMLDocument* document ) const; - virtual bool ShallowEqual( const XMLNode* compare ) const; + virtual XMLNode* ShallowClone(XMLDocument* document) const; + virtual bool ShallowEqual(const XMLNode* compare) const; -protected: - explicit XMLText( XMLDocument* doc ) : XMLNode( doc ), _isCData( false ) {} - virtual ~XMLText() {} + protected: + explicit XMLUnknown(XMLDocument* doc); + virtual ~XMLUnknown(); - char* ParseDeep( char* p, StrPair* parentEndTag, int* curLineNumPtr ); + char* ParseDeep(char* p, StrPair* parentEndTag, int* curLineNumPtr); -private: - bool _isCData; + private: + XMLUnknown(const XMLUnknown&); // not supported + XMLUnknown& operator=(const XMLUnknown&); // not supported + }; - XMLText( const XMLText& ); // not supported - XMLText& operator=( const XMLText& ); // not supported -}; -/** An XML Comment. */ -class TINYXML2_LIB XMLComment : public XMLNode -{ - friend class XMLDocument; -public: - virtual XMLComment* ToComment() { - return this; - } - virtual const XMLComment* ToComment() const { - return this; - } - - virtual bool Accept( XMLVisitor* visitor ) const; - - virtual XMLNode* ShallowClone( XMLDocument* document ) const; - virtual bool ShallowEqual( const XMLNode* compare ) const; + /** An attribute is a name-value pair. Elements have an arbitrary + number of attributes, each with a unique name. -protected: - explicit XMLComment( XMLDocument* doc ); - virtual ~XMLComment(); + @note The attributes are not XMLNodes. You may only query the + Next() attribute in a list. + */ + class TINYXML2_LIB XMLAttribute + { + friend class XMLElement; + public: + /// The name of the attribute. + const char* Name() const; - char* ParseDeep( char* p, StrPair* parentEndTag, int* curLineNumPtr); + /// The value of the attribute. + const char* Value() const; -private: - XMLComment( const XMLComment& ); // not supported - XMLComment& operator=( const XMLComment& ); // not supported -}; + /// Gets the line number the attribute is in, if the document was parsed from a file. + int GetLineNum() const { return _parseLineNum; } + /// The next attribute in the list. + const XMLAttribute* Next() const { + return _next; + } -/** In correct XML the declaration is the first entry in the file. - @verbatim - - @endverbatim + /** IntValue interprets the attribute as an integer, and returns the value. + If the value isn't an integer, 0 will be returned. There is no error checking; + use QueryIntValue() if you need error checking. + */ + int IntValue() const { + int i = 0; + QueryIntValue(&i); + return i; + } - TinyXML-2 will happily read or write files without a declaration, - however. + int64_t Int64Value() const { + int64_t i = 0; + QueryInt64Value(&i); + return i; + } - The text of the declaration isn't interpreted. It is parsed - and written as a string. -*/ -class TINYXML2_LIB XMLDeclaration : public XMLNode -{ - friend class XMLDocument; -public: - virtual XMLDeclaration* ToDeclaration() { - return this; - } - virtual const XMLDeclaration* ToDeclaration() const { - return this; - } + uint64_t Unsigned64Value() const { + uint64_t i = 0; + QueryUnsigned64Value(&i); + return i; + } - virtual bool Accept( XMLVisitor* visitor ) const; + /// Query as an unsigned integer. See IntValue() + unsigned UnsignedValue() const { + unsigned i = 0; + QueryUnsignedValue(&i); + return i; + } + /// Query as a boolean. See IntValue() + bool BoolValue() const { + bool b = false; + QueryBoolValue(&b); + return b; + } + /// Query as a double. See IntValue() + double DoubleValue() const { + double d = 0; + QueryDoubleValue(&d); + return d; + } + /// Query as a float. See IntValue() + float FloatValue() const { + float f = 0; + QueryFloatValue(&f); + return f; + } - virtual XMLNode* ShallowClone( XMLDocument* document ) const; - virtual bool ShallowEqual( const XMLNode* compare ) const; + /** QueryIntValue interprets the attribute as an integer, and returns the value + in the provided parameter. The function will return XML_SUCCESS on success, + and XML_WRONG_ATTRIBUTE_TYPE if the conversion is not successful. + */ + XMLError QueryIntValue(int* value) const; + /// See QueryIntValue + XMLError QueryUnsignedValue(unsigned int* value) const; + /// See QueryIntValue + XMLError QueryInt64Value(int64_t* value) const; + /// See QueryIntValue + XMLError QueryUnsigned64Value(uint64_t* value) const; + /// See QueryIntValue + XMLError QueryBoolValue(bool* value) const; + /// See QueryIntValue + XMLError QueryDoubleValue(double* value) const; + /// See QueryIntValue + XMLError QueryFloatValue(float* value) const; + + /// Set the attribute to a string value. + void SetAttribute(const char* value); + /// Set the attribute to value. + void SetAttribute(int value); + /// Set the attribute to value. + void SetAttribute(unsigned value); + /// Set the attribute to value. + void SetAttribute(int64_t value); + /// Set the attribute to value. + void SetAttribute(uint64_t value); + /// Set the attribute to value. + void SetAttribute(bool value); + /// Set the attribute to value. + void SetAttribute(double value); + /// Set the attribute to value. + void SetAttribute(float value); + + private: + enum { BUF_SIZE = 200 }; + + XMLAttribute() : _name(), _value(), _parseLineNum(0), _next(0), _memPool(0) {} + virtual ~XMLAttribute() {} + + XMLAttribute(const XMLAttribute&); // not supported + void operator=(const XMLAttribute&); // not supported + void SetName(const char* name); + + char* ParseDeep(char* p, bool processEntities, int* curLineNumPtr); + + mutable StrPair _name; + mutable StrPair _value; + int _parseLineNum; + XMLAttribute* _next; + MemPool* _memPool; + }; -protected: - explicit XMLDeclaration( XMLDocument* doc ); - virtual ~XMLDeclaration(); - char* ParseDeep( char* p, StrPair* parentEndTag, int* curLineNumPtr ); + /** The element is a container class. It has a value, the element name, + and can contain other elements, text, comments, and unknowns. + Elements also contain an arbitrary number of attributes. + */ + class TINYXML2_LIB XMLElement : public XMLNode + { + friend class XMLDocument; + public: + /// Get the name of an element (which is the Value() of the node.) + const char* Name() const { + return Value(); + } + /// Set the name of the element. + void SetName(const char* str, bool staticMem = false) { + SetValue(str, staticMem); + } -private: - XMLDeclaration( const XMLDeclaration& ); // not supported - XMLDeclaration& operator=( const XMLDeclaration& ); // not supported -}; + virtual XMLElement* ToElement() { + return this; + } + virtual const XMLElement* ToElement() const { + return this; + } + virtual bool Accept(XMLVisitor* visitor) const; + /** Given an attribute name, Attribute() returns the value + for the attribute of that name, or null if none + exists. For example: -/** Any tag that TinyXML-2 doesn't recognize is saved as an - unknown. It is a tag of text, but should not be modified. - It will be written back to the XML, unchanged, when the file - is saved. + @verbatim + const char* value = ele->Attribute( "foo" ); + @endverbatim - DTD tags get thrown into XMLUnknowns. -*/ -class TINYXML2_LIB XMLUnknown : public XMLNode -{ - friend class XMLDocument; -public: - virtual XMLUnknown* ToUnknown() { - return this; - } - virtual const XMLUnknown* ToUnknown() const { - return this; - } + The 'value' parameter is normally null. However, if specified, + the attribute will only be returned if the 'name' and 'value' + match. This allow you to write code: - virtual bool Accept( XMLVisitor* visitor ) const; + @verbatim + if ( ele->Attribute( "foo", "bar" ) ) callFooIsBar(); + @endverbatim - virtual XMLNode* ShallowClone( XMLDocument* document ) const; - virtual bool ShallowEqual( const XMLNode* compare ) const; + rather than: + @verbatim + if ( ele->Attribute( "foo" ) ) { + if ( strcmp( ele->Attribute( "foo" ), "bar" ) == 0 ) callFooIsBar(); + } + @endverbatim + */ + const char* Attribute(const char* name, const char* value = 0) const; + + /** Given an attribute name, IntAttribute() returns the value + of the attribute interpreted as an integer. The default + value will be returned if the attribute isn't present, + or if there is an error. (For a method with error + checking, see QueryIntAttribute()). + */ + int IntAttribute(const char* name, int defaultValue = 0) const; + /// See IntAttribute() + unsigned UnsignedAttribute(const char* name, unsigned defaultValue = 0) const; + /// See IntAttribute() + int64_t Int64Attribute(const char* name, int64_t defaultValue = 0) const; + /// See IntAttribute() + uint64_t Unsigned64Attribute(const char* name, uint64_t defaultValue = 0) const; + /// See IntAttribute() + bool BoolAttribute(const char* name, bool defaultValue = false) const; + /// See IntAttribute() + double DoubleAttribute(const char* name, double defaultValue = 0) const; + /// See IntAttribute() + float FloatAttribute(const char* name, float defaultValue = 0) const; + + /** Given an attribute name, QueryIntAttribute() returns + XML_SUCCESS, XML_WRONG_ATTRIBUTE_TYPE if the conversion + can't be performed, or XML_NO_ATTRIBUTE if the attribute + doesn't exist. If successful, the result of the conversion + will be written to 'value'. If not successful, nothing will + be written to 'value'. This allows you to provide default + value: + + @verbatim + int value = 10; + QueryIntAttribute( "foo", &value ); // if "foo" isn't found, value will still be 10 + @endverbatim + */ + XMLError QueryIntAttribute(const char* name, int* value) const { + const XMLAttribute* a = FindAttribute(name); + if (!a) { + return XML_NO_ATTRIBUTE; + } + return a->QueryIntValue(value); + } -protected: - explicit XMLUnknown( XMLDocument* doc ); - virtual ~XMLUnknown(); + /// See QueryIntAttribute() + XMLError QueryUnsignedAttribute(const char* name, unsigned int* value) const { + const XMLAttribute* a = FindAttribute(name); + if (!a) { + return XML_NO_ATTRIBUTE; + } + return a->QueryUnsignedValue(value); + } - char* ParseDeep( char* p, StrPair* parentEndTag, int* curLineNumPtr ); + /// See QueryIntAttribute() + XMLError QueryInt64Attribute(const char* name, int64_t* value) const { + const XMLAttribute* a = FindAttribute(name); + if (!a) { + return XML_NO_ATTRIBUTE; + } + return a->QueryInt64Value(value); + } -private: - XMLUnknown( const XMLUnknown& ); // not supported - XMLUnknown& operator=( const XMLUnknown& ); // not supported -}; + /// See QueryIntAttribute() + XMLError QueryUnsigned64Attribute(const char* name, uint64_t* value) const { + const XMLAttribute* a = FindAttribute(name); + if (!a) { + return XML_NO_ATTRIBUTE; + } + return a->QueryUnsigned64Value(value); + } + /// See QueryIntAttribute() + XMLError QueryBoolAttribute(const char* name, bool* value) const { + const XMLAttribute* a = FindAttribute(name); + if (!a) { + return XML_NO_ATTRIBUTE; + } + return a->QueryBoolValue(value); + } + /// See QueryIntAttribute() + XMLError QueryDoubleAttribute(const char* name, double* value) const { + const XMLAttribute* a = FindAttribute(name); + if (!a) { + return XML_NO_ATTRIBUTE; + } + return a->QueryDoubleValue(value); + } + /// See QueryIntAttribute() + XMLError QueryFloatAttribute(const char* name, float* value) const { + const XMLAttribute* a = FindAttribute(name); + if (!a) { + return XML_NO_ATTRIBUTE; + } + return a->QueryFloatValue(value); + } + /// See QueryIntAttribute() + XMLError QueryStringAttribute(const char* name, const char** value) const { + const XMLAttribute* a = FindAttribute(name); + if (!a) { + return XML_NO_ATTRIBUTE; + } + *value = a->Value(); + return XML_SUCCESS; + } -/** An attribute is a name-value pair. Elements have an arbitrary - number of attributes, each with a unique name. - @note The attributes are not XMLNodes. You may only query the - Next() attribute in a list. -*/ -class TINYXML2_LIB XMLAttribute -{ - friend class XMLElement; -public: - /// The name of the attribute. - const char* Name() const; - /// The value of the attribute. - const char* Value() const; + /** Given an attribute name, QueryAttribute() returns + XML_SUCCESS, XML_WRONG_ATTRIBUTE_TYPE if the conversion + can't be performed, or XML_NO_ATTRIBUTE if the attribute + doesn't exist. It is overloaded for the primitive types, + and is a generally more convenient replacement of + QueryIntAttribute() and related functions. - /// Gets the line number the attribute is in, if the document was parsed from a file. - int GetLineNum() const { return _parseLineNum; } + If successful, the result of the conversion + will be written to 'value'. If not successful, nothing will + be written to 'value'. This allows you to provide default + value: - /// The next attribute in the list. - const XMLAttribute* Next() const { - return _next; - } + @verbatim + int value = 10; + QueryAttribute( "foo", &value ); // if "foo" isn't found, value will still be 10 + @endverbatim + */ + XMLError QueryAttribute(const char* name, int* value) const { + return QueryIntAttribute(name, value); + } - /** IntValue interprets the attribute as an integer, and returns the value. - If the value isn't an integer, 0 will be returned. There is no error checking; - use QueryIntValue() if you need error checking. - */ - int IntValue() const { - int i = 0; - QueryIntValue(&i); - return i; - } - - int64_t Int64Value() const { - int64_t i = 0; - QueryInt64Value(&i); - return i; - } - - uint64_t Unsigned64Value() const { - uint64_t i = 0; - QueryUnsigned64Value(&i); - return i; - } + XMLError QueryAttribute(const char* name, unsigned int* value) const { + return QueryUnsignedAttribute(name, value); + } - /// Query as an unsigned integer. See IntValue() - unsigned UnsignedValue() const { - unsigned i=0; - QueryUnsignedValue( &i ); - return i; - } - /// Query as a boolean. See IntValue() - bool BoolValue() const { - bool b=false; - QueryBoolValue( &b ); - return b; - } - /// Query as a double. See IntValue() - double DoubleValue() const { - double d=0; - QueryDoubleValue( &d ); - return d; - } - /// Query as a float. See IntValue() - float FloatValue() const { - float f=0; - QueryFloatValue( &f ); - return f; - } + XMLError QueryAttribute(const char* name, int64_t* value) const { + return QueryInt64Attribute(name, value); + } - /** QueryIntValue interprets the attribute as an integer, and returns the value - in the provided parameter. The function will return XML_SUCCESS on success, - and XML_WRONG_ATTRIBUTE_TYPE if the conversion is not successful. - */ - XMLError QueryIntValue( int* value ) const; - /// See QueryIntValue - XMLError QueryUnsignedValue( unsigned int* value ) const; - /// See QueryIntValue - XMLError QueryInt64Value(int64_t* value) const; - /// See QueryIntValue - XMLError QueryUnsigned64Value(uint64_t* value) const; - /// See QueryIntValue - XMLError QueryBoolValue( bool* value ) const; - /// See QueryIntValue - XMLError QueryDoubleValue( double* value ) const; - /// See QueryIntValue - XMLError QueryFloatValue( float* value ) const; - - /// Set the attribute to a string value. - void SetAttribute( const char* value ); - /// Set the attribute to value. - void SetAttribute( int value ); - /// Set the attribute to value. - void SetAttribute( unsigned value ); - /// Set the attribute to value. - void SetAttribute(int64_t value); - /// Set the attribute to value. - void SetAttribute(uint64_t value); - /// Set the attribute to value. - void SetAttribute( bool value ); - /// Set the attribute to value. - void SetAttribute( double value ); - /// Set the attribute to value. - void SetAttribute( float value ); - -private: - enum { BUF_SIZE = 200 }; - - XMLAttribute() : _name(), _value(),_parseLineNum( 0 ), _next( 0 ), _memPool( 0 ) {} - virtual ~XMLAttribute() {} - - XMLAttribute( const XMLAttribute& ); // not supported - void operator=( const XMLAttribute& ); // not supported - void SetName( const char* name ); - - char* ParseDeep( char* p, bool processEntities, int* curLineNumPtr ); - - mutable StrPair _name; - mutable StrPair _value; - int _parseLineNum; - XMLAttribute* _next; - MemPool* _memPool; -}; - - -/** The element is a container class. It has a value, the element name, - and can contain other elements, text, comments, and unknowns. - Elements also contain an arbitrary number of attributes. -*/ -class TINYXML2_LIB XMLElement : public XMLNode -{ - friend class XMLDocument; -public: - /// Get the name of an element (which is the Value() of the node.) - const char* Name() const { - return Value(); - } - /// Set the name of the element. - void SetName( const char* str, bool staticMem=false ) { - SetValue( str, staticMem ); - } + XMLError QueryAttribute(const char* name, uint64_t* value) const { + return QueryUnsigned64Attribute(name, value); + } - virtual XMLElement* ToElement() { - return this; - } - virtual const XMLElement* ToElement() const { - return this; - } - virtual bool Accept( XMLVisitor* visitor ) const; - - /** Given an attribute name, Attribute() returns the value - for the attribute of that name, or null if none - exists. For example: - - @verbatim - const char* value = ele->Attribute( "foo" ); - @endverbatim - - The 'value' parameter is normally null. However, if specified, - the attribute will only be returned if the 'name' and 'value' - match. This allow you to write code: - - @verbatim - if ( ele->Attribute( "foo", "bar" ) ) callFooIsBar(); - @endverbatim - - rather than: - @verbatim - if ( ele->Attribute( "foo" ) ) { - if ( strcmp( ele->Attribute( "foo" ), "bar" ) == 0 ) callFooIsBar(); - } - @endverbatim - */ - const char* Attribute( const char* name, const char* value=0 ) const; + XMLError QueryAttribute(const char* name, bool* value) const { + return QueryBoolAttribute(name, value); + } - /** Given an attribute name, IntAttribute() returns the value - of the attribute interpreted as an integer. The default - value will be returned if the attribute isn't present, - or if there is an error. (For a method with error - checking, see QueryIntAttribute()). - */ - int IntAttribute(const char* name, int defaultValue = 0) const; - /// See IntAttribute() - unsigned UnsignedAttribute(const char* name, unsigned defaultValue = 0) const; - /// See IntAttribute() - int64_t Int64Attribute(const char* name, int64_t defaultValue = 0) const; - /// See IntAttribute() - uint64_t Unsigned64Attribute(const char* name, uint64_t defaultValue = 0) const; - /// See IntAttribute() - bool BoolAttribute(const char* name, bool defaultValue = false) const; - /// See IntAttribute() - double DoubleAttribute(const char* name, double defaultValue = 0) const; - /// See IntAttribute() - float FloatAttribute(const char* name, float defaultValue = 0) const; - - /** Given an attribute name, QueryIntAttribute() returns - XML_SUCCESS, XML_WRONG_ATTRIBUTE_TYPE if the conversion - can't be performed, or XML_NO_ATTRIBUTE if the attribute - doesn't exist. If successful, the result of the conversion - will be written to 'value'. If not successful, nothing will - be written to 'value'. This allows you to provide default - value: - - @verbatim - int value = 10; - QueryIntAttribute( "foo", &value ); // if "foo" isn't found, value will still be 10 - @endverbatim - */ - XMLError QueryIntAttribute( const char* name, int* value ) const { - const XMLAttribute* a = FindAttribute( name ); - if ( !a ) { - return XML_NO_ATTRIBUTE; + XMLError QueryAttribute(const char* name, double* value) const { + return QueryDoubleAttribute(name, value); } - return a->QueryIntValue( value ); - } - /// See QueryIntAttribute() - XMLError QueryUnsignedAttribute( const char* name, unsigned int* value ) const { - const XMLAttribute* a = FindAttribute( name ); - if ( !a ) { - return XML_NO_ATTRIBUTE; + XMLError QueryAttribute(const char* name, float* value) const { + return QueryFloatAttribute(name, value); } - return a->QueryUnsignedValue( value ); - } - /// See QueryIntAttribute() - XMLError QueryInt64Attribute(const char* name, int64_t* value) const { - const XMLAttribute* a = FindAttribute(name); - if (!a) { - return XML_NO_ATTRIBUTE; - } - return a->QueryInt64Value(value); - } - - /// See QueryIntAttribute() - XMLError QueryUnsigned64Attribute(const char* name, uint64_t* value) const { - const XMLAttribute* a = FindAttribute(name); - if(!a) { - return XML_NO_ATTRIBUTE; - } - return a->QueryUnsigned64Value(value); - } + XMLError QueryAttribute(const char* name, const char** value) const { + return QueryStringAttribute(name, value); + } - /// See QueryIntAttribute() - XMLError QueryBoolAttribute( const char* name, bool* value ) const { - const XMLAttribute* a = FindAttribute( name ); - if ( !a ) { - return XML_NO_ATTRIBUTE; + /// Sets the named attribute to value. + void SetAttribute(const char* name, const char* value) { + XMLAttribute* a = FindOrCreateAttribute(name); + a->SetAttribute(value); } - return a->QueryBoolValue( value ); - } - /// See QueryIntAttribute() - XMLError QueryDoubleAttribute( const char* name, double* value ) const { - const XMLAttribute* a = FindAttribute( name ); - if ( !a ) { - return XML_NO_ATTRIBUTE; + /// Sets the named attribute to value. + void SetAttribute(const char* name, int value) { + XMLAttribute* a = FindOrCreateAttribute(name); + a->SetAttribute(value); } - return a->QueryDoubleValue( value ); - } - /// See QueryIntAttribute() - XMLError QueryFloatAttribute( const char* name, float* value ) const { - const XMLAttribute* a = FindAttribute( name ); - if ( !a ) { - return XML_NO_ATTRIBUTE; + /// Sets the named attribute to value. + void SetAttribute(const char* name, unsigned value) { + XMLAttribute* a = FindOrCreateAttribute(name); + a->SetAttribute(value); } - return a->QueryFloatValue( value ); - } - /// See QueryIntAttribute() - XMLError QueryStringAttribute(const char* name, const char** value) const { - const XMLAttribute* a = FindAttribute(name); - if (!a) { - return XML_NO_ATTRIBUTE; - } - *value = a->Value(); - return XML_SUCCESS; - } - - - - /** Given an attribute name, QueryAttribute() returns - XML_SUCCESS, XML_WRONG_ATTRIBUTE_TYPE if the conversion - can't be performed, or XML_NO_ATTRIBUTE if the attribute - doesn't exist. It is overloaded for the primitive types, - and is a generally more convenient replacement of - QueryIntAttribute() and related functions. - - If successful, the result of the conversion - will be written to 'value'. If not successful, nothing will - be written to 'value'. This allows you to provide default - value: - - @verbatim - int value = 10; - QueryAttribute( "foo", &value ); // if "foo" isn't found, value will still be 10 - @endverbatim - */ - XMLError QueryAttribute( const char* name, int* value ) const { - return QueryIntAttribute( name, value ); - } - - XMLError QueryAttribute( const char* name, unsigned int* value ) const { - return QueryUnsignedAttribute( name, value ); - } + /// Sets the named attribute to value. + void SetAttribute(const char* name, int64_t value) { + XMLAttribute* a = FindOrCreateAttribute(name); + a->SetAttribute(value); + } - XMLError QueryAttribute(const char* name, int64_t* value) const { - return QueryInt64Attribute(name, value); - } + /// Sets the named attribute to value. + void SetAttribute(const char* name, uint64_t value) { + XMLAttribute* a = FindOrCreateAttribute(name); + a->SetAttribute(value); + } - XMLError QueryAttribute(const char* name, uint64_t* value) const { - return QueryUnsigned64Attribute(name, value); - } + /// Sets the named attribute to value. + void SetAttribute(const char* name, bool value) { + XMLAttribute* a = FindOrCreateAttribute(name); + a->SetAttribute(value); + } + /// Sets the named attribute to value. + void SetAttribute(const char* name, double value) { + XMLAttribute* a = FindOrCreateAttribute(name); + a->SetAttribute(value); + } + /// Sets the named attribute to value. + void SetAttribute(const char* name, float value) { + XMLAttribute* a = FindOrCreateAttribute(name); + a->SetAttribute(value); + } - XMLError QueryAttribute( const char* name, bool* value ) const { - return QueryBoolAttribute( name, value ); - } + /** + Delete an attribute. + */ + void DeleteAttribute(const char* name); - XMLError QueryAttribute( const char* name, double* value ) const { - return QueryDoubleAttribute( name, value ); - } + /// Return the first attribute in the list. + const XMLAttribute* FirstAttribute() const { + return _rootAttribute; + } + /// Query a specific attribute in the list. + const XMLAttribute* FindAttribute(const char* name) const; + + /** Convenience function for easy access to the text inside an element. Although easy + and concise, GetText() is limited compared to getting the XMLText child + and accessing it directly. + + If the first child of 'this' is a XMLText, the GetText() + returns the character string of the Text node, else null is returned. + + This is a convenient method for getting the text of simple contained text: + @verbatim + This is text + const char* str = fooElement->GetText(); + @endverbatim + + 'str' will be a pointer to "This is text". + + Note that this function can be misleading. If the element foo was created from + this XML: + @verbatim + This is text + @endverbatim + + then the value of str would be null. The first child node isn't a text node, it is + another element. From this XML: + @verbatim + This is text + @endverbatim + GetText() will return "This is ". + */ + const char* GetText() const; + + /** Convenience function for easy access to the text inside an element. Although easy + and concise, SetText() is limited compared to creating an XMLText child + and mutating it directly. + + If the first child of 'this' is a XMLText, SetText() sets its value to + the given string, otherwise it will create a first child that is an XMLText. + + This is a convenient method for setting the text of simple contained text: + @verbatim + This is text + fooElement->SetText( "Hullaballoo!" ); + Hullaballoo! + @endverbatim + + Note that this function can be misleading. If the element foo was created from + this XML: + @verbatim + This is text + @endverbatim + + then it will not change "This is text", but rather prefix it with a text element: + @verbatim + Hullaballoo!This is text + @endverbatim + + For this XML: + @verbatim + + @endverbatim + SetText() will generate + @verbatim + Hullaballoo! + @endverbatim + */ + void SetText(const char* inText); + /// Convenience method for setting text inside an element. See SetText() for important limitations. + void SetText(int value); + /// Convenience method for setting text inside an element. See SetText() for important limitations. + void SetText(unsigned value); + /// Convenience method for setting text inside an element. See SetText() for important limitations. + void SetText(int64_t value); + /// Convenience method for setting text inside an element. See SetText() for important limitations. + void SetText(uint64_t value); + /// Convenience method for setting text inside an element. See SetText() for important limitations. + void SetText(bool value); + /// Convenience method for setting text inside an element. See SetText() for important limitations. + void SetText(double value); + /// Convenience method for setting text inside an element. See SetText() for important limitations. + void SetText(float value); + + /** + Convenience method to query the value of a child text node. This is probably best + shown by example. Given you have a document is this form: + @verbatim + + 1 + 1.4 + + @endverbatim + + The QueryIntText() and similar functions provide a safe and easier way to get to the + "value" of x and y. + + @verbatim + int x = 0; + float y = 0; // types of x and y are contrived for example + const XMLElement* xElement = pointElement->FirstChildElement( "x" ); + const XMLElement* yElement = pointElement->FirstChildElement( "y" ); + xElement->QueryIntText( &x ); + yElement->QueryFloatText( &y ); + @endverbatim + + @returns XML_SUCCESS (0) on success, XML_CAN_NOT_CONVERT_TEXT if the text cannot be converted + to the requested type, and XML_NO_TEXT_NODE if there is no child text to query. + + */ + XMLError QueryIntText(int* ival) const; + /// See QueryIntText() + XMLError QueryUnsignedText(unsigned* uval) const; + /// See QueryIntText() + XMLError QueryInt64Text(int64_t* uval) const; + /// See QueryIntText() + XMLError QueryUnsigned64Text(uint64_t* uval) const; + /// See QueryIntText() + XMLError QueryBoolText(bool* bval) const; + /// See QueryIntText() + XMLError QueryDoubleText(double* dval) const; + /// See QueryIntText() + XMLError QueryFloatText(float* fval) const; + + int IntText(int defaultValue = 0) const; + + /// See QueryIntText() + unsigned UnsignedText(unsigned defaultValue = 0) const; + /// See QueryIntText() + int64_t Int64Text(int64_t defaultValue = 0) const; + /// See QueryIntText() + uint64_t Unsigned64Text(uint64_t defaultValue = 0) const; + /// See QueryIntText() + bool BoolText(bool defaultValue = false) const; + /// See QueryIntText() + double DoubleText(double defaultValue = 0) const; + /// See QueryIntText() + float FloatText(float defaultValue = 0) const; + + /** + Convenience method to create a new XMLElement and add it as last (right) + child of this node. Returns the created and inserted element. + */ + XMLElement* InsertNewChildElement(const char* name); + /// See InsertNewChildElement() + XMLComment* InsertNewComment(const char* comment); + /// See InsertNewChildElement() + XMLText* InsertNewText(const char* text); + /// See InsertNewChildElement() + XMLDeclaration* InsertNewDeclaration(const char* text); + /// See InsertNewChildElement() + XMLUnknown* InsertNewUnknown(const char* text); + + + // internal: + enum ElementClosingType { + OPENED, // + CLOSED, // + CLOSING // + }; + ElementClosingType ClosingType() const { + return _closingType; + } + virtual XMLNode* ShallowClone(XMLDocument* document) const; + virtual bool ShallowEqual(const XMLNode* compare) const; + + protected: + char* ParseDeep(char* p, StrPair* parentEndTag, int* curLineNumPtr); + + private: + XMLElement(XMLDocument* doc); + virtual ~XMLElement(); + XMLElement(const XMLElement&); // not supported + void operator=(const XMLElement&); // not supported + + XMLAttribute* FindOrCreateAttribute(const char* name); + char* ParseAttributes(char* p, int* curLineNumPtr); + static void DeleteAttribute(XMLAttribute* attribute); + XMLAttribute* CreateAttribute(); + + enum { BUF_SIZE = 200 }; + ElementClosingType _closingType; + // The attribute list is ordered; there is no 'lastAttribute' + // because the list needs to be scanned for dupes before adding + // a new attribute. + XMLAttribute* _rootAttribute; + }; - XMLError QueryAttribute( const char* name, float* value ) const { - return QueryFloatAttribute( name, value ); - } - XMLError QueryAttribute(const char* name, const char** value) const { - return QueryStringAttribute(name, value); - } + enum Whitespace { + PRESERVE_WHITESPACE, + COLLAPSE_WHITESPACE + }; - /// Sets the named attribute to value. - void SetAttribute( const char* name, const char* value ) { - XMLAttribute* a = FindOrCreateAttribute( name ); - a->SetAttribute( value ); - } - /// Sets the named attribute to value. - void SetAttribute( const char* name, int value ) { - XMLAttribute* a = FindOrCreateAttribute( name ); - a->SetAttribute( value ); - } - /// Sets the named attribute to value. - void SetAttribute( const char* name, unsigned value ) { - XMLAttribute* a = FindOrCreateAttribute( name ); - a->SetAttribute( value ); - } - /// Sets the named attribute to value. - void SetAttribute(const char* name, int64_t value) { - XMLAttribute* a = FindOrCreateAttribute(name); - a->SetAttribute(value); - } + /** A Document binds together all the functionality. + It can be saved, loaded, and printed to the screen. + All Nodes are connected and allocated to a Document. + If the Document is deleted, all its Nodes are also deleted. + */ + class TINYXML2_LIB XMLDocument : public XMLNode + { + friend class XMLElement; + // Gives access to SetError and Push/PopDepth, but over-access for everything else. + // Wishing C++ had "internal" scope. + friend class XMLNode; + friend class XMLText; + friend class XMLComment; + friend class XMLDeclaration; + friend class XMLUnknown; + public: + /// constructor + XMLDocument(bool processEntities = true, Whitespace whitespaceMode = PRESERVE_WHITESPACE); + ~XMLDocument(); + + virtual XMLDocument* ToDocument() { + TIXMLASSERT(this == _document); + return this; + } + virtual const XMLDocument* ToDocument() const { + TIXMLASSERT(this == _document); + return this; + } - /// Sets the named attribute to value. - void SetAttribute(const char* name, uint64_t value) { - XMLAttribute* a = FindOrCreateAttribute(name); - a->SetAttribute(value); - } + /** + Parse an XML file from a character string. + Returns XML_SUCCESS (0) on success, or + an errorID. + + You may optionally pass in the 'nBytes', which is + the number of bytes which will be parsed. If not + specified, TinyXML-2 will assume 'xml' points to a + null terminated string. + */ + XMLError Parse(const char* xml, size_t nBytes = static_cast(-1)); + + /** + Load an XML file from disk. + Returns XML_SUCCESS (0) on success, or + an errorID. + */ + XMLError LoadFile(const char* filename); + + /** + Load an XML file from disk. You are responsible + for providing and closing the FILE*. + + NOTE: The file should be opened as binary ("rb") + not text in order for TinyXML-2 to correctly + do newline normalization. + + Returns XML_SUCCESS (0) on success, or + an errorID. + */ + XMLError LoadFile(FILE*); + + /** + Save the XML file to disk. + Returns XML_SUCCESS (0) on success, or + an errorID. + */ + XMLError SaveFile(const char* filename, bool compact = false); + + /** + Save the XML file to disk. You are responsible + for providing and closing the FILE*. + + Returns XML_SUCCESS (0) on success, or + an errorID. + */ + XMLError SaveFile(FILE* fp, bool compact = false); + + bool ProcessEntities() const { + return _processEntities; + } + Whitespace WhitespaceMode() const { + return _whitespaceMode; + } - /// Sets the named attribute to value. - void SetAttribute( const char* name, bool value ) { - XMLAttribute* a = FindOrCreateAttribute( name ); - a->SetAttribute( value ); - } - /// Sets the named attribute to value. - void SetAttribute( const char* name, double value ) { - XMLAttribute* a = FindOrCreateAttribute( name ); - a->SetAttribute( value ); - } - /// Sets the named attribute to value. - void SetAttribute( const char* name, float value ) { - XMLAttribute* a = FindOrCreateAttribute( name ); - a->SetAttribute( value ); - } + /** + Returns true if this document has a leading Byte Order Mark of UTF8. + */ + bool HasBOM() const { + return _writeBOM; + } + /** Sets whether to write the BOM when writing the file. + */ + void SetBOM(bool useBOM) { + _writeBOM = useBOM; + } - /** - Delete an attribute. - */ - void DeleteAttribute( const char* name ); + /** Return the root element of DOM. Equivalent to FirstChildElement(). + To get the first node, use FirstChild(). + */ + XMLElement* RootElement() { + return FirstChildElement(); + } + const XMLElement* RootElement() const { + return FirstChildElement(); + } - /// Return the first attribute in the list. - const XMLAttribute* FirstAttribute() const { - return _rootAttribute; - } - /// Query a specific attribute in the list. - const XMLAttribute* FindAttribute( const char* name ) const; - - /** Convenience function for easy access to the text inside an element. Although easy - and concise, GetText() is limited compared to getting the XMLText child - and accessing it directly. - - If the first child of 'this' is a XMLText, the GetText() - returns the character string of the Text node, else null is returned. - - This is a convenient method for getting the text of simple contained text: - @verbatim - This is text - const char* str = fooElement->GetText(); - @endverbatim - - 'str' will be a pointer to "This is text". - - Note that this function can be misleading. If the element foo was created from - this XML: - @verbatim - This is text - @endverbatim - - then the value of str would be null. The first child node isn't a text node, it is - another element. From this XML: - @verbatim - This is text - @endverbatim - GetText() will return "This is ". - */ - const char* GetText() const; - - /** Convenience function for easy access to the text inside an element. Although easy - and concise, SetText() is limited compared to creating an XMLText child - and mutating it directly. - - If the first child of 'this' is a XMLText, SetText() sets its value to - the given string, otherwise it will create a first child that is an XMLText. - - This is a convenient method for setting the text of simple contained text: - @verbatim - This is text - fooElement->SetText( "Hullaballoo!" ); - Hullaballoo! - @endverbatim - - Note that this function can be misleading. If the element foo was created from - this XML: - @verbatim - This is text - @endverbatim - - then it will not change "This is text", but rather prefix it with a text element: - @verbatim - Hullaballoo!This is text - @endverbatim - - For this XML: - @verbatim - - @endverbatim - SetText() will generate - @verbatim - Hullaballoo! - @endverbatim - */ - void SetText( const char* inText ); - /// Convenience method for setting text inside an element. See SetText() for important limitations. - void SetText( int value ); - /// Convenience method for setting text inside an element. See SetText() for important limitations. - void SetText( unsigned value ); - /// Convenience method for setting text inside an element. See SetText() for important limitations. - void SetText(int64_t value); - /// Convenience method for setting text inside an element. See SetText() for important limitations. - void SetText(uint64_t value); - /// Convenience method for setting text inside an element. See SetText() for important limitations. - void SetText( bool value ); - /// Convenience method for setting text inside an element. See SetText() for important limitations. - void SetText( double value ); - /// Convenience method for setting text inside an element. See SetText() for important limitations. - void SetText( float value ); + /** Print the Document. If the Printer is not provided, it will + print to stdout. If you provide Printer, this can print to a file: + @verbatim + XMLPrinter printer( fp ); + doc.Print( &printer ); + @endverbatim + + Or you can use a printer to print to memory: + @verbatim + XMLPrinter printer; + doc.Print( &printer ); + // printer.CStr() has a const char* to the XML + @endverbatim + */ + void Print(XMLPrinter* streamer = 0) const; + virtual bool Accept(XMLVisitor* visitor) const; + + /** + Create a new Element associated with + this Document. The memory for the Element + is managed by the Document. + */ + XMLElement* NewElement(const char* name); + /** + Create a new Comment associated with + this Document. The memory for the Comment + is managed by the Document. + */ + XMLComment* NewComment(const char* comment); + /** + Create a new Text associated with + this Document. The memory for the Text + is managed by the Document. + */ + XMLText* NewText(const char* text); + /** + Create a new Declaration associated with + this Document. The memory for the object + is managed by the Document. + + If the 'text' param is null, the standard + declaration is used.: + @verbatim + + @endverbatim + */ + XMLDeclaration* NewDeclaration(const char* text = 0); + /** + Create a new Unknown associated with + this Document. The memory for the object + is managed by the Document. + */ + XMLUnknown* NewUnknown(const char* text); + + /** + Delete a node associated with this document. + It will be unlinked from the DOM. + */ + void DeleteNode(XMLNode* node); + + /// Clears the error flags. + void ClearError(); + + /// Return true if there was an error parsing the document. + bool Error() const { + return _errorID != XML_SUCCESS; + } + /// Return the errorID. + XMLError ErrorID() const { + return _errorID; + } + const char* ErrorName() const; + static const char* ErrorIDToName(XMLError errorID); - /** - Convenience method to query the value of a child text node. This is probably best - shown by example. Given you have a document is this form: - @verbatim - - 1 - 1.4 - - @endverbatim - - The QueryIntText() and similar functions provide a safe and easier way to get to the - "value" of x and y. - - @verbatim - int x = 0; - float y = 0; // types of x and y are contrived for example - const XMLElement* xElement = pointElement->FirstChildElement( "x" ); - const XMLElement* yElement = pointElement->FirstChildElement( "y" ); - xElement->QueryIntText( &x ); - yElement->QueryFloatText( &y ); - @endverbatim - - @returns XML_SUCCESS (0) on success, XML_CAN_NOT_CONVERT_TEXT if the text cannot be converted - to the requested type, and XML_NO_TEXT_NODE if there is no child text to query. + /** Returns a "long form" error description. A hopefully helpful + diagnostic with location, line number, and/or additional info. + */ + const char* ErrorStr() const; - */ - XMLError QueryIntText( int* ival ) const; - /// See QueryIntText() - XMLError QueryUnsignedText( unsigned* uval ) const; - /// See QueryIntText() - XMLError QueryInt64Text(int64_t* uval) const; - /// See QueryIntText() - XMLError QueryUnsigned64Text(uint64_t* uval) const; - /// See QueryIntText() - XMLError QueryBoolText( bool* bval ) const; - /// See QueryIntText() - XMLError QueryDoubleText( double* dval ) const; - /// See QueryIntText() - XMLError QueryFloatText( float* fval ) const; - - int IntText(int defaultValue = 0) const; - - /// See QueryIntText() - unsigned UnsignedText(unsigned defaultValue = 0) const; - /// See QueryIntText() - int64_t Int64Text(int64_t defaultValue = 0) const; - /// See QueryIntText() - uint64_t Unsigned64Text(uint64_t defaultValue = 0) const; - /// See QueryIntText() - bool BoolText(bool defaultValue = false) const; - /// See QueryIntText() - double DoubleText(double defaultValue = 0) const; - /// See QueryIntText() - float FloatText(float defaultValue = 0) const; + /// A (trivial) utility function that prints the ErrorStr() to stdout. + void PrintError() const; - /** - Convenience method to create a new XMLElement and add it as last (right) - child of this node. Returns the created and inserted element. - */ - XMLElement* InsertNewChildElement(const char* name); - /// See InsertNewChildElement() - XMLComment* InsertNewComment(const char* comment); - /// See InsertNewChildElement() - XMLText* InsertNewText(const char* text); - /// See InsertNewChildElement() - XMLDeclaration* InsertNewDeclaration(const char* text); - /// See InsertNewChildElement() - XMLUnknown* InsertNewUnknown(const char* text); - - - // internal: - enum ElementClosingType { - OPENED, // - CLOSED, // - CLOSING // - }; - ElementClosingType ClosingType() const { - return _closingType; - } - virtual XMLNode* ShallowClone( XMLDocument* document ) const; - virtual bool ShallowEqual( const XMLNode* compare ) const; - -protected: - char* ParseDeep( char* p, StrPair* parentEndTag, int* curLineNumPtr ); - -private: - XMLElement( XMLDocument* doc ); - virtual ~XMLElement(); - XMLElement( const XMLElement& ); // not supported - void operator=( const XMLElement& ); // not supported - - XMLAttribute* FindOrCreateAttribute( const char* name ); - char* ParseAttributes( char* p, int* curLineNumPtr ); - static void DeleteAttribute( XMLAttribute* attribute ); - XMLAttribute* CreateAttribute(); - - enum { BUF_SIZE = 200 }; - ElementClosingType _closingType; - // The attribute list is ordered; there is no 'lastAttribute' - // because the list needs to be scanned for dupes before adding - // a new attribute. - XMLAttribute* _rootAttribute; -}; - - -enum Whitespace { - PRESERVE_WHITESPACE, - COLLAPSE_WHITESPACE -}; - - -/** A Document binds together all the functionality. - It can be saved, loaded, and printed to the screen. - All Nodes are connected and allocated to a Document. - If the Document is deleted, all its Nodes are also deleted. -*/ -class TINYXML2_LIB XMLDocument : public XMLNode -{ - friend class XMLElement; - // Gives access to SetError and Push/PopDepth, but over-access for everything else. - // Wishing C++ had "internal" scope. - friend class XMLNode; - friend class XMLText; - friend class XMLComment; - friend class XMLDeclaration; - friend class XMLUnknown; -public: - /// constructor - XMLDocument( bool processEntities = true, Whitespace whitespaceMode = PRESERVE_WHITESPACE ); - ~XMLDocument(); - - virtual XMLDocument* ToDocument() { - TIXMLASSERT( this == _document ); - return this; - } - virtual const XMLDocument* ToDocument() const { - TIXMLASSERT( this == _document ); - return this; - } + /// Return the line where the error occurred, or zero if unknown. + int ErrorLineNum() const + { + return _errorLineNum; + } - /** - Parse an XML file from a character string. - Returns XML_SUCCESS (0) on success, or - an errorID. - - You may optionally pass in the 'nBytes', which is - the number of bytes which will be parsed. If not - specified, TinyXML-2 will assume 'xml' points to a - null terminated string. - */ - XMLError Parse( const char* xml, size_t nBytes=static_cast(-1) ); + /// Clear the document, resetting it to the initial state. + void Clear(); - /** - Load an XML file from disk. - Returns XML_SUCCESS (0) on success, or - an errorID. - */ - XMLError LoadFile( const char* filename ); + /** + Copies this document to a target document. + The target will be completely cleared before the copy. + If you want to copy a sub-tree, see XMLNode::DeepClone(). - /** - Load an XML file from disk. You are responsible - for providing and closing the FILE*. + NOTE: that the 'target' must be non-null. + */ + void DeepCopy(XMLDocument* target) const; - NOTE: The file should be opened as binary ("rb") - not text in order for TinyXML-2 to correctly - do newline normalization. + // internal + char* Identify(char* p, XMLNode** node); - Returns XML_SUCCESS (0) on success, or - an errorID. - */ - XMLError LoadFile( FILE* ); + // internal + void MarkInUse(const XMLNode* const); - /** - Save the XML file to disk. - Returns XML_SUCCESS (0) on success, or - an errorID. - */ - XMLError SaveFile( const char* filename, bool compact = false ); + virtual XMLNode* ShallowClone(XMLDocument* /*document*/) const { + return 0; + } + virtual bool ShallowEqual(const XMLNode* /*compare*/) const { + return false; + } - /** - Save the XML file to disk. You are responsible - for providing and closing the FILE*. + private: + XMLDocument(const XMLDocument&); // not supported + void operator=(const XMLDocument&); // not supported + + bool _writeBOM; + bool _processEntities; + XMLError _errorID; + Whitespace _whitespaceMode; + mutable StrPair _errorStr; + int _errorLineNum; + char* _charBuffer; + int _parseCurLineNum; + int _parsingDepth; + // Memory tracking does add some overhead. + // However, the code assumes that you don't + // have a bunch of unlinked nodes around. + // Therefore it takes less memory to track + // in the document vs. a linked list in the XMLNode, + // and the performance is the same. + DynArray _unlinked; + + MemPoolT< sizeof(XMLElement) > _elementPool; + MemPoolT< sizeof(XMLAttribute) > _attributePool; + MemPoolT< sizeof(XMLText) > _textPool; + MemPoolT< sizeof(XMLComment) > _commentPool; + + static const char* _errorNames[XML_ERROR_COUNT]; + + void Parse(); + + void SetError(XMLError error, int lineNum, const char* format, ...); + + // Something of an obvious security hole, once it was discovered. + // Either an ill-formed XML or an excessively deep one can overflow + // the stack. Track stack depth, and error out if needed. + class DepthTracker { + public: + explicit DepthTracker(XMLDocument* document) { + this->_document = document; + document->PushDepth(); + } + ~DepthTracker() { + _document->PopDepth(); + } + private: + XMLDocument* _document; + }; + void PushDepth(); + void PopDepth(); + + template + NodeType* CreateUnlinkedNode(MemPoolT& pool); + }; - Returns XML_SUCCESS (0) on success, or - an errorID. - */ - XMLError SaveFile( FILE* fp, bool compact = false ); + template + inline NodeType* XMLDocument::CreateUnlinkedNode(MemPoolT& pool) + { + TIXMLASSERT(sizeof(NodeType) == PoolElementSize); + TIXMLASSERT(sizeof(NodeType) == pool.ItemSize()); + NodeType* returnNode = new (pool.Alloc()) NodeType(this); + TIXMLASSERT(returnNode); + returnNode->_memPool = &pool; - bool ProcessEntities() const { - return _processEntities; - } - Whitespace WhitespaceMode() const { - return _whitespaceMode; + _unlinked.Push(returnNode); + return returnNode; } /** - Returns true if this document has a leading Byte Order Mark of UTF8. - */ - bool HasBOM() const { - return _writeBOM; - } - /** Sets whether to write the BOM when writing the file. - */ - void SetBOM( bool useBOM ) { - _writeBOM = useBOM; - } - - /** Return the root element of DOM. Equivalent to FirstChildElement(). - To get the first node, use FirstChild(). - */ - XMLElement* RootElement() { - return FirstChildElement(); - } - const XMLElement* RootElement() const { - return FirstChildElement(); - } - - /** Print the Document. If the Printer is not provided, it will - print to stdout. If you provide Printer, this can print to a file: - @verbatim - XMLPrinter printer( fp ); - doc.Print( &printer ); - @endverbatim - - Or you can use a printer to print to memory: - @verbatim - XMLPrinter printer; - doc.Print( &printer ); - // printer.CStr() has a const char* to the XML - @endverbatim + A XMLHandle is a class that wraps a node pointer with null checks; this is + an incredibly useful thing. Note that XMLHandle is not part of the TinyXML-2 + DOM structure. It is a separate utility class. + + Take an example: + @verbatim + + + + + + + @endverbatim + + Assuming you want the value of "attributeB" in the 2nd "Child" element, it's very + easy to write a *lot* of code that looks like: + + @verbatim + XMLElement* root = document.FirstChildElement( "Document" ); + if ( root ) + { + XMLElement* element = root->FirstChildElement( "Element" ); + if ( element ) + { + XMLElement* child = element->FirstChildElement( "Child" ); + if ( child ) + { + XMLElement* child2 = child->NextSiblingElement( "Child" ); + if ( child2 ) + { + // Finally do something useful. + @endverbatim + + And that doesn't even cover "else" cases. XMLHandle addresses the verbosity + of such code. A XMLHandle checks for null pointers so it is perfectly safe + and correct to use: + + @verbatim + XMLHandle docHandle( &document ); + XMLElement* child2 = docHandle.FirstChildElement( "Document" ).FirstChildElement( "Element" ).FirstChildElement().NextSiblingElement(); + if ( child2 ) + { + // do something useful + @endverbatim + + Which is MUCH more concise and useful. + + It is also safe to copy handles - internally they are nothing more than node pointers. + @verbatim + XMLHandle handleCopy = handle; + @endverbatim + + See also XMLConstHandle, which is the same as XMLHandle, but operates on const objects. */ - void Print( XMLPrinter* streamer=0 ) const; - virtual bool Accept( XMLVisitor* visitor ) const; + class TINYXML2_LIB XMLHandle + { + public: + /// Create a handle from any node (at any depth of the tree.) This can be a null pointer. + explicit XMLHandle(XMLNode* node) : _node(node) { + } + /// Create a handle from a node. + explicit XMLHandle(XMLNode& node) : _node(&node) { + } + /// Copy constructor + XMLHandle(const XMLHandle& ref) : _node(ref._node) { + } + /// Assignment + XMLHandle& operator=(const XMLHandle& ref) { + _node = ref._node; + return *this; + } - /** - Create a new Element associated with - this Document. The memory for the Element - is managed by the Document. - */ - XMLElement* NewElement( const char* name ); - /** - Create a new Comment associated with - this Document. The memory for the Comment - is managed by the Document. - */ - XMLComment* NewComment( const char* comment ); - /** - Create a new Text associated with - this Document. The memory for the Text - is managed by the Document. - */ - XMLText* NewText( const char* text ); - /** - Create a new Declaration associated with - this Document. The memory for the object - is managed by the Document. - - If the 'text' param is null, the standard - declaration is used.: - @verbatim - - @endverbatim - */ - XMLDeclaration* NewDeclaration( const char* text=0 ); - /** - Create a new Unknown associated with - this Document. The memory for the object - is managed by the Document. - */ - XMLUnknown* NewUnknown( const char* text ); + /// Get the first child of this handle. + XMLHandle FirstChild() { + return XMLHandle(_node ? _node->FirstChild() : 0); + } + /// Get the first child element of this handle. + XMLHandle FirstChildElement(const char* name = 0) { + return XMLHandle(_node ? _node->FirstChildElement(name) : 0); + } + /// Get the last child of this handle. + XMLHandle LastChild() { + return XMLHandle(_node ? _node->LastChild() : 0); + } + /// Get the last child element of this handle. + XMLHandle LastChildElement(const char* name = 0) { + return XMLHandle(_node ? _node->LastChildElement(name) : 0); + } + /// Get the previous sibling of this handle. + XMLHandle PreviousSibling() { + return XMLHandle(_node ? _node->PreviousSibling() : 0); + } + /// Get the previous sibling element of this handle. + XMLHandle PreviousSiblingElement(const char* name = 0) { + return XMLHandle(_node ? _node->PreviousSiblingElement(name) : 0); + } + /// Get the next sibling of this handle. + XMLHandle NextSibling() { + return XMLHandle(_node ? _node->NextSibling() : 0); + } + /// Get the next sibling element of this handle. + XMLHandle NextSiblingElement(const char* name = 0) { + return XMLHandle(_node ? _node->NextSiblingElement(name) : 0); + } - /** - Delete a node associated with this document. - It will be unlinked from the DOM. - */ - void DeleteNode( XMLNode* node ); + /// Safe cast to XMLNode. This can return null. + XMLNode* ToNode() { + return _node; + } + /// Safe cast to XMLElement. This can return null. + XMLElement* ToElement() { + return (_node ? _node->ToElement() : 0); + } + /// Safe cast to XMLText. This can return null. + XMLText* ToText() { + return (_node ? _node->ToText() : 0); + } + /// Safe cast to XMLUnknown. This can return null. + XMLUnknown* ToUnknown() { + return (_node ? _node->ToUnknown() : 0); + } + /// Safe cast to XMLDeclaration. This can return null. + XMLDeclaration* ToDeclaration() { + return (_node ? _node->ToDeclaration() : 0); + } - /// Clears the error flags. - void ClearError(); + private: + XMLNode* _node; + }; - /// Return true if there was an error parsing the document. - bool Error() const { - return _errorID != XML_SUCCESS; - } - /// Return the errorID. - XMLError ErrorID() const { - return _errorID; - } - const char* ErrorName() const; - static const char* ErrorIDToName(XMLError errorID); - /** Returns a "long form" error description. A hopefully helpful - diagnostic with location, line number, and/or additional info. + /** + A variant of the XMLHandle class for working with const XMLNodes and Documents. It is the + same in all regards, except for the 'const' qualifiers. See XMLHandle for API. */ - const char* ErrorStr() const; - - /// A (trivial) utility function that prints the ErrorStr() to stdout. - void PrintError() const; - - /// Return the line where the error occurred, or zero if unknown. - int ErrorLineNum() const + class TINYXML2_LIB XMLConstHandle { - return _errorLineNum; - } - - /// Clear the document, resetting it to the initial state. - void Clear(); - - /** - Copies this document to a target document. - The target will be completely cleared before the copy. - If you want to copy a sub-tree, see XMLNode::DeepClone(). - - NOTE: that the 'target' must be non-null. - */ - void DeepCopy(XMLDocument* target) const; - - // internal - char* Identify( char* p, XMLNode** node ); - - // internal - void MarkInUse(const XMLNode* const); - - virtual XMLNode* ShallowClone( XMLDocument* /*document*/ ) const { - return 0; - } - virtual bool ShallowEqual( const XMLNode* /*compare*/ ) const { - return false; - } - -private: - XMLDocument( const XMLDocument& ); // not supported - void operator=( const XMLDocument& ); // not supported - - bool _writeBOM; - bool _processEntities; - XMLError _errorID; - Whitespace _whitespaceMode; - mutable StrPair _errorStr; - int _errorLineNum; - char* _charBuffer; - int _parseCurLineNum; - int _parsingDepth; - // Memory tracking does add some overhead. - // However, the code assumes that you don't - // have a bunch of unlinked nodes around. - // Therefore it takes less memory to track - // in the document vs. a linked list in the XMLNode, - // and the performance is the same. - DynArray _unlinked; - - MemPoolT< sizeof(XMLElement) > _elementPool; - MemPoolT< sizeof(XMLAttribute) > _attributePool; - MemPoolT< sizeof(XMLText) > _textPool; - MemPoolT< sizeof(XMLComment) > _commentPool; - - static const char* _errorNames[XML_ERROR_COUNT]; - - void Parse(); - - void SetError( XMLError error, int lineNum, const char* format, ... ); - - // Something of an obvious security hole, once it was discovered. - // Either an ill-formed XML or an excessively deep one can overflow - // the stack. Track stack depth, and error out if needed. - class DepthTracker { - public: - explicit DepthTracker(XMLDocument * document) { - this->_document = document; - document->PushDepth(); - } - ~DepthTracker() { - _document->PopDepth(); - } - private: - XMLDocument * _document; - }; - void PushDepth(); - void PopDepth(); - - template - NodeType* CreateUnlinkedNode( MemPoolT& pool ); -}; - -template -inline NodeType* XMLDocument::CreateUnlinkedNode( MemPoolT& pool ) -{ - TIXMLASSERT( sizeof( NodeType ) == PoolElementSize ); - TIXMLASSERT( sizeof( NodeType ) == pool.ItemSize() ); - NodeType* returnNode = new (pool.Alloc()) NodeType( this ); - TIXMLASSERT( returnNode ); - returnNode->_memPool = &pool; - - _unlinked.Push(returnNode); - return returnNode; -} - -/** - A XMLHandle is a class that wraps a node pointer with null checks; this is - an incredibly useful thing. Note that XMLHandle is not part of the TinyXML-2 - DOM structure. It is a separate utility class. - - Take an example: - @verbatim - - - - - - - @endverbatim - - Assuming you want the value of "attributeB" in the 2nd "Child" element, it's very - easy to write a *lot* of code that looks like: - - @verbatim - XMLElement* root = document.FirstChildElement( "Document" ); - if ( root ) - { - XMLElement* element = root->FirstChildElement( "Element" ); - if ( element ) - { - XMLElement* child = element->FirstChildElement( "Child" ); - if ( child ) - { - XMLElement* child2 = child->NextSiblingElement( "Child" ); - if ( child2 ) - { - // Finally do something useful. - @endverbatim - - And that doesn't even cover "else" cases. XMLHandle addresses the verbosity - of such code. A XMLHandle checks for null pointers so it is perfectly safe - and correct to use: - - @verbatim - XMLHandle docHandle( &document ); - XMLElement* child2 = docHandle.FirstChildElement( "Document" ).FirstChildElement( "Element" ).FirstChildElement().NextSiblingElement(); - if ( child2 ) - { - // do something useful - @endverbatim - - Which is MUCH more concise and useful. - - It is also safe to copy handles - internally they are nothing more than node pointers. - @verbatim - XMLHandle handleCopy = handle; - @endverbatim - - See also XMLConstHandle, which is the same as XMLHandle, but operates on const objects. -*/ -class TINYXML2_LIB XMLHandle -{ -public: - /// Create a handle from any node (at any depth of the tree.) This can be a null pointer. - explicit XMLHandle( XMLNode* node ) : _node( node ) { - } - /// Create a handle from a node. - explicit XMLHandle( XMLNode& node ) : _node( &node ) { - } - /// Copy constructor - XMLHandle( const XMLHandle& ref ) : _node( ref._node ) { - } - /// Assignment - XMLHandle& operator=( const XMLHandle& ref ) { - _node = ref._node; - return *this; - } - - /// Get the first child of this handle. - XMLHandle FirstChild() { - return XMLHandle( _node ? _node->FirstChild() : 0 ); - } - /// Get the first child element of this handle. - XMLHandle FirstChildElement( const char* name = 0 ) { - return XMLHandle( _node ? _node->FirstChildElement( name ) : 0 ); - } - /// Get the last child of this handle. - XMLHandle LastChild() { - return XMLHandle( _node ? _node->LastChild() : 0 ); - } - /// Get the last child element of this handle. - XMLHandle LastChildElement( const char* name = 0 ) { - return XMLHandle( _node ? _node->LastChildElement( name ) : 0 ); - } - /// Get the previous sibling of this handle. - XMLHandle PreviousSibling() { - return XMLHandle( _node ? _node->PreviousSibling() : 0 ); - } - /// Get the previous sibling element of this handle. - XMLHandle PreviousSiblingElement( const char* name = 0 ) { - return XMLHandle( _node ? _node->PreviousSiblingElement( name ) : 0 ); - } - /// Get the next sibling of this handle. - XMLHandle NextSibling() { - return XMLHandle( _node ? _node->NextSibling() : 0 ); - } - /// Get the next sibling element of this handle. - XMLHandle NextSiblingElement( const char* name = 0 ) { - return XMLHandle( _node ? _node->NextSiblingElement( name ) : 0 ); - } - - /// Safe cast to XMLNode. This can return null. - XMLNode* ToNode() { - return _node; - } - /// Safe cast to XMLElement. This can return null. - XMLElement* ToElement() { - return ( _node ? _node->ToElement() : 0 ); - } - /// Safe cast to XMLText. This can return null. - XMLText* ToText() { - return ( _node ? _node->ToText() : 0 ); - } - /// Safe cast to XMLUnknown. This can return null. - XMLUnknown* ToUnknown() { - return ( _node ? _node->ToUnknown() : 0 ); - } - /// Safe cast to XMLDeclaration. This can return null. - XMLDeclaration* ToDeclaration() { - return ( _node ? _node->ToDeclaration() : 0 ); - } - -private: - XMLNode* _node; -}; - - -/** - A variant of the XMLHandle class for working with const XMLNodes and Documents. It is the - same in all regards, except for the 'const' qualifiers. See XMLHandle for API. -*/ -class TINYXML2_LIB XMLConstHandle -{ -public: - explicit XMLConstHandle( const XMLNode* node ) : _node( node ) { - } - explicit XMLConstHandle( const XMLNode& node ) : _node( &node ) { - } - XMLConstHandle( const XMLConstHandle& ref ) : _node( ref._node ) { - } - - XMLConstHandle& operator=( const XMLConstHandle& ref ) { - _node = ref._node; - return *this; - } - - const XMLConstHandle FirstChild() const { - return XMLConstHandle( _node ? _node->FirstChild() : 0 ); - } - const XMLConstHandle FirstChildElement( const char* name = 0 ) const { - return XMLConstHandle( _node ? _node->FirstChildElement( name ) : 0 ); - } - const XMLConstHandle LastChild() const { - return XMLConstHandle( _node ? _node->LastChild() : 0 ); - } - const XMLConstHandle LastChildElement( const char* name = 0 ) const { - return XMLConstHandle( _node ? _node->LastChildElement( name ) : 0 ); - } - const XMLConstHandle PreviousSibling() const { - return XMLConstHandle( _node ? _node->PreviousSibling() : 0 ); - } - const XMLConstHandle PreviousSiblingElement( const char* name = 0 ) const { - return XMLConstHandle( _node ? _node->PreviousSiblingElement( name ) : 0 ); - } - const XMLConstHandle NextSibling() const { - return XMLConstHandle( _node ? _node->NextSibling() : 0 ); - } - const XMLConstHandle NextSiblingElement( const char* name = 0 ) const { - return XMLConstHandle( _node ? _node->NextSiblingElement( name ) : 0 ); - } - - - const XMLNode* ToNode() const { - return _node; - } - const XMLElement* ToElement() const { - return ( _node ? _node->ToElement() : 0 ); - } - const XMLText* ToText() const { - return ( _node ? _node->ToText() : 0 ); - } - const XMLUnknown* ToUnknown() const { - return ( _node ? _node->ToUnknown() : 0 ); - } - const XMLDeclaration* ToDeclaration() const { - return ( _node ? _node->ToDeclaration() : 0 ); - } - -private: - const XMLNode* _node; -}; - - -/** - Printing functionality. The XMLPrinter gives you more - options than the XMLDocument::Print() method. - - It can: - -# Print to memory. - -# Print to a file you provide. - -# Print XML without a XMLDocument. - - Print to Memory - - @verbatim - XMLPrinter printer; - doc.Print( &printer ); - SomeFunction( printer.CStr() ); - @endverbatim - - Print to a File - - You provide the file pointer. - @verbatim - XMLPrinter printer( fp ); - doc.Print( &printer ); - @endverbatim - - Print without a XMLDocument + public: + explicit XMLConstHandle(const XMLNode* node) : _node(node) { + } + explicit XMLConstHandle(const XMLNode& node) : _node(&node) { + } + XMLConstHandle(const XMLConstHandle& ref) : _node(ref._node) { + } - When loading, an XML parser is very useful. However, sometimes - when saving, it just gets in the way. The code is often set up - for streaming, and constructing the DOM is just overhead. + XMLConstHandle& operator=(const XMLConstHandle& ref) { + _node = ref._node; + return *this; + } - The Printer supports the streaming case. The following code - prints out a trivially simple XML file without ever creating - an XML document. + const XMLConstHandle FirstChild() const { + return XMLConstHandle(_node ? _node->FirstChild() : 0); + } + const XMLConstHandle FirstChildElement(const char* name = 0) const { + return XMLConstHandle(_node ? _node->FirstChildElement(name) : 0); + } + const XMLConstHandle LastChild() const { + return XMLConstHandle(_node ? _node->LastChild() : 0); + } + const XMLConstHandle LastChildElement(const char* name = 0) const { + return XMLConstHandle(_node ? _node->LastChildElement(name) : 0); + } + const XMLConstHandle PreviousSibling() const { + return XMLConstHandle(_node ? _node->PreviousSibling() : 0); + } + const XMLConstHandle PreviousSiblingElement(const char* name = 0) const { + return XMLConstHandle(_node ? _node->PreviousSiblingElement(name) : 0); + } + const XMLConstHandle NextSibling() const { + return XMLConstHandle(_node ? _node->NextSibling() : 0); + } + const XMLConstHandle NextSiblingElement(const char* name = 0) const { + return XMLConstHandle(_node ? _node->NextSiblingElement(name) : 0); + } - @verbatim - XMLPrinter printer( fp ); - printer.OpenElement( "foo" ); - printer.PushAttribute( "foo", "bar" ); - printer.CloseElement(); - @endverbatim -*/ -class TINYXML2_LIB XMLPrinter : public XMLVisitor -{ -public: - /** Construct the printer. If the FILE* is specified, - this will print to the FILE. Else it will print - to memory, and the result is available in CStr(). - If 'compact' is set to true, then output is created - with only required whitespace and newlines. - */ - XMLPrinter( FILE* file=0, bool compact = false, int depth = 0 ); - virtual ~XMLPrinter() {} - /** If streaming, write the BOM and declaration. */ - void PushHeader( bool writeBOM, bool writeDeclaration ); - /** If streaming, start writing an element. - The element must be closed with CloseElement() - */ - void OpenElement( const char* name, bool compactMode=false ); - /// If streaming, add an attribute to an open element. - void PushAttribute( const char* name, const char* value ); - void PushAttribute( const char* name, int value ); - void PushAttribute( const char* name, unsigned value ); - void PushAttribute( const char* name, int64_t value ); - void PushAttribute( const char* name, uint64_t value ); - void PushAttribute( const char* name, bool value ); - void PushAttribute( const char* name, double value ); - /// If streaming, close the Element. - virtual void CloseElement( bool compactMode=false ); - - /// Add a text node. - void PushText( const char* text, bool cdata=false ); - /// Add a text node from an integer. - void PushText( int value ); - /// Add a text node from an unsigned. - void PushText( unsigned value ); - /// Add a text node from a signed 64bit integer. - void PushText( int64_t value ); - /// Add a text node from an unsigned 64bit integer. - void PushText( uint64_t value ); - /// Add a text node from a bool. - void PushText( bool value ); - /// Add a text node from a float. - void PushText( float value ); - /// Add a text node from a double. - void PushText( double value ); - - /// Add a comment - void PushComment( const char* comment ); - - void PushDeclaration( const char* value ); - void PushUnknown( const char* value ); - - virtual bool VisitEnter( const XMLDocument& /*doc*/ ); - virtual bool VisitExit( const XMLDocument& /*doc*/ ) { - return true; - } + const XMLNode* ToNode() const { + return _node; + } + const XMLElement* ToElement() const { + return (_node ? _node->ToElement() : 0); + } + const XMLText* ToText() const { + return (_node ? _node->ToText() : 0); + } + const XMLUnknown* ToUnknown() const { + return (_node ? _node->ToUnknown() : 0); + } + const XMLDeclaration* ToDeclaration() const { + return (_node ? _node->ToDeclaration() : 0); + } - virtual bool VisitEnter( const XMLElement& element, const XMLAttribute* attribute ); - virtual bool VisitExit( const XMLElement& element ); + private: + const XMLNode* _node; + }; - virtual bool Visit( const XMLText& text ); - virtual bool Visit( const XMLComment& comment ); - virtual bool Visit( const XMLDeclaration& declaration ); - virtual bool Visit( const XMLUnknown& unknown ); /** - If in print to memory mode, return a pointer to - the XML file in memory. + Printing functionality. The XMLPrinter gives you more + options than the XMLDocument::Print() method. + + It can: + -# Print to memory. + -# Print to a file you provide. + -# Print XML without a XMLDocument. + + Print to Memory + + @verbatim + XMLPrinter printer; + doc.Print( &printer ); + SomeFunction( printer.CStr() ); + @endverbatim + + Print to a File + + You provide the file pointer. + @verbatim + XMLPrinter printer( fp ); + doc.Print( &printer ); + @endverbatim + + Print without a XMLDocument + + When loading, an XML parser is very useful. However, sometimes + when saving, it just gets in the way. The code is often set up + for streaming, and constructing the DOM is just overhead. + + The Printer supports the streaming case. The following code + prints out a trivially simple XML file without ever creating + an XML document. + + @verbatim + XMLPrinter printer( fp ); + printer.OpenElement( "foo" ); + printer.PushAttribute( "foo", "bar" ); + printer.CloseElement(); + @endverbatim */ - const char* CStr() const { - return _buffer.Mem(); - } - /** - If in print to memory mode, return the size - of the XML file in memory. (Note the size returned - includes the terminating null.) - */ - int CStrSize() const { - return _buffer.Size(); - } - /** - If in print to memory mode, reset the buffer to the - beginning. - */ - void ClearBuffer( bool resetToFirstElement = true ) { - _buffer.Clear(); - _buffer.Push(0); - _firstElement = resetToFirstElement; - } - -protected: - virtual bool CompactMode( const XMLElement& ) { return _compactMode; } + class TINYXML2_LIB XMLPrinter : public XMLVisitor + { + public: + /** Construct the printer. If the FILE* is specified, + this will print to the FILE. Else it will print + to memory, and the result is available in CStr(). + If 'compact' is set to true, then output is created + with only required whitespace and newlines. + */ + XMLPrinter(FILE* file = 0, bool compact = false, int depth = 0); + virtual ~XMLPrinter() {} + + /** If streaming, write the BOM and declaration. */ + void PushHeader(bool writeBOM, bool writeDeclaration); + /** If streaming, start writing an element. + The element must be closed with CloseElement() + */ + void OpenElement(const char* name, bool compactMode = false); + /// If streaming, add an attribute to an open element. + void PushAttribute(const char* name, const char* value); + void PushAttribute(const char* name, int value); + void PushAttribute(const char* name, unsigned value); + void PushAttribute(const char* name, int64_t value); + void PushAttribute(const char* name, uint64_t value); + void PushAttribute(const char* name, bool value); + void PushAttribute(const char* name, double value); + /// If streaming, close the Element. + virtual void CloseElement(bool compactMode = false); + + /// Add a text node. + void PushText(const char* text, bool cdata = false); + /// Add a text node from an integer. + void PushText(int value); + /// Add a text node from an unsigned. + void PushText(unsigned value); + /// Add a text node from a signed 64bit integer. + void PushText(int64_t value); + /// Add a text node from an unsigned 64bit integer. + void PushText(uint64_t value); + /// Add a text node from a bool. + void PushText(bool value); + /// Add a text node from a float. + void PushText(float value); + /// Add a text node from a double. + void PushText(double value); + + /// Add a comment + void PushComment(const char* comment); + + void PushDeclaration(const char* value); + void PushUnknown(const char* value); + + virtual bool VisitEnter(const XMLDocument& /*doc*/); + virtual bool VisitExit(const XMLDocument& /*doc*/) { + return true; + } - /** Prints out the space before an element. You may override to change - the space and tabs used. A PrintSpace() override should call Print(). - */ - virtual void PrintSpace( int depth ); - virtual void Print( const char* format, ... ); - virtual void Write( const char* data, size_t size ); - virtual void Putc( char ch ); + virtual bool VisitEnter(const XMLElement& element, const XMLAttribute* attribute); + virtual bool VisitExit(const XMLElement& element); - inline void Write(const char* data) { Write(data, strlen(data)); } + virtual bool Visit(const XMLText& text); + virtual bool Visit(const XMLComment& comment); + virtual bool Visit(const XMLDeclaration& declaration); + virtual bool Visit(const XMLUnknown& unknown); - void SealElementIfJustOpened(); - bool _elementJustOpened; - DynArray< const char*, 10 > _stack; + /** + If in print to memory mode, return a pointer to + the XML file in memory. + */ + const char* CStr() const { + return _buffer.Mem(); + } + /** + If in print to memory mode, return the size + of the XML file in memory. (Note the size returned + includes the terminating null.) + */ + int CStrSize() const { + return _buffer.Size(); + } + /** + If in print to memory mode, reset the buffer to the + beginning. + */ + void ClearBuffer(bool resetToFirstElement = true) { + _buffer.Clear(); + _buffer.Push(0); + _firstElement = resetToFirstElement; + } -private: - /** - Prepares to write a new node. This includes sealing an element that was - just opened, and writing any whitespace necessary if not in compact mode. - */ - void PrepareForNewNode( bool compactMode ); - void PrintString( const char*, bool restrictedEntitySet ); // prints out, after detecting entities. - - bool _firstElement; - FILE* _fp; - int _depth; - int _textDepth; - bool _processEntities; - bool _compactMode; - - enum { - ENTITY_RANGE = 64, - BUF_SIZE = 200 + protected: + virtual bool CompactMode(const XMLElement&) { return _compactMode; } + + /** Prints out the space before an element. You may override to change + the space and tabs used. A PrintSpace() override should call Print(). + */ + virtual void PrintSpace(int depth); + virtual void Print(const char* format, ...); + virtual void Write(const char* data, size_t size); + virtual void Putc(char ch); + + inline void Write(const char* data) { Write(data, strlen(data)); } + + void SealElementIfJustOpened(); + bool _elementJustOpened; + DynArray< const char*, 10 > _stack; + + private: + /** + Prepares to write a new node. This includes sealing an element that was + just opened, and writing any whitespace necessary if not in compact mode. + */ + void PrepareForNewNode(bool compactMode); + void PrintString(const char*, bool restrictedEntitySet); // prints out, after detecting entities. + + bool _firstElement; + FILE* _fp; + int _depth; + int _textDepth; + bool _processEntities; + bool _compactMode; + + enum { + ENTITY_RANGE = 64, + BUF_SIZE = 200 + }; + bool _entityFlag[ENTITY_RANGE]; + bool _restrictedEntityFlag[ENTITY_RANGE]; + + DynArray< char, 20 > _buffer; + + // Prohibit cloning, intentionally not implemented + XMLPrinter(const XMLPrinter&); + XMLPrinter& operator=(const XMLPrinter&); }; - bool _entityFlag[ENTITY_RANGE]; - bool _restrictedEntityFlag[ENTITY_RANGE]; - - DynArray< char, 20 > _buffer; - - // Prohibit cloning, intentionally not implemented - XMLPrinter( const XMLPrinter& ); - XMLPrinter& operator=( const XMLPrinter& ); -}; } // tinyxml2 diff --git a/Cigarette/workthread.cpp b/Cigarette/workthread.cpp index 05669b21..72ff76b7 100644 --- a/Cigarette/workthread.cpp +++ b/Cigarette/workthread.cpp @@ -8,16 +8,16 @@ #include "exportData.h" #include -extern AlgJd alg_jd[NumberOfSupportedCameras]; //检测胶点的AI算法 +extern AlgJd alg_jd[NumberOfSupportedCameras]; //妫娴嬭兌鐐圭殑AI绠楁硶 extern ConfPath g_conf_path; -extern SysConf g_sys_conf; //系统配置参数 +extern SysConf g_sys_conf; //绯荤粺閰嶇疆鍙傛暟 extern DisplayLabelConf g_display_label_conf[NumberOfSupportedCameras]; -extern int rotationAngle[NumberOfSupportedCameras]; //图片旋转角度 +extern int rotationAngle[NumberOfSupportedCameras]; //鍥剧墖鏃嬭浆瑙掑害 extern bool isNeedRotate[NumberOfSupportedCameras]; -extern SyncQueue >* g_save_queue; //图片保存队列 -extern SyncQueue>* g_image_queue[NumberOfSupportedCameras]; //int表示一个目标拍了几张 +extern SyncQueue >* g_save_queue; //鍥剧墖淇濆瓨闃熷垪 +extern SyncQueue>* g_image_queue[NumberOfSupportedCameras]; //int琛ㄧず涓涓洰鏍囨媿浜嗗嚑寮 #ifdef __UDPSend extern SyncQueue<_UDPSendInfo>* UDP_Info_queue; #endif @@ -32,292 +32,294 @@ extern bool g_debug_mode; WorkThread::~WorkThread() { - stop(); - local_g_image_queue->put(std::make_pair(0, cv::Mat())); - quit(); - wait(); + stop(); + local_g_image_queue->put(std::make_pair(0, cv::Mat())); + quit(); + wait(); } void WorkThread::init(SyncQueue>* image_ptr, ASyncQueue* result_ptr, int classid, int Num) { - local_camera_number = Num; - local_classid = classid; - local_g_image_queue = image_ptr; - local_g_result_queue = result_ptr; - b_quit = false; - frame_total = 0; + local_camera_number = Num; + local_classid = classid; + local_g_image_queue = image_ptr; + local_g_result_queue = result_ptr; + b_quit = false; + frame_total = 0; } void WorkThread::start_work() { - start(HighestPriority); + start(HighestPriority); } void WorkThread::stop() { - b_quit = true; + b_quit = true; } void WorkThread::run() { - try{ - uint32_t result_index = 0; - while (!b_quit) { - {//不要删掉这个括号,用来定义锁的作用域 - std::lock_guard locker(g_sys_conf.lock); - local_SysConf.save = g_sys_conf.save; - local_SysConf.shoot[local_camera_number] = g_sys_conf.shoot[local_camera_number]; - local_SysConf.MisMatchAct = g_sys_conf.MisMatchAct; - local_SysConf.ConfThreshold = g_sys_conf.ConfThreshold;// - for (int i = 0; i < 3; i++)local_SysConf.no[local_camera_number][i] = g_sys_conf.no[local_camera_number][i]; + try { + uint32_t result_index = 0; + while (!b_quit) { + {//涓嶈鍒犳帀杩欎釜鎷彿锛岀敤鏉ュ畾涔夐攣鐨勪綔鐢ㄥ煙 + std::lock_guard locker(g_sys_conf.lock); + local_SysConf.save = g_sys_conf.save; + local_SysConf.shoot[local_camera_number] = g_sys_conf.shoot[local_camera_number]; + local_SysConf.MisMatchAct = g_sys_conf.MisMatchAct; + local_SysConf.ConfThreshold = g_sys_conf.ConfThreshold;// + for (int i = 0; i < 3; i++)local_SysConf.no[local_camera_number][i] = g_sys_conf.no[local_camera_number][i]; #ifdef DRAW_RECT - std::lock_guard locker2(g_display_label_conf[local_camera_number].lock); - local_DisplayLabelConf.leftButtonDownFlag = g_display_label_conf[local_camera_number].leftButtonDownFlag; - local_DisplayLabelConf.Flag[0] = g_display_label_conf[local_camera_number].Flag[0]; - local_DisplayLabelConf.Flag[1] = g_display_label_conf[local_camera_number].Flag[1]; - local_DisplayLabelConf.originalPoint = g_display_label_conf[local_camera_number].originalPoint; - local_DisplayLabelConf.processPoint = g_display_label_conf[local_camera_number].processPoint; - local_DisplayLabelConf.RectVet[0] = g_display_label_conf[local_camera_number].RectVet[0]; - local_DisplayLabelConf.RectVet[1] = g_display_label_conf[local_camera_number].RectVet[1]; + std::lock_guard locker2(g_display_label_conf[local_camera_number].lock); + local_DisplayLabelConf.leftButtonDownFlag = g_display_label_conf[local_camera_number].leftButtonDownFlag; + local_DisplayLabelConf.Flag[0] = g_display_label_conf[local_camera_number].Flag[0]; + local_DisplayLabelConf.Flag[1] = g_display_label_conf[local_camera_number].Flag[1]; + local_DisplayLabelConf.originalPoint = g_display_label_conf[local_camera_number].originalPoint; + local_DisplayLabelConf.processPoint = g_display_label_conf[local_camera_number].processPoint; + local_DisplayLabelConf.RectVet[0] = g_display_label_conf[local_camera_number].RectVet[0]; + local_DisplayLabelConf.RectVet[1] = g_display_label_conf[local_camera_number].RectVet[1]; #endif - } + } - QDateTime now_ts = QDateTime::currentDateTime(); - std::pair element; - local_g_image_queue->take(element); - int unit_count = element.first; - cv::Mat image = element.second; + QDateTime now_ts = QDateTime::currentDateTime(); + std::pair element; + local_g_image_queue->take(element); + int unit_count = element.first; + cv::Mat image = element.second; #ifdef __UDPSend - _UDPSendInfo UDPSendInfo; - UDPSendInfo.FrameID = info_frame; - UDPSendInfo.index = local_camera_number; + _UDPSendInfo UDPSendInfo; + UDPSendInfo.FrameID = info_frame; + UDPSendInfo.index = local_camera_number; #endif #ifdef __TCPSend - _TCPSendInfo TCPSendInfo; + _TCPSendInfo TCPSendInfo; #endif - if (!image.data) - { - continue; //图像为空,跳过 - } - if (image.channels() == 1) - { - cv::cvtColor(image, image, CV_BGR2RGB); //灰度图像转为彩色图像 - } - if (local_SysConf.shoot[local_camera_number] == unit_count) - { - std::vector vec_in; - int w = image.cols; - int h = image.rows / unit_count; - for (int index = 0; index < unit_count; index++) { - cv::Rect temp_Rect(0, h * index, w, h); - cv::Mat temp_image = image(temp_Rect).clone(); - if (isNeedRotate[local_camera_number]) { - if (rotationAngle[local_camera_number] != (cv::ROTATE_90_COUNTERCLOCKWISE + 1)) - { - cv::rotate(temp_image, temp_image, rotationAngle[local_camera_number]); - } - } - vec_in.push_back(temp_image.clone()); - } + if (!image.data) + { + continue; //鍥惧儚涓虹┖锛岃烦杩 + } + if (image.channels() == 1) + { + cv::cvtColor(image, image, CV_BGR2RGB); //鐏板害鍥惧儚杞负褰╄壊鍥惧儚 + } + if (local_SysConf.shoot[local_camera_number] == unit_count) + { + std::vector vec_in; + int w = image.cols; + int h = image.rows / unit_count; + for (int index = 0; index < unit_count; index++) { + cv::Rect temp_Rect(0, h * index, w, h); + cv::Mat temp_image = image(temp_Rect).clone(); + if (isNeedRotate[local_camera_number]) { + if (rotationAngle[local_camera_number] != (cv::ROTATE_90_COUNTERCLOCKWISE + 1)) + { + cv::rotate(temp_image, temp_image, rotationAngle[local_camera_number]); + } + } + vec_in.push_back(temp_image.clone()); + } - std::vector vec_out; - std::vector > > vec_results; - QDateTime ts_start = QDateTime::currentDateTime(); - if(unit_count == 1){ - std::vector > results; - cv::Mat imagein,imageout; - imagein = vec_in[0]; - alg_jd[local_camera_number].detect(imagein, imageout, results); - vec_out.push_back(imageout.clone()); - vec_results.push_back(results); - }else{ - alg_jd[local_camera_number].detect_batch(vec_in, vec_out, vec_results); - } - QDateTime ts_jd = QDateTime::currentDateTime(); - int time_process = ts_start.msecsTo(ts_jd); + std::vector vec_out; + std::vector > > vec_results; + QDateTime ts_start = QDateTime::currentDateTime(); + if (unit_count == 1) { + std::vector > results; + cv::Mat imagein, imageout; + imagein = vec_in[0]; + alg_jd[local_camera_number].detect(imagein, imageout, results); + vec_out.push_back(imageout.clone()); + vec_results.push_back(results); + } + else { + alg_jd[local_camera_number].detect_batch(vec_in, vec_out, vec_results); + } + QDateTime ts_jd = QDateTime::currentDateTime(); + int time_process = ts_start.msecsTo(ts_jd); #ifndef SYNC_CAMERA - emit display_timecost(local_camera_number, time_process); + emit display_timecost(local_camera_number, time_process); #endif #ifdef __UDPSend - UDPSendInfo.timecost = QString::number(time_process); + UDPSendInfo.timecost = QString::number(time_process); #endif - cv::Mat image1; - cv::Mat image2; + cv::Mat image1; + cv::Mat image2; - QString jd_no; - for (int index = 0; index < unit_count; index++) { - jd_no += QString::number(vec_results[index].size()) + ","; - } - jd_no.chop(1); + QString jd_no; + for (int index = 0; index < unit_count; index++) { + jd_no += QString::number(vec_results[index].size()) + ","; + } + jd_no.chop(1); #ifndef SYNC_CAMERA - emit display_jd_no(local_camera_number, jd_no); + emit display_jd_no(local_camera_number, jd_no); #endif #ifdef __UDPSend - UDPSendInfo.JD = jd_no; + UDPSendInfo.JD = jd_no; #endif - bool IsNG = false; - int ngReason = 0; - QMap ng_reason_maps; - ng_reason_maps[0] = "unknow"; - ng_reason_maps[1] = "less_than_setting"; - ng_reason_maps[2] = "too_diff_from_model"; - ng_reason_maps[3] = "out_of_setting_range"; - for(int index=0;indexput(std::make_pair(filename, m)); - - QString sendName = now_ts.toString("yyyy-MM-dd_HH-mm-ss_zzz_") + QString::number(local_camera_number + 1) + - "#" + "_" + QString::number(index + 1) + ".jpg"; + bool IsNG = false; + int ngReason = 0; + QMap ng_reason_maps; + ng_reason_maps[0] = "unknow"; + ng_reason_maps[1] = "less_than_setting"; + ng_reason_maps[2] = "too_diff_from_model"; + ng_reason_maps[3] = "out_of_setting_range"; + for (int index = 0; index < unit_count; index++) + { + if (vec_results[index].size() < local_SysConf.no[local_camera_number][index]) + { + IsNG |= true; + ngReason = 1; + } + //if (vec_results[index].size() != 1)IsNG |= true;//鍙嶅悜璁粌 + if (local_SysConf.ConfThreshold == 0) + { + IsNG = false; + ngReason = 0; + } + if (local_SysConf.save == 2)//涓夊紶鐓х墖鍒嗗埆瀛樺偍 + { + cv::Mat m = vec_in[index].clone(); + QString file_name = g_conf_path.save_pics_path + "/ALL/" + + now_ts.toString("yyyy-MM-dd") + "/" + + QString::number(local_camera_number + 1) + "/" + QString::number(index + 1) + "/" + + now_ts.toString("yyyy-MM-dd_HH-mm-ss_zzz_") + QString::number(local_camera_number + 1) + + "#" + "_" + QString::number(index + 1) + ".jpg"; + std::string filename = file_name.toLocal8Bit().constData(); + g_save_queue->put(std::make_pair(filename, m)); + + QString sendName = now_ts.toString("yyyy-MM-dd_HH-mm-ss_zzz_") + QString::number(local_camera_number + 1) + + "#" + "_" + QString::number(index + 1) + ".jpg"; #ifdef __TCPSend - TCPSendInfo.pics_name = sendName.toLocal8Bit().constData(); - TCP_Info_queue->put(TCPSendInfo); + TCPSendInfo.pics_name = sendName.toLocal8Bit().constData(); + TCP_Info_queue->put(TCPSendInfo); #endif - } - } + } + } - if (unit_count >= 2){ - image1 = vec_out[(result_index) % 2].clone(); + if (unit_count >= 2) { + image1 = vec_out[(result_index) % 2].clone(); #ifdef DRAW_RECT - IsNG|=CheckSelectRects(image1,vec_results,(result_index) % 2,local_DisplayLabelConf,0); - if (IsNG) { - ngReason = 2; - } + IsNG |= CheckSelectRects(image1, vec_results, (result_index) % 2, local_DisplayLabelConf, 0); + if (IsNG) { + ngReason = 2; + } #endif - }else { - image1 = vec_out[0].clone(); + } + else { + image1 = vec_out[0].clone(); #ifdef DRAW_RECT - IsNG|=CheckSelectRects(image1,vec_results,0,local_DisplayLabelConf,0); - if (IsNG) { - ngReason = 2; - } + IsNG |= CheckSelectRects(image1, vec_results, 0, local_DisplayLabelConf, 0); + if (IsNG) { + ngReason = 2; + } #endif - } + } #ifdef DRAW_RECT - DrawSelectRects(image1, local_DisplayLabelConf, 0); + DrawSelectRects(image1, local_DisplayLabelConf, 0); #endif - - if (unit_count >= 3) { - image2 = vec_out[2].clone(); + + if (unit_count >= 3) { + image2 = vec_out[2].clone(); #ifdef DRAW_RECT - DrawSelectRects(image2, local_DisplayLabelConf, 1); - IsNG|=CheckSelectRects(image1,vec_results,2,local_DisplayLabelConf,1); - if (IsNG) { - ngReason = 3; - } + DrawSelectRects(image2, local_DisplayLabelConf, 1); + IsNG |= CheckSelectRects(image1, vec_results, 2, local_DisplayLabelConf, 1); + if (IsNG) { + ngReason = 3; + } #endif - } - result_index++; + } + result_index++; - if (!IsNG) - { - if (!g_debug_mode) - { + if (!IsNG) + { + if (!g_debug_mode) + { #ifndef SYNC_CAMERA - emit event_ok(local_camera_number); + emit event_ok(local_camera_number); #endif - local_g_result_queue->put(true); - } - } - else - { - if (!g_debug_mode) - { + local_g_result_queue->put(true); + } + } + else + { + if (!g_debug_mode) + { #ifndef SYNC_CAMERA - emit event_ng(local_camera_number); + emit event_ng(local_camera_number); #endif - local_g_result_queue->put(false); - } - - if ((local_SysConf.save == 2) || (local_SysConf.save == 1)) - { - for(int index=0;indexput(std::make_pair(file_name.toLocal8Bit().constData(), m)); + local_g_result_queue->put(false); + } - m = vec_out[index].clone(); - file_name = g_conf_path.save_pics_path + "/ng_result/" + - now_ts.toString("yyyy-MM-dd") + "/" - + QString::number(local_camera_number + 1) + "/" + QString::number(index + 1) + "/" + - now_ts.toString("yyyy-MM-dd_HH-mm-ss_zzz_") + QString::number(local_camera_number + 1) + - "#" + "_" + QString::number(index + 1) + "_" + ng_reason_maps[ngReason] + - ".jpg"; - remotePath = "/image/ng_result/" + - now_ts.toString("yyyy-MM-dd_HH-mm-ss_zzz_") + QString::number(local_camera_number + 1) + - "#" + "_" + QString::number(index + 1) + "_" + ng_reason_maps[ngReason] + - ".jpg"; - //g_save_queue->put(std::make_pair(file_name.toStdString(), m)); - g_save_queue->put(std::make_pair(file_name.toLocal8Bit().constData(), m)); - } - } - } + if ((local_SysConf.save == 2) || (local_SysConf.save == 1)) + { + for (int index = 0; index < unit_count; index++) + { + cv::Mat m = vec_in[index].clone(); + QString file_name = g_conf_path.save_pics_path + "/ng/" + + now_ts.toString("yyyy-MM-dd") + "/" + + QString::number(local_camera_number + 1) + "/" + QString::number(index + 1) + "/" + + now_ts.toString("yyyy-MM-dd_HH-mm-ss_zzz_") + QString::number(local_camera_number + 1) + + "#" + "_" + QString::number(index + 1) + "_" + ng_reason_maps[ngReason] + + ".jpg"; + QString remotePath = "/image/ng/" + + now_ts.toString("yyyy-MM-dd_HH-mm-ss_zzz_") + QString::number(local_camera_number + 1) + + "#" + "_" + QString::number(index + 1) + "_" + ng_reason_maps[ngReason] + + ".jpg"; + g_save_queue->put(std::make_pair(file_name.toLocal8Bit().constData(), m)); + + m = vec_out[index].clone(); + file_name = g_conf_path.save_pics_path + "/ng_result/" + + now_ts.toString("yyyy-MM-dd") + "/" + + QString::number(local_camera_number + 1) + "/" + QString::number(index + 1) + "/" + + now_ts.toString("yyyy-MM-dd_HH-mm-ss_zzz_") + QString::number(local_camera_number + 1) + + "#" + "_" + QString::number(index + 1) + "_" + ng_reason_maps[ngReason] + + ".jpg"; + remotePath = "/image/ng_result/" + + now_ts.toString("yyyy-MM-dd_HH-mm-ss_zzz_") + QString::number(local_camera_number + 1) + + "#" + "_" + QString::number(index + 1) + "_" + ng_reason_maps[ngReason] + + ".jpg"; + //g_save_queue->put(std::make_pair(file_name.toStdString(), m)); + g_save_queue->put(std::make_pair(file_name.toLocal8Bit().constData(), m)); + } + } + } #ifndef SYNC_CAMERA - if (!g_debug_mode) - { - emit display_check_total(local_camera_number, ++frame_total); - //exportDataInfo.cameraTotal = frame_total; + if (!g_debug_mode) + { + emit display_check_total(local_camera_number, ++frame_total); + //exportDataInfo.cameraTotal = frame_total; - emit notify(local_camera_number, 0, image1); - if (unit_count >= 3) - emit notify(local_camera_number, 1, image2); - } + emit notify(local_camera_number, 0, image1); + if (unit_count >= 3) + emit notify(local_camera_number, 1, image2); + } #endif - } + } #ifndef SYNC_CAMERA - else - { - //保证不错位 - if (!g_debug_mode) - { - if (local_SysConf.MisMatchAct == 1)//as ng - emit event_ng(local_camera_number); - else if (local_SysConf.MisMatchAct == 0)//as ok - emit event_ok(local_camera_number); - emit display_check_total(local_camera_number, ++frame_total); - qDebug() << local_camera_number << "#camera# " << now_ts.toString("yyyy-MM-dd_HH-mm-ss_zzz_") << "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx " << unit_count; - } - } + else + { + //淇濊瘉涓嶉敊浣 + if (!g_debug_mode) + { + if (local_SysConf.MisMatchAct == 1)//as ng + emit event_ng(local_camera_number); + else if (local_SysConf.MisMatchAct == 0)//as ok + emit event_ok(local_camera_number); + emit display_check_total(local_camera_number, ++frame_total); + qDebug() << local_camera_number << "#camera# " << now_ts.toString("yyyy-MM-dd_HH-mm-ss_zzz_") << "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx " << unit_count; + } + } #endif #ifdef __UDPSend - UDP_Info_queue->put(UDPSendInfo); + UDP_Info_queue->put(UDPSendInfo); #endif - } - } - catch (cv::Exception& e) - { - const char* err_msg = e.what(); - std::cout << "exception caught: " << err_msg << std::endl; - } -} \ No newline at end of file + } + } + catch (cv::Exception& e) + { + const char* err_msg = e.what(); + std::cout << "exception caught: " << err_msg << std::endl; + } +} diff --git a/Cigarette/workthread.h b/Cigarette/workthread.h index 9ea95d9d..50f901b8 100644 --- a/Cigarette/workthread.h +++ b/Cigarette/workthread.h @@ -13,34 +13,34 @@ class WorkThread : public QThread Q_OBJECT #ifndef SYNC_CAMERA signals: - void notify(int Num,int Cnt,cv::Mat); - void display_timecost(int Num,int ms); - void display_check_total(int Num,long no); - void display_jd_no(int Num,QString jd_no); + void notify(int Num, int Cnt, cv::Mat); + void display_timecost(int Num, int ms); + void display_check_total(int Num, long no); + void display_jd_no(int Num, QString jd_no); - void event_ok(int Num); - void event_ng(int Num); + void event_ok(int Num); + void event_ng(int Num); #endif public: - WorkThread(QObject *parent = 0): QThread(parent) - { + WorkThread(QObject* parent = 0) : QThread(parent) + { - } - ~WorkThread(); - - void init(SyncQueue>* image_ptr,ASyncQueue *result_ptr, int classid, int Num); - void start_work(); - void stop(); + } + ~WorkThread(); + + void init(SyncQueue>* image_ptr, ASyncQueue* result_ptr, int classid, int Num); + void start_work(); + void stop(); protected: - void run(); + void run(); public: - int local_camera_number; - int local_classid; - SyncQueue>* local_g_image_queue; - ASyncQueue* local_g_result_queue; - bool b_quit; - long frame_total; - SysConf local_SysConf; - DisplayLabelConf local_DisplayLabelConf; + int local_camera_number; + int local_classid; + SyncQueue>* local_g_image_queue; + ASyncQueue* local_g_result_queue; + bool b_quit; + long frame_total; + SysConf local_SysConf; + DisplayLabelConf local_DisplayLabelConf; };