catch_ml.cpp

本文展示了一个使用C++编写的简单异常处理程序示例,其中包括了如何在函数中抛出不同类型的数据作为异常,并在catch块中进行捕获处理。

  name="google_ads_frame" marginwidth="0" marginheight="0" src="http://pagead2.googlesyndication.com/pagead/ads?client=ca-pub-5572165936844014&dt=1194442938015&lmt=1194190197&format=336x280_as&output=html&correlator=1194442937843&url=file%3A%2F%2F%2FC%3A%2FDocuments%2520and%2520Settings%2Flhh1%2F%E6%A1%8C%E9%9D%A2%2FCLanguage.htm&color_bg=FFFFFF&color_text=000000&color_link=000000&color_url=FFFFFF&color_border=FFFFFF&ad_type=text&ga_vid=583001034.1194442938&ga_sid=1194442938&ga_hid=1942779085&flash=9&u_h=768&u_w=1024&u_ah=740&u_aw=1024&u_cd=32&u_tz=480&u_java=true" frameborder="0" width="336" scrolling="no" height="280" allowtransparency="allowtransparency"> #include <iostream.h>

void XHandler(int test)
 {
   try
   {
      if(test==0) throw test;
      if(test==1) throw 'a';
      if(test==2) throw 123.23;
    }
   catch(...)
    {
      cout << "Caught one." << endl;
    }
 }

void main(void)
 {
   cout << "Start: " << endl;
   XHandler(0);
   XHandler(1);
   XHandler(2);
   cout << "End";
 }
 

