QT串口和数据库通信

创建串口

串口连接客户端并向服务器发送消息

client.pro

#-------------------------------------------------
#
# Project created by QtCreator 2024-07-02T14:11:20
#
#-------------------------------------------------

QT       += core gui network
QT       += core gui serialport

greaterThan(QT_MAJOR_VERSION, 4): QT += widgets

TARGET = client
TEMPLATE = app

# The following define makes your compiler emit warnings if you use
# any feature of Qt which as 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\
        widget.cpp

HEADERS  += widget.h

FORMS    += widget.ui

widget.h

#ifndef WIDGET_H
#define WIDGET_H

#include <QWidget>
#include <QTcpSocket>
#include <QSerialPort>

namespace Ui {
class Widget;
}

class Widget : public QWidget
{
    Q_OBJECT

public:
    explicit Widget(QWidget *parent = 0);
    ~Widget();

    void InitClient();
    void InitWidget();

private slots:
    void on_connect_bt_clicked();
    void OnReadData();
    void OnReadyData1();
    void on_open_bt_clicked();

private:
    Ui::Widget *ui;

    QTcpSocket *m_pSocket;
    QSerialPort *m_pSerial;
};

#endif // WIDGET_H

main.cpp

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

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    Widget w;
    w.InitClient();
    w.InitWidget();

    w.show();

    return a.exec();
}

widget.cpp

#include "widget.h"
#include "ui_widget.h"
#include <QDebug>
#include <QHostAddress>
#include <QSerialPort>
#include <QSerialPortInfo>

Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);
    m_pSocket = NULL;
    m_pSerial = NULL;
}

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

void Widget::InitClient()
{
    qDebug() << "Widget::InitClient() enter";
    if (NULL == m_pSocket)
    {
        m_pSocket = new QTcpSocket(this);
        connect(m_pSocket, SIGNAL(readyRead()), this, SLOT(OnReadData()));
    }
    qDebug() << "Widget::InitClient() exit";
}

void Widget::on_connect_bt_clicked()
{
    qDebug() << "Widget::on_connect_bt_clicked() enter";

    QString strIP = ui->ip_edit->text();
    QString strPort = ui->port_edit->text();
    qDebug() << strIP << " " << strPort;
    if (strIP.length() == 0 || strPort.length() == 0)
    {
        qDebug() << "input error";
        return;
    }

    if (NULL == m_pSocket)
    {
        qDebug() << "socket error";
        return;
    }

    m_pSocket->connectToHost(QHostAddress("127.0.0.1"), strPort.toShort());
    if (m_pSocket->waitForConnected(3000))
    {
        qDebug() << "connect ok";
    }
    else
    {
        qDebug() << "connect error";
    }
    qDebug() << "Widget::on_connect_bt_clicked() exit";
}

void Widget::OnReadData()
{
    QByteArray arr = m_pSocket->readAll();
    qDebug() << arr;
}

void Widget::InitWidget()
{
    qDebug()  << "Widget::InitWidget() enter";
    if (NULL  == m_pSerial)
    {
        m_pSerial  = new QSerialPort(this);
        connect(m_pSerial, SIGNAL(readyRead()), this, SLOT(OnReadyData1()));
    }
    qDebug()  << "Widget::InitWidget() exit";
}

void Widget::OnReadyData1() //串口数据就绪槽函数,当串口有数据可读时,该函数会被调用
{
    qDebug()  << "Widget::OnReadyData1() enter";
    QByteArray strData = m_pSerial->readAll(); // 读取所有数据,处理接收到的数据
    m_pSocket->write(strData.toStdString().data());
    qDebug()  << "Widget::OnReadyData1() exit";
}

