Qt 二维码扫描仪(SDK+串口)

#include "widget.h"
#include "ui_widget.h"
 
 
Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);
    Init();
    on_deviceCheck_clicked();
//    on_fallAsleep_clicked();
    on_wakeUp_clicked();        //保持常醒状态
}
 
 
Widget::~Widget()
{
    delete ui;
    UnInit();
}
 
 
void Widget::Init(){
 
 
    comDevice           = false;
    sdkDevice           = false;
    state               = State::INACTIVE;
    m_pPort             = new QSerialPort;
 
 
    m_getAppHld         = NULL;
    m_setQRable         = NULL;
    m_setBarcode        = NULL;
    m_SetBeepTime       = NULL;
    m_StartDevice       = NULL;
    m_SetBeep           = NULL;
    m_SetLed            = NULL;
    m_GetDecodeString   = NULL;
    m_ReleaseDevice     = NULL;
    m_ReleaseLostDevice = NULL;
    m_GetDevice         = NULL;
    m_ploadChat         = NULL;
    m_nChatRet          = 0;
    m_tempmsChatTime    = 0;
 
 
    m_detector.setInterval(1000);
 
 
    connect(&m_detector,&QTimer::timeout,this,&Widget::sdk_slotDetectData,Qt::QueuedConnection);
    connect(m_pPort,&QSerialPort::readyRead,this,&Widget::com_slotGetData,Qt::QueuedConnection);
    connect(this,&Widget::readySendMessage,this,&Widget::on_sendMessage_clicked,Qt::QueuedConnection);
//    if(m_udpSocket.bind(QHostAddress::LocalHost,59999,QAbstractSocket::ShareAddress|QAbstractSocket::ReuseAddressHint))
//        connect(&m_udpSocket,&QUdpSocket::readyRead,this,&Widget::analyzeCommand,Qt::QueuedConnection);
//    else
//        qDebug()<<"QR---Udp bind port failed";
}
 
 
void Widget::UnInit()
{
    //sdk
    if(m_detector.isActive())
        m_detector.stop();
    if(NULL != m_ploadChat)
    {
        if(m_ploadChat->isLoaded())
        {
            sdk_ReleaseDll();
            m_ploadChat->unload();
            delete m_ploadChat;
            m_ploadChat=NULL;
        }
    }
 
 
    //com
    if(m_pPort->isOpen())
        m_pPort->close();
    m_pPort->deleteLater();
}
 
 
//检测设备   ( 意锐RC532-4.2  / 图腾易讯E20  )
void Widget::on_deviceCheck_clicked()
{
    //1.加载dll_camera       2.getDevice()检测是否是yirui  3.dllDevice赋值
    sdk_LoadDllAndScanSDKQRDevice();
    //1.遍历USB设备,查找COM口 2.打开com口,并始终保持KEEP状态 3.comDevice赋值
    com_ScanUSBQRDevice();
 
 
    if(!sdkDevice&&!comDevice){
        qDebug("QR---************not found sdk&com QRDevice************");
    //没有设备的处理...
 
 
    }
}
 
 
//接收到唤醒命令,开始解析/发送二维码数据
void Widget::on_wakeUp_clicked()
{
    state=State::ACTIVE;
    if(sdkDevice&&!m_detector.isActive())
        m_detector.start();
    if(comDevice)
        m_pPort->clear();  //clear com buffer,very important!
    return;
}
 
 
//接收到睡眠命令,停止解析/发送二维码数据
void Widget::on_fallAsleep_clicked()
{
    state=State::INACTIVE;
    if(sdkDevice&&m_detector.isActive())
        m_detector.stop();
    if(comDevice)
        ;
}
 
 
//发送
void Widget::on_sendMessage_clicked()
{
    QString temp;
    if(!m_strBuffer.isEmpty()){                 //缓存发送
        temp=m_strBuffer;
    }else if(!ui->lineEdit->text().isEmpty()){  //编辑栏发送
        temp=ui->lineEdit->text();
    }else{
        return;
    }
    //send temp
    m_udpSocket.writeDatagram(temp.toLocal8Bit().data(),QHostAddress::LocalHost,RECEIVERUDPPORT);
    ui->textBrowser->append(temp);
    ui->lineEdit->clear();
    m_strBuffer.clear();
}
 
 
void Widget::sdk_slotDetectData()
{
    // timer: 1s 外部控制 开关
    // 持续调用m_GetDevice()会导致 句柄 50+飙升
//    int nDvcs = 0;
//    if(NULL != m_GetDevice)
//        nDvcs = m_GetDevice();
//    if(-1 == nDvcs)
//    {
//        m_nChatRet = 0;
////        m_szLog = QString("二维码设备有问题,请检查设备,并重启此软件!");
////        g_pLogger->WriteLog(m_szLog.toUtf8().data());
//    }
    if(1 == m_nChatRet)
    {
        m_setQRable(false);
        m_setBarcode(false);
 
 
        char szData[2000] = {0};
        int nLen = 0;
 
 
        if(NULL != m_GetDecodeString)
        {
            m_GetDecodeString(szData,nLen);
            if (nLen > 1 && nLen < 60)
            {
                if((QDateTime::currentMSecsSinceEpoch() - m_tempmsChatTime)/1000 > 2)
                {
                    m_tempmsChatTime = QDateTime::currentMSecsSinceEpoch();
//                    if(m_pDlgSignType->isVisible())
//                    {
//                        m_pDlgSignType->showStopReturn();
//                        Thread_Msg msg;
//                        msg.utype = 2; //1=签到码签到; 2=二维码签到
                    QString strData = QString::fromUtf8(szData);
//                        if(strData.contains(","))
//                          {
                            //10679e9f11,狗蛋,18888888888
//                            msg.msgtype = trdSaleswomanMsgType_phonecheckExist;
//                            strData = strData.right(11);
//                        }
//                        else
//                            msg.msgtype = trdSaleswomanMsgType_qrcodecheckExist;
//                        qstrcpy(msg.szParam1, strData.toUtf8().data());
//                        QString szTempPicPath;
//                        m_pDataFacer->GetTempPicPath(szTempPicPath);              ???
//                        qstrcpy(msg.szParam2, szTempPicPath.toUtf8().data()); //picPath
//                        m_pSaleswoman->PostThreadMsg(&msg);
//                        }
                   ////解析部分发回主程序,主程序解析
                   m_strBuffer=strData;
                   //区分一下是哪个设备发出的数据
                   ui->textBrowser->append("SDKDevice:");
                   emit readySendMessage();
                   qDebug() << "QR---QRcontent:"<<QString::fromUtf8(szData);
                }
            }
        }
        if(NULL != m_setQRable)
            m_setQRable(true);
        if(NULL != m_setBarcode)
            m_setBarcode(true);
    }
}
 
 
void Widget::com_slotGetData()
{
    if(State::ACTIVE!=state){
        m_pPort->readAll();     //clear buffer
    }else{
        m_strBuffer=m_pPort->readAll();
        //区分一下是哪个设备发出的数据
        ui->textBrowser->append("ComDevice:");
        emit readySendMessage();
    }
}
 
 
//接收命令分析命令(暂不用)
void Widget::analyzeCommand()
{
    qDebug()<<"QR---receive CMD Data";
    //拆解命令
    QByteArray bArry, bOnce;
    int nNeeds= m_udpSocket.pendingDatagramSize();
    while (0 < nNeeds)
    {
        bOnce.resize(nNeeds);
        QHostAddress sender;
        quint16 senderPort;
        m_udpSocket.readDatagram(bOnce.data(),bOnce.size(), &sender, &senderPort);
//        if(m_senderPort!=senderPort)
//            m_senderPort=senderPort;
        bArry += bOnce;
        bOnce.clear();
        nNeeds = m_udpSocket.pendingDatagramSize();
    }
    //激活
    if(bArry==QByteArray("active")){
        if(state==State::ACTIVE)
            return;
        on_wakeUp_clicked();
    }
    //睡
    else if(bArry==QByteArray("inactive")){
        if(state==State::INACTIVE)
            return;
        on_fallAsleep_clicked();
    }
    //退出
    else if(bArry==QByteArray("quit")){
        qApp->quit();
    }
}
 
 
void Widget::com_ScanUSBQRDevice()
{
    qDebug()<<"QR-----------------START SCAN USB-------------";
    CONST GUID *pClassGuid=NULL;
    LPCTSTR pszEnumerator=TEXT("USB");
    unsigned i;
    DWORD dwSize;
    DEVPROPTYPE ulPropertyType;
    CONFIGRET status;
    HDEVINFO hDevInfo;
    SP_DEVINFO_DATA DeviceInfoData;
    TCHAR szDeviceInstanceID [MAX_DEVICE_ID_LEN];
    WCHAR szBuffer[4096];
    FN_SetupDiGetDevicePropertyW fn_SetupDiGetDevicePropertyW = (FN_SetupDiGetDevicePropertyW)
        GetProcAddress (GetModuleHandle (TEXT("Setupapi.dll")), "SetupDiGetDevicePropertyW");
 
 
    // List all connected USB devices
    hDevInfo = SetupDiGetClassDevs (pClassGuid, pszEnumerator, NULL,
                                    pClassGuid != NULL ? DIGCF_PRESENT: DIGCF_ALLCLASSES | DIGCF_PRESENT);
    if (hDevInfo == INVALID_HANDLE_VALUE)
        return;
 
 
    // Find the ones that are driverless
    for (i = 0; ; i++)  {
        DeviceInfoData.cbSize = sizeof (DeviceInfoData);
        if (!SetupDiEnumDeviceInfo(hDevInfo, i, &DeviceInfoData))
            break;
 
 
        status = CM_Get_Device_ID(DeviceInfoData.DevInst, szDeviceInstanceID , MAX_PATH, 0);
        if (status != CR_SUCCESS)
            continue;
 
 
        // Display device instance ID
        qDebug()<<QString::fromWCharArray(szDeviceInstanceID);
 
 
        //BusReportedDeviceDesc总线返回设备信息---二维码扫描仪硬件标志
        if (fn_SetupDiGetDevicePropertyW && fn_SetupDiGetDevicePropertyW \
                (hDevInfo, &DeviceInfoData, &DEVPKEY_Device_BusReportedDeviceDesc,\
                 &ulPropertyType, (BYTE*)szBuffer, sizeof(szBuffer), &dwSize, 0)){
 
 
            QString busReport=QString::fromWCharArray(szBuffer);
            qDebug()<<busReport;
            if(busReport!=QRDEVICE)
                continue;
            //FriendlyName友好名称---找到串口号
            if (fn_SetupDiGetDevicePropertyW \
                    (hDevInfo, &DeviceInfoData, &DEVPKEY_Device_FriendlyName,\
                     &ulPropertyType, (BYTE*)szBuffer, sizeof(szBuffer), &dwSize, 0)){
 
 
                QString friendlyName=QString::fromWCharArray(szBuffer);
                QRegExp regexp("[()]");
                QString strResult = friendlyName.section(regexp, 1, 1);
                m_portName=strResult;
                comDevice=true;
                com_OpenCom();
                qDebug()<<strResult;
            }
        }
    }
    qDebug()<<"QR-----------------END SCAN USB-------------";
    return;
}
 
 
void Widget::com_OpenCom()
{
     foreach (const QSerialPortInfo &info, QSerialPortInfo::availablePorts()){
         if(info.portName()==m_portName){
             m_pPort->setPort(info);
             qDebug("QR---The QRSerialportinfo Be Found !!!");
             break;
         }
     }
     if(!m_pPort->open(QIODevice::ReadWrite))
         return;
     m_pPort->setBaudRate(QSerialPort::Baud9600);
     m_pPort->setParity(QSerialPort::NoParity);
     m_pPort->setDataBits(QSerialPort::Data8);
     m_pPort->setStopBits(QSerialPort::OneStop);
     m_pPort->setFlowControl(QSerialPort::NoFlowControl);
}
 
 
void Widget::sdk_LoadDllAndScanSDKQRDevice()
{
    QDir dir;
    QString szLoadDll= QString("%0/dll_camera.dll").arg(dir.currentPath());
    m_ploadChat = new QLibrary(szLoadDll);
 
 
    if(m_ploadChat->load())
    {
 
 
        /*
             * void GetAppHandle(HWND hwnd)
             * hwnd:接收解码信息的窗口句柄
             * func:将接收解码信息的窗口句柄传给dll
             */
        m_getAppHld = (getAppHld)m_ploadChat->resolve("GetAppHandle");
        /*
             * void setQRable(bool bqr)
             * bqr: true qr引擎开启;false qr引擎关闭
             * func:设置QR引擎状态
             */
        m_setQRable = (setQRable)m_ploadChat->resolve("setQRable");
        /*
             * void setBarcode(bool bbarcode)
             * bbarcode: true 一维引擎开启;false 一维引擎关闭
             * func:设置一维引擎状态
             */
        m_setBarcode = (setBarcode)m_ploadChat->resolve("setBarcode");
        /*
             * void SetBeepTime(int BeepTime)
             * BeepTime: 蜂鸣时间 单位:ms
             * func:设置解码成功后的蜂鸣时间
             */
        m_SetBeepTime = (SetBeepTime)m_ploadChat->resolve("SetBeepTime");
        /*
             * int StartDevice()
             * func:启动设备
             * 返回值: 1 设备启动成功
             *         -1 设备启动
             *         -2 没有找到设备
             *         -3 设备初始化失败
             */
        m_StartDevice = (StartDevice)m_ploadChat->resolve("StartDevice");
        /*
             * void SetBeep(bool bctrlBeep)
             * bctrlBeep: true:蜂鸣开启 false:蜂鸣关闭
             * func:设置蜂鸣器的开启关闭
             */
        m_SetBeep = (SetBeep)m_ploadChat->resolve("SetBeep");
        /*
             * void m_SetLed(bool bctrlLed)
             * bctrlLed: true:开启 false:关闭
             * func:设置Led灯开启关闭
             */
        m_SetLed = (SetLed)m_ploadChat->resolve("SetLed");
        /*
             * void GetDecodeString(char *aa, int &len)
             * aa:获取解码信息的指针
             * len:传出参数,获取解码信息的数据长度
             * func:获取解码信息
             */
        m_GetDecodeString = (GetDecodeString)m_ploadChat->resolve("GetDecodeString");
        /*
             * void ReleaseDevice()
             * func:释放摄像头
             */
        m_ReleaseDevice = (ReleaseDevice)m_ploadChat->resolve("ReleaseDevice");
        /*
             * void ReleaseLostDevice()
             * func:人为拔出设备时,需要释放的摄像头资源
             */
        m_ReleaseLostDevice = (ReleaseLostDevice)m_ploadChat->resolve("ReleaseLostDevice");
        /*
             * int GetDevice()
             * func:查找设备
             * 返回值 1,表示查找设备成功
             *        -1,表示查找设备失败
             */
        m_GetDevice = (GetDevice)m_ploadChat->resolve("GetDevice");
 
 
        //
        qDebug()<<QString("QR---LoadChatDLL() Success!");
        sdk_InitChatDvc();
    }
    else
    {
       qDebug()<<QString("QR---LoadChatDLL() Fail!=%1").arg(szLoadDll);
    }
 
 
}
 
 
void Widget::sdk_InitChatDvc()
{
    WId hShow = this->winId();
    if(NULL != m_getAppHld)
        m_getAppHld((HWND)hShow);
    if(NULL != m_setQRable)
        m_setQRable(true);
    if(NULL != m_setBarcode)
        m_setBarcode(true);
    if(NULL != m_SetBeepTime)
        m_SetBeepTime(100);
    if(NULL != m_StartDevice)
        m_nChatRet = m_StartDevice();
    qDebug()<<"m_nChatRet:"<<m_nChatRet;
    if (1 == m_nChatRet)
    {
//        if(NULL != m_setBarcode)
//            m_setBarcode(true);
//        if(NULL != m_SetBeepTime)
//            m_SetBeepTime(100);
        if(NULL != m_SetBeep)
            m_SetBeep(true);
        if(NULL != m_SetLed)
            m_SetLed(true);
        // 1 设备启动成功 -1 设备启动 -2 没有找到设备 -3 设备初始化失败
        qDebug()<<QString("QR---sdkDevice ready ok");
        sdkDevice=true;
    }
    else if(-1 == m_nChatRet){
        qDebug()<<QString("QR---sdkDevice be starting");
    }
    else if(-2 == m_nChatRet)
    {
       qDebug()<<QString("QR---not find sdkDevice");
    }
    else if(-3 == m_nChatRet)
    {
        qDebug()<<QString("QR---sdkDevice init fail");
    }
    else
    {
        qDebug()<< QString("QR---sdkDevice find error,please check");
    }
}
 
 
void Widget::sdk_ReleaseDll()
{
    int nDvcs = 0;
    if(NULL != m_GetDevice)
        nDvcs = m_GetDevice();
    if(-1 == nDvcs)
    {
        m_nChatRet = 0;
    }
    qDebug()<<"m_GetDevice"<<"nDvcs"<<nDvcs<<"m_nChatRet"<<m_nChatRet;
    if(1 == m_nChatRet )
    {
        if(NULL != m_setQRable)
        {
            m_setQRable(false);
        }
        if(NULL != m_setBarcode)
        {
            m_setBarcode(false);
        }
        if(NULL != m_ReleaseDevice)
        {
            m_ReleaseDevice();
        }
    }
}
 
 
 

猜你喜欢

转载自blog.csdn.net/jianzemax/article/details/78363223
今日推荐