qt 西门子SIEMENS读卡器上位机程序

使用

serialport.h

#ifndef SERIALPORT_H
#define SERIALPORT_H

#include <QMainWindow>
#include<QLabel>
#include<QSerialPort>
#include<QTimer>
namespace Ui {
class SerialPort;
}

class SerialPort : public QMainWindow
{
    Q_OBJECT
private:

    QSerialPort *serial;
    QTimer *m_pTimer;
    void serialport_init();
    int rxCount=0,txCount=0;
    QLabel *portStateLabel;
    void show_portStateLabel();


public:
    explicit SerialPort(QWidget *parent = 0);
    ~SerialPort();
signals:
    void  signal_read();
private slots:
    void slot_read_from_port();
    void on_btnReloadPort_clicked();

    void on_btnOpenPort_clicked();

    void on_btnClosePort_clicked();

    void on_btnSendData_clicked();

    void on_chk_auto_send_clicked(bool checked);

    void on_btnResetInfo_clicked();

    void on_pushButton_2_clicked();

    void on_pushButton_clicked();

    void on_recvData();
    void string_to_hex(QString hex,QByteArray &qbyte);
    void on_pushButton_3_clicked();

    void on_pushButton_4_clicked();

    void on_pushButton_5_clicked();

    void on_pushButton_6_clicked();

    void on_pushButton_8_clicked();

    void on_pushButton_7_clicked();

    void on_pushButton_9_clicked();
    void timeoutSlot();

private:
    Ui::SerialPort *ui;
     void closeEvent(QCloseEvent *event);
     QByteArray m_byteArry;
     int hex_char_value(char c);
     int hex_to_decimal(const char* szHex, int len);

};

#endif // SERIALPORT_H

.cpp

#include "serialport.h"
#include "ui_serialport.h"
#include<QSerialPortInfo>
#include<QDebug>
#include<QButtonGroup>
#include<QTextCodec>
#include<QMessageBox>
#include <stdlib.h>
#include <cmath>
#include<QThread>
void SerialPort::serialport_init()
{
    foreach(const QSerialPortInfo info,QSerialPortInfo::availablePorts())//可以不使用
    {
        ui->comboBox_port->addItem(info.portName());
    }
}

void SerialPort::show_portStateLabel()
{
    QString info=QString("RX^%0    TX^%1 Bytes").arg(rxCount).arg(txCount);
    portStateLabel->setText(info);
}
SerialPort::SerialPort(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::SerialPort)
{
    ui->setupUi(this);

    portStateLabel=new QLabel("RX ----  TX ----");
    portStateLabel->setContentsMargins(20,0,20,0);
    portStateLabel->setMaximumWidth(1000);
    ui->statusBar->addWidget(portStateLabel);

    QButtonGroup *btnGroupRev=new QButtonGroup(this);
    btnGroupRev->addButton(ui->radio_accept_ascii,0);
    btnGroupRev->addButton(ui->radio_accept_hex,1);
    ui->radio_accept_hex->setChecked(true);
    QButtonGroup *btnGroupSend=new QButtonGroup(this);
    btnGroupSend->addButton(ui->radio_send_ascii,0);
    btnGroupSend->addButton(ui->radio_send_hex,1);
    ui->radio_send_hex->setChecked(true);
    m_pTimer = new QTimer;
    connect(m_pTimer, &QTimer::timeout, this, &SerialPort::timeoutSlot);
    m_pTimer->start(500);
    serial=new  QSerialPort(this);
    serialport_init();
    connect(serial,SIGNAL(readyRead()),this,SLOT(slot_read_from_port()));
}

SerialPort::~SerialPort()
{
    delete ui;
}

