rtuport.cpp 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. #include "rtuport.h"
  2. RtuPort::RtuPort()
  3. {
  4. m_serialPort = new QSerialPort(this);
  5. stard = false;
  6. _handle = nullptr;
  7. //设置参数
  8. // m_serialPort->setPortName(GlobalInfo::this_()->config().portName);
  9. // m_serialPort->setBaudRate(GlobalInfo::this_()->config().portBaudRate.toInt());//设置默认波特率和读写方向
  10. // m_serialPort->setDataBits(QSerialPort::Data8); //数据位为8位
  11. // m_serialPort->setFlowControl(QSerialPort::NoFlowControl);//无流控制
  12. // m_serialPort->setParity(QSerialPort::NoParity); //无校验位
  13. // m_serialPort->setStopBits(QSerialPort::OneStop); //一位停止位
  14. connect(m_serialPort,SIGNAL(readyRead()),this,SLOT(receiveInfo()));
  15. // ret = QByteArray::fromHex("010300000006C5C8");
  16. // portTimer = new QTimer(this);
  17. // connect(portTimer,&QTimer::timeout,this,&RtuPort::portStart);
  18. // portTimer->start(1000);
  19. timer = new QTimer(this);
  20. connect(timer,&QTimer::timeout,this,&RtuPort::portWrite);
  21. }
  22. void RtuPort::start(QString & name, int band, SerialBaseHandle * handle)
  23. {
  24. if(m_serialPort->isOpen()) m_serialPort->close();
  25. m_serialPort->setPortName(name);
  26. m_serialPort->setBaudRate(band);
  27. _handle = handle;
  28. m_serialPort->open(QIODevice::ReadWrite);
  29. if(!timer->isActive())
  30. timer->start(200);
  31. stard = true;
  32. }
  33. void RtuPort::portWrite()
  34. {
  35. if(!m_serialPort->isOpen()){
  36. m_serialPort->open(QIODevice::ReadWrite);
  37. return;
  38. }
  39. if(_handle && _handle->needSend()){
  40. m_serialPort->write(_handle->sendData());
  41. }
  42. }
  43. void RtuPort::receiveInfo()
  44. {
  45. QByteArray info = m_serialPort->readAll();
  46. if(_handle)
  47. _handle->handle(info);
  48. }