Compare commits

...

53 Commits

Author SHA1 Message Date
Jinhuan a8d4a359c4 更新一些mqtt文件 3 months ago
Jinhuan c10ad02d1a 调整文件布局,增加mqtt文件 3 months ago
Jinhuan cc8ce53abc 增加程序不能重复打开的功能 9 months ago
seiyu ca135833a0 将TCP连接的IP与Port改为可配置,修改TCP只传送全存的图片名。 10 months ago
seiyu b2cba2ee05 更新CryptoToolLib.lib 10 months ago
seiyu 096007f412 修复合成图片异常的问题 10 months ago
seiyu 1864c6cf04 较多变动主要是在于改变了编码,代码格式发生变化; 代码变动主要在syncworkthread.cpp,修复了相机断开后数据仍在变动的问题。 10 months ago
seiyu c7c63a3b2e 修复拍四张软件卡死的问题,修复conf.txt中不按顺序设置相机则balluff相机不能正常工作的问题 10 months ago
seiyu e376b84212 修改部分同步线程的内容,添加合成图片 10 months ago
Jeffrey_Li 2506ac806e 更新同步检测功能 10 months ago
Jeffrey_Li 03444ed917 尝试解决basler关不掉的问题 10 months ago
seiyu fc8f54c7d3 tcp传图片名 10 months ago
seiyu 215acc558b 修改巴鲁夫部分代码、删除产量统计部分代码等 1 year ago
seiyu 39f080cdca 完善ftp传文件功能 1 year ago
seiyu 3f6c64d10c 删除一些注释以及添加模拟win+tab按钮 1 year ago
Flamingo 4c319c9ae5 Modified to make uploading pic to remote works 1 year ago
seiyu 7d33939aa1 实现换班上传xml文件,传图片正在尝试使用InternetWriteFile编写,还未实现 1 year ago
Jeffrey_Li 2020f6a810 解决ftp传送问题 1 year ago
seiyu 92d931e56d 该版本可以上传xml文件以及图片到ftp服务器 1 year ago
seiyu 9e2355e2d5 目前数据类型基本完成修改,添加了QtFtp,但目前无法正常运行 1 year ago
Flamingo 6dffbbba19 Add feature to upload files to remote ftp server 1 year ago
seiyu 5aa4f78df5 目前已经可以正常保存数据到XML文件 1 year ago
seiyu d5303e4de1 完善了一下传输的数据类型以及添加XML节点函数,但目前读取数据存取数据有问题 1 year ago
Flamingo f565de07a8 Add demo to transfer file to remote and modify the name of NG images saved to local 1 year ago
seiyu ed9c76f165 进行部分代码更新以及修改传输数据功能 1 year ago
seiyu dfacffd891 修改部分中文路径读取文件异常的问题 1 year ago
seiyu a4a9b3f7e1 八相机多模型版 1 year ago
seiyu 79d7bb38c5 添加选择配置文件路径、选择图片保存路径功能(支持中文路径) 1 year ago
seiyu 9fc16465ed 增加选择配置文件路径、存图路径的功能;
修改清理图片功能,不再清除ng文件夹只清除ALL文件夹。
1 year ago
Chu Jun 805cdc855c 添加启动提示自动关闭、重启客户端弹出提示功能 1 year ago
seiyu 85d59b3ee9 修改产量统计功能的剔除率异常并增加ng率 1 year ago
seiyu 41fe0fff27 更新lib文件以及调整相机反馈时间 1 year ago
seiyu 637bbef357 修复连接PLC的问题 1 year ago
seiyu 96e94011c4 修改调试模式导致软件卡死的问题;
修改调试模式导致画面异常的问题。
1 year ago
Jeffrey_Li 6cc6ed3e76 优化测试图片时候的显示窗口,可以调节窗口大小 1 year ago
Jeffrey_Li 4728a58767 解决调试模式测试图片不能用的问题 1 year ago
Jeffrey_Li 3863c89610 更新CryptoToolLib.lib 1 year ago
seiyu f5be5614bf 解决客户端与远程端数据不统一的问题 1 year ago
Jeffrey_Li 1ba73b82f2 解决标框重叠无法识别的问题 1 year ago
seiyu b9d04918b9 对代码进行更新 1 year ago
18661908385 4323f75315 该版本修改了较多功能:
1.修改部分路径名;
2.修改选择模型路径功能;
3.修改报警功能;
4.修改换班功能;
5.修改调试功能;
6.修改画框功能。
1 year ago
Jeffrey_Li 1e9c49ec92 上传上海主机厂一部分测试代码 1 year ago
Jeffrey_Li 088f6fb1a0 默认关闭__DEBUG 1 year ago
Jeffrey_Li b6f0e95103 默认关闭__DEBUG 1 year ago
Jeffrey_Li 20165d19d2 修改一下默认路径 1 year ago
Jeffrey_Li a6da5c3b77 有几个参数名字重复,修改一下 1 year ago
Jeffrey_Li 228e781876 fix build error 1 year ago
Jeffrey_Li 8720cce3d4 打开__DEBUG宏后会在系统配置页面显示测试图片按钮方便测试 1 year ago
Flamingo fc94eea6ae 去掉测试代码 1 year ago
Flamingo fc3e8de896 添加检测数据导出为XML,读取XML文件统计平均值的功能输出到产量统计的功能 1 year ago
CJ980606 aa9e765f26 补传文件 1 year ago
18661908385 e9233bd88c 修改加密软件相关文件 1 year ago
Jeffrey_Li 521d4d8c2f 解决编译报错 1 year ago

@ -0,0 +1,68 @@
{
"files.associations": {
"string": "cpp",
"array": "cpp",
"atomic": "cpp",
"bit": "cpp",
"*.tcc": "cpp",
"cctype": "cpp",
"chrono": "cpp",
"clocale": "cpp",
"cmath": "cpp",
"compare": "cpp",
"complex": "cpp",
"concepts": "cpp",
"condition_variable": "cpp",
"cstdarg": "cpp",
"cstddef": "cpp",
"cstdint": "cpp",
"cstdio": "cpp",
"cstdlib": "cpp",
"cstring": "cpp",
"ctime": "cpp",
"cwchar": "cpp",
"cwctype": "cpp",
"deque": "cpp",
"list": "cpp",
"map": "cpp",
"set": "cpp",
"unordered_map": "cpp",
"unordered_set": "cpp",
"vector": "cpp",
"exception": "cpp",
"algorithm": "cpp",
"functional": "cpp",
"iterator": "cpp",
"memory": "cpp",
"memory_resource": "cpp",
"numeric": "cpp",
"random": "cpp",
"ratio": "cpp",
"string_view": "cpp",
"system_error": "cpp",
"tuple": "cpp",
"type_traits": "cpp",
"utility": "cpp",
"fstream": "cpp",
"future": "cpp",
"initializer_list": "cpp",
"iomanip": "cpp",
"iosfwd": "cpp",
"iostream": "cpp",
"istream": "cpp",
"limits": "cpp",
"mutex": "cpp",
"new": "cpp",
"numbers": "cpp",
"ostream": "cpp",
"semaphore": "cpp",
"sstream": "cpp",
"stdexcept": "cpp",
"stop_token": "cpp",
"streambuf": "cpp",
"thread": "cpp",
"cinttypes": "cpp",
"typeindex": "cpp",
"typeinfo": "cpp"
}
}

@ -24,11 +24,9 @@ Global
{B12702AD-ABFB-343A-A199-8E24837244A3}.Release|x86.ActiveCfg = Release|Win32
{B12702AD-ABFB-343A-A199-8E24837244A3}.Release|x86.Build.0 = Release|Win32
{795A8611-044A-46D3-8DD9-13A338925BC4}.Debug|x64.ActiveCfg = Debug|x64
{795A8611-044A-46D3-8DD9-13A338925BC4}.Debug|x64.Build.0 = Debug|x64
{795A8611-044A-46D3-8DD9-13A338925BC4}.Debug|x86.ActiveCfg = Debug|x64
{795A8611-044A-46D3-8DD9-13A338925BC4}.Debug|x86.Build.0 = Debug|x64
{795A8611-044A-46D3-8DD9-13A338925BC4}.Release|x64.ActiveCfg = Release|x64
{795A8611-044A-46D3-8DD9-13A338925BC4}.Release|x64.Build.0 = Release|x64
{795A8611-044A-46D3-8DD9-13A338925BC4}.Release|x86.ActiveCfg = Release|x64
{795A8611-044A-46D3-8DD9-13A338925BC4}.Release|x86.Build.0 = Release|x64
EndGlobalSection

@ -0,0 +1,5 @@
/* This file was generated by qmake with the info from <root>/src/mqtt/mqtt.pro. */
#ifdef __cplusplus /* create empty PCH in C mode */
#include <QtCore/QtCore>
#include <QtNetwork/QtNetwork>
#endif

Binary file not shown.

Binary file not shown.

@ -1,3 +1,3 @@
#include "ASyncQueue.h"

@ -3,28 +3,28 @@
//#include<condition_variable>
#include<list>
#include<iostream>
using namespace std;
template<class T> 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<T> q;
int size;
int max_size;
mutex lock;
//condition_variable_any cv_full, cv_empty;
list<T> q;
int size;
int max_size;
};
using namespace std;
@ -42,40 +42,40 @@ ASyncQueue<T>::~ASyncQueue()
template<class T>
void ASyncQueue<T>::put(const T& val)
{
lock_guard<mutex> locker(lock);
q.emplace_back(val);
lock_guard<mutex> locker(lock);
q.emplace_back(val);
}
template<class T>
void ASyncQueue<T>::take(T& val)
{
lock_guard<mutex> locker(lock);
val = q.front();
q.pop_front();
lock_guard<mutex> locker(lock);
val = q.front();
q.pop_front();
}
template<class T>
void ASyncQueue<T>::clear()
{
lock_guard<mutex> locker(lock);
q.clear();
lock_guard<mutex> locker(lock);
q.clear();
}
template<class T>
bool ASyncQueue<T>::isEmpty()
{
return q.size() == 0;
return q.size() == 0;
}
template<class T>
bool ASyncQueue<T>::isFull()
{
return q.size() == max_size;
return q.size() == max_size;
}
template<class T>
int ASyncQueue<T>::count()
{
lock_guard<mutex> locker(lock);
return q.size();
}
lock_guard<mutex> locker(lock);
return q.size();
}

@ -1,12 +1,9 @@
#include "AlarmInfo.h"
AlarmInfo::AlarmInfo()
{
}
AlarmInfo::~AlarmInfo()
{
}

@ -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; //报警代码
};

@ -1,150 +0,0 @@
#include "CaptureThread.h"
#include "common.h"
extern bool g_debug_mode; //相机调试模式,调试模式必须暂停状态才能打开
//-----------------------------------------------------------------------------
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<cv::Mat>(Unit_Queue_Size);
}
CaptureThread::~CaptureThread()
{
delete p_unit_queue;
}
//-----------------------------------------------------------------------------
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");
#ifdef IMM_PROCESS
pEventCtrl_.eventNotification.writeS("Off");
#else
pEventCtrl_.eventNotification.writeS("On");
#endif
#ifndef IMM_PROCESS
EventCallback eventCallback(&pEventCtrl_);
eventCallback.p_unit_queue_ = p_unit_queue;
eventCallback.p_image_queue_ = p_image_queue;
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;
//相机掉线回调
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 )
{
qDebug() << "'FunctionInterface.imageRequestSingle' returned with an unexpected result: " << QString::fromStdString( mvIMPACT::acquire::ImpactAcquireException::getErrorCodeAsString( result ) );
}
manuallyStartAcquisitionIfNeeded( pDev_, *pFI_ );
int cnt = 0;
// run thread loop
mvIMPACT::acquire::Statistics statistics( pDev_ );
mvIMPACT::acquire::Request* pRequest = 0;
mvIMPACT::acquire::Request* pPreviousRequest = nullptr;
const unsigned int timeout_ms = 200;
Ready = true;
while( !boTerminated_ )
{
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)
{
#ifdef IMM_PROCESS
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); //放入调试队列
}
cnt++;
// display some statistics
if (cnt % 100 == 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);
#endif
}
manuallyStopAcquisitionIfNeeded( pDev_, *pFI_ );
if( pRequest )
{
pRequest->unlock();
}
pFI_->imageRequestReset( 0, 0 );
}
catch( const ImpactAcquireException& e )
{
emit error( QString::fromStdString( e.getErrorCodeAsString() ) );
}
}
//-----------------------------------------------------------------------------
int CaptureThread::getPendingRequestNr( void )
//-----------------------------------------------------------------------------
{
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;
}

@ -1,241 +0,0 @@
//-----------------------------------------------------------------------------
#ifndef CaptureThreadH
#define CaptureThreadH CaptureThreadH
//-----------------------------------------------------------------------------
#include "balluffcamera.h"
#include <QThread>
#include <QMutex>
#include <QTimer>
#include <qdebug.h>
#include "SyncQueue.h"
#include "ASyncQueue.h"
#include "apps/Common/exampleHelper.h"
#include <apps/Common/qtIncludePrologue.h>
#include <apps/Common/qtIncludeEpilogue.h>
#include <opencv2/opencv.hpp>
#include <common.h>
extern SingleCamInfoStruct SingleCamInfo[NumberOfSupportedCameras];
class CaptureThread_Func
{
public:
Device* m_pMVCamera;
ASyncQueue<bool> *p_result_queue_;
ASyncQueue<bool> *p_double_queue_;
void SendFeedBack(int OpID)
{
bool send_ng=false;
bool send_ok=false;
if(OpID == EdgeEvent)
{
#if defined DOUBLE_FEED_BACK
if(p_double_queue_->count() > 0)
{
bool temp;
p_double_queue_->take(temp);
send_ng=true;
}
#endif
}
if (p_result_queue_->count() > 0)
{
bool result;
p_result_queue_->take(result);
if (!result)
{
#if defined DOUBLE_FEED_BACK
p_double_queue_->put(true);
#endif
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 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 )
{
boTerminated_ = true;
}
int getPendingRequestNr();
signals:
void error( QString err );
void finished( void );
void requestReady( void );
void updateStatistics( const QString& data ,int Num);
private slots:
void process( void );
public:
int Local_Num;
SyncQueue<std::pair<int, cv::Mat> > *p_image_queue;
ASyncQueue<cv::Mat> *p_unit_queue;
ASyncQueue<bool> *p_result_queue;
ASyncQueue<bool> *p_result_wait_queue;
ASyncQueue<bool> *p_double_queue;
ASyncQueue<bool> *p_shooted_queue;
SyncQueue<cv::Mat> *p_debug_queue;
bool Ready = false;
CaptureThread_Func m_threadFunc;
private:
Device* pDev_;
volatile bool boTerminated_;
int requestPendingForDisplay_;
FunctionInterface* pFI_;
QMutex lock_;
};
//=============================================================================
//================= Camera's property callback ================================
//=============================================================================
class EventCallback : public mvIMPACT::acquire::ComponentCallback
{
public:
ASyncQueue<cv::Mat> *p_unit_queue_;
SyncQueue<std::pair<int, cv::Mat> > *p_image_queue_;
ASyncQueue<bool> *p_result_wait_queue_;
ASyncQueue<bool> *p_shooted_queue_;
ASyncQueue<bool> *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<mvIMPACT::acquire::GenICam::EventControl*>(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);
}
#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);
}
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);
}
#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);
}
p_image_queue_->put(std::make_pair(unit_count, long_image));
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;
}
};
//-----------------------------------------------------------------------------
#endif // CaptureThreadH

@ -1,176 +0,0 @@
#include "CaptureThreadBasler.h"
#include <QtWidgets/QApplication>
#include "PLCDevice.h"
#include "common.h"
#include <qdebug.h>
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<cv::Mat>(Unit_Queue_Size);
Shoot_Num = shoot;
}
CaptureThreadBasler::~CaptureThreadBasler()
{
delete p_unit_queue;
}
//-----------------------------------------------------------------------------
void CaptureThreadBasler::process(void)
//-----------------------------------------------------------------------------
{
bool last_high = false;
bool last_result = false;
try
{
CSampleConfigurationEventHandler *CfgEvent=NULL;
CfgEvent = new CSampleConfigurationEventHandler;
CfgEvent->channel_ = Local_Num;
pDev_->RegisterConfiguration(CfgEvent, Pylon::RegistrationMode_Append, Pylon::Cleanup_None);
CSampleImageEventHandler ImageEvent;
ImageEvent.p_image_queue_ = p_image_queue;
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;
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.p_image_queue_ = p_image_queue;
BurstEvent.pDev__ = pDev_;
BurstEvent.pCaptureThreadBasler = this;
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);
}
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);
}
}
#else
/*Set here*/
if (pDev_->TriggerSelector.TrySetValue(Basler_UniversalCameraParams::TriggerSelector_FrameBurstStart))
{
DEBUG(" TriggerSelector_FrameBurstStart\n");
pDev_->TriggerMode.SetValue(Basler_UniversalCameraParams::TriggerMode_Off);
if(pDev_->EventSelector.TrySetValue(Basler_UniversalCameraParams::EventSelector_FrameBurstStart))
{
DEBUG(" EventSelector_FrameBurstStart\n");
pDev_->EventNotification.SetValue(Basler_UniversalCameraParams::EventNotification_Off);
}
}
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);
#else
pDev_->EventNotification.SetValue(Basler_UniversalCameraParams::EventNotification_On);
#endif
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);
#else
pDev_->EventNotification.SetValue(Basler_UniversalCameraParams::EventNotification_On);
#endif
#endif
const unsigned int timeout_ms = 200;
// This smart pointer will receive the grab result data.
Pylon::CGrabResultPtr ptrGrabResult;
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);
#if defined (IMM_FEED_BACK) || defined (CAP_FEED_BACK)
m_threadFunc.SendFeedBack(ImageCap);
#endif
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;
#endif
if (m_Timer) delete m_Timer;
pDev_->StopGrabbing();
pDev_->Close();
pDev_->GrabCameraEvents = false;
pDev_->DeregisterConfiguration(CfgEvent);
pDev_->DeregisterImageEventHandler(&ImageEvent);
#ifndef USB_BASLER_NEW_FW
pDev_->DeregisterCameraEventHandler(&BurstEvent, "EventFrameBurstStartData");
#endif
}
catch(const Pylon::GenericException& e)
{
emit error( QString::fromStdString( e.GetDescription()) );
std::cout << e.GetSourceLine()<<e.GetDescription() << std::endl;
pDev_->StopGrabbing();
}
}
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);
}
void CaptureThreadBasler::ioTimeout()
{
pDev_->UserOutputSelector.SetValue(Basler_UniversalCameraParams::UserOutputSelector_UserOutput1);
pDev_->UserOutputValue.SetValue(false);
pDev_->UserOutputSelector.SetValue(Basler_UniversalCameraParams::UserOutputSelector_UserOutput3);
pDev_->UserOutputValue.SetValue(false);
}

