1. 程式人生 > >經典vc串列埠通訊

經典vc串列埠通訊

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

772

773

774

775

776

777

778

779

780

781

782

783

784

785

786

787

788

789

790

791

792

793

794

795

796

797

798

799

800

801

802

803

804

805

806

807

808

809

810

811

812

813

814

815

816

817

818

819

820

821

822

823

824

825

826

827

828

829

830

831

832

833

834

835

836

837

838

839

840

841

842

843

844

845

846

847

848

849

850

851

852

853

854

855

856

857

858

859

860

861

862

863

864

865

866

867

868

869

870

871

872

873

874

875

876

877

878

// Serial.cpp: implementation of the CSerial class.

// download by http://www.NewXing.com

//////////////////////////////////////////////////////////////////////

 

#include "stdafx.h"

#include "Serial.h"

 

#include "DataStruct.h"

 

#ifdef _DEBUG

#undef THIS_FILE

static char THIS_FILE[]=__FILE__;

#define new DEBUm_NEW

#endif

 

 

#define MSG_READ    0

#define MSG_WRITE   1

//全域性變數,暫時儲存資料用的

DATA_GROUP  g_read_data_group;

DATA_GROUP  g_send_data_group;

//////////////////////////////////////////////////////////////////////

// Construction/Destruction

//////////////////////////////////////////////////////////////////////

 

CSerial::CSerial()

{

    Init();

}

 

CSerial::~CSerial()

{

    UnInit();

}

/******************************************************************************

*功能:初始化

*說明:

*引數:

*返回:

******************************************************************************/

void CSerial::Init()

{

    m_h_father_wnd=NULL;

    m_u_message=0;

 

    m_bOpened = false;

    m_hCommPort=INVALID_HANDLE_VALUE;

 

    m_start_data_thread=CreateEvent(0,true,0,0);

    m_start_analysis_thread=CreateEvent(0,true,0,0);

    m_start_event_thread=CreateEvent(0,true,0,0);

 

    m_end_event_thread=CreateEvent(0,true,0,0);

    m_end_analysis_thread=CreateEvent(0,true,0,0);

    m_end_data_thread=CreateEvent(0,true,0,0);

 

    m_event_thread_end=CreateEvent(0,true,0,0);

    m_analysis_thread_end=CreateEvent(0,true,0,0);

    m_data_thread_end=CreateEvent(0,true,0,0);

 

    m_data_come_event=CreateEvent(0,true,0,0);

    m_event_come_event=CreateEvent(0,true,0,0);

 

    m_end_send_thread=CreateEvent(0,true,0,0);

    m_send_thread_end=CreateEvent(0,true,0,0);

    m_send_data_event=CreateEvent(0,true,0,0);

}

/******************************************************************************

*功能:釋放資源

*說明:

*引數:

*返回:

******************************************************************************/

void CSerial::UnInit()

{

    Close();

 

    //關閉一直存活的事件物件

    CloseAndCleanHandle(m_start_event_thread);

    CloseAndCleanHandle(m_start_data_thread);

    CloseAndCleanHandle(m_start_analysis_thread);

    CloseAndCleanHandle(m_end_event_thread);

    CloseAndCleanHandle(m_end_analysis_thread);

    CloseAndCleanHandle(m_end_data_thread);

    CloseAndCleanHandle(m_event_thread_end);

    CloseAndCleanHandle(m_analysis_thread_end);

    CloseAndCleanHandle(m_data_thread_end);

    CloseAndCleanHandle(m_data_come_event);

    CloseAndCleanHandle(m_event_come_event);

 

    CloseAndCleanHandle(m_end_send_thread);

    CloseAndCleanHandle(m_send_thread_end);

    CloseAndCleanHandle(m_send_data_event);

}

/******************************************************************************

*功能:關閉串列埠

*說明:

*引數:

*返回:

******************************************************************************/

BOOL CSerial::Close()

