CRS232.h 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. #ifndef __SERIAL_PORT_FILE_H__
  2. #define __SERIAL_PORT_FILE_H__
  3. //#pragma warning(disable:4996)
  4. #ifdef SERIAL_PORT_EXPORTS
  5. #define CSerialPort_DLL_API __declspec(dllexport)
  6. #else
  7. #define CSerialPort_DLL_API //__declspec(dllimport)
  8. #endif
  9. #include <stdio.h>
  10. #include <stdlib.h>
  11. #include <windows.h>
  12. #include "assert.h"
  13. #include <iostream>
  14. #include <cstdarg>
  15. #include <sstream>
  16. #include <string>
  17. using std::string;
  18. #define SERIAL_PORT_BASE_ERROR (-90000)
  19. typedef enum
  20. {
  21. COM_OK = 0,
  22. COM_FAIL = -1,
  23. SERIAL_PORT_BASE_FAIL = SERIAL_PORT_BASE_ERROR,
  24. COM_NO_OPEN,
  25. SET_TIME_OUT_FAIL,
  26. GET_COM_PRAM_FAIL,
  27. SET_COM_PRAM_FAIL,
  28. SET_COM_BUF_FAIL,
  29. CLEAR_COM_BUF_FAIL,
  30. COM_OPEN_FAIL,
  31. COM_READ_FAIL,
  32. COM_WRITE_FAIL,
  33. INPUT_NULL_FAIL,
  34. NOT_INIT_FAIL
  35. } COMERR;
  36. class CSerialPort_DLL_API CRS232
  37. {
  38. private:
  39. DCB m_stDcb;
  40. COMMTIMEOUTS m_CommTimerOuts;
  41. HANDLE m_hCom = INVALID_HANDLE_VALUE;
  42. OVERLAPPED m_overlappedRead;
  43. OVERLAPPED m_overlappedWrite;
  44. private:
  45. inline bool IsOpen();
  46. long SetTimerOut(unsigned long dwTimerOut = 5000);
  47. long SetDCBParm(unsigned long xBabd, unsigned char xDataSize,
  48. unsigned char xParity, unsigned char xStopBit);
  49. long SetPortBuffSize(unsigned long InputBuffSize, unsigned long OutputBuffSize);
  50. long GetInBuffCount();
  51. long GetOutBuffCount();
  52. public:
  53. long OpenPort(unsigned long xPort, unsigned long xBabd, unsigned char xDataSize,
  54. unsigned char xParity, unsigned char xStopBit, unsigned long InputBuffSize,
  55. unsigned long OutputBuffSize, unsigned long dwTimerOut);
  56. long OpenPort(char *strPort, unsigned long xBabd, unsigned char xDataSize,
  57. unsigned char xParity, unsigned char xStopBit, unsigned long InputBuffSize,
  58. unsigned long OutputBuffSize, unsigned long dwTimerOut);
  59. void ClosePort();
  60. void ClearBuffer();
  61. long SerialPortRead(unsigned long dwBufferLength, char *buff, unsigned long dwWaitTime);
  62. long SerialPortWrite(unsigned long dwBufferLength, char *buff);
  63. static string GetErrText(long errid);
  64. };
  65. #endif