void Widget::on_open_bt_clicked()
{
    qDebug()  << "Widget::on_open_bt_clicked() enter";
    if (NULL == m_pSerial)
    {
        qDebug()  << "serial obj error";
        return;
    }
    QString strBt = ui->open_bt->text();
    if (strBt == "open")
    {
        QString strCom = ui->uart_com->currentText();
        if (strCom.length() == 0)
        {
            qDebug() << "com port error";
            return;
        }
        m_pSerial->setPortName(strCom);
        m_pSerial->setBaudRate(QSerialPort::Baud9600);
        m_pSerial->setDataBits(QSerialPort::Data8);
        m_pSerial->setStopBits(QSerialPort::OneStop);
        m_pSerial->setParity(QSerialPort::NoParity);
        m_pSerial->setFlowControl(QSerialPort::NoFlowControl);

        if (!m_pSerial->isOpen())
        {
            if (m_pSerial->open(QIODevice::ReadWrite))
            {
                qDebug()  <<  "open ok";
                ui->open_bt->setText("close");
                ui->uart_com->setEnabled(false);
            }
            else
            {
                qDebug()  << "open error";
            }
        }
    }
    else
    {
        m_pSerial->close();
        ui->open_bt->setText("open");
        //ui->send_bt->setEnabled(false);
        ui->uart_com->setEnabled(true);
    }
qDebug()  << "Widget::on_open_bt_clicked() exit";

}

widget.ui

<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
 <class>Widget</class>
 <widget class="QWidget" name="Widget">
  <property name="geometry">
   <rect>
    <x>0</x>
    <y>0</y>
    <width>692</width>
    <height>468</height>
   </rect>
  </property>
  <property name="windowTitle">
   <string>Widget</string>
  </property>
  <widget class="QLabel" name="label">
   <property name="geometry">
    <rect>
     <x>30</x>
     <y>140</y>
     <width>72</width>
     <height>15</height>
    </rect>
   </property>
   <property name="text">
    <string>ip</string>
   </property>
  </widget>
  <widget class="QLineEdit" name="ip_edit">
   <property name="geometry">
    <rect>
     <x>110</x>
     <y>140</y>
     <width>181</width>
     <height>21</height>
    </rect>
   </property>
  </widget>
  <widget class="QLabel" name="label_2">
   <property name="geometry">
    <rect>
     <x>30</x>
     <y>180</y>
     <width>72</width>
     <height>15</height>
    </rect>
   </property>
   <property name="text">
    <string>port</string>
   </property>
  </widget>
  <widget class="QLineEdit" name="port_edit">
   <property name="geometry">
    <rect>
     <x>110</x>
     <y>180</y>
     <width>181</width>
     <height>21</height>
    </rect>
   </property>
  </widget>
  <widget class="QPushButton" name="connect_bt">
   <property name="geometry">
    <rect>
     <x>340</x>
     <y>150</y>
     <width>93</width>
     <height>28</height>
    </rect>
   </property>
   <property name="text">
    <string>connect</string>
   </property>
  </widget>
  <widget class="QComboBox" name="uart_com">
   <property name="geometry">
    <rect>
     <x>30</x>
     <y>50</y>
     <width>87</width>
     <height>22</height>
    </rect>
   </property>
   <item>
    <property name="text">
     <string>com9</string>
    </property>
   </item>
  </widget>
  <widget class="QPushButton" name="open_bt">
   <property name="geometry">
    <rect>
     <x>200</x>
     <y>50</y>
     <width>93</width>
     <height>28</height>
    </rect>
   </property>
   <property name="text">
    <string>open</string>
   </property>
  </widget>
 </widget>
 <layoutdefault spacing="6" margin="11"/>
 <resources/>
 <connections/>
</ui>

服务器接收数据并存储在数据库内

server.pro

#-------------------------------------------------
#
# Project created by QtCreator 2024-07-02T09:20:48
#
#-------------------------------------------------

QT       += core gui network
QT       += core gui sql

greaterThan(QT_MAJOR_VERSION, 4): QT += widgets

TARGET = server
TEMPLATE = app