@ -1,301 +0,0 @@
#include "CaptureThreadHIK.h"
#include <QtWidgets/QApplication>
#include "PLCDevice.h"
#include "common.h"
#include <windows.h>
extern bool g_debug_mode; //相机调试模式,调试模式必须暂停状态才能打开
extern SingleCamInfoStruct SingleCamInfo[NumberOfSupportedCameras];
extern PLCDevice * m_PLCDevice;
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);
}
CaptureThreadHIKptr->p_image_queue->put(std::make_pair(unit_count, long_image));
CaptureThreadHIKptr->p_shooted_queue->put(true);
}
CaptureThreadHIKptr->p_unit_queue->clear();
}
catch(...){
std::cout << "FallingGpioEventfunction error" << std::endl;
}
}
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);
}
#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);
}
#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;
}
}
#define CaptureThreadHIK_init(a)\
void __stdcall LossCallBack##a(unsigned int pData, void* pUser){LossCallBackfunction(pData,pUser);}\
void __stdcall FallingGpioEvent##a(MV_EVENT_OUT_INFO* pEventInfo, void* pUser){FallingGpioEventfunction(pEventInfo,pUser);}\
void __stdcall RisingGpioEvent##a(MV_EVENT_OUT_INFO* pEventInfo, void* pUser){RisingGpioEventfunction(pEventInfo,pUser);}
#if defined(NumberOfSupportedCameras) && (NumberOfSupportedCameras>0)
CaptureThreadHIK_init(1)
#endif
#if defined(NumberOfSupportedCameras) && (NumberOfSupportedCameras>1)
CaptureThreadHIK_init(2)
#endif
#if defined(NumberOfSupportedCameras) && (NumberOfSupportedCameras>2)
CaptureThreadHIK_init(3)
#endif
#if defined(NumberOfSupportedCameras) && (NumberOfSupportedCameras>3)
CaptureThreadHIK_init(4)
#endif
#if defined(NumberOfSupportedCameras) && (NumberOfSupportedCameras>4)
CaptureThreadHIK_init(5)
#endif
#if defined(NumberOfSupportedCameras) && (NumberOfSupportedCameras>5)
CaptureThreadHIK_init(6)
#endif
#if defined(NumberOfSupportedCameras) && (NumberOfSupportedCameras>6)
CaptureThreadHIK_init(7)
#endif
#if defined(NumberOfSupportedCameras) && (NumberOfSupportedCameras>7)
CaptureThreadHIK_init(8)
#endif
void(*LossCallBack[NumberOfSupportedCameras])(unsigned int pData, void* pUser) = {
#if defined(NumberOfSupportedCameras) && (NumberOfSupportedCameras>0)
LossCallBack1
#endif
#if defined(NumberOfSupportedCameras) && (NumberOfSupportedCameras>1)
,LossCallBack2
#endif
#if defined(NumberOfSupportedCameras) && (NumberOfSupportedCameras>2)
,LossCallBack3
#endif
#if defined(NumberOfSupportedCameras) && (NumberOfSupportedCameras>3)
,LossCallBack4
#endif
#if defined(NumberOfSupportedCameras) && (NumberOfSupportedCameras>4)
,LossCallBack5
#endif
#if defined(NumberOfSupportedCameras) && (NumberOfSupportedCameras>5)
,LossCallBack6
#endif
#if defined(NumberOfSupportedCameras) && (NumberOfSupportedCameras>6)
,LossCallBack7
#endif
#if defined(NumberOfSupportedCameras) && (NumberOfSupportedCameras>7)
,LossCallBack8
#endif
};
void(*FallingGpioEvent[NumberOfSupportedCameras])(MV_EVENT_OUT_INFO* pEventInfo, void* pUser) = {
#if defined(NumberOfSupportedCameras) && (NumberOfSupportedCameras>0)
FallingGpioEvent1
#endif
#if defined(NumberOfSupportedCameras) && (NumberOfSupportedCameras>1)
,FallingGpioEvent2
#endif
#if defined(NumberOfSupportedCameras) && (NumberOfSupportedCameras>2)
,FallingGpioEvent3
#endif
#if defined(NumberOfSupportedCameras) && (NumberOfSupportedCameras>3)
,FallingGpioEvent4
#endif
#if defined(NumberOfSupportedCameras) && (NumberOfSupportedCameras>4)
,FallingGpioEvent5
#endif
#if defined(NumberOfSupportedCameras) && (NumberOfSupportedCameras>5)
,FallingGpioEvent6
#endif
#if defined(NumberOfSupportedCameras) && (NumberOfSupportedCameras>6)
,FallingGpioEvent7
#endif
#if defined(NumberOfSupportedCameras) && (NumberOfSupportedCameras>7)
,FallingGpioEvent8
#endif
};
void(*RisingGpioEvent[NumberOfSupportedCameras])(MV_EVENT_OUT_INFO* pEventInfo, void* pUser) = {
#if defined(NumberOfSupportedCameras) && (NumberOfSupportedCameras>0)
RisingGpioEvent1
#endif
#if defined(NumberOfSupportedCameras) && (NumberOfSupportedCameras>1)
,RisingGpioEvent2
#endif
#if defined(NumberOfSupportedCameras) && (NumberOfSupportedCameras>2)
,RisingGpioEvent3
#endif
#if defined(NumberOfSupportedCameras) && (NumberOfSupportedCameras>3)
,RisingGpioEvent4
#endif
#if defined(NumberOfSupportedCameras) && (NumberOfSupportedCameras>4)
,RisingGpioEvent5
#endif
#if defined(NumberOfSupportedCameras) && (NumberOfSupportedCameras>5)
,RisingGpioEvent6
#endif
#if defined(NumberOfSupportedCameras) && (NumberOfSupportedCameras>6)
,RisingGpioEvent7
#endif
#if defined(NumberOfSupportedCameras) && (NumberOfSupportedCameras>7)
,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);
}
//-----------------------------------------------------------------------------
CaptureThreadHIK::CaptureThreadHIK(void *camhandle, bool boTerminated,int Num) :
CamHandle( camhandle ), boTerminated_( boTerminated ),Local_Num(Num)
//-----------------------------------------------------------------------------
{
p_unit_queue = new ASyncQueue<cv::Mat>(Unit_Queue_Size);
g_pImage_buf = (unsigned char*)malloc(3000 * 3000 * 3);
}
CaptureThreadHIK::~CaptureThreadHIK()
{
delete p_unit_queue;
free(g_pImage_buf);
}
//-----------------------------------------------------------------------------
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;
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 ///不打开无反馈等
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, "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_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
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;
MV_CC_StartGrabbing(CamHandle);
Ready = true;
while(!boTerminated_)
{
nRet = MV_CC_GetOneFrameTimeout(CamHandle, g_pImage_buf, nDataSize, &stFrameInfo, 200);
if (MV_OK == nRet)
{
m_cntGrabbedImages++;
cv::Mat openCVImage(stFrameInfo.nHeight, stFrameInfo.nWidth, CV_8UC1, 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));
#else
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;
}
}
//-----------------------------------------------------------------------------

File diff suppressed because one or more lines are too long

File diff suppressed because it is too large Load Diff

@ -33,6 +33,18 @@
<Extensions>cpp;moc</Extensions>
<SourceControlFiles>False</SourceControlFiles>
</Filter>
<Filter Include="Header Files\Ui">
<UniqueIdentifier>{473883a5-266b-4c0a-97ce-c07ce50ee349}</UniqueIdentifier>
</Filter>
<Filter Include="Header Files\Thread">
<UniqueIdentifier>{081898e5-fc92-47a4-9de7-0317588c2c6c}</UniqueIdentifier>
</Filter>
<Filter Include="Source Files\Ui">
<UniqueIdentifier>{045acf89-3551-4318-a690-0f58eaf08f4d}</UniqueIdentifier>
</Filter>
<Filter Include="Source Files\Thread">
<UniqueIdentifier>{91e6e8fc-6df2-4732-839b-4f873694fc78}</UniqueIdentifier>
</Filter>
</ItemGroup>
<ItemGroup>
<ClCompile Include="main.cpp">
@ -41,33 +53,6 @@
<ClCompile Include="cigarette.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="GeneratedFiles\Debug\moc_cigarette.cpp">
<Filter>Generated Files\Debug</Filter>
</ClCompile>
<ClCompile Include="GeneratedFiles\Release\moc_cigarette.cpp">
<Filter>Generated Files\Release</Filter>
</ClCompile>
<ClCompile Include="GeneratedFiles\qrc_cigarette.cpp">
<Filter>Generated Files</Filter>
</ClCompile>
<ClCompile Include="dialogsetuppasswd.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="GeneratedFiles\Debug\moc_dialogsetuppasswd.cpp">
<Filter>Generated Files\Debug</Filter>
</ClCompile>
<ClCompile Include="GeneratedFiles\Release\moc_dialogsetuppasswd.cpp">
<Filter>Generated Files\Release</Filter>
</ClCompile>
<ClCompile Include="dialogsetup.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="GeneratedFiles\Debug\moc_dialogsetup.cpp">
<Filter>Generated Files\Debug</Filter>
</ClCompile>
<ClCompile Include="GeneratedFiles\Release\moc_dialogsetup.cpp">
<Filter>Generated Files\Release</Filter>
</ClCompile>
<ClCompile Include="basecamera.cpp">
<Filter>Source Files</Filter>
</ClCompile>
@ -80,274 +65,169 @@
<ClCompile Include="balluffcamera.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="plcsetup.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="GeneratedFiles\Debug\moc_plcsetup.cpp">
<Filter>Generated Files\Debug</Filter>
</ClCompile>
<ClCompile Include="GeneratedFiles\Release\moc_plcsetup.cpp">
<Filter>Generated Files\Release</Filter>
</ClCompile>
<ClCompile Include="CaptureThread.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="GeneratedFiles\Debug\moc_CaptureThread.cpp">
<Filter>Generated Files\Debug</Filter>
</ClCompile>
<ClCompile Include="GeneratedFiles\Release\moc_CaptureThread.cpp">
<Filter>Generated Files\Release</Filter>
</ClCompile>
<ClCompile Include="plc_item.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="db_label.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="GeneratedFiles\Debug\moc_db_label.cpp">
<Filter>Generated Files\Debug</Filter>
</ClCompile>
<ClCompile Include="GeneratedFiles\Release\moc_db_label.cpp">
<Filter>Generated Files\Release</Filter>
</ClCompile>
<ClCompile Include="alarmdialog.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="GeneratedFiles\Debug\moc_alarmdialog.cpp">
<Filter>Generated Files\Debug</Filter>
</ClCompile>
<ClCompile Include="GeneratedFiles\Release\moc_alarmdialog.cpp">
<Filter>Generated Files\Release</Filter>
</ClCompile>
<ClCompile Include="AlarmInfo.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="common.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="debugthread.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="GeneratedFiles\Debug\moc_debugthread.cpp">
<Filter>Generated Files\Debug</Filter>
</ClCompile>
<ClCompile Include="GeneratedFiles\Release\moc_debugthread.cpp">
<Filter>Generated Files\Release</Filter>
</ClCompile>
<ClCompile Include="dialogin.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="GeneratedFiles\Debug\moc_dialogin.cpp">
<Filter>Generated Files\Debug</Filter>
</ClCompile>
<ClCompile Include="GeneratedFiles\Release\moc_dialogin.cpp">
<Filter>Generated Files\Release</Filter>
</ClCompile>
<ClCompile Include="ASyncQueue.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="baslercamera.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="GeneratedFiles\Debug\moc_workthread.cpp">
<Filter>Generated Files\Debug</Filter>
</ClCompile>
<ClCompile Include="GeneratedFiles\Release\moc_workthread.cpp">
<Filter>Generated Files\Release</Filter>
</ClCompile>
<ClCompile Include="workthread.cpp">
<ClCompile Include="hikcamera.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="GeneratedFiles\Debug\moc_CaptureThreadBasler.cpp">
<Filter>Generated Files\Debug</Filter>
</ClCompile>
<ClCompile Include="GeneratedFiles\Release\moc_CaptureThreadBasler.cpp">
<Filter>Generated Files\Release</Filter>
</ClCompile>
<ClCompile Include="CaptureThreadBasler.cpp">
<ClCompile Include="PLC\PLCDevice.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="GeneratedFiles\Debug\moc_savethread.cpp">
<Filter>Generated Files\Debug</Filter>
</ClCompile>
<ClCompile Include="GeneratedFiles\Release\moc_savethread.cpp">
<Filter>Generated Files\Release</Filter>
</ClCompile>
<ClCompile Include="hikcamera.cpp">
<ClCompile Include="exportData.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="GeneratedFiles\Debug\moc_CaptureThreadHIK.cpp">
<Filter>Generated Files\Debug</Filter>
</ClCompile>
<ClCompile Include="GeneratedFiles\Release\moc_CaptureThreadHIK.cpp">
<Filter>Generated Files\Release</Filter>
</ClCompile>
<ClCompile Include="CaptureThreadHIK.cpp">
<ClCompile Include="tinyxml2.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="PLC\PLCDevice.cpp">
<Filter>Source Files</Filter>
<ClCompile Include="Thread\CaptureThread.cpp">
<Filter>Source Files\Thread</Filter>
</ClCompile>
<ClCompile Include="threadSend.cpp">
<Filter>Source Files</Filter>
<ClCompile Include="Thread\CaptureThreadBasler.cpp">
<Filter>Source Files\Thread</Filter>
</ClCompile>
<ClCompile Include="GeneratedFiles\Debug\moc_camera_glue.cpp">
<Filter>Generated Files\Debug</Filter>
<ClCompile Include="Thread\CaptureThreadHIK.cpp">
<Filter>Source Files\Thread</Filter>
</ClCompile>
<ClCompile Include="GeneratedFiles\Release\moc_camera_glue.cpp">
<Filter>Generated Files\Release</Filter>
<ClCompile Include="Thread\Cleanthread.cpp">
<Filter>Source Files\Thread</Filter>
</ClCompile>
<ClCompile Include="camera_glue.cpp">
<Filter>Source Files</Filter>
<ClCompile Include="Thread\debugthread.cpp">
<Filter>Source Files\Thread</Filter>
</ClCompile>
<ClCompile Include="GeneratedFiles\Debug\moc_change_shift.cpp">
<Filter>Generated Files\Debug</Filter>
<ClCompile Include="Thread\Logthread.cpp">
<Filter>Source Files\Thread</Filter>
</ClCompile>
<ClCompile Include="GeneratedFiles\Release\moc_change_shift.cpp">
<Filter>Generated Files\Release</Filter>
<ClCompile Include="Thread\syncworkthread.cpp">
<Filter>Source Files\Thread</Filter>
</ClCompile>
<ClCompile Include="change_shift.cpp">
<Filter>Source Files</Filter>
<ClCompile Include="Thread\threadReceive.cpp">
<Filter>Source Files\Thread</Filter>
</ClCompile>
<ClCompile Include="GeneratedFiles\Debug\moc_output_statistic.cpp">
<Filter>Generated Files\Debug</Filter>
<ClCompile Include="Thread\threadSend.cpp">
<Filter>Source Files\Thread</Filter>
</ClCompile>
<ClCompile Include="GeneratedFiles\Release\moc_output_statistic.cpp">
<Filter>Generated Files\Release</Filter>
<ClCompile Include="Thread\threadSendTCP.cpp">
<Filter>Source Files\Thread</Filter>
</ClCompile>
<ClCompile Include="output_statistic.cpp">
<Filter>Source Files</Filter>
<ClCompile Include="Thread\workthread.cpp">
<Filter>Source Files\Thread</Filter>
</ClCompile>
<ClCompile Include="GeneratedFiles\Debug\moc_Logthread.cpp">
<Filter>Generated Files\Debug</Filter>
<ClCompile Include="Ui\alarmdialog.cpp">
<Filter>Source Files\Ui</Filter>
</ClCompile>
<ClCompile Include="GeneratedFiles\Release\moc_Logthread.cpp">
<Filter>Generated Files\Release</Filter>
<ClCompile Include="Ui\camera_glue.cpp">
<Filter>Source Files\Ui</Filter>
</ClCompile>
<ClCompile Include="Logthread.cpp">
<Filter>Source Files</Filter>
<ClCompile Include="Ui\change_shift.cpp">
<Filter>Source Files\Ui</Filter>
</ClCompile>
<ClCompile Include="GeneratedFiles\Debug\moc_Cleanthread.cpp">
<Filter>Generated Files\Debug</Filter>
<ClCompile Include="Ui\dialogin.cpp">
<Filter>Source Files\Ui</Filter>
</ClCompile>
<ClCompile Include="GeneratedFiles\Release\moc_Cleanthread.cpp">
<Filter>Generated Files\Release</Filter>
<ClCompile Include="Ui\dialogsetup.cpp">
<Filter>Source Files\Ui</Filter>
</ClCompile>
<ClCompile Include="Cleanthread.cpp">
<Filter>Source Files</Filter>
<ClCompile Include="Ui\dialogsetuppasswd.cpp">
<Filter>Source Files\Ui</Filter>
</ClCompile>
<ClCompile Include="threadReceive.cpp">
<Filter>Source Files</Filter>
<ClCompile Include="Ui\output_statistic.cpp">
<Filter>Source Files\Ui</Filter>
</ClCompile>
<ClCompile Include="GeneratedFiles\Debug\moc_threadReceive.cpp">
<Filter>Generated Files\Debug</Filter>
<ClCompile Include="Ui\plcsetup.cpp">
<Filter>Source Files\Ui</Filter>
</ClCompile>
<ClCompile Include="GeneratedFiles\Release\moc_threadReceive.cpp">
<Filter>Generated Files\Release</Filter>
<ClCompile Include="Thread\threadSendMqtt.cpp">
<Filter>Source Files\Thread</Filter>
</ClCompile>
</ItemGroup>
<ItemGroup>
<CustomBuild Include="cigarette.h">
<QtMoc Include="cigarette.h">
<Filter>Header Files</Filter>
</CustomBuild>
<CustomBuild Include="cigarette.ui">
</QtMoc>
<QtUic Include="cigarette.ui">
<Filter>Form Files</Filter>
</CustomBuild>
<CustomBuild Include="cigarette.qrc">
</QtUic>
<QtRcc Include="cigarette.qrc">
<Filter>Resource Files</Filter>
</CustomBuild>
<CustomBuild Include="dialogsetuppasswd.hpp">
<Filter>Header Files</Filter>
</CustomBuild>
<CustomBuild Include="dialogsetuppasswd.ui">
<Filter>Form Files</Filter>
</CustomBuild>
<CustomBuild Include="dialogsetup.hpp">
<Filter>Header Files</Filter>
</CustomBuild>
<CustomBuild Include="dialogsetup.ui">
<Filter>Form Files</Filter>
</CustomBuild>
<CustomBuild Include="plcsetup.hpp">
<Filter>Header Files</Filter>
</CustomBuild>
<CustomBuild Include="plcsetup.ui">
<Filter>Form Files</Filter>
</CustomBuild>
<CustomBuild Include="CaptureThread.h">
<Filter>Header Files</Filter>
</CustomBuild>
<CustomBuild Include="db_label.h">
</QtRcc>
<QtMoc Include="db_label.h">
<Filter>Header Files</Filter>
</CustomBuild>
<CustomBuild Include="alarmdialog.hpp">
</QtMoc>
<QtMoc Include="exportData.h">
<Filter>Header Files</Filter>
</CustomBuild>
<CustomBuild Include="alarmdialog.ui">
<Filter>Form Files</Filter>
</CustomBuild>
<CustomBuild Include="debugthread.h">
<Filter>Header Files</Filter>
</CustomBuild>
<CustomBuild Include="dialogin.hpp">
<Filter>Header Files</Filter>
</CustomBuild>
<CustomBuild Include="dialogin.ui">
<Filter>Form Files</Filter>
</CustomBuild>
<CustomBuild Include="workthread.h">
<Filter>Header Files</Filter>
</CustomBuild>
<CustomBuild Include="CaptureThreadBasler.h">
<Filter>Header Files</Filter>
</CustomBuild>
<CustomBuild Include="savethread.h">
<Filter>Header Files</Filter>
</CustomBuild>
<CustomBuild Include="CaptureThreadHIK.h">
<Filter>Header Files</Filter>
</CustomBuild>
<CustomBuild Include="threadSend.h">
<Filter>Header Files</Filter>
</CustomBuild>
<CustomBuild Include="camera_glue.h">
<Filter>Header Files</Filter>
</CustomBuild>
<CustomBuild Include="camera_glue.ui">
<Filter>Form Files</Filter>
</CustomBuild>
<CustomBuild Include="change_shift.h">
<Filter>Header Files</Filter>
</CustomBuild>
<CustomBuild Include="change_shift.ui">
<Filter>Form Files</Filter>
</CustomBuild>
<CustomBuild Include="output_statistic.h">
<Filter>Header Files</Filter>
</CustomBuild>
<CustomBuild Include="output_statistic.ui">
<Filter>Form Files</Filter>
</CustomBuild>
<CustomBuild Include="Logthread.h">
<Filter>Header Files</Filter>
</CustomBuild>
<CustomBuild Include="Cleanthread.h">
<Filter>Header Files</Filter>
</CustomBuild>
<CustomBuild Include="threadReceive.h">
<Filter>Header Files</Filter>
</CustomBuild>
</QtMoc>
<QtMoc Include="Thread\CaptureThread.h">
<Filter>Header Files\Thread</Filter>
</QtMoc>
<QtMoc Include="Thread\CaptureThreadBasler.h">
<Filter>Header Files\Thread</Filter>
</QtMoc>
<QtMoc Include="Thread\CaptureThreadHIK.h">
<Filter>Header Files\Thread</Filter>
</QtMoc>
<QtMoc Include="Thread\Cleanthread.h">
<Filter>Header Files\Thread</Filter>
</QtMoc>
<QtMoc Include="Thread\debugthread.h">
<Filter>Header Files\Thread</Filter>
</QtMoc>
<QtMoc Include="Thread\Logthread.h">
<Filter>Header Files\Thread</Filter>
</QtMoc>
<QtMoc Include="Thread\savethread.h">
<Filter>Header Files\Thread</Filter>
</QtMoc>
<QtMoc Include="Thread\syncworkthread.h">
<Filter>Header Files\Thread</Filter>
</QtMoc>
<QtMoc Include="Thread\threadReceive.h">
<Filter>Header Files\Thread</Filter>
</QtMoc>
<QtMoc Include="Thread\workthread.h">
<Filter>Header Files\Thread</Filter>
</QtMoc>
<QtMoc Include="Ui\alarmdialog.hpp">
<Filter>Header Files\Ui</Filter>
</QtMoc>
<QtMoc Include="Ui\dialogin.hpp">
<Filter>Header Files\Ui</Filter>
</QtMoc>
<QtMoc Include="Ui\dialogsetup.hpp">
<Filter>Header Files\Ui</Filter>
</QtMoc>
<QtMoc Include="Ui\dialogsetuppasswd.hpp">
<Filter>Header Files\Ui</Filter>
</QtMoc>
<QtMoc Include="Ui\plcsetup.hpp">
<Filter>Header Files\Ui</Filter>
</QtMoc>
<QtMoc Include="Ui\camera_glue.h">
<Filter>Header Files\Ui</Filter>
</QtMoc>
<QtMoc Include="Ui\change_shift.h">
<Filter>Header Files\Ui</Filter>
</QtMoc>
<QtMoc Include="Ui\output_statistic.h">
<Filter>Header Files\Ui</Filter>
</QtMoc>
</ItemGroup>
<ItemGroup>
<ClInclude Include="GeneratedFiles\ui_cigarette.h">
<Filter>Generated Files</Filter>
</ClInclude>
<ClInclude Include="GeneratedFiles\ui_dialogsetuppasswd.h">
<Filter>Generated Files</Filter>
</ClInclude>
<ClInclude Include="GeneratedFiles\ui_dialogsetup.h">
<Filter>Generated Files</Filter>
</ClInclude>
<ClInclude Include="basecamera.h">
<Filter>Header Files</Filter>
</ClInclude>
@ -363,21 +243,12 @@
<ClInclude Include="common.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="GeneratedFiles\ui_plcsetup.h">
<Filter>Generated Files</Filter>
</ClInclude>
<ClInclude Include="plc_item.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="GeneratedFiles\ui_alarmdialog.h">
<Filter>Generated Files</Filter>
</ClInclude>
<ClInclude Include="AlarmInfo.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="GeneratedFiles\ui_dialogin.h">
<Filter>Generated Files</Filter>
</ClInclude>
<ClInclude Include="ASyncQueue.h">
<Filter>Header Files</Filter>
</ClInclude>
@ -390,14 +261,46 @@
<ClInclude Include="PLC\PLCDevice.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="GeneratedFiles\ui_camera_glue.h">
<Filter>Generated Files</Filter>
<ClInclude Include="tinyxml2.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="GeneratedFiles\ui_change_shift.h">
<Filter>Generated Files</Filter>
<ClInclude Include="FtpManager.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="GeneratedFiles\ui_output_statistic.h">
<Filter>Generated Files</Filter>
<ClInclude Include="Thread\threadSend.h">
<Filter>Header Files\Thread</Filter>
</ClInclude>
<ClInclude Include="Thread\threadSendTCP.h">
<Filter>Header Files\Thread</Filter>
</ClInclude>
<ClInclude Include="Thread\threadSendMqtt.h">
<Filter>Header Files\Thread</Filter>
</ClInclude>
</ItemGroup>
<ItemGroup>
<QtUic Include="Ui\alarmdialog.ui">
<Filter>Form Files</Filter>
</QtUic>
<QtUic Include="Ui\camera_glue.ui">
<Filter>Form Files</Filter>
</QtUic>
<QtUic Include="Ui\change_shift.ui">
<Filter>Form Files</Filter>
</QtUic>
<QtUic Include="Ui\dialogin.ui">
<Filter>Form Files</Filter>
</QtUic>
<QtUic Include="Ui\dialogsetup.ui">
<Filter>Form Files</Filter>
</QtUic>
<QtUic Include="Ui\dialogsetuppasswd.ui">
<Filter>Form Files</Filter>
</QtUic>
<QtUic Include="Ui\output_statistic.ui">
<Filter>Form Files</Filter>
</QtUic>
<QtUic Include="Ui\plcsetup.ui">
<Filter>Form Files</Filter>
</QtUic>
</ItemGroup>
</Project>

