QT串口和数据库通信

创建串口

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

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.xdnf.cn/news/1488181.html

如若内容造成侵权/违法违规/事实不符,请联系一条长河网进行投诉反馈,一经查实,立即删除!

相关文章

房屋出租系统 学习笔记 韩顺平 零基础30天学会Java(2024.7.15)

代码见package houserent P362 房屋出租需求 P363 房屋出租设计 分层模式 P364 房屋出租工具 给了一个工具包&#xff1a;Utility&#xff0c;使用&#xff1a;String s2 Utility.readString(10,”hspedu”);来限制输入字符大小最大是10&#xff0c;同时初始化的值为hspedu&a…

完全移动huggingface模型仓库(不是简单mv)

Linux中移动huggingface模型仓库 参考链接 先在bashrc中配置&#xff1a; export HF_DATASETS_CACHE"/your/path/dataset" export HF_HOME"/your/path/" export HUGGINGFACE_HUB_CACHE"/your/path/hub" export TRANSFORMERS_CACHE"/your…

速腾聚创激光雷达复现FAST-LIO

目录 1.软件环境 2.测试执行 3.代码学习 3.1.找主节点代码文件 3.2.整体流程结构 3.3.具体函数理解 记录复现FAST-LIO算法的过程和&#xff0c;代码梳理和理解 1.软件环境 Windows 10(64bits) VMware 16 Pro Ubuntu 20.04 ROS Noetic FAST-LIO的简化版、注释版。感谢…

Hospital 14.6.0全开源医院管理预约系统源码

InfyHMS 具有 60 种功能和 9 种不同类型的用户类型&#xff0c; 他们可以登录系统并根据他们的角色访问他们的数据。 源码下载&#xff1a;https://download.csdn.net/download/m0_66047725/89580674 更多资源下载&#xff1a;关注我。

Top-down Microarchitecture Analysis Method

1、英文链接&#xff1a; 1. https://www.intel.com/content/www/us/en/docs/vtune-profiler/cookbook/2023-0/top-down-microarchitecture-analysis-method.html 2. http://portal.nacad.ufrj.br/online/intel/vtune2017/help/GUID-02271361-CCD4-410C-8338-4B8158157EB6.ht…

LC61----1374. 生成每种字符都是奇数个的字符串(字符串)---java版

1.题目 2.思路 &#xff08;1&#xff09;题目要生成每种字符是奇数个的字符串。 &#xff08;2&#xff09;所以直接用参数n%2来判断。 (3)返回的字符串必须只含小写英文字母。如果存在多个满足题目要求的字符串&#xff0c;则返回其中任意一个即可。 (4)感觉题目不是很规范哈…

go程序在windows服务中优雅开启和关闭

本篇主要是讲述一个go程序&#xff0c;如何在windows服务中优雅开启和关闭&#xff0c;废话不多说&#xff0c;开搞&#xff01;&#xff01;&#xff01;   使用方式&#xff1a;go程序 net服务启动 Ⅰ 开篇不利 Windows go进程编译后&#xff0c;为一个.exe文件,直接执行即…

知名医药医疗行业人工智能数字化转型讲师培训师唐兴通谈医药医疗销售与创新思维创新管理数字化AI及大客户销售医美生活美容品牌市场

​唐兴通 数字化商业创新顾问、数字化转型教练、沃顿商学院演讲嘉宾。全球商业思想大家EM罗杰斯&#xff08;创新的扩散&#xff09;、杰弗里摩尔&#xff08;跨越鸿沟&#xff09;、马修狄克逊&#xff08;挑战式销售&#xff09;、布兰登博格&#xff08;竞合战略&#xff0…

css渐变色背景|<gradient

使用渐变色作为背景 可以直接将渐变色用作元素的背景&#xff0c;可以看做是一种特殊的背景图片。&#xff08;是作为背景background一个属性值不是背景颜色background-color的属性值 &#xff09; CSS 渐变是一种从一种颜色平滑过渡到另一种颜色的效果&#xff0c;由 <gra…

Java数据结构(四)——链表

