| 1 | /**************************************************************************** |
| 2 | ** Copyright (c) 2000-2003 Wayne Roth |
| 3 | ** Copyright (c) 2004-2007 Stefan Sander |
| 4 | ** Copyright (c) 2007 Michal Policht |
| 5 | ** Copyright (c) 2008 Brandon Fosdick |
| 6 | ** Copyright (c) 2009-2010 Liam Staskawicz |
| 7 | ** Copyright (c) 2011 Debao Zhang |
| 8 | ** All right reserved. |
| 9 | ** Web: http://code.google.com/p/qextserialport/ |
| 10 | ** |
| 11 | ** Permission is hereby granted, free of charge, to any person obtaining |
| 12 | ** a copy of this software and associated documentation files (the |
| 13 | ** "Software"), to deal in the Software without restriction, including |
| 14 | ** without limitation the rights to use, copy, modify, merge, publish, |
| 15 | ** distribute, sublicense, and/or sell copies of the Software, and to |
| 16 | ** permit persons to whom the Software is furnished to do so, subject to |
| 17 | ** the following conditions: |
| 18 | ** |
| 19 | ** The above copyright notice and this permission notice shall be |
| 20 | ** included in all copies or substantial portions of the Software. |
| 21 | ** |
| 22 | ** THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, |
| 23 | ** EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF |
| 24 | ** MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND |
| 25 | ** NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE |
| 26 | ** LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION |
| 27 | ** OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION |
| 28 | ** WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. |
| 29 | ** |
| 30 | ****************************************************************************/ |
| 31 | |
| 32 | #include "qextserialport.h" |
| 33 | #include "qextserialport_p.h" |
| 34 | #include <QtCore/QThread> |
| 35 | #include <QtCore/QReadWriteLock> |
| 36 | #include <QtCore/QMutexLocker> |
| 37 | #include <QtCore/QDebug> |
| 38 | #include <QtCore/QRegExp> |
| 39 | #include <QtCore/QMetaType> |
| 40 | #if QT_VERSION >= QT_VERSION_CHECK(5, 0, 0) |
| 41 | # include <QtCore/QWinEventNotifier> |
| 42 | #else |
| 43 | # include <QtCore/private/qwineventnotifier_p.h> |
| 44 | #endif |
| 45 | void QextSerialPortPrivate::platformSpecificInit() |
| 46 | { |
| 47 | handle = INVALID_HANDLE_VALUE; |
| 48 | ZeroMemory(&overlap, sizeof(OVERLAPPED)); |
| 49 | overlap.hEvent = CreateEvent(NULL, true, false, NULL); |
| 50 | winEventNotifier = 0; |
| 51 | bytesToWriteLock = new QReadWriteLock; |
| 52 | } |
| 53 | |
| 54 | void QextSerialPortPrivate::platformSpecificDestruct() { |
| 55 | CloseHandle(overlap.hEvent); |
| 56 | delete bytesToWriteLock; |
| 57 | } |
| 58 | |
| 59 | |
| 60 | /*! |
| 61 | \internal |
| 62 | COM ports greater than 9 need \\.\ prepended |
| 63 | |
| 64 | This is only need when open the port. |
| 65 | */ |
| 66 | static QString fullPortNameWin(const QString &name) |
| 67 | { |
| 68 | QRegExp rx(QLatin1String("^COM(\\d+)")); |
| 69 | QString fullName(name); |
| 70 | if (fullName.contains(rx)) |
| 71 | fullName.prepend(QLatin1String("\\\\.\\")); |
| 72 | return fullName; |
| 73 | } |
| 74 | |
| 75 | bool QextSerialPortPrivate::open_sys(QIODevice::OpenMode mode) |
| 76 | { |
| 77 | Q_Q(QextSerialPort); |
| 78 | DWORD confSize = sizeof(COMMCONFIG); |
| 79 | commConfig.dwSize = confSize; |
| 80 | DWORD dwFlagsAndAttributes = 0; |
| 81 | if (queryMode == QextSerialPort::EventDriven) |
| 82 | dwFlagsAndAttributes += FILE_FLAG_OVERLAPPED; |
| 83 | |
| 84 | /*open the port*/ |
| 85 | handle = CreateFileW((wchar_t *)fullPortNameWin(port).utf16(), GENERIC_READ|GENERIC_WRITE, |
| 86 | 0, NULL, OPEN_EXISTING, dwFlagsAndAttributes, NULL); |
| 87 | if (handle != INVALID_HANDLE_VALUE) { |
| 88 | q->setOpenMode(mode); |
| 89 | /*configure port settings*/ |
| 90 | GetCommConfig(handle, &commConfig, &confSize); |
| 91 | GetCommState(handle, &(commConfig.dcb)); |
| 92 | |
| 93 | /*set up parameters*/ |
| 94 | commConfig.dcb.fBinary = TRUE; |
| 95 | commConfig.dcb.fInX = FALSE; |
| 96 | commConfig.dcb.fOutX = FALSE; |
| 97 | commConfig.dcb.fAbortOnError = FALSE; |
| 98 | commConfig.dcb.fNull = FALSE; |
| 99 | /* Dtr default to true. See Issue 122*/ |
| 100 | commConfig.dcb.fDtrControl = TRUE; |
| 101 | /*flush all settings*/ |
| 102 | settingsDirtyFlags = DFE_ALL; |
| 103 | updatePortSettings(); |
| 104 | |
| 105 | //init event driven approach |
| 106 | if (queryMode == QextSerialPort::EventDriven) { |
| 107 | if (!SetCommMask(handle, EV_TXEMPTY | EV_RXCHAR | EV_DSR)) { |
| 108 | QESP_WARNING()<<"failed to set Comm Mask. Error code:"<<GetLastError(); |
| 109 | return false; |
| 110 | } |
| 111 | winEventNotifier = new QWinEventNotifier(overlap.hEvent, q); |
| 112 | qRegisterMetaType<HANDLE>("HANDLE"); |
| 113 | q->connect(winEventNotifier, SIGNAL(activated(HANDLE)), q, SLOT(_q_onWinEvent(HANDLE)), Qt::DirectConnection); |
| 114 | WaitCommEvent(handle, &eventMask, &overlap); |
| 115 | } |
| 116 | return true; |
| 117 | } |
| 118 | return false; |
| 119 | } |
| 120 | |
| 121 | bool QextSerialPortPrivate::close_sys() |
| 122 | { |
| 123 | flush_sys(); |
| 124 | CancelIo(handle); |
| 125 | if (CloseHandle(handle)) |
| 126 | handle = INVALID_HANDLE_VALUE; |
| 127 | if (winEventNotifier) { |
| 128 | winEventNotifier->setEnabled(false); |
| 129 | winEventNotifier->deleteLater(); |
| 130 | winEventNotifier = 0; |
| 131 | } |
| 132 | |
| 133 | foreach (OVERLAPPED *o, pendingWrites) { |
| 134 | CloseHandle(o->hEvent); |
| 135 | delete o; |
| 136 | } |
| 137 | pendingWrites.clear(); |
| 138 | return true; |
| 139 | } |
| 140 | |
| 141 | bool QextSerialPortPrivate::flush_sys() |
| 142 | { |
| 143 | FlushFileBuffers(handle); |
| 144 | return true; |
| 145 | } |
| 146 | |
| 147 | qint64 QextSerialPortPrivate::bytesAvailable_sys() const |
| 148 | { |
| 149 | DWORD Errors; |
| 150 | COMSTAT Status; |
| 151 | if (ClearCommError(handle, &Errors, &Status)) { |
| 152 | return Status.cbInQue; |
| 153 | } |
| 154 | return (qint64)-1; |
| 155 | } |
| 156 | |
| 157 | /* |
| 158 | Translates a system-specific error code to a QextSerialPort error code. Used internally. |
| 159 | */ |
| 160 | void QextSerialPortPrivate::translateError(ulong error) |
| 161 | { |
| 162 | if (error & CE_BREAK) { |
| 163 | lastErr = E_BREAK_CONDITION; |
| 164 | } |
| 165 | else if (error & CE_FRAME) { |
| 166 | lastErr = E_FRAMING_ERROR; |
| 167 | } |
| 168 | else if (error & CE_IOE) { |
| 169 | lastErr = E_IO_ERROR; |
| 170 | } |
| 171 | else if (error & CE_MODE) { |
| 172 | lastErr = E_INVALID_FD; |
| 173 | } |
| 174 | else if (error & CE_OVERRUN) { |
| 175 | lastErr = E_BUFFER_OVERRUN; |
| 176 | } |
| 177 | else if (error & CE_RXPARITY) { |
| 178 | lastErr = E_RECEIVE_PARITY_ERROR; |
| 179 | } |
| 180 | else if (error & CE_RXOVER) { |
| 181 | lastErr = E_RECEIVE_OVERFLOW; |
| 182 | } |
| 183 | else if (error & CE_TXFULL) { |
| 184 | lastErr = E_TRANSMIT_OVERFLOW; |
| 185 | } |
| 186 | } |
| 187 | |
| 188 | /* |
| 189 | Reads a block of data from the serial port. This function will read at most maxlen bytes from |
| 190 | the serial port and place them in the buffer pointed to by data. Return value is the number of |
| 191 | bytes actually read, or -1 on error. |
| 192 | |
| 193 | \warning before calling this function ensure that serial port associated with this class |
| 194 | is currently open (use isOpen() function to check if port is open). |
| 195 | */ |
| 196 | qint64 QextSerialPortPrivate::readData_sys(char *data, qint64 maxSize) |
| 197 | { |
| 198 | DWORD bytesRead = 0; |
| 199 | bool failed = false; |
| 200 | if (queryMode == QextSerialPort::EventDriven) { |
| 201 | OVERLAPPED overlapRead; |
| 202 | ZeroMemory(&overlapRead, sizeof(OVERLAPPED)); |
| 203 | if (!ReadFile(handle, (void *)data, (DWORD)maxSize, &bytesRead, &overlapRead)) { |
| 204 | if (GetLastError() == ERROR_IO_PENDING) |
| 205 | GetOverlappedResult(handle, &overlapRead, &bytesRead, true); |
| 206 | else |
| 207 | failed = true; |
| 208 | } |
| 209 | } else if (!ReadFile(handle, (void *)data, (DWORD)maxSize, &bytesRead, NULL)) { |
| 210 | failed = true; |
| 211 | } |
| 212 | if (!failed) |
| 213 | return (qint64)bytesRead; |
| 214 | |
| 215 | lastErr = E_READ_FAILED; |
| 216 | return -1; |
| 217 | } |
| 218 | |
| 219 | /* |
| 220 | Writes a block of data to the serial port. This function will write len bytes |
| 221 | from the buffer pointed to by data to the serial port. Return value is the number |
| 222 | of bytes actually written, or -1 on error. |
| 223 | |
| 224 | \warning before calling this function ensure that serial port associated with this class |
| 225 | is currently open (use isOpen() function to check if port is open). |
| 226 | */ |
| 227 | qint64 QextSerialPortPrivate::writeData_sys(const char *data, qint64 maxSize) |
| 228 | { |
| 229 | DWORD bytesWritten = 0; |
| 230 | bool failed = false; |
| 231 | if (queryMode == QextSerialPort::EventDriven) { |
| 232 | OVERLAPPED *newOverlapWrite = new OVERLAPPED; |
| 233 | ZeroMemory(newOverlapWrite, sizeof(OVERLAPPED)); |
| 234 | newOverlapWrite->hEvent = CreateEvent(NULL, true, false, NULL); |
| 235 | if (WriteFile(handle, (void *)data, (DWORD)maxSize, &bytesWritten, newOverlapWrite)) { |
| 236 | CloseHandle(newOverlapWrite->hEvent); |
| 237 | delete newOverlapWrite; |
| 238 | } |
| 239 | else if (GetLastError() == ERROR_IO_PENDING) { |
| 240 | // writing asynchronously...not an error |
| 241 | QWriteLocker writelocker(bytesToWriteLock); |
| 242 | pendingWrites.append(newOverlapWrite); |
| 243 | } |
| 244 | else { |
| 245 | QESP_WARNING()<<"QextSerialPort write error:"<<GetLastError(); |
| 246 | failed = true; |
| 247 | if (!CancelIo(newOverlapWrite->hEvent)) |
| 248 | QESP_WARNING("QextSerialPort: couldn't cancel IO"); |
| 249 | if (!CloseHandle(newOverlapWrite->hEvent)) |
| 250 | QESP_WARNING("QextSerialPort: couldn't close OVERLAPPED handle"); |
| 251 | delete newOverlapWrite; |
| 252 | } |
| 253 | } else if (!WriteFile(handle, (void *)data, (DWORD)maxSize, &bytesWritten, NULL)) { |
| 254 | failed = true; |
| 255 | } |
| 256 | |
| 257 | if (!failed) |
| 258 | return (qint64)bytesWritten; |
| 259 | |
| 260 | lastErr = E_WRITE_FAILED; |
| 261 | return -1; |
| 262 | } |
| 263 | |
| 264 | void QextSerialPortPrivate::setDtr_sys(bool set) { |
| 265 | EscapeCommFunction(handle, set ? SETDTR : CLRDTR); |
| 266 | } |
| 267 | |
| 268 | void QextSerialPortPrivate::setRts_sys(bool set) { |
| 269 | EscapeCommFunction(handle, set ? SETRTS : CLRRTS); |
| 270 | } |
| 271 | |
| 272 | ulong QextSerialPortPrivate::lineStatus_sys(void) { |
| 273 | unsigned long Status = 0, Temp = 0; |
| 274 | GetCommModemStatus(handle, &Temp); |
| 275 | if (Temp & MS_CTS_ON) Status |= LS_CTS; |
| 276 | if (Temp & MS_DSR_ON) Status |= LS_DSR; |
| 277 | if (Temp & MS_RING_ON) Status |= LS_RI; |
| 278 | if (Temp & MS_RLSD_ON) Status |= LS_DCD; |
| 279 | return Status; |
| 280 | } |
| 281 | |
| 282 | /* |
| 283 | Triggered when there's activity on our HANDLE. |
| 284 | */ |
| 285 | void QextSerialPortPrivate::_q_onWinEvent(HANDLE h) |
| 286 | { |
| 287 | Q_Q(QextSerialPort); |
| 288 | if (h == overlap.hEvent) { |
| 289 | if (eventMask & EV_RXCHAR) { |
| 290 | if (q->sender() != q && bytesAvailable_sys() > 0) |
| 291 | _q_canRead(); |
| 292 | } |
| 293 | if (eventMask & EV_TXEMPTY) { |
| 294 | /* |
| 295 | A write completed. Run through the list of OVERLAPPED writes, and if |
| 296 | they completed successfully, take them off the list and delete them. |
| 297 | Otherwise, leave them on there so they can finish. |
| 298 | */ |
| 299 | qint64 totalBytesWritten = 0; |
| 300 | QList<OVERLAPPED *> overlapsToDelete; |
| 301 | foreach (OVERLAPPED *o, pendingWrites) { |
| 302 | DWORD numBytes = 0; |
| 303 | if (GetOverlappedResult(handle, o, &numBytes, false)) { |
| 304 | overlapsToDelete.append(o); |
| 305 | totalBytesWritten += numBytes; |
| 306 | } else if (GetLastError() != ERROR_IO_INCOMPLETE) { |
| 307 | overlapsToDelete.append(o); |
| 308 | QESP_WARNING()<<"CommEvent overlapped write error:" << GetLastError(); |
| 309 | } |
| 310 | } |
| 311 | |
| 312 | if (q->sender() != q && totalBytesWritten > 0) { |
| 313 | QWriteLocker writelocker(bytesToWriteLock); |
| 314 | Q_EMIT q->bytesWritten(totalBytesWritten); |
| 315 | } |
| 316 | |
| 317 | foreach (OVERLAPPED *o, overlapsToDelete) { |
| 318 | OVERLAPPED *toDelete = pendingWrites.takeAt(pendingWrites.indexOf(o)); |
| 319 | CloseHandle(toDelete->hEvent); |
| 320 | delete toDelete; |
| 321 | } |
| 322 | } |
| 323 | if (eventMask & EV_DSR) { |
| 324 | if (lineStatus_sys() & LS_DSR) |
| 325 | Q_EMIT q->dsrChanged(true); |
| 326 | else |
| 327 | Q_EMIT q->dsrChanged(false); |
| 328 | } |
| 329 | } |
| 330 | WaitCommEvent(handle, &eventMask, &overlap); |
| 331 | } |
| 332 | |
| 333 | void QextSerialPortPrivate::updatePortSettings() |
| 334 | { |
| 335 | if (!q_ptr->isOpen() || !settingsDirtyFlags) |
| 336 | return; |
| 337 | |
| 338 | //fill struct : COMMCONFIG |
| 339 | if (settingsDirtyFlags & DFE_BaudRate) { |
| 340 | commConfig.dcb.BaudRate = settings.BaudRate; |
| 341 | } |
| 342 | if (settingsDirtyFlags & DFE_Parity) { |
| 343 | commConfig.dcb.Parity = (BYTE)settings.Parity; |
| 344 | commConfig.dcb.fParity = (settings.Parity == PAR_NONE) ? FALSE : TRUE; |
| 345 | } |
| 346 | if (settingsDirtyFlags & DFE_DataBits) { |
| 347 | commConfig.dcb.ByteSize = (BYTE)settings.DataBits; |
| 348 | } |
| 349 | if (settingsDirtyFlags & DFE_StopBits) { |
| 350 | switch (settings.StopBits) { |
| 351 | case STOP_1: |
| 352 | commConfig.dcb.StopBits = ONESTOPBIT; |
| 353 | break; |
| 354 | case STOP_1_5: |
| 355 | commConfig.dcb.StopBits = ONE5STOPBITS; |
| 356 | break; |
| 357 | case STOP_2: |
| 358 | commConfig.dcb.StopBits = TWOSTOPBITS; |
| 359 | break; |
| 360 | } |
| 361 | } |
| 362 | if (settingsDirtyFlags & DFE_Flow) { |
| 363 | switch(settings.FlowControl) { |
| 364 | /*no flow control*/ |
| 365 | case FLOW_OFF: |
| 366 | commConfig.dcb.fOutxCtsFlow = FALSE; |
| 367 | commConfig.dcb.fRtsControl = RTS_CONTROL_DISABLE; |
| 368 | commConfig.dcb.fInX = FALSE; |
| 369 | commConfig.dcb.fOutX = FALSE; |
| 370 | break; |
| 371 | /*software (XON/XOFF) flow control*/ |
| 372 | case FLOW_XONXOFF: |
| 373 | commConfig.dcb.fOutxCtsFlow = FALSE; |
| 374 | commConfig.dcb.fRtsControl = RTS_CONTROL_DISABLE; |
| 375 | commConfig.dcb.fInX = TRUE; |
| 376 | commConfig.dcb.fOutX = TRUE; |
| 377 | break; |
| 378 | /*hardware flow control*/ |
| 379 | case FLOW_HARDWARE: |
| 380 | commConfig.dcb.fOutxCtsFlow = TRUE; |
| 381 | commConfig.dcb.fRtsControl = RTS_CONTROL_HANDSHAKE; |
| 382 | commConfig.dcb.fInX = FALSE; |
| 383 | commConfig.dcb.fOutX = FALSE; |
| 384 | break; |
| 385 | } |
| 386 | } |
| 387 | |
| 388 | //fill struct : COMMTIMEOUTS |
| 389 | if (settingsDirtyFlags & DFE_TimeOut) { |
| 390 | if (queryMode != QextSerialPort::EventDriven) { |
| 391 | int millisec = settings.Timeout_Millisec; |
| 392 | if (millisec == -1) { |
| 393 | commTimeouts.ReadIntervalTimeout = MAXDWORD; |
| 394 | commTimeouts.ReadTotalTimeoutConstant = 0; |
| 395 | } else { |
| 396 | commTimeouts.ReadIntervalTimeout = millisec; |
| 397 | commTimeouts.ReadTotalTimeoutConstant = millisec; |
| 398 | } |
| 399 | commTimeouts.ReadTotalTimeoutMultiplier = 0; |
| 400 | commTimeouts.WriteTotalTimeoutMultiplier = millisec; |
| 401 | commTimeouts.WriteTotalTimeoutConstant = 0; |
| 402 | } |
| 403 | else { |
| 404 | commTimeouts.ReadIntervalTimeout = MAXDWORD; |
| 405 | commTimeouts.ReadTotalTimeoutMultiplier = 0; |
| 406 | commTimeouts.ReadTotalTimeoutConstant = 0; |
| 407 | commTimeouts.WriteTotalTimeoutMultiplier = 0; |
| 408 | commTimeouts.WriteTotalTimeoutConstant = 0; |
| 409 | } |
| 410 | } |
| 411 | |
| 412 | |
| 413 | if (settingsDirtyFlags & DFE_Settings_Mask) |
| 414 | SetCommConfig(handle, &commConfig, sizeof(COMMCONFIG)); |
| 415 | if ((settingsDirtyFlags & DFE_TimeOut)) |
| 416 | SetCommTimeouts(handle, &commTimeouts); |
| 417 | settingsDirtyFlags = 0; |
| 418 | } |