void SerialPort::closeEvent(QCloseEvent *event)
{
    if(serial->isOpen()){
        int  result;
        result=QMessageBox::question(this,"提示","端口已打开,确认退出?",
                   QMessageBox::Yes|QMessageBox::No);
        if(result==QMessageBox::Yes)
        {
            serial->close();
            event->accept();
        }else{
            event->ignore();
        }
    }
}
void SerialPort::timeoutSlot()
{
    QString str = QString::fromUtf8(m_byteArry);
    if(str.length() <= 0)
    {
        ui->label_11->setText("");
        return ;
    }
    else if(str.length() <= 15)
    {
        ui->label_11->setText("      设置成功!");
         m_byteArry.clear();
        return;
    }

    QStringList list = str.split("\r\n");

    for(int i=0;i<list.size()-1;i++)
    {
         QString strValue = list.at(i);
         QStringList strList = strValue.split('=');
         if(strList.at(0) == "local_ip")
         {
             ui->lineEdit->setText(strList.at(1));
         }
         else if(strList.at(0) == "local_port")
         {
             ui->lineEdit_2->setText(strList.at(1));
         }
         else if(strList.at(0) == "mask")
         {
             ui->lineEdit_3->setText(strList.at(1));
         }
         else if(strList.at(0) == "gateway")
         {
             ui->lineEdit_4->setText(strList.at(1));
         }
         else if(strList.at(0) == "remote_ip")
         {
             ui->lineEdit_5->setText(strList.at(1));
         }
         else if(strList.at(0) == "remote_port")
         {
             ui->lineEdit_6->setText(strList.at(1));
         }
         else if(strList.at(0) == "device_id")
         {
             ui->lineEdit_7->setText(strList.at(1));
         }
    }
    ui->label_11->setText("      读取配置成功!");
    m_byteArry.clear();
}
void SerialPort::on_btnReloadPort_clicked()
{
    ui->comboBox_port->clear();
    serialport_init();
}
void SerialPort::on_btnOpenPort_clicked()
{
    serial->setPortName(ui->comboBox_port->currentText());
    if (serial->open(QIODevice::ReadWrite))
    {
        qint32 baudrate=ui->comboBox_baud->currentText().toInt();
        serial->setBaudRate(baudrate);
        switch(ui->comboBox_databit->currentText().toInt())
        {
            case 8:
                serial->setDataBits(QSerialPort::Data8);  break;
            case 7:
                serial->setDataBits(QSerialPort::Data7);  break;
            case 6:
                serial->setDataBits(QSerialPort::Data6);  break;
            case 5:
                serial->setDataBits(QSerialPort::Data5);  break;
            default : qDebug()<<"default"<<"databit";
                break;
        }
        switch (ui->comboBox_checkbit->currentIndex()) {
            case 0:
                serial->setParity(QSerialPort::NoParity);   break;
            case 1: //odd
                serial->setParity(QSerialPort::OddParity);  break;
            case 2: //even
                serial->setParity(QSerialPort::EvenParity); break;
            case 3:
                serial->setParity(QSerialPort::SpaceParity);break;
            case 4:
                serial->setParity(QSerialPort::MarkParity); break;
            default:    qDebug()<<"default"<<"checkbit";
                break;
        }
        switch(ui->comboBox_stopbit->currentText().toInt())
        {
            case 1:
                serial->setStopBits(QSerialPort::OneStop); break;
            case 2:
                serial->setStopBits(QSerialPort::TwoStop); break;
            default: qDebug()<<"default"<<"stopbit";
                break;
        }
        switch(ui->comboBox_flow->currentIndex())
        {
            case 0:
                serial->setFlowControl(QSerialPort::NoFlowControl);break;
            case 1:
                serial->setFlowControl(QSerialPort::HardwareControl);break;
            case 2:
                serial->setFlowControl(QSerialPort::SoftwareControl);break;
            default: qDebug()<<"default"<<"flow";
                break;
        }
        ui->btnOpenPort->setEnabled(false);
        ui->btnClosePort->setEnabled(true);
        ui->label_com_baud->setText(QString(" %0  %1").
                 arg(ui->comboBox_port->currentText()).
                arg(ui->comboBox_baud->currentText()));
     }
    else
    {
        ui->label_com_baud->setText(QString("Open Failed").
                   arg(ui->comboBox_port->currentText()));
    }
}
void SerialPort::on_btnClosePort_clicked()
{
    serial->close();
    ui->btnOpenPort->setEnabled(true);
    ui->btnClosePort->setEnabled(false);
    ui->label_com_baud->setText("        **********");
}
void SerialPort::on_btnResetInfo_clicked()
{
    ui->lcdRevNum->display(0);
    ui->lcdSendNum->display(0);
}
void SerialPort::on_chk_auto_send_clicked(bool checked)
{
}
void SerialPort::slot_read_from_port()
{
    QByteArray  byteArray = serial->readAll();
    QString recv = ui->plainTextEdit_rev->toPlainText();
    recv += QString(byteArray);
    ui->plainTextEdit_rev->clear();
    ui->plainTextEdit_rev->appendPlainText(recv);
    m_byteArry.append(byteArray);
}

void SerialPort::string_to_hex(QString hex,QByteArray &qbyte)
{
    hex=hex.trimmed();
    QStringList sl=hex.split(" ");
    foreach(QString s,sl)
    {
        if(!s.isEmpty())
            qbyte.append((char)s.toInt(0,16)&0xFF);
    }
 }
void SerialPort::on_btnSendData_clicked()
{
    ui->lcdSendNum->display(ui->lcdSendNum->value()+1);
    QString sendstr=ui->plainTextEdit_send->toPlainText();
    if(ui->radio_send_ascii->isChecked())
    {   //Unicode转GBK 参考博客问答http://bbs.csdn.net/topics/390024555
//        QTextCodec *codec = QTextCodec::codecForName("GBK"); //建立一个unicode与GBK之间的转换器
//        QByteArray bytes = codec->fromUnicode(sendstr); //unicode转换成gbk
        QByteArray bytes=sendstr.toLocal8Bit();//toLatin1
        serial->write(bytes);
        txCount+=bytes.length();show_portStateLabel();
    }
    else if(ui->radio_send_hex->isChecked())
    {
        QByteArray bytes;
        bytes = QByteArray::fromHex(sendstr.toLatin1());//toLatin1
        serial->write(bytes);
        txCount+=bytes.length();  show_portStateLabel();
        qDebug()<<bytes.toHex();
    }
}

 int SerialPort::hex_char_value(char c)
{
        if(c >= '0' && c <= '9')
                return c - '0';
        else if(c >= 'a' && c <= 'f')
                return (c - 'a' + 10);
        else if(c >= 'A' && c <= 'F')
                return (c - 'A' + 10);
        assert(0);
        return 0;
}
int SerialPort::hex_to_decimal(const char* szHex, int len)
{
        int result = 0;
        for(int i = 0; i < len; i++)
        {
                result += (int)pow((float)16, (int)len-i-1) * hex_char_value(szHex[i]);
        }
        return result;
}