文章目录 链表概念及结构单链表的实现LinkedList的使用构造方法遍历 LinkedList的模拟实现ArrayList与LinkedList区别链表的相关练习反转链表链表的中间结点链表的回文结构判断链表是否有环寻找入环的第一个结点 链表 概念及结构 链表是一种物理存储结构上非连续存储结构&…

【C语言】 二叉树创建(结构体,先序遍历,中序遍历,后续遍历)

二叉树的创建&#xff1a;首先先定义一个结构体&#xff0c;里面包含数据&#xff08;data&#xff09;&#xff0c;指向左子树的指针&#xff08;L&#xff09;&#xff0c;指向右子树的指针&#xff08;R&#xff09;三个部分 在创建树的函数中&#xff0c;首先先输入…

netty使用redis发布订阅实现消息推送

netty使用redis发布订阅实现消息推送 场景 项目中需要给用户推送消息: 接口 RestController public class PushApi {Autowiredprivate PushService pushService;/*** 消息推送* param query* return*/PostMapping("/push/message")public String push(RequestBody…

『 Linux 』信号的写入与保存

文章目录 信号的发送信号的保存sigset_t 类型与信号集操作函数阻塞信号集(信号屏蔽字)操作函数未决信号集操作函数验证阻塞信号集与未决信号集 信号的发送 $ kill -l1) SIGHUP 2) SIGINT 3) SIGQUIT 4) SIGILL 5) SIGTRAP6) SIGABRT 7) SIGBUS 8) SIGFPE 9) SIGKILL 10)…

EXCEL自动公式计算始终为0

如果你的数据单元格的左上角存在绿色的三角小箭头&#xff0c;那么就会造成这种问题&#xff1a; 你的数字是以文本形式存入的单元格 解决办法&#xff1a; 选中数据列&#xff0c;数据->分列 直接选择完成 此时就可以进行公式计算了

Linux作业---dns服务器的搭建

1.先在/www下创建一个net.haha的文件&#xff0c;然后在net.haha下的vim编辑index.html写入想写的内容 [rootrhcsa redhat]# cat /www/net.haha/index.html this is 192.168.127.11 server 2.继续在/etc/nginx/conf.d/baidu.conf下编辑web配置 [rootrhcsa redhat]# cat /etc…

Mem0 - 个人 AI 的内存层

文章目录 一、关于 Mem0核心功能&#x1f511;路线图 &#x1f5fa;️常见用例Mem0与RAG有何不同&#xff1f; 二、快速入门 &#x1f680;1、安装2、基本用法&#xff08;开源&#xff09;3、高级用法&#x1f527;4、大模型支持 三、MultiOn1、概览2、设置和配置4、将记忆添加…

javaScrip的学习(一)

目录 引言 一、java和JavaScript的联系 二、js中的弹出框 1.alert弹出框 2.confirm带确认取消的按钮弹框 3.prompt带有提示信息且带有输入框的弹框 4.输出到网页中 ​三、js引入方式 1. 放在script标签中 2.放在外部js文件中 四、执行顺序 五、书写规范 1. 语句结…

暑期C++ printf和scanf的平替

有任何不懂的问题可以评论区留言&#xff0c;能力范围内都会一一回答 C中也有专门的输入和输出的方法 首先我们需要一个头文件&#xff0c;也就是#include<iostream> 然后根据我们命名空间的知识可知这个地方如果我们要使用必须先展开 可以全部展开比如using namespa…

算法——二分查找(day9)

704.二分查找 704. 二分查找 - 力扣&#xff08;LeetCode&#xff09; 题目解析&#xff1a; 这道题其实用暴力其实很简单&#xff0c;挨个对比就完事了~ 但我们可以利用其升序的特性对其进行优化&#xff1a; 随机选择一个数&#xff08;5&#xff09;&#xff0c;发现比目标…

38.综合练习:评委打分

需求&#xff1a;有6位评委打分&#xff0c;分数范围[0&#xff0c;100]&#xff0c;去掉一个最高分和最低分之后&#xff0c;剩下4个评委的平均分就是最终得分 import java.util.Scanner;public class 评委打分 {public static void main(String[] args) {int[] arr new int…