{

    if(!m_bOpened)return TRUE;

 

    m_bOpened=false;

 

    HANDLE handle[4];

    handle[0]=m_event_thread_end;

    handle[1]=m_analysis_thread_end;

    handle[2]=m_data_thread_end;

    handle[3]=m_send_thread_end;

 

    SetEvent(m_end_event_thread);

    SetEvent(m_end_send_thread);

 

    ::WaitForMultipleObjects(4,handle,TRUE,INFINITE);

 

    TRACE("已經關閉了四個執行緒!\n");

    Sleep(100);

 

    CloseAndCleanHandle(m_hCommPort);

 

    //關閉串列埠時,要重置一下這個訊號

    ResetEvent(m_start_event_thread);

    ResetEvent(m_start_data_thread);

    ResetEvent(m_start_analysis_thread);

    ResetEvent(m_end_event_thread);

    ResetEvent(m_end_analysis_thread);

    ResetEvent(m_end_data_thread);

    ResetEvent(m_event_thread_end);

    ResetEvent(m_analysis_thread_end);

    ResetEvent(m_data_thread_end);

    ResetEvent(m_data_come_event);

    ResetEvent(m_event_come_event);

 

    ResetEvent(m_end_send_thread);

    ResetEvent(m_send_thread_end);

    ResetEvent(m_send_data_event);

 

    return TRUE;

}

/******************************************************************************

*功能:關閉並非法化控制代碼

*說明:

*引數:

*返回:

******************************************************************************/

void CSerial::CloseAndCleanHandle(HANDLE &handle)

{

    ASSERT(handle);

    if(handle==INVALID_HANDLE_VALUE)return;

    BOOL bRet=CloseHandle(handle);

 

    if(!bRet)

    {

        TRACE0( "close handle fail!\n" );

        ASSERT(0);

    }

    else

    {

        handle = INVALID_HANDLE_VALUE;

    }

}

/******************************************************************************

*功能:開啟串列埠

*說明:

*引數:    nCom        :開啟哪一個串列埠--------1,2

        dwBaudRate  :波特率----------------9600?

        byByteSize  :資料位----------------8

        byParity    :奇偶較驗位------------0

        byStopBits  :停止位----------------1

*返回: 如果之前已經開啟,TRUE,但引數不是最新設定的,而是上次開啟串列埠時的數值;

        如果之前沒有開啟串列埠:

            成功,TRUE,失敗,FALSE

******************************************************************************/

BOOL CSerial::Open(HWND hWnd,UINT Msg,BYTE nCom, DWORD dwBaudRate,

                    BYTE byByteSize,BYTE byParity,BYTE byStopBits)