_ConnectionPtr* m_pConnect = new _ConnectionPtr; // 创建连接对象 m_pConnect->CreateInstance(__uuidof(Connection)); string strConnectStr = "Provider=OraOLEDB.Oracle.1;Password=bsoftbsoft;Persist Security Info=True;User ID=bsrun;Data Source=HRP"; //"Provider=SQLOLEDB.1;Password=Kqyy@88063058;Persist Security Info=True;User ID=sa;Initial Catalog=OpenMas;Data Source=168.168.199.11,1433"; try { _bstr_t bstrConnection = strConnectStr.c_str(); if (NULL != *m_pConnect) { (*m_pConnect)->ConnectionString = bstrConnection; (*m_pConnect)->Open("", "", "", NULL); //(*m_pConnect)->Open("Provider=MSDASQL.1;Persist Security Info=False;User ID=sa;Data Source=hissms", (_bstr_t)"sa", (_bstr_t)"Kqyy@88063058", adModeUnknown); } _RecordsetPtr* pRecordsetTbkk = new _RecordsetPtr; pRecordsetTbkk->CreateInstance(__uuidof(Recordset)); (*pRecordsetTbkk)->CursorLocation = adUseClient;// adUseClient; // 必须在Open前设置:ml-citation{ref="3" data="citationList"} FieldsPtr pFields = (*pRecordsetTbkk)->GetFields(); FieldPtr pField2 = pFields->Append("jjje", adDouble, 8, adFldUnspecified); (*pRecordsetTbkk)->Open("SELECT ZY_TBKK.JKXH,ZY_TBKK.ZYH,ZY_BRRY.ZYHM,ZY_BRRY.BRXM,ZY_BRRY.BRCH,ZY_BRRY.BRKS,ZY_TBKK.JKRQ,'' AS DXJE, ZY_TBKK.JKJE, ZY_TBKK.JKJE as jkje2,ZY_TBKK.JKFS,ZY_TBKK.SJHM,ZY_TBKK.ZPHM,ZY_TBKK.ZFPB,ZY_TBKK.CZGH,ZY_TBKK.JGID,zy_tbkk.cdbz,ZY_BRRY.dmpi,ZY_TBKK.zfrq,ZY_TBKK.zfgh,ZY_TBKK.JKRQ as czrq,ZY_TBKK.cwtk,ZY_TBKK.bqczgh FROM ZY_TBKK left join ZY_BRRY on ZY_TBKK.ZYH = ZY_BRRY.ZYH where ZY_TBKK.ZYH in(select distinct(zyh) from zy_zyjs left join gy_ygdm on zy_zyjs.czgh = gy_ygdm.ygdm where jsrq >= to_date('2025-07-31 00:00:00', 'yyyy-mm-dd hh24:mi:ss') and jsrq <= to_date('2025-07-31 23:59:59', 'yyyy-mm-dd hh24:mi:ss') and (czgh = '0' or '0' = '0')) and ZY_TBKK.JKJE > 0 and (ZY_TBKK.zfpb <> 1 or (ZY_TBKK.zfpb = 1 and ZY_TBKK.zfrq > to_date('2025-07-31 23:59:59', 'yyyy-mm-dd hh24:mi:ss'))) order by zyh, jkxh desc", (*m_pConnect).GetInterfacePtr(), adOpenStatic, adLockOptimistic, adCmdText); double dJkje, dJjje; while (!(*pRecordsetTbkk)->adoBOF) { dJkje = GetJCommonInterface()->getDB_DecimalValue((*pRecordsetTbkk)->GetCollect("jkje")); dJjje = GetJCommonInterface()->getDB_DecimalValue((*pRecordsetTbkk)->GetCollect("jjje")); // 报错 "在对应所需名称或序数的集合中,未找到项目。" _variant_t vTest = (*pRecordsetTbkk)->GetCollect("jkje"); _variant_t vTest2 = (*pRecordsetTbkk)->GetCollect("jjje"); (*pRecordsetTbkk)->PutCollect(_variant_t("jkje"), _variant_t(double(dJkje + dJjje))); DECIMAL decVal; VarDecFromR8(0.0, &decVal); VARIANT varTemp; VariantInit(&varTemp); varTemp.vt = VT_DECIMAL; varTemp.decVal = decVal; _variant_t varValue; varValue.vt = VT_DECIMAL; varValue.Attach(varTemp); (*pRecordsetTbkk)->PutCollect(_variant_t("jkje"), _variant_t(double(0.0))); // 检查字段类型 long jjjeType = (*pRecordsetTbkk)->Fields->Item["jjje"]->Type; // 写入数据 if (jjjeType == adDecimal || jjjeType == adNumeric) { DECIMAL decVal; VarDecFromR8(1.1, &decVal); (*pRecordsetTbkk)->PutCollect(_variant_t("jjje"), _variant_t(decVal)); } else { (*pRecordsetTbkk)->Fields->GetItem("jjje")->PutValue(_variant_t(1.1)); (*pRecordsetTbkk)->Fields->Item["jjje"]->Value = vtMissing; (*pRecordsetTbkk)->Fields->Item["jjje"]->Value = _variant_t(1.1); (*pRecordsetTbkk)->PutCollect(_variant_t("jjje"), _variant_t(double(1.1))); } // (*pRecordsetTbkk)->PutCollect(_variant_t("jjje"), _variant_t(double(1.1))); //(*pRecordsetTbkk)->PutCollect(_variant_t("jkje"), varValue); (*pRecordsetTbkk)->MovePrevious(); } } catch (_com_error &e) { string m_strLastErrorInfo = GetJCommonInterface()->getDBErrorDetail(e); return; }
08-14
#include "form_voip.h" #include "ui_form_voip.h" #include "parammanager.h" #include <QPushButton> #include <QMediaDevices> #include <QVideoSink> #include <QCamera> #include <QTimer> #include <QAudioInput> #include <QVideoFrame> using namespace pj; class MyEndpoint : public Endpoint { public: MyEndpoint() : Endpoint() {}; virtual pj_status_t onCredAuth(OnCredAuthParam &prm) { PJ_UNUSED_ARG(prm); std::cout << "*** Callback onCredAuth called ***" << std::endl; /* Return PJ_ENOTSUP to use * pjsip_auth_create_aka_response()/<b>libmilenage</b> (default), * if PJSIP_HAS_DIGEST_AKA_AUTH is defined. */ return PJ_ENOTSUP; } }; class MyAccount; class MyAudioMediaPort: public AudioMediaPort { virtual void onFrameRequested(MediaFrame &frame) { // Give the input frame here frame.type = PJMEDIA_FRAME_TYPE_AUDIO; // frame.buf.assign(frame.size, 'c'); } virtual void onFrameReceived(MediaFrame &frame) { PJ_UNUSED_ARG(frame); // Process the incoming frame here } }; class MyCall : public Call { private: MyAccount *myAcc; AudioMediaPlayer *wav_player; AudioMediaPort *med_port; // 视频窗口指针 VideoWindow *localVideoWin = nullptr; VideoWindow *remoteVideoWin = nullptr; public: MyCall(Account &acc, int call_id = PJSUA_INVALID_ID) : Call(acc, call_id) { wav_player = NULL; med_port = NULL; myAcc = (MyAccount *)&acc; } ~MyCall() { if (wav_player) delete wav_player; if (med_port) delete med_port; // 清理视频窗口 if (localVideoWin) delete localVideoWin; if (remoteVideoWin) delete remoteVideoWin; } virtual void onCallState(OnCallStateParam &prm); virtual void onCallTransferRequest(OnCallTransferRequestParam &prm); virtual void onCallReplaceRequest(OnCallReplaceRequestParam &prm); virtual void onCallMediaState(OnCallMediaStateParam &prm); }; class MyAccount : public Account { public: std::vector<Call *> calls; public: MyAccount() {} ~MyAccount() { std::cout << "*** Account is being deleted: No of calls=" << calls.size() << std::endl; for (std::vector<Call *>::iterator it = calls.begin(); it != calls.end(); ) { delete (*it); it = calls.erase(it); } } void removeCall(Call *call) { for (std::vector<Call *>::iterator it = calls.begin(); it != calls.end(); ++it) { if (*it == call) { calls.erase(it); break; } } } //‌ OnRegStateParam ‌是 PJSUA2 开发框架中的一个参数类,用于处理注册状态的变化。当帐户的注册状态发生变化时, Account 类会触发一个事件,该事件传递 OnRegStateParam 参数,其中包含了注册状态变化的详细信息。 virtual void onRegState(OnRegStateParam &prm) { AccountInfo ai = getInfo(); std::cout << (ai.regIsActive? "***** Register: code=" : "***** Unregister: code=") << prm.code << std::endl; } virtual void onIncomingCall(OnIncomingCallParam &iprm) { Call *call = new MyCall(*this, iprm.callId); CallInfo ci = call->getInfo(); CallOpParam prm; std::cout << "*** Incoming Call: " << ci.remoteUri << " [" << ci.stateText << "]" << std::endl; calls.push_back(call); prm.statusCode = (pjsip_status_code)200; // 2.15.1 必须设置这两个参数 prm.opt.audioCount = 1; prm.opt.videoCount = 1; //prm.opt.audioDir = PJMEDIA_DIR_ENCODING_DECODING; //prm.opt.videoDir = PJMEDIA_DIR_ENCODING_DECODING; prm.opt.mediaDir.push_back(PJMEDIA_DIR_ENCODING_DECODING); // 音频 prm.opt.mediaDir.push_back(PJMEDIA_DIR_ENCODING_DECODING); // 视频 call->answer(prm); //currentCall = call; // 启动来电铃声 // pjmedia_tonegen_param toneParam; // pj_bzero(&toneParam, sizeof(toneParam)); // toneParam.flags = PJMEDIA_TONEGEN_LOOP; // toneParam.tones[0].freq1 = 440; // 音频频率 // toneParam.tones[0].duration = -1; // 持续时间(无限循环) // pjmedia_tonegen_create(pjsua_get_media_transport(), NULL, &toneParam, &call->ringToneId); //使用 pjmedia_tonegen_create 函数创建一个音频生成器来播放铃声。上述代码中,ringToneId 是生成的铃声音频流 ID,用于后续停止铃声 //当用户点击接听按钮时,可以通过调用 answer 方法接听电话,并停止铃声播放 // void MyCall::answerCall() { // CallOpParam answer_op; // answer_op.statusCode = PJSIP_SC_OK; // 使用 200 OK 表示接听电话 // answer(answer_op); // // 停止来电铃声 // if (ringToneId != PJMEDIA_TONEGEN_ID_INVALID) { // pjmedia_tonegen_destroy(ringToneId); // ringToneId = PJMEDIA_TONEGEN_ID_INVALID; // } // PJ_LOG(3, (pj_get_log_writer(), "Call answered!")); // } // 假设这是 GUI 框架中的按钮点击事件处理函数 // void onAnswerButtonClicked(MyCall *call) { // call->answerCall(); // } } // void MyAccount::onIncomingCall(OnIncomingCallParam &iprm) { // PJ_LOG(3, (pj_get_log_writer(), "Incoming call from %.*s!", // (int)iprm.rinfo.fromUri.slen, iprm.rinfo.fromUri.ptr)); // // 创建一个新的 Call 对象 // MyCall *call = new MyCall(*this, iprm.callId); // // 启动来电铃声 // pjmedia_tonegen_param toneParam; // pj_bzero(&toneParam, sizeof(toneParam)); // toneParam.flags = PJMEDIA_TONEGEN_LOOP; // toneParam.tones[0].freq1 = 440; // 音频频率 // toneParam.tones[0].duration = -1; // 持续时间(无限循环) // pjmedia_tonegen_create(pjsua_get_media_transport(), NULL, &toneParam, &call->ringToneId); // } }; //condition_variable cv; void MyCall::onCallState(OnCallStateParam &prm) { PJ_UNUSED_ARG(prm); CallInfo ci = getInfo(); std::cout << "*** Call: " << ci.remoteUri << " [" << ci.stateText << "]" << std::endl; if (ci.state == PJSIP_INV_STATE_DISCONNECTED) { //myAcc->removeCall(this); /* Delete the call */ //delete this; } else if (ci.state == PJSIP_INV_STATE_CONFIRMED) { std::cout << "*** 通话已连接" << std::endl; //callConnected = true; //cv.notify_one(); } } // 创建视频窗口 // void createVideoWindows(int med_idx) { // // 获取视频媒体 // VideoMedia vid_med = getVideoMedia(med_idx); // // 创建本地预览窗口 // VideoPreviewOpParam pre_param; // VideoWindowHandle wnd_handle; // try { // VideoPreview *preview = vid_med.startPreview(pre_param); // VideoWindow win = preview->getVideoWindow(); // win.Show(true); // cout << "本地预览窗口ID: " << win.getInfo().winId << endl; // } catch(Error& err) { // cout << "预览窗口错误: " << err.info() << endl; // } // // 创建远程视频窗口 // try { // VideoWindow remote_win = vid_med.getRemoteVideoWindow(); // remote_win.Show(true); // cout << "远程视频窗口ID: " << remote_win.getInfo().winId << endl; // } catch(Error& err) { // cout << "远程窗口错误: " << err.info() << endl; // } // } void MyCall::onCallMediaState(OnCallMediaStateParam &prm) { PJ_UNUSED_ARG(prm); CallInfo ci = getInfo(); AudioMedia aud_med; AudioMedia& play_dev_med = MyEndpoint::instance().audDevManager().getPlaybackDevMedia(); qDebug()<<"AudioMedia& play_dev_med = MyEndpoint::instance().audDevManager().getPlaybackDevMedia();"; try { // Get the first audio media aud_med = getAudioMedia(-1); } catch(...) { std::cout << "Failed to get audio media" << std::endl; return; } if (!wav_player) { wav_player = new AudioMediaPlayer(); try { wav_player->createPlayer( "./closecall.wav", 0); std::cout << "Success opened wav file" << std::endl; } catch (...) { std::cout << "Failed opening wav file" << std::endl; delete wav_player; wav_player = NULL; } } // This will connect the wav file to the call audio media if (wav_player) wav_player->startTransmit(aud_med); if (!med_port) { med_port = new MyAudioMediaPort(); MediaFormatAudio fmt; fmt.init(PJMEDIA_FORMAT_PCM, 16000, 1, 20000, 16); med_port->createPort("med_port", fmt); // Connect the media port to the call audio media in both directions med_port->startTransmit(aud_med); aud_med.startTransmit(*med_port); } // And this will connect the call audio media to the sound device/speaker aud_med.startTransmit(play_dev_med); // 遍历媒体流 for (unsigned i = 0; i < ci.media.size(); i++) { if (ci.media[i].type == PJMEDIA_TYPE_VIDEO) { // 获取视频媒体流 VideoMedia *vid_med = (VideoMedia *)getMedia(i); if (vid_med) { // 创建本地预览窗口 try { VideoPreviewOpParam pre_param; VideoPreview *preview = vid_med->startPreview(pre_param); localVideoWin = new VideoWindow(preview->getVideoWindow()); localVideoWin->Show(true); //std::cout << "本地预览窗口句柄: " << localVideoWin->getInfo().hwnd << std::endl; } catch(Error& err) { std::cout << "预览窗口错误: " << err.info() << std::endl; } // 创建远程视频窗口 try { remoteVideoWin = new VideoWindow(vid_med->getRemoteVideoWindow()); remoteVideoWin->Show(true); //std::cout << "远程窗口句柄: " << remoteVideoWin->getInfo().hwnd << std::endl; } catch(Error& err) { std::cout << "远程窗口错误: " << err.info() << std::endl; } } } } } void MyCall::onCallTransferRequest(OnCallTransferRequestParam &prm) { /* Create new Call for call transfer */ prm.newCall = new MyCall(*myAcc); } void MyCall::onCallReplaceRequest(OnCallReplaceRequestParam &prm) { /* Create new Call for call replace */ prm.newCall = new MyCall(*myAcc); } Form_VoIP::Form_VoIP(QWidget *parent) : QWidget(parent) , ui(new Ui::Form_VoIP) { ui->setupUi(this); this->resize(1680,920); // 初始化GStreamer qputenv("GST_DEBUG", "2"); // 设置GStreamer调试级别 qputenv("GST_PLUGIN_PATH", "/usr/lib/gstreamer-1.0"); // 设置插件路径 connect(ui->registerButton, &QPushButton::clicked, this, &Form_VoIP::onRegisterClicked); connect(ui->unregisterButton, &QPushButton::clicked, this, &Form_VoIP::onUnRegisterClicked); connect(ui->callButton, &QPushButton::clicked, this, &Form_VoIP::onCallClicked); connect(ui->hangupButton, &QPushButton::clicked, this, &Form_VoIP::onHangupClicked); connect(this, &Form_VoIP::callStateChanged, this, &Form_VoIP::onCallStateChanged); connect(this, &Form_VoIP::incomingVideoFrame, this, &Form_VoIP::handleIncomingFrame); connect(this, &Form_VoIP::outgoingVideoFrame, this, &Form_VoIP::handleOutgoingFrame); } Form_VoIP::~Form_VoIP() { // if (registered) { // this->setRegistration(false); // } ep.libDestroy(); delete ui; } void Form_VoIP::PJSUA2_Init() { if (ep.libGetState() == PJSUA_STATE_NULL) { ep.libCreate(); // 安全调用 } else { return; } qDebug() << "ep.libCreate(); 完成"; pj::EpConfig ep_cfg; ep_cfg.logConfig.level = 5; // 关键设置:启用视频支持 ep_cfg.medConfig.vidCount = 1; // 必须 >=1 才能支持视频 ep_cfg.medConfig.hasIoqueue = true; ep_cfg.medConfig.clockRate = 16000; ep_cfg.medConfig.quality = 10; ep_cfg.medConfig.ecOptions = PJMEDIA_ECHO_USE_SW_ECHO; // 视频配置 - 根据您的ffmpeg参数调整 ep_cfg.vidConfig.capDev = PJMEDIA_VID_DEFAULT_CAPTURE_DEV; ep_cfg.vidConfig.rendDev = PJMEDIA_VID_DEFAULT_RENDER_DEV; ep_cfg.vidConfig.autoShowIncoming = true; ep_cfg.vidConfig.autoTransmitOutgoing = true; // 设置视频格式参数(与您的ffmpeg命令匹配) MediaFormatVideo videoFormat; videoFormat.init(PJMEDIA_FORMAT_RGB24, // formatId 640, // width 480, // height 30, // fpsNum (帧率分子) 1, // fpsDenum (帧率分母) 0, // avgBps (平均比特率,0=自动) 0); // maxBps (最大比特率,0=自动) // 将视频格式应用到配置中 ep_cfg.medConfig.videoConfig.defaultCaptureFormat = videoFormat.toPj(); // 检查是否已执行 libCreate // 检查是否已执行 libInit if (ep.libGetState() == PJSUA_STATE_CREATED) { qDebug() << "开始 ep.libInit(ep_cfg)"; ep.libInit(ep_cfg); } else { return; } qDebug() << "配置视频编解码器参数"; // 配置视频编解码器参数 VidCodecParam vid_codec_param; vid_codec_param.ignoreFmtp = true; // 优先使用H264,如果没有则使用VP8 try { ep.videoCodecSetPriority("H264/97/98", PJMEDIA_CODEC_PRIO_HIGHEST); ep.setVideoCodecParam("H264", vid_codec_param); } catch (...) { qDebug() << "H264编解码器不可用,尝试VP8"; ep.videoCodecSetPriority("VP8", PJMEDIA_CODEC_PRIO_HIGHEST); } qDebug() << "传输配置"; // 传输配置 pj::TransportConfig tcfg; tcfg.port = 5060; ep.transportCreate(PJSIP_TRANSPORT_UDP, tcfg); // 设置默认设备 // ep.audDevManager().setCaptureDev(1); // ep.audDevManager().setPlaybackDev(1); //ep.audDevManager().refreshDevs();// 刷新设备列表 qDebug() << "检查设备"; // 检查设备 if (ep.audDevManager().getDevCount() == 0) { qDebug() << "无音频设备,加载虚拟设备..."; // 调用系统命令加载 snd-dummy(需提前配置) system("sudo modprobe snd-dummy"); ep.audDevManager().refreshDevs(); // 重新刷新 } else { qDebug() << "音频设备数量:"<<ep.audDevManager().getDevCount(); AudioDevInfoVector2 aud_devices = ep.audDevManager().enumDev2(); qDebug() << aud_devices.size(); for (int i = 0; i < aud_devices.size(); i++) { qDebug()<< "设备 " << i << ": " << aud_devices[i].name << " (输入通道: " << aud_devices[i].inputCount << ", 输出通道: " << aud_devices[i].outputCount << ")\n"; } } // ep.audDevManager().setCaptureDev(3); // ep.audDevManager().setPlaybackDev(3); ep.vidDevManager().refreshDevs(); // 手动刷新设备枚举 if (ep.vidDevManager().getDevCount() == 0) { qDebug() << "无视频设备,..."; } else { qDebug() << "视频设备数量:"<<ep.vidDevManager().getDevCount(); } // 获取当前音频设备参数 // AudDevMgr::Param param = ep.audDevMgr().getParam(); // // 设置输入和输出设备ID // param.input_dev = inputDevId; // param.output_dev = outputDevId; // try { // // 应用新的音频设备参数 // ep.audDevMgr().setParam(param); // std::cout << "Successfully configured audio devices with IDs: " // << inputDevId << " (input), " << outputDevId << " (output)." << std::endl; // } catch (Error &err) { // std::cerr << "Failed to set audio device settings: " << err.info() << std::endl; // } // 启动 PJSUA2 ep.libStart(); // 新增自动注册逻辑 // QTimer::singleShot(1000, this, [this]() { // auto& paramMgr = ParamManager::instance(); // QString server = paramMgr.getParamValue("SIP", "Server").toString(); // QString user = paramMgr.getParamValue("SIP", "User").toString(); // QString pass = paramMgr.getParamValue("SIP", "Password").toString(); // if(!server.isEmpty() && !user.isEmpty()) { // registerAccount(server, user, pass); // } // }); } void Form_VoIP::showEvent(QShowEvent *event) { Q_UNUSED(event); qDebug()<<"Form_VoIP::showEvent"; PJSUA2_Init(); //qDebug() << "音频设备数量:"<<ep.audDevManager().getDevCount(); } void Form_VoIP::startStream() { if (streaming) return; streaming = true; VideoDevice::init(); AudioDevice::init(); // 启动视频采集定时器 QTimer *videoTimer = new QTimer(this); connect(videoTimer, &QTimer::timeout, [this](){ QVideoFrame frame = VideoDevice::captureFrame(); if (frame.isValid()) { emit outgoingVideoFrame(frame); } }); videoTimer->start(33); // ~30fps // 音频流处理类似... } void Form_VoIP::stopStream() { if (!streaming) return; streaming = false; VideoDevice::cleanup(); AudioDevice::cleanup(); } void Form_VoIP::handleIncomingFrame(const QVideoFrame &frame) { // 处理接收到的视频帧 // 这里可以添加解码和显示逻辑 } void Form_VoIP::handleOutgoingFrame(const QVideoFrame &frame) { // 处理要发送的视频帧 // 这里可以添加编码和网络传输逻辑 } void Form_VoIP::onRegisterClicked() { m_sipserver = ui->serverEdit->text(); m_sipuser = ui->userEdit->text(); m_sippassword = ui->passwordEdit->text(); registerAccount(m_sipserver, m_sipuser, m_sippassword); } void Form_VoIP::onUnRegisterClicked() { try { if(!acc)return; // 获取已注册的账户对象 Account& account = *acc; // 发送Expires=0的REGISTER请求(注销) account.setRegistration(false); // 核心注销指令 若Account已经注销,则该方法会报错 } catch (pj::Error &e) { std::cerr << "PJSIP Error: " << e.reason << std::endl; // 输出具体错误:ml-citation{ref="4" data="citationList"} } } void Form_VoIP::onCallClicked() { QString number = ui->numberEdit->text(); //makeCall(number); if (currentCall) return; // Make outgoing call Call *call = new MyCall(*acc); acc->calls.push_back(call); CallOpParam prm(true); prm.opt.audioCount = 1; prm.opt.videoCount = 1; // 带视频呼叫 // 设置媒体方向(2.15.1 要求) //prm.opt.audioDir = PJMEDIA_DIR_ENCODING_DECODING; //prm.opt.videoDir = PJMEDIA_DIR_ENCODING_DECODING; prm.opt.mediaDir.push_back(PJMEDIA_DIR_ENCODING_DECODING); // 音频 prm.opt.mediaDir.push_back(PJMEDIA_DIR_ENCODING_DECODING); // 视频 const QString uri = QString("sip:%1@%2").arg(number).arg(m_sipserver); try { call->makeCall(uri.toStdString(), prm); currentCall = call; qDebug() << "发起视频呼叫:" << uri; } catch (pj::Error &e) { delete call; currentCall = nullptr; std::cerr << "PJSIP Error: " << e.reason << std::endl; // 输出具体错误:ml-citation{ref="4" data="citationList"} qDebug() << "呼叫失败:" << e.reason.c_str(); } // pj::Call *call = new pj::Call(*this); // pj::CallOpParam prm(true); // currentCall = call; // try { // call->makeCall("sip:" + uri.toStdString(), prm); // emit callStateChanged(1); // 连接中 // } catch (...) { // delete call; // currentCall = nullptr; // emit callStateChanged(0); // 空闲状态 // } } void Form_VoIP::onHangupClicked() { //hangup(); currentCall = nullptr; ep.hangupAllCalls(); } void Form_VoIP::onCallStateChanged(int state) { // 更新界面状态 // 0: 空闲, 1: 连接中, 2: 通话中 if (state == 2) { // 通话中 setupVideoCall(); } //有拨号界面时,关闭拨号 // else if (callWindow) { // callWindow->close(); // callWindow = nullptr; // } } void Form_VoIP::setupVideoCall() { // if (!callWindow) // { // callWindow = new CallWindow(this); // VideoDevice::init(); // connect(VideoDevice::instance(), &VideoDevice::frameAvailable, // callWindow, [this](const QVideoFrame &frame) { // // 获取本地视频项的videoSink并设置视频帧 // if (auto sink = callWindow->localVideoItem()->videoSink()) { // sink->setVideoFrame(frame); // } // }); // } // callWindow->show(); VideoDevice::init(); connect(VideoDevice::instance(), &VideoDevice::frameAvailable, this, [this](const QVideoFrame &frame) { // if (auto* sink = this->localVideoItem()->videoSink()) { // 明确指出 sink 是指针类型 // if (sink && sink->isActive()) { // 添加必要的有效性检查 // qDebug() << "Video sink is active."; // sink->setVideoFrame(frame); // } else { // qDebug() << "No valid video sink or it's inactive."; // } // } // 获取本地视频项的videoSink并设置视频帧 if (auto sink = this->localVideoItem->videoSink()) { sink->setVideoFrame(frame); } }); } AudioFilter::AudioFilter(int frameSize, int sampleRate) : frameSize(frameSize), sampleRate(sampleRate) { m_format.setSampleRate(sampleRate); m_format.setChannelCount(1); m_format.setSampleFormat(QAudioFormat::Int16); // 获取默认音频输入设备并创建QAudioInput QAudioDevice inputDevice = QMediaDevices::defaultAudioInput(); if (!inputDevice.isFormatSupported(m_format)) { qWarning() << "Default audio input device does not support the required format"; m_format = inputDevice.preferredFormat(); } // m_audioInput = new QAudioInput(inputDevice, m_format, this); // // 设置音频处理选项 // QAudioInputOptions options; // options.setEchoCancel(true); // options.setNoiseSuppression(true); // m_audioInput->setOptions(options); // // 启动音频输入 // m_audioInput->start(); } AudioFilter::~AudioFilter() { //m_audioDevice.stop(); } void AudioFilter::processCapture(const QAudioBuffer &input, QAudioBuffer &output) { // Qt6.7处理逻辑 - 使用QAudioSink处理输入 // QAudioSink sink(m_audioDevice, m_format); // sink.start(); // sink.write(input.data(), input.byteCount()); // // 处理输出缓冲区 // QAudioSource source(m_audioDevice, m_format); // source.start(); // source.read(output.data(), output.byteCount()); } void AudioFilter::processPlayback(const QAudioBuffer &input) { // QAudioSink sink(m_audioDevice, m_format); // QIODevice *ioDevice = sink.start(); // if (ioDevice) { // ioDevice->write(input.constData<char>(), input.byteCount()); // } // sink.stop(); // sink.write(input.data(), input.byteCount()); } // 静态成员变量定义 QAudioDevice AudioDevice::m_inputDevice; QAudioDevice AudioDevice::m_outputDevice; QAudioFormat AudioDevice::m_format; void AudioDevice::init() { // 初始化音频格式 m_format.setSampleRate(44100); m_format.setChannelCount(2); m_format.setSampleFormat(QAudioFormat::Int16); // 获取默认输入输出设备 m_inputDevice = QMediaDevices::defaultAudioInput(); m_outputDevice = QMediaDevices::defaultAudioOutput(); // 验证设备是否支持所需格式 if (!m_inputDevice.isFormatSupported(m_format)) { qWarning() << "Default input device does not support required format"; } if (!m_outputDevice.isFormatSupported(m_format)) { qWarning() << "Default output device does not support required format"; } } void AudioDevice::cleanup() { // 清理音频资源 m_inputDevice = QAudioDevice(); m_outputDevice = QAudioDevice(); } int AudioDevice::capture(void *buffer, int samples) { static QAudioSource *input = nullptr; if (!input) { input = new QAudioSource(m_inputDevice, m_format); } if (input->state() == QAudio::StoppedState) { //input->start(buffer); } return 0;//input->read((char*)buffer, samples * m_format.bytesPerSample()); } int AudioDevice::play(void *buffer, int samples) { static QAudioSink *output = nullptr; static QIODevice *ioDevice = nullptr; if (!output) { output = new QAudioSink(m_outputDevice, m_format); ioDevice = output->start(); } if (ioDevice) { return ioDevice->write(static_cast<const char*>(buffer), samples); } return 0; if (output->state() == QAudio::StoppedState) { //output->start(buffer); } return 0;//output->write((const char*)buffer, samples * m_format.bytesPerSample()); } VideoDevice *VideoDevice::m_instance = nullptr; QCamera *VideoDevice::camera = nullptr; VideoDevice *VideoDevice::instance() { if (!m_instance) { m_instance = new VideoDevice(); } return m_instance; } VideoDevice::VideoDevice(QObject *parent) : QObject(parent) {} void VideoDevice::init() { auto videoInputs = QMediaDevices::videoInputs(); if (videoInputs.isEmpty()) { qWarning() << "No video input devices found"; return; } // 配置视频格式以匹配您的ffmpeg参数 QCameraFormat format; foreach (auto fmt, videoInputs.first().videoFormats()) { if (fmt.resolution() == QSize(640, 480) && fmt.maxFrameRate() >= 30) { format = fmt; break; } } if (!format.isNull()) { camera = new QCamera(videoInputs.first()); camera->setCameraFormat(format); auto *captureSession = new QMediaCaptureSession; captureSession->setCamera(camera); auto *videoSink = new QVideoSink; QObject::connect(videoSink, &QVideoSink::videoFrameChanged, [](const QVideoFrame &frame) { emit VideoDevice::instance()->frameAvailable(frame); }); captureSession->setVideoSink(videoSink); camera->start(); qDebug() << "摄像头启动: 640x480 @ 30fps"; } else { qWarning() << "未找到匹配的视频格式"; } } void VideoDevice::cleanup() { if (camera) { camera->stop(); delete camera; camera = nullptr; } } QVideoFrame VideoDevice::captureFrame() { if (!camera) return QVideoFrame(); // 创建视频帧并映射内存 //QVideoFrame frame(QSize(640, 480), QVideoFrameFormat::Format_ARGB8888); // 先创建格式对象 QVideoFrameFormat format( QSize(640, 480), QVideoFrameFormat::Format_ARGB8888 ); // 再创建视频帧对象 QVideoFrame frame(format); if (frame.map(QVideoFrame::WriteOnly)) { // 这里可以填充帧数据 frame.unmap(); } return frame; } void Form_VoIP::registerAccount(const QString &server, const QString &user, const QString &pass) { accCfg.idUri = "sip:" + user.toStdString() + "@" + server.toStdString(); accCfg.regConfig.registrarUri = "sip:" + server.toStdString(); accCfg.callConfig.timerMinSESec = 90; // 强制最小值 accCfg.callConfig.timerSessExpiresSec = 1800; // 推荐30分钟超时 accCfg.sipConfig.authCreds.push_back( pj::AuthCredInfo("digest", "*", user.toStdString(), 0, pass.toStdString()) ); // 关键:启用视频配置 accCfg.videoConfig.autoShowIncoming = true; accCfg.videoConfig.autoTransmitOutgoing = true; accCfg.videoConfig.defaultCaptureDevice = PJMEDIA_VID_DEFAULT_CAPTURE_DEV; accCfg.videoConfig.defaultRenderDevice = PJMEDIA_VID_DEFAULT_RENDER_DEV; // 设置媒体功能 MediaFormatVideo accVideoFormat; accVideoFormat.init(PJMEDIA_FORMAT_RGB24, 640, 480, 30, 1, 0, 0); // acc= new MyAccount; try { acc->create(accCfg); registered = true; emit callStateChanged(0); } catch (...) { std::cout << "Adding account failed" << std::endl; registered = false; } } void Form_VoIP::hangup() { if (currentCall) { try { pj::CallOpParam prm; currentCall->hangup(prm); currentCall = nullptr; emit callStateChanged(0); // 空闲状态 } catch (pj::Error &e) { currentCall = nullptr; std::cerr << "PJSIP Error: " << e.reason << std::endl; // 输出具体错误:ml-citation{ref="4" data="citationList"} } } //hangUpAllCalls(); } //还没调好 void Form_VoIP::hangUpAllCalls() { std::vector<pj::Call*> calls = acc->calls; for (auto call : calls) { CallInfo ci = call->getInfo(); if (ci.state != PJSIP_INV_STATE_DISCONNECTED) { try { pj::CallOpParam prm; call->hangup(prm); } catch (...) { // 处理可能的异常 } } } } void Form_VoIP::setVideoWindows(QVideoSink *local, QVideoSink *remote) { // Qt6.7视频架构兼容实现 if (remote) { connect(this, &Form_VoIP::incomingVideoFrame, this, [remote](const QVideoFrame &frame) { QVideoFrame clonedFrame(frame); clonedFrame.map(QVideoFrame::ReadOnly); remote->setVideoFrame(clonedFrame); clonedFrame.unmap(); }, Qt::QueuedConnection); } if (local) { connect(this, &Form_VoIP::outgoingVideoFrame, this, [local](const QVideoFrame &frame) { QVideoFrame clonedFrame(frame); clonedFrame.map(QVideoFrame::ReadOnly); local->setVideoFrame(clonedFrame); clonedFrame.unmap(); }, Qt::QueuedConnection); } } 编译报错/home/shz/Project/appHDQt6/form_voip.cpp:322: error: ‘class pj::VideoMedia’ has no member named ‘startPreview’ ../../form_voip.cpp: In member function ‘virtual void MyCall::onCallMediaState(pj::OnCallMediaStateParam&)’: ../../form_voip.cpp:322:54: error: ‘class pj::VideoMedia’ has no member named ‘startPreview’ 322 | VideoPreview *preview = vid_med->startPreview(pre_param); | ^~~~~~~~~~~~/home/shz/Project/appHDQt6/form_voip.cpp:332: error: ‘class pj::VideoMedia’ has no member named ‘getRemoteVideoWindow’ ../../form_voip.cpp:332:63: error: ‘class pj::VideoMedia’ has no member named ‘getRemoteVideoWindow’ 332 | remoteVideoWin = new VideoWindow(vid_med->getRemoteVideoWindow()); | ^~~~~~~~~~~~~~~~~~~~/home/shz/Project/appHDQt6/form_voip.cpp:410: error: ‘struct pj::MediaConfig’ has no member named ‘vidCount’ ../../form_voip.cpp: In member function ‘void Form_VoIP::PJSUA2_Init()’: ../../form_voip.cpp:410:22: error: ‘struct pj::MediaConfig’ has no member named ‘vidCount’ 410 | ep_cfg.medConfig.vidCount = 1; // 必须 >=1 才能支持视频 | ^~~~~~~~/home/shz/Project/appHDQt6/form_voip.cpp:417: error: ‘struct pj::EpConfig’ has no member named ‘vidConfig’; did you mean ‘medConfig’? ../../form_voip.cpp:417:12: error: ‘struct pj::EpConfig’ has no member named ‘vidConfig’; did you mean ‘medConfig’? 417 | ep_cfg.vidConfig.capDev = PJMEDIA_VID_DEFAULT_CAPTURE_DEV; | ^~~~~~~~~ | medConfig/home/shz/Project/appHDQt6/form_voip.cpp:433: error: ‘struct pj::MediaConfig’ has no member named ‘videoConfig’ ../../form_voip.cpp:433:22: error: ‘struct pj::MediaConfig’ has no member named ‘videoConfig’ 433 | ep_cfg.medConfig.videoConfig.defaultCaptureFormat = videoFormat.toPj(); | ^~~~~~~~~~~/home/shz/Project/appHDQt6/form_voip.cpp:885: error: invalid use of incomplete type ‘class QMediaCaptureSession’ ../../form_voip.cpp: In static member function ‘static void VideoDevice::init()’: ../../form_voip.cpp:885:36: error: invalid use of incomplete type ‘class QMediaCaptureSession’ 885 | auto *captureSession = new QMediaCaptureSession; | ^~~~~~~~~~~~~~~~~~~~
09-27
#include "pch.h" #include "LCMESClass.h" #include <QDateTime> #include <mmsystem.h> extern CGlobalFunction m_GFunction; // 全局函数 extern Loger m_Loger; // 全局Log类 extern CGlobalVariant m_GVariant; // 全局变量 extern CDlgDevError m_dlgError; // 错误信息对话框 extern CActionFlow m_GActionFlow; // 主动作流程 extern CAction_Station3Tester m_GActionTester; // 测试工位流程 #pragma comment(lib, "winmm.lib") LCMESClass* LCMESClass::m_pInstance = nullptr; LCMESClass* LCMESClass::GetInstance() { static CCriticalSection cs; CriticalSectionLock lock(cs); // 使用我们之前定义的 RAII 锁 if (m_pInstance == nullptr) // 错误:m_pInstance 未声明 { m_pInstance = new LCMESClass(); } return m_pInstance; } LCMESClass::LCMESClass() { updataRun = false; StartWorkerThread(); } LCMESClass::~LCMESClass() { StopWorkerThread(); StopTimer(); } void LCMESClass::StartWorkerThread() { if (m_pWorkerThread == nullptr) { m_pWorkerThread = AfxBeginThread(WorkerThreadProc, this); } } void LCMESClass::StopWorkerThread() { if (m_pWorkerThread != nullptr) { m_bStopThread = true; m_taskEvent.SetEvent(); // 唤醒线程退出 WaitForSingleObject(m_pWorkerThread->m_hThread, INFINITE); m_pWorkerThread = nullptr; } } void LCMESClass::PostTask(TaskType type, const CString& param, const CString& param2) { if (m_GVariant.m_MesConfig->Enable == 0) { return; } TaskItem* pItem = new TaskItem(); pItem->type = type; pItem->param = param; pItem->param2 = param2; { CriticalSectionLock lock(m_cs); // 使用自定义锁 m_taskList.AddTail(pItem); } m_taskEvent.SetEvent(); // 触发事件 } UINT LCMESClass::WorkerThreadProc(LPVOID pParam) { LCMESClass* pThis = (LCMESClass*)pParam; while (!pThis->m_bStopThread) { DWORD dwWait = WaitForSingleObject(pThis->m_taskEvent.m_hObject, INFINITE); if (dwWait != WAIT_OBJECT_0) continue; if (pThis->m_bStopThread) break; TaskItem* pItem = nullptr; { CriticalSectionLock lock(pThis->m_cs); // 使用自定义锁 if (!pThis->m_taskList.IsEmpty()) { pItem = pThis->m_taskList.RemoveHead(); } } if (pItem) { pThis->ProcessTask(pItem); delete pItem; } } return 0; } void LCMESClass::ProcessTask(TaskItem* pItem) { switch (pItem->type) { case TASK_EVENT_PRODUCT_MOVED: ExecuteProductMoved(_ttoi(pItem->param), m_GFunction.CString2String(pItem->param2)); break; case TASK_EVENT_DEVICE_STATE_CHANGED: ExecuteDeviceStateChanged(_ttoi(pItem->param)); break; case TASK_EVENT_TEST_END: ExecuteTestEnd(m_GFunction.CString2String(pItem->param)); break; case TASK_STATISTICS: ExecuteStatistics(); case TASK_ALARM_CLEAR: ExecuteAlarmClear(); break; } } void LCMESClass::ExecuteProductMoved(const int & state, const string& sn) { CriticalSectionLock lock(m_cs); // 线程安全调用 this->ProductMoved(static_cast<ProductPosition>(state), sn); } void LCMESClass::ExecuteDeviceStateChanged(int state) { CriticalSectionLock lock(m_cs); // 线程安全调用 DeviceState deviceState = static_cast<DeviceState>(state); this->DeviceStateChanged(deviceState); } void LCMESClass::ExecuteTestEnd(string sn) { CriticalSectionLock lock(m_cs); // 线程安全调用 this->TestEnd(sn); } void LCMESClass::ExecuteStatistics() { CriticalSectionLock lock(m_cs); // 发送统计数量总计和OK品数量 this->sendStatistics(); } void LCMESClass::ExecuteAlarmClear() { CriticalSectionLock lock(m_cs); this->DeviceAlarmCleared(); } // 定时五分钟发送统计数量总计和OK品数量 void LCMESClass::StartTimer(UINT interval) { if (m_GVariant.m_MesConfig->Enable == 0) { return; } if (m_timerID == 0) { m_timerID = timeSetEvent( interval, 10, TimerProc, (DWORD_PTR)this, TIME_PERIODIC | TIME_CALLBACK_FUNCTION); } } void LCMESClass::StopTimer() { // 停止定时器(需保存 timer ID) if (m_timerID != 0) { timeKillEvent(m_timerID); m_timerID = 0; } } void CALLBACK LCMESClass::TimerProc(UINT uID, UINT uMsg, DWORD_PTR dwUser, DWORD_PTR dw1, DWORD_PTR dw2) { LCMESClass* pThis = (LCMESClass*)dwUser; if (pThis) { pThis->PostTask(TASK_STATISTICS); } } // 产品check Response LCMESClass::EquipmentTextData_Check(string info) { CriticalSectionLock lock(m_cs); // 使用类成员 CCriticalSection m_cs; // 原始配置 string hostname = m_GVariant.m_MesConfig->Host; int port = m_GVariant.m_MesConfig->Port; string api = m_GVariant.m_MesConfig->Check; Response resp = Send(info, hostname, port, api); if (SUCCESS == resp.Code) { return ParseRcv(resp.Msg); } return resp; } // 产品过站 Response LCMESClass::EquipmentTextData_Save(string info) { // 原始配置 string hostname = m_GVariant.m_MesConfig->Host; int port = m_GVariant.m_MesConfig->Port; string api = m_GVariant.m_MesConfig->Check; Response resp = Send(info, hostname, port, api); if (SUCCESS == resp.Code) { return ParseRcv(resp.Msg); } return resp; } // 产品生产过程事件、配方比对 Response LCMESClass::deviceInfoCollerct(string info) { // 原始配置 string hostname = m_GVariant.m_MesConfig->Host; int port = m_GVariant.m_MesConfig->Port; string api = m_GVariant.m_MesConfig->Check; Response resp = Send(info, hostname, port, api); if (SUCCESS == resp.Code) { return ParseRcv(resp.Msg); } return resp; } void LCMESClass::Connect() { CriticalSectionLock lock(m_cs); // 使用类成员 CCriticalSection m_cs; if (m_GVariant.m_MesConfig->Enable == 0) { return; } std::string hostname = m_GVariant.m_MesConfig->Host; int port = m_GVariant.m_MesConfig->Port; // 如果已有连接且目标主机和端口一致,直接复用 if (m_pConnection) { if (m_cachedHost == hostname && m_cachedPort == port) { return; // 已连接到目标主机,无需重复连接 } else { // 不同主机或端口,释放旧连接 delete m_pConnection; m_pConnection = nullptr; } } // 设置全局超时参数 HINTERNET hSession = (HINTERNET)m_Session; // ✅ 正确获取 HINTERNET 句柄 if (hSession) { DWORD connectTimeout = 5000; // 5 秒 DWORD sendTimeout = m_GVariant.m_MesConfig->SendTimeout; DWORD recvTimeout = m_GVariant.m_MesConfig->RecvTimeout; InternetSetOption(hSession, INTERNET_OPTION_CONNECT_TIMEOUT, &connectTimeout, sizeof(connectTimeout)); InternetSetOption(hSession, INTERNET_OPTION_SEND_TIMEOUT, &sendTimeout, sizeof(sendTimeout)); InternetSetOption(hSession, INTERNET_OPTION_RECEIVE_TIMEOUT, &recvTimeout, sizeof(recvTimeout)); } // 创建新连接 m_cachedHost = hostname; m_cachedPort = port; m_pConnection = m_Session.GetHttpConnection( m_GFunction.String2CString(hostname), port, _T(""), // username _T("") // password ); if (!m_pConnection) { // 连接失败,记录错误 CString logMessage; logMessage.Format(_T("连接到 %s:%d 失败,无法创建 HTTP 连接\n"), m_GFunction.String2CString(hostname), port); addInfo(m_GFunction.CString2String(logMessage)); } } Response LCMESClass::Send(const string & info, const string & hostname, const int & port, const string & apiPath) { CriticalSectionLock lock(m_cs); // ✅ 加锁 Response resp; if (!m_pConnection) { resp.Code = NETWORK_ERROR; resp.Msg = "Not connected to server. Call Connect() first."; return resp; } try { auto deleter = [](CHttpFile* p) { if (p) delete p; }; std::unique_ptr<CHttpFile, decltype(deleter)> pFile( m_pConnection->OpenRequest(CHttpConnection::HTTP_VERB_POST, m_GFunction.String2CString(apiPath)), deleter); CString strHeaders = _T("Content-Type: application/json"); CString strData = m_GFunction.String2CString(info); pFile->SendRequest ( strHeaders, (DWORD)strHeaders.GetLength(), (LPVOID)(LPCTSTR)strData, (DWORD)strData.GetLength() ); DWORD dwStatusCode; pFile->QueryInfoStatusCode(dwStatusCode); CString strResponse; if (dwStatusCode == HTTP_STATUS_OK) { TCHAR szBuffer[1024]; while (pFile->Read(szBuffer, 1023) > 0) { strResponse += szBuffer; } } if (dwStatusCode != HTTP_STATUS_OK) { resp.Code = HTTP_ERROR; resp.Msg = std::to_string(dwStatusCode); return resp; } resp.Msg = m_GFunction.CString2String(strResponse); pFile->Close(); } catch (CInternetException* pEx) { TCHAR szError[1024]; pEx->GetErrorMessage(szError, 1024); resp.Msg = m_GFunction.CString2String(szError);// 异常信息写入resultMSG pEx->Delete(); resp.Code = NETWORK_ERROR; return resp; } resp.Code = SUCCESS; return resp; } void LCMESClass::PullMes() { CriticalSectionLock lock(m_cs); // ✅ 加锁 if (m_GVariant.m_MesConfig->Enable == 0) { return; } sSC_PullMes.Init(); updataRun = true; while (true) { int iRtn = FL_PullMes(); if (-1 == iRtn) { updataRun = false; break; } Sleep(5); } } int LCMESClass::Check(string sn) { CriticalSectionLock lock(m_cs); // ✅ 加锁 if (m_GVariant.m_MesConfig->Enable == 0) { return 1; } Check_MesInfo checkInof; checkInof.EquipmentEncode = m_GVariant.m_MesConfig->m_MesInfo.EquipmentEncode; checkInof.SpecificationName = m_GVariant.m_MesConfig->m_MesInfo.SpecificationName; checkInof.UserName = m_GVariant.m_MesConfig->m_MesInfo.UserName; checkInof.SN = QString::fromLocal8Bit(sn.c_str()); QJsonObject jsonObj; serializeToJsonFile(checkInof, jsonObj); QJsonDocument doc(jsonObj); QString jsonMesInfo = doc.toJson(QJsonDocument::Compact); jsonMesInfo = jsonMesInfo.replace("/", "//"); jsonMesInfo = jsonMesInfo.replace("\"", "\\\""); jsonMesInfo = "{\"jsonData\":\"" + jsonMesInfo + "\"}"; jsonMesInfo = jsonMesInfo.replace("\r", ""); string info = jsonMesInfo.toLocal8Bit(); Response res = EquipmentTextData_Check(info); if (res.Code == 0 || res.Result == "OK") { return 1; } else { addErrInfo(res.Msg); return -1; } } int LCMESClass::getDeviceInfoCollerctResult(Device_MesInfo& mes) { CriticalSectionLock lock(m_cs); // ✅ 加锁 mes.EquipmentEncode = m_GVariant.m_MesConfig->m_MesInfo.EquipmentEncode; mes.type = 1; mes.SpecificationName = m_GVariant.m_MesConfig->m_MesInfo.SpecificationName; mes.UserName = m_GVariant.m_MesConfig->m_MesInfo.UserName; mes.DocumentMD5 = QString::fromLocal8Bit(m_GActionTester.md5forconfig.c_str()); mes.deviceParams.Total = m_GActionFlow.m_Statistics.m_lTotal; mes.deviceParams.OKCount = (m_GActionFlow.m_Statistics.m_lBest + m_GActionFlow.m_Statistics.m_lMed + m_GActionFlow.m_Statistics.m_lPass); QJsonObject jsonObj; serializeToJsonFile(mes, jsonObj); QJsonDocument doc(jsonObj); QString jsonMesInfo = doc.toJson(QJsonDocument::Compact); jsonMesInfo = jsonMesInfo.replace("/", "//"); jsonMesInfo = jsonMesInfo.replace("\"", "\\\""); jsonMesInfo = "{\"jsonData\":\"" + jsonMesInfo + "\"}"; jsonMesInfo = jsonMesInfo.replace("\r", ""); string info = jsonMesInfo.toLocal8Bit(); Response res = deviceInfoCollerct(info); if (res.Code == 0 || res.Result == "OK") { return 1; } else { addErrInfo(res.Msg); return -1; } return 0; } int LCMESClass::DeviceStateChanged(DeviceState state) { CriticalSectionLock lock(m_cs); // ✅ 加锁 string eventDesc = ""; int deviceStatus = 0; switch (state) { case Waiting: eventDesc = "待机"; deviceStatus = 1; break; case Wroking: eventDesc = "作业"; deviceStatus = 2; break; case Faulted: eventDesc = "故障"; deviceStatus = 3; break; case Stopped: eventDesc = "关机"; deviceStatus = 4; break; default: eventDesc = "开机"; deviceStatus = 0; break; } Device_MesInfo mes; mes.eventName = QString::fromLocal8Bit("设备状态"); mes.eventDesc = QString::fromLocal8Bit(eventDesc.c_str()); mes.deviceStatus = deviceStatus; return getDeviceInfoCollerctResult(mes); } // 设备状态解除事件 int LCMESClass::DeviceAlarmCleared() { CriticalSectionLock lock(m_cs); // ✅ 加锁 Device_MesInfo mes; mes.eventName = QString::fromLocal8Bit("报警解除"); mes.eventDesc = QString::fromLocal8Bit("设备报警状态已被人工确认后解除,恢复待机"); mes.deviceStatus = 1; // 待机1 return getDeviceInfoCollerctResult(mes); } // 产品移动事件 int LCMESClass::ProductMoved(ProductPosition ProductPosition, string sn) { CriticalSectionLock lock(m_cs); // ✅ 加锁 string value = "未知"; switch (ProductPosition) { case In: value = "接料"; break; case Out: value = "出料"; break; default: value = "未知"; break; } Device_MesInfo mes; mes.eventName = QString::fromLocal8Bit("产品移动"); mes.eventDesc = QString::fromLocal8Bit(value.c_str()); // 接料/出料 mes.deviceStatus = 2; // 作业2 mes.deviceParams.SN = QString::fromLocal8Bit(sn.c_str()); return getDeviceInfoCollerctResult(mes); } // 测试完成发送完工报告事件 int LCMESClass::TestEnd(string sn) { CriticalSectionLock lock(m_cs); // ✅ 加锁 Device_MesInfo mes; mes.eventName = QString::fromLocal8Bit("测试完成"); mes.eventDesc = QString::fromLocal8Bit("测试软件完成产品测试"); mes.deviceStatus = 2; // 作业2 mes.deviceParams.SN = QString::fromLocal8Bit(sn.c_str()); return getDeviceInfoCollerctResult(mes); } int LCMESClass::sendStatistics() { CriticalSectionLock lock(m_cs); // ✅ 加锁 Device_MesInfo mes; mes.eventName = QString::fromLocal8Bit("生产产品数量"); mes.eventDesc = QString::fromLocal8Bit("统计所有物料和OK物料的数量"); return getDeviceInfoCollerctResult(mes); } Response LCMESClass::ParseRcv(string& msg) { json j = json::parse(msg); return Response::from_json(j); } int LCMESClass::FL_PullMes() { int iRtn = 0; switch (sSC_PullMes.nStep) { case 0: addInfo(sSC_PullMes, 5, "开始巡检MES目录", true); return 0; case 5: iRtn = checkFolder(); if (-1 == iRtn) { addInfo(sSC_PullMes, ST_ERR, "巡检MES目录失败"); } if (1 == iRtn) { sSC_PullMes.nStep = 10; } else { sSC_PullMes.SetDelay(5, 1000); } return 0; case 10: if (m_File.checkFileExist(m_destinationFolder, m_currentFileNames)) { sSC_PullMes.nStep = 15; //addInfo(sSC_PullMes, 10, "检查所有文件都剪切完成;准备解析文件"); } else { addInfo(sSC_PullMes, ST_ERR, "检查MES文件是否存在失败"); } return 0; case 15: if (m_bufferFileNames.size() == 0) { sSC_PullMes.nStep = ST_END; } else { sSC_PullMes.nStep = 20; } return 0; case 20: if (m_iItemIndex <= m_bufferFileNames.size() - 1) { m_qstrRemoveFile = m_bufferFileNames[m_iItemIndex]; QString tempFile = m_destinationFolder + "\\" + m_qstrRemoveFile; if (deserializeFromJsonFile(tempFile, m_MesInfo)) { if (m_MesInfo.Barcode == "" || m_MesInfo.Barcode.length() < 5) { m_iItemIndex = 0;//将索引归零 addInfo(sSC_PullMes, 15, "条码长度小于5:条码为" + (string)m_MesInfo.Barcode.toLocal8Bit()); m_bufferFileNames.removeOne(m_bufferFileNames[m_iItemIndex]); } else { m_iItemIndex++; m_qqmesInfos.append(m_MesInfo); if (1 == m_GVariant.m_MesConfig->TestAngleCount) { addInfo(sSC_PullMes, 25, "准备上传单角度数据"); } else { if (m_qqmesInfos.size() == 1) { m_AllRemoveFileNames.append(m_bufferFileNames[m_iItemIndex]); m_bufferFileNames.removeOne(m_bufferFileNames[m_iItemIndex]); m_iItemIndex = 0; addInfo(sSC_PullMes, 15, "上传双角度,但是只有角度1数据,继续寻找角度2数据文件"); } else if (m_qqmesInfos.size() == 2) { addInfo(sSC_PullMes, 30, "准备上传双角度数据"); } } } } else { addInfo(sSC_PullMes, ST_ERR, "文件" + (string)tempFile.toLocal8Bit() + "json序列化失败"); } } else { addInfo(sSC_PullMes, ST_END, "缓存文件已上传完毕"); } return 0; case 25: iRtn = updataMes(m_MesInfo, m_GVariant.m_MesConfig->m_MesInfo); if (1 == iRtn) { //清空队列中的 m_bufferFileNames.removeOne(m_qstrRemoveFile); m_qqmesInfos.clear(); m_iItemIndex = 0;//将索引归零 addInfo(sSC_PullMes, 15, "单角度上传完成,开始缓存新MES数据"); } else if (-1 == iRtn) { sSC_PullMes.nStep = ST_ERR; } return 0; case 30: if (m_qqmesInfos[0].Barcode == m_qqmesInfos[1].Barcode) { m_AllRemoveFileNames.append(m_qstrRemoveFile); iCount = 0; addInfo(sSC_PullMes, 35, "比对2次条码一致,准备合并上传"); } else { m_qqmesInfos.removeAt(1); iCount++; addInfo(sSC_PullMes, 15, "比对2次条码不一致,继续寻找相同条码文件"); if (iCount >= 2) { iCount = 0; m_AllRemoveFileNames.clear(); m_qqmesInfos.clear(); m_iItemIndex = 0;//将索引归零 } } return 0; case 35: iRtn = updataMes(m_qqmesInfos, m_GVariant.m_MesConfig->m_MesInfo); if (-1 == iRtn) { sSC_PullMes.nStep = ST_ERR; } if (1 == iRtn) { m_bufferFileNames.removeOne(m_AllRemoveFileNames[0]); m_bufferFileNames.removeOne(m_AllRemoveFileNames[1]); m_qqmesInfos.clear(); m_AllRemoveFileNames.clear(); m_iItemIndex = 0; addInfo(sSC_PullMes, 15, "双角度合并上传完成"); } return 0; case ST_DELAY: if (GetTickCount() - sSC_PullMes.dwStart >= sSC_PullMes.dwDelay) { sSC_PullMes.nStep = sSC_PullMes.nStepNext; } return 0; case ST_ERR: return -1; case ST_END: sSC_PullMes.ulCountEnd = m_GFunction.GetCPUPerformanceCounter(); sSC_PullMes.dCycleTime = (sSC_PullMes.ulCountEnd - sSC_PullMes.ulCountStart) / 1000.0; sSC_PullMes.AddCTRecordEnd(m_Loger.m_iRecordCycleTime, "Handler流程初始化执行结束", sSC_PullMes.dCycleTime); if (1 == m_Loger.m_iRecordCycleTime) m_Loger.RecordLogOperation(sSC_PullMes.strRecord);// 添加到缓存变量 sSC_PullMes.Init(); return 1; default: sSC_PullMes.Init(); break; } return 0; } int LCMESClass::checkFolder() { CriticalSectionLock lock(m_cs); // ✅ 加锁 m_currentFileNames.clear(); QString m_sourceFolder = QString::fromLocal8Bit(m_GVariant.m_MesConfig->Path_SourceTestFile.c_str()) + "\\MES" + QDateTime::currentDateTime().addDays(-1).toString("yyyyMMdd"); m_destinationFolder = QString::fromLocal8Bit(m_GVariant.m_MesConfig->Path_DestTestFile.c_str()) + "\\" + QDateTime::currentDateTime().addDays(-1).toString("yyyyMMdd"); bool result1 = m_File.moveAllFiles(m_sourceFolder, m_destinationFolder, m_currentFileNames); m_sourceFolder = QString::fromLocal8Bit(m_GVariant.m_MesConfig->Path_SourceTestFile.c_str()) + "\\MES" + QDateTime::currentDateTime().toString("yyyyMMdd"); m_destinationFolder = QString::fromLocal8Bit(m_GVariant.m_MesConfig->Path_DestTestFile.c_str()) + "\\" + QDateTime::currentDateTime().toString("yyyyMMdd"); bool result2 = m_File.moveAllFiles(m_sourceFolder, m_destinationFolder, m_currentFileNames); if (result1 || result2) { if (m_currentFileNames.size() > 0) { for (auto item : m_currentFileNames) { m_bufferFileNames.append(item); } return 1; } } else { return -1; } return 0; } int LCMESClass::updataMes(TestData testData, MesInfo mesInfo) { mesInfo.SN = testData.Barcode; mesInfo.LastResult = testData.Result.Aggregate; mesInfo.TestDate = testData.Basic.Time; // 重新排序处理 QString tempString = ShortLCMesInfo(testData); QJsonObject jsonObj2; serializeToJsonFile(mesInfo, jsonObj2); QJsonDocument doc(jsonObj2); QString jsonString = doc.toJson(QJsonDocument::Compact); QStringList list = jsonString.split(","); list.insert(5, tempString); QString jsonMesInfo = list.join(",");; jsonMesInfo = jsonMesInfo.replace("/", "//"); jsonMesInfo = jsonMesInfo.replace("\"", "\\\""); jsonMesInfo = "{\"jsonData\":\"" + jsonMesInfo + "\"}"; string info = jsonMesInfo.toLocal8Bit(); Response res = EquipmentTextData_Save(info); if (res.Code == 0 || res.Result == "OK") { return 1; } else { addInfo(res.Msg); return -1; } return 0; } int LCMESClass::updataMes(QQueue<TestData> testData, MesInfo mesInfo) { QString tempString = ShortLCMesInfo(testData[0]); tempString.chop(1); mesInfo.SN = testData[0].Barcode; QString firstResult = testData[0].Result.Final; QString secoundResult = testData[1].Result.Final; if (firstResult == "FAIL" || secoundResult == "FAIL") { mesInfo.LastResult = "FAIL"; } else { mesInfo.LastResult = "PASS"; } mesInfo.TestDate = testData[0].Basic.Time; QString tempString2 = ShortLCMesInfo(testData[1]); tempString2.replace("\"TestData\":{", ""); tempString = tempString + "," + tempString2; QJsonObject jsonObject3; serializeToJsonFile(mesInfo, jsonObject3); QJsonDocument doc(jsonObject3); QString jsonString2 = doc.toJson(QJsonDocument::Compact); QStringList list = jsonString2.split(","); list.insert(5, tempString); QString jsonMesInfo = list.join(","); jsonMesInfo = jsonMesInfo.replace("/", "//"); jsonMesInfo = jsonMesInfo.replace("\"", "\\\""); jsonMesInfo = "{\"jsonData\":\"" + jsonMesInfo + "\"}"; string info = jsonMesInfo.toLocal8Bit(); Response res = EquipmentTextData_Save(info); if (res.Code == 0 || res.Result == "OK") { return 1; } else { addInfo(res.Msg); return -1; } return 0; } QString LCMESClass::ShortLCMesInfo(TestData testData) { QString key = ""; QString value = ""; QString tempString = "\"TestData\":{\""; SplicingEFL(testData, tempString); SplicingFFL(testData, tempString); key = "FinalMTFResult"; value = testData.Result.Aggregate; tempString += (key + "\":\"" + value + "\",\""); SplicingMTF(testData, tempString); key = "Angle"; value = testData.Normal.Tilt.Angle; tempString += (key + "\":\"" + value + "\",\""); SplicingFocalShfit(testData, tempString); SplicingPeak(testData, tempString); SplicingFOV(testData, tempString); SplicingDOF(testData, tempString); SplicingMultiFrqMTF(testData, tempString); key = "SymmetricalGroupAverageCAM2_5TAN"; try { value = testData.Normal.SymmetricalFieldMTF.at(1); } catch (const std::exception&) { value = ""; } tempString += (key + "\":\"" + value + "\",\""); key = "AstigmatismCameras1"; try { value = testData.Normal.Astigmatism.first(); } catch (const std::exception&) { value = ""; } tempString += (key + "\":\"" + value + "\",\""); key = "Symmetrical_Group_Ml_(Max-in)_CAM10..13TAN"; if (testData.Normal.SymmetricalGroupMTF.size() > 2) { value = testData.Normal.SymmetricalGroupMTF.at(2).Tan; } else { value = ""; } tempString += (key + "\":\"" + value + "\"}"); return tempString; } QString LCMESClass::SplicingEFL(TestData testData, QString & tempString) { QString key = "EFL"; QString value = testData.Normal.EFL; tempString += (key + "\":\"" + value + "\",\""); return tempString; } QString LCMESClass::SplicingFFL(TestData testData, QString & tempString) { QString key = "FFL"; QString value = testData.Normal.FFL; tempString += (key + "\":\"" + value + "\",\""); return tempString; } QString LCMESClass::SplicingMTF(TestData testData, QString & tempString) { QString key = ""; QString value = ""; key = "Result"; value = testData.Result.MTF; tempString += (key + "\":\"" + value + "\",\""); for (int i = 0; i < testData.Normal.MTF.size(); i++) { key = "S" + QString::number(i + 1); value = testData.Normal.MTF.at(i).Sag; tempString += (key + "\":\"" + value + "\",\""); key = "T" + QString::number(i + 1); value = testData.Normal.MTF.at(i).Tan; tempString += (key + "\":\"" + value + "\",\""); } return tempString; } QString LCMESClass::SplicingFocalShfit(TestData testData, QString & tempString) { QString key = "FocalShift_S2"; QString value = testData.Normal.FocalShift.Cameras.at(1).Sag; tempString += (key + "\":\"" + value + "\",\""); key = "FocalShift_T2"; value = testData.Normal.FocalShift.Cameras.at(1).Tan; tempString += (key + "\":\"" + value + "\",\""); key = "FocalShift_S3"; value = testData.Normal.FocalShift.Cameras.at(2).Sag; tempString += (key + "\":\"" + value + "\",\""); key = "FocalShift_T3"; value = testData.Normal.FocalShift.Cameras.at(2).Tan; tempString += (key + "\":\"" + value + "\",\""); key = "FocalShift_S4"; value = testData.Normal.FocalShift.Cameras.at(3).Sag; tempString += (key + "\":\"" + value + "\",\""); key = "FocalShift_T4"; value = testData.Normal.FocalShift.Cameras.at(3).Tan; tempString += (key + "\":\"" + value + "\",\""); key = "FocalShift_S5"; value = testData.Normal.FocalShift.Cameras.at(4).Sag; tempString += (key + "\":\"" + value + "\",\""); key = "FocalShift_T5"; value = testData.Normal.FocalShift.Cameras.at(4).Tan; tempString += (key + "\":\"" + value + "\",\""); key = "FocalShift_S6"; value = testData.Normal.FocalShift.Cameras.at(5).Sag; tempString += (key + "\":\"" + value + "\",\""); key = "FocalShift_T6"; value = testData.Normal.FocalShift.Cameras.at(5).Tan; tempString += (key + "\":\"" + value + "\",\""); key = "FocalShift_S7"; value = testData.Normal.FocalShift.Cameras.at(6).Sag; tempString += (key + "\":\"" + value + "\",\""); key = "FocalShift_T7"; value = testData.Normal.FocalShift.Cameras.at(6).Tan; tempString += (key + "\":\"" + value + "\",\""); key = "FocalShift_S8"; value = testData.Normal.FocalShift.Cameras.at(7).Sag; tempString += (key + "\":\"" + value + "\",\""); key = "FocalShift_T8"; value = testData.Normal.FocalShift.Cameras.at(7).Tan; tempString += (key + "\":\"" + value + "\",\""); key = "FocalShift_S9"; value = testData.Normal.FocalShift.Cameras.at(8).Sag; tempString += (key + "\":\"" + value + "\",\""); key = "FocalShift_T9"; value = testData.Normal.FocalShift.Cameras.at(8).Tan; tempString += (key + "\":\"" + value + "\",\""); key = "FocalShift_S10"; if (testData.Normal.FocalShift.Cameras.size() > 9) { value = testData.Normal.FocalShift.Cameras.at(9).Sag; } else { value = ""; } tempString += (key + "\":\"" + value + "\",\""); key = "FocalShift_T10"; if (testData.Normal.FocalShift.Cameras.size() > 9) { value = testData.Normal.FocalShift.Cameras.at(9).Tan; } else { value = ""; } tempString += (key + "\":\"" + value + "\",\""); key = "FocalShift_S11"; if (testData.Normal.FocalShift.Cameras.size() > 9) { value = testData.Normal.FocalShift.Cameras.at(10).Sag; } else { value = ""; } tempString += (key + "\":\"" + value + "\",\""); key = "FocalShift_T11"; if (testData.Normal.FocalShift.Cameras.size() > 9) { value = testData.Normal.FocalShift.Cameras.at(10).Tan; } else { value = ""; } tempString += (key + "\":\"" + value + "\",\""); key = "FocalShift_S12"; if (testData.Normal.FocalShift.Cameras.size() > 9) { value = testData.Normal.FocalShift.Cameras.at(11).Sag; } tempString += (key + "\":\"" + value + "\",\""); key = "FocalShift_T12"; if (testData.Normal.FocalShift.Cameras.size() > 9) { value = testData.Normal.FocalShift.Cameras.at(11).Tan; } else { value = ""; } tempString += (key + "\":\"" + value + "\",\""); key = "FocalShift_S13"; if (testData.Normal.FocalShift.Cameras.size() > 9) { value = testData.Normal.FocalShift.Cameras.at(12).Sag; } else { value = ""; } tempString += (key + "\":\"" + value + "\",\""); key = "FocalShift_T13"; if (testData.Normal.FocalShift.Cameras.size() > 9) { value = testData.Normal.FocalShift.Cameras.at(12).Tan; } else { value = ""; } tempString += (key + "\":\"" + value + "\",\""); key = "Focal_Shift_Group_CAM_2..5_SAG"; if (testData.Normal.FocalShiftGroup.size() != 0) { value = testData.Normal.FocalShiftGroup.at(0).Sag; } else { value = ""; } tempString += (key + "\":\"" + value + "\",\""); key = "Focal_Shift_Group_CAM_2..5_TAN"; if (testData.Normal.FocalShiftGroup.size() != 0) { value = testData.Normal.FocalShiftGroup.at(0).Tan; } else { value = ""; } tempString += (key + "\":\"" + value + "\",\""); key = "Focal_Shift_Group_CAM_6..9_SAG"; if (testData.Normal.FocalShiftGroup.size() > 1) { value = testData.Normal.FocalShiftGroup.at(1).Sag; } else { value = ""; } tempString += (key + "\":\"" + value + "\",\""); key = "Focal_Shift_Group_CAM_6..9_TAN"; if (testData.Normal.FocalShiftGroup.size() > 1) { value = testData.Normal.FocalShiftGroup.at(1).Tan; } else { value = ""; } tempString += (key + "\":\"" + value + "\",\""); key = "Focal_Shift_Group_CAM_10..13_SAG"; if (testData.Normal.FocalShiftGroup.size() > 2) { value = testData.Normal.FocalShiftGroup.at(2).Sag; } else { value = ""; } tempString += (key + "\":\"" + value + "\",\""); key = "Focal_Shift_Group_CAM_10..13_TAN"; if (testData.Normal.FocalShiftGroup.size() > 2) { value = testData.Normal.FocalShiftGroup.at(2).Tan; } else { value = ""; } tempString += (key + "\":\"" + value + "\",\""); return tempString; } QString LCMESClass::SplicingPeak(TestData testData, QString & tempString) { QString key = "S1PEAK"; QString value = testData.Normal.MTFPeaks.at(0).Sag; tempString += (key + "\":\"" + value + "\",\""); key = "T1PEAK"; value = testData.Normal.MTFPeaks.at(0).Tan; tempString += (key + "\":\"" + value + "\",\""); key = "S2PEAK"; value = testData.Normal.MTFPeaks.at(1).Sag; tempString += (key + "\":\"" + value + "\",\""); key = "T2PEAK"; value = testData.Normal.MTFPeaks.at(1).Tan; tempString += (key + "\":\"" + value + "\",\""); key = "S3PEAK"; value = testData.Normal.MTFPeaks.at(2).Sag; tempString += (key + "\":\"" + value + "\",\""); key = "T3PEAK"; value = testData.Normal.MTFPeaks.at(2).Tan; tempString += (key + "\":\"" + value + "\",\""); key = "S4PEAK"; value = testData.Normal.MTFPeaks.at(3).Sag; tempString += (key + "\":\"" + value + "\",\""); key = "T4PEAK"; value = testData.Normal.MTFPeaks.at(3).Tan; tempString += (key + "\":\"" + value + "\",\""); key = "S5PEAK"; value = testData.Normal.MTFPeaks.at(4).Sag; tempString += (key + "\":\"" + value + "\",\""); key = "T5PEAK"; value = testData.Normal.MTFPeaks.at(4).Tan; tempString += (key + "\":\"" + value + "\",\""); key = "S6PEAK"; value = testData.Normal.MTFPeaks.at(5).Sag; tempString += (key + "\":\"" + value + "\",\""); key = "T6PEAK"; value = testData.Normal.MTFPeaks.at(5).Tan; tempString += (key + "\":\"" + value + "\",\""); key = "S7PEAK"; value = testData.Normal.MTFPeaks.at(6).Sag; tempString += (key + "\":\"" + value + "\",\""); key = "T7PEAK"; value = testData.Normal.MTFPeaks.at(6).Tan; tempString += (key + "\":\"" + value + "\",\""); key = "S8PEAK"; value = testData.Normal.MTFPeaks.at(7).Sag; tempString += (key + "\":\"" + value + "\",\""); key = "T8PEAK"; value = testData.Normal.MTFPeaks.at(7).Tan; tempString += (key + "\":\"" + value + "\",\""); key = "S9PEAK"; value = testData.Normal.MTFPeaks.at(8).Sag; tempString += (key + "\":\"" + value + "\",\""); key = "T9PEAK"; value = testData.Normal.MTFPeaks.at(8).Tan; tempString += (key + "\":\"" + value + "\",\""); key = "S10PEAK"; if (testData.Normal.MTFPeaks.size() > 9) { value = testData.Normal.MTFPeaks.at(9).Sag; } else { value = ""; } tempString += (key + "\":\"" + value + "\",\""); key = "T10PEAK"; if (testData.Normal.MTFPeaks.size() > 9) { value = testData.Normal.MTFPeaks.at(9).Tan; } else { value = ""; } tempString += (key + "\":\"" + value + "\",\""); key = "S11PEAK"; if (testData.Normal.MTFPeaks.size() > 9) { value = testData.Normal.MTFPeaks.at(10).Sag; } else { value = ""; } tempString += (key + "\":\"" + value + "\",\""); key = "T11PEAK"; if (testData.Normal.MTFPeaks.size() > 9) { value = testData.Normal.MTFPeaks.at(10).Tan; } else { value = ""; } tempString += (key + "\":\"" + value + "\",\""); key = "S12PEAK"; if (testData.Normal.MTFPeaks.size() > 9) { value = testData.Normal.MTFPeaks.at(11).Sag; } else { value = ""; } tempString += (key + "\":\"" + value + "\",\""); key = "T12PEAK"; if (testData.Normal.MTFPeaks.size() > 9) { value = testData.Normal.MTFPeaks.at(11).Tan; } else { value = ""; } tempString += (key + "\":\"" + value + "\",\""); key = "S13PEAK"; if (testData.Normal.MTFPeaks.size() > 9) { value = testData.Normal.MTFPeaks.at(12).Sag; } else { value = ""; } tempString += (key + "\":\"" + value + "\",\""); key = "T13PEAK"; if (testData.Normal.MTFPeaks.size() > 9) { value = testData.Normal.MTFPeaks.at(12).Tan; } else { value = ""; } tempString += (key + "\":\"" + value + "\",\""); return tempString; } QString LCMESClass::SplicingFOV(TestData testData, QString & tempString) { QString key = "FullFOV2_4"; QString value = ""; if (testData.Normal.FullFOV.size() != 0) { value = testData.Normal.FullFOV.at(0); } else { value = ""; } tempString += (key + "\":\"" + value + "\",\""); key = "FullFOV3_5"; if (testData.Normal.FullFOV.size() > 1) { value = testData.Normal.FullFOV.at(1); } else { value = ""; } tempString += (key + "\":\"" + value + "\",\""); key = "FullFOV6_8"; if (testData.Normal.FullFOV.size() > 2) { value = testData.Normal.FullFOV.at(2); } else { value = ""; } tempString += (key + "\":\"" + value + "\",\""); key = "FullFOV7_9"; if (testData.Normal.FullFOV.size() > 3) { value = testData.Normal.FullFOV.at(3); } else { value = ""; } tempString += (key + "\":\"" + value + "\",\""); key = "FullFOV10_12"; if (testData.Normal.FullFOV.size() > 4) { value = testData.Normal.FullFOV.at(4); } else { value = ""; } tempString += (key + "\":\"" + value + "\",\""); key = "FullFOV11_13"; if (testData.Normal.FullFOV.size() > 5) { value = testData.Normal.FullFOV.at(5); } else { value = ""; } tempString += (key + "\":\"" + value + "\",\""); return tempString; } QString LCMESClass::SplicingDOF(TestData testData, QString & tempString) { QString key = "DOF"; QString value = testData.Normal.DOF.DOF; tempString += (key + "\":\"" + value + "\",\""); key = "A2DOF"; value = testData.Normal.A2DOF.A2DOF; tempString += (key + "\":\"" + value + "\",\""); key = "A2_DOFMinus"; try { value = testData.Normal.A2DOF.Minus; } catch (const std::exception&) { value = ""; } tempString += (key + "\":\"" + value + "\",\""); key = "A2_DOFPlus"; try { value = testData.Normal.A2DOF.Plus; } catch (const std::exception&) { value = ""; } tempString += (key + "\":\"" + value + "\",\""); if (testData.m_bDefocus || testData.Defocus.MTF.size() > 0) { // 如果有defocus数据,应该在这里就要拼接好 for (int i = 0; i < testData.Defocus.MTF.size(); i++) { key = "Defocus"; QStringList list = testData.Result.Defocus.split(" "); value = list.at(i); tempString += (key + "\":\"" + value + "\",\""); QVector<MTFData> q_verMtfData = testData.Defocus.MTF.at(i); for (int j = 0; j < q_verMtfData.size(); j++) { MTFData data = q_verMtfData.at(j); key = "S" + QString::number(j + 1); value = data.Sag; tempString += (key + "\":\"" + value + "\",\""); key = "T" + QString::number(j + 1); value = data.Tan; tempString += (key + "\":\"" + value + "\",\""); } } } return tempString; } QString LCMESClass::SplicingMultiFrqMTF(TestData testData, QString & tempString) { if (testData.Normal.m_bMultiFrqMTF || testData.Normal.MultiFrqMTF.size() > 0) { QString key = ""; QString value = ""; for (int i = 0; i < testData.Normal.MultiFrqMTF.size(); i++) { MultiFrqMTFData data = testData.Normal.MultiFrqMTF.at(i); key = "LstFrq"; value = data.LstFrq; tempString += (key + "\":\"" + value + "\",\""); key = "Result"; QStringList list = testData.Result.MultiFrqMTF.split(" "); value = list.at(i + 1); tempString += (key + "\":\"" + value + "\",\""); for (int j = 0; j < data.MTF.size(); j++) { key = "S" + QString::number(j + 1);; value = data.MTF.at(j).Sag; tempString += (key + "\":\"" + value + "\",\""); key = "T" + QString::number(j + 1); value = data.MTF.at(j).Tan; tempString += (key + "\":\"" + value + "\",\""); } } } return tempString; } QVariantList LCMESClass::jsonArrayToVariantList(const QJsonArray & array) { QVariantList list; for (const QJsonValue& v : array) { list.append(v.toVariant()); } return list; } QJsonArray LCMESClass::variantListToJsonArray(const QVariantList & list) { QJsonArray array; for (const QVariant& v : list) { array.append(QJsonValue::fromVariant(v)); } return array; } int LCMESClass::addInfo(string& info) { if (m_logInfo == info) { return 1; } m_logInfo = info; m_Loger.RecordLogMes(m_logInfo); // 发送消息,传递快照指针 if (NULL != m_GActionFlow.m_hwdMainView) { // 使用PostMessage CString* pMsg = new CString(CA2CT(info.c_str())); ::SendMessage(m_GActionFlow.m_hwdMainView, WM_MESINFO, (WPARAM)pMsg, 0); } return 0; } int LCMESClass::addInfo(StepCtrl & crtl, int next, string info, bool blag) { addInfo(info); crtl.nStep = next; if (blag) { crtl.ulCountStart = m_GFunction.GetCPUPerformanceCounter(); crtl.InitRecordString(); } if (next == ST_ERR) { addErrInfo(info); } return 0; } int LCMESClass::addInfo(StepCtrl & crtl, int next, string info, int delay) { crtl.SetDelay(next, delay); addInfo(info); return 0; } int LCMESClass::addErrInfo(string info) { info = "MES" + info; m_GActionFlow.LightOpenRed(); m_dlgError.SetError(info); m_Loger.RecordLogError(info); AfxMessageBox(m_GFunction.String2CString(info), MB_OK | MB_ICONSTOP | MB_SYSTEMMODAL); m_GActionFlow.LightOpenYellow(); return 0; } 增加连接状态判断
09-26
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值