void SerialPort::on_recvData()
{
    char idBuf[2]={0};
    char typeBuf[4] ={0};
    unsigned int id;
    QString str;


    memcpy(typeBuf,m_byteArry.data()+13,2);
    str = typeBuf;
    ui->lineEdit->setText(str);

    memcpy(typeBuf,m_byteArry.data()+15,2);
    str = typeBuf;
    ui->lineEdit_2->setText(str);

    memcpy(idBuf,m_byteArry.data()+17,2);
    id = hex_to_decimal(idBuf,2);
    str = QString("%1").arg(id);
    ui->lineEdit_3->setText(str);

    memcpy(idBuf,m_byteArry.data()+19,2);
    id = hex_to_decimal(idBuf,2);
    memcpy(typeBuf,m_byteArry.data()+21,2);
    QString strType = typeBuf;

    str = QString("%1").arg(id);
    ui->lineEdit_4->setText(str);
    ui->lineEdit_5->setText(strType);
    m_byteArry.clear();
}
void SerialPort::on_pushButton_2_clicked()//读取卡片信息;
{
    serial->write("get+netcfg?");

}

static std::string getStr(int nodeID)
{
    QString s ;
    if (nodeID <= 15)
        s  += '0';
    s += QString::number(nodeID, 16).toUpper();
    std::string strID = s.toStdString();
    return strID;
}
void SerialPort::on_pushButton_clicked()//写卡信息根据配置写卡;
{
    serial->write("set+save\r\n",10);
}

void SerialPort::on_pushButton_3_clicked()//loacalip
{
    QString str = "set+local_ip="+ui->lineEdit->text()+"\r\n";
    serial->write(str.toUtf8().constData(),str.length());
    qDebug()<<str<<endl;;
}

void SerialPort::on_pushButton_4_clicked()//localport
{
    QString str = "set+local_port="+ui->lineEdit_2->text()+"\r\n";
    serial->write(str.toUtf8().constData());
}

void SerialPort::on_pushButton_5_clicked()//mask
{
    QString str = "set+mask="+ui->lineEdit_3->text()+"\r\n";
    serial->write(str.toUtf8().constData());
}

void SerialPort::on_pushButton_6_clicked()//gateway
{

    QString str = "set+gateway="+ui->lineEdit_4->text()+"\r\n";
    serial->write(str.toUtf8().constData());
}

void SerialPort::on_pushButton_8_clicked()//remoteprot
{
    QString str = "set+remote_port="+ui->lineEdit_6->text()+"\r\n";
    serial->write(str.toUtf8().constData());
}

void SerialPort::on_pushButton_7_clicked()//remoteip
{
    QString str = "set+remote_ip="+ui->lineEdit_5->text()+"\r\n";
    serial->write(str.toUtf8().constData());
}

void SerialPort::on_pushButton_9_clicked()//设备id
{
    QString str = "set+device_id="+ui->lineEdit_7->text()+"\r\n";
    serial->write(str.toUtf8().constData());
}

.pro

#-------------------------------------------------
#
# Project created by QtCreator 2019-04-02T15:43:39
#
#-------------------------------------------------

QT       += core gui

greaterThan(QT_MAJOR_VERSION, 4): QT += widgets

TARGET = SerialPort
TEMPLATE = app

# The following define makes your compiler emit warnings if you use
# any feature of Qt which has been marked as deprecated (the exact warnings
# depend on your compiler). Please consult the documentation of the
# deprecated API in order to know how to port your code away from it.
DEFINES += QT_DEPRECATED_WARNINGS

# You can also make your code fail to compile if you use deprecated APIs.
# In order to do so, uncomment the following line.
# You can also select to disable deprecated APIs only up to a certain version of Qt.
#DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000    # disables all the APIs deprecated before Qt 6.0.0


SOURCES += \
        main.cpp \
        serialport.cpp

HEADERS += \
        serialport.h

FORMS += \
        serialport.ui
QT += serialport

RESOURCES += \
    title.qrc


main.cpp

#include "serialport.h"
#include <QApplication>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    SerialPort w;
    w.show();

    return a.exec();
}

 以上读卡器界面用于工业机器人轨道标注

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值