@ -2,11 +2,16 @@
<Project ToolsVersion="Current" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<QTDIR>C:\Qt\5.15.2\msvc2019_64</QTDIR>
<LocalDebuggerEnvironment>PATH=$(QTDIR)\bin%3b$(PATH)</LocalDebuggerEnvironment>
<DebuggerFlavor>WindowsLocalDebugger</DebuggerFlavor>
<LocalDebuggerEnvironment>PATH=$(QTDIR)\bin%3b$(SOLUTIONDIR)runtime%3b$(QTDIR)\bin%3bD:\Qt\5.15.0\msvc2019_64\bin%3b$(PATH)</LocalDebuggerEnvironment>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<QTDIR>C:\Qt\5.15.2\msvc2019_64</QTDIR>
<LocalDebuggerEnvironment>PATH=$(QTDIR)\bin%3b$(PATH)</LocalDebuggerEnvironment>
<LocalDebuggerEnvironment>PATH=$(QTDIR)\bin%3bD:\Qt\5.15.2\msvc2019_64\bin%3b$(PATH)</LocalDebuggerEnvironment>
</PropertyGroup>
<PropertyGroup Label="QtSettings" Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<QtLastBackgroundBuild>2024-10-04T06:46:34.3746998Z</QtLastBackgroundBuild>
</PropertyGroup>
<PropertyGroup Label="QtSettings" Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<QtLastBackgroundBuild>2024-10-04T06:46:35.5916473Z</QtLastBackgroundBuild>
</PropertyGroup>
</Project>

@ -1,147 +0,0 @@
#include "Cleanthread.h"
#include <QMutex>
#include <QDate>
#include <QDir>
#include <QFileInfoList>
#include <Windows.h>
#include <QSignalMapper>
#include <QIntValidator>
#include "common.h"///
extern SysConf g_sys_conf;///
CleanWorkThread::CleanWorkThread(QObject* parent) : QObject(parent)
{
}
CleanWorkThread::~CleanWorkThread()
{
}
void CleanWorkThread::setSelAuto() {
delSelection = 1;
}
void CleanWorkThread::setSel() {
delSelection = 2;
}
void CleanWorkThread::startWork()
{
emit workStart();
doWork();
}
void CleanWorkThread::startWorkAuto()
{
emit workStartAuto();
doWork();
}
void CleanWorkThread::doWork()
{
qint64 spaceSize;
qint64 dirSize;
QString iDriver = "D:/";
LPCWSTR strDriver = (LPCWSTR)iDriver.utf16();
ULARGE_INTEGER freeDiskSpaceAvailable, totalDiskSpace, totalFreeDiskSpace;
qint64 gb = (1024 * 1024 * 1024);
QString dir("D:/image");
if (delSelection == 2)
{
CleanImageFile(dir, 1);
}
else
{
qint64 delDays = g_sys_conf.save_days;///
qint64 freeSize = g_sys_conf.freesize;
CleanImageFile(dir, delDays--);
//调用函数获取磁盘参数(单位为字节Byte),转化为GB需要除以(1024*1024*1024)
GetDiskFreeSpaceEx(strDriver, &freeDiskSpaceAvailable, &totalDiskSpace, &totalFreeDiskSpace);
spaceSize = ((qint64)totalFreeDiskSpace.QuadPart * (100/freeSize)) / (qint64)totalDiskSpace.QuadPart;
dirSize = DirFileSize(dir) / gb;
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; }//文件夹为空则返回false
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;
match = v.validate(fileInfo.fileName(), pos);
QString name = fileInfo.fileName();
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;
}

@ -1,24 +0,0 @@
#pragma once
#include <QObject>
class CleanWorkThread : public QObject
{
Q_OBJECT
public:
CleanWorkThread(QObject* parent = nullptr);
~CleanWorkThread();
public slots:
void startWork();
void startWorkAuto();
void doWork();
void setSelAuto();
void setSel();
signals:
void workFinished();
void workStart();
void workStartAuto();
public:
qint64 DirFileSize(const QString& path);
void CleanImageFile(const QString& path, const qint64& delDays);
private:
int delSelection;
};

@ -1,11 +1,13 @@
#pragma once
#include "Windows.h"
typedef enum _EncMethod {
none = 0,
addtime = 1
Device = 0,
License = 1
}EncMethod;
extern "C" bool GenerateDeviceID(void);
extern "C" bool GenerateLicenseData(EncMethod Method, char* suffix);
extern "C" bool VerifyLicense(EncMethod Method);
extern "C" bool GenerateLicenseData(const char* flag, const char* suffix);
extern "C" bool VerifyLicense(void);
extern "C" bool AddParaForLicenseData(char* flag, char* suffix);
extern "C" bool DeleteParaForLicenseData(char* flag);
extern "C" bool AnalysisLicense(const char* flag);

Binary file not shown.

@ -0,0 +1,75 @@
#pragma once
#include "exportData.h"
#include "QtCore\qfile.h"
#include "QtCore\qtextstream.h"
#include <QUrl>
#include <QFile>
#include <QObject>
#include <QByteArray>
#include <QNetworkAccessManager>
#include <QtNetwork/QNetworkReply>
class FtpManager
{
private:
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);
}
void uploadSingleFile(QString filePath, QString remotePath) {
// 设置路径
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();
// 上传数据,上传成功后会在远端创建文件
manager.setNetworkAccessible(QNetworkAccessManager::Accessible);
QNetworkReply* reply = manager.put(QNetworkRequest(url), data);
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();
// }
// // 清理资源
// reply->deleteLater();
// });
}
}
};

@ -0,0 +1 @@
8<EFBFBD><EFBFBD><EFBFBD>“ם׳x;¶i‡Bˆ׃2@%^/|׳y׃<>5 *•„¢‏)*3Hgkָ<6B>¬ץ<C2AC><D7A5>¼g EdֿQ₪¦+SBt<42>RRֱ~ףMצ£X¨Tֹ2÷ּO'EֲָS<D6B8>1…,¬ִֵl תgZֲײ=wµ†xI<78>ׂKָ„¿ƒ,Rb?ױ¶ׂi<D782>«<EFBFBD>% :YCm<43>ע†<D7A2>¬n}ב

@ -1,164 +0,0 @@
#include "Logthread.h"
#include <QDir>
#include <QMutex>
#include <QDate>
const char PATH_LogPath[] = "D:/log/";
const char Suffix[] = ".txt";
bool CLog::isFileReady = false;
bool CLog::isRecord2File = true;
QFile localFile;
QMutex mutexLog;
CLog::CLog()
{
}
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;
}
bool CLog::createDir(QString dirPath)
{
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));
#ifndef QT_NO_DEBUG
recordInfo.append(QString("[%1:%2:%3]").arg(fileDesc).arg(functionDesc).arg(lineNum));
#endif
va_list vlist;
va_start(vlist, data);
QByteArray byteArray;
#if defined(Q_OS_WIN)
int recordLen = _vscprintf(data, vlist);
byteArray.resize(recordLen);
#else
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()<<recordInfo;
}
}
}
void CLog::log(CLOG_TYPE nType, 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));
recordInfo.append(" ");
va_list vlist;
va_start(vlist, data);
QByteArray byteArray;
#if defined(Q_OS_WIN)
int recordLen = _vscprintf(data, vlist);
byteArray.resize(recordLen);
#else
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()<<recordInfo;
}
}
}
QString CLog::getTypeDesc(CLog::CLOG_TYPE type)
{
/*
switch (type)
{
case CLOG_TYPE::STARTAPP:
return "[INFO]";
case CLOG_TYPE::STARTWORK:
return "[WARNING]";
case CLOG_TYPE::PAUSEWORK:
return "[ERROR]";
}
*/
return "[INFO]";
}
void CLog::recMegFromCigarette(QString str)
{
CLog::LogConfig logConfig;
logConfig.isRecord2File = true;
logConfig.level = 0;
CLog::init(logConfig);
//qDebug() << GetCurrentThreadId() << "WinAPI";
CLOG_INFO(str.toStdString().c_str());
}

@ -1,71 +0,0 @@
#pragma once
#include <QDialog>
class CLog : public QObject
{
Q_OBJECT
public:
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;
};
CLog();
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, ...);
public slots:
void recMegFromCigarette(QString);
private:
static QString getTypeDesc(CLOG_TYPE type);
private:
static bool isRecord2File;
static bool isFileReady;
};
#ifdef Q_OS_WIN
#define FILE_SEPARATOR '\\'
#else
#define FILE_SEPARATOR '/'
#endif
#define FUNC_SEPARATOR '::'
#ifndef QT_NO_DEBUG
#define __FILENAME__ (strrchr(__FILE__, FILE_SEPARATOR) ? (strrchr(__FILE__, FILE_SEPARATOR) + 1):__FILE__)
#define __FUNNAME__ (strrchr(__FUNCTION__,FUNC_SEPARATOR)?(strrchr(__FUNCTION__, FUNC_SEPARATOR) + 1):__FUNCTION__)
#else
#define __FILENAME__ NULL
#define __FUNNAME__ NULL
#endif
#define CLOG_INFO(...) CLog::log(CLog::STARTAPP, __VA_ARGS__)

@ -7,95 +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)
{
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);
// modbus_connect() 建立连接成功返回0错误返回-1
// modbus_new_rtu 生成RTU的连接建立成功则返回指向modbus_t结构的指针否则将返回NULL/0
modbus_set_response_timeout(g_modbus, 1, 0);
if (g_modbus && modbus_connect(g_modbus) == -1) {
PLCptr->g_plc_ok = false;
}
else {
modbus_set_slave(g_modbus, 1);
PLCptr->g_plc_ok = true;
}
return true;
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); // 用flag设置debug调试标志位flag=1时显示modbus消息的字节
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;
}
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;
}
}
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;
}
}

@ -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);
};

@ -1,3 +1,3 @@
#include "SyncQueue.h"

@ -3,28 +3,28 @@
#include<condition_variable>
#include<list>
#include<iostream>
using namespace std;
template<class T> 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<T> q;
int size;
int max_size;
mutex lock;
condition_variable_any cv_full, cv_empty;
list<T> q;
int size;
int max_size;
};
using namespace std;
@ -42,54 +42,54 @@ SyncQueue<T>::~SyncQueue()
template<class T>
void SyncQueue<T>::put(const T& val)
{
lock_guard<mutex> 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<mutex> 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<class T>
void SyncQueue<T>::take(T& val)
{
lock_guard<mutex> 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<mutex> 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<class T>
void SyncQueue<T>::clear()
{
lock_guard<mutex> locker(lock);
q.clear();
lock_guard<mutex> locker(lock);
q.clear();
}
template<class T>
bool SyncQueue<T>::isEmpty()
{
return q.size() == 0;
return q.size() == 0;
}
template<class T>
bool SyncQueue<T>::isFull()
{
return q.size() == max_size;
return q.size() == max_size;
}
template<class T>
int SyncQueue<T>::count()
{
lock_guard<mutex> locker(lock);
return q.size();
}
lock_guard<mutex> locker(lock);
return q.size();
}

@ -0,0 +1,166 @@
#include "CaptureThread.h"
#include "common.h"
#include "exportData.h"
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)
//-----------------------------------------------------------------------------
{
p_unit_queue = new ASyncQueue<cv::Mat>(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);
}
CaptureThread::~CaptureThread()
{
delete p_unit_queue;
}
//-----------------------------------------------------------------------------
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");
#ifdef IMM_PROCESS
pEventCtrl_.eventNotification.writeS("Off");
#else
pEventCtrl_.eventNotification.writeS("On");
#endif
#ifndef IMM_PROCESS
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;
#else
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);
#endif
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";
}
//图像采集循环
TDMR_ERROR result = DMR_NO_ERROR;
while ((result = static_cast<TDMR_ERROR>(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));
}
manuallyStartAcquisitionIfNeeded(pDev_, *pFI_);
int cnt = 0;
// run thread loop
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_)
{
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)
{
#ifdef IMM_PROCESS
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); //放入调试队列
}
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);
#endif
}
manuallyStopAcquisitionIfNeeded(pDev_, *pFI_);
if (pRequest)
{
pRequest->unlock();
}
pFI_->imageRequestReset(0, 0);
}
catch (const ImpactAcquireException& e)
{
emit error(QString::fromStdString(e.getErrorCodeAsString()));
}
}
//-----------------------------------------------------------------------------
int CaptureThread::getPendingRequestNr(void)
//-----------------------------------------------------------------------------
{
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;
}

@ -0,0 +1,268 @@
//-----------------------------------------------------------------------------
#ifndef CaptureThreadH
#define CaptureThreadH CaptureThreadH
//-----------------------------------------------------------------------------
#include "balluffcamera.h"
#include <QThread>
#include <QMutex>
#include <QTimer>
#include <qdebug.h>
#include "SyncQueue.h"
#include "ASyncQueue.h"
#include "apps/Common/exampleHelper.h"
#include <apps/Common/qtIncludePrologue.h>
#include <apps/Common/qtIncludeEpilogue.h>
#include <opencv2/opencv.hpp>
#include "common.h"
extern SingleCamInfoStruct SingleCamInfo[NumberOfSupportedCameras];
extern int work_camera_nums;
class CaptureThread_Func
{
public:
Device* m_pMVCamera;
ASyncQueue<bool>* p_result_queue_;
ASyncQueue<bool>* p_double_queue_;
void SendFeedBack(int OpID)
{
bool send_ng = false;
bool send_ok = false;
if (OpID == EdgeEvent)
{
#if defined DOUBLE_FEED_BACK
if (p_double_queue_->count() > 0)
{
bool temp;
p_double_queue_->take(temp);
send_ng = true;
}
#endif
}
if (p_result_queue_->count() > 0)
{
bool result;
p_result_queue_->take(result);
if (!result)
{
#if defined DOUBLE_FEED_BACK
p_double_queue_->put(true);
#endif
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 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)
{
boTerminated_ = true;
}
int getPendingRequestNr();
signals:
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);
public:
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<std::vector<std::pair<int, cv::Mat>>>* p_image_sync_queue;
#else
SyncQueue<std::pair<int, cv::Mat> >* p_image_queue;
#endif
ASyncQueue<cv::Mat>* p_unit_queue;
ASyncQueue<bool>* p_result_queue;
ASyncQueue<bool>* p_result_wait_queue;
ASyncQueue<bool>* p_double_queue;
ASyncQueue<bool>* p_shooted_queue;
SyncQueue<cv::Mat>* p_debug_queue;
bool Ready = false;
CaptureThread_Func m_threadFunc;
private:
Device* pDev_;
volatile bool boTerminated_;
int requestPendingForDisplay_;
FunctionInterface* pFI_;
QMutex lock_;
};
//=============================================================================
//================= Camera's property callback ================================
//=============================================================================
class EventCallback : public mvIMPACT::acquire::ComponentCallback
{
public:
ASyncQueue<cv::Mat>* p_unit_queue_;
#ifdef SYNC_CAMERA
ImageSyncArr* p_image_sync_arr_;
SyncQueue<std::vector<std::pair<int, cv::Mat>>>* p_image_sync_queue_;
#else
SyncQueue<std::pair<int, cv::Mat> >* p_image_queue_;
#endif
ASyncQueue<bool>* p_result_wait_queue_;
ASyncQueue<bool>* p_shooted_queue_;
ASyncQueue<bool>* 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<mvIMPACT::acquire::GenICam::EventControl*>(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);
}
#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);
}
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);
}
#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);
}
#ifdef SYNC_CAMERA
{
std::lock_guard<std::mutex> 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));
#endif
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;
}
};
//-----------------------------------------------------------------------------
#endif // CaptureThreadH

@ -0,0 +1,207 @@
#include "CaptureThreadBasler.h"
#include <QtWidgets/QApplication>
#include "PLCDevice.h"
#include "common.h"
#include <qdebug.h>
#include <exportData.h>
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)
//-----------------------------------------------------------------------------
{
p_unit_queue = new ASyncQueue<cv::Mat>(Unit_Queue_Size);
Shoot_Num = shoot;
}
CaptureThreadBasler::~CaptureThreadBasler()
{
delete p_unit_queue;
}
//-----------------------------------------------------------------------------
void CaptureThreadBasler::process(void)
//-----------------------------------------------------------------------------
{
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);
CSampleImageEventHandler ImageEvent;
#ifdef SYNC_CAMERA
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;
#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);
CSampleCameraEventHandler BurstEvent;
#ifdef SYNC_CAMERA
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;
#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;
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);
}
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);
}
}
#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);
}
}
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);
#else
pDev_->EventNotification.SetValue(Basler_UniversalCameraParams::EventNotification_On);
#endif
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);
#else
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;
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);
#if defined (IMM_FEED_BACK) || defined (CAP_FEED_BACK)
m_threadFunc.SendFeedBack(ImageCap);
#endif
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;
#endif
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");
#else
pDev_->DeregisterCameraEventHandler(&BurstEvent, "EventLine1RisingEdgeData");
pDev_->DeregisterCameraEventHandler(&BurstEvent, "EventLine1FallingEdgeData");
#endif
}
catch (const Pylon::GenericException& e)
{
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");
#else
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);
}
void CaptureThreadBasler::ioTimeout()
{
pDev_->UserOutputSelector.SetValue(Basler_UniversalCameraParams::UserOutputSelector_UserOutput1);
pDev_->UserOutputValue.SetValue(false);
pDev_->UserOutputSelector.SetValue(Basler_UniversalCameraParams::UserOutputSelector_UserOutput3);
pDev_->UserOutputValue.SetValue(false);
}

