123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135 |
- #include <cassert>
- #include "DiosUnitComm_V3.h"
- #include "ResDataObject.h"
- //-----------------------------------------------------------------------------
- // DiosConnect
- //-----------------------------------------------------------------------------
- namespace DIOS::Dev::Communication
- {
- DiosConnect::DiosConnect(int millisecond)
- {
- //m_DataThread = nullptr;
- m_tbFunction = nullptr;
- m_iWaitSCFTimeOut = millisecond; // 如果子类不重新设置, 默认就是 0.2 秒
- }
- DiosConnect::~DiosConnect()
- {
- std::this_thread::sleep_for(100ms);
- Disconnect();
- }
- void DiosConnect::Prepare(std::string DllName)
- {
- assert(DllName.length());
- try {
- m_SCF = nsSCF::SCF::FromDLL(DllName.c_str());
- m_SCF.OnPassiveDisconnected = [this]()
- {
- this->m_NewPacket.Set();
- };
- m_SCF.Queue.OnNewPacket = [this]()
- {
- this->m_NewPacket.Set();
- };
- }
- catch (const std::exception& exp)
- {
- printf("get SCF err:%s",exp.what());
- }
- catch (...)
- {
- printf("get SCF Mould failed");
- }
- }
- bool DiosConnect::Connect(std::string strProfile, tPacketPredate Pr, _SCF_Transfertype TransferType, DWORD msTimeOut)
- {
- m_tConnectParam = strProfile;
- auto erCode = m_SCF.Connect(m_tConnectParam, Pr, SCF_PACKET_TRANSFER, 3000);
- if (erCode != SCF_ERR::SCF_SUCCEED)
- {
- return false;
- }
- return true;
- }
- bool DiosConnect::Run(tbDataFun Dequeue)
- {
- m_tbFunction = Dequeue;
- auto THReadPacket = [this]()
- {
- auto msWait = std::chrono::milliseconds(m_iWaitSCFTimeOut);
- while (true)
- {
- auto rc = m_NewPacket.Wait(msWait);
- if (!m_SCF.isConnected())
- return;
- if (!rc) continue; //等待超时
- if (!m_SCF.isConnected())
- return;
- while (true) //有数据到达, 全部读完, 然后等待下一个事件
- {
- if (!m_SCF.isConnected())
- return;
- if (m_SCF.Queue.isEmpty())
- break;
- char cMsg[CMD_LEN_MAX];
- memset(cMsg, 0, sizeof(cMsg));
- int PacketLength = CMD_LEN_MAX;
- int len = m_SCF.Queue.Dequeue(cMsg, PacketLength, 20);
- if (m_tbFunction != nullptr && len > 0)
- m_tbFunction(cMsg, len);
- }
- }
- };
- auto THFunc = [this, THReadPacket]()
- {
- THReadPacket();
- m_TID = decltype (m_TID) (); // ! 记得在这里复位 ThreadID
- };
- if (m_TID == decltype (m_TID) ())
- {
- auto TH = std::thread(THFunc);
- m_TID = TH.get_id();
- TH.detach();
- }
- m_SCF.DecodePack(isActDecodeFun);
- return true;
- }
- bool DiosConnect::DecodePack(bool action)
- {
- isActDecodeFun = action;
- return isActDecodeFun;
- }
- void DiosConnect::Disconnect()
- {
- m_SCF.Disconnect();
- m_NewPacket.Set();
- }
- bool DiosConnect::isConnected()
- {
- return m_SCF.isConnected();
- }
- bool DiosConnect::TryReconnect()
- {
- Disconnect();
- }
- }
|