serialtool.cpp 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. #include "SerialTool.h"
  2. #include <QDebug>
  3. // 定义静态成员变量并初始化为 nullptr
  4. SerialTool* SerialTool::instance = nullptr;
  5. SerialTool::SerialTool(QObject* parent) : QObject(parent) {}
  6. SerialTool::~SerialTool() {
  7. if (serialPort.isOpen()) {
  8. serialPort.close();
  9. }
  10. }
  11. SerialTool* SerialTool::getInstance(QObject* parent) {
  12. if (instance == nullptr) {
  13. instance = new SerialTool(parent);
  14. }
  15. return instance;
  16. }
  17. // 打开串口的函数
  18. void SerialTool::openSerialPort() {
  19. const QString portName = "COM8";
  20. const qint32 baudRate = 9600;
  21. if (!serialPort.isOpen()) {
  22. serialPort.setPortName(portName);
  23. serialPort.setBaudRate(baudRate);
  24. // 设置数据位,通常为 8 位
  25. serialPort.setDataBits(QSerialPort::Data8);
  26. // 设置停止位,这里设置为 1 位停止位
  27. serialPort.setStopBits(QSerialPort::OneStop);
  28. // 设置校验位,这里设置为无校验
  29. serialPort.setParity(QSerialPort::NoParity);
  30. if (serialPort.open(QIODevice::ReadWrite)) {
  31. qDebug() << "serialPortOpened";
  32. emit serialPortOpened(); // 发射新信号
  33. } else {
  34. qDebug() << "Failed to open serial port:" << serialPort.errorString();
  35. emit openError();
  36. }
  37. }
  38. }
  39. // 关闭串口的函数
  40. void SerialTool::closeSerialPort() {
  41. if (serialPort.isOpen()) {
  42. serialPort.close();
  43. emit openCloseButtonTextChanged("打开串口");
  44. }
  45. }
  46. bool SerialTool::sendData(const QByteArray& data) {
  47. if (serialPort.isOpen()) {
  48. qint64 bytesWritten = serialPort.write(data);
  49. return bytesWritten == data.size();
  50. }
  51. return false;
  52. }
  53. void SerialTool::handleSendDataReques(const QByteArray& data) { sendData(data); }
  54. void SerialTool::readData() {
  55. QByteArray newData = serialPort.readAll();
  56. buffer.append(newData);
  57. // 查找完整的命令
  58. int startIndex = buffer.indexOf("\\r\\n");
  59. while (startIndex != -1) {
  60. int endIndex = buffer.indexOf("\\r\\n", startIndex + 4);
  61. if (endIndex != -1) {
  62. // 提取完整的命令
  63. QByteArray command = buffer.mid(startIndex + 4, endIndex - startIndex - 4);
  64. emit dataReceived(newData);
  65. qDebug() << "Complete command:" << command;
  66. // 移除已处理的部分
  67. buffer = buffer.mid(endIndex + 4);
  68. } else {
  69. break;
  70. }
  71. startIndex = buffer.indexOf("\\r\\n");
  72. }
  73. qDebug() << "Received data:" << newData;
  74. }
  75. void SerialTool::setupSerialPort() {
  76. openSerialPort();
  77. // openCloseSerialPort();
  78. qDebug() << "Received data:";
  79. connect(&serialPort, &QSerialPort::readyRead, this, &SerialTool::readData);
  80. }