// DIOS.Dev.GEN.DEMO.cpp : 定义 DLL 应用程序的导出函数。 // #include "stdafx.h" #include "FileVersion.hpp" #include "DIOS.Dev.SyncBoxe.DYN.h" #include "Helper.JSON.hpp" #include "CommonFun.h" // "SimpleLog.hpp" #include "common_api.h" //SimpleLog* g_SLogger = NULL; using namespace DIOS::Dev::Detail::SYNBOX; namespace nsSYN = DIOS::Dev::Detail::SYNBOX; #pragma warning (disable:4244) // warning C4244: “初始化”: 从“double”转换到“float”,可能丢失数据 #pragma warning (disable:4305) // warning C4305: “参数”: 从“double”到“float”截断 #pragma warning (disable:4267) // warning C4267 : “初始化”: 从“size_t”转换到“int”,可能丢失数据 #ifdef _WIN64 #ifdef _DEBUG static const auto COM_SCFDllName = "Dios.Dev.SerialSCFX64D.dll"; #else static const auto COM_SCFDllName = "Dios.Dev.SerialSCFX64.dll"; #endif #endif #ifdef _WIN64 #ifdef _DEBUG static const auto TCP_SCFDllName = "Dios.Dev.TcpipSCFX64D.dll"; #else static const auto TCP_SCFDllName = "Dios.Dev.TcpipSCFX64.dll"; #endif #endif using namespace DIOS::Dev::Detail::SYNBOX; namespace nsSYN = DIOS::Dev::Detail::SYNBOX; Log4CPP::Logger* mLog::gLogger = nullptr; ////----------------------------------------------------------------------------- //// DynBoxDevice ////----------------------------------------------------------------------------- nsSYN::SyncBoxDevice::SyncBoxDevice(std::shared_ptr center, nsSCF::SCF SCF) : super(center, SCF) { assert(EventCenter); m_DynBoxDevice.reset(new DynBoxDevice(center,SCF)); m_MSGUnit.reset(new nsDetail::MSGUnit(center, SyncConsoleUnitType)); m_CollimatorDevice.reset(new CollimatorDevice(center, SCF)); Register(); OnCallBack(); } nsSYN::SyncBoxDevice::~SyncBoxDevice() { } std::string nsSYN::SyncBoxDevice::GetGUID() const { mLog::Info("\n===============GetGUID : {$} ===================\n", SyncConsoleUnitType); return SyncConsoleUnitType; } void nsSYN::SyncBoxDevice::Register() { auto Disp = &Dispatch; m_DynBoxDevice->Register(Disp); auto fun_SimulateHandSwitchSignal = [this](auto in, auto& out) { string value[5]; ResDataObject json; mLog::Error("in [{$}]", in.c_str()); json.decode(in.c_str()); int paramCount = json.GetKeyCount("P0"); for (int i = 0; i < paramCount; i++) { value[i] = (const char*)json[i]; } return m_DynBoxDevice->SimulateHandSwitchSignal(value[0], atoi(value[1].c_str())); }; Disp->Action.Push("SimulateHandSwitchSignal", fun_SimulateHandSwitchSignal); m_CollimatorDevice->Register(Disp); Disp->Get.Push(m_MSGUnit->GetKey().c_str(), [this](std::string& out) { out = m_MSGUnit->JSGet(); return RET_STATUS::RET_SUCCEED; }); } void nsSYN::SyncBoxDevice::OnCallBack() { //m_DynBoxDevice->OnCallBack(); //m_CollimatorDevice->OnCallback(); auto HWNotProcess = [](const char* value, int length) -> void { mLog::Error("\n This commands didn't need to process!\n"); }; auto HWSignal = [this](const char* value, int length) { assert(value); char cChannelValue; cChannelValue = value[5]; //status : on /off string strChannel = ((string)value).substr(3, 2); bool bStatus = ChartoInt(cChannelValue); m_DynBoxDevice->DealtheSignal(strChannel.c_str(), bStatus); }; auto HWCAN = [this](const char* value, int length) -> void { string sCmdID = ((string)value).substr(8, 3); int nlen = ChartoInt(value[11]) * 256 + ChartoInt(value[12]); m_CollimatorDevice->DealReceiveData(sCmdID, &value[13], nlen); }; // 有部分前缀是包含关系, 长的包含短的, 例如 KVS 包含了 KV. // 因此长的在前面, 短的在后面 // !!! Device 是个短寿命对象, 而 arFrame 是静态变量 !!! // !!! 因此, 在添加到 arFrame 之前, 务必先清零 !!! arFrame.clear(); arFrame.push_back(tFrameMapping("SRA", 3, HWNotProcess)); arFrame.push_back(tFrameMapping("SEC", 3, HWNotProcess)); arFrame.push_back(tFrameMapping("SPT", 3, HWNotProcess)); arFrame.push_back(tFrameMapping("SRS", 3, HWNotProcess)); arFrame.push_back(tFrameMapping("SAI", 3, HWSignal)); arFrame.push_back(tFrameMapping("SWS", 3, HWSignal)); arFrame.push_back(tFrameMapping("SCR", 3, HWCAN)); arFrame.push_back(tFrameMapping("STL", 3, HWCAN)); } //V3新方法 void nsSYN::SyncBoxDevice::SubscribeSelf(dios_mqtt_connection* conn) { mLog::Debug("SubscribeSelf"); //订阅GEN所有Action if (nullptr != conn) { SubscribeTopic(conn, "DIOS/DEVICE/SyncBox/Action/#"); } else { mLog::Error("SubscribeSelf conn is empty"); } } //----------------------------------------------------------------------------- // DynBoxDriver //----------------------------------------------------------------------------- nsSYN::DynBoxDriver::DynBoxDriver () { m_bDemoMode = false; m_bDemoConnected = false; m_pAttribute.reset(new ResDataObject()); m_pDescription.reset(new ResDataObject()); #ifdef _WIN64 g_strAppPath = GetProcessDirectory() + R"(OEMDrivers\SyncBox\DYN\DIOS.Dev.SyncBoxe.DYN64.dll)"; #else g_strAppPath = GetProcessDirectory() + R"(OEMDrivers\SyncBox\DYN\DIOS.Dev.SyncBoxe.DYN.dll)"; #endif } nsSYN::DynBoxDriver::~DynBoxDriver () { } auto nsSYN::DynBoxDriver::CreateDevice (int index) -> std::unique_ptr { if (m_bDemoMode) { if (! m_bDemoConnected) return nullptr; auto dev = std::unique_ptr (new IODevice(new SyncBoxDevice(EventCenter, m_SCF))); return dev; } if (!m_SCF.isConnected()) return nullptr; ResDataObject r_config; //pSDCDevice = new nsSYN::DynBoxDevice(EventCenter,m_SCF); pSDCDevice=new SyncBoxDevice(EventCenter, m_SCF); //auto pSDCDevice = std::unique_ptr (new DynBoxDevice(EventCenter, m_SCF)); auto dev = std::unique_ptr (new IODevice(pSDCDevice)); if (r_config.loadFile(m_ConfigFileName.c_str())) { pSDCDevice->m_DynBoxDevice->ResDYNConfig = r_config["CONFIGURATION"]["DeviceConfig"]; pSDCDevice->m_DynBoxDevice->m_bSynUpdataGenerStatus = r_config["CONFIGURATION"]["SynUpdataGenerStatus"]; pSDCDevice->m_CollimatorDevice->ResDYNConfig = r_config["CONFIGURATION"]["DeviceConfig"]; //pSDCDevice->m_DynBoxDevice->m_DefaultExpFrameRate = r_config["CONFIGURATION"]["DefaultExpFrameRate"]; //pSDCDevice->m_DynBoxDevice->m_DefaultExpTimes = r_config["CONFIGURATION"]["DefaultExpTimes"]; try { pSDCDevice->m_DynBoxDevice->m_DefaultExpFrameRate = r_config["CONFIGURATION"]["DefaultExpFrameRate"]; } catch (ResDataObjectExption& e) { mLog::Error("Read DefaultExpFrameRate failed: {$}", e.what()); } try { pSDCDevice->m_DynBoxDevice->m_DefaultExpTimes = r_config["CONFIGURATION"]["DefaultExpTimes"]; } catch (ResDataObjectExption& e) { mLog::Error("Read DefaultExpTimes failed: {$}", e.what()); } } pSDCDevice->m_CollimatorDevice->SetCollimatorMode(6); return dev; } void nsSYN::DynBoxDriver::FireNotify (int code, std::string key, std::string content) { EventCenter->OnNotify (code, key, content); } void nsSYN::DynBoxDriver::Prepare () { string strLogPath = GetProcessDirectory() + R"(\OEMDrivers\SyncBox\Conf\Log4CPP.Config.SYN.xml)"; Log4CPP::GlobalContext::Map::Set(ECOM::Utility::Hash("LogFileName"), "SYN.DYN"); auto rc = Log4CPP::LogManager::LoadConfigFile(strLogPath.c_str()); if (!rc) { printf("\n Load log configfile failed!\n"); } mLog::gLogger = Log4CPP::LogManager::GetLogger("SYN.DYN"); ResDataObject r_config; if (r_config.loadFile (m_ConfigFileName.c_str ())) { m_bDemoMode = (atoi)(((string)r_config ["CONFIGURATION"] ["IsDemo"]).c_str ()); ResDataObject Connection = r_config ["CONFIGURATION"] ["connections"] [0]; if ((string)Connection ["type"] == "COM") m_SCFDllName = COM_SCFDllName; else m_SCFDllName = TCP_SCFDllName; } //add by wxx:自动获取版本号并更新到日志 string version; ResDataObject TempConfig = r_config["CONFIGURATION"]; if (GetVersion(version,TempConfig)) mLog::Info("--Func-- driver prepare : version:{$}\n", version.c_str()); else mLog::Info("--Func-- driver prepare, v1.0.0.1 \n"); super::Prepare (); } bool nsSYN::DynBoxDriver::Connect () { if (m_bDemoMode) { m_bDemoConnected = true; return true;// SCF_ERR::SCF_SUCCEED; } ResDataObject r_config; if (!r_config.loadFile(m_ConfigFileName.c_str())) return false;// SCF_ERR::SCF_OPEN_FAILED; ResDataObject Connection = r_config["CONFIGURATION"]["connections"][0]; mLog::Info("connections:{$} \n", Connection.encode()); auto erCode = m_SCF.Connect(Connection.encode(), &nsSYN::DynBoxDriver::callbackPackageProcess, SCF_PACKET_TRANSFER, 3000); if (erCode != SCF_ERR::SCF_SUCCEED) return false; // erCode; CanShakeHand(); Sleep(200); SetCANState(true);//open can auto rc = super::Connect(); if (!rc) return false;// 0; //return (erCode == SCF_ERR::SCF_SUCCEED); return true;// SCF_ERR::SCF_SUCCEED; } void nsSYN::DynBoxDriver::Disconnect() { super::Disconnect(); m_SCF.Disconnect(); m_bDemoConnected = false; } bool nsSYN::DynBoxDriver::isConnected() const { if (m_bDemoMode) return m_bDemoConnected; else return super::isConnected(); } std::string nsSYN::DynBoxDriver::DriverProbe () { ResDataObject r_config, HardwareInfo; if (r_config.loadFile (m_ConfigFileName.c_str ())) { HardwareInfo.add ("MajorID", r_config ["CONFIGURATION"] ["MajorID"]); HardwareInfo.add ("MinorID", r_config ["CONFIGURATION"] ["MinorID"]); HardwareInfo.add ("VendorID", r_config ["CONFIGURATION"] ["VendorID"]); HardwareInfo.add ("ProductID", r_config ["CONFIGURATION"] ["ProductID"]); HardwareInfo.add ("SerialID", r_config ["CONFIGURATION"] ["SerialID"]); } else { HardwareInfo.add("MajorID", "SYN"); HardwareInfo.add("MinorID", "Dr"); HardwareInfo.add("VendorID", "ECOM"); HardwareInfo.add("ProductID", "DYN"); HardwareInfo.add("SerialID", "1234"); } string ret = HardwareInfo.encode (); return ret; } bool nsSYN::DynBoxDriver::GetDeviceConfig(std::string& Cfg) { Cfg = m_DeviceConfig.encode(); printf("GetDeviceConfig over"); return true; } bool nsSYN::DynBoxDriver::SetDeviceConfig(std::string Cfg) { mLog::Info("--Func-- SetDeviceConfig {$}\n", Cfg.c_str()); ResDataObject DeviceConfig; DeviceConfig.decode(Cfg.c_str()); ResDataObject DescriptionTempEx; DescriptionTempEx = DeviceConfig["DeviceConfig"]["Attribute"]; mLog::Debug("Attribute:{$}", DescriptionTempEx.encode()); bool bSaveFile = false; //true:重新保存配置文件 string strAccess = ""; for (int i = 0; i < DescriptionTempEx.size(); i++) { string strKey = DescriptionTempEx.GetKey(i); mLog::Info("{$}", strKey.c_str()); try { if (m_pAttribute->GetFirstOf(strKey.c_str()) >= 0) { strAccess = (string)(*m_pDescription)[strKey.c_str()]["Access"]; if ("RW" == strAccess) { //修改对应配置,在其他单元的配置项要同时调用其修改函数修改真实值 //1. 修改内存中的值,用于给上层发消息 (*m_pAttribute)[strKey.c_str()] = DescriptionTempEx[i]; //2. 拿到Innerkey int nConfigInfoCount = (int)m_Configurations["ConfigToolInfo"].GetKeyCount("AttributeInfo"); mLog::Info("nConfigInfoCount {$}", nConfigInfoCount); string strTemp = ""; //存储AttributeKey for (int nInfoIndex = 0; nInfoIndex < nConfigInfoCount; nInfoIndex++) { strTemp = (string)m_Configurations["ConfigToolInfo"][nInfoIndex]["AttributeKey"]; if (strTemp == strKey) { strTemp = (string)m_Configurations["ConfigToolInfo"][nInfoIndex]["InnerKey"]; break; } } //3. 修改配置文件中的值 if (SetDeviceConfigValue(m_Configurations, strTemp.c_str(), 1, DescriptionTempEx[i])) { mLog::Debug("SetDeviceConfigValue over"); bSaveFile = true; } } else { mLog::Info("{$} is not a RW configuration item", strKey.c_str()); } } else { mLog::Info("without this attribute {$}", strKey.c_str()); } } catch (ResDataObjectExption& e) { mLog::Error("SetDriverConfig crashed: {$}", e.what()); return false; } } if (bSaveFile) { //3. 重新保存配置文件 SaveConfigFile(true); } return true; } bool nsSYN::DynBoxDriver::SaveConfigFile(bool bSendNotify) { m_ConfigAll["CONFIGURATION"] = m_Configurations; bool bRt = m_ConfigAll.SaveFile(m_ConfigFileName.c_str()); mLog::Info("SaveConfigFile over {$}", bRt); return true; } bool nsSYN::DynBoxDriver::GetDeviceConfigValue(ResDataObject config, const char* pInnerKey, int nPathID, string& strValue) { strValue = ""; string strTemp = pInnerKey; if (1 == nPathID) //从DriverConfig路径下每个DPC自己的配置文件读取 { int pos = 0; ResDataObject resTemp = config; while ((pos = strTemp.find_first_of(',')) != string::npos) { string Key = strTemp.substr(0, pos); string TempValue = resTemp[Key.c_str()].encode(); resTemp.clear(); resTemp.decode(TempValue.c_str()); strTemp = strTemp.substr(pos + 1, strTemp.length() - pos - 1); } if (strTemp != "") { strValue = (string)resTemp[strTemp.c_str()]; } else { strValue = (string)resTemp; } } return true; } bool nsSYN::DynBoxDriver::SetDeviceConfigValue(ResDataObject& config, const char* pInnerKey, int nPathID, const char* szValue) { string strTemp = pInnerKey; mLog::Debug("Begin to change {$} item value to {$}", pInnerKey, szValue); if (1 == nPathID) //从DriverConfig路径下每个DPC自己的配置文件读取 { try { int pos = 0; ResDataObject* resTemp = &config; while ((pos = strTemp.find_first_of(',')) != string::npos) { string Key = strTemp.substr(0, pos); resTemp = &(*resTemp)[Key.c_str()]; strTemp = strTemp.substr(pos + 1, strTemp.length() - pos - 1); } if (strTemp != "") { (*resTemp)[strTemp.c_str()] = szValue; } else { *resTemp = szValue; } } catch (ResDataObjectExption& e) { mLog::Error("SetDriverConfigvalue crashed: {$}", e.what()); return false; } } return true; } std::string nsSYN::DynBoxDriver::GetResource() { ResDataObject r_config, temp; if (!temp.loadFile(m_ConfigFileName.c_str())) { return ""; } m_ConfigAll = temp; r_config = temp["CONFIGURATION"]; m_Configurations = r_config; ResDataObject DescriptionTemp; ResDataObject ListTemp; string strTemp = ""; //用于读取字符串配置信息 string strIndex = ""; //用于读取配置信息中的List项 int nTemp = -1; //用于读取整型配置信息 char sstream[10] = { 0 }; //用于转换值 string strValue = ""; //用于存储配置的值 string strType = ""; //用于存储配置的类型 int/float/string... /*** * 1. 通过循环,将所有配置项写到pDeviceConfig * 2. 记录配置项的内部key以及配置类型,类型对应了不同配置文件路径,用于读写真实值 ***/ try { int nConfigInfoCount = (int)m_Configurations["ConfigToolInfo"].GetKeyCount("AttributeInfo"); //mLog::Info(g_pFPDCtrlLog, "ConfigInfo Count: {$}", nConfigInfoCount); m_pAttribute->clear(); m_pDescription->clear(); for (int nInfoIndex = 0; nInfoIndex < nConfigInfoCount; nInfoIndex++) { DescriptionTemp.clear(); ListTemp.clear(); //AttributeType strTemp = (string)m_Configurations["ConfigToolInfo"][nInfoIndex]["AttributeDescripition"]["Type"]; DescriptionTemp.add(ConfKey::AttributeType, strTemp.c_str()); //DescriptionTemp= m_Configurations["ConfigToolInfo"][nInfoIndex]["AttributeDescripition"]; //mLog::Info(g_pFPDCtrlLog, "--> {$}: {$}", AttributeType, strTemp.c_str()); strType = strTemp; //记录配置项的类型 //AttributeKey //1. 根据AttributeType,内部key和配置路径,拿到当前的真实值 strTemp = (string)m_Configurations["ConfigToolInfo"][nInfoIndex]["InnerKey"]; nTemp = (int)m_Configurations["ConfigToolInfo"][nInfoIndex]["PathID"]; GetDeviceConfigValue(r_config, strTemp.c_str(), nTemp, strValue); //2. 赋值 strTemp = (string)m_Configurations["ConfigToolInfo"][nInfoIndex]["AttributeKey"]; if ("int" == strType) { (*m_pAttribute).add(strTemp.c_str(), atoi(strValue.c_str())); //mLog::Info(g_pFPDCtrlLog, "Key {$}: {$}", strTemp.c_str(), atoi(strValue.c_str())); } else if ("float" == strType) { (*m_pAttribute).add(strTemp.c_str(), atof(strValue.c_str())); //mLog::Info(g_pFPDCtrlLog, "Key {$}: {$}", strTemp.c_str(), atof(strValue.c_str())); } else //其它先按string类型处理 { (*m_pAttribute).add(strTemp.c_str(), strValue.c_str()); //mLog::Info(g_pFPDCtrlLog, "Key {$}: {$}", strTemp.c_str(), strValue.c_str()); } //AttributeAccess strTemp = (string)m_Configurations["ConfigToolInfo"][nInfoIndex]["AttributeDescripition"]["Access"]; DescriptionTemp.add(ConfKey::AttributeAccess, strTemp.c_str()); //mLog::Info(g_pFPDCtrlLog, "{$}: {$}", AttributeAccess, strTemp.c_str()); //AttributeRangeMin strTemp = (string)m_Configurations["ConfigToolInfo"][nInfoIndex]["AttributeDescripition"]["RangeMin"]; if (strTemp != "") //不需要的配置项为空 { DescriptionTemp.add(ConfKey::AttributeRangeMin, strTemp.c_str()); //mLog::Info(g_pFPDCtrlLog, "{$}: {$}", AttributeRangeMin, strTemp.c_str()); } //AttributeRangeMax strTemp = (string)m_Configurations["ConfigToolInfo"][nInfoIndex]["AttributeDescripition"]["RangeMax"]; if (strTemp != "") //不需要的配置项为空 { DescriptionTemp.add(ConfKey::AttributeRangeMax, strTemp.c_str()); //mLog::Info(g_pFPDCtrlLog, "{$}: {$}", AttributeRangeMax, strTemp.c_str()); } //AttributeList nTemp = m_Configurations["ConfigToolInfo"][nInfoIndex]["AttributeDescripition"]["ListNum"]; if (nTemp > 0) //ListNum不大于0时说明不需要list配置 { for (int nListIndex = 0; nListIndex < nTemp; nListIndex++) { strTemp = (string)m_Configurations["ConfigToolInfo"][nInfoIndex]["AttributeDescripition"]["ListInfo"][nListIndex]; //sprintf_s(sstream, "{$}", nListIndex); auto temKey = std::to_string(nListIndex); ListTemp.add(temKey.c_str(), strTemp.c_str()); //mLog::Info(g_pFPDCtrlLog, "list {$}: {$}", nListIndex, strTemp.c_str()); } DescriptionTemp.add(ConfKey::AttributeList, ListTemp.encode()); } //AttributeRequired strTemp = (string)m_Configurations["ConfigToolInfo"][nInfoIndex]["AttributeDescripition"]["Required"]; DescriptionTemp.add(ConfKey::AttributeRequired, strTemp.c_str()); //mLog::Info(g_pFPDCtrlLog, "{$}: {$}", AttributeRequired, strTemp.c_str()); //AttributeDefaultValue strTemp = (string)m_Configurations["ConfigToolInfo"][nInfoIndex]["AttributeDescripition"]["DefaultValue"]; if (strTemp != "") //不需要的配置项为空 { DescriptionTemp.add(ConfKey::AttributeDefaultValue, strTemp.c_str()); //mLog::Info(g_pFPDCtrlLog, "{$}: {$}", AttributeDefaultValue, strTemp.c_str()); } strTemp = (string)m_Configurations["ConfigToolInfo"][nInfoIndex]["AttributeKey"]; (*m_pDescription).add(strTemp.c_str(), DescriptionTemp); } } catch (ResDataObjectExption& e) { mLog::Error("Get config error: {$}", e.what()); return ""; } ResDataObject resDeviceResource; resDeviceResource.add(ConfKey::DiosAttribute, (*m_pAttribute)); resDeviceResource.add(ConfKey::DiosDescription, (*m_pDescription)); ResDataObject DescriptionTempEx; DescriptionTempEx.add(ConfKey::DiosConfig, resDeviceResource); m_DeviceConfig.clear(); m_DeviceConfig = DescriptionTempEx; string res = DescriptionTempEx.encode(); //mLog::Debug("get resource over {$}", DescriptionTempEx.encode()); //printf("get resource over : %s \n", DescriptionTempEx.encode()); return res; } //std::string nsSYN::DynBoxDriver::GetResource () //{ // ResDataObject temp; // if (!temp.loadFile (m_ConfigFileName.c_str ())) // return std::string (); // // auto r_config = temp ["CONFIGURATION"]; // for (auto &Item : m_ConfigInfo) // { // string key = Item.GetKey (); // if (key == ConfKey::DiosType) // { // Item.SetCurrentValue (((string)r_config ["VendorID"]).c_str ()); // } // else if (key == ConfKey::DiosModel) // { // Item.SetCurrentValue (((string)r_config ["ProductID"]).c_str ()); // } // else if (key == ConfKey::DiosSCFType) // { // Item.SetCurrentValue (((string)r_config ["connections"] [0] ["type"]).c_str ()); // } // else if (key == ConfKey::DiosSCFPort || key == ConfKey::DiosSCFBaudrate || key == ConfKey::DiosSCFBytesize // || key == ConfKey::DiosSCFParity || key == ConfKey::DiosSCFStopbits || key == ConfKey::DiosSCFIP) // { // if (r_config ["connections"] [0].GetFirstOf (key.c_str ()) >= 0) // { // Item.SetCurrentValue (((string)r_config ["connections"] [0] [key.c_str ()]).c_str ()); // } // } // } // ResDataObject resAttr, resDescription; // for (auto Item : m_ConfigInfo) // { // resAttr.add (Item.GetKey (), Item.GetCurrentValue ()); // resDescription.add (Item.GetKey (), Item.GetDescription ()); // } // ResDataObject resDeviceResource; // resDeviceResource.add (ConfKey::DiosAttribute, resAttr); // resDeviceResource.add (ConfKey::DiosDescription, resDescription); // m_DeviceConfig = resDeviceResource; // string res = resDeviceResource.encode (); // mLog::Info("resDeviceResource :{$} \n", resDeviceResource.encode ()); // return res; //} std::string nsSYN::DynBoxDriver::DeviceProbe () { ResDataObject r_config, HardwareInfo; if (r_config.loadFile (m_ConfigFileName.c_str ())) { HardwareInfo.add ("MajorID", r_config ["CONFIGURATION"] ["MajorID"]); HardwareInfo.add ("MinorID", r_config ["CONFIGURATION"] ["MinorID"]); HardwareInfo.add ("VendorID", r_config ["CONFIGURATION"] ["VendorID"]); HardwareInfo.add ("ProductID", r_config ["CONFIGURATION"] ["ProductID"]); HardwareInfo.add ("SerialID", r_config ["CONFIGURATION"] ["SerialID"]); } else { HardwareInfo.add ("MajorID", "SYN"); HardwareInfo.add ("MinorID", "Dr"); HardwareInfo.add ("VendorID", "ECOM"); HardwareInfo.add ("ProductID", "DYN"); HardwareInfo.add ("SerialID", "1234"); } string ret = HardwareInfo.encode (); return ret; } void nsSYN::DynBoxDriver::Dequeue (const char * Packet, DWORD Length) { DecodeFrame (Packet, Length); } PACKET_RET nsSYN::DynBoxDriver::callbackPackageProcess (const char * RecData, DWORD nLength, DWORD& PacketLength) { //判断是否是整包 /* 这个是回调函数,我收到的数据会需要这个回调函数帮我判断是否是整个的包; 如果有整个的包,返回值为true,在PacketLength处返回给我整个包的长度,我再截取后放入缓存供上层使用; 如果缓存中的数据没有整个的数据包,那么返回false */ if (nLength < 1) { mLog::Error("nLength < 1, nLength=={$} \n", nLength); return PACKET_USELESS; } for (DWORD i = 0; i < nLength - 1; i++) { if (RecData [i] == 0x0d && RecData [i + 1] == 0x0a) { PacketLength = i + 2; char strtemp [100] = { 0 }; memcpy (strtemp, RecData, i); strtemp [PacketLength + 1] = 0; mLog::Info("==IN ==:{$}\n", strtemp); //printf("==IN(Hex) ==:"); //for (int j = 0; j < i; j++) //{ // printf("%02X ", RecData[j]); //} //printf("\n"); return PACKET_ISPACKET; } else if (RecData [i] == 0x03) { mLog::Error("(Hex)0x03 ,len={$} \n", i); PacketLength = i + 1; return PACKET_USELESS; } } return PACKET_NOPACKET; } //----------------------------------------------------------------------------- // //----------------------------------------------------------------------------- void nsSYN::DynBoxDriver::CanShakeHand() { int nTimeout = 100; char cCmd[MAX_COMMAND_LEN] = "SECA00"; int nCmdSize = 6; FormatCmd(cCmd, nCmdSize); string strLog; CmdtoString(cCmd, nCmdSize, strLog); mLog::Info( "[Send:{$}]", strLog.c_str()); mLog::Info("CanShakeHand ==OUT==: {$} \n", cCmd); int ret = 0; m_SCF.Lock(msTimeOut_Lock) .SendPacket(cCmd, nCmdSize, nTimeout, ret); Sleep(nTimeout); } void nsSYN::DynBoxDriver::SetCANState(bool state) { int nTimeout = 100; ResDataObject r_config; if (!r_config.loadFile(m_ConfigFileName.c_str())) return; ResDataObject ResDYNConfig = r_config["CONFIGURATION"]["DeviceConfig"]; char cCmd[MAX_COMMAND_LEN] = "SCSA13"; string CANProtocol = (string)ResDYNConfig["CANPortocol"]; string CANBaud = (string)ResDYNConfig["CANBaud"]; string CANEnable; if (state) { CANEnable = "1"; mLog::Info( "OpenCAN"); } else { CANEnable = "0"; mLog::Info( "CloseCAN"); } string CANFilter = (string)ResDYNConfig["CANFilter"]; vector vecFilter; if (!CANFilter.empty()) { while (!CANFilter.empty()) { string strTemp = GetContentFromString(CANFilter, ','); vecFilter.push_back(String2Hex(strTemp)); } } INT32 nIDS = 0, nFilter = 0; int nSize = vecFilter.size(); if (nSize > 0) { //int nIDStemp = vecFilter[0], nFiltertemp = vecFilter[0]; int nIDStemp = 0xFFFFFFFF, nFiltertemp = 0xFFFFFFFF; for (int n = 0; n < nSize; n++) { nIDStemp &= vecFilter[n]; } if (nSize > 1) { nFiltertemp = 0; const int num = 11; int ntem[num]; for (int m = 0; m < num; m++) { ntem[m] = 1; int nvalue = (vecFilter[0] >> (num - 1 - m)) & 0x01; for (int l = 1; l < nSize; l++) { if (nvalue != ((vecFilter[l] >> (num - 1 - m)) & 0x01)) { ntem[m] = 0; break; } } nFiltertemp += (ntem[m] << (num - 1 - m)); } } nIDS = nIDStemp << 21; nFilter = (nFiltertemp) << 21; } string strtemp; char cFilter[16]; for (int i = 0; i < 8; i++) { int nres = ((nIDS & (0xF << ((7 - i) * 4))) >> ((7 - i) * 4)) & 0x0F; if (nres > 9) { cFilter[i] = char(0x30 + nres + 7); } else { cFilter[i] = char(0x30 + nres); } } for (int i = 0; i < 8; i++) { int nres = ((nFilter & (0xF << ((7 - i) * 4))) >> ((7 - i) * 4)) & 0x0F; if (nres > 9) { cFilter[i + 8] = char(0x30 + nres + 7); } else { cFilter[i + 8] = char(0x30 + nres); } } cCmd[6] = CANProtocol[0]; cCmd[7] = CANBaud[0]; for (int i = 0; i < 16; i++) { cCmd[8 + i] = cFilter[i]; //cCmd[8 + i] = '0'; } cCmd[24] = CANEnable[0]; int nCmdSize = 25; FormatCmd(cCmd, nCmdSize); string strLog; CmdtoString(cCmd, nCmdSize, strLog); mLog::Info( "[Send:{$}]", strLog.c_str()); mLog::Info("==OUT==: {$} \n", cCmd); int ret = 0; m_SCF.Lock(msTimeOut_Lock) .SendPacket(cCmd, nCmdSize, nTimeout, ret); Sleep(nTimeout); } //----------------------------------------------------------------------------- // GetIODriver & CreateIODriver //----------------------------------------------------------------------------- static nsSYN::DynBoxDriver gIODriver; extern "C" DIOS::Dev::IODriver * __cdecl GetIODriver () // 返回静态对象的引用, 调用者不能删除 ! { return &gIODriver; } extern "C" DIOS::Dev::IODriver * __cdecl CreateIODriver () // 返回新对象, 调用者必须自行删除此对象 ! { return new nsSYN::DynBoxDriver (); }