# The following define makes your compiler emit warnings if you use
# any feature of Qt which as 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\
        widget.cpp \
    db.cpp

HEADERS  += widget.h \
    common.h \
    db.h

FORMS    += widget.ui

common.h

#ifndef _COMMON_H_
#define _COMMON_H_

#include <QDebug>
#include <QTime>

#define _TIME_ qPrintable(QTime::currentTime().toString("hh:mm:ss:zzz"))

#define FUNCTION_ENTER qDebug("%s %s %d %s start!",__FILE__,__FUNCTION__,__LINE__,_TIME_);
#define FUNCTION_EXIT qDebug("%s %s %d %s end!",__FILE__,__FUNCTION__,__LINE__,_TIME_);

#endif //_COMMON_H_

db.h

#ifndef _DB_H_
#define _DB_H_

#include <QSqlDatabase>
#include <QSqlQuery>

class DBManager
{
public:
    enum DBMANAGER_TYPE
    {
        DBMANAGER_OK = 0,
        DBMANAGER_ERR,
    };

public:
    static DBManager * GetInstance();
    static void DestroyInstance();

    int ExecSql(QString strSql);
    int ExecSql(QString strSql, QSqlQuery &query);

private:
    DBManager();
    ~DBManager();

    void InitDb();

private:
    static DBManager *m_pManager;
    QSqlDatabase m_db;
};

#endif //_DB_H_

widget.h

#ifndef WIDGET_H
#define WIDGET_H

#include <QWidget>
#include <QTcpServer>

namespace Ui {
class Widget;
}

class Widget : public QWidget
{
    Q_OBJECT

public:
    explicit Widget(QWidget *parent = 0);
    ~Widget();

    void InitServer();
    void InitWidget();

private slots:
    void OnNewConnection();
    void on_listen_bt_clicked();
    void Insert();
    void on_pushButton_2_clicked();

private:
    Ui::Widget *ui;
    QTcpServer *m_pServer;
};

#endif // WIDGET_H

db.cpp

#include "common.h"
#include "db.h"
#include <QSqlError>

DBManager *DBManager::m_pManager = NULL;

int DBManager::ExecSql(QString strSql, QSqlQuery &query)
{
    FUNCTION_ENTER;
    if (strSql.length() == 0)
    {
        return DBMANAGER_ERR;
    }
    query = m_db.exec(strSql);
    if (m_db.lastError().isValid())
    {
        qDebug() << m_db.lastError().text();
        return DBMANAGER_ERR;
    }
    FUNCTION_EXIT;
    return DBMANAGER_OK;
}

int DBManager::ExecSql(QString strSql)
{
    FUNCTION_ENTER;
    if (strSql.length() == 0)
    {
        return DBMANAGER_ERR;
    }
    m_db.exec(strSql);
    if (m_db.lastError().isValid())
    {
        qDebug() << m_db.lastError().text();
        return DBMANAGER_ERR;
    }
    FUNCTION_EXIT;
    return DBMANAGER_OK;
}

DBManager::DBManager()
{
    FUNCTION_ENTER;
    FUNCTION_EXIT;
}

DBManager::~DBManager()
{
    FUNCTION_ENTER;
    FUNCTION_EXIT;
}

DBManager *DBManager::GetInstance()
{
    FUNCTION_ENTER;
    if (NULL == m_pManager)
    {
        m_pManager = new DBManager();
        m_pManager->InitDb();
    }
    FUNCTION_EXIT;
    return m_pManager;
}

void DBManager::DestroyInstance()
{
    FUNCTION_ENTER;
    if (NULL != m_pManager)
    {
        delete m_pManager;
        m_pManager = NULL;
    }
    FUNCTION_EXIT;
}

