qserialport.cpp 16.2 KB
Newer Older
James Goppert's avatar
James Goppert committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771
/*
 * Unofficial Qt Serial Port Library
 *
 * Copyright (c) 2010 Inbiza Systems Inc. All rights reserved.
 *
 * This program is free software: you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as published by the
 * Free Software Foundation, either version 3 of the License, or (at your
 * option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for
 * more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>
 *
 * author labs@inbiza.com
 */

#include <QDebug>
#include "qserialport.h"

#ifdef TNX_POSIX_SERIAL_PORT
# include <QSocketNotifier>
# include <fcntl.h>
# include <sys/ioctl.h>
# include <errno.h>
# include "posix/termioshelper.h"
#elif defined(TNX_WINDOWS_SERIAL_PORT)
# include "win32/commdcbhelper.h"
# include "win32/qwincommevtnotifier.h"
#endif

namespace TNX {

/*!
  Constructs a QSerialPort object with the given \a port name and \a parent.
*/
QSerialPort::QSerialPort(const QString &portName, QObject *parent)
  : QSerialPortNative(portName, parent), pendingByteCount_(0),
    doNotify_(false), readNotifyThreshold_(1)
{
}

/*!
  Constructs a QSerialPort object with the given \a port name, \a settings and \a parent.
*/
QSerialPort::QSerialPort(const QString &portName, const QPortSettings &settings, QObject *parent)
  : QSerialPortNative(portName, settings, parent), pendingByteCount_(0), doNotify_(false),
    readNotifyThreshold_(1)
{
}

/*!
  Constructs a QSerialPort object with the given \a port name, \a settings and \a parent.
*/
QSerialPort::QSerialPort(const QString &portName, const QString &settings, QObject *parent)
  : QSerialPortNative(portName, settings, parent), pendingByteCount_(0), doNotify_(false),
    readNotifyThreshold_(1)
{
}

QSerialPort::~QSerialPort()
{
  close();
}

/*!

 */
bool QSerialPort::setPortSettings(const QPortSettings &portSettings)
{
  bool result = false;
  if ( isOpen() ) {
    portHelper_->setBaudRate(portSettings.baudRate());
    portHelper_->setDataBits(portSettings.dataBits());
    portHelper_->setStopBits(portSettings.stopBits());
    portHelper_->setFlowControl(portSettings.flowControl());
    portHelper_->setParity(portSettings.parity());

    result = portHelper_->applyChanges(PortAttrOnlyAppTy);
  }
  else {
    portSettings_ = portSettings;
    result = true;
  }

  if ( !result )
    setErrorString(lastErrorText_impl());
  else
    portSettings_ = portSettings;

  return result;
}

/*! \reimp
*/
bool QSerialPort::isSequential() const
{
  return true;
}

/*!
  Opens the I/O device for the serial port.
*/
bool QSerialPort::open(OpenMode mode)
{
  if ( isOpen() )
    return true;

  // mode argument is ignored intentionally

  if ( portName_.isEmpty() ) {
    setErrorString("Port name is empty.");
    return false;
  }

  if ( !open_impl() ) {
    qCritical() << QString("QSerialPort::open(%1) failed: %2(Err #%3)")
                    .arg(portName_)
                    .arg(lastErrorText_impl())
                    .arg(lastError_impl());
    setErrorString(lastErrorText_impl());

    // we don't know exactly what state this object in before the error.
    // make sure that we don't leave any unused object hanging in the memory.
    delete portHelper_;
    delete readNotifier_;
    readNotifier_ = NULL;
    portHelper_ = NULL;

    return false;
  }

  // open QIODevice

  setOpenMode(mode | QIODevice::Unbuffered);

  qDebug() << "Serial port \"" << portName_ << "\" is successfully opened";

  // Set port attributes

  setPortSettings(portSettings_);

  // Set communication timing values

  setCommTimeouts(commTimeouts_);

  if ( !portHelper_->applyChanges() ) {
    qCritical() << QString("QSerialPort::open(%1) failed when setting up the port: %2(Err #%3)")
                    .arg(portName_)
                    .arg(lastErrorText_impl())
                    .arg(lastError_impl());
    setErrorString(lastErrorText_impl());
   }

  return true;
}

/*!
  Closes the I/O device for the serial port.

  See QIODevice::close() for a description of the actions that occur when an I/O
  device is closed.
*/
void QSerialPort::close()
{
  if ( isOpen() ) {

    delete portHelper_;
    portHelper_ = NULL;
    
    // disconnect the ReadNotifier

    if ( readNotifier_ ) {
      disconnect(readNotifier_, SIGNAL(activated(int)), this, SLOT(onDataReceived()));
      delete readNotifier_;
      readNotifier_ = NULL;
    }

    close_impl();
    
    // Close the device

    QIODevice::close();

    qDebug() << "Serial port \"" << portName_ << "\" is successfully closed";
  }
}

/*! \reimp
*/
qint64 QSerialPort::pos() const
{
  return 0;
}

/*! \reimp
*/
qint64 QSerialPort::size() const
{
  return bytesAvailable();
}

/*! \reimp
*/
bool QSerialPort::seek(qint64 /*pos*/)
{
  return false;
}

/*! \reimp
*/
bool QSerialPort::atEnd() const
{
  return true;
}

/*! \reimp
*/
qint64 QSerialPort::bytesAvailable() const
{
  qint64 nBytes = bytesAvailable_impl();
  if ( nBytes == -1LL ) {
    qDebug() << QString("QSerialPort::bytesAvailable(%1) failed: %2(Err #%3)")
                    .arg(portName_)
                    .arg(lastErrorText_impl())
                    .arg(lastError_impl());
    const_cast<QSerialPort*>(this)->setErrorString(lastErrorText_impl());
    return -1LL;
  }

  return QIODevice::bytesAvailable() + nBytes;
}

/*! \reimp
*/
qint64 QSerialPort::bytesToWrite() const
{
  return 0LL;
}

/*! \reimp
*/
bool QSerialPort::canReadLine() const
{
  return false;
}

/*! \reimp
 
 */
bool QSerialPort::waitForReadyRead(int timeout)
{
  bool ret = false;
  readNotifier_->setEnabled(false);

  int result = waitForReadyRead_impl((timeout < 0 ? -1 : timeout));
  if ( result > 0 ) {
    ret = true;
    emit readyRead();
  }
  else if ( result == 0 )
   ; // Timeout occurred. Do nothing, return false
  else {
    // Error occurred. Logs the error and return false
    qDebug() << QString("QSerialPort::waitForReadyRead(%1) failed: %2(Err #%3)")
                    .arg(portName_)
                    .arg(lastErrorText_impl())
                    .arg(lastError_impl());
    setErrorString(lastErrorText_impl());
  }

  readNotifier_->setEnabled(true);
  return ret;
}

/*! \reimp

*/
bool QSerialPort::waitForBytesWritten(int /*msecs*/)
{
  return true;
}

/*! \reimp
*/
qint64 QSerialPort::readData(char *data, qint64 maxlen)
{
  Q_CHECK_PTR(data);

  qint64 bytesRead = readData_impl(data, maxlen);

  if ( bytesRead == -1LL ) {
    qDebug() << QString("QSerialPort::readData(%1) failed: %2(Err #%3)")
                    .arg(portName_)
                    .arg(lastErrorText_impl())
                    .arg(lastError_impl());
    setErrorString(lastErrorText_impl());
  }
      
  if ( bytesRead > 0LL ) {
    doNotify_ = false;

    // the number of bytes consumed can be higher than the pending byte count
    pendingByteCount_ = (pendingByteCount_ - bytesRead) < 0LL ? 0LL :
                          (pendingByteCount_ - bytesRead);
  }

  readNotifier_->setEnabled(true);
  return bytesRead;
}

/*! \reimp
*/
qint64 QSerialPort::writeData(const char *data, qint64 len)
{
  Q_CHECK_PTR(data);

  qint64 nBytes = writeData_impl(data, len);
  if ( nBytes == -1LL ) {
    qDebug() << QString("QSerialPort::writeData(%1) failed: %2(Err #%3)")
                    .arg(portName_)
                    .arg(lastErrorText_impl())
                    .arg(lastError_impl());
    setErrorString(lastErrorText_impl());
  }

  if ( 0LL == nBytes && 0LL < len ) {
    qDebug() << QString("QSerialPort::writeData(%1) - method returns no error but " \
                          "number of bytes written is zero: %2(Err #%3)")
                .arg(portName_)
                .arg(lastErrorText_impl())
                .arg(lastError_impl());
  }

  if ( nBytes > 0LL )
    emit bytesWritten(nBytes);

  return nBytes;
}

/*!

*/
void QSerialPort::onDataReceived()
{
  qint64 nBytes = bytesAvailable_impl();

  if ( -1LL == nBytes )
    return;

  if ( nBytes > pendingByteCount_ ||
       (nBytes > 0LL && nBytes == pendingByteCount_ && !doNotify_) ) {
    pendingByteCount_ = nBytes;
    doNotify_ = true;

    if ( pendingByteCount_ >= (qint64)readNotifyThreshold_ ) {
      readNotifier_->setEnabled(false);
      emit readyRead();
    }
  }
}

/*!

 */
bool QSerialPort::flushOutBuffer()
{
  bool result = flushOutBuffer_impl();
  if ( !result ) {
    qDebug() << QString("QSerialPort::flushOutBuffer(%1) failed: %2(Err #%3)")
                    .arg(portName_)
                    .arg(lastErrorText_impl())
                    .arg(lastError_impl());
    setErrorString(lastErrorText_impl());
  }
  return result;
}

/*!

*/
bool QSerialPort::flushInBuffer()
{
  bool result = flushInBuffer_impl();
  if ( !result ) {
    qDebug() << QString("QSerialPort::flushInBuffer(%1) failed: %2(Err #%3)")
                    .arg(portName_)
                    .arg(lastErrorText_impl())
                    .arg(lastError_impl());
    setErrorString(lastErrorText_impl());
  }
  else {
    pendingByteCount_ = 0LL;
    readNotifier_->setEnabled(true);
  }
  return result;
}

/*!

*/
bool QSerialPort::sendBreak(int timeout)
{
  bool result = sendBreak_impl(timeout);
  if ( !result ) {
    qDebug() << QString("QSerialPort::sendBreak(%1) failed: %2(Err #%3)")
                    .arg(portName_)
                    .arg(lastErrorText_impl())
                    .arg(lastError_impl());
    setErrorString(lastErrorText_impl());
  }
  return result;
}


CommTimeouts QSerialPort::commTimeouts()
{
  if ( !isOpen() )
    return commTimeouts_;

  Q_CHECK_PTR(portHelper_);

  CommTimeouts commtimeouts;
  bool res = portHelper_->commTimeouts(commtimeouts);
  if ( !res ) {
    qDebug() << QString("QSerialPort::commTimeouts(%1) failed: %2(Err #%3)")
                    .arg(portName_)
                    .arg(lastErrorText_impl())
                    .arg(lastError_impl());
    setErrorString(lastErrorText_impl());
  }
  else {
    commTimeouts_ = commtimeouts;
  }

  return commTimeouts_;
}

bool QSerialPort::setCommTimeouts(const CommTimeouts commtimeouts)
{
  commTimeouts_ = commtimeouts;

  if ( !isOpen() )
    return true;

  Q_CHECK_PTR(portHelper_);

  portHelper_->setCommTimeouts(commTimeouts_);
  bool result = portHelper_->applyChanges(CommTimeoutsOnlyAppTy);
  if ( !result ) {
    qDebug() << QString("QSerialPort::setCommTimouts(%1) failed: %2(Err #%3)")
                  .arg(portName_)
                  .arg(lastErrorText_impl())
                  .arg(lastError_impl());
    setErrorString(lastErrorText_impl());
  }
  return result;
}

bool QSerialPort::setCommTimeouts(CommTimeoutSchemes scheme, int timeout)
{
  if ( scheme == CtScheme_NonBlockingRead ) {
    commTimeouts_.PosixVMIN = 0;
    commTimeouts_.PosixVTIME = 0;
    commTimeouts_.Win32ReadIntervalTimeout = CommTimeouts::NoTimeout;
    commTimeouts_.Win32ReadTotalTimeoutConstant = 0;
    commTimeouts_.Win32ReadTotalTimeoutMultiplier = 0;
  }
  else if ( scheme == CtScheme_TimedRead ) {
    commTimeouts_.PosixVMIN = 0;
    // converting ms to one-tenths-of-second (sec * 0.1)
    commTimeouts_.PosixVTIME = timeout / 100;
    commTimeouts_.Win32ReadIntervalTimeout = 0;
    commTimeouts_.Win32ReadTotalTimeoutConstant = timeout;
    commTimeouts_.Win32ReadTotalTimeoutMultiplier = 0;
  }

  if ( !isOpen() )
    return true;

  Q_CHECK_PTR(portHelper_);

  portHelper_->setCommTimeouts(commTimeouts_);
  bool result = portHelper_->applyChanges(CommTimeoutsOnlyAppTy);
  if ( !result ) {
    qDebug() << QString("QSerialPort::setCommTimouts(%1, scheme: %2) failed: %3(Err #%4)")
                  .arg(portName_)
                  .arg((int)scheme)
                  .arg(lastErrorText_impl())
                  .arg(lastError_impl());
    setErrorString(lastErrorText_impl());
  }
  return result;
}

/*!

*/
QPortSettings::BaudRate QSerialPort::baudRate() const
{
  if ( !isOpen() )
    return portSettings_.baudRate();

  Q_CHECK_PTR(portHelper_);

  return portHelper_->baudRate();
}

/*!

*/
bool QSerialPort::setBaudRate(QPortSettings::BaudRate baudRate)
{
  if ( !isOpen() ) {
    portSettings_.setBaudRate(baudRate);
    return true;
  }

  Q_CHECK_PTR(portHelper_);

  bool result = false;

  portHelper_->setBaudRate(baudRate);
  if ( (result = portHelper_->applyChanges(PortAttrOnlyAppTy)) )
    portSettings_.setBaudRate(baudRate);
  else
    setErrorString(lastErrorText_impl());

  return result;
}

/*!

*/
QPortSettings::Parity QSerialPort::parity() const
{
  if ( !isOpen() )
    return portSettings_.parity();

  Q_CHECK_PTR(portHelper_);

  return portHelper_->parity();
}

/*!

*/
bool QSerialPort::setParity(QPortSettings::Parity parity)
{
  if ( !isOpen() ) {
    portSettings_.setParity(parity);
    return true;
  }

  Q_CHECK_PTR(portHelper_);

  bool result = false;

  portHelper_->setParity(parity);
  if ( (result = portHelper_->applyChanges(PortAttrOnlyAppTy)) )
    portSettings_.setParity(parity);
  else
    setErrorString(lastErrorText_impl());

  return result;
}

/*!

*/
QPortSettings::StopBits QSerialPort::stopBits() const
{
  if ( !isOpen() )
    return portSettings_.stopBits();

  Q_CHECK_PTR(portHelper_);

  return portHelper_->stopBits();
}

/*!

*/
bool QSerialPort::setStopBits(QPortSettings::StopBits stopBits)
{
  if ( !isOpen() ) {
    portSettings_.setStopBits(stopBits);
    return true;
  }

  Q_CHECK_PTR(portHelper_);

  bool result = false;

  portHelper_->setStopBits(stopBits);
  if ( (result = portHelper_->applyChanges(PortAttrOnlyAppTy)) )
    portSettings_.setStopBits(stopBits);
  else
    setErrorString(lastErrorText_impl());

  return result;
}

/*!

*/
QPortSettings::DataBits QSerialPort::dataBits() const
{
  if ( !isOpen() )
    return portSettings_.dataBits();

  Q_CHECK_PTR(portHelper_);

  return portHelper_->dataBits();
}

/*!

*/
bool QSerialPort::setDataBits(QPortSettings::DataBits dataBits)
{
  if ( !isOpen() ) {
    portSettings_.setDataBits(dataBits);
    return true;
  }

  Q_CHECK_PTR(portHelper_);

  bool result = false;

  portHelper_->setDataBits(dataBits);
  if ( (result = portHelper_->applyChanges(PortAttrOnlyAppTy)) )
    portSettings_.setDataBits(dataBits);
  else
    setErrorString(lastErrorText_impl());

  return result;
}

/*!

*/
QPortSettings::FlowControl QSerialPort::flowControl() const
{
  if ( !isOpen() )
    return portSettings_.flowControl();

  Q_CHECK_PTR(portHelper_);

  return portHelper_->flowControl();
}

/*!

*/
bool QSerialPort::setFlowControl(QPortSettings::FlowControl flowControl)
{
  if ( !isOpen() ) {
    portSettings_.setFlowControl(flowControl);
    return true;
  }

  Q_CHECK_PTR(portHelper_);

  bool result = false;

  portHelper_->setFlowControl(flowControl);
  if ( (result = portHelper_->applyChanges(PortAttrOnlyAppTy)) )
    portSettings_.setFlowControl(flowControl);
  else
    setErrorString(lastErrorText_impl());

  return result;
}


/*!

*/
bool QSerialPort::setRts(bool on)
{
  if ( !isOpen() )
    return false;

  if ( !portHelper_->setRts(on) ) {
    setErrorString(lastErrorText_impl());
    return false;
  }
  return true;
}

/*!

*/
bool QSerialPort::setDtr(bool on)
{
  if ( !isOpen() )
    return false;

  if ( !portHelper_->setDtr(on) ) {
    setErrorString(lastErrorText_impl());
    return false;
  }
  return true;
}

/*!

*/
QSerialPort::CommSignalValues QSerialPort::cts()
{
  if ( !isOpen() )
    return Signal_Unknown;

  CommSignalValues cts;
  if ( Signal_Unknown == (cts = portHelper_->cts()) )
    setErrorString(lastErrorText_impl());

  return cts;
}

/*!

*/
QSerialPort::CommSignalValues QSerialPort::dsr()
{
  if ( !isOpen() )
    return Signal_Unknown;

  CommSignalValues dsr;
  if ( Signal_Unknown == (dsr = portHelper_->dsr()) )
    setErrorString(lastErrorText_impl());

  return dsr;
}

/*!

*/
QSerialPort::CommSignalValues QSerialPort::dcd()
{
  if ( !isOpen() )
    return Signal_Unknown;

  CommSignalValues dcd;
  if ( Signal_Unknown == (dcd = portHelper_->dcd()) )
    setErrorString(lastErrorText_impl());

  return dcd;
}

/*!

*/
QSerialPort::CommSignalValues QSerialPort::ri()
{
  if ( !isOpen() )
    return Signal_Unknown;

  CommSignalValues ri;
  if ( Signal_Unknown == (ri = portHelper_->ri()) )
    setErrorString(lastErrorText_impl());

  return ri;
}

} // namespace