@ -6,6 +6,7 @@
#include <QThread>
#include <QMutex>
#include <QTimer>
#include <qdebug.h>
#include "SyncQueue.h"
#include "ASyncQueue.h"
@ -13,6 +14,7 @@
#include <opencv2/opencv.hpp>
extern bool g_debug_mode;
extern int work_camera_nums;
extern SingleCamInfoStruct SingleCamInfo[NumberOfSupportedCameras];
enum MyEvents
{
@ -26,21 +28,21 @@ class CaptureThreadBasler_Func
{
public:
Pylon::CBaslerUniversalInstantCamera* pDev__;
ASyncQueue<bool> *p_result_queue_;
ASyncQueue<bool> *p_double_queue_;
QTimer *m_IOTimer_ = NULL;
ASyncQueue<bool>* p_result_queue_;
ASyncQueue<bool>* 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
}
@ -52,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
@ -90,35 +92,40 @@ 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);
public:
int Local_Num;
int Shoot_Num;
SyncQueue<std::pair<int, cv::Mat> > *p_image_queue;
ASyncQueue<cv::Mat> *p_unit_queue;
ASyncQueue<bool> *p_result_queue;
ASyncQueue<bool> *p_result_wait_queue;
ASyncQueue<bool> *p_double_queue;
ASyncQueue<bool> *p_shooted_queue;
SyncQueue<cv::Mat> *p_debug_queue;
QTimer *m_Timer = NULL,*m_IOTimer = NULL;
#ifdef SYNC_CAMERA
ImageSyncArr* p_image_sync_arr;
SyncQueue<std::vector<std::pair<int, cv::Mat>>>* p_image_sync_queue;
#else
SyncQueue<std::pair<int, cv::Mat> >* p_image_queue;
#endif
ASyncQueue<cv::Mat>* p_unit_queue;
ASyncQueue<bool>* p_result_queue;
ASyncQueue<bool>* p_result_wait_queue;
ASyncQueue<bool>* p_double_queue;
ASyncQueue<bool>* p_shooted_queue;
SyncQueue<cv::Mat>* p_debug_queue;
QTimer* m_Timer = NULL, * m_IOTimer = NULL;
uint64_t m_cntGrabbedImages = 0;
uint64_t m_cntLastGrabbedImages = 0;
bool Ready = false;
@ -134,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;
}
@ -144,140 +151,158 @@ public:
class CSampleCameraEventHandler : public Pylon::CBaslerUniversalCameraEventHandler
{
public:
QTimer * ioTimer;
QTimer* ioTimer;
ASyncQueue<cv::Mat>* p_unit_queue_;
ASyncQueue<bool> *p_result_wait_queue_;
ASyncQueue<bool> *p_result_queue_;
ASyncQueue<bool> *p_double_queue_;
ASyncQueue<bool> *p_shooted_queue_;
ASyncQueue<bool>* p_result_wait_queue_;
ASyncQueue<bool>* p_result_queue_;
ASyncQueue<bool>* p_double_queue_;
ASyncQueue<bool>* p_shooted_queue_;
#ifdef SYNC_CAMERA
ImageSyncArr* p_image_sync_arr_;
SyncQueue<std::vector<std::pair<int, cv::Mat>>>* p_image_sync_queue_;
#else
SyncQueue<std::pair<int, cv::Mat> >* 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());
}
p_image_queue_->put(std::make_pair(unit_count, long_image));
p_shooted_queue_->put(true);
cv::Rect r(0, i * image.rows, image.cols, image.rows);
cv::Mat roi = long_image(r);
image.copyTo(roi);
}
p_unit_queue_->clear();
break;
#ifdef SYNC_CAMERA
{
std::lock_guard<std::mutex> 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));
#endif
p_shooted_queue_->put(true);
}
p_unit_queue_->clear();
break;
}
#endif
default:
break;
@ -289,9 +314,14 @@ class CSampleImageEventHandler : public Pylon::CBaslerUniversalImageEventHandler
{
public:
ASyncQueue<cv::Mat>* p_unit_queue_;
#ifdef SYNC_CAMERA
ImageSyncArr* p_image_sync_arr_;
SyncQueue<std::vector<std::pair<int, cv::Mat>>>* p_image_sync_queue_;
#else
SyncQueue<std::pair<int, cv::Mat> >* p_image_queue_;
#endif
SyncQueue<cv::Mat>* p_debug_queue_;
ASyncQueue<bool> *p_shooted_queue_;
ASyncQueue<bool>* p_shooted_queue_;
Pylon::CBaslerUniversalInstantCamera* pDev__;
uint64_t* m_cntGrabbedImages_;
int Shoot_Num_;
@ -314,11 +344,10 @@ public:
// Create an OpenCV image from a pylon image.
openCvImage = cv::Mat(ptrGrabResult->GetHeight(), ptrGrabResult->GetWidth(), CV_8UC1, (uint8_t*)pylonImage.GetBuffer());
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

@ -0,0 +1,326 @@
#include "CaptureThreadHIK.h"
#include <QtWidgets/QApplication>
#include "PLCDevice.h"
#include "common.h"
#include <windows.h>
#include "exportData.h"
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 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<std::mutex> 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;
}
}
#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;
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;
#ifdef IMM_FEED_BACK
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);
}
#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;
}
}
#define CaptureThreadHIK_init(a)\
void __stdcall LossCallBack##a(unsigned int pData, void* pUser){LossCallBackfunction(pData,pUser);}\
void __stdcall FallingGpioEvent##a(MV_EVENT_OUT_INFO* pEventInfo, void* pUser){FallingGpioEventfunction(pEventInfo,pUser);}\
void __stdcall RisingGpioEvent##a(MV_EVENT_OUT_INFO* pEventInfo, void* pUser){RisingGpioEventfunction(pEventInfo,pUser);}
#if defined(NumberOfSupportedCameras) && (NumberOfSupportedCameras>0)
CaptureThreadHIK_init(1)
#endif
#if defined(NumberOfSupportedCameras) && (NumberOfSupportedCameras>1)
CaptureThreadHIK_init(2)
#endif
#if defined(NumberOfSupportedCameras) && (NumberOfSupportedCameras>2)
CaptureThreadHIK_init(3)
#endif
#if defined(NumberOfSupportedCameras) && (NumberOfSupportedCameras>3)
CaptureThreadHIK_init(4)
#endif
#if defined(NumberOfSupportedCameras) && (NumberOfSupportedCameras>4)
CaptureThreadHIK_init(5)
#endif
#if defined(NumberOfSupportedCameras) && (NumberOfSupportedCameras>5)
CaptureThreadHIK_init(6)
#endif
#if defined(NumberOfSupportedCameras) && (NumberOfSupportedCameras>6)
CaptureThreadHIK_init(7)
#endif
#if defined(NumberOfSupportedCameras) && (NumberOfSupportedCameras>7)
CaptureThreadHIK_init(8)
#endif
void(*LossCallBack[NumberOfSupportedCameras])(unsigned int pData, void* pUser) = {
#if defined(NumberOfSupportedCameras) && (NumberOfSupportedCameras>0)
LossCallBack1
#endif
#if defined(NumberOfSupportedCameras) && (NumberOfSupportedCameras>1)
,LossCallBack2
#endif
#if defined(NumberOfSupportedCameras) && (NumberOfSupportedCameras>2)
,LossCallBack3
#endif
#if defined(NumberOfSupportedCameras) && (NumberOfSupportedCameras>3)
,LossCallBack4
#endif
#if defined(NumberOfSupportedCameras) && (NumberOfSupportedCameras>4)
,LossCallBack5
#endif
#if defined(NumberOfSupportedCameras) && (NumberOfSupportedCameras>5)
,LossCallBack6
#endif
#if defined(NumberOfSupportedCameras) && (NumberOfSupportedCameras>6)
,LossCallBack7
#endif
#if defined(NumberOfSupportedCameras) && (NumberOfSupportedCameras>7)
,LossCallBack8
#endif
};
void(*FallingGpioEvent[NumberOfSupportedCameras])(MV_EVENT_OUT_INFO* pEventInfo, void* pUser) = {
#if defined(NumberOfSupportedCameras) && (NumberOfSupportedCameras>0)
FallingGpioEvent1
#endif
#if defined(NumberOfSupportedCameras) && (NumberOfSupportedCameras>1)
,FallingGpioEvent2
#endif
#if defined(NumberOfSupportedCameras) && (NumberOfSupportedCameras>2)
,FallingGpioEvent3
#endif
#if defined(NumberOfSupportedCameras) && (NumberOfSupportedCameras>3)
,FallingGpioEvent4
#endif
#if defined(NumberOfSupportedCameras) && (NumberOfSupportedCameras>4)
,FallingGpioEvent5
#endif
#if defined(NumberOfSupportedCameras) && (NumberOfSupportedCameras>5)
,FallingGpioEvent6
#endif
#if defined(NumberOfSupportedCameras) && (NumberOfSupportedCameras>6)
,FallingGpioEvent7
#endif
#if defined(NumberOfSupportedCameras) && (NumberOfSupportedCameras>7)
,FallingGpioEvent8
#endif
};
void(*RisingGpioEvent[NumberOfSupportedCameras])(MV_EVENT_OUT_INFO* pEventInfo, void* pUser) = {
#if defined(NumberOfSupportedCameras) && (NumberOfSupportedCameras>0)
RisingGpioEvent1
#endif
#if defined(NumberOfSupportedCameras) && (NumberOfSupportedCameras>1)
,RisingGpioEvent2
#endif
#if defined(NumberOfSupportedCameras) && (NumberOfSupportedCameras>2)
,RisingGpioEvent3
#endif
#if defined(NumberOfSupportedCameras) && (NumberOfSupportedCameras>3)
,RisingGpioEvent4
#endif
#if defined(NumberOfSupportedCameras) && (NumberOfSupportedCameras>4)
,RisingGpioEvent5
#endif
#if defined(NumberOfSupportedCameras) && (NumberOfSupportedCameras>5)
,RisingGpioEvent6
#endif
#if defined(NumberOfSupportedCameras) && (NumberOfSupportedCameras>6)
,RisingGpioEvent7
#endif
#if defined(NumberOfSupportedCameras) && (NumberOfSupportedCameras>7)
,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);
}
//-----------------------------------------------------------------------------
CaptureThreadHIK::CaptureThreadHIK(void* camhandle, bool boTerminated, int Num) :
CamHandle(camhandle), boTerminated_(boTerminated), Local_Num(Num)
//-----------------------------------------------------------------------------
{
p_unit_queue = new ASyncQueue<cv::Mat>(Unit_Queue_Size);
g_pImage_buf = (unsigned char*)malloc(3000 * 3000 * 3);
}
CaptureThreadHIK::~CaptureThreadHIK()
{
delete p_unit_queue;
free(g_pImage_buf);
}
//-----------------------------------------------------------------------------
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;
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; }
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, "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, "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);
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)
{
#ifdef IMM_PROCESS
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); //放入调试队列
}
}
#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;
}
}
//-----------------------------------------------------------------------------

@ -3,7 +3,7 @@
#define CaptureThreadHIKH CaptureThreadHIKH
//-----------------------------------------------------------------------------
#include "hikcamera.h"
#include "common.h"
#include <QThread>
#include <QMutex>
#include <functional>
@ -17,21 +17,21 @@
class CaptureThreadHIK_Func
{
public:
void *CamHandle_;
ASyncQueue<bool> *p_result_queue_;
ASyncQueue<bool> *p_double_queue_;
void* CamHandle_;
ASyncQueue<bool>* p_result_queue_;
ASyncQueue<bool>* 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,45 +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;
SyncQueue<std::pair<int, cv::Mat> > *p_image_queue;
ASyncQueue<cv::Mat> *p_unit_queue;
ASyncQueue<bool> *p_result_queue;
ASyncQueue<bool> *p_result_wait_queue;
ASyncQueue<bool> *p_double_queue;
ASyncQueue<bool> *p_shooted_queue;
SyncQueue<cv::Mat> *p_debug_queue;
#ifdef SYNC_CAMERA
ImageSyncArr* p_image_sync_arr;
SyncQueue<std::vector<std::pair<int, cv::Mat>>>* p_image_sync_queue;
#else
SyncQueue<std::pair<int, cv::Mat> >* p_image_queue;
#endif
ASyncQueue<cv::Mat>* p_unit_queue;
ASyncQueue<bool>* p_result_queue;
ASyncQueue<bool>* p_result_wait_queue;
ASyncQueue<bool>* p_double_queue;
ASyncQueue<bool>* p_shooted_queue;
SyncQueue<cv::Mat>* 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_;
};

@ -0,0 +1,158 @@
#include "Cleanthread.h"
#include <QMutex>
#include <QDate>
#include <QDir>
#include <QFileInfoList>
#include <Windows.h>
#include <QSignalMapper>
#include <QIntValidator>
#include "common.h"///
extern SysConf g_sys_conf;///
extern ConfPath g_conf_path;
CleanWorkThread::CleanWorkThread(QObject* parent) : QObject(parent)
{
}
CleanWorkThread::~CleanWorkThread()
{
}
void CleanWorkThread::setSelAuto() {
delSelection = 1;
}
void CleanWorkThread::setSel() {
delSelection = 2;
}
void CleanWorkThread::startWork()
{
emit workStart();
doWork();
}
void CleanWorkThread::startWorkAuto()
{
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];
_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--);
//调用函数获取磁盘参数(单位为字节Byte),转化为GB需要除以(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; }//文件夹为空则返回false
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;
}

@ -0,0 +1,24 @@
#pragma once
#include <QObject>
class CleanWorkThread : public QObject
{
Q_OBJECT
public:
CleanWorkThread(QObject* parent = nullptr);
~CleanWorkThread();
public slots:
void startWork();
void startWorkAuto();
void doWork();
void setSelAuto();
void setSel();
signals:
void workFinished();
void workStart();
void workStartAuto();
public:
qint64 DirFileSize(const QString& path);
void CleanImageFile(const QString& path, const qint64& delDays);
private:
int delSelection;
};

@ -0,0 +1,164 @@
#include "Logthread.h"
#include <QDir>
#include <QMutex>
#include <QDate>
const char PATH_LogPath[] = "D:/log/";
const char Suffix[] = ".txt";
bool CLog::isFileReady = false;
bool CLog::isRecord2File = true;
QFile localFile;
QMutex mutexLog;
CLog::CLog()
{
}
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;
}
bool CLog::createDir(QString dirPath)
{
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));
#ifndef QT_NO_DEBUG
recordInfo.append(QString("[%1:%2:%3]").arg(fileDesc).arg(functionDesc).arg(lineNum));
#endif
va_list vlist;
va_start(vlist, data);
QByteArray byteArray;
#if defined(Q_OS_WIN)
int recordLen = _vscprintf(data, vlist);
byteArray.resize(recordLen);
#else
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()<<recordInfo;
}
}
}
void CLog::log(CLOG_TYPE nType, 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));
recordInfo.append(" ");
va_list vlist;
va_start(vlist, data);
QByteArray byteArray;
#if defined(Q_OS_WIN)
int recordLen = _vscprintf(data, vlist);
byteArray.resize(recordLen);
#else
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()<<recordInfo;
}
}
}
QString CLog::getTypeDesc(CLog::CLOG_TYPE type)
{
/*
switch (type)
{
case CLOG_TYPE::STARTAPP:
return "[INFO]";
case CLOG_TYPE::STARTWORK:
return "[WARNING]";
case CLOG_TYPE::PAUSEWORK:
return "[ERROR]";
}
*/
return "[INFO]";
}
void CLog::recMegFromCigarette(QString str)
{
CLog::LogConfig logConfig;
logConfig.isRecord2File = true;
logConfig.level = 0;
CLog::init(logConfig);
//qDebug() << GetCurrentThreadId() << "WinAPI";
CLOG_INFO(str.toStdString().c_str());
}

@ -0,0 +1,71 @@
#pragma once
#include <QDialog>
class CLog : public QObject
{
Q_OBJECT
public:
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;
};
CLog();
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, ...);
public slots:
void recMegFromCigarette(QString);
private:
static QString getTypeDesc(CLOG_TYPE type);
private:
static bool isRecord2File;
static bool isFileReady;
};
#ifdef Q_OS_WIN
#define FILE_SEPARATOR '\\'
#else
#define FILE_SEPARATOR '/'
#endif
#define FUNC_SEPARATOR '::'
#ifndef QT_NO_DEBUG
#define __FILENAME__ (strrchr(__FILE__, FILE_SEPARATOR) ? (strrchr(__FILE__, FILE_SEPARATOR) + 1):__FILE__)
#define __FUNNAME__ (strrchr(__FUNCTION__,FUNC_SEPARATOR)?(strrchr(__FUNCTION__, FUNC_SEPARATOR) + 1):__FUNCTION__)
#else
#define __FILENAME__ NULL
#define __FUNNAME__ NULL
#endif
#define CLOG_INFO(...) CLog::log(CLog::STARTAPP, __VA_ARGS__)

@ -0,0 +1,95 @@
#ifndef _DEBUGTHREAD_H
#define _DEBUGTHREAD_H
#include <QThread>
#include <QDebug>
#include <QDateTime>
#include <opencv2/opencv.hpp>
#include <opencv2/imgproc/types_c.h>
#include "SyncQueue.h"
#include "basecamera.h"
#include "common.h"
#include "balluffcamera.h"
#include "hikcamera.h"
extern SyncQueue<cv::Mat>* 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
signals:
void notify(int Num, int Cnt, cv::Mat);
public:
DebugThread(QObject* parent = 0) : QThread(parent)
{
}
~DebugThread()
{
stop();
p_debug_queue->put(cv::Mat());
quit();
wait();
}
void init(SyncQueue<cv::Mat>* 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)
{
//cv::cvtColor(image, image, CV_BGR2RGB); //灰度图像转为彩色图像
// 解决进入调试模式海康彩色相机变色,关闭色彩调整巴鲁夫相机变黑的问题
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::rotate(image, image, rotationAngle[local_camera_number]);
}
}
//sleep(100);
emit notify(local_camera_number, 0, image);
}
#ifdef DRAW_RECT
std::lock_guard<std::mutex> 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);
#endif
}
}
public:
int local_camera_number;
int local_classid;
bool b_quit;
SyncQueue<cv::Mat>* p_debug_queue;
DisplayLabelConf local_DisplayLabelConf;
};
#endif //end of _DEBUGTHREAD_H

@ -0,0 +1,100 @@
#ifndef SAVE_THREAD_H
#define SAVE_THREAD_H
#include <QThread>
#include <QDebug>
#include <QDateTime>
#include "SyncQueue.h"
#include "common.h"
#include <iostream>
#include <string>
#include <vector>
#include <qdir.h>
#include <opencv2/opencv.hpp>
#include <opencv2/imgproc/types_c.h>
extern SyncQueue<std::pair<std::string, cv::Mat>>* g_save_queue; //图像保存队列
class SaveThread : public QThread
{
Q_OBJECT
signals:
void sendDataToExport(QString filePath);
public:
SaveThread(QObject* parent = 0) : QThread(parent)
{
}
~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;
}
protected:
void run()
{
while (!b_quit) {
cv::Mat image;
std::pair<std::string, cv::Mat> 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++)
{
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()));
QDir dir;
if (!dir.exists(dir_str))
{
dir.mkpath(dir_str);
}
vec_save_dirs.push_back(dir_path);
}
}
public:
bool b_quit;
std::vector<std::string> vec_save_dirs;
};
#endif

@ -0,0 +1,348 @@
#include "SyncWorkThread.h"
#include "alg_jd.h"
#include "common.h"
#include "balluffcamera.h"
#include "baslercamera.h"
#include "threadSend.h"
#include <PLCDevice.h>
#include "exportData.h"
#include <QMap>
extern AlgJd alg_jd[NumberOfSupportedCameras]; //检测胶点的AI算法
extern ConfPath g_conf_path;
extern SysConf g_sys_conf; //系统配置参数
extern DisplayLabelConf g_display_label_conf[NumberOfSupportedCameras];
extern int rotationAngle[NumberOfSupportedCameras]; //图片旋转角度
extern bool isNeedRotate[NumberOfSupportedCameras];
extern int work_camera_nums;
extern SingleCamInfoStruct SingleCamInfo[NumberOfSupportedCameras];
extern SyncQueue<std::pair<std::string, cv::Mat> >* g_save_queue; //图片保存队列
extern SyncQueue<std::pair<int, cv::Mat>>* g_image_queue[NumberOfSupportedCameras]; //int表示一个目标拍了几张
#ifdef __UDPSend
extern SyncQueue<_UDPSendInfo>* UDP_Info_queue;
#endif
#ifdef __TCPSend
extern SyncQueue<_TCPSendInfo>* TCP_Info_queue;
#endif
#ifdef __ExportData
extern ExportDataThread exportDataThread;
#endif
extern PLCDevice* m_PLCDevice;
extern bool g_debug_mode;
SyncWorkThread::~SyncWorkThread()
{
stop();
std::vector<std::pair<int, cv::Mat>> queue;
local_g_image_sync_queue->put(queue);
quit();
wait();
}
void SyncWorkThread::init(SyncQueue<std::vector<std::pair<int, cv::Mat>>>* image_ptr, ASyncQueue<bool>* 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;
}
}
void SyncWorkThread::start_work()
{
start(HighestPriority);
}
void SyncWorkThread::stop()
{
b_quit = true;
}
void SyncWorkThread::run()
{
try {
uint32_t result_index[NumberOfSupportedCameras] = { 0 };
while (!b_quit) {
QDateTime now_ts = QDateTime::currentDateTime();
std::vector<std::pair<int, cv::Mat>> element_vec;
local_g_image_sync_queue->take(element_vec);
bool IsNGForAll = false;
int merge_index;
cv::Mat merge_image = cv::Mat::zeros(512 * work_camera_nums, 640 * g_sys_conf.shoot[0], CV_8UC3);
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;
std::pair<int, cv::Mat> element;
element = element_vec[i];
int unit_count = element.first;
cv::Mat image = element.second;
{//不要删掉这个括号,用来定义锁的作用域
std::lock_guard<std::mutex> 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<std::mutex> 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;
#endif
#ifdef __TCPSend
_TCPSendInfo TCPSendInfo;
#endif
if (!image.data)
{
continue; //图像为空,跳过
}
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<cv::Mat> 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<cv::Mat> vec_out;
std::vector<std::vector<std::pair<int, cv::Rect>>> vec_results;
QDateTime ts_start = QDateTime::currentDateTime();
if (unit_count == 1) {
std::vector<std::pair<int, cv::Rect>> 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);
#endif
#ifdef __UDPSend
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);
#ifdef SYNC_CAMERA
emit display_jd_no(local_camera_number, jd_no);
#endif
#ifdef __UDPSend
UDPSendInfo.JD = jd_no;
#endif
bool IsNG = false;
int ngReason = 0;
QMap<int, QString> 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)//三张照片分别存储
{
/// 合成work_camera_nums * 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));
#ifdef __TCPSend
QString sendName = now_ts.toString("yyyy-MM-dd_HH-mm-ss_zzz_") + ".jpg";
TCPSendInfo.pics_name = sendName.toLocal8Bit().constData();
TCP_Info_queue->put(TCPSendInfo);
#endif
}
}
}
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;
}
#endif
}
else {
image1 = vec_out[0].clone();
#ifdef DRAW_RECT
IsNG |= CheckSelectRects(image1, vec_results, 0, local_DisplayLabelConf, 0);
if (IsNG) {
ngReason = 2;
}
#endif
}
#ifdef DRAW_RECT
DrawSelectRects(image1, local_DisplayLabelConf, 0);
#endif
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;
}
#endif
}
result_index[i]++;
if (!IsNG)
{
if (!g_debug_mode)
{
#ifdef SYNC_CAMERA
emit event_ok(local_camera_number);
#endif
local_g_result_queue->put(true);
}
}
else
{
if (!g_debug_mode)
{
#ifdef SYNC_CAMERA
emit event_ng(local_camera_number);
#endif
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));
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)
{
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
{
#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;
}
#endif
}
#ifdef __UDPSend
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;
}
}

@ -0,0 +1,46 @@
#pragma once
#include <QThread>
#include <QDebug>
#include <QDateTime>
#include <opencv2/opencv.hpp>
#include <opencv2/imgproc/types_c.h>
#include "SyncQueue.h"
#include "ASyncQueue.h"
#include "common.h"
class SyncWorkThread :
public QThread
{
Q_OBJECT
#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 event_ok(int Num);
void event_ng(int Num);
#endif
public:
SyncWorkThread(QObject* parent = 0) : QThread(parent)
{
}
~SyncWorkThread();
void init(SyncQueue<std::vector<std::pair<int, cv::Mat>>>* image_ptr, ASyncQueue<bool>* result_ptr);
void start_work();
void stop();
protected:
void run();
public:
int local_camera_number;
SyncQueue<std::vector<std::pair<int, cv::Mat>>>* local_g_image_sync_queue;
ASyncQueue<bool>* local_g_result_queue;
bool b_quit;
long frame_total[NumberOfSupportedCameras];
SysConf local_SysConf;
DisplayLabelConf local_DisplayLabelConf;
};

@ -0,0 +1,89 @@
#include "threadReceive.h"
#include "cigarette.h"
#include "basecamera.h"
void threadReceive::start_work()
{
//start(HighestPriority);
start();
}
void threadReceive::stop()
{
isLoop = false;
BOOL bDontLinger = FALSE;
mSocket->abort();
filemSocket->abort();
// wait();
}
void threadReceive::init(std::string IP, int port)
{
ip = QString::fromStdString(IP);
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);
}
void threadReceive::processPendingDatagram()
{
// 拥有等待的数据报
while (mSocket->hasPendingDatagrams())
{
QByteArray datagram;
// 让datagram的大小为等待处理的数据报的大小这样才能接收到完整的数据
datagram.resize(mSocket->pendingDatagramSize());
// 接收数据报将其存放到datagram中
mSocket->readDatagram(datagram.data(), datagram.size());
QString data = datagram;
emit sendMsgToCigratte(data);
}
}
void threadReceive::fileprocessPendingDatagram()
{
QString filename;
std::fstream file;
// 拥有等待的数据报
while (filemSocket->hasPendingDatagrams())
{
QByteArray datagram;
// 让datagram的大小为等待处理的数据报的大小这样才能接收到完整的数据
datagram.resize(filemSocket->pendingDatagramSize());
// 接收数据报将其存放到datagram中
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();
}
}
}
}

