You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1376 lines
40 KiB
C++

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

#include "CMainWin.h"
#include <QDateTime>
#include "lpSysLog.h"
#include <QMessageBox>
#include <QCloseEvent>
#include <QLibrary>
#include "quserinfo_global.h"
#include "Serialport_global.h"
#include <QProcess>
#include "lpSysConfig.h"
#include <QMenu>
#include "WfCtrl.h"
#include "lpGlobalConfig.h"
#define LEAPER_LOGO ":/leaper/Resource/app.png"
#define WINDOWS_ICON ":/leaper/Resource/app.png"
#define DELETE_POINTER(p) if (p) {delete p; p = NULL;}
#pragma execution_character_set("utf-8")
static QImage cvMat2QImage(const cv::Mat& mat) {
if (mat.type() == CV_8UC1) {
QImage image(mat.cols, mat.rows, QImage::Format_Indexed8);
image.setColorCount(256);
for (int i = 0; i < 256; i++) {
image.setColor(i, qRgb(i, i, i));
}
uchar *pSrc = mat.data;
for (int row = 0; row < mat.rows; row++) {
uchar *pDest = image.scanLine(row);
memcpy(pDest, pSrc, mat.cols);
pSrc += mat.step;
}
return image;
}
else if (mat.type() == CV_8UC3) {
const uchar *pSrc = (const uchar*)mat.data;
QImage image(pSrc, mat.cols, mat.rows, mat.step, QImage::Format_RGB888);
if (image.isNull())
return QImage();
return image.rgbSwapped();
}
else if (mat.type() == CV_8UC4) {
const uchar *pSrc = (const uchar*)mat.data;
QImage image(pSrc, mat.cols, mat.rows, mat.step, QImage::Format_ARGB32);
return image.copy();
}
else {
qDebug() << "ERROR: Mat could not be converted to QImage.";
return QImage();
}
}
static cv::Mat QImageToMat(QImage image) {
cv::Mat mat;
switch (image.format())
{
case QImage::Format_ARGB32:
case QImage::Format_RGB32:
case QImage::Format_ARGB32_Premultiplied:
mat = cv::Mat(image.height(), image.width(), CV_8UC4, (void*)image.constBits(), image.bytesPerLine());
break;
case QImage::Format_RGB888:
mat = cv::Mat(image.height(), image.width(), CV_8UC3, (void*)image.constBits(), image.bytesPerLine());
cv::cvtColor(mat, mat, CV_BGR2RGB);
break;
case QImage::Format_Grayscale8:
case QImage::Format_Indexed8:
mat = cv::Mat(image.height(), image.width(), CV_8UC1, (void*)image.constBits(), image.bytesPerLine());
break;
}
return mat;
}
CMainWin::CMainWin(QWidget *parent)
: QMainWindow(parent)
{
ui.setupUi(this);
setWindowIcon(QIcon(LEAPER_LOGO));
onInitCoreCtrl();
onInitSerial();
onInitUser();
onInitUI();
onInitStatus();
lpSysLog::instance()->Init();
lpSysConfig::instance()->readConfig();
lpSysConfig::instance()->writeConfig();
lpGlobalConfig::instance()->readConfig();
SYSLOG_STATUS << "系统启动";
{
QString strPath = QCoreApplication::applicationDirPath();
QString DBFilePath = strPath + "\\DBFiles";
QDir dbDir;
dbDir.mkpath(DBFilePath);
m_db = new StationDB(DBFilePath + "\\AntMan.db");
m_db->InitDatabase();
}
m_pCameraTrig = new AutoTrigger;
connect(m_pCameraTrig, SIGNAL(sgTrig()), this, SLOT(onTrigImage()));
connect(&m_devMgrWid, SIGNAL(sgChangeLanguage(QString)), this, SLOT(onLanguageChange(QString)));
connect(&m_testWid, SIGNAL(sgTestMode(int)), this, SLOT(onTestMode(int)));
m_pWfCtrl = new CWfCtrl(m_pDetectorEngine);
m_pWfCtrl->onInit();
m_mangeWid.onInitModelList(m_pWfCtrl);
QStringList strList = m_pWfCtrl->IGetStationKeys();
foreach(QString str, strList) {
IStation *pS = m_pWfCtrl->IGetStationByKey(str);
connect(pS, SIGNAL(sgShowModeName(QString, QString)), this, SLOT(onShowName(QString, QString)));
}
{
if (m_pDetectorEngine)
{
QStringList Names = m_pDetectorEngine->getSolutionMgr()->GetAllSolutions().keys();
}
}
m_pWfCtrl->ISelModel(lpGlobalConfig::instance()->m_StationSolution_1, lpGlobalConfig::instance()->m_StationRunModel_1);
m_pWfCtrl->ISelModel(lpGlobalConfig::instance()->m_StationSolution_2, lpGlobalConfig::instance()->m_StationRunModel_2);
}
CMainWin::~CMainWin()
{
DELETE_POINTER(m_pCameraTrig);
if (m_db)
{
delete m_db;
m_db = NULL;
}
if (m_pUserCtrl) {
delete m_pUserCtrl;
m_pUserCtrl = NULL;
}
if (m_pSerialPort) {
m_HeartBit.stop();
m_pSerialPort->CloseCom();
delete m_pSerialPort;
m_pSerialPort = NULL;
}
if (m_pDesigner)
{
delete m_pDesigner;
m_pDesigner = nullptr;
}
if (m_pDllDesigner)
{
delete m_pDllDesigner;
m_pDllDesigner = nullptr;
}
if (m_pDllDetectorEngine)
{
delete m_pDllDetectorEngine;
m_pDllDetectorEngine = nullptr;
}
//load coretrl
if (m_pDllCoreCtrl)
{
delete m_pDllCoreCtrl;
m_pDllCoreCtrl = nullptr;
}
if (m_pWfCtrl)
{
delete m_pWfCtrl;
m_pWfCtrl = nullptr;
}
lpSysConfig::uninstance();
rmTranslator();
lpSysLog::uninstance();
}
//相机原图接收回调 用于展示图像
void CMainWin::INewCameraImage(const QString& camKey, QImage img)
{
emit sgShowSrcImg(camKey, img);
QString solutionName;
QString strRunModel;
int stationID = 0;
if (camKey == lpGlobalConfig::instance()->m_StationCamKey_1)
{
solutionName = lpGlobalConfig::instance()->m_StationSolution_1;
strRunModel = lpGlobalConfig::instance()->m_StationRunModel_1;
stationID = 1;
}
else if (camKey == lpGlobalConfig::instance()->m_StationCamKey_2)
{
solutionName = lpGlobalConfig::instance()->m_StationSolution_2;
strRunModel = lpGlobalConfig::instance()->m_StationRunModel_2;
stationID = 2;
}
onShowImage(stationID, img);
if (solutionName.isEmpty())
{
}
else {
QString strMode = strRunModel;
cv::Mat srcMat = QImageToMat(img);
AlgResultCallBack func = std::bind(&CMainWin::IEngineResult, this, std::placeholders::_1);
m_pDetectorEngine->detectByName(srcMat, solutionName, strMode, func);
}
}
//算法结果接收
void CMainWin::IVariantMapToUI(const QString& camKey, const QVariantMap& vMap)
{
// return;
// QImage srcImg = vMap.value("srcImage").value<QImage>();
// cv::Mat srcMat = QImageToMat(srcImg);
// QString strMode;// = pResult->m_strModel;
// AlgResultCallBack func = std::bind(&CMainWin::IEngineResult, this, std::placeholders::_1);
// m_pDetectorEngine->detect(srcMat, strMode, func);
/* QVariantMap mMap = vMap.value("algoRlt").toMap();
IStation *pStation = m_pWfCtrl->IGetStationByKey(camKey);
if (pStation)
{
QImage image = vMap.value("image").value<QImage>();
int nSize = image.height();
if (!vMap.contains("angle")) {
qWarning() << "no angle result";
}
QImage srcImg = vMap.value("originImage").value<QImage>();
double dAngle = vMap.contains("angle") ? vMap.value("angle").toDouble() : 365;
int errorType = vMap.contains("error") ? vMap.value("error").toInt() : 16;
double matchScore = vMap.value("score").toDouble() * 100;
QString str = vMap.value("resultTip").toString();
QStringList strList = str.split("/");
QString strRusltTip = strList.first();
QString threshBenchMark = strList.last();
//QString strImgPath = vMap.value("imageName").toString();
QString strResult = QTime::currentTime().toString("hh:mm:ss zzz:") + strList.first();
strResult += "angle result : " + QString::number(dAngle, 'f', 3);
pStation->setSerialPortPtr(m_pSerialPort);
if (dAngle >= 361)
dAngle = 361.0;
pStation->sendResult(dAngle);
if (image.isNull())
int b = 0;
SYSLOG_STATUS << QString("◎工位%1收到算法结果,当前型号为[%2],发送角度为:%3").arg(pStation->stationId()).arg(pStation->currentRunningModel()).arg(dAngle);
emit sgShowImg(pStation->stationId(),image);
emit sgShowLog(pStation->stationId(), strResult);
pStation->revResult();
QString str2 = pStation->currentRunningModel();
int ID = pStation->stationId();
QString strModelName = QString("%1_%2").arg(ID).arg(str2);
QString strImgPath;
if((lpSysConfig::instance()->m_bSaveRltImg_st1 == true && pStation->stationId() == 1)
||(lpSysConfig::instance()->m_bSaveRltImg_st2 == true && pStation->stationId() == 2))
strImgPath = genSavePath(strModelName, image);
if((lpSysConfig::instance()->m_bSaveSrcImg_st1 == true&&pStation->stationId()==1)
|| (lpSysConfig::instance()->m_bSaveSrcImg_st2 == true && pStation->stationId() == 2))
genSaveSrcImgPath(strModelName, srcImg);
Struct2SaveData nStructData;
nStructData.dAngle = dAngle;
nStructData.errorType = errorType;
nStructData.matchScore = matchScore;
nStructData.threshBenchMark = threshBenchMark;
nStructData.resultTip = strRusltTip;
nStructData.stationName = pStation->stationShowName();
nStructData.value1 = strImgPath;
nStructData.value2 = str2;
m_db->addData2DB(nStructData);
}
*/
}
QVariant CMainWin::IGetVariantById(int id)
{
// IStation *pStation = m_pWfCtrl->IGetStationById(id);
// if (pStation) {
// return pStation->getVariant();
// }
return QVariant();
}
QString CMainWin::genSaveSrcImgPath(QString modelName, QImage &img)
{
QString strApp = QApplication::applicationDirPath();
QString targetPath = "/DBFiles/SrcImages";
QString strData = QDateTime::currentDateTime().toString("yyyyMMdd");
QString strFileName = QDateTime::currentDateTime().toString("yyyy_MM_dd_hhmmsszzz") + ".bmp";
targetPath = targetPath + "/" + strData + "/" + modelName;
QDir dir;
dir.mkpath(strApp + targetPath);
targetPath = targetPath + "/" + strFileName;
if (!img.isNull()) {
QString strImg = strApp + targetPath;
img.save(strImg);
}
return targetPath;
}
QString CMainWin::genSavePath(QString modelName, QImage &img)
{
QString strApp = QApplication::applicationDirPath();
QString targetPath = "/DBFiles/Images";
QString strData = QDateTime::currentDateTime().toString("yyyyMMdd");
QString strFileName = QDateTime::currentDateTime().toString("yyyy_MM_dd_hhmmsszzz") + ".jpg";
targetPath = targetPath + "/" + strData + "/" + modelName;
QDir dir;
dir.mkpath(strApp + targetPath);
targetPath = targetPath + "/" + strFileName;
if (!img.isNull()) {
QString strImg = strApp + targetPath;
img.save(strImg, "jpg", 5);
}
return targetPath;
}
Q_SLOT void CMainWin::onAppanalysis(SComFrame frame)
{
//数据接收
/* int nCmd = frame.cmd;
if (0x43 == nCmd)
{
onHeartComm(frame);
return;
}
else if (0x50 == nCmd) {
int nCameraID = -1;
if (5 == frame.data1) {
nCameraID = 1;
}
else if (6 == frame.data1) {
nCameraID = 2;
}
if (!m_pWfCtrl) {
qDebug() << "CommAchieved m_pWfCtrl is null";
return;
}
IStation *pStation = m_pWfCtrl->IGetStationById(nCameraID);
if (!pStation) {
return;
}
if (m_pWfCtrl->IOnlineMode() == true)
{
if (nCameraID == 1)
{
if (m_StationInfo_1.m_bRunEnable == true)
{
pStation->trigImage();
}
else {
QString strMsg = QString("%1:该型号ID:%2在模型库中不存在不能拍照").arg(QTime::currentTime().toString("hh:mm:ss zzz:")).arg(m_StationInfo_1.m_PLCID);
emit sgShowLog(1, strMsg);
if (m_StationInfo_1.m_PLCID > 0) {
pStation->setSerialPortPtr(m_pSerialPort);
pStation->sendResult(999);
SYSLOG_STATUS << QString("●工位%1:收到触发信号,因索引不合法所以没触发相机拍照,发送了999角度数据,型号为[%2],型号索引ID为[%3],时间:%4")
.arg(nCameraID)
.arg(m_StationInfo_1.strModelName.isEmpty() == true ? "空" : m_StationInfo_1.strModelName)
.arg(m_StationInfo_1.m_PLCID)
.arg(QDateTime::currentDateTime().toString("hh:mm:ss zzz"));
}
else {
SYSLOG_STATUS << QString("●工位%1:收到触发信号,因索引不合法所以没触发相机拍照,型号为[%2],型号索引ID为[%3],时间:%4")
.arg(nCameraID)
.arg(m_StationInfo_1.strModelName.isEmpty() == true ? "空" : m_StationInfo_1.strModelName)
.arg(m_StationInfo_1.m_PLCID)
.arg(QDateTime::currentDateTime().toString("hh:mm:ss zzz"));
}
}
}
else if (nCameraID == 2)
{
if (m_StationInfo_2.m_bRunEnable == true)
{
pStation->trigImage();
}
else
{
QString strMsg = QString("%1:该型号ID:%2在模型库中不存在不能拍照").arg(QTime::currentTime().toString("hh:mm:ss zzz:")).arg(m_StationInfo_2.m_PLCID);
emit sgShowLog(2, strMsg);
if (m_StationInfo_2.m_PLCID > 0) {
pStation->setSerialPortPtr(m_pSerialPort);
pStation->sendResult(999);
SYSLOG_STATUS << QString("●工位%1:收到触发信号,因索引不合法所以没触发相机拍照,发送了999角度数据,型号为[%2],型号索引ID为[%3],时间:%4")
.arg(nCameraID)
.arg(m_StationInfo_2.strModelName.isEmpty() == true ? "空" : m_StationInfo_2.strModelName)
.arg(m_StationInfo_2.m_PLCID)
.arg(QDateTime::currentDateTime().toString("hh:mm:ss zzz"));
}
else {
SYSLOG_STATUS << QString("●工位%1:收到触发信号,因索引不合法所以没触发相机拍照,型号为[%2],型号索引ID为[%3],时间:%4")
.arg(nCameraID)
.arg(m_StationInfo_2.strModelName.isEmpty() == true ? "空" : m_StationInfo_2.strModelName)
.arg(m_StationInfo_2.m_PLCID)
.arg(QDateTime::currentDateTime().toString("hh:mm:ss zzz"));
}
}
}
}
else
pStation->trigImage();
}
else if (0xf1 == nCmd)
{//接收到下位机的命令关闭所有窗口 关机
qApp->closeAllWindows();
//shutDown();
}*/
}
void CMainWin::onHeartComm(SComFrame &frame)
{
/* static int nS1 = -1;
static int nS2 = -1;
if (m_pWfCtrl)
m_pWfCtrl->registerConnect();
else
return;
if (m_pWfCtrl->IOnlineMode() == true)
{
int nSta1 = frame.data1;
int nSta2 = frame.data2;
if (nS1 != nSta1 || nS2 != nSta2)
{
nS1 = nSta1;
nS2 = nSta2;
}
else
return;
QStringList lstKeys = m_pWfCtrl->IGetStationKeys();
for each (QString var in lstKeys)
{
IStation *pStation = m_pWfCtrl->IGetStationByKey(var);
if (!pStation) {
continue;
}
int nId = pStation->stationId();
if (nId <= 0 || nId > 8) {
//error
qWarning() << "error, id is beyong";
continue;
}
int mmCmd = 0;
if (nId == 1)
mmCmd = frame.data1;
if (nId == 2)
mmCmd = frame.data2;
if (nId == 3)
mmCmd = frame.data3;
if (nId == 4)
mmCmd = frame.data4;
if (nId == 5)
mmCmd = frame.data5;
if (nId == 6)
mmCmd = frame.data6;
if (nId == 7)
mmCmd = frame.data7;
if (nId == 8)
mmCmd = frame.data8;
QString strModel = pStation->modelByPlcCmd(mmCmd);
if (!strModel.isEmpty())
{
emit(sgSelModel(nId, strModel));
if (nId == 1)
{
if (m_StationInfo_1.m_PLCID != mmCmd)
{
m_StationInfo_1.m_PLCID = mmCmd;
m_StationInfo_1.strModelName = strModel;
SYSLOG_STATUS << QString("★工位%1:切换型号为[%2],型号索引ID为[%3],时间:%4")
.arg(nId)
.arg(strModel)
.arg(mmCmd)
.arg(QDateTime::currentDateTime().toString("hh:mm:ss zzz"));
}
m_StationInfo_1.m_bRunEnable = true;
}
else if (nId == 2)
{
if (m_StationInfo_2.m_PLCID != mmCmd) {
m_StationInfo_2.m_PLCID = mmCmd;
m_StationInfo_2.strModelName = strModel;
SYSLOG_STATUS << QString("★工位%1:切换型号为[%2],型号索引ID为[%3],时间:%4")
.arg(nId)
.arg(strModel)
.arg(mmCmd)
.arg(QDateTime::currentDateTime().toString("hh:mm:ss zzz"));
}
m_StationInfo_2.m_bRunEnable = true;
}
}
else {
if (nId == 1)
{
if (m_StationInfo_1.m_PLCID != mmCmd) {
m_StationInfo_1.m_PLCID = mmCmd;
m_StationInfo_1.strModelName = strModel;
if (mmCmd <= 0)
SYSLOG_STATUS << QString("★工位%1:型号清零,型号索引ID为[%2],时间:%3")
.arg(nId)
.arg(mmCmd)
.arg(QDateTime::currentDateTime().toString("hh:mm:ss zzz"));
else
SYSLOG_STATUS << QString("★工位%1:型号切换失败,对应的索引不存在,型号索引ID为[%2],时间:%3")
.arg(nId)
.arg(mmCmd)
.arg(QDateTime::currentDateTime().toString("hh:mm:ss zzz"));
}
m_StationInfo_1.m_bRunEnable = false;
if (mmCmd > 0)
{
QString strMsg = QString("%1:型号设置失败,模型库中不存在索引%2").arg(QTime::currentTime().toString("hh:mm:ss zzz:")).arg(mmCmd);
emit sgShowLog(1, strMsg);
}
}
else if (nId == 2)
{
if (m_StationInfo_2.m_PLCID != mmCmd) {
m_StationInfo_2.m_PLCID = mmCmd;
m_StationInfo_2.strModelName = strModel;
if (mmCmd <= 0)
SYSLOG_STATUS << QString("★工位%1:型号清零,型号索引ID为[%2],时间:%3")
.arg(nId)
.arg(mmCmd)
.arg(QDateTime::currentDateTime().toString("hh:mm:ss zzz"));
else
SYSLOG_STATUS << QString("★工位%1:型号切换失败,对应的索引不存在,型号索引ID为[%2],时间:%3")
.arg(nId)
.arg(mmCmd)
.arg(QDateTime::currentDateTime().toString("hh:mm:ss zzz"));
}
m_StationInfo_2.m_bRunEnable = false;
if (mmCmd > 0) {
QString strMsg = QString("%1:型号设置失败,模型库中不存在索引%2").arg(QTime::currentTime().toString("hh:mm:ss zzz:")).arg(mmCmd);
emit sgShowLog(2, strMsg);
}
}
}
}
}*/
}
Q_SLOT void CMainWin::onHeardBit()
{
if (m_pSerialPort) {
SComFrame frame;
memset(&frame, 0, sizeof(SComFrame));
frame.cmd = 0x43;
frame.data7 = 200;
frame.data8 = 0x50;
m_pSerialPort->enquequeData(frame);
}
}
Q_SLOT void CMainWin::onActionClicked()
{
QString strObj = sender()->objectName();
if ("actionSetting" == strObj) {//标定
if (m_pDesigner) {
m_pDesigner->ShowMainFrame(this);
}
}
else if ("actionManage" == strObj) {//模板管理
m_mangeWid.setParent(this);
m_mangeWid.setWindowFlags(Qt::Dialog | Qt::WindowCloseButtonHint);
m_mangeWid.setWindowModality(Qt::ApplicationModal);
m_mangeWid.setAttribute(Qt::WA_ShowModal, true);
m_mangeWid.show();
}
else if ("actionTest" == strObj) {//测试
m_testWid.setParent(this);
m_testWid.setWindowFlags(Qt::Dialog | Qt::WindowCloseButtonHint);
m_testWid.setWindowModality(Qt::ApplicationModal);
m_testWid.setAttribute(Qt::WA_ShowModal, true);
m_testWid.show();
}
else if ("actionHelp" == strObj) {//帮助
m_aboutWid.setParent(this);
m_aboutWid.setWindowIcon(QIcon(LEAPER_LOGO));
m_aboutWid.setWindowFlags(Qt::Dialog | Qt::WindowCloseButtonHint);
m_aboutWid.setWindowModality(Qt::ApplicationModal);
m_aboutWid.setAttribute(Qt::WA_ShowModal, true);
m_aboutWid.show();
}
else if ("action_Check" == strObj) {//历史记录查询
QProcess process;
process.setWorkingDirectory(QCoreApplication::applicationDirPath());
#ifdef _DEBUG
QString strTaskName = "Reportd.exe";
#else
QString strTaskName = "Report.exe";
#endif
process.startDetached(strTaskName);
}
else if ("action" == strObj) {//系统参数设置
m_devMgrWid.setParent(this);
m_devMgrWid.setWindowIcon(QIcon(LEAPER_LOGO));
m_devMgrWid.setWindowFlags(Qt::Dialog | Qt::WindowCloseButtonHint);
m_devMgrWid.setWindowModality(Qt::ApplicationModal);
m_devMgrWid.setAttribute(Qt::WA_ShowModal, true);
QStringList camkeys = m_pCoreCtrl->ICameraKeys();
QStringList solutions = m_pDetectorEngine->getSolutionMgr()->GetAllSolutions().keys();
m_devMgrWid.setSystemConfig(camkeys, solutions);
m_devMgrWid.show();
}
else if ("main_Login_action" == strObj) {//用户登陆
if (m_pUserCtrl) {
if (m_pUserCtrl->getLoginState() == EM_LOGIN)
{
QMessageBox infobox(QMessageBox::Information, QString(QObject::tr("提示")), QString(QObject::tr("你确定要注销%1 ?")).arg(m_pUserCtrl->CurUser()), QMessageBox::Yes | QMessageBox::No, NULL);
infobox.setWindowIcon(QIcon(":/image/leaper"));
infobox.setButtonText(QMessageBox::Yes, QString("确认"));
infobox.setButtonText(QMessageBox::No, QString("取消"));
if (infobox.exec() == QMessageBox::Yes) {
m_pUserCtrl->LogOutUser();
}
}
else
m_pUserCtrl->CheckLogin(this);
}
else
{
QMessageBox infobox(QMessageBox::Information, QString(QObject::tr("提示")), QString(QObject::tr("该功能未启用.")), QMessageBox::Yes, NULL);
infobox.setWindowIcon(QIcon(":/image/leaper"));
infobox.setButtonText(QMessageBox::Yes, QString(QObject::tr("确认")));
infobox.exec();
}
}
else if ("main_action_userManager" == strObj) {//用户管理
if (m_pUserCtrl) {
m_pUserCtrl->ShowUserMgrDlg(this);
}
else
{
QMessageBox infobox(QMessageBox::Information, QString(QObject::tr("提示")), QString(QObject::tr("该功能未启用.")), QMessageBox::Yes, NULL);
infobox.setWindowIcon(QIcon(":/image/leaper"));
infobox.setButtonText(QMessageBox::Yes, QString(QObject::tr("确认")));
infobox.exec();
}
}
}
void CMainWin::timerEvent(QTimerEvent *event)
{
if (m_TimerID_Status == event->timerId())
{
onUpdateStatus();
}
}
void CMainWin::closeEvent(QCloseEvent *event)
{
QMessageBox info(this);
info.setWindowIcon(QIcon(LEAPER_LOGO));
info.setWindowTitle(QObject::tr("警告"));
info.setText(QObject::tr("本检测系统正在运行,您真的要关闭?"));
info.setStandardButtons(QMessageBox::Ok | QMessageBox::Cancel);
info.setButtonText(QMessageBox::Ok, QObject::tr("确定"));
info.setButtonText(QMessageBox::Cancel, QObject::tr("取消"));
if (info.exec() != QMessageBox::Ok)
{
event->ignore();
}
else
event->accept();
}
void CMainWin::changeEvent(QEvent *event)
{
if (event->type() == QEvent::LanguageChange)
{
ui.retranslateUi(this);
}
}
//初始化状态栏
void CMainWin::onInitStatus()
{
const int c_nWidth = 170;
m_pLbCurrentTime = new QLabel(QObject::tr("系统时间"));
m_pLbCurrentTime->setMinimumHeight(40);
m_pLbCurrentTime->setMinimumWidth(c_nWidth);
m_pLbOnLine = new class QLabel(QObject::tr("模式:"));
m_pLbOnLine->setMinimumWidth(c_nWidth);
m_pLbUser = new class QLabel(QObject::tr("用户:无"));
m_pLbUser->setMinimumWidth(c_nWidth);
m_pLbConnect = new class QLabel(QObject::tr("连接状态:"));
m_pLbConnect->setMinimumWidth(c_nWidth);
//m_pLbDiskSpace = new class QLabel(QObject::tr("硬盘剩余空间:xxx.xG"));
//m_pLbDiskSpace->setMinimumWidth(c_nWidth);
ui.statusBar->addWidget(m_pLbOnLine);
ui.statusBar->addWidget(m_pLbConnect);
ui.statusBar->addWidget(m_pLbUser);
ui.statusBar->addWidget(m_pLbCurrentTime);
//ui.statusBar->addWidget(m_pLbDiskSpace);
}
void CMainWin::onUpdateStatus()
{
/* if (m_pLbCurrentTime) {
QString m_currentTimerString = QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss");
m_pLbCurrentTime->setText(QObject::tr("系统时间: ") + m_currentTimerString + " ");
//m_pLbCurrentTime->setStyleSheet("font: 14px;");
}
if (m_pLbOnLine && m_pWfCtrl) {
QString strOnlineState = QString(QObject::tr("检测模式:"))
+ (m_pWfCtrl->IOnlineMode() == true ? QObject::tr("在线模式") : QObject::tr("离线模式"));
m_pLbOnLine->setText(strOnlineState);
// m_pLbOnLine->setStyleSheet("font: bold 14px;");
}
if (m_pLbConnect && m_pWfCtrl) {
QString strOnlineState = QString(QObject::tr("连接状态:"))
+ (m_pWfCtrl->IConnectStatus() == true ? QObject::tr("连接正常") : QObject::tr("连接异常"));
m_pLbConnect->setText(strOnlineState);
}
if (m_pLbUser) {
m_pLbUser->setText(QObject::tr("用户: %1").arg(m_strUserName.isEmpty()==true?QObject::tr("未登录"):m_strUserName));
}
// if (m_pLbDiskSpace)
// {
// QString strDiskSpace = QString(QObject::tr("硬盘剩余空间:%1G")).arg(100 / 1024.0);
// m_pLbDiskSpace->setText(strDiskSpace);
// }
*/
}
bool CMainWin::onInitCoreCtrl()
{
//load coretrl 初始化框架模块
if (NULL == m_pDllCoreCtrl)
{
m_pDllCoreCtrl = new CDllCoreCtrl(QStringList());
if (NULL == m_pDllCoreCtrl)
{
return false;
}
m_pCoreCtrl = m_pDllCoreCtrl->m_pCoreCtrl;
if (m_pCoreCtrl == nullptr)//corectrl 加载失败
{
QMessageBox infobox(QMessageBox::Critical, tr("提示"), tr("Corectrl模块加载失败,请检查!"), QMessageBox::Yes, this);
infobox.setWindowIcon(QIcon(":/image/leaper"));
infobox.setButtonText(QMessageBox::Yes, tr("确认"));
infobox.exec();
exit(0);
}
FuncCallBack_VarInt getVarfunc = std::bind(&CMainWin::IGetVariantById, this, std::placeholders::_1);
m_pCoreCtrl->IRegisterGetVariant(getVarfunc);
FuncCallBack_StrMap strMapfunc = std::bind(&CMainWin::IVariantMapToUI, this, std::placeholders::_1, std::placeholders::_2);
m_pCoreCtrl->IRegisterResultCallBack(strMapfunc);
FuncCallBack_StrImg strImgfunc = std::bind(&CMainWin::INewCameraImage, this, std::placeholders::_1, std::placeholders::_2);
m_pCoreCtrl->IRegisterImageCallBack(strImgfunc);
if (m_pCoreCtrl->ICameraKeys().size() <= 0)
{
QMessageBox infobox(QMessageBox::Critical, tr("提示"), tr("camera.json文件出错,请检查!"), QMessageBox::Yes, this);
infobox.setWindowIcon(QIcon(":/image/leaper"));
infobox.setButtonText(QMessageBox::Yes, tr("确认"));
infobox.exec();
exit(0);
}
}
//load engine
if (NULL == m_pDllDetectorEngine)
{
m_pDllDetectorEngine = new CDllDetectorEngine();
if (NULL == m_pDllDetectorEngine)
{
return false;
}
m_pDetectorEngine = m_pDllDetectorEngine->m_pDE;
if (m_pDetectorEngine == nullptr)
{
QMessageBox infobox(QMessageBox::Critical, tr("提示"), tr("lpbengine模块加载失败,请检查!"), QMessageBox::Yes, this);
infobox.setWindowIcon(QIcon(":/image/leaper"));
infobox.setButtonText(QMessageBox::Yes, tr("确认"));
infobox.exec();
exit(0);
}
}
if (m_pDllDesigner == nullptr)
{
m_pDllDesigner = new CDllDesigner();
if (m_pDllDesigner != nullptr)
{
m_pDesigner = m_pDllDesigner->GetDesignerInterface();
if (m_pDesigner && m_pDetectorEngine)
{
m_pDesigner->Initialize(m_pDetectorEngine);
}
else {
QMessageBox infobox(QMessageBox::Critical, tr("提示"), tr("lpdesigner模块加载失败,请检查!"), QMessageBox::Yes, this);
infobox.setWindowIcon(QIcon(":/image/leaper"));
infobox.setButtonText(QMessageBox::Yes, tr("确认"));
infobox.exec();
exit(0);
}
}
}
return true;
}
void CMainWin::onInitDevice()
{
QStringList strCamKeys = m_pCoreCtrl->ICameraKeys();
for (int nIndex = 0; nIndex < strCamKeys.size(); nIndex++)
{
QString camKey = strCamKeys.at(nIndex);
m_pCoreCtrl->IOpenCamera(camKey);
m_pCoreCtrl->IStartCamera(camKey);
}
}
void CMainWin::onInitUser()
{
{//用户管理模块加载
#ifdef _DEBUG
QLibrary lib("QUserInfod");
#else
QLibrary lib("QUserInfo");
#endif
_UserCtrlCreate func = (_UserCtrlCreate)lib.resolve("UserCtrlCreate");
if (func) {
m_pUserCtrl = func();
connect(m_pUserCtrl, SIGNAL(sgCurrentUserInfo(QString, int, int)), this, SLOT(onLogInOut(QString, int, int)));
}
}
}
void CMainWin::onInitSerial()
{
{//串口设备加载
#ifdef _DEBUG
QLibrary lib("SerialPortToold");//库文件名
#else
QLibrary lib("SerialPortTool");//库文件名
#endif
_SerialPortCreate func = (_SerialPortCreate)lib.resolve("SerialPortCreate");
if (func)
m_pSerialPort = func();
//load seriport dll
if (m_pSerialPort)//如果文件存在 使用自定义的串口
{
m_pSerialPort->loadAnalysefunc(this, &CMainWin::onAppanalysis);
//关闭框架的串口使用
QString strDefaultPort = lpSysConfig::instance()->m_ComName;
int baut = lpSysConfig::instance()->m_Baut;
bool bOpen = m_pSerialPort->OpenCom(strDefaultPort, QString::number(baut));
if (bOpen == false)
{
QMessageBox infobox(QMessageBox::Information, QString(QObject::tr("提示")), QString("Com %1 %2 open failed").arg(strDefaultPort).arg(baut), QMessageBox::Yes | QMessageBox::No, NULL);
infobox.setWindowIcon(QIcon(LEAPER_LOGO));
infobox.exec();
}
connect(&m_HeartBit, SIGNAL(timeout()), this, SLOT(onHeardBit()));
m_HeartBit.start(300);
}
}
}
void CMainWin::onInitUI()
{
//工具栏按钮事件绑定
connect(ui.actionSetting, SIGNAL(triggered()), this, SLOT(onActionClicked()));
connect(ui.actionManage, SIGNAL(triggered()), this, SLOT(onActionClicked()));
connect(ui.actionTest, SIGNAL(triggered()), this, SLOT(onActionClicked()));
connect(ui.actionHelp, SIGNAL(triggered()), this, SLOT(onActionClicked()));
connect(ui.action_Check, SIGNAL(triggered()), this, SLOT(onActionClicked()));
connect(ui.action, SIGNAL(triggered()), this, SLOT(onActionClicked()));
connect(ui.main_Login_action, SIGNAL(triggered()), this, SLOT(onActionClicked()));
connect(ui.main_action_userManager, SIGNAL(triggered()), this, SLOT(onActionClicked()));
//图像结果展示
connect(this, SIGNAL(sgShowImg(int, QImage)), this, SLOT(onShowImage(int, QImage)));
connect(this, SIGNAL(sgSelModel(int, QString)), this, SLOT(onSelModel(int, QString)));
connect(this, SIGNAL(sgShowLog(int, QString)), this, SLOT(onShowLog(int, QString)));
m_TimerID_Status = startTimer(1000);
ui.main_action_userManager->setVisible(false);
//ui.action->setVisible(false);
QTextDocument *pDoc = ui.wf_text_edit_result_1->document();
pDoc->setMaximumBlockCount(200);
pDoc = ui.wf_text_edit_result_2->document();
pDoc->setMaximumBlockCount(200);
ui.wf_lb_image_show_1->setContextMenuPolicy(Qt::CustomContextMenu);
connect(ui.wf_lb_image_show_1, SIGNAL(customContextMenuRequested(const QPoint&)), this, SLOT(onPopMenu(const QPoint&)));
ui.wf_lb_image_show_2->setContextMenuPolicy(Qt::CustomContextMenu);
connect(ui.wf_lb_image_show_2, SIGNAL(customContextMenuRequested(const QPoint&)), this, SLOT(onPopMenu(const QPoint&)));
connect(this, SIGNAL(sgShowSrcImg(QString, QImage)), &m_camSetWid, SLOT(onShowImage(QString, QImage)));
}
//======系统翻译相关
void CMainWin::SearchQmFile(const QString & strDir)
{
QDir dir(strDir);
if (!dir.exists())
{
return;
}
dir.setFilter(QDir::Dirs | QDir::Files | QDir::NoDotAndDotDot);
dir.setSorting(QDir::DirsFirst); // 文件夹优先
// 转换成一个List
QFileInfoList list = dir.entryInfoList();
if (list.size() < 1)
{
return;
}
int i = 0;
do
{
QFileInfo fileInfo = list.at(i);
QString tt = fileInfo.fileName();
// 如果是文件夹
bool bisDir = fileInfo.isDir();
if (bisDir)
{
SearchQmFile(fileInfo.filePath());
}
else
{
bool bQm = fileInfo.fileName().endsWith(".qm");
SetTranslator(fileInfo.filePath());
}
i++;
} while (i < list.size());
}
void CMainWin::SetTranslator(const QString strPath)
{
if (strPath.isEmpty())
{
return;
}
QTranslator *pTrans = new QTranslator;
if (pTrans->load(strPath)) // 如果加载成功
{
qApp->installTranslator(pTrans);
m_VecTranPtr.append(pTrans);
}
else
{
delete pTrans;
pTrans = NULL;
}
}
Q_SLOT void CMainWin::onLanguageChange(QString strLanguage)
{
// QSettings languageSetting(lpSysConfig::instance()->getCfgPath(), QSettings::IniFormat);
// languageSetting.value("language/select", "Chinese").toString();
SetLanguage(strLanguage);
}
void CMainWin::SetLanguage(QString strLangage)
{
QString strDirPath = QString(QCoreApplication::applicationDirPath() + "/language/");
QString translatorFileName = strLangage;
if (!translatorFileName.isEmpty())
{
rmTranslator();
QLocale::setDefault(QLocale(translatorFileName));
QString transDir = strDirPath + translatorFileName;
SearchQmFile(transDir);
}
}
void CMainWin::rmTranslator()
{
if (m_VecTranPtr.size() > 0)
{
while (m_VecTranPtr.size())
{
QTranslator *pVa = m_VecTranPtr.takeFirst();
qApp->removeTranslator(pVa);
delete pVa;
pVa = NULL;
}
}
}
void CMainWin::writeConfig()
{
// QSettings setting("language.ini", QSettings::IniFormat);
// setting.setValue("language", m_strCurLanguage);
}
void CMainWin::saveSolution()
{
}
Q_SLOT void CMainWin::onMainFrameClose()
{
}
Q_SLOT void CMainWin::onSnapImage(int nCamera /*= -1*/)
{
if (nCamera == 1)
{
QString camKey = lpGlobalConfig::instance()->m_StationCamKey_1;
m_pCoreCtrl->ISnapImage(QStringList() << camKey);
}
else if (nCamera == 2)
{
QString camKey = lpGlobalConfig::instance()->m_StationCamKey_2;
m_pCoreCtrl->ISnapImage(QStringList() << camKey);
}
}
Q_SLOT void CMainWin::onTrigImage()
{
onSnapImage(1);
onSnapImage(2);
}
Q_SLOT void CMainWin::onSelModel(int nId, QString strModel)
{
}
Q_SLOT void CMainWin::onChangeUI(QString strUsr, int nLevel)
{
switch (nLevel) {
case 9:
case 8:
case 7:
case 6:
ui.main_action_userManager->setVisible(true);
ui.action->setEnabled(true);
ui.actionTest->setEnabled(true);
break;
case 5:
ui.main_action_userManager->setVisible(true);
ui.action->setEnabled(true);
ui.actionTest->setEnabled(true);
break;
case 4:
case 3:
case 2:
case 1:
case 0:
ui.main_action_userManager->setVisible(false);
ui.action->setEnabled(false);
ui.actionTest->setEnabled(false);
break;
default:
break;
}
}
Q_SLOT void CMainWin::onLogInOut(QString strName, int level, int state)
{
onChangeUI(strName, level);
m_strUserName = strName;
if (state == 0) {
ui.main_Login_action->setText(QObject::tr("注 销"));
}
else
{
ui.main_Login_action->setText(QObject::tr("登 录"));
}
}
Q_SLOT void CMainWin::onTestMode(int val)
{
if (val == 0) {
m_pCameraTrig->start(1000);
}
else if(val ==1){
m_pCameraTrig->stop();
}
else if (val == 2) {
onSnapImage(1);
}
else if (val == 3) {
onSnapImage(2);
}
}
//展示结果图片
Q_SLOT void CMainWin::onShowImage(int ID, QImage img)
{
auto ShowImg=[&](QLabel* pLab ,QImage& img) {
if (!pLab) {
qDebug() << "label image is null";
return;
}
if (img.isNull())
{
QString str = QObject::tr("检测到错误: 模型与图像尺寸不匹配,请重新标定模型!!!");
pLab->setText(str);
}
else
{
QRect rt = pLab->rect();
int h = img.height();
int w = img.width();
float d = w * 1.0 / h;
if (d > 0)
{
int h2 = rt.width() / d;
rt.setHeight(h2);
}
QImage imgShow = img.scaled(QSize(rt.size()));
pLab->setPixmap(QPixmap::fromImage(imgShow));
}
};
if (ID == 1)
{
ShowImg(ui.wf_lb_image_show_1,img);
}
else if (ID == 2)
{
ShowImg(ui.wf_lb_image_show_2, img);
}
}
//展示正在检测的型号名
Q_SLOT void CMainWin::onShowName(QString ID, QString strName)
{
if (ID == lpGlobalConfig::instance()->m_StationSolution_1) {
ui.wf_lb_station_name_1->setText(strName);
}
else if (ID == lpGlobalConfig::instance()->m_StationSolution_2) {
ui.wf_lb_station_name_2->setText(strName);
}
}
//展示log
Q_SLOT void CMainWin::onShowLog(int nID, QString strMsg)
{
if (nID == 1) {
ui.wf_text_edit_result_1->append(strMsg);
}
else if (nID == 2) {
ui.wf_text_edit_result_2->append(strMsg);
}
}
Q_SLOT void CMainWin::onPopMenu(const QPoint& pt)
{
/*根据UI名判断是哪个工位需要设置相机*/
QString strCamKey;
QString strObj = sender()->objectName();
if ("wf_lb_image_show_1" == strObj)
{
strCamKey = lpGlobalConfig::instance()->m_StationCamKey_1;
}
else if ("wf_lb_image_show_2" == strObj)
{
strCamKey = lpGlobalConfig::instance()->m_StationCamKey_2;
}
QStringList camkeys = m_pCoreCtrl->ICameraKeys();
if (!camkeys.contains(strCamKey) || strCamKey.isEmpty())
{
QMessageBox infobox(QMessageBox::Critical, tr("提示"), tr("请对该工位的相机进行绑定!"), QMessageBox::Yes, this);
infobox.setWindowIcon(QIcon(WINDOWS_ICON));
infobox.setButtonText(QMessageBox::Yes, tr("确认"));
infobox.exec();
return ;
}
QMenu menu;
QAction *pSetAction = menu.addAction(tr("相机属性配置"));
pSetAction->setObjectName("setAction");
QAction *pSelect = menu.exec(QCursor::pos());
if (!pSelect)
{
menu.clear();
return;
}
QString strObjAction = pSelect->objectName();
if (strObjAction == "setAction") {
m_camSetWid.setParent(this);
m_camSetWid.setWindowIcon(QIcon(LEAPER_LOGO));
m_camSetWid.setWindowFlags(Qt::Dialog | Qt::WindowCloseButtonHint);
m_camSetWid.setWindowModality(Qt::ApplicationModal);
m_camSetWid.setAttribute(Qt::WA_ShowModal, true);
m_camSetWid.setCamParam(m_pCoreCtrl, strCamKey);
m_camSetWid.show();
}
menu.clear();
}
Q_SLOT void CMainWin::onSlotAddNewModel(QString strName)
{
if (m_pDetectorEngine)
{
IDetectorSolutionMgr* pMgr = m_pDetectorEngine->getSolutionMgr();
if (pMgr)
{
IDetectorSolution* pSolution = pMgr->GetRunSolution();
if (pSolution) {
pSolution->AddTaskByTemplate(strName);
pSolution->SaveTaskByName(strName);
}
}
}
}
Q_SLOT void CMainWin::onSlotDelOldModel(QString strName)
{
if (m_pDetectorEngine) {
IDetectorSolutionMgr* pMgr = m_pDetectorEngine->getSolutionMgr();
if (pMgr) {
IDetectorSolution* pSolution = pMgr->GetRunSolution();
if (pSolution) {
pSolution->DeleteTask(strName);
pSolution->SaveTaskByName("");
}
}
}
}
void CMainWin::IEngineResult(QVariantMap vMap)
{
QImage srcImg = vMap.value("originImage").value<QImage>();
bool taskCali = vMap.value("taskCali").toBool();
QString solutionName = vMap.value("solutionName").toString();
if (taskCali == false)//模板未标定
{
// ui.main_value_Result->setText("该型号未标定");
// ui.main_value_Result->setStyleSheet("background-color: rgb(255, 212, 83);");
// ui.main_label_angle->setText("-");
// ui.main_value_Center_point->setText("-");
// ui.main_value_DetectTime->setText("-");
// ui.main_value_Score->setText("-");
//获取图像 保存到当天NG图
// ValueResult valueRlt;
// valueRlt.angle = 361;
// valueRlt.strModel = "NG";
// valueRlt.score = 0;
// valueRlt.strRunState = "no Cali";
// valueRlt.pixmap = QPixmap::fromImage(srcImg);
// valueRlt.resultType = 2;//识别出型号 但未标定
// onSaveValveResult(valueRlt);
return;
}
//不包含算法检测结果表示没有相关task
if (!vMap.contains("AlgoResult"))
{
// ui.main_value_Result->setText("没有找到相关task");
// ui.main_value_Result->setStyleSheet("background-color: rgb(255, 212, 83);");
// ui.main_label_angle->setText("-");
// ui.main_value_Center_point->setText("-");
// ui.main_value_DetectTime->setText("-");
// ui.main_value_Score->setText("-");
//获取图像 保存到当天NG图
// ValueResult valueRlt;
// valueRlt.angle = 361;
// valueRlt.strModel = "NG";
// valueRlt.score = 0;
// valueRlt.strRunState = "no task";
// valueRlt.pixmap = QPixmap::fromImage(srcImg);
// valueRlt.resultType = 3;//识别出型号 但未标定
// onSaveValveResult(valueRlt);
int stationID = 0;
if (solutionName == lpGlobalConfig::instance()->m_StationSolution_1)
{
stationID = 1;
}
else if (solutionName == lpGlobalConfig::instance()->m_StationSolution_2)
{
stationID = 2;
}
onShowImage(stationID, srcImg);
}
else {
QVariantMap algResult = vMap.value("AlgoResult").toMap();
double dAngle = algResult.contains("angle") ? algResult.value("angle").toDouble() : 365;
int errorType = algResult.contains("error") ? algResult.value("error").toInt() : 16;
double matchScore = algResult.value("score").toDouble() * 100;
QImage maskImg = algResult.value("image").value<QImage>();
QString str = algResult.value("resultTip").toString();
QPointF centerPoint = algResult.value("centerPoint").toPointF();
QString taskName = vMap.value("taskName").toString();
double taskTime = vMap.value("tasktime").toDouble();
// ui.main_label_angle->setText(QString("%1").arg(dAngle));
//
// ValueResult valueRlt;
// valueRlt.angle = dAngle;
// valueRlt.strModel = taskName;
// valueRlt.centerPix = centerPoint;
//
// valueRlt.score = matchScore;
// valueRlt.errorCode = errorType;
// valueRlt.runtime = taskTime;
// valueRlt.pixmap = QPixmap::fromImage(maskImg);
// valueRlt.strRunState = "run Alg success";
// /*中心坐标偏移值计算*/
// int centerX = centerPoint.x() * lpGlobalConfig::instance()->fScale + lpGlobalConfig::instance()->pointXOffset;
// int centerY = centerPoint.y() * lpGlobalConfig::instance()->fScale + lpGlobalConfig::instance()->pointYOffset;
// valueRlt.center.setX(centerX);
// valueRlt.center.setY(centerY);
// if (dAngle >= 361)//NG
// {
// ui.main_value_Result->setStyleSheet("background-color: rgb(250, 0, 0);");
// ui.main_value_Result->setText("找不到气门芯");
// ui.main_value_Center_point->setText("-");
// ui.main_value_Score->setText(QString("%1").arg(matchScore));
// valueRlt.strModel = "NG";
// valueRlt.resultType = 1;//识别出型号 但未标定
// }
// else {//OK
// ui.main_value_Result->setStyleSheet("background-color: rgb(0, 250, 0);");
// ui.main_value_Result->setText("定位成功");
// ui.main_value_Center_point->setText(QString("(%1,%2)").arg(centerPoint.x()).arg(centerPoint.y()));
// ui.main_value_Score->setText(QString("%1").arg(matchScore));
// valueRlt.resultType = 0;//识别出型号 但未标定
// }
// onSaveValveResult(valueRlt);
// /*展示结果*/
// ui.main_value_DetectTime->setText(QString("%1s").arg(taskTime));
// if (m_ImgViewer)
// {
// if (!maskImg.isNull())
// m_ImgViewer->setImg(maskImg);
// }
int stationID = 0;
if (solutionName == lpGlobalConfig::instance()->m_StationSolution_1)
{
stationID = 1;
}
else if (solutionName == lpGlobalConfig::instance()->m_StationSolution_2)
{
stationID = 2;
}
onShowImage(stationID, maskImg);
}
}