void DBManager::InitDb()
{
    FUNCTION_ENTER;
    m_db = QSqlDatabase::addDatabase("QMYSQL");
    m_db.setHostName("localhost");
    m_db.setDatabaseName("text");
    m_db.setUserName("root");
    m_db.setPassword("123456");

    if (m_db.open())
    {
        qDebug() << "open ok";
    }
    FUNCTION_EXIT;
}

main.cpp

#include "widget.h"
#include <QApplication>
#include <QSqlDatabase> //sql驱动基础
#include <QSqlQuery>//sql查询相关
#include <QSqlError>//sql输出错误

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

    return a.exec();
}

widget.cpp

#include "widget.h"
#include "ui_widget.h"
#include <QDebug>
#include <QHostAddress>
#include <QTcpSocket>
#include "common.h"
#include "db.h"
#include <QTableWidgetItem>

Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);
    m_pServer = NULL;
}

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

void Widget::InitServer()
{
    qDebug() << "Widget::InitServer() enter";
    if (NULL == m_pServer)
    {
        m_pServer = new QTcpServer(this);
        connect(m_pServer, SIGNAL(newConnection()), this, SLOT(OnNewConnection()));
    }
    qDebug() << "Widget::InitServer() exit";
}

void Widget::InitWidget()
{
    FUNCTION_ENTER;
    ui->tableWidget->setColumnCount(2);
    ui->tableWidget->setRowCount(5);
    QStringList strList;
    strList << "id"<<"name"  ;
    ui->tableWidget->setHorizontalHeaderLabels(strList);
    ui->tableWidget->setAutoScroll(true);
    ui->tableWidget->setEditTriggers(QAbstractItemView::NoEditTriggers);
    ui->tableWidget->setSelectionBehavior( QAbstractItemView::SelectRows);
    FUNCTION_EXIT;
}

void Widget::OnNewConnection()
{
    qDebug() << "new connection";
    QTcpSocket *pTmp = m_pServer->nextPendingConnection();
    if (NULL != pTmp)
    {
        connect(pTmp, SIGNAL(readyRead()), this, SLOT(Insert()));
    }
}


void Widget::on_listen_bt_clicked()
{
    qDebug() << "Widget::on_listen_bt_clicked() enter";
    if (NULL == m_pServer)
    {
        return;
    }
    QString strIP = ui->ip_edit->text();
    QString strPort = ui->port_edit->text();
    if (strIP.length() == 0 || strPort.length() == 0)
    {
        qDebug() << "input error";
        return;
    }
    bool bRet = m_pServer->listen(QHostAddress(strIP), strPort.toShort());
    if (bRet == true)
    {
        qDebug() << "server listen ok";
    }
    qDebug() << "Widget::on_listen_bt_clicked() enter";
}



void Widget::Insert()
{
    FUNCTION_ENTER;
    DBManager *pTmp = DBManager::GetInstance();
    if (NULL == pTmp)
    {
        qDebug() << "db error";
    }

    QTcpSocket *pTmps = (QTcpSocket *)sender();
    if (NULL == pTmps)
    {
        qDebug() << "socket error";
        return;
    }
    QByteArray arr = pTmps->readAll();
    //qDebug() << arr;
    QString str(arr);
    QStringList list = str.split(" ");
    QString strSql = QString("insert into text2 (id,name) values ('%1', '%2')").arg(list.at(0)).arg(list.at(1));
    int iRet = pTmp->ExecSql(strSql);
    if (iRet != DBManager::DBMANAGER_OK)
    {
        qDebug() << "insert data error";
        return;
    }
    FUNCTION_EXIT;
}

void Widget::on_pushButton_2_clicked()
{
    FUNCTION_ENTER;
    DBManager *pTmp = DBManager::GetInstance();
    if (NULL == pTmp)
    {
        qDebug() << "db error";
    }
    QString strSql = "select * from text2";
    QSqlQuery query;
    int iRet = pTmp->ExecSql(strSql, query);
    if (iRet != DBManager::DBMANAGER_OK)
    {
        qDebug() << "select data error";
        return;
    }
    int i = 0;
    while(query.next())
    {
        int j = 0;
        for (j = 0; j < 2; j++)
        {
            //qDebug() << query.value(j).toString();
            QTableWidgetItem *pItem = new QTableWidgetItem(query.value(j).toString());
            ui->tableWidget->setItem(i, j, pItem);
        }
        i++;
    }
    FUNCTION_EXIT;
}

