commdcbhelper.cpp 23.4 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
/*
 * 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 "commdcbhelper.h"

25 26 27 28 29 30 31 32
/* glue for unsupported windows speeds */

#define CBR_230400	230400
#define CBR_460800	460800
#define CBR_500000	500000
#define CBR_576000	576000
#define CBR_921600	921600

James Goppert's avatar
James Goppert committed
33 34 35 36 37 38
namespace TNX {

/*!
  Constructs a CommDCBHelper object with the given \a file handle.
*/
CommDCBHelper::CommDCBHelper(HANDLE fileHandle)
39
    : fileHandle_(fileHandle), originalAttrs_(NULL), currentAttrs_(NULL)
James Goppert's avatar
James Goppert committed
40
{
41 42 43 44
    Q_ASSERT(fileHandle_ > 0);

    originalAttrs_ = new DCB();
    currentAttrs_ = new DCB();
James Goppert's avatar
James Goppert committed
45

46 47
    // save the current serial port attributes
    // see restoreDCB()
James Goppert's avatar
James Goppert committed
48

49
    saveDCB();
James Goppert's avatar
James Goppert committed
50
    
51
    // clone the original attributes
James Goppert's avatar
James Goppert committed
52

53
    *currentAttrs_ = *originalAttrs_;
James Goppert's avatar
James Goppert committed
54

55
    // initialize port attributes for serial port communication
James Goppert's avatar
James Goppert committed
56

57
    initDCB();
James Goppert's avatar
James Goppert committed
58 59 60 61 62
}


CommDCBHelper::~CommDCBHelper()
{
63 64
    // It is good practice to reset a serial port back to the state in
    // which you found it. This is why we saved the original DCB struct
James Goppert's avatar
James Goppert committed
65

66 67 68 69
    restoreDCB();

    delete originalAttrs_;
    delete currentAttrs_;
James Goppert's avatar
James Goppert committed
70 71 72 73 74 75 76
}

/*!
   Sets the DCB structure.
 */
bool CommDCBHelper::applyChanges(ChangeApplyTypes apptype)
{
77 78 79 80 81 82 83 84
    if ( apptype == PortAttrOnlyAppTy || apptype == AllAppTy ) {
        if ( !SetCommState(fileHandle_, currentAttrs_) ) {
            qDebug() << QString("CommDCBHelper::applyChanges(file: %1, PortAttributes) failed: %2(Err #%3)")
                        .arg((quintptr)fileHandle_)
                        .arg(errorText(GetLastError()))
                        .arg(GetLastError());
            return false;
        }
James Goppert's avatar
James Goppert committed
85 86
    }

87
    // Communication Timeouts
James Goppert's avatar
James Goppert committed
88

89 90 91 92 93 94 95 96
    if ( apptype == CommTimeoutsOnlyAppTy || apptype == AllAppTy ) {
        if ( !SetCommTimeouts(fileHandle_, &commTimeouts_) ) {
            qDebug() << QString("CommDCBHelper::applyChanges(file: %1, CommTimeouts) failed: %2(Err #%3)")
                        .arg((quintptr)fileHandle_)
                        .arg(errorText(GetLastError()))
                        .arg(GetLastError());
            return false;
        }
James Goppert's avatar
James Goppert committed
97 98
    }

99
    return true;
James Goppert's avatar
James Goppert committed
100 101 102 103 104 105 106
}

/*!

 */
bool CommDCBHelper::setCtrSignal(ControlSignals csig, bool value)
{
107
    DWORD sig;
James Goppert's avatar
James Goppert committed
108

109
    switch ( csig ) {
James Goppert's avatar
James Goppert committed
110
    case CSIGNAL_RTS:
111 112
        sig = value ? SETRTS : CLRRTS;
        break;
James Goppert's avatar
James Goppert committed
113 114

    case CSIGNAL_DTR:
115 116
        sig = value ? SETDTR : CLRDTR;
        break;
James Goppert's avatar
James Goppert committed
117 118

    default:
119
        qDebug() << QString("CommDCBHelper::setCtrSignal(file: %1, csig: %2) failed." \
James Goppert's avatar
James Goppert committed
120
                            "Given signal is read only.")
121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136
                    .arg((quintptr)fileHandle_)
                    .arg(csig);
        return false;
    }

    if ( !EscapeCommFunction(fileHandle_, sig) ) {
        qDebug() <<  QString("CommDCBHelper::setCtrSignal(file: %1, csig: %2) failed" \
                             "when fetching control signal values : %3(Err #%4)")
                     .arg((quintptr)fileHandle_)
                     .arg(csig)
                     .arg(errorText(GetLastError()))
                     .arg(GetLastError());
        return false;
    }

    return true;
James Goppert's avatar
James Goppert committed
137 138 139 140 141 142 143
}

/*!

 */
QSerialPort::CommSignalValues CommDCBHelper::ctrSignal(ControlSignals csig) const
{
144 145 146 147 148 149 150 151 152 153 154 155 156 157
    DWORD status = 0;

    if ( !GetCommModemStatus(fileHandle_, &status) ) {
        qDebug() << QString("CommDCBHelper::ctrSignal(file: %1, csig: %2) failed" \
                            "when fetching control signal values : %3(Err #%4)")
                    .arg((quintptr)fileHandle_)
                    .arg(csig)
                    .arg(errorText(GetLastError()))
                    .arg(GetLastError());
        return QSerialPort::Signal_Unknown;
    }

    DWORD sig;
    switch ( csig ) {
James Goppert's avatar
James Goppert committed
158
    case CSIGNAL_CTS:
159 160
        sig = MS_CTS_ON;
        break;
James Goppert's avatar
James Goppert committed
161 162

    case CSIGNAL_DSR:
163 164
        sig = MS_DSR_ON;
        break;
James Goppert's avatar
James Goppert committed
165 166

    case CSIGNAL_DCD:
167 168
        sig = MS_RLSD_ON;
        break;
James Goppert's avatar
James Goppert committed
169 170

    case CSIGNAL_RNG:
171 172
        sig = MS_RING_ON;
        break;
James Goppert's avatar
James Goppert committed
173 174

    default:
175
        qDebug() << QString("CommDCBHelper::ctrSignal(file: %1, csig: %2) failed." \
James Goppert's avatar
James Goppert committed
176
                            "Invalid signal.")
177 178 179 180
                    .arg((quintptr)fileHandle_)
                    .arg(csig);
        return QSerialPort::Signal_Unknown;
    }
James Goppert's avatar
James Goppert committed
181

182
    return ((status & sig) ? QSerialPort::Signal_On : QSerialPort::Signal_Off);
James Goppert's avatar
James Goppert committed
183 184 185 186 187 188 189
}

/*!

 */
void CommDCBHelper::initDCB()
{   
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
    currentAttrs_->DCBlength          = sizeof(DCB);

    currentAttrs_->EvtChar            =   '\0';
    currentAttrs_->EofChar            =   '\0';
    currentAttrs_->ErrorChar          =   '\0';
    currentAttrs_->XonChar            =   '\0';
    currentAttrs_->XoffChar           =   '\0';
    currentAttrs_->fDtrControl        =   DTR_CONTROL_DISABLE;
    currentAttrs_->fRtsControl        =   RTS_CONTROL_DISABLE;
    currentAttrs_->fOutxCtsFlow       =   0;
    currentAttrs_->fOutxDsrFlow       =   0;
    currentAttrs_->fDsrSensitivity    =   0;
    currentAttrs_->fOutX              =   0;
    currentAttrs_->fInX               =   0;
    currentAttrs_->fTXContinueOnXoff  =   0;
    currentAttrs_->fErrorChar         =   0;
    currentAttrs_->XonLim             =   0;
    currentAttrs_->XoffLim            =   0;
    currentAttrs_->fBinary            =   1;
    currentAttrs_->fNull              =   0;

    // If a communications port has been set up with a TRUE value for the fAbortOnError member
    // of the setup DCB structure, the communications software will terminate all read and write
    // operations on the communications port when a communications error occurs. No new read or write
    // operations will be accepted until the application acknowledges the communications error by
    // calling the ClearCommError function.

    currentAttrs_->fAbortOnError      =   0;
    currentAttrs_->BaudRate           =   CBR_9600;
    currentAttrs_->fParity            =   0;
    currentAttrs_->Parity             =   0;
    currentAttrs_->StopBits           =   0;
    currentAttrs_->ByteSize           =   8;

    // ensure the new attributes take effect immediately

    applyChanges(AllAppTy);
James Goppert's avatar
James Goppert committed
227 228 229 230 231 232 233
}

/*!

*/
void CommDCBHelper::saveDCB()
{
234 235 236 237 238 239 240 241 242
    // get the current serial port attributes

    if ( !GetCommState(fileHandle_, originalAttrs_) ) {
        qDebug() << QString("CommDCBHelper::saveDCB(file: %1) failed when" \
                            " getting original port attributes: %2(Err #%3)")
                    .arg((quintptr)fileHandle_)
                    .arg(errorText(GetLastError()))
                    .arg(GetLastError());
    }
James Goppert's avatar
James Goppert committed
243 244 245 246 247 248 249
}

/*!

*/
bool CommDCBHelper::getCommTimeouts()
{
250 251 252 253 254 255 256 257 258 259 260
    // get the current communication timeouts

    if ( !GetCommTimeouts(fileHandle_, &commTimeouts_) ) {
        qDebug() << QString("CommDCBHelper::getCommTimeouts(file: %1) failed when" \
                            " getting communication timeout values: %2(Err #%3)")
                    .arg((quintptr)fileHandle_)
                    .arg(errorText(GetLastError()))
                    .arg(GetLastError());
        return false;
    }
    return true;
James Goppert's avatar
James Goppert committed
261 262 263 264 265 266 267
}

/*!

*/
void CommDCBHelper::restoreDCB()
{
268 269 270 271 272 273 274
    if ( !originalAttrs_ || !SetCommState(fileHandle_, originalAttrs_) ) {
        qDebug() << QString("CommDCBHelper::restoreDCB(file: %1) failed when resetting " \
                            "serial port attributes: %2(Err #%3)")
                    .arg((quintptr)fileHandle_)
                    .arg(errorText(GetLastError()))
                    .arg(GetLastError());
    }
James Goppert's avatar
James Goppert committed
275 276 277 278 279 280 281
}

/*!

*/
void CommDCBHelper::setBaudRate(QPortSettings::BaudRate baudRate)
{
282
    DWORD baud = CBR_9600;
James Goppert's avatar
James Goppert committed
283

284
    switch ( baudRate ) {
James Goppert's avatar
James Goppert committed
285
    case QPortSettings::BAUDR_110:
286 287
        baud = CBR_110;
        break;
James Goppert's avatar
James Goppert committed
288
    case QPortSettings::BAUDR_300:
289 290
        baud = CBR_300;
        break;
James Goppert's avatar
James Goppert committed
291
    case QPortSettings::BAUDR_600:
292 293
        baud = CBR_600;
        break;
James Goppert's avatar
James Goppert committed
294
    case QPortSettings::BAUDR_1200:
295 296
        baud = CBR_1200;
        break;
James Goppert's avatar
James Goppert committed
297
    case QPortSettings::BAUDR_2400:
298 299
        baud = CBR_2400;
        break;
James Goppert's avatar
James Goppert committed
300
    case QPortSettings::BAUDR_4800:
301 302
        baud = CBR_4800;
        break;
James Goppert's avatar
James Goppert committed
303
    case QPortSettings::BAUDR_9600:
304 305
        baud = CBR_9600;
        break;
James Goppert's avatar
James Goppert committed
306
    case QPortSettings::BAUDR_14400:
307 308
        baud = CBR_14400;
        break;
James Goppert's avatar
James Goppert committed
309
    case QPortSettings::BAUDR_19200:
310 311
        baud = CBR_19200;
        break;
James Goppert's avatar
James Goppert committed
312
    case QPortSettings::BAUDR_38400:
313 314
        baud = CBR_38400;
        break;
James Goppert's avatar
James Goppert committed
315
    case QPortSettings::BAUDR_56000:
316 317
        baud = CBR_56000;
        break;
James Goppert's avatar
James Goppert committed
318
    case QPortSettings::BAUDR_57600:
319 320
        baud = CBR_57600;
        break;
James Goppert's avatar
James Goppert committed
321
    case QPortSettings::BAUDR_115200:
322 323
        baud = CBR_115200;
        break;
James Goppert's avatar
James Goppert committed
324
    case QPortSettings::BAUDR_128000:
325 326 327 328 329
        baud = CBR_128000;
        break;
    case QPortSettings::BAUDR_230400:
        baud = CBR_230400;
        break;
James Goppert's avatar
James Goppert committed
330
    case QPortSettings::BAUDR_256000:
331 332 333 334 335 336 337 338 339 340 341 342 343 344
        baud = CBR_256000;
        break;
    case QPortSettings::BAUDR_460800:
        baud = CBR_460800;
        break;
    case QPortSettings::BAUDR_500000:
        baud = CBR_500000;
        break;
    case QPortSettings::BAUDR_576000:
        baud = CBR_576000;
        break;
    case QPortSettings::BAUDR_921600:
        baud = CBR_921600;
        break;
James Goppert's avatar
James Goppert committed
345
    default:
346 347 348 349
        qWarning() << "CommDCBHelper::setBaudRate(" << baudRate << "): " \
                      "Unsupported baud rate";
    }
    currentAttrs_->BaudRate = baud;
James Goppert's avatar
James Goppert committed
350 351 352 353 354 355 356
}

/*!

*/
QPortSettings::BaudRate CommDCBHelper::baudRate() const
{
357 358 359 360 361 362 363 364 365 366 367 368
    DWORD baud;
    DCB dcb;

    // although we store the last value of the baud rate attribute in currentAttrs_ structure,
    // it is better practice to request the actual value from the OS.

    if ( !GetCommState(fileHandle_, &dcb) ) {
        qDebug() << QString("CommDCBHelper::baudRate(file: %1) failed when" \
                            " getting baud rate: %2(Err #%3)")
                    .arg((quintptr)fileHandle_)
                    .arg(errorText(GetLastError()))
                    .arg(GetLastError());
James Goppert's avatar
James Goppert committed
369

370 371 372 373 374
        baud = currentAttrs_->BaudRate;
    }
    else {
        baud = dcb.BaudRate;
    }
James Goppert's avatar
James Goppert committed
375 376 377



378
    Q_ASSERT(currentAttrs_->BaudRate == baud);
James Goppert's avatar
James Goppert committed
379

380
    switch ( baud ) {
381
    case CBR_110:
382
        return QPortSettings::BAUDR_110;
383
    case CBR_300:
384
        return QPortSettings::BAUDR_300;
385
    case CBR_600:
386
        return QPortSettings::BAUDR_600;
387
    case CBR_1200:
388
        return QPortSettings::BAUDR_1200;
389
    case CBR_2400:
390
        return QPortSettings::BAUDR_2400;
391
    case CBR_4800:
392
        return QPortSettings::BAUDR_4800;
393
    case CBR_9600:
394
        return QPortSettings::BAUDR_9600;
395
    case CBR_14400:
396
        return QPortSettings::BAUDR_14400;
397
    case CBR_19200:
398
        return QPortSettings::BAUDR_19200;
399
    case CBR_38400:
400
        return QPortSettings::BAUDR_38400;
401
    case CBR_56000:
402
        return QPortSettings::BAUDR_56000;
403
    case CBR_57600:
404
        return QPortSettings::BAUDR_57600;
405
    case CBR_115200:
406
        return QPortSettings::BAUDR_115200;
407
    case CBR_128000:
408 409 410
        return QPortSettings::BAUDR_128000;
    case CBR_230400:
        return QPortSettings::BAUDR_230400;
411
    case CBR_256000:
412 413 414 415 416 417 418
        return QPortSettings::BAUDR_256000;
    case CBR_500000:
        return QPortSettings::BAUDR_500000;
    case CBR_576000:
        return QPortSettings::BAUDR_57600;
    case CBR_921600:
        return QPortSettings::BAUDR_921600;
419
    default:
420 421
        qWarning() << "CommDCBHelper::baudRate(): Unknown baud rate";
    }
James Goppert's avatar
James Goppert committed
422

423
    return QPortSettings::BAUDR_UNKNOWN;
James Goppert's avatar
James Goppert committed
424 425 426 427 428 429 430
}

/*!

*/
QPortSettings::DataBits CommDCBHelper::dataBits() const
{
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
    DCB dcb;
    BYTE dataBits;

    // get the current serial port attributes

    if ( !GetCommState(fileHandle_, &dcb) ) {
        qDebug() << QString("CommDCBHelper::dataBits(file: %1) failed when" \
                            " getting original port attributes: %2(Err #%3)")
                    .arg((quintptr)fileHandle_)
                    .arg(errorText(GetLastError()))
                    .arg(GetLastError());

        dataBits = currentAttrs_->ByteSize;
    }
    else {
        dataBits = dcb.ByteSize;
    }

    Q_ASSERT(currentAttrs_->ByteSize == dataBits);

    if ( dataBits == 5 )
        return QPortSettings::DB_5;
    else if ( dataBits == 6 )
        return QPortSettings::DB_6;
    else if ( dataBits == 7 )
        return QPortSettings::DB_7;
    else if ( dataBits == 8 )
        return QPortSettings::DB_8;
    else
        return QPortSettings::DB_UNKNOWN;
James Goppert's avatar
James Goppert committed
461 462 463 464 465 466 467
}

/*!

*/
void CommDCBHelper::setDataBits(QPortSettings::DataBits dataBits)
{
468
    switch( dataBits ) {
James Goppert's avatar
James Goppert committed
469 470
    /*5 data bits*/
    case QPortSettings::DB_5:
471 472
        currentAttrs_->ByteSize = 5;
        break;
James Goppert's avatar
James Goppert committed
473

474
        /*6 data bits*/
James Goppert's avatar
James Goppert committed
475
    case QPortSettings::DB_6:
476 477
        currentAttrs_->ByteSize = 6;
        break;
James Goppert's avatar
James Goppert committed
478

479
        /*7 data bits*/
James Goppert's avatar
James Goppert committed
480
    case QPortSettings::DB_7:
481 482
        currentAttrs_->ByteSize = 7;
        break;
James Goppert's avatar
James Goppert committed
483

484
        /*8 data bits*/
James Goppert's avatar
James Goppert committed
485
    case QPortSettings::DB_8:
486 487
        currentAttrs_->ByteSize = 8;
        break;
James Goppert's avatar
James Goppert committed
488 489

    default:
490 491 492
        currentAttrs_->ByteSize = 8;
        qWarning() << "CommDCBHelper::setDataBits(enum[" << dataBits << "]): Unsupported data bits";
    }
James Goppert's avatar
James Goppert committed
493 494 495 496 497 498 499
}

/*!

 */
QPortSettings::Parity CommDCBHelper::parity() const
{
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
    DCB dcb;
    BYTE parity;
    DWORD fParity;

    // get the current serial port attributes

    if ( !GetCommState(fileHandle_, &dcb) ) {
        qDebug() << QString("CommDCBHelper::parity(file: %1) failed when" \
                            " getting original port attributes: %2(Err #%3)")
                    .arg((quintptr)fileHandle_)
                    .arg(errorText(GetLastError()))
                    .arg(GetLastError());

        fParity = currentAttrs_->fParity;
        parity = currentAttrs_->Parity;
    }
    else {
        fParity = dcb.fParity;
        parity = dcb.Parity;
    }

    // For some reason windows keep changing fParity value even Parity field is set
    // something other than 0 (no parity)

    //Q_ASSERT(currentAttrs_->fParity == fParity && currentAttrs_->Parity == parity);

    //if ( fParity != 1 ) {
    //  return QPortSettings::PAR_NONE;
    //}
    //else {
James Goppert's avatar
James Goppert committed
530
    if ( parity == 0 )
531
        return QPortSettings::PAR_NONE;
James Goppert's avatar
James Goppert committed
532
    else if ( parity == 1 )
533
        return QPortSettings::PAR_ODD;
James Goppert's avatar
James Goppert committed
534
    else if ( parity == 2 )
535
        return QPortSettings::PAR_EVEN;
James Goppert's avatar
James Goppert committed
536
    else if ( parity == 3 )
537
        return QPortSettings::PAR_MARK;
James Goppert's avatar
James Goppert committed
538
    else if ( parity == 4 )
539
        return QPortSettings::PAR_SPACE;
James Goppert's avatar
James Goppert committed
540
    else
541 542
        return QPortSettings::PAR_UNKNOWN;
    //}
James Goppert's avatar
James Goppert committed
543 544 545 546 547 548 549
}

/*!

*/
void CommDCBHelper::setParity(QPortSettings::Parity parity)
{
550
    switch ( parity ) {
James Goppert's avatar
James Goppert committed
551 552
    /*no parity*/
    case QPortSettings::PAR_NONE:
553 554 555
        currentAttrs_->fParity = 0;
        currentAttrs_->Parity = 0;
        break;
James Goppert's avatar
James Goppert committed
556

557
        /*odd parity*/
James Goppert's avatar
James Goppert committed
558
    case QPortSettings::PAR_ODD:
559 560 561
        currentAttrs_->fParity = 1;
        currentAttrs_->Parity = 1;
        break;
James Goppert's avatar
James Goppert committed
562

563
        /*even parity*/
James Goppert's avatar
James Goppert committed
564
    case QPortSettings::PAR_EVEN:
565 566 567
        currentAttrs_->fParity = 1;
        currentAttrs_->Parity = 2;
        break;
James Goppert's avatar
James Goppert committed
568

569
        /*mark parity*/
James Goppert's avatar
James Goppert committed
570
    case QPortSettings::PAR_MARK:
571 572 573
        currentAttrs_->fParity = 1;
        currentAttrs_->Parity = 3;
        break;
James Goppert's avatar
James Goppert committed
574

575
        /*space parity*/
James Goppert's avatar
James Goppert committed
576
    case QPortSettings::PAR_SPACE:
577 578 579 580
        currentAttrs_->fParity = 1;
        currentAttrs_->Parity = 4;
        break;

James Goppert's avatar
James Goppert committed
581
    default:
582 583 584 585
        currentAttrs_->fParity = 0;
        currentAttrs_->Parity = 0;
        qWarning() << "CommDCBHelper::setParity(enum[" << parity << "]): Unsupported parity";
    }
James Goppert's avatar
James Goppert committed
586 587 588 589 590 591 592
}

/*!

 */
QPortSettings::StopBits CommDCBHelper::stopBits() const
{
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
    DCB dcb;
    BYTE stopBits;

    // get the current serial port attributes

    if ( !GetCommState(fileHandle_, &dcb) ) {
        qDebug() << QString("CommDCBHelper::stopBits(file: %1) failed when" \
                            " getting original port attributes: %2(Err #%3)")
                    .arg((quintptr)fileHandle_)
                    .arg(errorText(GetLastError()))
                    .arg(GetLastError());

        stopBits = currentAttrs_->StopBits;
    }
    else {
        stopBits = dcb.StopBits;
    }

    Q_ASSERT(currentAttrs_->StopBits == stopBits);

    if ( stopBits == 0 )
        return QPortSettings::STOP_1;
    else if ( stopBits == 1 )
        return QPortSettings::STOP_1_5;
    else if ( stopBits == 2 )
        return QPortSettings::STOP_2;
    else
        return QPortSettings::STOP_UNKNOWN;
James Goppert's avatar
James Goppert committed
621 622 623 624 625 626 627
}

/*!

*/
void CommDCBHelper::setStopBits(QPortSettings::StopBits stopBits)
{
628
    switch( stopBits ) {
James Goppert's avatar
James Goppert committed
629 630
    /*one stop bit*/
    case QPortSettings::STOP_1:
631 632
        currentAttrs_->StopBits = 0;
        break;
James Goppert's avatar
James Goppert committed
633

634
        /*one and half bit*/
James Goppert's avatar
James Goppert committed
635
    case QPortSettings::STOP_1_5:
636 637
        currentAttrs_->StopBits = 1;
        break;
James Goppert's avatar
James Goppert committed
638

639
        /*two stop bits*/
James Goppert's avatar
James Goppert committed
640
    case QPortSettings::STOP_2:
641 642
        currentAttrs_->StopBits = 2;
        break;
James Goppert's avatar
James Goppert committed
643 644

    default:
645 646 647
        currentAttrs_->StopBits = 0;
        qWarning() << "CommDCBHelper::setStopBits(enum[" << stopBits << "]): Unsupported stop bits";
    }
James Goppert's avatar
James Goppert committed
648 649 650 651 652 653 654
}

/*!
  @return FLOW_UNKNOWN in error case
 */
QPortSettings::FlowControl CommDCBHelper::flowControl() const
{
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
    DCB dcb;

    // get the current serial port attributes.

    if ( !GetCommState(fileHandle_, &dcb) ) {
        qWarning() << QString("CommDCBHelper::flowControl(file: %1) failed when" \
                              " getting original port attributes: %2(Err #%3)")
                      .arg((quintptr)fileHandle_)
                      .arg(errorText(GetLastError()))
                      .arg(GetLastError());

        return QPortSettings::FLOW_UNKNOWN;
    }

    if ( !dcb.fOutxCtsFlow && dcb.fRtsControl == RTS_CONTROL_DISABLE ) {
        if ( dcb.fInX && dcb.fOutX )
            return QPortSettings::FLOW_XONXOFF;
        else if ( !dcb.fInX && !dcb.fOutX )
            return QPortSettings::FLOW_OFF;
        else
            return QPortSettings::FLOW_UNKNOWN;
    }
    else if ( dcb.fOutxCtsFlow && dcb.fRtsControl == RTS_CONTROL_HANDSHAKE &&
              !dcb.fInX && !dcb.fOutX ) {
        return QPortSettings::FLOW_HARDWARE;
    }
    else {
        return QPortSettings::FLOW_UNKNOWN;
    }
James Goppert's avatar
James Goppert committed
684 685 686 687 688 689 690
}

/*!

*/
void CommDCBHelper::setFlowControl(QPortSettings::FlowControl flow)
{
691
    switch( flow ) {
James Goppert's avatar
James Goppert committed
692 693
    /*no flow control*/
    case QPortSettings::FLOW_OFF:
694 695 696 697 698
        currentAttrs_->fOutxCtsFlow = false;
        currentAttrs_->fRtsControl = RTS_CONTROL_DISABLE;
        currentAttrs_->fInX = false;
        currentAttrs_->fOutX = false;
        break;
James Goppert's avatar
James Goppert committed
699

700
        /*software (XON/XOFF) flow control*/
James Goppert's avatar
James Goppert committed
701
    case QPortSettings::FLOW_XONXOFF:
702 703 704 705 706
        currentAttrs_->fOutxCtsFlow = false;
        currentAttrs_->fRtsControl = RTS_CONTROL_DISABLE;
        currentAttrs_->fInX = true;
        currentAttrs_->fOutX = true;
        break;
James Goppert's avatar
James Goppert committed
707 708

    case QPortSettings::FLOW_HARDWARE:
709 710 711 712 713
        currentAttrs_->fOutxCtsFlow = true;
        currentAttrs_->fRtsControl = RTS_CONTROL_HANDSHAKE;
        currentAttrs_->fInX = false;
        currentAttrs_->fOutX = false;
        break;
James Goppert's avatar
James Goppert committed
714 715

    default:
716 717 718 719 720 721
        currentAttrs_->fOutxCtsFlow = false;
        currentAttrs_->fRtsControl = RTS_CONTROL_DISABLE;
        currentAttrs_->fInX = false;
        currentAttrs_->fOutX = false;
        qWarning("CommDCBHelper::setFlowControl(%i): Unsupported FlowType", flow);
    }
James Goppert's avatar
James Goppert committed
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
}

//
//  ReadIntervalTimeout
//    Maximum time allowed to elapse between the arrival of two characters on the communications
//    line, in milliseconds. During a ReadFile operation, the time period begins when the first
//    character is received. If the interval between the arrival of any two characters
//    exceeds this amount, the ReadFile operation is completed and any buffered data is returned.
//    A value of zero indicates that interval time-outs are not used. A value of MAXDWORD,
//    combined with zero values for both the ReadTotalTimeoutConstant and ReadTotalTimeoutMultiplier
//    parameters, specifies that the read operation is to return immediately with the characters that
//    have already been received, even if no characters have been received.
//
//  ReadTotalTimeoutMultiplier
//    Multiplier used to calculate the total time-out period for read operations,
//    in milliseconds. For each read operation, this value is multiplied by the requested
//    number of bytes to be read.
//
//  ReadTotalTimeoutConstant
//    Constant used to calculate the total time-out period for read operations, in milliseconds.
//    For each read operation, this value is added to the product of the ReadTotalTimeoutMultiplier
//    parameter and the requested number of bytes. A value of zero for both the ReadTotalTimeoutMultiplier
//    and ReadTotalTimeoutConstant members indicates that total time-outs are not used for read operations.
//
//  WriteTotalTimeoutMultiplier
//    Multiplier used to calculate the total time-out period for write operations, in milliseconds.
//    For each write operation, this value is multiplied by the number of bytes to be written.
//
//  WriteTotalTimeoutConstant
//    Constant used to calculate the total time-out period for write operations, in milliseconds.
//    For each write operation, this value is added to the product of the WriteTotalTimeoutMultiplier
//    member and the number of bytes to be written. A value of zero for both the WriteTotalTimeoutMultiplier
//    and WriteTotalTimeoutConstant parameters indicates that total time-outs are not used for write operations.
//

bool CommDCBHelper::commTimeouts(CommTimeouts &commtimeouts)
{
759
    // get the current serial port attributes
James Goppert's avatar
James Goppert committed
760

761 762
    if ( !getCommTimeouts() )
        return false;
James Goppert's avatar
James Goppert committed
763

764 765 766 767 768
    commtimeouts.Win32ReadIntervalTimeout = commTimeouts_.ReadIntervalTimeout;
    commtimeouts.Win32ReadTotalTimeoutConstant = commTimeouts_.ReadTotalTimeoutConstant;
    commtimeouts.Win32ReadTotalTimeoutMultiplier = commTimeouts_.ReadTotalTimeoutMultiplier;
    commtimeouts.Win32WriteTotalTimeoutConstant = commTimeouts_.WriteTotalTimeoutConstant;
    commtimeouts.Win32WriteTotalTimeoutMultiplier = commTimeouts_.WriteTotalTimeoutMultiplier;
James Goppert's avatar
James Goppert committed
769

770
    return true;
James Goppert's avatar
James Goppert committed
771 772 773 774
}

void CommDCBHelper::setCommTimeouts(const CommTimeouts commtimeouts)
{
775 776 777 778 779
    commTimeouts_.ReadIntervalTimeout = commtimeouts.Win32ReadIntervalTimeout;
    commTimeouts_.ReadTotalTimeoutConstant = commtimeouts.Win32ReadTotalTimeoutConstant;
    commTimeouts_.ReadTotalTimeoutMultiplier = commtimeouts.Win32ReadTotalTimeoutMultiplier;
    commTimeouts_.WriteTotalTimeoutConstant = commtimeouts.Win32WriteTotalTimeoutConstant;
    commTimeouts_.WriteTotalTimeoutMultiplier = commtimeouts.Win32WriteTotalTimeoutMultiplier;
James Goppert's avatar
James Goppert committed
780 781 782 783 784 785 786
}

/*!

*/
QString CommDCBHelper::errorText(DWORD err)
{
787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806
    unsigned short *pMsg = 0;

    // if character set is Ascii, pMsg should be defined as char *string = 0
    // and QString::fromLocal8Bit(pMsg) should be used instead.

    if ( FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER|FORMAT_MESSAGE_FROM_SYSTEM,
                       0,
                       err,
                       MAKELANGID(LANG_NEUTRAL,SUBLANG_DEFAULT),
                       (LPTSTR)&pMsg,
                       0,
                       NULL) == 0 ) {
        return "There is no message associated with that error code.";
    }
    else {
        QString errMsg = QString::fromUtf16(pMsg);
        LocalFree(pMsg); // free memory allocated by the OS

        return errMsg;
    }
James Goppert's avatar
James Goppert committed
807 808 809 810 811
}

} // namespace