{

    if(m_bOpened)return TRUE;

 

    m_h_father_wnd=hWnd;

    m_u_message=Msg;

 

    CString szPortName;

    szPortName.Format("COM%d",nCom);

 

    try

    {

        //開啟串列埠

        m_hCommPort = ::CreateFile(

            szPortName,

            GENERIC_READ | GENERIC_WRITE,

            0,

            0,

            OPEN_EXISTING,

            FILE_FLAG_OVERLAPPED,

            0);

        if(m_hCommPort==INVALID_HANDLE_VALUE)

        {

            TRACE("open com port failed!\n");

            CloseAndCleanHandle(m_hCommPort);

            return FALSE;

        }

        TRACE("open com port success!\n");

 

        //設定過濾事件

        if(!::SetCommMask(m_hCommPort,EV_RXCHAR | EV_ERR))//| EV_TXEMPTY

        {

            TRACE("setcommmask fail!\n");

            CloseAndCleanHandle(m_hCommPort);

            return FALSE;

        }

        TRACE("SetCommMask success!\n");

 

        //設定DCB結構

        DCB dcb;

        memset(&dcb,0,sizeof(DCB));

         

        if(!::GetCommState(m_hCommPort,&dcb))

        {

            TRACE("GetCommState(m_hCommPort,&dcb) failed!\n");

            CloseAndCleanHandle(m_hCommPort);

            return FALSE;

        }

        TRACE("GetCommState success!\n");

         

        dcb.BaudRate    = dwBaudRate;

        dcb.ByteSize    = byByteSize;

        dcb.Parity      = byParity;

        if(byStopBits==1)

        {

            dcb.StopBits = ONESTOPBIT;

        }

        else if(byStopBits==2)

        {

            dcb.StopBits = TWOSTOPBITS;

        }

        else

        {

            dcb.StopBits = ONE5STOPBITS;

        }

//*現在不清楚流控怎麼用,所以先不寫了,預設就行了

//      dcb.fDsrSensitivity = 0;

//      dcb.fDtrControl     = DTR_CONTROL_ENABLE;

//      dcb.fOutxDsrFlow    = 0;

//*/       

        if(!::SetCommState(m_hCommPort,&dcb))

        {

            TRACE("SetCommState(m_hCommPort,&dcb)) failed!\n");

            CloseAndCleanHandle(m_hCommPort);

            return FALSE;

        }

        TRACE("SetCommState success!\n");

 

        //設定超時,我準備用事件判斷接收到單個字元,所以超時這樣設了

        COMMTIMEOUTS timeouts;

        memset(&timeouts,0,sizeof(COMMTIMEOUTS));

        timeouts.ReadIntervalTimeout        = MAXDWORD;

        timeouts.ReadTotalTimeoutConstant   = 0;

        timeouts.ReadTotalTimeoutMultiplier = 0;

        timeouts.WriteTotalTimeoutConstant  = 0;

        timeouts.WriteTotalTimeoutMultiplier= 0;

 

        if(!::SetCommTimeouts(m_hCommPort,&timeouts))

        {

            TRACE("SetCommTimeouts(m_hCommPort,&timeouts) failed!\n");

            CloseAndCleanHandle(m_hCommPort);

            return FALSE;

        }

        TRACE("SetCommTimeouts success!\n");

 

//      m_end_read_thread   = CreateEvent(0,true,0,0);  //手動恢復訊號

 

        AfxBeginThread(ReadEventProc,(LPVOID)this);

        AfxBeginThread(AnalysisEventProc,(LPVOID)this);

        AfxBeginThread(ReadDataProc,(LPVOID)this);

        AfxBeginThread(SendDataProc,(LPVOID)this);

 

        //首先啟動讀取資料執行緒,其它執行緒會依次被它啟動

        //退出時,先退出接收事件執行緒,然後,事件分析執行緒,最後是資料接收執行緒

        SetEvent(m_start_data_thread); 

 

        m_bOpened = TRUE;

    }

    catch(...)

    {

        ASSERT(0);

        CloseAndCleanHandle(m_hCommPort);

    }

 

    return TRUE;

}

/******************************************************************************

*功能:讀取資料執行緒

*說明:    每接收到一個字元,都會有事件發出。這個執行緒把接收到的第個字元訊息,都

        傳送給訊息分析執行緒。

*引數:lpParam:即:CSerial類物件本身

*返回:0

******************************************************************************/

UINT CSerial::ReadEventProc(LPVOID lpParam)