widget.ui

<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
 <class>Widget</class>
 <widget class="QWidget" name="Widget">
  <property name="geometry">
   <rect>
    <x>0</x>
    <y>0</y>
    <width>893</width>
    <height>629</height>
   </rect>
  </property>
  <property name="windowTitle">
   <string>Widget</string>
  </property>
  <widget class="QLabel" name="label">
   <property name="geometry">
    <rect>
     <x>80</x>
     <y>60</y>
     <width>72</width>
     <height>15</height>
    </rect>
   </property>
   <property name="text">
    <string>ip</string>
   </property>
  </widget>
  <widget class="QLineEdit" name="ip_edit">
   <property name="geometry">
    <rect>
     <x>140</x>
     <y>60</y>
     <width>221</width>
     <height>21</height>
    </rect>
   </property>
  </widget>
  <widget class="QLineEdit" name="port_edit">
   <property name="geometry">
    <rect>
     <x>140</x>
     <y>100</y>
     <width>221</width>
     <height>21</height>
    </rect>
   </property>
  </widget>
  <widget class="QLabel" name="label_2">
   <property name="geometry">
    <rect>
     <x>70</x>
     <y>100</y>
     <width>71</width>
     <height>21</height>
    </rect>
   </property>
   <property name="text">
    <string>port</string>
   </property>
  </widget>
  <widget class="QPushButton" name="listen_bt">
   <property name="geometry">
    <rect>
     <x>400</x>
     <y>100</y>
     <width>93</width>
     <height>28</height>
    </rect>
   </property>
   <property name="text">
    <string>listen</string>
   </property>
  </widget>
  <widget class="QTableWidget" name="tableWidget">
   <property name="geometry">
    <rect>
     <x>60</x>
     <y>170</y>
     <width>531</width>
     <height>301</height>
    </rect>
   </property>
  </widget>
  <widget class="QPushButton" name="pushButton_2">
   <property name="geometry">
    <rect>
     <x>670</x>
     <y>180</y>
     <width>101</width>
     <height>31</height>
    </rect>
   </property>
   <property name="text">
    <string>select</string>
   </property>
  </widget>
 </widget>
 <layoutdefault spacing="6" margin="11"/>
 <resources/>
 <connections/>
</ui>

测试

相关推荐
秃头佛爷28 分钟前
Python学习大纲总结及注意事项
开发语言·python·学习
待磨的钝刨29 分钟前
【格式化查看JSON文件】coco的json文件内容都在一行如何按照json格式查看
开发语言·javascript·json
XiaoLeisj2 小时前
【JavaEE初阶 — 多线程】单例模式 & 指令重排序问题
java·开发语言·java-ee
励志成为嵌入式工程师3 小时前
c语言简单编程练习9
c语言·开发语言·算法·vim
捕鲸叉4 小时前
创建线程时传递参数给线程
开发语言·c++·算法
A charmer4 小时前
【C++】vector 类深度解析:探索动态数组的奥秘
开发语言·c++·算法
Peter_chq4 小时前
【操作系统】基于环形队列的生产消费模型
linux·c语言·开发语言·c++·后端
记录成长java5 小时前
ServletContext,Cookie,HttpSession的使用
java·开发语言·servlet
前端青山5 小时前
Node.js-增强 API 安全性和性能优化
开发语言·前端·javascript·性能优化·前端框架·node.js
睡觉谁叫~~~5 小时前
一文解秘Rust如何与Java互操作
java·开发语言·后端·rust