serialtool.cpp 2.7 KB

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