qserialportnative_win32.cpp 10.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
/*
 * 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
 */

// See http://msdn.microsoft.com/en-us/library/ms810467.aspx#serial_topic1
// for Win32 Serial Port programming.
// Also see the following forum http://www.codeguru.com/forum/archive/index.php/t-324660.html

#include <QDebug>
#include "qwincommevtnotifier.h"
#include "commdcbhelper.h"
#include "qserialport.h"
#include "qserialportnative.h"

namespace TNX {

/*!
  Constructs a QSerialPortNative object with the given \a port name and \a parent.
*/
QSerialPortNative::QSerialPortNative(const QString &portName, QObject *parent)
  : QIODevice(parent), portName_(portName), fileDescriptor_(0), portHelper_(NULL),
    readNotifier_(NULL)
{
#ifdef __MINGW32__
  ZeroMemory(&ovRead_, sizeof(OVERLAPPED));
  ZeroMemory(&ovWrite_, sizeof(OVERLAPPED));
#else
  SecureZeroMemory(&ovRead_, sizeof(OVERLAPPED));
  SecureZeroMemory(&ovWrite_, sizeof(OVERLAPPED));
#endif
}

/*!
  Constructs a QSerialPortNative object with the given \a port name, \a settings and \a parent.
*/
QSerialPortNative::QSerialPortNative(const QString &portName, const QPortSettings &settings, QObject *parent)
  : QIODevice(parent), portName_(portName), portSettings_(settings), fileDescriptor_(0), portHelper_(NULL),
    readNotifier_(NULL)
{
#ifdef __MINGW32__
  ZeroMemory(&ovRead_, sizeof(OVERLAPPED));
  ZeroMemory(&ovWrite_, sizeof(OVERLAPPED));
#else
  SecureZeroMemory(&ovRead_, sizeof(OVERLAPPED));
  SecureZeroMemory(&ovWrite_, sizeof(OVERLAPPED));
#endif
}

/*!
*/
bool QSerialPortNative::open_impl()
{
  // This is needed if comport number
  // is higher than 9

  if ( "//./" != portName_.left(4) )
    portName_.insert(0, "//./");

  fileDescriptor_ = CreateFileA(portName_.toLatin1(), GENERIC_READ|GENERIC_WRITE,
                                0, NULL, OPEN_EXISTING, FILE_FLAG_OVERLAPPED, NULL);

  if ( INVALID_HANDLE_VALUE == fileDescriptor_ )
    return false;

  readNotifier_ = new QWinCommEvtNotifier(fileDescriptor_, this);

  Q_CHECK_PTR(readNotifier_);

  if ( !readNotifier_ || !connect(readNotifier_, SIGNAL(activated(int)), 
                                  this, SLOT(onDataReceived()), Qt::QueuedConnection ) ) {
    qWarning() << QString("QSerialPort::open(%1) failed when connecting to read notifier")
                    .arg(portName_);
  }
  
  // Create a dcb helper object

  portHelper_ = new CommDCBHelper(fileDescriptor_);

  Q_CHECK_PTR(portHelper_);

  // Prepare overlapped io structure for Read/Write operations

  ovRead_.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL); // manual-reset event and initial state is nonsignaled
  Q_ASSERT(ovRead_.hEvent != NULL);
  ovWrite_.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);// manual-reset event and initial state is nonsignaled
  Q_ASSERT(ovWrite_.hEvent != NULL);

  return true;
}

/*!
*/
void QSerialPortNative::close_impl()
{
  // Close Read/Write overlapped io event handles
  CloseHandle(ovRead_.hEvent);
  CloseHandle(ovWrite_.hEvent);

  // Close the serial port, and init the handle

  if ( !CloseHandle(fileDescriptor_) ) {
    qWarning() << QString("QSerialPort::close(%1) failed: %2(Err #%3)")
                    .arg(portName_)
                    .arg(lastErrorText_impl())
                    .arg(lastError_impl());
  }
  fileDescriptor_ = INVALID_HANDLE_VALUE;
}

/*!
*/
QString QSerialPortNative::lastErrorText_impl() const
{
  return CommDCBHelper::errorText(GetLastError());
}

/*!
*/
int QSerialPortNative::lastError_impl() const
{
  return GetLastError();
}

/*!
*/
qint64 QSerialPortNative::bytesAvailable_impl() const
{
  DWORD errorMask = 0;
  COMSTAT comStat;
  if ( !ClearCommError(fileDescriptor_, &errorMask, &comStat) )
    return -1LL;

  return QIODevice::bytesAvailable() + (qint64)comStat.cbInQue;
}

/*!
 * @return -1 if error, 0 if timed-out, 1 if incoming data
 */