@ -0,0 +1,45 @@
#pragma once
#include <QThread>
#include <QDebug>
#include <QDateTime>
#include <opencv2/opencv.hpp>
#include <opencv2/imgproc/types_c.h>
#include <atomic>
#include <mutex>
#include "common.h"
#include "SyncQueue.h"
#include <QUdpSocket>
class threadReceive : public QThread
{
Q_OBJECT
public:
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();
private slots:
void processPendingDatagram();
void fileprocessPendingDatagram();
signals:
void sendMsgToCigratte(QString data);
public:
std::atomic_bool isLoop = { 0 };
QUdpSocket* mSocket;
QUdpSocket* filemSocket;
};

@ -3,13 +3,13 @@
#include "basecamera.h"
#include <QFile>
#include <QFileInfo>
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:"<<ip<<"|MonitorPort:"<<dataport;
qDebug() << "MonitorIP ip:" << ip << "|MonitorPort:" << dataport;
}
void threadSend::start_work()
{
@ -29,42 +29,41 @@ void threadSend::run()
{
_UDPSendInfo UDPSendInfo;
Local_UDP_Info_queue->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))
.arg(UDPSendInfo->JD)
@ -77,25 +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));
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,23 +111,23 @@ 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))
.arg(QString::number(UDPSendInfo->ok));
.arg(QString::number(UDPSendInfo->ok[UDPSendInfo->index]));
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))
.arg(QString::number(UDPSendInfo->ng));
.arg(QString::number(UDPSendInfo->ng[UDPSendInfo->index]));
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();
}
}

@ -0,0 +1,96 @@
#pragma once
#include <QThread>
#include <QDebug>
#include <QDateTime>
#include <opencv2/opencv.hpp>
#include <opencv2/imgproc/types_c.h>
#include <atomic>
#include <mutex>
#include "common.h"
#include "SyncQueue.h"
#include <QUdpSocket>
#define image_width 160
#define image_heigh 120
#define info_frame 1
#define speed_frame 2
#define kick_frame 3
#define ok_frame 4
#define ng_frame 5
#define image_frame 6
#define total_frame 7
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];
_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; i < NumberOfSupportedCameras; i++)Kick[i] = 0;
}
};
class threadSend : public QThread
{
public:
QString ip;
int dataport;
int imageport;
threadSend(QObject* o = nullptr) :QThread(o)
{
isLoop = true;
}
~threadSend()
{
stop();
_UDPSendInfo UDPSendInfo;
Local_UDP_Info_queue->put(UDPSendInfo);
quit();
wait();
}
void stop();
protected:
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);
public:
SyncQueue<_UDPSendInfo>* Local_UDP_Info_queue;
std::atomic_bool isLoop = { 0 };
QUdpSocket mSocket;
};

@ -0,0 +1,97 @@
#include "threadSendMqtt.h"
#include <WinSock2.h>
#include <WS2tcpip.h>
#include <stdio.h>
#include <qtcpsocket.h>
// 相关头文件
#include <QFile> // 文件操作
#include <QJsonObject> // JSON对象
#include <QJsonArray> // JSON数组
#include <QJsonDocument> // JSON文档
#include <QJsonParseError> // JSON异常捕捉
void threadSendMqtt::init(SyncQueue<_MqttSendInfo>* p_MQTT_Info_queue, std::string ip_, int port_) {
ip = QString::fromStdString(ip_);
port = port_;
qDebug() << "Mqtt ip:" << ip << "| Mqtt port:" << port;
Local_MQTT_Info_queue = p_MQTT_Info_queue;
}
void threadSendMqtt::start_work()
{
//start(HighestPriority);
start();
}
void threadSendMqtt::stop()
{
isLoop = false;
wait();
delete m_client;
}
bool threadSendMqtt::connectTCP() {
m_client = new QMqttClient(this);
m_client->setHostname(ip);
m_client->setPort(port);
//m_client->setUsername(userName);
//m_client->setPassword(userPassword);
m_client->connectToHost();
//connect(m_client, &QMqttClient::stateChanged, this, &MainWindow::updateLogStateChange);
connect(m_client, &QMqttClient::connected, this, [this](void) {qDebug() << "Mqtt connected";});
connect(m_client, &QMqttClient::disconnected, this, [this](void) {qDebug() << "Mqtt disconnected"; });
connect(m_client, SIGNAL(messageSent(qint32)), this, SLOT(MQTT_DATASEND_SUCCESS(qint32)));//消息发送成功提示的槽函数绑定
connect(m_client, &QMqttClient::messageReceived, this, [this](const QByteArray &message, const QMqttTopicName &topic) {
const QString content = QDateTime::currentDateTime().toString()
+ QLatin1String(" Received Topic: ")
+ topic.name()
+ QLatin1String(" Message: ")
+ message
+ QLatin1Char('\n');
//ui->editLog->insertPlainText(content);
});
connect(m_client, &QMqttClient::pingResponseReceived, this, [this]() {
const QString content = QDateTime::currentDateTime().toString()
+ QLatin1String(" PingResponse")
+ QLatin1Char('\n');
//ui->editLog->insertPlainText(content);
});
//connect(ui->lineEditHost, &QLineEdit::textChanged, m_client, &QMqttClient::setHostname);
//connect(ui->spinBoxPort, QOverload<int>::of(&QSpinBox::valueChanged), this, &MainWindow::setClientPort);
return true;
}
void threadSendMqtt::run()
{
if (!connectTCP())
qDebug() << "Mqtt connect error!";
while (isLoop) {
_MqttSendInfo TCPSendInfo;
Local_MQTT_Info_queue->take(TCPSendInfo);
num++;
sendData(&TCPSendInfo, num);
}
}
void threadSendMqtt::sendData(_MqttSendInfo* TCPSendInfo, int Num) {
QJsonObject addressObject;
// 方式二:赋值
addressObject["street"] = "123 Main St.";
addressObject["city"] = "Anytown";
addressObject["country"] = "USA";
if (m_client->state() == QMqttClient::Connected) {
QJsonDocument jsonDoc(addressObject);
QByteArray jsonBytes = jsonDoc.toJson();
auto result = m_client->publish(QMqttTopicName("topic"), jsonBytes, 0, true);
}
}

@ -0,0 +1,56 @@
#pragma once
#include <QDebug>
#include <QDateTime>
#include <iostream>
#include <QThread>
#include <QtMqtt/qmqttclient.h>
#include "common.h"
#include "SyncQueue.h"
class _MqttSendInfo
{
public:
int MsgID;
QString timecost;
_MqttSendInfo()
{
}
};
class threadSendMqtt : public QThread {
public:
QString ip;
int port;
int num = 0;
threadSendMqtt(QObject* o = nullptr) :QThread(o)
{
isLoop = true;
}
~threadSendMqtt()
{
stop();
_MqttSendInfo TCPSendInfo;
Local_MQTT_Info_queue->put(TCPSendInfo);
quit();
wait();
}
void stop();
bool connectTCP();
protected:
void run();
public:
void init(SyncQueue<_MqttSendInfo>* p_MQTT_Info_queue, std::string ip_, int port_);
void start_work();
void sendData(_MqttSendInfo* TCPSendInfo, int Num);
public:
SyncQueue<_MqttSendInfo>* Local_MQTT_Info_queue;
std::atomic_bool isLoop = { 0 };
QMqttClient* m_client = NULL;
};

@ -0,0 +1,60 @@
#include "threadSendTCP.h"
#include <WinSock2.h>
#include <WS2tcpip.h>
#include <stdio.h>
#include <qtcpsocket.h>
#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;
Local_TCP_Info_queue = p_TCP_Info_queue;
}
void threadSendTCP::start_work()
{
//start(HighestPriority);
start();
}
void threadSendTCP::stop()
{
isLoop = false;
// wait();
delete mySocket;
}
bool threadSendTCP::connectTCP() {
mySocket = new QTcpSocket();
// 取消已有的连接
mySocket->abort();
// 连接服务器
mySocket->connectToHost(ip, port);
if (!mySocket->waitForConnected(30000)) {
qDebug() << "connect failed!";
return false;
}
qDebug() << "connect successfully!";
return true;
}
void threadSendTCP::run()
{
if (!connectTCP())
qDebug() << "TCP connect error!";
while (isLoop) {
_TCPSendInfo TCPSendInfo;
Local_TCP_Info_queue->take(TCPSendInfo);
num++;
sendData(&TCPSendInfo, num);
//mySocket->write("Hello! here is tcp client!\n");
//mySocket->flush();
}
}
void threadSendTCP::sendData(_TCPSendInfo* TCPSendInfo, int Num) {
std::string fileName = TCPSendInfo->pics_name + ", " + QString::number(Num).toStdString();
mySocket->write(fileName.c_str());
mySocket->write("\n");
mySocket->flush();
}

@ -0,0 +1,55 @@
#pragma once
#include <QDebug>
#include <QDateTime>
#include <iostream>
#include <QThread>
#include <qtcpsocket.h>
#include "common.h"
#include "SyncQueue.h"
class _TCPSendInfo
{
public:
std::string 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();
protected:
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);
public:
SyncQueue<_TCPSendInfo>* Local_TCP_Info_queue;
std::atomic_bool isLoop = { 0 };
QTcpSocket* mySocket;
};

@ -0,0 +1,325 @@
#include "workthread.h"
#include "alg_jd.h"
#include "common.h"
#include "balluffcamera.h"
#include "baslercamera.h"
#include "threadSend.h"
#include <PLCDevice.h>
#include "exportData.h"
#include <QMap>
extern AlgJd alg_jd[NumberOfSupportedCameras]; //检测胶点的AI算法
extern ConfPath g_conf_path;
extern SysConf g_sys_conf; //系统配置参数
extern DisplayLabelConf g_display_label_conf[NumberOfSupportedCameras];
extern int rotationAngle[NumberOfSupportedCameras]; //图片旋转角度
extern bool isNeedRotate[NumberOfSupportedCameras];
extern SyncQueue<std::pair<std::string, cv::Mat> >* g_save_queue; //图片保存队列
extern SyncQueue<std::pair<int, cv::Mat>>* g_image_queue[NumberOfSupportedCameras]; //int表示一个目标拍了几张
#ifdef __UDPSend
extern SyncQueue<_UDPSendInfo>* UDP_Info_queue;
#endif
#ifdef __TCPSend
extern SyncQueue<_TCPSendInfo>* TCP_Info_queue;
#endif
#ifdef __ExportData
extern ExportDataThread exportDataThread;
#endif
extern PLCDevice* m_PLCDevice;
extern bool g_debug_mode;
WorkThread::~WorkThread()
{
stop();
local_g_image_queue->put(std::make_pair(0, cv::Mat()));
quit();
wait();
}
void WorkThread::init(SyncQueue<std::pair<int, cv::Mat>>* image_ptr, ASyncQueue<bool>* 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;
}
void WorkThread::start_work()
{
start(HighestPriority);
}
void WorkThread::stop()
{
b_quit = true;
}
void WorkThread::run()
{
try {
uint32_t result_index = 0;
while (!b_quit) {
{//不要删掉这个括号,用来定义锁的作用域
std::lock_guard<std::mutex> 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<std::mutex> 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<int, cv::Mat> 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;
#endif
#ifdef __TCPSend
_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<cv::Mat> 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<cv::Mat> vec_out;
std::vector<std::vector<std::pair<int, cv::Rect> > > vec_results;
QDateTime ts_start = QDateTime::currentDateTime();
if (unit_count == 1) {
std::vector<std::pair<int, cv::Rect> > 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);
#endif
#ifdef __UDPSend
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);
#ifndef SYNC_CAMERA
emit display_jd_no(local_camera_number, jd_no);
#endif
#ifdef __UDPSend
UDPSendInfo.JD = jd_no;
#endif
bool IsNG = false;
int ngReason = 0;
QMap<int, QString> 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);
#endif
}
}
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;
}
#endif
}
else {
image1 = vec_out[0].clone();
#ifdef DRAW_RECT
IsNG |= CheckSelectRects(image1, vec_results, 0, local_DisplayLabelConf, 0);
if (IsNG) {
ngReason = 2;
}
#endif
}
#ifdef DRAW_RECT
DrawSelectRects(image1, local_DisplayLabelConf, 0);
#endif
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;
}
#endif
}
result_index++;
if (!IsNG)
{
if (!g_debug_mode)
{
#ifndef SYNC_CAMERA
emit event_ok(local_camera_number);
#endif
local_g_result_queue->put(true);
}
}
else
{
if (!g_debug_mode)
{
#ifndef SYNC_CAMERA
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; 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;
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;
}
}
#endif
#ifdef __UDPSend
UDP_Info_queue->put(UDPSendInfo);
#endif
}
}
catch (cv::Exception& e)
{
const char* err_msg = e.what();
std::cout << "exception caught: " << err_msg << std::endl;
}
}

@ -0,0 +1,46 @@
#pragma once
#include <QThread>
#include <QDebug>
#include <QDateTime>
#include <opencv2/opencv.hpp>
#include <opencv2/imgproc/types_c.h>
#include "SyncQueue.h"
#include "ASyncQueue.h"
#include "common.h"
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 event_ok(int Num);
void event_ng(int Num);
#endif
public:
WorkThread(QObject* parent = 0) : QThread(parent)
{
}
~WorkThread();
void init(SyncQueue<std::pair<int, cv::Mat>>* image_ptr, ASyncQueue<bool>* result_ptr, int classid, int Num);
void start_work();
void stop();
protected:
void run();
public:
int local_camera_number;
int local_classid;
SyncQueue<std::pair<int, cv::Mat>>* local_g_image_queue;
ASyncQueue<bool>* local_g_result_queue;
bool b_quit;
long frame_total;
SysConf local_SysConf;
DisplayLabelConf local_DisplayLabelConf;
};

@ -0,0 +1,45 @@
#include "alarmdialog.hpp"
#include "AlarmInfo.h"
extern std::vector<AlarmInfo> 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("报警代码");
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();
}
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();
}

@ -0,0 +1,18 @@
#pragma once
#include <QDialog>
#include "ui_alarmdialog.h"
class AlarmDialog : public QDialog {
Q_OBJECT
public:
AlarmDialog(QWidget* parent = Q_NULLPTR);
~AlarmDialog();
private slots:
void on_pushButton_close_released();
void on_pushButton_clear_released();
private:
Ui::AlarmDialog ui;
};

@ -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;i<NumberOfSupportedCameras;i++)
for(int j=0;j<3;j++)
spinBox[i][j]->setValue(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;i<NumberOfSupportedCameras;i++)
for(int j=0;j<3;j++)
mat[i][j]=spinBox[i][j]->value();
emit sendMsgToDialogSetup(mat);
this->close();
}
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();
}

@ -0,0 +1,25 @@
#pragma once
#include <QDialog>
#include "ui_camera_glue.h"
#include "basecamera.h"
#include "common.h"
class camera_glue : public QDialog
{
Q_OBJECT
public:
camera_glue(QDialog* parent = Q_NULLPTR);
~camera_glue();
signals:
void sendMsgToDialogSetup(int ptr[][3]);
public slots:
void recMsgFromDialogSetup(int ptr[][3]);
void on_pushButton_take_released(void);
private:
Ui::camera_glue ui;
QSpinBox* spinBox[NumberOfSupportedCameras][3];
SysConf local_SysConf;
};

@ -0,0 +1,90 @@
#include "change_shift.h"
#include <common.h>
#include <dialogsetup.hpp>
extern SysConf g_sys_conf;
change_shift::change_shift(QDialog* parent)
: QDialog(parent)
{
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);
}
}
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;
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->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();
}
void change_shift::recMsgFromDialogSetup(QTime timeA, QTime timeB, QTime timeC)
{
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.C_hour->setValue(timeC.hour());
ui.C_minute->setValue(timeC.minute());
this->show();
}

@ -0,0 +1,27 @@
#pragma once
#include <QDialog>
#include "ui_change_shift.h"
#include "QtCore/qdatetime.h"
class change_shift : public QDialog
{
Q_OBJECT
public:
change_shift(QDialog* parent = Q_NULLPTR);
~change_shift();
private:
Ui::change_shift ui;
private slots:
void on_pushButton_apply_released();
public slots:
void recMsgFromDialogSetup(QTime timeA, QTime timeB, QTime timeC);
signals:
void sendMsgToDialogSetup(QTime timeA, QTime timeB, QTime timeC);
};

@ -0,0 +1,96 @@
#include "dialogin.hpp"
#include <QCryptographicHash>
#include <qdebug.h>
#include <qmessagebox.h>
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() {
}
void Dialogin::on_pushButton_close_released()
{
this->close();
}
void Dialogin::on_pushButton_clr_released()
{
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();
}
}
void Dialogin::on_pushButton_0_released()
{
m_pswd += "0";
ui.lineEdit->setText(ui.lineEdit->text() + "*");
}
void Dialogin::on_pushButton_1_released()
{
m_pswd += "1";
ui.lineEdit->setText(ui.lineEdit->text() + "*");
}
void Dialogin::on_pushButton_2_released()
{
m_pswd += "2";
ui.lineEdit->setText(ui.lineEdit->text() + "*");
}
void Dialogin::on_pushButton_3_released()
{
m_pswd += "3";
ui.lineEdit->setText(ui.lineEdit->text() + "*");
}
void Dialogin::on_pushButton_4_released()
{
m_pswd += "4";
ui.lineEdit->setText(ui.lineEdit->text() + "*");
}
void Dialogin::on_pushButton_5_released()
{
m_pswd += "5";
ui.lineEdit->setText(ui.lineEdit->text() + "*");
}
void Dialogin::on_pushButton_6_released()
{
m_pswd += "6";
ui.lineEdit->setText(ui.lineEdit->text() + "*");
}
void Dialogin::on_pushButton_7_released()
{
m_pswd += "7";
ui.lineEdit->setText(ui.lineEdit->text() + "*");
}
void Dialogin::on_pushButton_8_released()
{
m_pswd += "8";
ui.lineEdit->setText(ui.lineEdit->text() + "*");
}
void Dialogin::on_pushButton_9_released()
{
m_pswd += "9";
ui.lineEdit->setText(ui.lineEdit->text() + "*");
}

@ -0,0 +1,34 @@
#pragma once
#include <QDialog>
#include "ui_dialogin.h"
class Dialogin : public QDialog {
Q_OBJECT
signals:
void enter_op();
public:
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();
public:
QString m_pswd;
private:
Ui::Dialogin ui;
};

@ -0,0 +1,858 @@
#include "dialogsetup.hpp"
#include <qprocess.h>
#include <thread>
#include <qmessagebox.h>
#include <QCryptographicHash>
#include <QIntValidator>
#include "common.h"
#include <iostream>
#include <fstream>
#include <QFileDialog>
#include <QInputDialog>
#include "basecamera.h"
#include <windows.h> //用于显示桌面
#include <shldisp.h> //用于显示桌面
#include <QThread>
#include "Cleanthread.h"
extern ConfPath g_conf_path;
extern SysConf g_sys_conf; //系统配置参数
extern QString g_admin_pswd; //管理员密码
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; 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);
#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();
}
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();
}
void DialogSetup::onComboBoxSelect(int index) {
// 获取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();
}
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();
}
}
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();
}
void DialogSetup::on_pushButton_expo_released()
{
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;
}
}
void DialogSetup::on_checkBox_auto_work_clicked(bool checked)
{
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; 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);
}
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);
}
}
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);
}
}
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; 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();
}
void DialogSetup::on_pushButton_clear_pic_released()
{
QThread* handleThread = new QThread();
CleanWorkThread* cleanWorkThread = new CleanWorkThread();
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();
}
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;
}
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;
}
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;
}
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); // 在comboBox中显示文件路径
g_sys_conf.model_jpg_path = JpgPath; // 将选择的路径写入conf配置文件中
}
}
}
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();
}
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();
}
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();
}
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));
#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));
#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));
#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));
#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));
#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));
#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));
#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));
#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));
#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);
cfg_file.write(buf, strlen(buf));
sprintf(buf, "MonitorPort=%d\n", g_sys_conf.MonitorPort);
cfg_file.write(buf, strlen(buf));
memset(buf, 0, 256);
sprintf(buf, "TcpIP=%s\n", g_sys_conf.TcpIP.c_str());
cfg_file.write(buf, strlen(buf));
memset(buf, 0, 256);
cfg_file.write(buf, strlen(buf));
sprintf(buf, "TcpPort=%d\n", g_sys_conf.TcpPort);
cfg_file.write(buf, strlen(buf));
}
cfg_file.close();
}
#define InitPtrMatDef(a,b)\
lineEdit_expo_mat[a]=ui.lineEdit_expo_##b; \
lineEdit_gain_mat[a]=ui.lineEdit_gain_##b; \
lineEdit_filter_mat[a]=ui.lineEdit_filter_##b;
void DialogSetup::InitPtrMat()
{
#if defined(NumberOfSupportedCameras) && (NumberOfSupportedCameras>0)
InitPtrMatDef(0, 1);
#endif
#if defined(NumberOfSupportedCameras) && (NumberOfSupportedCameras>1)
InitPtrMatDef(1, 2);
#endif
#if defined(NumberOfSupportedCameras) && (NumberOfSupportedCameras>2)
InitPtrMatDef(2, 3);
#endif
#if defined(NumberOfSupportedCameras) && (NumberOfSupportedCameras>3)
InitPtrMatDef(3, 4);
#endif
#if defined(NumberOfSupportedCameras) && (NumberOfSupportedCameras>4)
InitPtrMatDef(4, 5);
#endif
#if defined(NumberOfSupportedCameras) && (NumberOfSupportedCameras>5)
InitPtrMatDef(5, 6);
#endif
#if defined(NumberOfSupportedCameras) && (NumberOfSupportedCameras>6)
InitPtrMatDef(6, 7);
#endif
#if defined(NumberOfSupportedCameras) && (NumberOfSupportedCameras>7)
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());//移动父窗口中心位置
emit sendMsgToConfig(g_sys_conf.no);
}
void DialogSetup::recMsgFromDialogConfig(int ptr[][3])
{
for (int i = 0; i < NumberOfSupportedCameras; i++)
for (int j = 0; j < 3; j++)
g_sys_conf.no[i][j] = ptr[i][j];
}
void DialogSetup::on_pushButton_change_released()
{
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();
}
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);
}
#ifdef __DEBUG
void DialogSetup::on_pushButton_testimg_released()
{
emit _testimg();
}
void DialogSetup::on_pushButton_testimgs_released()
{
emit _testimgs();
}
#endif

