rtuport.cpp 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. #include "rtuport.h"
  2. RtuPort::RtuPort()
  3. {
  4. m_serialPort = new QSerialPort();
  5. //设置参数
  6. m_serialPort->setPortName(GlobalInfo::this_()->config().portName);
  7. m_serialPort->setBaudRate(GlobalInfo::this_()->config().portBaudRate.toInt(),QSerialPort::AllDirections);//设置默认波特率和读写方向
  8. m_serialPort->setDataBits(QSerialPort::Data8); //数据位为8位
  9. m_serialPort->setFlowControl(QSerialPort::NoFlowControl);//无流控制
  10. m_serialPort->setParity(QSerialPort::NoParity); //无校验位
  11. m_serialPort->setStopBits(QSerialPort::OneStop); //一位停止位
  12. connect(m_serialPort,SIGNAL(readyRead()),this,SLOT(receiveInfo()));
  13. ret = QByteArray::fromHex("010300000006C5C8");
  14. portTimer = new QTimer(this);
  15. connect(portTimer,&QTimer::timeout,this,&RtuPort::portStart);
  16. portTimer->start(1000);
  17. }
  18. void RtuPort::portStart()
  19. {
  20. m_serialPort->open(QIODevice::ReadWrite);
  21. if(!m_serialPort->isOpen()){
  22. qDebug()<<"串口未打开";
  23. return;
  24. }
  25. qDebug("串口已开启");
  26. portTimer->stop();
  27. timer = new QTimer(this);
  28. connect(timer,&QTimer::timeout,this,&RtuPort::portWrite);
  29. timer->start(200);
  30. }
  31. void RtuPort::portWrite()
  32. {
  33. // qDebug()<<"测试";
  34. // if(hexData.isEmpty()){
  35. // qDebug()<<"null";
  36. // timer->stop();
  37. // portTimer->start(1000);
  38. // }
  39. m_serialPort->write(ret);
  40. }
  41. void RtuPort::receiveInfo()
  42. {
  43. QByteArray info = m_serialPort->readAll();
  44. QByteArray hexData = info.toHex().data();
  45. // qDebug()<<"receiveInfo测试:"<<hexData.toUpper();
  46. log.readed(info);
  47. // QByteArray data;
  48. }