#include "stdafx.h" #include "ComHandle.h" #include "global.h" ComHandle::ComHandle() { } int ComHandle::opencom(int portno) { closecom(); if (portno > 0) { //新建串口通讯对象 m_pSerial = new CMyCESeries(); m_pSerial->m_OnSeriesRead = OnComRead; //m_nPortNo = portNo; int rtn = m_pSerial->OpenPort(this, portno); //打开串口 if (rtn) { addText("打开串口" + std::to_string(portno) + "成功"); } else { addText("打开串口" + std::to_string(portno) + "失败"); if (m_pSerial) { delete m_pSerial; m_pSerial = NULL; } } return rtn; } else return false; } int ComHandle::closecom() { if (m_pSerial) { m_pSerial->ClosePort(); delete m_pSerial; m_pSerial = NULL; return true; } return false; } int ComHandle::senddata() { //int nRc = m_pSerial->WriteSyncPort(buff, len); //return nRc; return false; } void ComHandle::addText(string str) { if (m_pRichEdit) { m_pRichEdit->SetSel(-1, -1); m_pRichEdit->ReplaceSel((str+ string("\r\n")).c_str()); m_pRichEdit->PostMessage(WM_VSCROLL, SB_BOTTOM, 0); } } bool ComHandle::ProcessComData(BYTE* buf, DWORD bufLen) { CString strS = ""; for (int i = 0; i < bufLen; ++i) { CString strW; CStringA str; strW.Format(_T("%.2x"), buf[i]); strS += strW + " "; } CString str; str.Format("%s 收到数据:%s", getCurrentTime().c_str(), strS); addText(str.GetString()); return true; } void ComHandle::linkRichEdit(CRichEditCtrl* pRichEdit) { m_pRichEdit = pRichEdit; } int ComHandle::senddata(const BYTE*buf, DWORD bufLen) { if (!m_pSerial) { addText("串口未成功打开"); return false; } int nRc = m_pSerial->WriteSyncPort(buf, bufLen); if (nRc) { CString strS = ""; for (int i = 0; i < bufLen; ++i) { CString strW; CStringA str; strW.Format(_T("%.2x"), buf[i]); strS += strW + " "; } addText(getCurrentTime() + string(" 发送:") + strS.GetString()); } else { addText("发送数据失败"); } return nRc; }