12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697 |
- #include "SerialTool.h"
- #include <QDebug>
- // 定义静态成员变量并初始化为 nullptr
- SerialTool* SerialTool::instance = nullptr;
- SerialTool::SerialTool(QObject* parent) : QObject(parent) {}
- SerialTool::~SerialTool() {
- if (serialPort.isOpen()) {
- serialPort.close();
- }
- }
- SerialTool* SerialTool::getInstance(QObject* parent) {
- if (instance == nullptr) {
- instance = new SerialTool(parent);
- }
- return instance;
- }
- // 打开串口的函数
- void SerialTool::openSerialPort() {
- const QString portName = "COM8";
- const qint32 baudRate = 9600;
- if (!serialPort.isOpen()) {
- serialPort.setPortName(portName);
- serialPort.setBaudRate(baudRate);
- // 设置数据位,通常为 8 位
- serialPort.setDataBits(QSerialPort::Data8);
- // 设置停止位,这里设置为 1 位停止位
- serialPort.setStopBits(QSerialPort::OneStop);
- // 设置校验位,这里设置为无校验
- serialPort.setParity(QSerialPort::NoParity);
- if (serialPort.open(QIODevice::ReadWrite)) {
- qDebug() << "serialPortOpened";
- emit serialPortOpened(); // 发射新信号
- } else {
- qDebug() << "Failed to open serial port:" << serialPort.errorString();
- emit openError();
- }
- }
- }
- // 关闭串口的函数
- void SerialTool::closeSerialPort() {
- if (serialPort.isOpen()) {
- serialPort.close();
- emit openCloseButtonTextChanged("打开串口");
- }
- }
- bool SerialTool::sendData(const QByteArray& data) {
- if (serialPort.isOpen()) {
- qint64 bytesWritten = serialPort.write(data);
- return bytesWritten == data.size();
- }
- return false;
- }
- void SerialTool::handleSendDataReques(const QByteArray& data) { sendData(data); }
- void SerialTool::readData() {
- QByteArray newData = serialPort.readAll();
- buffer.append(newData);
- // 查找完整的命令
- int startIndex = buffer.indexOf("\\r\\n");
- while (startIndex != -1) {
- int endIndex = buffer.indexOf("\\r\\n", startIndex + 4);
- if (endIndex != -1) {
- // 提取完整的命令
- QByteArray command = buffer.mid(startIndex + 4, endIndex - startIndex - 4);
- emit dataReceived(newData);
- qDebug() << "Complete command:" << command;
- // 移除已处理的部分
- buffer = buffer.mid(endIndex + 4);
- } else {
- break;
- }
- startIndex = buffer.indexOf("\\r\\n");
- }
- qDebug() << "Received data:" << newData;
- }
- void SerialTool::setupSerialPort() {
- openSerialPort();
- // openCloseSerialPort();
- qDebug() << "Received data:";
- connect(&serialPort, &QSerialPort::readyRead, this, &SerialTool::readData);
- }
|