@ -0,0 +1,73 @@
#pragma once
#include <QDialog>
#include "ui_dialogsetup.h"
#include "basecamera.h"
#include <qdebug.h>
#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]);
#ifdef __DEBUG
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();
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 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();
#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();
public:
camera_glue* m_camera_glue = NULL;
change_shift* m_change_shift = NULL;
output_statistic* m_output_statistic = NULL;
private:
Ui::DialogSetup ui;
};

File diff suppressed because it is too large Load Diff

@ -0,0 +1,98 @@
#include "dialogsetuppasswd.hpp"
#include <QCryptographicHash>
#include <qdebug.h>
#include <qmessagebox.h>
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() {
}
void DialogSetupPasswd::on_pushButton_close_released()
{
this->close();
}
void DialogSetupPasswd::on_pushButton_clr_released()
{
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();
}
}
void DialogSetupPasswd::on_pushButton_0_released()
{
m_pswd += "0";
ui.lineEdit->setText(ui.lineEdit->text() + "*");
}
void DialogSetupPasswd::on_pushButton_1_released()
{
m_pswd += "1";
ui.lineEdit->setText(ui.lineEdit->text() + "*");
}
void DialogSetupPasswd::on_pushButton_2_released()
{
m_pswd += "2";
ui.lineEdit->setText(ui.lineEdit->text() + "*");
}
void DialogSetupPasswd::on_pushButton_3_released()
{
m_pswd += "3";
ui.lineEdit->setText(ui.lineEdit->text() + "*");
}
void DialogSetupPasswd::on_pushButton_4_released()
{
m_pswd += "4";
ui.lineEdit->setText(ui.lineEdit->text() + "*");
}
void DialogSetupPasswd::on_pushButton_5_released()
{
m_pswd += "5";
ui.lineEdit->setText(ui.lineEdit->text() + "*");
}
void DialogSetupPasswd::on_pushButton_6_released()
{
m_pswd += "6";
ui.lineEdit->setText(ui.lineEdit->text() + "*");
}
void DialogSetupPasswd::on_pushButton_7_released()
{
m_pswd += "7";
ui.lineEdit->setText(ui.lineEdit->text() + "*");
}
void DialogSetupPasswd::on_pushButton_8_released()
{
m_pswd += "8";
ui.lineEdit->setText(ui.lineEdit->text() + "*");
}
void DialogSetupPasswd::on_pushButton_9_released()
{
m_pswd += "9";
ui.lineEdit->setText(ui.lineEdit->text() + "*");
}

@ -0,0 +1,35 @@
#pragma once
#include <QDialog>
#include "ui_dialogsetuppasswd.h"
class DialogSetupPasswd : public QDialog {
Q_OBJECT
signals:
void enter_admin();
public:
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();
public:
QString m_pswd;
private:
Ui::DialogSetupPasswd ui;
};

@ -0,0 +1,69 @@
#include "output_statistic.h"
#include "QtCore\qfile.h"
#include "QtCore\qtextstream.h"
#include "exportData.h"
#include <map>
extern ConfPath g_conf_path;
#define output_init(a, b)\
textBrowser_mat[a] = ui.textBrowser_##b;
output_statistic::output_statistic(QDialog* parent)
: QDialog(parent)
{
ui.setupUi(this);
this->setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint);
#if defined(NumberOfSupportedCameras) && (NumberOfSupportedCameras > 0)
output_init(0, 1);
#endif
#if defined(NumberOfSupportedCameras) && (NumberOfSupportedCameras > 1)
output_init(1, 2);
#endif
#if defined(NumberOfSupportedCameras) && (NumberOfSupportedCameras > 2)
output_init(2, 3);
#endif
#if defined(NumberOfSupportedCameras) && (NumberOfSupportedCameras > 3)
output_init(3, 4);
#endif
#if defined(NumberOfSupportedCameras) && (NumberOfSupportedCameras > 4)
output_init(4, 5);
#endif
#if defined(NumberOfSupportedCameras) && (NumberOfSupportedCameras > 5)
output_init(5, 6);
#endif
#if defined(NumberOfSupportedCameras) && (NumberOfSupportedCameras > 6)
output_init(6, 7);
#endif
#if defined(NumberOfSupportedCameras) && (NumberOfSupportedCameras > 7)
output_init(7, 8);
#endif
}
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();
}

@ -0,0 +1,21 @@
#pragma once
#include <QDialog>
#include "common.h"
#include "ui_output_statistic.h"
class output_statistic : public QDialog
{
Q_OBJECT
public:
output_statistic(QDialog* parent = Q_NULLPTR);
~output_statistic();
private:
Ui::output_statistic ui;
QTextBrowser* textBrowser_mat[NumberOfSupportedCameras];
public slots:
void recMsgFromDialogSetup();
};

@ -0,0 +1,297 @@
#include "plcsetup.hpp"
#include "common.h"
#include <iostream>
#include <fstream>
#include <thread>
#include <qdebug.h>
#include <qlineedit.h>
#include <qmessagebox.h>
#include <QIntValidator>
#include "PLCDevice.h"
#define PLC_ITEM_FILE "plc.txt"
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");
}
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);
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);
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<QPushButton*>(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;
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<QPushButton*>(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<QPushButton*>(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;
}
}
}
}
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))));
}
}
}
}
void PlcSetup::on_toolButton_keyboard_released()
{
std::thread osk_thread = std::thread(task_osk_);
osk_thread.detach();
}
void PlcSetup::on_toolButton_close_released()
{
g_plc_dialog_open = false;
this->close();
}
void PlcSetup::handleTimeout()
{
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;
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<std::string> 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();
}
}

@ -0,0 +1,39 @@
#pragma once
#include <QDialog>
#include <QPushButton>
#include "ui_plcsetup.h"
#include "plc_item.h"
#include <iostream>
#include <vector>
#include <QTimer>
#include "modbus.h"
class QTimer;
class PlcSetup : public QDialog {
Q_OBJECT
public:
PlcSetup(QWidget* parent = Q_NULLPTR);
~PlcSetup();
QTimer* m_pTimer;
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 handleTimeout(); //窗口加载时执行一次,批处理读取所有地址
private:
Ui::PlcSetup ui;
std::vector<PlcItem> m_plc_items;
};

@ -1,45 +0,0 @@
#include "alarmdialog.hpp"
#include "AlarmInfo.h"
extern std::vector<AlarmInfo> 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("报警代码");
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();
}
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();
}

@ -1,18 +0,0 @@
#pragma once
#include <QDialog>
#include "ui_alarmdialog.h"
class AlarmDialog : public QDialog {
Q_OBJECT
public:
AlarmDialog(QWidget * parent = Q_NULLPTR);
~AlarmDialog();
private slots:
void on_pushButton_close_released();
void on_pushButton_clear_released();
private:
Ui::AlarmDialog ui;
};

@ -1,38 +1,37 @@
#include "alg_jd.h"
#include <direct.h> //所需的库文件
// Remove the bounding boxes with low confidence using non-maxima suppression
static void post_process(cv::Mat& frame, std::vector<cv::Mat>& outs, std::vector<std::pair<int, cv::Rect> > &results);
#include <direct.h> //所需的库文件
static void post_process_batch(std::vector<cv::Mat>& vec_frame, std::vector<cv::Mat>& outs, std::vector<std::vector<std::pair<int, cv::Rect> > > &vec_results);
// Get the names of the output layers
static std::vector<cv::String> getOutputsNames(const cv::dnn::Net& net);
// Draw the predicted bounding box
static void drawPred(int classId, float conf, int left, int top, int right, int bottom, cv::Mat& frame);
extern SysConf g_sys_conf;
// Initialize the parameters
static float confThreshold = 0.1; // 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
static std::vector<std::string> classes;
bool AlgJd::init(QString path_model, QString path_jpg)
bool AlgJd::init(QString model_path, QString model_name)
{
// Load names of classes
std::string classesFile = "../model/jd.names";
// Give the configuration and weight files for the model
cv::String modelConfiguration = "../model/jd.cfg";
std::string classesFile;
cv::String modelConfiguration;
cv::String modelWeights;
if (path_model.length() > 0) {
modelWeights = path_model.toStdString();
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";
image_path = model_path + "/" + "alg_jd.bmp";
}
else {
modelWeights = "../model/jd.weights";
modelWeights = "D:/model/jd.weights";
classesFile = "D:/model/jd.names";
// Give the configuration and weight files for the model
modelConfiguration = "D:/model/jd.cfg";
image_path = "D:/model/alg_jd.bmp";
}
std::ifstream classNamesFile(classesFile.c_str());
@ -42,8 +41,8 @@ bool AlgJd::init(QString path_model, QString path_jpg)
while (std::getline(classNamesFile, className))
classes.push_back(className);
}
else{
return false;
else {
return false;
}
// Load the network
@ -52,31 +51,32 @@ bool AlgJd::init(QString path_model, QString path_jpg)
net.setPreferableBackend(cv::dnn::DNN_BACKEND_CUDA);
net.setPreferableTarget(cv::dnn::DNN_TARGET_CUDA);
//cv::Mat image = cv::imread("alg_jd.jpg");
cv::Mat image;
if (path_jpg.length() > 0) {
image = cv::imread(path_jpg.toStdString());
//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());
}
else {
image = cv::imread("alg_jd.jpg");
}
//识别一张图测试模型是否正确并且完成GPU数据加载
if (!image.data) return false; //判断测试图片是否正常读取
std::vector<std::pair<int, cv::Rect> > results;
detect(image, image, results);
if (results.size() > 0)
return true; //检测到目标,则初始化成功
else
return false; //否则初始化失败
image = cv::imread("D:/Release/alg_jd.bmp");
}*/
//识别一张图测试模型是否正确并且完成GPU数据加载
if (!image.data) return false; //判断测试图片是否正常读取
std::vector<std::pair<int, cv::Rect> > 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<std::pair<int, cv::Rect> > results;
std::vector<std::pair<int, cv::Rect> > 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;
@ -86,39 +86,42 @@ bool AlgJd::test_detect_batcht(int shoot)
{
std::vector<cv::Mat> vec_in;
std::vector<cv::Mat> vec_out;
std::vector<std::vector<std::pair<int, cv::Rect> > > vec_results;
std::vector<std::vector<std::pair<int, cv::Rect>>> vec_results;
cv::Mat m1, m2, m3;
cv::Mat m4;
m1 = cv::Mat(544, 728, CV_8UC3, cv::Scalar(0, 0, 0));
m2 = cv::Mat(544, 728, CV_8UC3, cv::Scalar(0, 0, 0));
m3 = cv::Mat(544, 728, CV_8UC3, cv::Scalar(0, 0, 0));
m4 = cv::Mat(544, 728, CV_8UC3, cv::Scalar(0, 0, 0));
double t = (double)cv::getTickCount();
switch(shoot){
case 1:{
std::vector<std::pair<int, cv::Rect> > results;
detect(m1, m1, results);
break;
}
case 3:vec_in.push_back(m3);
case 2:vec_in.push_back(m2);
default:{
vec_in.push_back(m1);
detect_batch(vec_in, vec_out, vec_results);
}
switch (shoot) {
case 1: {
std::vector<std::pair<int, cv::Rect> > 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<std::pair<int, cv::Rect> > &results)
int AlgJd::detect(cv::Mat& _frame, cv::Mat& out, std::vector<std::pair<int, cv::Rect> >& 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);
@ -137,14 +140,28 @@ int AlgJd::detect(cv::Mat& _frame, cv::Mat &out, std::vector<std::pair<int, cv::
cv::Mat detectedFrame;
frame.convertTo(detectedFrame, CV_8U);
//show detectedFrame
out=detectedFrame.clone();
return results.size();
out = detectedFrame.clone();
return results.size();
}
void AlgJd::analyse(cv::Mat vec_in, std::vector<std::pair<int, cv::Rect> >& vec_results)
{
for (int i = 0; i < vec_results.size(); i++)
{
std::pair<int, cv::Rect> element;
cv::Rect TempRect = vec_results[i].second;
cv::Point position = cv::Point(TempRect.x + (TempRect.width / 2), TempRect.y + (TempRect.height / 2));
cv::Mat topography = vec_in(TempRect);
cv::imshow("analyse", topography);
cv::waitKey(1);
}
}
// Get the names of the output layers
static std::vector<cv::String> getOutputsNames(const cv::dnn::Net& net)
std::vector<cv::String> AlgJd::getOutputsNames(const cv::dnn::Net& net)
{
static std::vector<cv::String> names;
std::vector<cv::String> names;
if (names.empty())
{
//Get the indices of the output layers, i.e. the layers with unconnected outputs
@ -156,17 +173,16 @@ static std::vector<cv::String> 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;
}
static void post_process(cv::Mat& frame, std::vector<cv::Mat>& outs, std::vector<std::pair<int, cv::Rect> > &results)
void AlgJd::post_process(cv::Mat& frame, std::vector<cv::Mat>& outs, std::vector<std::pair<int, cv::Rect> >& results)
{
std::vector<int> classIds;
std::vector<float> confidences;
std::vector<cv::Rect> boxes;
std::vector < std::vector<int>> classIds(classes.size());
std::vector < std::vector<float>> confidences(classes.size());
std::vector < std::vector<cv::Rect>> boxes(classes.size());
for (size_t i = 0; i < outs.size(); ++i)
{
// Scan through all the bounding boxes output from the network and keep only the
@ -190,9 +206,9 @@ static void post_process(cv::Mat& frame, std::vector<cv::Mat>& outs, std::vector
int left = centerX - width / 2;
int top = centerY - height / 2;
classIds.push_back(classIdPoint.x);
confidences.push_back((float)confidence);
boxes.push_back(cv::Rect(left, top, width, height));
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));
}
}
}
@ -200,34 +216,37 @@ static void post_process(cv::Mat& frame, std::vector<cv::Mat>& outs, std::vector
// Perform non maximum suppression to eliminate redundant overlapping boxes with
// lower confidences
std::vector<int> indices;
cv::dnn::NMSBoxes(boxes, confidences, confThreshold, nmsThreshold, indices);
for (size_t i = 0; i < indices.size(); ++i)
for (size_t i = 0; i < classes.size(); ++i)
{
int idx = indices[i];
cv::Rect box = boxes[idx];
drawPred(classIds[idx], confidences[idx], box.x, box.y,
box.x + box.width, box.y + box.height, frame);
results.push_back(std::make_pair(classIds[idx], box));
std::vector<int> indices;
cv::dnn::NMSBoxes(boxes[i], confidences[i], confThreshold, nmsThreshold, indices);
for (size_t j = 0; j < indices.size(); ++j)
{
int idx = indices[j];
cv::Rect box = boxes[i][idx];
drawPred(classIds[i][idx], confidences[i][idx], box.x, box.y,
box.x + box.width, box.y + box.height, frame);
results.push_back(std::make_pair(classIds[i][idx], box));
}
}
}
// Draw the predicted bounding box
static void drawPred(int classId, float conf, int left, int top, int right, int bottom, cv::Mat& frame)
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());
@ -235,115 +254,119 @@ static void drawPred(int classId, float conf, int left, int top, int right, int
}
else
{
std::cout<<"classes is empty..."<<std::endl;
std::cout << "classes is empty..." << std::endl;
}
//Display the label at the top of the bounding box
int baseLine;
cv::Size labelSize = cv::getTextSize(label, cv::FONT_HERSHEY_SIMPLEX, 1, 1, &baseLine);
top = std::max(top, labelSize.height);
cv::putText(frame, label, cv::Point(left, top-5), cv::FONT_HERSHEY_SIMPLEX, 0.8, color, 1);
cv::putText(frame, label, cv::Point(left, top - 5), cv::FONT_HERSHEY_SIMPLEX, 0.8, color, 1);
}
void AlgJd::detect_batch(std::vector<cv::Mat>& vec_in, std::vector<cv::Mat> &vec_out, std::vector<std::vector<std::pair<int, cv::Rect> > > &vec_results)
void AlgJd::detect_batch(std::vector<cv::Mat>& vec_in, std::vector<cv::Mat>& vec_out, std::vector<std::vector<std::pair<int, cv::Rect> > >& vec_results)
{
cv::Mat blobs;
cv::Mat blobs;
std::vector<cv::Mat> 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);
// Runs the forward pass to get output of the output layers
std::vector<cv::Mat> outs;
net.forward(outs, getOutputsNames(net));
//Sets the input to the network
net.setInput(blobs);
for (int i = 0; i < vec_in.size(); i++)
{
image.push_back(vec_in[i].clone());
}
// Runs the forward pass to get output of the output layers
std::vector<cv::Mat> outs;
net.forward(outs, getOutputsNames(net));
// Remove the bounding boxes with low confidence
post_process_batch(image, outs, vec_results);
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);
// 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);
}
}
static void post_process_batch(std::vector<cv::Mat>& vec_frame, std::vector<cv::Mat>& outs, std::vector<std::vector<std::pair<int, cv::Rect> > > &vec_results)
void AlgJd::post_process_batch(std::vector<cv::Mat>& vec_frame, std::vector<cv::Mat>& outs, std::vector<std::vector<std::pair<int, cv::Rect> > >& vec_results)
{
int batch = vec_frame.size();
for (int k = 0; k < batch; k++)
{
std::vector<int> classIds;
std::vector<float> confidences;
std::vector<cv::Rect> boxes;
//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.push_back(classIdPoint.x);
confidences.push_back((float)confidence);
boxes.push_back(cv::Rect(left, top, width, height));
}
}
}
// Perform non maximum suppression to eliminate redundant overlapping boxes with
// lower confidences
std::vector<int> indices;
cv::dnn::NMSBoxes(boxes, confidences, confThreshold, nmsThreshold, indices);
std::vector<std::pair<int, cv::Rect> > results;
for (size_t i = 0; i < indices.size(); ++i)
{
int idx = indices[i];
cv::Rect box = boxes[idx];
//识别框宽度大于15显示识别小于认为无胶点NG处理
if (box.width > 15)
int batch = vec_frame.size();
double confidence;///
for (int k = 0; k < batch; k++)
{
std::vector < std::vector<int>> classIds(classes.size());
std::vector < std::vector<float>> confidences(classes.size());
std::vector < std::vector<cv::Rect>> 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)
{
drawPred(classIds[idx], confidences[idx], box.x, box.y,
box.x + box.width, box.y + box.height, vec_frame[k]);
results.push_back(std::make_pair(classIds[idx], box));
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));
}
}
}
vec_results.push_back(results);
}
}
std::vector<std::pair<int, cv::Rect> > results;
// Perform non maximum suppression to eliminate redundant overlapping boxes with
// lower confidences
for (size_t i = 0; i < classes.size(); ++i)
{
std::vector<int> indices;
cv::dnn::NMSBoxes(boxes[i], confidences[i], confThreshold, nmsThreshold, indices);
for (size_t j = 0; j < indices.size(); ++j)
{
int idx = indices[j];
cv::Rect box = boxes[i][idx];
if (confidences[i][idx] > g_sys_conf.ConfThreshold * 0.01)///识别度低于阈值NG处理
{
if (box.width > 15)
{//识别框宽度大于15显示识别小于认为无胶点NG处理
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);
}
}

@ -11,14 +11,25 @@
#include "common.h"
class AlgJd
{
public:
bool init(QString path_model, QString path_jpg);
bool test_detect();
bool test_detect_batcht(int shoot);
int detect(cv::Mat& in, cv::Mat &out, std::vector<std::pair<int, cv::Rect> > &results);
void detect_batch(std::vector<cv::Mat>& vec_in, std::vector<cv::Mat> &vec_out, std::vector<std::vector<std::pair<int, cv::Rect> > > &vec_results);
private:
cv::dnn::Net net;
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<std::pair<int, cv::Rect> >& results);
// Remove the bounding boxes with low confidence using non-maxima suppression
void post_process(cv::Mat& frame, std::vector<cv::Mat>& outs, std::vector<std::pair<int, cv::Rect> >& results);
void CircleImagePro(cv::Mat src, cv::Mat dst, std::vector<float> radius);
void detect_batch(std::vector<cv::Mat>& vec_in, std::vector<cv::Mat>& vec_out, std::vector<std::vector<std::pair<int, cv::Rect> > >& vec_results);
// Remove the bounding boxes with low confidence using non-maxima suppression
void post_process_batch(std::vector<cv::Mat>& vec_frame, std::vector<cv::Mat>& outs, std::vector<std::vector<std::pair<int, cv::Rect> > >& vec_results);
void analyse(cv::Mat vec_in, std::vector<std::pair<int, cv::Rect> >& vec_results);
// Get the names of the output layers
std::vector<cv::String> 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<std::string> classes;
};
#endif //end of _CIGARETTE_JD