{

    CSerial * pSerial = (CSerial *)lpParam;

 

    bool bQuit=false;

 

    DWORD dwEventMask=0;

 

    //接收到訊息重疊

    OVERLAPPED ov;

    memset(&ov,0,sizeof(OVERLAPPED));

    ov.hEvent   = CreateEvent(0,true,0,0);

 

    //讀取串列埠事件、退出執行緒訊號

    HANDLE mask_handle[2];

    mask_handle[0] = pSerial->m_end_event_thread;

    mask_handle[1] = ov.hEvent;

     

    //檢查有沒有訊息的標誌量

    DWORD dwRet;

    BOOL  bRet;

    bool  bHasMessage  =false;

    bool  bMaskOverlapping = false;

 

    //錯誤處理

    DWORD dwErrors=0;

    COMSTAT comstate;

    memset(&comstate,0,sizeof(COMSTAT));

 

    //等等待啟動訊號,資料處理執行緒啟動後,就會通知接收事件訊息執行緒啟動

    ::WaitForSingleObject(pSerial->m_start_event_thread,INFINITE);

    TRACE("get event thread start!\n");

 

    //清空系統緩衝區

    pSerial->ClearSysReadBufferContent();

 

    while(!bQuit)

    {

        dwEventMask=0;

        bRet=::WaitCommEvent(pSerial->m_hCommPort,&dwEventMask,&ov);

        if(bRet)    //正好得到一個串列埠訊息

        {

            bHasMessage=true;

        }

        else        //沒有得到串列埠訊息,看看是否在進行重疊操作吧

        {

            if(GetLastError()==ERROR_IO_PENDING)//正在進行重疊操作...

            {

                bMaskOverlapping=true;//正在進行重疊操作,直接跳出,到下邊的處理程式碼

//              TRACE("已經進入到了重疊操作,errorcode=[%d][%d]\n",GetLastError(),dwEventMask);

            }

            else

            {

                TRACE("WaitCommEvent發生錯誤!errorcode=[%d][%d]\n",GetLastError(),dwEventMask);

                continue;

            }

        }

        if(bMaskOverlapping)    //如果是在進行疊操作,就等待...

        {

            bMaskOverlapping=false;

            dwRet=::WaitForMultipleObjects(2,mask_handle,false,INFINITE);

            switch(dwRet-WAIT_OBJECT_0)

            {

            case 0://退出執行緒

                {

                    bQuit=true;

                }

                break;

            case 1://接收到訊息

                {

                    ResetEvent(ov.hEvent);//恢復串列埠事件訊號

                    bRet=::GetOverlappedResult(pSerial->m_hCommPort,&ov,&dwErrors,false);

                    if(bRet)

                    {

                        bHasMessage=true;

                    }

                }

                break;

            default://未知訊號

                {

                }

                break;

            }

        }

        if(bHasMessage)//最終,如果有訊息到來

        {

            bHasMessage=false;

/*          dwEventMask=0;

            bRet=::GetCommMask(pSerial->m_hCommPort,&dwEventMask);

            if(!bRet)

            {

                ResetEvent(ov.hEvent);//恢復串列埠事件訊號

                TRACE0("GetCommMask(pSerial->m_hCommPort,&dwEventMask)\n");

                continue;

            }

            //他媽的,原來我用錯了,GetCommMask只是取得SetCommMask設定的事件!

*/

            //有訊息到來,並且成功得到了訊息

            if(EV_ERR == (dwEventMask & EV_ERR) )               //如果發生了錯誤,就只處理錯誤

            {

                //發生錯誤了,要能夠恢復才行

                ::ClearCommError(pSerial->m_hCommPort,&dwErrors,&comstate);

                TRACE("出現了錯誤!\n");

            }

/*          else if(EV_TXEMPTY == (dwEventMask & EV_TXEMPTY) )  //完成傳送所有資料

            {

                TRACE("資料傳送完畢!\n");

                pSerial->NotifyWriteData();

            }

*/

            else if(EV_RXCHAR == (dwEventMask & EV_RXCHAR) )    //讀取資料

            {

                static unsigned long l=0;

//              TRACE("事件接收執行緒接收到有字元到達的訊息!nIndex=[%ld]\n",l++);

                SetEvent(pSerial->m_event_come_event);

            }

        }

    }

 

    pSerial->CloseAndCleanHandle(ov.hEvent);

 

    TRACE("get event thread end!\n");

//AfxMessageBox("get event thread end!");

    //通知接收資料執行緒關閉

    SetEvent(pSerial->m_end_analysis_thread);

    SetEvent(pSerial->m_event_thread_end);

    return 0;

}

/******************************************************************************

*功能:分析是否成功接收到一個數據包

*說明:每接收到一個字元,都會有一個訊息傳送過來。根據兩個字元間是否超時來判斷是否成功接收到一個數據包

*引數:

*返回:

******************************************************************************/

UINT CSerial::AnalysisEventProc(LPVOID lpParam)