int QSerialPortNative::waitForReadyRead_impl(int timeout)
{
  int result = -1;
  OVERLAPPED osStatus;
  DWORD dwMask;
  DWORD orgFlags;

  readNotifier_->suspend();

  // store the current event mask.

  if ( !GetCommMask(fileDescriptor_, &orgFlags) )
    goto LExit;

  // this one is to release the notifier thread.

  if ( !SetCommMask(fileDescriptor_, 0) )
    goto LExit;

  // change the event mask to wait incoming bytes.

  if ( !SetCommMask(fileDescriptor_, EV_RXCHAR | EV_ERR) )
    goto LExit;

  {
#ifdef __MINGW32__
    ZeroMemory(&osStatus, sizeof(OVERLAPPED));
#else
    SecureZeroMemory(&osStatus, sizeof(OVERLAPPED));
#endif
    osStatus.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
    Q_ASSERT(osStatus.hEvent != NULL);

    if ( !WaitCommEvent(fileDescriptor_, &dwMask, &osStatus) ) {
      if ( GetLastError() == ERROR_IO_PENDING ) {
        // Wait until the operation is completed
        DWORD dwRes = WaitForSingleObject(osStatus.hEvent, (timeout == -1 ? INFINITE : timeout));
        switch (dwRes)
        {
          // Event occurred
          case WAIT_OBJECT_0:
            if ( !GetOverlappedResult(fileDescriptor_, &osStatus, (LPDWORD)&dwRes, FALSE) ) {
              // An error occurred in the overlapped operation;  call GetLastError to find out what it is.
              result = -1;
            }
            else {
              if ( dwMask & EV_RXCHAR )
                result = 1; // data pending
              else if ( dwMask & EV_ERR )
                result = -1;
              else {
                qWarning() << QString("QSerialPortNative::waitForReadyRead(%1): unexpected event returned.")
                           .arg(portName_);
                result = 0; // this path is not expected
              }
            }
            break;

          case WAIT_TIMEOUT:
            result = 0;
            break;

          // Error in the WaitForSingleObject;
          // This indicates a problem with the OVERLAPPED structure's
          // event handle.
          default:
            result = -1;
        }// switch
      }
      else {
        // Error while waiting for data
        result = -1;
      }
    }
    else {
      // WaitCommEvent returned immediately.
      result = 1;
    }

    CloseHandle(osStatus.hEvent);
  }

  // reset event mask for event notifier thread
  if ( !SetCommMask(fileDescriptor_, orgFlags) )
    result = -1;

LExit:
  readNotifier_->resume();
  return result;
}

/*!
*/
bool QSerialPortNative::flushInBuffer_impl()
{
  // PURGE_RXABORT: Terminates all outstanding overlapped read operations and returns immediately, 
  // even if the read operations have not been completed.
  // PURGE_TXABORT: Terminates all outstanding overlapped write operations and returns immediately, 
  // even if the write operations have not been completed.

  // clear internal buffers
  if ( !PurgeComm(fileDescriptor_, PURGE_RXABORT | PURGE_RXCLEAR ) )
    return false;

  return true;
}

/*!
*/
bool QSerialPortNative::flushOutBuffer_impl()
{
  // PURGE_RXABORT: Terminates all outstanding overlapped read operations and returns immediately, 
  // even if the read operations have not been completed.
  // PURGE_TXABORT: Terminates all outstanding overlapped write operations and returns immediately, 
  // even if the write operations have not been completed.

  // clear internal buffers
  if ( !PurgeComm(fileDescriptor_, PURGE_TXABORT | PURGE_TXCLEAR ) ) 
    return false;

  return true;
}

/*!
*/
bool QSerialPortNative::sendBreak_impl(int timeout)
{
  // send a break for a very short time

  if ( !SetCommBreak(fileDescriptor_) )
    return false;

  Sleep(timeout); 

  // clear the break and continue

  if ( !ClearCommBreak(fileDescriptor_) )
    return false;

  return true;
}

/*!
*/
qint64 QSerialPortNative::readData_impl(char *data, qint64 maxlen)
{
  ResetEvent(ovRead_.hEvent);

  qint64 numBytes = 0LL;
  if ( !ReadFile(fileDescriptor_, (void*)data, (DWORD)maxlen, (LPDWORD)&numBytes, &ovRead_) ) {
    if ( GetLastError() == ERROR_IO_PENDING ) {
      // Wait until read operation is completed
      DWORD dwRes = WaitForSingleObject(ovRead_.hEvent, INFINITE);
      switch (dwRes) 
      {
        // Event occurred
        case WAIT_OBJECT_0:
          if ( !GetOverlappedResult(fileDescriptor_, &ovRead_, (LPDWORD)&numBytes, FALSE) ) {
            // An error occurred in the overlapped operation;
            // call GetLastError to find out what it was
            numBytes = -1LL;
          }
          break;
  
        // Error in the WaitForSingleObject;
        // This indicates a problem with the OVERLAPPED structure's
        // event handle.
        default:
          numBytes = -1LL;
      }// switch
    }
    else {
      // Error while reading data
      numBytes = -1LL;
    }
  }//endif

  return numBytes;
}

/*!
*/
qint64 QSerialPortNative::writeData_impl(const char *data, qint64 len)
{
  ResetEvent(ovWrite_.hEvent);

  qint64 numBytes = 0LL;
  if ( !WriteFile(fileDescriptor_, (void*)data, (DWORD)len, (DWORD*)&numBytes, &ovWrite_) ) {
    if ( GetLastError() == ERROR_IO_PENDING ) {
      // Wait until write operation is completed
      DWORD dwRes = WaitForSingleObject(ovWrite_.hEvent, INFINITE);
      switch (dwRes) 
      {
        // Event occurred
        case WAIT_OBJECT_0:
          if ( !GetOverlappedResult(fileDescriptor_, &ovWrite_, (LPDWORD)&numBytes, FALSE) ) {
            // An error occurred in the overlapped operation;
            // call GetLastError to find out what it was
            numBytes = -1LL;
          }
          break;
  
        // Error in the WaitForSingleObject;
        // This indicates a problem with the OVERLAPPED structure's
        // event handle.
        default:
          numBytes = -1LL;
      }// switch
    }
    else {
      // Error while writing data
      numBytes = -1LL;
    }
  }
   
  return numBytes;
}

} // namespace