@ -0,0 +1,517 @@
#include "alg_jd_ng.h"
#include <direct.h> //所需的库文件
extern SysConf g_sys_conf;
// Initialize the parameters
static float 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
static std::vector<std::string> classes;
bool AlgJd_ng::init_ng(QString model_path, QString model_name)
{
// Load names of classes
std::string classesFile;
cv::String modelConfiguration;
cv::String modelWeights;
QString image_path;
modelWeights = model_path.toStdString() + "/" + model_name.toStdString();
modelConfiguration = model_path.toStdString() + "/jd_ng.cfg";
classesFile = model_path.toStdString() + "/jd_ng.names";
image_path = model_path + "/" + "alg_jd_ng.bmp";
std::ifstream classNamesFile(classesFile.c_str());
if (classNamesFile.is_open())
{
std::string className = "";
while (std::getline(classNamesFile, className))
classes.push_back(className);
}
else{
return false;
}
// Load the network
net_ng = cv::dnn::readNetFromDarknet(modelConfiguration, modelWeights);
net_ng.setPreferableBackend(cv::dnn::DNN_BACKEND_CUDA);
net_ng.setPreferableTarget(cv::dnn::DNN_TARGET_CUDA);
//cv::Mat image = cv::imread("alg_jd.bmp");
cv::Mat image = cv::imread(image_path.toStdString());
//识别一张图测试模型是否正确并且完成GPU数据加载
if (!image.data) return false; //判断测试图片是否正常读取
std::vector<std::pair<int, cv::Rect> > results;
detect_ng(image, image, results);
if (results.size() > 0)
return true; //检测到目标,则初始化成功
else
return false; //否则初始化失败
}
bool AlgJd_ng::test_detect_ng()
{
cv::Mat m1;
m1 = cv::Mat(544, 728, CV_8UC3, cv::Scalar(0, 0, 0));
std::vector<std::pair<int, cv::Rect> > results;
double t = (double)cv::getTickCount();
detect_ng(m1, m1, results);
t = ((double)cv::getTickCount() - t) / cv::getTickFrequency();
DEBUG(" test_detect time process:%f\n", t);
return true;
}
bool AlgJd_ng::test_detect_batcht_ng(int shoot)
{
std::vector<cv::Mat> vec_in;
std::vector<cv::Mat> vec_out;
std::vector<std::vector<std::pair<int, cv::Rect> > > vec_results;
cv::Mat m1, m2, m3;
m1 = cv::Mat(544, 728, CV_8UC3, cv::Scalar(0, 0, 0));
m2 = cv::Mat(544, 728, CV_8UC3, cv::Scalar(0, 0, 0));
m3 = cv::Mat(544, 728, CV_8UC3, cv::Scalar(0, 0, 0));
double t = (double)cv::getTickCount();
switch(shoot){
case 1:{
std::vector<std::pair<int, cv::Rect> > results;
detect_ng(m1, m1, results);
break;
}
case 3:vec_in.push_back(m3);
case 2:vec_in.push_back(m2);
default:{
vec_in.push_back(m1);
detect_batch_ng(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_ng::detect_ng(cv::Mat& _frame, cv::Mat &out, std::vector<std::pair<int, cv::Rect> > &results)
{
cv::Mat frame = _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);
//Sets the input to the network
net_ng.setInput(blob);
// Runs the forward pass to get output of the output layers
std::vector<cv::Mat> outs;
net_ng.forward(outs, getOutputsNames_ng(net_ng));
// Remove the bounding boxes with low confidence
post_process_ng(frame, outs, results);
// Write the frame with the detection boxes
cv::Mat detectedFrame;
frame.convertTo(detectedFrame, CV_8U);
//show detectedFrame
out=detectedFrame.clone();
return results.size();
}
int AlgJd_ng::detect_ng(cv::Mat& _frame, cv::Mat& draw_frame, cv::Mat& out, std::vector<std::pair<int, cv::Rect>>& results)
{
cv::Mat frame = _frame.clone();
// Process frames.
// Create a 4D blob from a frame.
// 创建4D的blob用于网络输入
cv::Mat blob;
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_ng.setInput(blob);
// Runs the forward pass to get output of the output layers
std::vector<cv::Mat> outs;
net_ng.forward(outs, getOutputsNames_ng(net_ng));
// Remove the bounding boxes with low confidence
// 删除低置信度的边界框
post_process_ng(draw_frame, outs, results);
// Write the frame with the detection boxes
cv::Mat detectedFrame;
draw_frame.convertTo(detectedFrame, CV_8U);
//show detectedFrame
out = detectedFrame.clone();
return results.size();
}
void AlgJd_ng::CircleImagePro_ng(cv::Mat src, cv::Mat dst, std::vector<float> radius) {
QStringList TestData;
src.copyTo(dst);
float c = float(20.5) / float(68.9);
std::vector<std::vector<cv::Point>> contours;
// 图像预处理
cv::Mat img;
cv::cvtColor(dst, img, cv::COLOR_BGR2GRAY);
GaussianBlur(img, img, cv::Size(3, 3), 1);
Canny(img, img, 50, 150, 3);
imshow("img", img);
cv::Mat kernel = cv::getStructuringElement(cv::MORPH_RECT, cv::Size(3, 3)); // 获取卷积核
dilate(img, img, kernel, cv::Point(-1, -1), 2);
findContours(img, contours, cv::RETR_EXTERNAL, cv::CHAIN_APPROX_SIMPLE);
img.release();
std::vector<cv::Point2f> center(contours.size());
std::vector<float> rad(contours.size());
if (contours.size() == 0) {
std::cout << "未找到检测物" << std::endl;
return;
}
for (size_t i = 0; i < contours.size(); ++i) {
minEnclosingCircle(contours[i], center[i], rad[i]);
radius.push_back(rad[i] * c);
}
for (size_t j = 0; j < center.size(); ++j) {
std::string str = "radius: ";
std::string str1;
float r = 0.0;
circle(dst, center[j], rad[j], cv::Scalar(0, 0, 255), 1);
r = rad[j] * c;
str1 = format("%.4f", r);
str.insert(str.end(), str1.begin(), str1.end());
TestData.append(QString::fromStdString(str));
cv::imshow("dst", dst);
cv::putText(dst, str, center[j], 1, 2, cv::Scalar(0, 255, 0), 2, 8);
cv::waitKey(1);
}
TestData.clear();
}
void AlgJd_ng::analyse_ng(cv::Mat vec_in, std::vector<std::pair<int, cv::Rect>>& vec_results)
{
bool IsNG = false;
std::vector<cv::Rect> vec_jd_results; // 0 胶点
std::vector<cv::Rect> vec_kz_results; // 1 卡纸距离
for (int i = 0; i < vec_results.size(); i++)
{
if (vec_results[i].first == 0) // jd
{
vec_jd_results.push_back(vec_results[i].second);
}
else if (vec_results[i].first == 1) // 卡纸距离
{
vec_kz_results.push_back(vec_results[i].second);
}
}
std::sort(vec_jd_results.begin(), vec_jd_results.end(), sort_rect_by_y_center_ng);//升序排列,//jinhuan+
//jinhuan+
if (vec_jd_results.size() && vec_kz_results.size())
{
//从上往下第一个胶点的中心y值
int top_jd_y = vec_jd_results[0].y + vec_jd_results[0].height / 2;
//从上往下最后一个胶点的中心y值
int bottom_jd_y = vec_jd_results[vec_jd_results.size()-1].y + vec_jd_results[vec_jd_results.size()-1].height / 2;
//卡纸的上边沿y值
int top_kz_y = vec_kz_results[0].tl().y;
//卡纸的下边沿y值
int bottom_kz_y = vec_kz_results[0].br().y;
//if(abs(top_jd_y- top_kz_y)>50);//50个像素
//if (abs(bottom_kz_y - bottom_jd_y)>40);//40个像素
} else {
IsNG = true;//卡纸和胶点数量不够
}
//if (vec_kz_results.size() != 1) {//卡纸有褶皱
// IsNG = true;
//}
//jinhuan-
cv::waitKey(1);
}
// Get the names of the output layers
std::vector<cv::String> AlgJd_ng::getOutputsNames_ng(const cv::dnn::Net& net)
{
std::vector<cv::String> names;
if (names.empty())
{
//Get the indices of the output layers, i.e. the layers with unconnected outputs
std::vector<int> outLayers = net.getUnconnectedOutLayers();
//get the names of all the layers in the network
std::vector<cv::String> layersNames = net.getLayerNames();
// 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];
}
return names;
}
void AlgJd_ng::post_process_ng(cv::Mat& frame, std::vector<cv::Mat>& outs, std::vector<std::pair<int, cv::Rect> > &results)
{
std::vector < std::vector<int>> classIds(classes.size());
std::vector < std::vector<float>> confidences(classes.size());
std::vector < std::vector<cv::Rect>> boxes(classes.size());
for (size_t i = 0; i < outs.size(); ++i)
{
// 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
// with the highest score for the box.
// 得到每个输出的数据
float* data = (float*)outs[i].data;
for (int j = 0; j < outs[i].rows; ++j, data += outs[i].cols)
{
// 得到每个输出的所有类别的分数
cv::Mat scores = outs[i].row(j).colRange(5, outs[i].cols);
cv::Point classIdPoint;
double confidence;
// Get the value and location of the maximum score
cv::minMaxLoc(scores, 0, &confidence, 0, &classIdPoint);
//if (confidence > g_sys_conf.ConfThresholds[classIdPoint.x]*0.0001)
if (confidence > confThreshold)
{
int centerX = (int)(data[0] * frame.cols);
int centerY = (int)(data[1] * frame.rows);
int width = (int)(data[2] * frame.cols);
int height = (int)(data[3] * frame.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));
}
}
}
// Perform non maximum suppression to eliminate redundant overlapping boxes with
// lower confidences
for (size_t i = 0; i < classes.size(); ++i)
{
std::vector<int> indices;
cv::dnn::NMSBoxes(boxes[i], confidences[i], confThreshold, nmsThreshold, indices);
for (size_t j = 0; j < indices.size(); ++j)
{
int idx = indices[j];
cv::Rect box = boxes[i][idx];
//if (classIds[i][idx] == 2) continue;
//else if (classIds[i][idx] == 3) continue;
drawPred_ng(classIds[i][idx], confidences[i][idx], box.x, box.y,
box.x + box.width, box.y + box.height, frame);
results.push_back(std::make_pair(classIds[i][idx], box));
}
}
}
// Draw the predicted bounding box
void AlgJd_ng::drawPred_ng(int classId, float conf, int left, int top, int right, int bottom, cv::Mat& frame)
{
cv::Scalar color;
if (classId == 0) //jd
color = cv::Scalar(0, 0, 255); // 绿色
else if (classId == 1) // kz
color = cv::Scalar(0, 255, 0); //
else if (classId == 2) // bm
color = cv::Scalar(0, 255, 0);
else if (classId == 3) // kzx
color = cv::Scalar(0, 255, 0);
else
color = cv::Scalar(255, 255, 255); // 白色
//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));///
if (!classes.empty())
{
CV_Assert(classId < (int)classes.size());
label = classes[classId] + ": " + label;
}
else
{
std::cout<<"classes is empty..."<<std::endl;
}
//Display the label at the top of the bounding box
int baseLine;
cv::Size labelSize = cv::getTextSize(label, cv::FONT_HERSHEY_SIMPLEX, 1, 1, &baseLine);
top = std::max(top, labelSize.height);
cv::putText(frame, label, cv::Point(left, top-5), cv::FONT_HERSHEY_SIMPLEX, 0.8, color, 1);
}
void AlgJd_ng::detect_batch_ng(std::vector<cv::Mat>& vec_in, std::vector<cv::Mat> &vec_out, std::vector<std::vector<std::pair<int, cv::Rect>>> &vec_results)
{
cv::Mat blobs;
std::vector<cv::Mat> 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_ng.setInput(blobs);
// Runs the forward pass to get output of the output layers
std::vector<cv::Mat> outs;
net_ng.forward(outs, getOutputsNames_ng(net_ng));
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_ng(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);
}
}
void AlgJd_ng::detect_batch_ng(std::vector<cv::Mat>& vec_in, std::vector<cv::Mat>& transits, std::vector<cv::Mat>& vec_out, std::vector<std::vector<std::pair<int, cv::Rect> > >& vec_results)
{
cv::Mat blobs;
//std::vector<cv::Mat> image= transits;
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_ng.setInput(blobs);
// Runs the forward pass to get output of the output layers
std::vector<cv::Mat> outs;
net_ng.forward(outs, getOutputsNames_ng(net_ng));
//for (int i = 0; i < vec_in.size(); i++)
//{
// //image.push_back(vec_in[i].clone());
// transits.push_back(vec_in[i].clone());
//}
// Remove the bounding boxes with low confidence
//post_process_batch_ng(image, outs, vec_results);
post_process_batch_ng(transits, 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);
transits[i].convertTo(detectedFrame, CV_8U);
out = detectedFrame.clone();
vec_out.push_back(out);
}
}
void AlgJd_ng::post_process_batch_ng(std::vector<cv::Mat>& vec_frame, std::vector<cv::Mat>& outs, std::vector<std::vector<std::pair<int, cv::Rect> > > &vec_results)
{
int batch = vec_frame.size();
double confidence;///
for (int k = 0; k < batch; k++)
{
std::vector < std::vector<int>> classIds(classes.size());
std::vector < std::vector<float>> confidences(classes.size());
std::vector < std::vector<cv::Rect>> 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 > g_sys_conf.ConfThresholds[classIdPoint.x]*0.0001)
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<std::pair<int, cv::Rect> > results;
// Perform non maximum suppression to eliminate redundant overlapping boxes with
// lower confidences
for (size_t i = 0; i < classes.size(); ++i)
{
std::vector<int> indices;
cv::dnn::NMSBoxes(boxes[i], confidences[i], confThreshold, nmsThreshold, indices);
for (size_t j = 0; j < indices.size(); ++j)
{
int idx = indices[j];
cv::Rect box = boxes[i][idx];
drawPred_ng(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);
}
}
//jinhuan+
bool sort_rect_by_x_center_ng(cv::Rect r1, cv::Rect r2)
{
return (r1.x + r1.width / 2) < (r2.x + r2.width / 2);
}
bool sort_rect_by_y_center_ng(cv::Rect r1, cv::Rect r2)
{
return (r1.y + r1.height / 2) < (r2.y + r2.height / 2);
}
bool sort_rect_by_height_ng(cv::Rect r1, cv::Rect r2)
{
return (r1.height) < (r2.height);
}
bool sort_rect_by_width_ng(cv::Rect r1, cv::Rect r2)
{
return (r1.width) < (r2.width);
}
//jinhuan-

@ -0,0 +1,42 @@
#ifndef _CIGARETTE_JD_ng
#define _CIGARETTE_JD_ng
#include <opencv2/opencv.hpp>
#include <opencv2/dnn.hpp>
#include <opencv2/dnn/shape_utils.hpp>
#include <opencv2/imgproc.hpp>
#include <opencv2/highgui.hpp>
#include <iostream>
#include <fstream>
#include "common.h"
class AlgJd_ng
{
public:
bool init_ng(QString model_path, QString model_name);
bool test_detect_ng();
bool test_detect_batcht_ng(int shoot);
int detect_ng(cv::Mat& in, cv::Mat &draw_frame, cv::Mat &out, std::vector<std::pair<int, cv::Rect>> &results);
int detect_ng(cv::Mat& in, cv::Mat &out, std::vector<std::pair<int, cv::Rect> > &results);
// Remove the bounding boxes with low confidence using non-maxima suppression
void post_process_ng(cv::Mat& frame, std::vector<cv::Mat>& outs, std::vector<std::pair<int, cv::Rect>> &results);
void CircleImagePro_ng(cv::Mat src, cv::Mat dst, std::vector<float> radius);
void detect_batch_ng(std::vector<cv::Mat>& vec_in, std::vector<cv::Mat> &vec_out, std::vector<std::vector<std::pair<int, cv::Rect> > > &vec_results);
void detect_batch_ng(std::vector<cv::Mat>& vec_in, std::vector<cv::Mat> &transits, std::vector<cv::Mat> &vec_out, std::vector<std::vector<std::pair<int, cv::Rect>>> &vec_results);
// Remove the bounding boxes with low confidence using non-maxima suppression
void post_process_batch_ng(std::vector<cv::Mat>& vec_frame, std::vector<cv::Mat>& outs, std::vector<std::vector<std::pair<int, cv::Rect>>> &vec_results);
void analyse_ng(cv::Mat vec_in, std::vector<std::pair<int, cv::Rect> > & vec_results);
// Get the names of the output layers
std::vector<cv::String> getOutputsNames_ng(const cv::dnn::Net& net);
// Draw the predicted bounding box
void drawPred_ng(int classId, float conf, int left, int top, int right, int bottom, cv::Mat& frame);
private:
cv::dnn::Net net_ng;
std::vector<std::string> classes_ng;
};
//jinhuan+
bool sort_rect_by_x_center_ng(cv::Rect r1, cv::Rect r2);
bool sort_rect_by_y_center_ng(cv::Rect r1, cv::Rect r2);
bool sort_rect_by_height_ng(cv::Rect r1, cv::Rect r2);
bool sort_rect_by_width_ng(cv::Rect r1, cv::Rect r2);
//jinhuan-
#endif //end of _CIGARETTE_JD

@ -3,11 +3,11 @@
#include <iostream>
#include <thread>
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();
}
return devMgr.deviceCount();
}

@ -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;
};
static int Enumerate();
public:
static mvIMPACT::acquire::DeviceManager devMgr;
static bool license_pass;
};

@ -2,26 +2,26 @@
#include <opencv2/opencv.hpp>
#define NumberOfSupportedCameras 8
#define NumberOfSupportedCameras 4
#define EdgeEvent 1
#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:
};

@ -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;
}
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;
}

@ -12,14 +12,21 @@
#define BaslerClassID 0x02
#define c_maxCamerasToUse (size_t)2
class BaslerCamera: public BaseCamera
//5:灰色
//6:黑色
//1:红色
//2:黄色
//3:白色
//4:绿色
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;
};

@ -1,25 +0,0 @@
#pragma once
#include <QDialog>
#include "ui_camera_glue.h"
#include "basecamera.h"
#include "common.h"
class camera_glue : public QDialog
{
Q_OBJECT
public:
camera_glue(QDialog *parent = Q_NULLPTR);
~camera_glue();
signals:
void sendMsgToDialogSetup(int ptr[][3]);
public slots:
void recMsgFromDialogSetup(int ptr[][3]);
void on_pushButton_take_released(void);
private:
Ui::camera_glue ui;
QSpinBox *spinBox[NumberOfSupportedCameras][3];
SysConf local_SysConf;
};

@ -1,88 +0,0 @@
#include "change_shift.h"
#include <common.h>
#include <dialogsetup.hpp>
extern SysConf g_sys_conf;
change_shift::change_shift(QDialog *parent)
: QDialog(parent)
{
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);
}
}
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;
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.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);
}
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.B_hour->setValue(timeB.hour());
ui.B_minute->setValue(timeB.minute());
ui.C_hour->setValue(timeC.hour());
ui.C_minute->setValue(timeC.minute());
this->show();
}

@ -1,27 +0,0 @@
#pragma once
#include <QDialog>
#include "ui_change_shift.h"
#include "QtCore/qdatetime.h"
class change_shift : public QDialog
{
Q_OBJECT
public:
change_shift(QDialog *parent = Q_NULLPTR);
~change_shift();
private:
Ui::change_shift ui;
private slots:
void on_pushButton_apply_released();
public slots:
void recMsgFromDialogSetup(QTime timeA, QTime timeB, QTime timeC);
signals:
void sendMsgToDialogSetup(QTime timeA, QTime timeB, QTime timeC);
};

File diff suppressed because it is too large Load Diff

@ -10,7 +10,11 @@
#include "balluffcamera.h"
#include "baslercamera.h"
#include "hikcamera.h"
#ifdef SYNC_CAMERA
#include "SyncWorkThread.h"
#else
#include "workthread.h"
#endif
#include "db_label.h"
#include "common.h"
#include "modbus.h"
@ -29,7 +33,9 @@
#include "Logthread.h"
#include "threadSend.h"
#include "threadReceive.h"
#include "threadSendTCP.h"
#include "Cleanthread.h"
#include "threadSendMqtt.h"
#include <QtWidgets/QMainWindow>
#include <QTimer>
@ -51,146 +57,188 @@ 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_sys_config(SysConf &conf);
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> &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_lock_released();
void on_btn_setup_released();
void on_checkBox_debug_clicked(bool checked);
void on_checkBox_unkick_clicked(bool checked);
void on_toolButton_plc_released();
void on_toolButton_alarm_released();
void on_pushButton_clear_released();
void enable_shift();
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 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();
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>& 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();
#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();
#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<PlcItem> m_plc_items;
Ui::CigaretteClass ui;
DialogSetupPasswd* dialog_setup_passwd;
Dialogin* dialogin;
DialogSetup* dialog_setup;
PlcSetup* dialog_plc_setup;
std::vector<PlcItem> 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];
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];
WorkThread work_thread[NumberOfSupportedCameras];
DebugThread debug_thread[NumberOfSupportedCameras];
SaveThread saveThread;
void record_output_statistic(qint64 cur_quantity, int shift);
QTimer *m_pTimer;
QTimer *m_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;
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];
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];
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; //管理员权限剩余时间
#ifdef CLEAR_THREAD
QTimer* clean_pTimer; //定时清理任务
#endif
#ifdef __MQTTSend
QTimer* mqtt_pTimer; //定时MQTT发送
#endif
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];
private:
#ifdef SYNC_CAMERA
SyncWorkThread sync_work_thread;
#else
WorkThread work_thread[NumberOfSupportedCameras];
#endif
DebugThread debug_thread[NumberOfSupportedCameras];
SaveThread saveThread;
#ifdef __UDPSend
threadSend sThread;
threadReceive rThread;
#endif
#ifdef __TCPSend
threadSendTCP TcpSendThread;
#endif
#ifdef __MQTTSend
threadSendMqtt MqttSendThread;
#endif
public slots:
void CleanThreadStartAuto();
void recMsgFromUdp(QString data);
//void ClogThreadStart();
public slots:
void CleanThreadStartAuto();
#ifdef __UDPSend
void recMsgFromUdp(QString data);
#endif
#ifdef __MQTTSend
void MqttMsgSend();
#endif
signals:
void sengMsgToClog(QString);
#ifdef LOG_RECORD
void sengMsgToClog(QString);
#endif
void sendMsgToExportData();
};
#endif // CIGARETTE_H