{

    CSerial * pSerial = (CSerial *)lpParam;

 

    bool bQuit=false;

 

    //讀取串列埠事件、退出執行緒訊號

    HANDLE handle[2];

    handle[0] = pSerial->m_end_analysis_thread;

    handle[1] = pSerial->m_event_come_event;

 

    //儲存WaitForMultipleObjects返回值

    DWORD dwRet;

 

    //用來判斷之前是否有過字元訊息,兩個字元訊息之間是否超時

    bool bHasMessageBefore       = false;

 

    ::WaitForSingleObject(pSerial->m_start_analysis_thread,INFINITE);

 

    TRACE("analysis event thread start!\n");

 

    SetEvent(pSerial->m_start_event_thread);//啟動接收事件執行緒

 

    while(!bQuit)

    {

//      bHasMessageBefore=false;//在下邊已經變為FALSE了

        dwRet=::WaitForMultipleObjects(2,handle,false,INFINITE);

         

        switch(dwRet-WAIT_OBJECT_0)

        {

        case 0://退出

            {

                bQuit=true;

            }

            continue;

        case 1://資料到來,進入下一級迴圈

            {

                TRACE0("一個數據包的第一個字元到達!\n");

                ResetEvent(handle[1]);

                if(!bHasMessageBefore)bHasMessageBefore=true;

            }

            break;

        default:

            {

                ResetEvent(handle[0]);

                ResetEvent(handle[1]);

            }

            continue;

        }

        while(!bQuit && bHasMessageBefore )

        {

            dwRet=::WaitForMultipleObjects(2,handle,false,DATA_READ_TIMEOUT);

            if(dwRet==WAIT_TIMEOUT)//成功接收到一個數據包

            {

                if(bHasMessageBefore)

                {

                    TRACE0("完整地接收到了一個數據包!通知資料接收執行緒進行接收!\n");

                    bHasMessageBefore=false;

                    SetEvent(pSerial->m_data_come_event);//通知資料接收執行緒接收資料

                }

                continue;

            }

            switch(dwRet-WAIT_OBJECT_0)

            {

            case 0://退出

                {

                    bQuit=true;

                }

                break;

            case 1://資料到來

                {

//                  TRACE0("事件分析執行緒接收到了一個字元!\n");

                    ResetEvent(handle[1]);

                }

                break;

            default://出錯了

                {

                    ResetEvent(handle[0]);

                    ResetEvent(handle[1]);

                }

                break;

            }

        }

    }

 

    TRACE("analysis event thread end\n");

//AfxMessageBox("analysis event thread end");

    SetEvent(pSerial->m_end_data_thread);

    SetEvent(pSerial->m_analysis_thread_end);

    return 1;

}

/******************************************************************************

*功能:讀取資料執行緒

*說明:    成功收到一個數據包後,這個執行緒會得到訊息。開始讀取這個資料包

        成功讀取一包資料後,會把資料放到g_read_data_group中,同時向呼叫者發出一個訊息

        此訊息由呼叫者初始化時傳入.

*引數:lpParam:即:CSerial類物件本身

*返回:0

******************************************************************************/

UINT CSerial::ReadDataProc(LPVOID lpParam)

{

    CSerial * pSerial = (CSerial *)lpParam;

 

    bool bQuit=false;

 

    DWORD dwEventMask=0;

 

    //接收到重疊訊息

    OVERLAPPED ov;

    memset(&ov,0,sizeof(OVERLAPPED));

    ov.hEvent   = CreateEvent(0,true,0,0);

 

    //讀取串列埠事件、退出執行緒訊號

    HANDLE event_handle[2];

    event_handle[0] = pSerial->m_end_data_thread;

    event_handle[1] = pSerial->m_data_come_event;

    HANDLE read_handle[2];

    read_handle[0] = pSerial->m_end_data_thread;

    read_handle[1] = ov.hEvent;

 

    //想要讀取的位元組數

    BOOL  bRet;

    DWORD dwBytesWantRead;

    DWORD dwBytesRead;

    char  temp_buf[2*MAX_COMM_BUF_LEN];

    bool bReadOverlapping = false;

    bool bReadDataSuccess = false;

 

    //想知道系統讀緩衝區裡共有多少位元組

    DWORD   dwErrors=0;//需要這個引數,但是根本沒有使用它的返回值,我們不關心它的返回值.

    COMSTAT comstate;

    memset(&comstate,0,sizeof(COMSTAT));

 

    //儲存WaitForMultipleObjects返回值

    DWORD dwRet;