SerialPort.cpp
上传用户:thirty
上传日期:2007-01-08
资源大小:37k
文件大小:18k
源码类别:

串口编程

开发平台:

Visual C++

  1. /*
  2. ** FILENAME CSerialPort.cpp
  3. **
  4. ** PURPOSE This class can read, write and watch one serial port.
  5. ** It sends messages to its owner when something happends on the port
  6. ** The class creates a thread for reading and writing so the main
  7. ** program is not blocked.
  8. */
  9. #include "stdafx.h"
  10. #include "SerialPort.h"
  11. #include "Data.h"
  12. #include <assert.h>
  13. #include "stdlib.h"
  14. #include "ver10.h"
  15.  
  16. //
  17. // Constructor
  18. //
  19. CSerialPort::CSerialPort()
  20. {
  21. m_hComm = NULL;
  22. // initialize overlapped structure members to zero
  23. m_ov.Offset = 0;
  24. m_ov.OffsetHigh = 0;
  25. // create events
  26. m_ov.hEvent = NULL;
  27. m_hWriteEvent = NULL;
  28. m_hShutdownEvent = NULL;
  29. m_szWriteBuffer = NULL;
  30. m_bThreadAlive = FALSE;
  31. }
  32. //
  33. // Delete dynamic memory
  34. //
  35. CSerialPort::~CSerialPort()
  36. {
  37. do
  38. {
  39. SetEvent(m_hShutdownEvent);
  40. } while (m_bThreadAlive);
  41. if (m_hComm!=NULL) CloseHandle(m_hComm);
  42. TRACE("Thread endedn");
  43. delete [] m_szWriteBuffer;
  44. }
  45. //
  46. // Initialize the port. This can be port 1 to 4.
  47. //
  48. BOOL CSerialPort::InitPort(CWnd* pPortOwner, // the owner (CWnd) of the port (receives message)
  49.    UINT  portnr, // portnumber (1..4)
  50.    UINT  baud, // baudrate
  51.    char  parity, // parity 
  52.    UINT  databits, // databits 
  53.    UINT  stopbits, // stopbits 
  54.    DWORD dwCommEvents, // EV_RXCHAR, EV_CTS etc
  55.    UINT  writebuffersize) // size to the writebuffer
  56. {
  57. assert(portnr > 0 && portnr < 5);
  58. assert(pPortOwner != NULL);
  59. // if the thread is alive: Kill
  60. if (m_bThreadAlive)
  61. {
  62. do
  63. {
  64. SetEvent(m_hShutdownEvent);
  65. } while (m_bThreadAlive);
  66. TRACE("Thread endedn");
  67. }
  68. // create events
  69. if (m_ov.hEvent != NULL)
  70. ResetEvent(m_ov.hEvent);
  71. m_ov.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
  72. if (m_hWriteEvent != NULL)
  73. ResetEvent(m_hWriteEvent);
  74. m_hWriteEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
  75. if (m_hShutdownEvent != NULL)
  76. ResetEvent(m_hShutdownEvent);
  77. m_hShutdownEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
  78. // initialize the event objects
  79. m_hEventArray[0] = m_hShutdownEvent; // highest priority
  80. m_hEventArray[1] = m_ov.hEvent;
  81. m_hEventArray[2] = m_hWriteEvent;
  82. // initialize critical section
  83. InitializeCriticalSection(&m_csCommunicationSync);
  84. // set buffersize for writing and save the owner
  85. m_pOwner = pPortOwner;
  86. if (m_szWriteBuffer != NULL)
  87. delete [] m_szWriteBuffer;
  88. m_szWriteBuffer = new char[writebuffersize];
  89. m_nPortNr = portnr;
  90. m_nWriteBufferSize = writebuffersize;
  91. m_dwCommEvents = dwCommEvents;
  92. BOOL bResult = FALSE;
  93. char *szPort = new char[50];
  94. char *szBaud = new char[50];
  95. // now it critical!
  96. EnterCriticalSection(&m_csCommunicationSync);
  97. // if the port is already opened: close it
  98. if (m_hComm != NULL)
  99. {
  100. CloseHandle(m_hComm);
  101. m_hComm = NULL;
  102. }
  103. // prepare port strings
  104. sprintf(szPort, "COM%d", portnr);
  105. sprintf(szBaud, "baud=%d parity=%c data=%d stop=%d", baud, parity, databits, stopbits);
  106. // get a handle to the port
  107. m_hComm = CreateFile(szPort, // communication port string (COMX)
  108.      GENERIC_READ | GENERIC_WRITE, // read/write types
  109.      0, // comm devices must be opened with exclusive access
  110.      NULL, // no security attributes
  111.      OPEN_EXISTING, // comm devices must use OPEN_EXISTING
  112.      FILE_FLAG_OVERLAPPED, // Async I/O
  113.      0); // template must be 0 for comm devices
  114. if (m_hComm == INVALID_HANDLE_VALUE)
  115. {
  116. // port not found
  117. delete [] szPort;
  118. delete [] szBaud;
  119. return FALSE;
  120. }
  121. // set the timeout values
  122. m_CommTimeouts.ReadIntervalTimeout = 1000;
  123. m_CommTimeouts.ReadTotalTimeoutMultiplier = 1000;
  124. m_CommTimeouts.ReadTotalTimeoutConstant = 1000;
  125. m_CommTimeouts.WriteTotalTimeoutMultiplier = 1000;
  126. m_CommTimeouts.WriteTotalTimeoutConstant = 1000;
  127. // configure
  128. if (SetCommTimeouts(m_hComm, &m_CommTimeouts))
  129. {    
  130. if (SetCommMask(m_hComm, dwCommEvents))
  131. {
  132. if (GetCommState(m_hComm, &m_dcb))
  133. {
  134. m_dcb.fRtsControl = RTS_CONTROL_ENABLE; // set RTS bit high!
  135. if (BuildCommDCB(szBaud, &m_dcb))
  136. {
  137. if (SetCommState(m_hComm, &m_dcb))
  138. ; // normal operation... continue
  139. else
  140. ProcessErrorMessage("SetCommState()");
  141. }
  142. else
  143. ProcessErrorMessage("BuildCommDCB()");
  144. }
  145. else
  146. ProcessErrorMessage("GetCommState()");
  147. }
  148. else
  149. ProcessErrorMessage("SetCommMask()");
  150. }
  151. else
  152. ProcessErrorMessage("SetCommTimeouts()");
  153. delete [] szPort;
  154. delete [] szBaud;
  155. // flush the port
  156. PurgeComm(m_hComm, PURGE_RXCLEAR | PURGE_TXCLEAR | PURGE_RXABORT | PURGE_TXABORT);
  157. // release critical section
  158. LeaveCriticalSection(&m_csCommunicationSync);
  159. TRACE("Initialisation for communicationport %d completed.nUse Startmonitor to communicate.n", portnr);
  160. return TRUE;
  161. }
  162. //
  163. //  The CommThread Function.
  164. //
  165. UINT CSerialPort::CommThread(LPVOID pParam)
  166. {
  167. // Cast the void pointer passed to the thread back to
  168. // a pointer of CSerialPort class
  169. CSerialPort *port = (CSerialPort*)pParam;
  170. // Set the status variable in the dialog class to
  171. // TRUE to indicate the thread is running.
  172. port->m_bThreadAlive = TRUE;
  173. // Misc. variables
  174. DWORD BytesTransfered = 0; 
  175. DWORD Event = 0;
  176. DWORD CommEvent = 0;
  177. DWORD dwError = 0;
  178. COMSTAT comstat;
  179. BOOL  bResult = TRUE;
  180. char* RXbuff;
  181. DWORD ByteRead;
  182. // Clear comm buffers at startup
  183. if (port->m_hComm) // check if the port is opened
  184. PurgeComm(port->m_hComm, PURGE_RXCLEAR | PURGE_TXCLEAR | PURGE_RXABORT | PURGE_TXABORT);
  185. // begin forever loop.  This loop will run as long as the thread is alive.
  186. for (;;) 
  187. // Make a call to WaitCommEvent().  This call will return immediatly
  188. // because our port was created as an async port (FILE_FLAG_OVERLAPPED
  189. // and an m_OverlappedStructerlapped structure specified).  This call will cause the 
  190. // m_OverlappedStructerlapped element m_OverlappedStruct.hEvent, which is part of the m_hEventArray to 
  191. // be placed in a non-signeled state if there are no bytes available to be read,
  192. // or to a signeled state if there are bytes available.  If this event handle 
  193. // is set to the non-signeled state, it will be set to signeled when a 
  194. // character arrives at the port.
  195. // we do this for each port!
  196. bResult = WaitCommEvent(port->m_hComm, &Event, &port->m_ov);
  197. if (!bResult)  
  198. // If WaitCommEvent() returns FALSE, process the last error to determin
  199. // the reason..
  200. switch (dwError = GetLastError()) 
  201. case ERROR_IO_PENDING: 
  202. // This is a normal return value if there are no bytes
  203. // to read at the port.
  204. // Do nothing and continue
  205. break;
  206. }
  207. case 87:
  208. {
  209. // Under Windows NT, this value is returned for some reason.
  210. // I have not investigated why, but it is also a valid reply
  211. // Also do nothing and continue.
  212. break;
  213. }
  214. default:
  215. {
  216. // All other error codes indicate a serious error has
  217. // occured.  Process this error.
  218. port->ProcessErrorMessage("WaitCommEvent()");
  219. break;
  220. }
  221. }
  222. }
  223. else
  224. {
  225. // If WaitCommEvent() returns TRUE, check to be sure there are
  226. // actually bytes in the buffer to read.  
  227. //
  228. // If you are reading more than one byte at a time from the buffer 
  229. // (which this program does not do) you will have the situation occur 
  230. // where the first byte to arrive will cause the WaitForMultipleObjects() 
  231. // function to stop waiting.  The WaitForMultipleObjects() function 
  232. // resets the event handle in m_OverlappedStruct.hEvent to the non-signelead state
  233. // as it returns.  
  234. //
  235. // If in the time between the reset of this event and the call to 
  236. // ReadFile() more bytes arrive, the m_OverlappedStruct.hEvent handle will be set again
  237. // to the signeled state. When the call to ReadFile() occurs, it will 
  238. // read all of the bytes from the buffer, and the program will
  239. // loop back around to WaitCommEvent().
  240. // 
  241. // At this point you will be in the situation where m_OverlappedStruct.hEvent is set,
  242. // but there are no bytes available to read.  If you proceed and call
  243. // ReadFile(), it will return immediatly due to the async port setup, but
  244. // GetOverlappedResults() will not return until the next character arrives.
  245. //
  246. // It is not desirable for the GetOverlappedResults() function to be in 
  247. // this state.  The thread shutdown event (event 0) and the WriteFile()
  248. // event (Event2) will not work if the thread is blocked by GetOverlappedResults().
  249. //
  250. // The solution to this is to check the buffer with a call to ClearCommError().
  251. // This call will reset the event handle, and if there are no bytes to read
  252. // we can loop back through WaitCommEvent() again, then proceed.
  253. // If there are really bytes to read, do nothing and proceed.
  254. bResult = ClearCommError(port->m_hComm, &dwError, &comstat);
  255. if (comstat.cbInQue == 0)
  256. continue;
  257. } // end if bResult
  258. // Main wait function.  This function will normally block the thread
  259. // until one of nine events occur that require action.
  260. Event = WaitForMultipleObjects(3, port->m_hEventArray, FALSE, INFINITE);
  261. switch (Event)
  262. {
  263. case 0:
  264. {
  265. // Shutdown event.  This is event zero so it will be
  266. // the higest priority and be serviced first.
  267.   port->m_bThreadAlive = FALSE;
  268. // Kill this thread.  break is not needed, but makes me feel better.
  269. AfxEndThread(100);
  270. break;
  271. }
  272. case 1: // read event
  273. {
  274. GetCommMask(port->m_hComm, &CommEvent);
  275. if (CommEvent & EV_CTS)
  276. ::SendMessage(port->m_pOwner->m_hWnd, WM_COMM_CTS_DETECTED, (WPARAM) 0, (LPARAM) port->m_nPortNr);
  277. if (CommEvent & EV_RXFLAG)
  278. ::SendMessage(port->m_pOwner->m_hWnd, WM_COMM_RXFLAG_DETECTED, (WPARAM) 0, (LPARAM) port->m_nPortNr);
  279. if (CommEvent & EV_BREAK)
  280. ::SendMessage(port->m_pOwner->m_hWnd, WM_COMM_BREAK_DETECTED, (WPARAM) 0, (LPARAM) port->m_nPortNr);
  281. if (CommEvent & EV_ERR)
  282. ::SendMessage(port->m_pOwner->m_hWnd, WM_COMM_ERR_DETECTED, (WPARAM) 0, (LPARAM) port->m_nPortNr);
  283. if (CommEvent & EV_RING)
  284. ::SendMessage(port->m_pOwner->m_hWnd, WM_COMM_RING_DETECTED, (WPARAM) 0, (LPARAM) port->m_nPortNr);
  285. if (CommEvent & EV_RXCHAR)
  286. // Receive character event from port.
  287. ReceiveChar(port, comstat,RXbuff,ByteRead);
  288. DataProcess(RXbuff,ByteRead);
  289. break;
  290. }  
  291. case 2: // write event
  292. {
  293. // Write character event from port
  294. WriteChar(port);
  295. break;
  296. }
  297. } // end switch
  298. } // close forever loop
  299. return 0;
  300. }
  301. //
  302. // start comm watching
  303. //
  304. BOOL CSerialPort::StartMonitoring()
  305. {
  306. if (!(m_Thread = AfxBeginThread(CommThread, this)))
  307. return FALSE;
  308. TRACE("Thread startedn");
  309. return TRUE;
  310. }
  311. //
  312. // Restart the comm thread
  313. //
  314. BOOL CSerialPort::RestartMonitoring()
  315. {
  316. TRACE("Thread resumedn");
  317. m_Thread->ResumeThread();
  318. return TRUE;
  319. }
  320. //
  321. // Suspend the comm thread
  322. //
  323. BOOL CSerialPort::StopMonitoring()
  324. {
  325. TRACE("Thread suspendedn");
  326. m_Thread->SuspendThread(); 
  327. return TRUE;
  328. }
  329. //
  330. // If there is a error, give the right message
  331. //
  332. void CSerialPort::ProcessErrorMessage(char* ErrorText)
  333. {
  334. char *Temp = new char[200];
  335. LPVOID lpMsgBuf;
  336. FormatMessage( 
  337. FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
  338. NULL,
  339. GetLastError(),
  340. MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
  341. (LPTSTR) &lpMsgBuf,
  342. 0,
  343. NULL 
  344. );
  345. sprintf(Temp, "WARNING:  %s Failed with the following error: n%snPort: %dn", (char*)ErrorText, lpMsgBuf, m_nPortNr); 
  346. MessageBox(NULL, Temp, "Application Error", MB_ICONSTOP);
  347. LocalFree(lpMsgBuf);
  348. delete[] Temp;
  349. }
  350. //
  351. // Write a character.
  352. //
  353. void CSerialPort::WriteChar(CSerialPort* port)
  354. {
  355. BOOL bWrite = TRUE;
  356. BOOL bResult = TRUE;
  357. DWORD BytesSent = 0;
  358. ResetEvent(port->m_hWriteEvent);
  359. // Gain ownership of the critical section
  360. EnterCriticalSection(&port->m_csCommunicationSync);
  361. if (bWrite)
  362. {
  363. // Initailize variables
  364. port->m_ov.Offset = 0;
  365. port->m_ov.OffsetHigh = 0;
  366. // Clear buffer
  367. PurgeComm(port->m_hComm, PURGE_RXCLEAR | PURGE_TXCLEAR | PURGE_RXABORT | PURGE_TXABORT);
  368. bResult = WriteFile(port->m_hComm, // Handle to COMM Port
  369. port->m_szWriteBuffer, // Pointer to message buffer in calling finction
  370. strlen((char*)port->m_szWriteBuffer), // Length of message to send
  371. &BytesSent, // Where to store the number of bytes sent
  372. &port->m_ov); // Overlapped structure
  373. // deal with any error codes
  374. if (!bResult)  
  375. {
  376. DWORD dwError = GetLastError();
  377. switch (dwError)
  378. {
  379. case ERROR_IO_PENDING:
  380. {
  381. // continue to GetOverlappedResults()
  382. BytesSent = 0;
  383. bWrite = FALSE;
  384. break;
  385. }
  386. default:
  387. {
  388. // all other error codes
  389. port->ProcessErrorMessage("WriteFile()");
  390. }
  391. }
  392. else
  393. {
  394. LeaveCriticalSection(&port->m_csCommunicationSync);
  395. }
  396. } // end if(bWrite)
  397. if (!bWrite)
  398. {
  399. bWrite = TRUE;
  400. bResult = GetOverlappedResult(port->m_hComm, // Handle to COMM port 
  401.   &port->m_ov, // Overlapped structure
  402.   &BytesSent, // Stores number of bytes sent
  403.   TRUE);  // Wait flag
  404. LeaveCriticalSection(&port->m_csCommunicationSync);
  405. // deal with the error code 
  406. if (!bResult)  
  407. {
  408. port->ProcessErrorMessage("GetOverlappedResults() in WriteFile()");
  409. }
  410. } // end if (!bWrite)
  411. // Verify that the data size send equals what we tried to send
  412. if (BytesSent != strlen((char*)port->m_szWriteBuffer))
  413. {
  414. TRACE("WARNING: WriteFile() error.. Bytes Sent: %d; Message Length: %dn", BytesSent, strlen((char*)port->m_szWriteBuffer));
  415. }
  416. }
  417. //
  418. // Character received. Inform the owner
  419. //
  420. void CSerialPort::ReceiveChar(CSerialPort* port, COMSTAT comstat,char* RXbuff,DWORD ByteRead)
  421. {
  422. BOOL  bRead = TRUE; 
  423. BOOL  bResult = TRUE;
  424. DWORD dwError = 0;
  425. //DWORD BytesRead = 0;
  426. //unsigned char RXBuff;
  427. char* buff;
  428. buff=RXbuff;
  429. for (;;) 
  430. // Gain ownership of the comm port critical section.
  431. // This process guarantees no other part of this program 
  432. // is using the port object. 
  433. EnterCriticalSection(&port->m_csCommunicationSync);
  434. // ClearCommError() will update the COMSTAT structure and
  435. // clear any other errors.
  436. bResult = ClearCommError(port->m_hComm, &dwError, &comstat);
  437. LeaveCriticalSection(&port->m_csCommunicationSync);
  438. // start forever loop.  I use this type of loop because I
  439. // do not know at runtime how many loops this will have to
  440. // run. My solution is to start a forever loop and to
  441. // break out of it when I have processed all of the
  442. // data available.  Be careful with this approach and
  443. // be sure your loop will exit.
  444. // My reasons for this are not as clear in this sample 
  445. // as it is in my production code, but I have found this 
  446. // solutiion to be the most efficient way to do this.
  447. if (comstat.cbInQue == 0)
  448. {
  449. // break out when all bytes have been read
  450. break;
  451. }
  452. EnterCriticalSection(&port->m_csCommunicationSync);
  453. if (bRead)
  454. {
  455. bResult = ReadFile(port->m_hComm, // Handle to COMM port 
  456.    buff, // RX Buffer Pointer
  457.    70, // Read one byte
  458.    &ByteRead, // Stores number of bytes read
  459.    &port->m_ov); // pointer to the m_ov structure
  460. // deal with the error code 
  461. if (!bResult)  
  462. switch (dwError = GetLastError()) 
  463. case ERROR_IO_PENDING: 
  464. // asynchronous i/o is still in progress 
  465. // Proceed on to GetOverlappedResults();
  466. bRead = FALSE;
  467. ByteRead=0;
  468. break;
  469. }
  470. default:
  471. {
  472. // Another error has occured.  Process this error.
  473. port->ProcessErrorMessage("ReadFile()");
  474. break;
  475. }
  476. }
  477. else
  478. {
  479. // ReadFile() returned complete. It is not necessary to call GetOverlappedResults()
  480. bRead = TRUE;
  481. }
  482. }  // close if (bRead)
  483. if (!bRead)
  484. {
  485. bRead = TRUE;
  486. bResult = GetOverlappedResult(port->m_hComm, // Handle to COMM port 
  487.   &port->m_ov, // Overlapped structure
  488.   &ByteRead, // Stores number of bytes read
  489.   TRUE);  // Wait flag
  490. // deal with the error code 
  491. if (!bResult)  
  492. {
  493. port->ProcessErrorMessage("GetOverlappedResults() in ReadFile()");
  494. }
  495. }  // close if (!bRead)
  496. LeaveCriticalSection(&port->m_csCommunicationSync);
  497. // notify parent that a byte was received
  498. ::SendMessage((port->m_pOwner)->m_hWnd, WM_COMM_RXCHAR, (WPARAM)(* buff), (LPARAM) port->m_nPortNr);
  499. } // end forever loop
  500. }
  501. //
  502. // Write a string to the port
  503. //
  504. void CSerialPort::WriteToPort(char string)
  505. {
  506. assert(m_hComm != 0);
  507. memset(m_szWriteBuffer, 0, sizeof(m_szWriteBuffer));
  508. strcpy(m_szWriteBuffer, &string);
  509. // set event for write
  510. SetEvent(m_hWriteEvent);
  511. }
  512. //
  513. // Return the device control block
  514. //
  515. DCB CSerialPort::GetDCB()
  516. {
  517. return m_dcb;
  518. }
  519. //
  520. // Return the communication event masks
  521. //
  522. DWORD CSerialPort::GetCommEvents()
  523. {
  524. return m_dwCommEvents;
  525. }
  526. //
  527. // Return the output buffer size
  528. //
  529. DWORD CSerialPort::GetWriteBufferSize()
  530. {
  531. return m_nWriteBufferSize;
  532. }
  533. //--------------------------------------------------------
  534. //dataprocess connect with the database
  535. void CSerialPort::DataProcess(char* RXbuff,DWORD ByteRead)
  536. {
  537. int i; 
  538. char*  str=RXbuff;
  539. char a1[2];
  540. char a2[3];
  541. CData* m_pSet;
  542. switch (ByteRead)
  543. {
  544. case(60):
  545. {
  546. if(!m_pSet->IsBOF())
  547. {
  548. m_pSet->MoveLast();
  549. m_pSet->AddNew();
  550. for(i=0;i<2;i++)
  551. {
  552. a1[i]=(*str);
  553. str++;
  554. }
  555. m_pSet->m_Au_ID=atol(a1);
  556. for(i=0;i<3;i++)
  557. {
  558. a2[i]=(*str);
  559. str++;
  560. }
  561. m_pSet->m_Author=a2;
  562. m_pSet->Update();
  563. if(!m_pSet->Update())
  564. assert("cannot write to the database");
  565. //this is the normal data process
  566. };
  567. case(50):
  568. {
  569. //this is the quanlity data process
  570. }
  571. default:
  572. {
  573. ASSERT("THE BYTE'S NUMBER IS NOT WRIGHT");
  574. //something wrong with the data process
  575. }
  576. }
  577. }
  578. }