rtuport.cpp 1.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. #include "rtuport.h"
  2. RtuPort::RtuPort(QObject *p) : QObject(p)
  3. {
  4. m_serialPort = new QSerialPort(this);
  5. stard = false;
  6. _handle = nullptr;
  7. //设置参数
  8. connect(m_serialPort,SIGNAL(readyRead()),this,SLOT(receiveInfo()));
  9. timer = new QTimer(this);
  10. connect(timer,&QTimer::timeout,this,&RtuPort::portWrite);
  11. }
  12. void RtuPort::start(QString & name, int band, SerialBaseHandle * handle)
  13. {
  14. if(m_serialPort->isOpen()) m_serialPort->close();
  15. m_serialPort->setPortName(name);
  16. m_serialPort->setBaudRate(band);
  17. _handle = handle;
  18. m_serialPort->open(QIODevice::ReadWrite);
  19. if(!timer->isActive())
  20. timer->start(200);
  21. stard = true;
  22. }
  23. void RtuPort::portWrite()
  24. {
  25. if(!m_serialPort->isOpen()){
  26. m_serialPort->open(QIODevice::ReadWrite);
  27. return;
  28. }
  29. if(_handle && _handle->needSend()){
  30. m_serialPort->write(_handle->sendData());
  31. }
  32. }
  33. void RtuPort::receiveInfo()
  34. {
  35. QByteArray info = m_serialPort->readAll();
  36. if(_handle)
  37. _handle->handle(info);
  38. }