ComHandle.cpp 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154
  1. #include "stdafx.h"
  2. #include "ComHandle.h"
  3. #include "global.h"
  4. ComHandle::ComHandle()
  5. {
  6. }
  7. int ComHandle::opencom(int portno)
  8. {
  9. closecom();
  10. if (portno > 0)
  11. {
  12. //新建串口通讯对象
  13. m_pSerial = new CMyCESeries();
  14. m_pSerial->m_OnSeriesRead = OnComRead;
  15. //m_nPortNo = portNo;
  16. int rtn = m_pSerial->OpenPort(this, portno);
  17. //打开串口
  18. if (rtn)
  19. {
  20. addText("打开串口" + std::to_string(portno) + "成功");
  21. }
  22. else
  23. {
  24. addText("打开串口" + std::to_string(portno) + "失败");
  25. if (m_pSerial)
  26. {
  27. delete m_pSerial;
  28. m_pSerial = NULL;
  29. }
  30. }
  31. return rtn;
  32. }
  33. else
  34. return false;
  35. }
  36. int ComHandle::closecom()
  37. {
  38. if (m_pSerial)
  39. {
  40. m_pSerial->ClosePort();
  41. delete m_pSerial;
  42. m_pSerial = NULL;
  43. return true;
  44. }
  45. return false;
  46. }
  47. int ComHandle::senddata()
  48. {
  49. //int nRc = m_pSerial->WriteSyncPort(buff, len);
  50. //return nRc;
  51. return false;
  52. }
  53. void ComHandle::addText(string str)
  54. {
  55. if (m_pRichEdit)
  56. {
  57. m_pRichEdit->SetSel(-1, -1);
  58. m_pRichEdit->ReplaceSel((str+ string("\r\n")).c_str());
  59. m_pRichEdit->PostMessage(WM_VSCROLL, SB_BOTTOM, 0);
  60. }
  61. }
  62. bool ComHandle::ProcessComData(BYTE* buf, DWORD bufLen)
  63. {
  64. CString strS = "";
  65. for (int i = 0; i < bufLen; ++i)
  66. {
  67. CString strW;
  68. CStringA str;
  69. strW.Format(_T("%.2x"), buf[i]);
  70. strS += strW + " ";
  71. }
  72. CString str;
  73. str.Format("%s 收到数据:%s", getCurrentTime().c_str(), strS);
  74. addText(str.GetString());
  75. return true;
  76. }
  77. void ComHandle::linkRichEdit(CRichEditCtrl* pRichEdit)
  78. {
  79. m_pRichEdit = pRichEdit;
  80. }
  81. int ComHandle::senddata(const BYTE*buf, DWORD bufLen)
  82. {
  83. if (!m_pSerial)
  84. {
  85. addText("串口未成功打开");
  86. return false;
  87. }
  88. int nRc = m_pSerial->WriteSyncPort(buf, bufLen);
  89. if (nRc)
  90. {
  91. CString strS = "";
  92. for (int i = 0; i < bufLen; ++i)
  93. {
  94. CString strW;
  95. CStringA str;
  96. strW.Format(_T("%.2x"), buf[i]);
  97. strS += strW + " ";
  98. }
  99. addText(getCurrentTime() + string(" 发送:") + strS.GetString());
  100. }
  101. else
  102. {
  103. addText("发送数据失败");
  104. }
  105. return nRc;
  106. }