@ -1164,9 +1164,9 @@
<widget class="QLabel" name="label_cap_speed_1">
<property name="geometry">
<rect>
<x>80</x>
<x>70</x>
<y>20</y>
<width>50</width>
<width>71</width>
<height>20</height>
</rect>
</property>
@ -1188,7 +1188,7 @@
<rect>
<x>220</x>
<y>20</y>
<width>50</width>
<width>61</width>
<height>20</height>
</rect>
</property>
@ -1248,7 +1248,7 @@
<rect>
<x>360</x>
<y>20</y>
<width>50</width>
<width>61</width>
<height>20</height>
</rect>
</property>
@ -1552,10 +1552,10 @@
<widget class="QLabel" name="label_17">
<property name="geometry">
<rect>
<x>880</x>
<x>830</x>
<y>10</y>
<width>191</width>
<height>21</height>
<width>210</width>
<height>20</height>
</rect>
</property>
<property name="font">
@ -1570,16 +1570,16 @@
<string notr="true">color:white</string>
</property>
<property name="text">
<string>Tel:87907256(0532)</string>
<string>&lt;html&gt;&lt;head/&gt;&lt;body&gt;&lt;p&gt; Tel:87907256(0532)&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</string>
</property>
</widget>
<widget class="QLabel" name="label_18">
<property name="geometry">
<rect>
<x>1080</x>
<x>1060</x>
<y>10</y>
<width>81</width>
<height>21</height>
<width>80</width>
<height>20</height>
</rect>
</property>
<property name="font">
@ -1600,10 +1600,10 @@
<widget class="QLabel" name="label_cur_time">
<property name="geometry">
<rect>
<x>920</x>
<y>30</y>
<width>211</width>
<height>31</height>
<x>830</x>
<y>35</y>
<width>210</width>
<height>20</height>
</rect>
</property>
<property name="font">
@ -1618,7 +1618,7 @@
<string notr="true">color:white</string>
</property>
<property name="text">
<string>2020-10-10 13:15:39</string>
<string>&lt;html&gt;&lt;head/&gt;&lt;body&gt;&lt;p&gt;2020-10-10 13:15:39&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</string>
</property>
<property name="alignment">
<set>Qt::AlignCenter</set>
@ -1911,7 +1911,7 @@
<rect>
<x>80</x>
<y>20</y>
<width>50</width>
<width>61</width>
<height>20</height>
</rect>
</property>
@ -1933,7 +1933,7 @@
<rect>
<x>220</x>
<y>20</y>
<width>50</width>
<width>61</width>
<height>20</height>
</rect>
</property>
@ -1993,7 +1993,7 @@
<rect>
<x>360</x>
<y>20</y>
<width>50</width>
<width>61</width>
<height>20</height>
</rect>
</property>
@ -2297,9 +2297,9 @@
<widget class="QLabel" name="label_cap_speed_2">
<property name="geometry">
<rect>
<x>80</x>
<x>70</x>
<y>20</y>
<width>50</width>
<width>71</width>
<height>20</height>
</rect>
</property>
@ -2321,7 +2321,7 @@
<rect>
<x>220</x>
<y>20</y>
<width>50</width>
<width>61</width>
<height>20</height>
</rect>
</property>
@ -2381,7 +2381,7 @@
<rect>
<x>360</x>
<y>20</y>
<width>50</width>
<width>61</width>
<height>20</height>
</rect>
</property>
@ -2578,9 +2578,9 @@
<widget class="QLabel" name="label_cap_speed_3">
<property name="geometry">
<rect>
<x>80</x>
<x>70</x>
<y>20</y>
<width>50</width>
<width>71</width>
<height>20</height>
</rect>
</property>
@ -2602,7 +2602,7 @@
<rect>
<x>220</x>
<y>20</y>
<width>50</width>
<width>61</width>
<height>20</height>
</rect>
</property>
@ -2662,7 +2662,7 @@
<rect>
<x>360</x>
<y>20</y>
<width>50</width>
<width>61</width>
<height>20</height>
</rect>
</property>
@ -3194,7 +3194,7 @@
<rect>
<x>80</x>
<y>20</y>
<width>50</width>
<width>61</width>
<height>20</height>
</rect>
</property>
@ -3216,7 +3216,7 @@
<rect>
<x>220</x>
<y>20</y>
<width>50</width>
<width>61</width>
<height>20</height>
</rect>
</property>
@ -3276,7 +3276,7 @@
<rect>
<x>360</x>
<y>20</y>
<width>50</width>
<width>61</width>
<height>20</height>
</rect>
</property>
@ -3414,7 +3414,7 @@
<rect>
<x>80</x>
<y>20</y>
<width>50</width>
<width>61</width>
<height>20</height>
</rect>
</property>
@ -3436,7 +3436,7 @@
<rect>
<x>220</x>
<y>20</y>
<width>50</width>
<width>61</width>
<height>20</height>
</rect>
</property>
@ -3496,7 +3496,7 @@
<rect>
<x>360</x>
<y>20</y>
<width>50</width>
<width>61</width>
<height>20</height>
</rect>
</property>
@ -3586,7 +3586,7 @@
<rect>
<x>80</x>
<y>20</y>
<width>50</width>
<width>61</width>
<height>20</height>
</rect>
</property>
@ -3608,7 +3608,7 @@
<rect>
<x>220</x>
<y>20</y>
<width>50</width>
<width>61</width>
<height>20</height>
</rect>
</property>
@ -3668,7 +3668,7 @@
<rect>
<x>360</x>
<y>20</y>
<width>50</width>
<width>61</width>
<height>20</height>
</rect>
</property>
@ -3854,7 +3854,7 @@
<rect>
<x>80</x>
<y>20</y>
<width>50</width>
<width>61</width>
<height>20</height>
</rect>
</property>
@ -3876,7 +3876,7 @@
<rect>
<x>220</x>
<y>20</y>
<width>50</width>
<width>61</width>
<height>20</height>
</rect>
</property>
@ -3936,7 +3936,7 @@
<rect>
<x>360</x>
<y>20</y>
<width>50</width>
<width>61</width>
<height>20</height>
</rect>
</property>
@ -4394,10 +4394,10 @@
<widget class="QLabel" name="location">
<property name="geometry">
<rect>
<x>1180</x>
<y>10</y>
<width>81</width>
<height>21</height>
<x>1060</x>
<y>35</y>
<width>161</width>
<height>20</height>
</rect>
</property>
<property name="font">
@ -4415,6 +4415,28 @@
<string>CDTH</string>
</property>
</widget>
<widget class="QPushButton" name="pushButton_wintab">
<property name="geometry">
<rect>
<x>1180</x>
<y>10</y>
<width>81</width>
<height>41</height>
</rect>
</property>
<property name="font">
<font>
<family>微软雅黑</family>
<pointsize>12</pointsize>
</font>
</property>
<property name="styleSheet">
<string notr="true">color:white</string>
</property>
<property name="text">
<string>切换</string>
</property>
</widget>
<zorder>rotate_1</zorder>
<zorder>groupBox_status</zorder>
<zorder>label_title</zorder>
@ -4522,6 +4544,7 @@
<zorder>image_label_82</zorder>
<zorder>image_label_12</zorder>
<zorder>location</zorder>
<zorder>pushButton_wintab</zorder>
</widget>
</widget>
<layoutdefault spacing="6" margin="11"/>

@ -2,29 +2,33 @@
#include <string>
#include "stdarg.h"
#include <io.h>
#include <windows.h>
#include <ShlObj.h>
#include <Commdlg.h>
#include <tchar.h>
int string_split(std::string str, std::string pattern,std::vector<std::string> &out)
int string_split(std::string str, std::string pattern, std::vector<std::string>& out)
{
std::string::size_type pos;
int cnt = 0;
str += pattern;
int size = str.size();
for (int i = 0; i<size; i++)
{
pos = str.find(pattern, i);
if (pos<size)
{
cnt++;
std::string s = str.substr(i, pos - i);
out.push_back(s);
i = pos + pattern.size() - 1;
}
}
return cnt;
std::string::size_type pos;
int cnt = 0;
str += pattern;
int size = str.size();
for (int i = 0; i < size; i++)
{
pos = str.find(pattern, i);
if (pos < size)
{
cnt++;
std::string s = str.substr(i, pos - i);
out.push_back(s);
i = pos + pattern.size() - 1;
}
}
return cnt;
}
std::string format(const char *pszFmt, ...)
std::string format(const char* pszFmt, ...)
{
std::string str;
va_list args;
@ -40,110 +44,110 @@ std::string format(const char *pszFmt, ...)
return str;
}
void DrawSelectRects(cv::Mat input,DisplayLabelConf &t_DisplayLabelConf,int Cnt)
void DrawSelectRects(cv::Mat input, DisplayLabelConf& t_DisplayLabelConf, int Cnt)
{
if (t_DisplayLabelConf.Flag[Cnt] & DisplayLabel_Type_Bit) {
if (t_DisplayLabelConf.leftButtonDownFlag) {
cv::rectangle(
input,
cv::Point(
t_DisplayLabelConf.originalPoint.x * input.cols,
t_DisplayLabelConf.originalPoint.y * input.rows),
cv::Point(
t_DisplayLabelConf.processPoint.x * input.cols,
t_DisplayLabelConf.processPoint.y * input.rows),
cv::Scalar(0, 0, 255),
4);
}
for (int i = 0; i < t_DisplayLabelConf.RectVet[Cnt].size(); i++) {
cv::rectangle(
input,
cv::Point(
t_DisplayLabelConf.RectVet[Cnt][i].TL.x * input.cols,
t_DisplayLabelConf.RectVet[Cnt][i].TL.y * input.rows),
cv::Point(
t_DisplayLabelConf.RectVet[Cnt][i].BR.x * input.cols,
t_DisplayLabelConf.RectVet[Cnt][i].BR.y * input.rows),
cv::Scalar(0, 0, 255),
4);
}
}
if (t_DisplayLabelConf.Flag[Cnt] & DisplayLabel_Type_Bit) {
if (t_DisplayLabelConf.leftButtonDownFlag) {
cv::rectangle(
input,
cv::Point(
t_DisplayLabelConf.originalPoint.x * input.cols,
t_DisplayLabelConf.originalPoint.y * input.rows),
cv::Point(
t_DisplayLabelConf.processPoint.x * input.cols,
t_DisplayLabelConf.processPoint.y * input.rows),
cv::Scalar(0, 0, 255),
4);
}
for (int i = 0; i < t_DisplayLabelConf.RectVet[Cnt].size(); i++) {
cv::rectangle(
input,
cv::Point(
t_DisplayLabelConf.RectVet[Cnt][i].TL.x * input.cols,
t_DisplayLabelConf.RectVet[Cnt][i].TL.y * input.rows),
cv::Point(
t_DisplayLabelConf.RectVet[Cnt][i].BR.x * input.cols,
t_DisplayLabelConf.RectVet[Cnt][i].BR.y * input.rows),
cv::Scalar(0, 0, 255),
4);
}
}
}
bool CheckSelectRects(
cv::Mat input,
std::vector<std::vector<std::pair<int, cv::Rect> > > &VecRects,
int VecCnt,
DisplayLabelConf &t_DisplayLabelConf,
int LabelCnt
cv::Mat input,
std::vector<std::vector<std::pair<int, cv::Rect> > >& 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<std::string>& 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;
}
/*
@ -167,195 +171,255 @@ char* LPWSTR2LPSTR(LPWSTR lpwszStrIn)
//从string s的位置pos开始向后找找到第一个等于x的位置返回其位置
//找到,返回找到的位置,找不到返回-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 <Commdlg.h>
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("请选择图片");
// 文件必须存在、允许多选、隐藏只读选项、对话框使用资源管理器风格的用户界面
// 官方文档https://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 "";
}
// 把第一个文件名前的复制到szPath,即:
// 如果只选了一个文件,就复制到最后一个'/'
// 如果选了多个文件,就复制到第一个NULL字符
lstrcpyn(szPath, szOpenFileNames, ofn.nFileOffset);
// 当只选了一个文件时,下面这个NULL字符是必需的.
// 这里不区别对待选了一个和多个文件的情况
szPath[ofn.nFileOffset] = '\0';
nLen = lstrlen(szPath);
// 如果选了多个文件,则必须加上'//'
if (szPath[nLen - 1] != '\\') {
lstrcat(szPath, _T("\\"));
}
// 把指针移到第一个文件
p = szOpenFileNames + ofn.nFileOffset;
// 对szFileName进行清零
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;
// 将string转为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 <Commdlg.h>
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("请选择图片");
// 文件必须存在、允许多选、隐藏只读选项、对话框使用资源管理器风格的用户界面
// 官方文档https://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 "";
}
// 把第一个文件名前的复制到szPath,即:
// 如果只选了一个文件,就复制到最后一个'/'
// 如果选了多个文件,就复制到第一个NULL字符
lstrcpyn(szPath, szOpenFileNames, ofn.nFileOffset);
// 当只选了一个文件时,下面这个NULL字符是必需的.
// 这里不区别对待选了一个和多个文件的情况
szPath[ofn.nFileOffset] = '\0';
nLen = lstrlen(szPath);
// 如果选了多个文件,则必须加上'//'
if (szPath[nLen - 1] != '\\') {
lstrcat(szPath, _T("\\"));
}
// 把指针移到第一个文件
p = szOpenFileNames + ofn.nFileOffset;
// 对szFileName进行清零
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;
// 将string转为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;
}
void stdString2QString(std::string str, QString& qs) {
qs = QString::fromLocal8Bit(QByteArray::fromRawData(str.c_str(), str.size()));
}
void QString2stdString(QString qs, std::string& str) {
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;
}
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::vector<std::string> SpiteStringCharacter(std::string context) {
std::vector<std::string> 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;
}

@ -1,29 +1,31 @@
#pragma once
#pragma once
#include <iostream>
#include <vector>
#include <mutex>
#include "basecamera.h"
#include "QtCore\qdatetime.h"
#include <Windows.h>
#include <ShlObj.h>
#include <Commdlg.h>
#include <tchar.h>
#define __DEBUG //debug信息输出功能
//#define __UDPSend //网络发送功能
#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不要一起开
#if defined (ONE_TIME_SHIFT)
//#define CAP_FEED_BACK //拍照时也检测有没有测试结果,有的话就反馈
//#define DOUBLE_FEED_BACK //一次ng两次反馈ng信号
#endif
//#define identify_Hik_YSXID//识别海康相机YSXID
//#define __DEBUG //debug信息输出功能
#define LOG_RECORD //log日志功能
#define CLEAR_THREAD //定时清理线程
//#define __UDPSend //网络发送功能
//#define __TCPSend // TCP发送
#define __MQTTSend // MQTT发送
#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不要一起开
#if defined (ONE_TIME_SHIFT)
//#define CAP_FEED_BACK //拍照时也检测有没有测试结果,有的话就反馈
//#define DOUBLE_FEED_BACK //一次ng两次反馈ng信号
#endif
//#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
@ -35,194 +37,189 @@
#define DEBUG(format, ...)
#endif
// 主界面基本参数配置文件
#define CONFIGURE_FILE "../conf/conf.txt"
// 相机旋转角度配置文件
#define ROTATE_FILE "../conf/rotate.txt"
#define MODBUS_CONFIGURE_FILE "../conf/modbus.txt"
#define PLC_CONFIG_FILE "../conf/plc.txt"
#define SELECT_RECTS_FILE "../conf/SelectRects%d%d.txt"
#define STATISTIC_FILE "../conf/camera%d_statistic.txt"
// 主界面基本参数配置文件
#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 OP_TIME 300 //OP权限时长默认300秒
#define ADMIN_TIME 600 //ADMIN权限时长默认300秒
#define STOP_SECONDS 3 //检查多少次不变触发自动换班
#define STOP_SECONDS 3 //检查多少次不变触发自动换班
int string_split(std::string str, std::string pattern,std::vector<std::string> &out);
std::string format(const char *pszFmt, ...);
int string_split(std::string str, std::string pattern, std::vector<std::string>& out);
std::string format(const char* pszFmt, ...);
void getFiles(std::string path, std::vector<std::string>& files);
std::string SelectDirBRI();
std::string SelectFileOFN();
std::string SelectDirIFD();
std::string UTF8ToGBK(std::string utf8_str);
std::string WString2String(const std::wstring& ws);
std::wstring String2WString(const std::string& str);
std::vector<std::string> 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 = "";
}
};
class SysConf
{
public:
std::mutex lock;
int save; //图片是否保存0不保存1保存NG, 2全部保存
int MisMatchAct; //错位行为1NG,0ok
int save_days; ///照片保存天数
int freesize; /// 设定清理图片最小空间
std::string ComPort; ///COM口
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 path_model; // 模型路径
QString path_jpg; // 图片路径
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; //错位行为1NG,0ok
save_days = 1; ///照片保存天数
freesize = 10;
ComPort = "COM1";
auto_open=1; //是否自动打开相机0否1是
auto_work=1; //是否自动开始工作0否1是
auto_shift=0; //是否自动换班0否1是
shift_byhand = 1;
timing_shift=0; //是否定时换班0否1是
location = "";
path_model = "";
path_jpg = "";
shiftA.setHMS(0, 0, 0);
shiftB.setHMS(0, 0, 0);
shiftC.setHMS(0, 0, 0);
for(int i=0;i<NumberOfSupportedCameras;i++)
{
expo[i]=2000;
gain[i]=0;
filter[i]=500;
UserID[i]=0xff;
no[i][0]=0;
no[i][1]=0;
no[i][2]=0;
shoot[i]=3;
}
MonitorIP = "192.168.10.1";
FeedbackPort = MonitorPort + NumberOfSupportedCameras*2;
}
std::mutex lock;
int save; // 图片是否保存0不保存1保存NG, 2全部保存
int MisMatchAct; // 错位行为1NG,0ok
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为接受命令端口
std::string TcpIP; // TCP服务器端ip地址
int TcpPort; // TCP服务器端端口号
SysConf()
{
save = 0; //图片是否保存0不保存1保存NG, 2全部保存
MisMatchAct = 1; //错位行为1NG,0ok
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 < NumberOfSupportedCameras; i++)
{
expo[i] = 2000;
gain[i] = 0;
filter[i] = 500;
UserID[i] = 0xff;
no[i][0] = 0;
no[i][1] = 0;
no[i][2] = 0;
shoot[i] = 4;
}
MonitorIP = "192.168.10.1";
FeedbackPort = MonitorPort + NumberOfSupportedCameras * 2;
TcpIP = "192.168.1.126";
TcpPort = 8888;
}
};
//Modbus地址设置
class ModbusConf
#ifdef SYNC_CAMERA
class ImageSyncArr
{
public:
#if defined(NumberOfSupportedCameras) && (NumberOfSupportedCameras>0)
int kick1; //1#通道剔除个数地址
#endif
#if defined(NumberOfSupportedCameras) && (NumberOfSupportedCameras>1)
int kick2; //2#通道剔除个数地址
#endif
#if defined(NumberOfSupportedCameras) && (NumberOfSupportedCameras>2)
int kick3; //3#通道剔除个数地址
#endif
#if defined(NumberOfSupportedCameras) && (NumberOfSupportedCameras>3)
int kick4; //4#通道剔除个数地址
#endif
#if defined(NumberOfSupportedCameras) && (NumberOfSupportedCameras>4)
int kick5; //5#通道剔除个数地址
#endif
#if defined(NumberOfSupportedCameras) && (NumberOfSupportedCameras>5)
int kick6; //6#通道剔除个数地址
#endif
#if defined(NumberOfSupportedCameras) && (NumberOfSupportedCameras>6)
int kick7; //7#通道剔除个数地址
#endif
#if defined(NumberOfSupportedCameras) && (NumberOfSupportedCameras>7)
int kick8; //8#通道剔除个数地址
#endif
int quantity; //当班产量地址
int shift; //换班地址
int work; //开始/暂停
int no_kick; //只拍照不剔除模式
int debug; //调试模式PLC产生模拟的line4信号
int reset; //复位
int alarm; //报警
ModbusConf()
{
#if defined(NumberOfSupportedCameras) && (NumberOfSupportedCameras>0)
kick1=0; //1#通道剔除个数地址
#endif
#if defined(NumberOfSupportedCameras) && (NumberOfSupportedCameras>1)
kick2=0; //2#通道剔除个数地址
#endif
#if defined(NumberOfSupportedCameras) && (NumberOfSupportedCameras>2)
kick3=0; //3#通道剔除个数地址
#endif
#if defined(NumberOfSupportedCameras) && (NumberOfSupportedCameras>3)
kick4=0; //4#通道剔除个数地址
#endif
#if defined(NumberOfSupportedCameras) && (NumberOfSupportedCameras>4)
kick5=0; //1#通道剔除个数地址
#endif
#if defined(NumberOfSupportedCameras) && (NumberOfSupportedCameras>5)
kick6=0; //2#通道剔除个数地址
#endif
#if defined(NumberOfSupportedCameras) && (NumberOfSupportedCameras>6)
kick7=0; //3#通道剔除个数地址
#endif
#if defined(NumberOfSupportedCameras) && (NumberOfSupportedCameras>7)
kick8=0; //4#通道剔除个数地址
std::mutex lock;
std::vector<std::pair<int, cv::Mat>> image_sync_arr = std::vector<std::pair<int, cv::Mat>>(NumberOfSupportedCameras);
uint8_t collect_cnt;
ImageSyncArr()
{
collect_cnt = 0;
}
};
#endif
quantity=0; //当班产量地址
shift=0; //换班地址
work=0; //开始/暂停
no_kick=0; //只拍照不剔除模式
debug=0; //调试模式PLC产生模拟的line4信号
reset=0; //复位
alarm=0; //报警
}
//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++) {
#if defined(NumberOfSupportedCameras) && (NumberOfSupportedCameras > i)
kick[i] = 0;
#endif
}
quantity = 0; //当班产量地址
shift = 0; //换班地址
work = 0; //开始/停止
no_kick = 0; //只拍照不剔除模式
debug = 0; //调试模式PLC产生模拟的line4信号
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<RectRatio> 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<RectRatio> RectVet[2];
};
void DrawSelectRects(cv::Mat input, DisplayLabelConf& t_DisplayLabelConf, int Cnt);
bool CheckSelectRects(cv::Mat input, std::vector<std::vector<std::pair<int, cv::Rect> > >& VecRects, int VecCnt, DisplayLabelConf& t_DisplayLabelConf, int LabelCnt);

@ -0,0 +1,2 @@
CONF_PATH=D:/conf-模型1
SAVE_PICS_PATH=D:/image-中文测试

@ -1,12 +1,12 @@
//qlabel_doubleclick.cpp
#include "db_label.h"
#include <QDebug>
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;
}

Some files were not shown because too many files have changed in this diff Show More

Loading…
Cancel
Save