QT串口和数据库通信

ops/2024/9/24 21:19:10/

创建串口

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

client.pro

#-------------------------------------------------
#
# Project created by QtCreator 2024-07-02T14:11:20
#
#-------------------------------------------------QT       += core gui network
QT       += core gui serialportgreaterThan(QT_MAJOR_VERSION, 4): QT += widgetsTARGET = 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.0SOURCES += main.cpp\widget.cppHEADERS  += widget.hFORMS    += 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_OBJECTpublic: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 sqlgreaterThan(QT_MAJOR_VERSION, 4): QT += widgetsTARGET = 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.0SOURCES += main.cpp\widget.cpp \db.cppHEADERS  += widget.h \common.h \db.hFORMS    += 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_OBJECTpublic: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>

测试


http://www.ppmy.cn/ops/85899.html

相关文章

深入理解深度学习中的“预测”与“计算”

深入理解深度学习中的“预测”与“计算” 在探讨深度学习和人工智能的应用时&#xff0c;**“预测”**这个词经常被提及。很多时候&#xff0c;人们对预测的理解可能会带有一些误区&#xff0c;特别是当涉及到预测未来的事件或结果时。本文将详细探讨在Python深度学习框架中的…

【C#】在一个给定的宽、高范围内,获取到该多边形内部的所有坐标集合?

问题点 使用C#语言在一个给定的宽、高范围内&#xff0c;获取到该多边形内部的所有坐标集合&#xff1f; 这个多边形可能存在交叉及互相重叠部分 图像的宽、高可以定义为&#xff1a;2000*2000 多边形坐标集合&#xff1a;Point[] polygon_points new Point[] { new Point…

FastAPI集成mongodb的增删改查样例

样例如下 import os from typing import Optional, Listfrom fastapi import FastAPI, Body, HTTPException, status from fastapi.responses import Response from pydantic import ConfigDict, BaseModel, Field, EmailStr from pydantic.functional_validators import Befo…

HTML开发小技巧:根据用户浏览器的分辨率调整控件的大小

在Html页面开发中&#xff0c;我们通常会用Style进行控件的宽度高度进行控件的格式设置&#xff0c;如果直接设置像素的话&#xff0c;无法根据用户的浏览器进行宽高的适配&#xff0c;所以我们要做到根据实际使用的浏览器进行控件大小的自动调整&#xff0c;以下是几种控件自动…

100个python的基本语法知识【下】

50. 压缩文件&#xff1a; import zipfilewith zipfile.ZipFile("file.zip", "r") as zip_ref:zip_ref.extractall("extracted")51. 数据库操作&#xff1a; import sqlite3conn sqlite3.connect("my_database.db") cursor conn.c…

网络安全-华为华三交换机防火墙日志解析示例

DEF_SYSLOG_SWITCH_HUAWEI.py 华为交换机日志解析示例 # -*- coding: utf8 -*- import time from DEF_COLOR import * ## 终端显示颜色def 时间戳_2_时间文本(时间戳, 时间文本格式%Y-%m-%d %H:%M:%S):#时间文本格式 %Y-%m-%d %H:%M:%S时间类 time.localtime(时间戳)时间…

快速安装torch-gpu和Tensorflow-gpu(自用,Ubuntu)

要更详细的教程可以参考Tensorflow PyTorch 安装&#xff08;CPU GPU 版本&#xff09;&#xff0c;这里是有基础之后的快速安装。 一、Pytorch 安装 conda create -n torch_env python3.10.13 conda activate torch_env conda install cudatoolkit11.8 -c nvidia pip ins…

go 并发

一、问题 1.1描述 我想要检测一组url的运行状态&#xff0c;如果ok则返回true&#xff0c;结果返回的结果是空的 func CheckWebsites(wc WebsiteChecker, urls []string) map[string]bool {results : make(map[string]bool)for _, url : range urls {go func() {results[url…