CCOS.Dev.Generator.PSG_HD.cpp 67 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171
  1. // CCOS.Dev.GEN.PSGHD.cpp : 定义 DLL 应用程序的导出函数。
  2. #include <assert.h>
  3. #include <functional>
  4. #include <unordered_map>
  5. #include <fstream>
  6. #include <cmath>
  7. #include <climits>
  8. #include <unordered_set>
  9. #include <algorithm>
  10. #include "LogicDevice.h"
  11. using namespace std::placeholders;
  12. #include "LogLocalHelper.h"
  13. #include "Log4CPP.h"
  14. #include "Helper.JSON.hpp"
  15. #include "CCOS.Dev.Generator.PSG_HD.h"
  16. using namespace CCOS::Dev::Detail::Generator;
  17. namespace nsGEN = CCOS::Dev::Detail::Generator;
  18. const uint8_t STX = 0x02, CR = 0x0D, LF = 0x0A;
  19. const char TERM = ';';
  20. static nsGEN::PSGHDDriver* pIODriver = nullptr;
  21. #define PSGHD_LARGE_POWER 5
  22. #define PSGHD_SMALL_POWER 1.1
  23. #define PSGHD_MAX_HEAT 225
  24. #define PSGHD_MIN_MA 1.0
  25. #define PSGHD_MAX_MA 1000.0
  26. #define PSGHD_MIN_MS 1.0
  27. #define PSGHD_MAX_MS 10001.0
  28. //设置相关常量
  29. #define PSGHD_LoopDefHBTime 1000
  30. #define PSGHD_LoopExpHBTime 500
  31. static const int msTimeOut_Lock = 500; //通讯接口锁定时间
  32. #define PSGHD_Com_NormalLen 150
  33. #define PSGHD_ETX 0x03
  34. #define PSGHD_RESOK "$"
  35. #define Sleep(ms) std::this_thread::sleep_for(std::chrono::milliseconds(ms))
  36. static const auto COM_SCFDllName = "libSerialSCF.so";
  37. static const auto TCP_SCFDllName = "libTcpipSCF.so";
  38. static const float msSteps[] = {
  39. 100, 120, 160, 200, 250, 320, 400, 500, 630, 800,
  40. 1000, 1250, 1600, 2000
  41. };
  42. static const float maSteps[] = {
  43. 1.00f, 1.25f, 1.6f, 2.00f, 2.50f, 3.00f
  44. };
  45. static const size_t msStepCount = sizeof(msSteps) / sizeof(msSteps[0]);
  46. static const size_t maStepCount = sizeof(maSteps) / sizeof(maSteps[0]);
  47. //Log4CPP::Logger* gLogger = nullptr;
  48. struct tFrameMapping
  49. {
  50. static const int MaxLen = 7; // 前缀不能超过 7 个字符 !
  51. using cbFun = std::function <void(const char*, int)>;
  52. char strHead[MaxLen];
  53. int NbOfCharOfHead;
  54. cbFun fun;
  55. // 关键修改:将char*改为const char*,兼容字符串常量
  56. tFrameMapping(const char* str, int len, cbFun f)
  57. {
  58. assert(len < MaxLen); // len最大只能是4
  59. for (int i = 0; i < len; i++)
  60. strHead[i] = str[i];
  61. NbOfCharOfHead = len;
  62. fun = f;
  63. }
  64. };
  65. // 响应操作对照表
  66. static std::list <tFrameMapping> arFrame;
  67. static bool DecodeFrame(const char* data, int len) {
  68. if (!data || len < 8) {
  69. FINFO("DecodeFrame: Invalid input");
  70. return false;
  71. }
  72. int pos = 0;
  73. bool hasValid = false;
  74. while (pos < len) {
  75. while (pos < len && (uint8_t)data[pos] != STX) pos++;
  76. if (pos >= len) {
  77. FINFO("DecodeFrame: No STX found");
  78. break;
  79. }
  80. int start = pos;
  81. int end = -1;
  82. for (int i = start + 1; i < len - 1; i++) {
  83. if ((uint8_t)data[i] == CR && (uint8_t)data[i + 1] == LF) {
  84. end = i + 1;
  85. break;
  86. }
  87. }
  88. if (end == -1) {
  89. FINFO("DecodeFrame: Incomplete cmd (no CRLF)");
  90. break;
  91. }
  92. int cmdLen = end - start + 1;
  93. auto match = [&](const tFrameMapping& item) {
  94. if (item.NbOfCharOfHead >= cmdLen) return false;
  95. for (int i = 0; i < item.NbOfCharOfHead; i++) {
  96. if (data[start + 1 + i] != item.strHead[i]) return false;
  97. }
  98. return true;
  99. };
  100. auto it = std::find_if(arFrame.begin(), arFrame.end(), match);
  101. if (it != arFrame.end()) {
  102. // Extract ARG (between header and ';')
  103. int argStart = start + 1 + it->NbOfCharOfHead;
  104. int argEnd = -1;
  105. for (int i = argStart; i < end; i++) {
  106. if (data[i] == TERM) {
  107. argEnd = i;
  108. break;
  109. }
  110. }
  111. if (argEnd > argStart) {
  112. it->fun(data + argStart, argEnd - argStart);
  113. FINFO("DecodeFrame: Parsed cmd: [{$}], ARG len: {$}", it->strHead, argEnd - argStart);
  114. hasValid = true;
  115. }
  116. else FINFO("DecodeFrame: Cmd missing ';'");
  117. }
  118. else FINFO("DecodeFrame: No matching header");
  119. pos = end + 1; // Next cmd start
  120. }
  121. return hasValid;
  122. }
  123. //-----------------------------------------------------------------------------
  124. // PSGHDDevice
  125. //-----------------------------------------------------------------------------
  126. atomic<int> nsGEN::PSGHDDevice::m_iLoopTime = PSGHD_LoopDefHBTime;
  127. atomic<bool> nsGEN::PSGHDDevice::m_bExtraFlag = false;
  128. nsGEN::PSGHDDevice::PSGHDDevice(std::shared_ptr <IOEventCenter> center, std::shared_ptr<SCFWrapper> SCF, string configfile)
  129. : super(center)
  130. , superGen()
  131. ,m_SCF(SCF)
  132. , m_bConnectFlag(false)
  133. {
  134. m_bExtraFlag = true;
  135. //初始化
  136. m_bExpEnable = false;
  137. m_iLoopTime.store(PSGHD_LoopDefHBTime);
  138. for (int i = 0; i < 18; i++)
  139. {
  140. m_bFaultList[i] = false;
  141. }
  142. m_iMaxPower = PSGHD_LARGE_POWER; //KW
  143. MaxHeatContent = PSGHD_MAX_HEAT; //KJ
  144. FINFO("\n===============log begin : version:0.0.0.0 ===================\n");
  145. //设置发生器属性集合各个值的范围及精度
  146. m_DoseUnit.m_KV.reset(new KVMould(0.0, 39.0, 151.0, 1.0));
  147. m_DoseUnit.m_MA.reset(new MAMould(0.0, PSGHD_MIN_MA, PSGHD_MAX_MA, 0.1));
  148. m_DoseUnit.m_MS.reset(new MSMould(0.0, PSGHD_MIN_MS, PSGHD_MAX_MS, 0.01));
  149. m_DoseUnit.m_MAS.reset(new MASMould(0.0, 0.1, 1000.0, 0.01));
  150. m_DoseUnit.m_Techmode.reset(new TECHMODEMould(AttrKey::TECHMODE_TYPE::TECHMODE_NOAEC_2P, AttrKey::TECHMODE_NOAEC_3P, AttrKey::TECHMODE_AEC_MAS_MA, 1));
  151. m_DoseUnit.m_WS.reset(new WORKSTATIONMould(1, 0, 5, 1));
  152. m_DoseUnit.m_Focus.reset(new FOCUSMould(AttrKey::FOCUS_TYPE::FOCUS_LARGE, AttrKey::FOCUS_SMALL, AttrKey::FOCUS_LARGE, 1));
  153. m_DoseUnit.m_AECField.reset(new AECFIELDMould(0, 0, 111, 1));
  154. m_DoseUnit.m_AECFilm.reset(new AECFILMMould(0, 0, 2, 1));
  155. m_DoseUnit.m_AECDensity.reset(new AECDENSITYMould(0, -3, 3, 1));
  156. m_DoseUnit.m_GenHE.reset(new GENHEATMould(0, 0, 100, 1));
  157. m_DoseUnit.m_HE.reset(new TUBEHEATMould(0, 0, 100, 1));
  158. m_DoseUnit.m_GenSynState.reset(new GENSYNSTATEMould(AttrKey::GENERATOR_RAD_OFF, AttrKey::GENERATOR_SYNC_ERR, AttrKey::GENERATOR_SYNC_MAX, 1));
  159. m_DoseUnit.m_GenState.reset(new GENSTATEMould(0, AttrKey::GENERATOR_STATUS_SHUTDOWN, AttrKey::GENERATOR_STATUS_MAX, 1));
  160. m_DoseUnit.m_GenTotalExpNumber.reset(new TOTALEXPNUMMould(0, 0, 9999, 1));
  161. m_DoseUnit.m_GenTotalAcqTimes.reset(new TOTALACQTIMESMould(0, 0, 9999, 1));
  162. m_DoseUnit.m_GenTubeCoolWaitTimes.reset(new TUBECOOLTIMEMould(0, 0, 9999, 1));
  163. m_DoseUnit.m_GenTubeOverLoadNumber.reset(new TUBEOVERLOADNUMMould(0, 0, 9999, 1));
  164. m_DoseUnit.m_GenCurrentExpNumber.reset(new CUREXPNUMMould(0, 0, 9999, 1));
  165. m_DoseUnit.m_ExpMode.reset(new EXPMODEMould(AttrKey::EXPMODE_TYPE::Single));
  166. m_DoseUnit.m_FrameRate.reset(new FRAMERATEMould(0, 0, 16, 1));
  167. m_DoseUnit.m_FLMode.reset(new FLUModeMould(AttrKey::GENERATOR_FLUMode::GENERATOR_FLMODE_NOTFLU));
  168. m_DoseUnit.m_BatteryChargeState.reset(new BATTERYCHARGSTATEMould(0, 0, 1, 1));
  169. m_DoseUnit.m_TubeTargetMaterial.reset(new TUBETARGETMATERIALMould(AttrKey::TUBETARGETMATERIAL_TYPE::MO));
  170. m_DoseUnit.m_TubeAngle.reset(new TUBEANGLEMould(0, -45, 45, 1));
  171. m_DoseUnit.m_FLIntTime.reset(new FLUIntTimeMould(0.0, 0.0, 100.0, 0.1));
  172. m_DoseUnit.m_FLAccTime.reset(new FLAccTimeMould(0.0, 0.0, 999.0, 0.1));
  173. m_DoseUnit.m_FLKV.reset(new FLUKVMould(0, 40, 125, 1));
  174. m_DoseUnit.m_FLMS.reset(new FLUMSMould(10.0, 10.0, 999999.0, 0.01));
  175. m_DoseUnit.m_FLMA.reset(new FLUMAMould(0.5, 0.5, 99.0, 0.1));
  176. m_DoseUnit.m_ABSStatus.reset(new FLUABSStatusMould(0, 0, 2, 1));
  177. m_DoseUnit.m_PPS.reset(new PPSMould(0.5,0.5, 30, 0.1));
  178. m_DoseUnit.m_DoseLevel.reset(new FLUDoseLevelMould(0, 0, 2, 1));
  179. m_DoseUnit.m_FLMode.reset(new FLUModeMould(0, 0, 4, 1));
  180. m_DoseUnit.m_Curve.reset(new FLUCurveMould(0, 0, 3, 1));
  181. //Actual exposure parameters 值
  182. m_DoseUnit.m_PostKV.reset(new POSTKVMould(0.0, 40.0, 120.0, 1.0));
  183. m_DoseUnit.m_PostMA.reset(new POSTMAMould(0.0, 1.0, 1000.0, 0.1));
  184. m_DoseUnit.m_PostMS.reset(new POSTMSMould(0.0, 1.0, 10000.0, 0.01));
  185. m_DoseUnit.m_PostMAS.reset(new POSTMASMould(0.0, 0.5, 1000.0, 0.01));
  186. //发生器告警及错误消息
  187. m_MSGUnit.reset(new nsDetail::MSGUnit(center, nsGEN::GeneratorUnitType));
  188. m_hGenPostEvent = LinuxEvent::CreateEvent(LinuxEvent::MANUAL_RESET, false);
  189. //配置响应操作对照表 供发生器回传的数据触发相应的操作
  190. OnCallBack();
  191. //将发生器可以对外提供的指令注册集进行补充
  192. Register();
  193. LoadConfig(configfile);
  194. //启动硬件状态轮询进程
  195. StartHardwareStatusThread();
  196. }
  197. nsGEN::PSGHDDevice::~PSGHDDevice()
  198. {
  199. m_bExtraFlag = false;
  200. if (m_pHardwareStatusThread.joinable()) {
  201. m_pHardwareStatusThread.join();
  202. }
  203. FINFO("\n===============log end ===================\n");
  204. arFrame.clear();
  205. }
  206. std::string nsGEN::PSGHDDevice::GetGUID() const
  207. {
  208. FINFO("===============GetGUID : {$} ===================\n", GeneratorUnitType);
  209. return GeneratorUnitType;
  210. }
  211. void nsGEN::PSGHDDevice::Register()
  212. {
  213. auto Disp = m_Dispatch.Lock().As();
  214. superGen::Register(Disp);
  215. superGen::RegisterRAD(Disp);
  216. superGen::RegisterAEC(Disp);
  217. superGen::RegisterExpEnable(Disp);
  218. superGen::RegisterGeneratortoSyncStatus(Disp);
  219. superGen::RegisterFluoro(Disp);
  220. Disp->Get.Push(m_MSGUnit->GetKey().c_str(), [this](std::string& out) { out = m_MSGUnit->JSGet(); return RET_STATUS::RET_SUCCEED; });
  221. Disp->Get.Push(AttrKey::DENHEAT, [this](std::string& out) { out = m_DoseUnit.m_GenHE->JSGet(); return RET_STATUS::RET_SUCCEED; });
  222. auto fun_Clear_DAP = [this](auto in, auto& out)
  223. {
  224. return Clear_DAP();
  225. };
  226. Disp->Action.Push("Clear_DAP", fun_Clear_DAP);
  227. auto fun_GetValue_DAP = [this](auto in, auto& out)
  228. {
  229. float value = 0;
  230. RET_STATUS ret = GetValue_DAP(value);
  231. out = ToJSON(value);
  232. return ret;
  233. };
  234. Disp->Action.Push("GetValue_DAP", fun_GetValue_DAP);
  235. }
  236. RET_STATUS nsGEN::PSGHDDevice::IncKV()
  237. {
  238. FINFO("Enter PSGHDDevice::IncKV()\n");
  239. if (!m_DoseUnit.m_KV->CanInc()) return RET_STATUS::RET_SUCCEED;
  240. m_DoseUnit.m_KV->Inc();
  241. return SetKV(m_DoseUnit.m_KV->Get());
  242. }
  243. RET_STATUS nsGEN::PSGHDDevice::DecKV()
  244. {
  245. if (!m_DoseUnit.m_KV->CanDec()) return RET_STATUS::RET_SUCCEED;
  246. m_DoseUnit.m_KV->Dec();
  247. return SetKV(m_DoseUnit.m_KV->Get());
  248. }
  249. RET_STATUS nsGEN::PSGHDDevice::SetKV(float value)
  250. {
  251. if (!m_DoseUnit.m_KV->Verify(value)) return RET_STATUS::RET_SUCCEED;
  252. char temp[50] = { 0 };
  253. int kvValue = (int)(value * 10); // 转换为协议单位(100V)
  254. snprintf(temp, sizeof(temp), "VREF %04d", kvValue);
  255. return HWSend(temp, strlen(temp));
  256. }
  257. RET_STATUS nsGEN::PSGHDDevice::IncMA()
  258. {
  259. float currentMA = m_DoseUnit.m_MA->Get();
  260. // 查找当前值在档位中的位置
  261. size_t currentIndex = maStepCount;
  262. for (size_t i = 0; i < maStepCount; ++i) {
  263. if (fabs(maSteps[i] - currentMA) < 1e-6f) {
  264. currentIndex = i;
  265. break;
  266. }
  267. }
  268. if (currentIndex >= maStepCount - 1) {
  269. return RET_STATUS::RET_SUCCEED; // 已经是最大值
  270. }
  271. return SetMA(maSteps[currentIndex + 1]);
  272. }
  273. RET_STATUS nsGEN::PSGHDDevice::DecMA()
  274. {
  275. float currentMA = m_DoseUnit.m_MA->Get();
  276. // 查找当前值在档位中的位置
  277. size_t currentIndex = maStepCount;
  278. for (size_t i = 0; i < maStepCount; ++i) {
  279. if (fabs(maSteps[i] - currentMA) < 1e-6f) {
  280. currentIndex = i;
  281. break;
  282. }
  283. }
  284. if (currentIndex == 0 || currentIndex >= maStepCount) {
  285. return RET_STATUS::RET_SUCCEED; // 已经是最小值或无效值
  286. }
  287. return SetMA(maSteps[currentIndex - 1]);
  288. }
  289. RET_STATUS nsGEN::PSGHDDevice::SetMA(float value)
  290. {
  291. // 找到最接近的合法档位值
  292. size_t closestIndex = 0;
  293. float minDiff = fabsf(maSteps[0] - value);
  294. for (size_t i = 1; i < maStepCount; ++i) {
  295. float diff = fabsf(maSteps[i] - value);
  296. if (diff < minDiff) {
  297. minDiff = diff;
  298. closestIndex = i;
  299. }
  300. }
  301. // 转换为协议单位并发送命令
  302. char command[50] = { 0 };
  303. snprintf(command, sizeof(command), "IREF %04d", (int)(maSteps[closestIndex] * 100));
  304. return HWSend(command, strlen(command));
  305. }
  306. RET_STATUS nsGEN::PSGHDDevice::IncMS()
  307. {
  308. float currentMS = m_DoseUnit.m_MS->Get();
  309. // 查找当前值在档位中的位置
  310. size_t currentIndex = msStepCount;
  311. for (size_t i = 0; i < msStepCount; ++i) {
  312. if (fabs(msSteps[i] - currentMS) < 1e-6f) {
  313. currentIndex = i;
  314. break;
  315. }
  316. }
  317. if (currentIndex >= msStepCount - 1) {
  318. return RET_STATUS::RET_SUCCEED; // 已经是最大值
  319. }
  320. return SetMS(msSteps[currentIndex + 1]);
  321. }
  322. RET_STATUS nsGEN::PSGHDDevice::DecMS()
  323. {
  324. float currentMS = m_DoseUnit.m_MS->Get();
  325. // 查找当前值在档位中的位置
  326. size_t currentIndex = msStepCount;
  327. for (size_t i = 0; i < msStepCount; ++i) {
  328. if (fabs(msSteps[i] - currentMS) < 1e-6f) {
  329. currentIndex = i;
  330. break;
  331. }
  332. }
  333. if (currentIndex == 0 || currentIndex >= msStepCount) {
  334. return RET_STATUS::RET_SUCCEED; // 已经是最小值或无效值
  335. }
  336. return SetMS(msSteps[currentIndex - 1]);
  337. }
  338. RET_STATUS nsGEN::PSGHDDevice::SetMS(float value)
  339. {
  340. // 找到最接近的合法档位值
  341. size_t closestIndex = 0;
  342. float minDiff = fabsf(msSteps[0] - value);
  343. for (size_t i = 1; i < msStepCount; ++i) {
  344. float diff = fabsf(msSteps[i] - value);
  345. if (diff < minDiff) {
  346. minDiff = diff;
  347. closestIndex = i;
  348. }
  349. }
  350. // 发送命令
  351. char command[50] = { 0 };
  352. snprintf(command, sizeof(command), "SMS %07d", static_cast<int>(msSteps[closestIndex] * 100));
  353. return HWSend(command, strlen(command));
  354. }
  355. RET_STATUS nsGEN::PSGHDDevice::IncMAS()
  356. {
  357. return RET_STATUS::RET_SUCCEED;
  358. }
  359. RET_STATUS nsGEN::PSGHDDevice::DecMAS()
  360. {
  361. return RET_STATUS::RET_SUCCEED;
  362. }
  363. RET_STATUS nsGEN::PSGHDDevice::SetMAS(float value)
  364. {
  365. return RET_STATUS::RET_SUCCEED;
  366. }
  367. RET_STATUS nsGEN::PSGHDDevice::SetTechmode(int value)
  368. {
  369. return RET_STATUS::RET_SUCCEED;
  370. }
  371. RET_STATUS nsGEN::PSGHDDevice::SetEXAMMode(std::string value)
  372. {
  373. return RET_STATUS::RET_SUCCEED;
  374. }
  375. RET_STATUS nsGEN::PSGHDDevice::SetAPR(const _tAPRArgs& t)
  376. {
  377. m_bGenBusy = true;
  378. FINFO("APR:KV={$},MA={$},MS={$},MAS={$},Focus={$},Techmode={$},WS={$},AECDensity={$},AECField={$},AECFilm={$}", t.fKV, t.fMA, t.fMS, t.fMAS, t.nFocus, t.nTechmode, t.nWS, t.nAECDensity, t.nAECField, t.nAECFilm);
  379. SetKV(t.fKV);
  380. Sleep(50);
  381. SetMA(t.fMA);
  382. Sleep(80);
  383. SetMS(t.fMS);
  384. m_bGenBusy = false;
  385. return RET_STATUS::RET_SUCCEED;
  386. }
  387. RET_STATUS nsGEN::PSGHDDevice::RefreshData()
  388. {
  389. if (!m_bGenBusy)
  390. {
  391. }
  392. return RET_STATUS::RET_SUCCEED;
  393. }
  394. RET_STATUS nsGEN::PSGHDDevice::SetFocus(int value)
  395. {
  396. if (!m_DoseUnit.m_Focus->Verify(value)) return RET_STATUS::RET_SUCCEED;
  397. return RET_STATUS::RET_SUCCEED;
  398. }
  399. RET_STATUS nsGEN::PSGHDDevice::Reset()
  400. {
  401. FINFO("clear all errors \n");
  402. char errorCodeStr[20];
  403. snprintf(errorCodeStr, sizeof(errorCodeStr), "PSGHD_FLT_0");
  404. int level = 1;
  405. m_MSGUnit->DelWarnMessage(errorCodeStr, level, "");
  406. m_MSGUnit->DelErrorMessage(errorCodeStr, level, "");
  407. FINFO("HWFLT: Fault cleared (fault code 0)");
  408. return HWSend("CLR",3);//仅重置错误状态
  409. }
  410. RET_STATUS nsGEN::PSGHDDevice::ActiveSyncMode(_tSyncModeArgs value)
  411. {
  412. FINFO("value.strSyncMode: {$}, value.strSyncValue: {$}, value.strWS: {$} \n", value.strSyncMode, value.strSyncValue, value.strWS);
  413. int nSyncModeValue = atoi(value.strSyncValue.c_str());
  414. return RET_STATUS::RET_SUCCEED;
  415. }
  416. RET_STATUS nsGEN::PSGHDDevice::SetCollimatorLight(unsigned short value)
  417. {
  418. FINFO("Attempting to set collimator light value:{$}", value);
  419. return HWSend("COL", 3);
  420. }
  421. RET_STATUS nsGEN::PSGHDDevice::SetDeviceSleepState(const int value)
  422. {
  423. m_bSleepState = (bool)value;
  424. FINFO("Attempting to set device sleep state: {$}({$})",
  425. value, m_bSleepState ? "sleeping" : "awake");
  426. return RET_STATUS::RET_SUCCEED;
  427. }
  428. RET_STATUS nsGEN::PSGHDDevice::QueryHE(int& value)
  429. {
  430. return RET_STATUS::RET_SUCCEED;
  431. }
  432. void nsGEN::PSGHDDevice::SubscribeSelf(ccos_mqtt_connection* conn)
  433. {
  434. //订阅GEN所有Action
  435. //SubscribeTopic(conn, "CCOS/DEVICE/Generator/Action/#"); Moduld层默认订阅了这个Action,如果这边也订阅的话就会执行两遍Action,可能会出问题
  436. }
  437. RET_STATUS nsGEN::PSGHDDevice::SetAECDensity(int value)
  438. {
  439. if (!m_DoseUnit.m_AECDensity->Verify(value)) return RET_STATUS::RET_SUCCEED;
  440. if (m_DoseUnit.m_Techmode->Get() == AttrKey::TECHMODE_V2TYPE::ET_AEC) return RET_STATUS::RET_FAILED;
  441. int nAECDensity = m_DoseUnit.m_AECDensity->Get();
  442. if (value < m_DoseUnit.m_AECDensity->Get())
  443. {
  444. if (value < m_DoseUnit.m_AECDensity->Get() - 1)
  445. {
  446. nAECDensity = (int)value;
  447. }
  448. else
  449. {
  450. nAECDensity = nAECDensity - 1;
  451. }
  452. }
  453. else if (value > m_DoseUnit.m_AECDensity->Get())
  454. {
  455. if (value > m_DoseUnit.m_AECDensity->Get() + 1)
  456. {
  457. nAECDensity = (int)value;
  458. }
  459. else
  460. {
  461. nAECDensity = nAECDensity + 1;
  462. }
  463. }
  464. m_DoseUnit.m_AECDensity->Update(value);
  465. char temp[50] = { 0 };
  466. if (nAECDensity >= 0)
  467. {
  468. snprintf(temp, sizeof(temp), "FN+%01d", (int)nAECDensity);
  469. }
  470. else
  471. {
  472. snprintf(temp, sizeof(temp), "FN-%01d", (int)nAECDensity);
  473. }
  474. return HWSend(temp, strlen(temp));
  475. }
  476. RET_STATUS nsGEN::PSGHDDevice::SetAECField(int value)
  477. {
  478. if (!m_DoseUnit.m_AECField->Verify(value)) return RET_STATUS::RET_SUCCEED;
  479. if (m_DoseUnit.m_Techmode->Get() == AttrKey::TECHMODE_V2TYPE::ET_MAS) return RET_STATUS::RET_FAILED;
  480. m_DoseUnit.m_AECField->Update(value);
  481. char temp[50] = { 0 };
  482. snprintf(temp, sizeof(temp), "FI%03d", (int)value);
  483. return HWSend(temp, strlen(temp));
  484. }
  485. RET_STATUS nsGEN::PSGHDDevice::SetAECFilm(int value)
  486. {
  487. if (!m_DoseUnit.m_AECFilm->Verify(value)) return RET_STATUS::RET_SUCCEED;
  488. if (m_DoseUnit.m_Techmode->Get() == AttrKey::TECHMODE_V2TYPE::ET_MAS) return RET_STATUS::RET_FAILED;
  489. m_DoseUnit.m_AECFilm->Update(value);
  490. char temp[50] = { 0 };
  491. snprintf(temp, sizeof(temp), "FS%03d", (int)value);
  492. return HWSend(temp, strlen(temp));
  493. }
  494. RET_STATUS nsGEN::PSGHDDevice::SetWS(const string value)
  495. {
  496. FINFO("Enter SetWS {$}", value);
  497. int tempws = 0;
  498. if (value == "Table") tempws = (int)m_GenConfig["WSTable"];
  499. else if (value == "Wall") tempws = (int)m_GenConfig["WSWall"];
  500. else if (value == "Direct") tempws = (int)m_GenConfig["WSConventional"];
  501. else if (value == "Free") tempws = (int)m_GenConfig["WSFree"];
  502. else if (value == "Tomo") tempws = (int)m_GenConfig["WSTomo"];
  503. m_DoseUnit.m_WS->Update(tempws);
  504. char temp[50] = { 0 };
  505. snprintf(temp, sizeof(temp), "WS%01d", tempws);
  506. return HWSend(temp, strlen(temp));
  507. }
  508. RET_STATUS nsGEN::PSGHDDevice::QueryPostKV(float& value)
  509. {
  510. return RET_STATUS::RET_SUCCEED;
  511. }
  512. RET_STATUS nsGEN::PSGHDDevice::QueryPostMA(float& value)
  513. {
  514. return RET_STATUS::RET_SUCCEED;
  515. }
  516. RET_STATUS nsGEN::PSGHDDevice::QueryPostMS(float& value)
  517. {
  518. return RET_STATUS::RET_SUCCEED;
  519. }
  520. RET_STATUS nsGEN::PSGHDDevice::QueryPostMAS(float& value)
  521. {
  522. return RET_STATUS::RET_SUCCEED;
  523. }
  524. RET_STATUS nsGEN::PSGHDDevice::StartMove() //发生器无此设置
  525. {
  526. return RET_STATUS::RET_SUCCEED;
  527. }
  528. RET_STATUS nsGEN::PSGHDDevice::EndMove() //发生器无此设置
  529. {
  530. return RET_STATUS::RET_SUCCEED;
  531. }
  532. RET_STATUS nsGEN::PSGHDDevice::SetGenSynState(int value)
  533. {
  534. FINFO("Enter SetGenSynState...{$} \n", value);
  535. //if (AttrKey::GENERATOR_RAD_XRAYON == value)
  536. //{
  537. // FINFO("SetGenSynState be call.this is soft syn mode.");
  538. // HWSend("XR2",3);
  539. // m_DoseUnit.m_GenSynState->Update(AttrKey::GENERATOR_RAD_XRAYON);
  540. // FireNotify(m_DoseUnit.m_GenSynState->GetKey(), m_DoseUnit.m_GenSynState->JSGet());
  541. //}
  542. //else if(AttrKey::GENERATOR_FLU_XRAYON == value)
  543. //{
  544. // FINFO("SetGenSynState be call.this is soft syn mode.");
  545. // //HWSend("FLX2", 4);
  546. // //m_DoseUnit.m_GenSynState->Update(AttrKey::GENERATOR_FLU_XRAYON);
  547. // //FireNotify(m_DoseUnit.m_GenSynState->GetKey(), m_DoseUnit.m_GenSynState->JSGet());
  548. //}
  549. return RET_STATUS::RET_SUCCEED;
  550. }
  551. RET_STATUS nsGEN::PSGHDDevice::SetGenState(int value)
  552. {
  553. return RET_STATUS::RET_SUCCEED;
  554. }
  555. RET_STATUS nsGEN::PSGHDDevice::SetExpMode(std::string value)
  556. {
  557. FINFO("Enter SetExpMode...{$} \n",value.c_str());
  558. m_DoseUnit.m_ExpMode->Update(value);
  559. FireNotify(AttrKey::GENSTATE, m_DoseUnit.m_GenState->JSGet());
  560. return RET_STATUS::RET_SUCCEED;
  561. }
  562. RET_STATUS nsGEN::PSGHDDevice::SetFrameRate(float frameRate)
  563. {
  564. return RET_STATUS::RET_SUCCEED;
  565. }
  566. RET_STATUS nsGEN::PSGHDDevice::SetExpEnable()
  567. {
  568. FINFO("SetExpEnable in\n");
  569. return HWSend("DSW 1", 5);
  570. }
  571. RET_STATUS nsGEN::PSGHDDevice::SetExpDisable()
  572. {
  573. FINFO("SetExpDisable in\n");
  574. return HWSend("DSW 0", 5);
  575. }
  576. RET_STATUS nsGEN::PSGHDDevice::PrepareAcquisition()
  577. {
  578. FireNotify(AttrKey::GENSTATE, m_DoseUnit.m_GenState->JSGet());
  579. return RET_STATUS::RET_SUCCEED;
  580. }
  581. //-----------------------------------------------------------------------------
  582. // ProcessCmd
  583. //-----------------------------------------------------------------------------
  584. void nsGEN::PSGHDDevice::ProcessClientData(const char* pData, unsigned long nDataLength, void* lparam)
  585. {
  586. PSGHDDevice* pCurGen = (PSGHDDevice*)lparam;
  587. pCurGen->HWSend(pData, nDataLength);
  588. }
  589. RET_STATUS nsGEN::PSGHDDevice::HWSend(const char* strCommand, int length, bool reSend, int nTimeOut)
  590. {
  591. if (!m_SCF) {
  592. FINFO("Failed - Serial communication interface not initialized");
  593. return RET_STATUS::RET_FAILED;
  594. }
  595. if (!m_SCF->IsConnected())
  596. {
  597. FINFO("Failed - Device not connected");
  598. return RET_STATUS::RET_FAILED;
  599. }
  600. // 构造新协议格式:<Command><Data><ETX><Checksum>
  601. char strSendCommand[100] = { 0 };
  602. int len = 0;
  603. // 复制命令部分
  604. memcpy(strSendCommand + len, strCommand, length);
  605. len += length;
  606. // 添加ETX结束符(0x03)
  607. strSendCommand[len++] = 0x03;
  608. // 计算校验和:Command + Data + ETX的累加和取低位
  609. uint8_t checksum = 0;
  610. for (int i = 0; i < len; i++) { // 从首字节到ETX全部参与计算
  611. checksum += (uint8_t)strSendCommand[i];
  612. }
  613. checksum &= 0xFF; // 取累加和的低8位
  614. // 添加校验和
  615. strSendCommand[len++] = checksum;
  616. // 打印数据包前16字节的十六进制(含控制字符)便于调试
  617. /*std::string hexStr;
  618. int printLen = std::min(len, 16);
  619. for (int i = 0; i < printLen; i++) {
  620. char buf[4];
  621. snprintf(buf, sizeof(buf), "%02X ", (uint8_t)strSendCommand[i]);
  622. hexStr += buf;
  623. }
  624. if (len > 16) hexStr += "...";
  625. FINFO("Packet (hex, total len: {$}) - [{$}]", len, hexStr);*/
  626. // 发送
  627. unsigned int retLength;
  628. if (m_SCF->Lock(1000) == WAIT_OBJECT_0)
  629. {
  630. int result = m_SCF->SendPacket(strSendCommand, len, nTimeOut, retLength);
  631. m_SCF->Unlock();
  632. if (result == SCF_SUCCEED) {
  633. // 打印发送命令的关键信息(命令内容+完整包长度)
  634. FINFO("Command to send - [{$}] (raw command length: {$}) - Success - Sent {$} bytes",
  635. std::string(strCommand, length), len, retLength);
  636. return RET_STATUS::RET_SUCCEED;
  637. }
  638. else {
  639. FINFO("HWSend: Failed - SendPacket returned error code: {$}", result);
  640. return RET_STATUS::RET_FAILED;
  641. }
  642. }
  643. else
  644. {
  645. FINFO("HWSend: Failed - Could not acquire lock within 1000ms");
  646. return RET_STATUS::RET_FAILED;
  647. }
  648. return RET_STATUS::RET_SUCCEED;
  649. }
  650. void nsGEN::PSGHDDevice::FireNotify(string key, int context)
  651. {
  652. char szInfo[64] = { 0 };
  653. snprintf(szInfo, sizeof(szInfo), "%d", context); // Linux 标准函数
  654. std::string str = szInfo;
  655. EventCenter->OnNotify(1, key, str);
  656. }
  657. void nsGEN::PSGHDDevice::FireNotify(std::string key, float context)
  658. {
  659. char szInfo[16] = { 0 };
  660. snprintf(szInfo, sizeof(szInfo), "%.2f", context); // Linux 标准函数
  661. std::string str = szInfo;
  662. EventCenter->OnNotify(1, key, str);
  663. }
  664. void nsGEN::PSGHDDevice::FireNotify(std::string key, std::string context)
  665. {
  666. EventCenter->OnNotify(1, key, context);
  667. }
  668. void nsGEN::PSGHDDevice::FireErrorMessage(const bool Act, const int Code, const char* ResInfo)
  669. {
  670. string ErrorCode("PSGHD_ERR_");
  671. ErrorCode += std::to_string(Code);
  672. int level = PSG_HD_REGULATION_LEVEL::REG_ERRO;
  673. if (Act)
  674. {
  675. FINFO("add {$}:{$}", ErrorCode.c_str(), ResInfo);
  676. m_MSGUnit->AddErrorMessage(ErrorCode.c_str(), level, ResInfo);
  677. }
  678. else
  679. {
  680. FINFO("del {$}:{$}", ErrorCode.c_str(), ResInfo);
  681. m_MSGUnit->DelErrorMessage(ErrorCode.c_str(), level, ResInfo);
  682. }
  683. }
  684. void nsGEN::PSGHDDevice::FireWarnMessage(const bool Act, const int Code, const char* ResInfo)
  685. {
  686. string ErrorCode("PSGHD_WAR_");
  687. ErrorCode += std::to_string(Code);
  688. int level = PSG_HD_REGULATION_LEVEL::REG_WARN;
  689. if (Act)
  690. {
  691. FINFO("add {$}:{$}", ErrorCode.c_str(), ResInfo);
  692. m_MSGUnit->AddWarnMessage(ErrorCode.c_str(), level, ResInfo);
  693. }
  694. else
  695. {
  696. FINFO("del {$}:{$}", ErrorCode.c_str(), ResInfo);
  697. m_MSGUnit->DelWarnMessage(ErrorCode.c_str(), level, ResInfo);
  698. }
  699. }
  700. void nsGEN::PSGHDDevice::OnCallBack()
  701. {
  702. // 无操作处理函数
  703. auto HWNotProcess = [](const char* value, int length) -> void
  704. {
  705. FINFO("HWNotProcess: Command data (len: {$}) no need to process", length);
  706. };
  707. // 处理VREF响应 (电压参考)
  708. auto HWVREF = [this](const char* data, int length) -> void
  709. {
  710. // 需至少4字节数据(XXXX)
  711. if (length < 4) {
  712. FINFO("HWVREF: Invalid data length ({$} < 4), skip", length);
  713. return;
  714. }
  715. char kvStr[5] = { 0 };
  716. strncpy(kvStr, data, 4);
  717. int kvValue = atoi(kvStr);
  718. float actualKV = kvValue / 10.0f; // 转换为kV
  719. m_DoseUnit.m_KV->Update(actualKV);
  720. FireNotify(AttrKey::KV, m_DoseUnit.m_KV->JSGet());
  721. FINFO("HWVREF: Parsed actual KV = {$} kV", actualKV);
  722. };
  723. // 处理IREF响应 (电流参考)
  724. auto HWIREF = [this](const char* data, int length) -> void
  725. {
  726. if (length < 4) { // 需4字节(XXXX)
  727. FINFO("HWIREF: Invalid data length ({$} < 4), skip", length);
  728. return;
  729. }
  730. char maStr[5] = { 0 };
  731. strncpy(maStr, data, 4); // 直接取data
  732. int maValue = atoi(maStr);
  733. float actualMA = maValue / 100.0f; // 转换为mA
  734. m_DoseUnit.m_MA->Update(actualMA);
  735. FireNotify(AttrKey::MA, m_DoseUnit.m_MA->JSGet());
  736. FINFO("HWIREF: Parsed actual MA = {$} mA", actualMA);
  737. };
  738. // 处理ENBL响应 (X射线使能)
  739. auto HWENBL = [this](const char* data, int length) -> void
  740. {
  741. if (length < 1) { // 需1字节(X)
  742. FINFO("HWENBL: Invalid data length ({$} < 1), skip", length);
  743. return;
  744. }
  745. // 直接取data[0](无需跳过"ENBL ")
  746. char enblStr = data[0];
  747. bool isEnabled = (enblStr == '1');
  748. FINFO("HWENBL: X-ray enable status = {$}", isEnabled ? "Enabled" : "Disabled");
  749. };
  750. // 处理WDTE响应 (看门狗定时器)
  751. auto HWWDTE = [this](const char* data, int length) -> void
  752. {
  753. if (length < 1) { // 需1字节(X)
  754. FINFO("HWWDTE: Invalid data length ({$} < 1), skip", length);
  755. return;
  756. }
  757. char wdtStr = data[0]; // 直接取data[0]
  758. bool isWdtEnabled = (wdtStr == '1');
  759. FINFO("HWWDTE: Watchdog status = {$}", isWdtEnabled ? "Enabled" : "Disabled");
  760. };
  761. // 处理WDTT响应 (看门狗定时器重置)
  762. auto HWWDTT = [this](const char* data, int length) -> void
  763. {
  764. if (length < 1) { // 基础长度校验
  765. FINFO("HWWDTT: Invalid data length ({$} < 1), skip", length);
  766. return;
  767. }
  768. FINFO("HWWDTT: Watchdog timer reset response received");
  769. };
  770. // 处理CLR响应 (故障清除)
  771. auto HWCLR = [this](const char* data, int length) -> void
  772. {
  773. if (length < 1) {
  774. FINFO("HWCLR: Invalid data length ({$} < 1), skip", length);
  775. return;
  776. }
  777. FINFO("HWCLR: Received fault clear response, performing fault clearing");
  778. };
  779. // 处理SMS响应 (曝光时间)
  780. auto HWSMS = [this](const char* data, int length) -> void
  781. {
  782. if (length < 7) { // 需7字节(XXXXXXX)
  783. FINFO("HWSMS: Invalid data length ({$} < 7), skip", length);
  784. return;
  785. }
  786. char smsStr[8] = { 0 };
  787. strncpy(smsStr, data, 7); // 直接取data
  788. long timeValue = atol(smsStr);
  789. float exposureTime = timeValue * 0.01f; // 转换为ms
  790. m_DoseUnit.m_MS->Update(exposureTime);
  791. FireNotify(AttrKey::MS, m_DoseUnit.m_MS->JSGet());
  792. FINFO("HWSMS: Parsed exposure time = {$} ms", exposureTime);
  793. };
  794. // 处理FLT响应 (故障状态)
  795. auto HWFLT = [this](const char* data, int length) -> void
  796. {
  797. if (length < 3) { // 需3字节(XXX)
  798. FINFO("HWFLT: Invalid data length ({$} < 3), skip", length);
  799. return;
  800. }
  801. char faultStr[4] = { 0 };
  802. strncpy(faultStr, data, 3);
  803. int faultCode = atoi(faultStr);
  804. if (faultCode != 0)
  805. {
  806. static const std::unordered_map<int, std::string> errorMessages = {
  807. {2, "Charging circuit abnormal"}, {3, "Storage chip damaged"}, {136, "Filament current 1 exceeds limit"},
  808. {140, "Anode kV exceeds limit, exposure aborted abnormally"}, {142, "High-voltage generator or tube arcing, exposure aborted abnormally"},
  809. {165, "Bus voltage too low during high-voltage generator startup"}, {205, "Second-stage handswitch pressed during high-voltage generator wake-up or startup"},
  810. {206, "High-voltage generator low battery, please charge"}, {208, "Exposure interval too short, please expose later"},
  811. {209, "Parameter adjustment forbidden during exposure"}, {210, "First-stage handswitch repeated triggering, please use a single handswitch for exposure operation"},
  812. {216, "Battery being charged"}, {218, "kV parameter exceeds limit"}, {219, "mA parameter exceeds limit"},
  813. {220, "ms parameter exceeds limit"}, {229, "High-voltage generator power exceeds limit"}, {230, "Tube power exceeds limit"},
  814. {231, "Frame rate parameter exceeds limit"}, {249, "High-voltage generator bus voltage exceeds limit"}, {255, "kV establishment timeout"},
  815. {259, "Handswitch released in advance during exposure"}, {260, "Parameter adjustment forbidden during exposure"}, {263, "kV too high during exposure, exposure aborted abnormally"},
  816. {267, "mA too low during exposure, exposure aborted abnormally"}, {268, "mA too high during exposure, exposure aborted abnormally"}, {281, "Power exceeds limit during exposure, exposure aborted abnormally"}
  817. };
  818. static const std::unordered_set<int> firstSixErrors = { 2, 3, 136, 140, 142, 165 };
  819. char errorCodeStr[20];
  820. snprintf(errorCodeStr, sizeof(errorCodeStr), "PSGHD_FLT_%d", faultCode);
  821. int level = 1;
  822. auto it = errorMessages.find(faultCode);
  823. if (it != errorMessages.end())
  824. {
  825. if (firstSixErrors.count(faultCode))
  826. m_MSGUnit->AddErrorMessage(errorCodeStr, level, it->second.c_str());
  827. else
  828. m_MSGUnit->AddWarnMessage(errorCodeStr, level, it->second.c_str());
  829. FINFO("HWFLT: Fault code {$} detected - {$}", faultCode, it->second.c_str());
  830. }
  831. }
  832. else
  833. {
  834. char errorCodeStr[20];
  835. snprintf(errorCodeStr, sizeof(errorCodeStr), "PSGHD_FLT_0");
  836. int level = 1;
  837. m_MSGUnit->DelWarnMessage(errorCodeStr, level, "");
  838. m_MSGUnit->DelErrorMessage(errorCodeStr, level, "");
  839. FINFO("HWFLT: Fault cleared (fault code 0)");
  840. }
  841. };
  842. // 处理工作相位响应 (RST<aaa>)
  843. auto HWPhase = [this](const char* data, int length) -> void
  844. {
  845. if (length < 3) { // 需3字节(aaa)
  846. FINFO("HWPhase: Invalid data length ({$} < 3), skip", length);
  847. return;
  848. }
  849. // 设备首次连接时禁止曝光!
  850. if (m_isFirstHWPhase) {
  851. SetExpDisable();
  852. m_isFirstHWPhase = false;
  853. }
  854. char phaseCodeStr[4] = { 0 };
  855. strncpy(phaseCodeStr, data, 3);
  856. int phaseCode = atoi(phaseCodeStr);
  857. auto updateAndNotify = [this](nsGEN::AttrKey::GENERATOR_STATUS status)
  858. {
  859. if (m_DoseUnit.m_GenState->Update(status))
  860. {
  861. FireNotify(AttrKey::GENSTATE, m_DoseUnit.m_GenState->JSGet());
  862. FINFO("HWPhase: Generator status updated to {$}", static_cast<int>(status));
  863. }
  864. };
  865. switch (phaseCode)
  866. {
  867. case 1: updateAndNotify(nsGEN::AttrKey::GENERATOR_STATUS_INIT); break;
  868. case 7: updateAndNotify(nsGEN::AttrKey::GENERATOR_STATUS_ERROR); break;
  869. case 9: case 11: updateAndNotify(nsGEN::AttrKey::GENERATOR_STATUS_EXP); break;
  870. default: FINFO("HWPhase: Unsupported phase code {$}", phaseCode); break;
  871. }
  872. };
  873. auto HWVMON = [this](const char* data, int length) -> void
  874. {
  875. if (length < 4) { // 需4字节(XXXX)
  876. FINFO("HWVMON: Invalid data length ({$} < 4), skip", length);
  877. return;
  878. }
  879. char vmonStr[5] = { 0 };
  880. strncpy(vmonStr, data, 4); // 直接取data
  881. int vmonValue = atoi(vmonStr);
  882. float actualVMON = vmonValue / 10.0f; // 转换为kV
  883. m_DoseUnit.m_PostKV->Update(actualVMON);
  884. FireNotify(AttrKey::POSTKV, m_DoseUnit.m_PostKV->JSGet());
  885. FINFO("HWVMON: Parsed monitoring KV = {$} kV", actualVMON);
  886. };
  887. auto HWIMON = [this](const char* data, int length) -> void
  888. {
  889. if (length < 4) { // 需4字节(XXXX)
  890. FINFO("HWIMON: Invalid data length ({$} < 4), skip", length);
  891. return;
  892. }
  893. char imonStr[5] = { 0 };
  894. strncpy(imonStr, data, 4); // 直接取data
  895. int imonValue = atoi(imonStr);
  896. float actualIMON = imonValue / 100.0f; // 转换为mA
  897. m_DoseUnit.m_PostMA->Update(actualIMON);
  898. FireNotify(AttrKey::POSTMA, m_DoseUnit.m_PostMA->JSGet());
  899. FINFO("HWIMON: Parsed monitoring MA = {$} mA", actualIMON);
  900. };
  901. auto HWRAT = [this](const char* data, int length) -> void
  902. {
  903. if (length < 7) { // 需7字节(XXXXXXX)
  904. FINFO("HWRAT: Invalid data length ({$} < 7), skip", length);
  905. return;
  906. }
  907. char ratStr[8] = { 0 };
  908. strncpy(ratStr, data, 7); // 直接取data
  909. int ratio = atoi(ratStr);
  910. float actualRatio = ratio / 100.0f;
  911. m_DoseUnit.m_PostMS->Update(actualRatio);
  912. FireNotify(m_DoseUnit.m_PostMS->GetKey(), m_DoseUnit.m_PostMS->JSGet());
  913. FINFO("HWRAT: Parsed ratio parameter = {$}", actualRatio);
  914. };
  915. auto HWPOW = [this](const char* data, int length) -> void
  916. {
  917. if (length < 1) { // 需1字节(X)
  918. FINFO("HWPOW: Invalid data length ({$} < 1), skip", length);
  919. return;
  920. }
  921. char powStr = data[0]; // 直接取data[0]
  922. bool isPowerOn = (powStr == '1');
  923. FINFO("HWPOW: Power status = {$}", isPowerOn ? "On" : "Off");
  924. };
  925. auto HWEOK = [this](const char* data, int length) -> void
  926. {
  927. if (length < 1) { // 需1字节(X)
  928. FINFO("HWEOK: Invalid data length ({$} < 1), skip", length);
  929. return;
  930. }
  931. char eokStr = data[0]; // 直接取data[0]
  932. bool isReady = (eokStr == '1');
  933. if (isReady)
  934. {
  935. if (m_DoseUnit.m_GenState->Update(nsGEN::AttrKey::GENERATOR_STATUS_STANDBY))
  936. {
  937. //FireNotify(AttrKey::GENSTATE, m_DoseUnit.m_GenState->JSGet());
  938. FINFO("HWEOK: Device ready, status updated to STANDBY");
  939. }
  940. }
  941. else
  942. {
  943. if (m_DoseUnit.m_GenState->Update(nsGEN::AttrKey::GENERATOR_STATUS_SLEEP))
  944. {
  945. //FireNotify(AttrKey::GENSTATE, m_DoseUnit.m_GenState->JSGet());
  946. FINFO("HWEOK: Device not ready, status updated to SLEEP");
  947. }
  948. }
  949. };
  950. auto HWDSW = [this](const char* data, int length) -> void
  951. {
  952. if (length < 1) { // 需1字节(X)
  953. FINFO("HWDSW: Invalid data length ({$} < 1), skip", length);
  954. return;
  955. }
  956. char eokStr = data[0]; // 直接取data[0]
  957. bool isReady = (eokStr == '1');
  958. if (isReady && m_DoseUnit.m_GenState->Get()== nsGEN::AttrKey::GENERATOR_STATUS_STANDBY)
  959. {
  960. FireNotify(AttrKey::GENSTATE, m_DoseUnit.m_GenState->JSGet());
  961. FINFO("HWDSW: Device ready, status updated to STANDBY");
  962. }
  963. else
  964. {
  965. m_DoseUnit.m_GenState->Update(nsGEN::AttrKey::GENERATOR_STATUS_SLEEP);
  966. FireNotify(AttrKey::GENSTATE, m_DoseUnit.m_GenState->JSGet());
  967. FINFO("HWDSW: Device not ready, status updated to SLEEP");
  968. }
  969. };
  970. auto HWECD = [this](const char* data, int length) -> void
  971. {
  972. if (length < 3) { // 需3字节(XXX)
  973. FINFO("HWECD: Invalid data length ({$} < 3), skip", length);
  974. return;
  975. }
  976. char ecdStr[4] = { 0 };
  977. strncpy(ecdStr, data, 3); // 直接取data
  978. int countdown = atoi(ecdStr);
  979. FINFO("HWECD: High-voltage OK light countdown = {$}s", countdown);
  980. };
  981. auto HWSOC = [this](const char* data, int length) -> void
  982. {
  983. if (length < 3) { // 需3字节(XXX)
  984. FINFO("HWSOC: Invalid data length ({$} < 3), skip", length);
  985. return;
  986. }
  987. char socStr[4] = { 0 };
  988. strncpy(socStr, data, 3); // 直接取data
  989. int remainingPower = atoi(socStr);
  990. FINFO("HWSOC: Generator remaining power = {$}%", remainingPower);
  991. };
  992. auto HWFLX = [this](const char* data, int length) -> void
  993. {
  994. if (length < 1) { // 需1字节(X)
  995. FINFO("HWFLX: Invalid data length ({$} < 1), skip", length);
  996. return;
  997. }
  998. char flxStr[2] = { 0 };
  999. strncpy(flxStr, data, 1);
  1000. int fluoroMode = atoi(flxStr);
  1001. FINFO("HWFLX: Fluorescence mode detected = {$}", fluoroMode);
  1002. if (fluoroMode == 2)
  1003. {
  1004. m_DoseUnit.m_GenSynState->Update(AttrKey::GENERATOR_RAD_XRAYON);
  1005. FireNotify(m_DoseUnit.m_GenSynState->GetKey(), m_DoseUnit.m_GenSynState->JSGet());
  1006. FINFO("HWFLX: X-ray turned ON (mode 2)");
  1007. }
  1008. else if (fluoroMode == 1)
  1009. {
  1010. m_DoseUnit.m_GenSynState->Update(AttrKey::GENERATOR_RAD_READY);
  1011. m_hGenPostEvent->ResetEvent();
  1012. FireNotify(m_DoseUnit.m_GenSynState->GetKey(), m_DoseUnit.m_GenSynState->JSGet());
  1013. FINFO("HWFLX: X-ray ready (mode 1)");
  1014. }
  1015. else if (fluoroMode == 0)
  1016. {
  1017. m_bGenBusy = false;
  1018. m_DoseUnit.m_GenSynState->Update(AttrKey::GENERATOR_RAD_XRAYOFF);
  1019. FireNotify(m_DoseUnit.m_GenSynState->GetKey(), m_DoseUnit.m_GenSynState->JSGet());
  1020. FINFO("HWFLX: X-ray turned OFF (mode 0)");
  1021. }
  1022. };
  1023. auto HWVER = [this](const char* data, int length) -> void
  1024. {
  1025. if (length < 6) { // 需6字节(XXXXXX)
  1026. FINFO("HWVER: Invalid data length ({$} < 6), skip", length);
  1027. return;
  1028. }
  1029. char verStr[7] = { 0 };
  1030. strncpy(verStr, data, 6); // 直接取data
  1031. std::string version(verStr);
  1032. FINFO("HWVER: Generator version = {$}", version);
  1033. };
  1034. auto HWVSN = [this](const char* data, int length) -> void
  1035. {
  1036. if (length < 8) { // 需8字节(XXXXXXXX)
  1037. FINFO("HWVSN: Invalid data length ({$} < 8), skip", length);
  1038. return;
  1039. }
  1040. char vsnStr[9] = { 0 };
  1041. strncpy(vsnStr, data, 8); // 直接取data
  1042. std::string serialNumber(vsnStr);
  1043. FINFO("HWVSN: Generator serial number = {$}", serialNumber);
  1044. };
  1045. auto HWMAS = [this](const char* data, int length) -> void
  1046. {
  1047. if (length < 3) { // 至少3字节(避免atof解析错误)
  1048. FINFO("HWMAS: Invalid data length ({$} < 3), skip", length);
  1049. return;
  1050. }
  1051. float fmas = atof(data) / 100.0f; // 直接用data解析
  1052. if (m_DoseUnit.m_MAS->Update(fmas))
  1053. {
  1054. FireNotify(AttrKey::MAS, m_DoseUnit.m_MAS->JSGet());
  1055. FINFO("HWMAS: Parsed MAS value = {$}", fmas);
  1056. }
  1057. };
  1058. auto HWAP = [this](const char* data, int length) -> void
  1059. {
  1060. if (length < 3) { // 至少3字节(避免atof解析错误)
  1061. FINFO("HWAP: Invalid data length ({$} < 3), skip", length);
  1062. return;
  1063. }
  1064. float fmas = atof(data) / 100.0f; // 直接用data解析
  1065. m_DoseUnit.m_PostMAS->Update(fmas);
  1066. FireNotify(AttrKey::POSTMAS, m_DoseUnit.m_PostMAS->JSGet());
  1067. FINFO("HWAP: Parsed POSTMAS value = {$}", fmas);
  1068. };
  1069. auto HWWS = [this](const char* data, int length) -> void
  1070. {
  1071. if (length < 1) { // 需1字节以上(避免atoi解析错误)
  1072. FINFO("HWWS: Invalid data length ({$} < 1), skip", length);
  1073. return;
  1074. }
  1075. int nValue = atoi(data); // 直接用data解析
  1076. m_DoseUnit.m_WS->Update(nValue);
  1077. FireNotify(m_DoseUnit.m_WS->GetKey(), m_DoseUnit.m_WS->JSGet());
  1078. FINFO("HWWS: Parsed WS parameter = {$}", nValue);
  1079. };
  1080. auto HWEHE = [this](const char* data, int length) -> void
  1081. {
  1082. if (length < 1) { // 需1字节以上
  1083. FINFO("HWEHE: Invalid data length ({$} < 1), skip", length);
  1084. return;
  1085. }
  1086. m_iHeartBeats = 0;
  1087. int nhe = atoi(data); // 直接用data解析
  1088. if (m_DoseUnit.m_HE->Update(nhe))
  1089. {
  1090. FireNotify(m_DoseUnit.m_HE->GetKey(), m_DoseUnit.m_HE->JSGet());
  1091. FINFO("HWEHE: Parsed HE parameter = {$}", nhe);
  1092. }
  1093. };
  1094. arFrame.clear();
  1095. // 指令映射表补充
  1096. arFrame.push_back(tFrameMapping("VREF ", 5, HWVREF));
  1097. arFrame.push_back(tFrameMapping("IREF ", 5, HWIREF));
  1098. arFrame.push_back(tFrameMapping("VMON ", 5, HWVMON));
  1099. arFrame.push_back(tFrameMapping("IMON ", 5, HWIMON));
  1100. arFrame.push_back(tFrameMapping("ENBL ", 5, HWENBL));
  1101. arFrame.push_back(tFrameMapping("RST ", 4, HWPhase));
  1102. arFrame.push_back(tFrameMapping("SMS ", 4, HWSMS));
  1103. arFrame.push_back(tFrameMapping("RAT ", 4, HWRAT));
  1104. arFrame.push_back(tFrameMapping("POW ", 4, HWPOW));
  1105. arFrame.push_back(tFrameMapping("EOK ", 4, HWEOK));
  1106. arFrame.push_back(tFrameMapping("ECD ", 4, HWECD));
  1107. arFrame.push_back(tFrameMapping("FLX ", 4, HWFLX));
  1108. arFrame.push_back(tFrameMapping("FLT ", 4, HWFLT));
  1109. arFrame.push_back(tFrameMapping("RHE ", 4, HWEHE));
  1110. arFrame.push_back(tFrameMapping("VER ", 4, HWVER));
  1111. arFrame.push_back(tFrameMapping("VSN ", 4, HWVSN));
  1112. arFrame.push_back(tFrameMapping("CLR", 4, HWCLR));
  1113. arFrame.push_back(tFrameMapping("EC", 2, HWNotProcess));
  1114. arFrame.push_back(tFrameMapping("PW", 2, HWNotProcess));
  1115. arFrame.push_back(tFrameMapping("MX", 2, HWMAS));
  1116. arFrame.push_back(tFrameMapping("WS", 2, HWWS));
  1117. }
  1118. bool nsGEN::PSGHDDevice::ReConnect()
  1119. {
  1120. FINFO("Enter PSG_reConnect");
  1121. m_SCF->Disconnect();
  1122. if (!pIODriver)
  1123. {
  1124. FINFO("PSG_reConnect:Driver null");
  1125. }
  1126. else
  1127. {
  1128. // 需要将 pIODriver 转换为 PSGHDDriver*
  1129. PSGHDDriver* driver = dynamic_cast<PSGHDDriver*>(pIODriver.get());
  1130. if (driver && driver->ReConnection())
  1131. {
  1132. FireErrorMessage(false, 1, "lost Connect");
  1133. m_bConnectFlag = true;
  1134. FINFO("PSG_reConnect success");
  1135. return true;
  1136. }
  1137. else
  1138. {
  1139. FINFO("PSG_reConnect failed");
  1140. }
  1141. }
  1142. return false;
  1143. }
  1144. int nsGEN::PSGHDDevice::GetGenState()
  1145. {
  1146. if (m_DoseUnit.m_GenState != NULL)
  1147. {
  1148. return m_DoseUnit.m_GenState->Get();
  1149. }
  1150. else
  1151. {
  1152. return 0;
  1153. }
  1154. }
  1155. int nsGEN::PSGHDDevice::LoadConfig(string configfile)
  1156. {
  1157. FINFO("=====================LoadConfig=========================");
  1158. // 检查文件是否存在
  1159. std::ifstream file(configfile);
  1160. if (!file) {
  1161. // 文件不存在,直接返回空的Connection对象
  1162. FINFO("Config file does not exist: {$}", configfile.c_str());
  1163. return -1;
  1164. }
  1165. if (m_bIsConfigLoaded)
  1166. {
  1167. FINFO("Configuration already loaded.");
  1168. return 0;
  1169. }
  1170. ResDataObject temp;
  1171. temp.loadFile(configfile.c_str());
  1172. m_GenConfig = temp["CONFIGURATION"];
  1173. TransJsonText(m_GenConfig);
  1174. if (m_GenConfig.GetKeyCount("loopEnable") > 0)
  1175. {
  1176. m_bExtraFlag = (int)m_GenConfig["loopEnable"];
  1177. }
  1178. if (m_GenConfig.GetKeyCount(ConfKey::CcosTubeInfo) > 0)
  1179. {
  1180. string tempValue = (string)m_GenConfig[ConfKey::CcosTubeInfo];
  1181. m_DoseUnit.m_TubeInfo.reset(new TUBEINFOMould(tempValue));
  1182. FireNotify(AttrKey::TUBEINFO, m_DoseUnit.m_TubeInfo->JSGet());
  1183. }
  1184. if (m_GenConfig.GetKeyCount(ConfKey::CcosFocusSmall) > 0)
  1185. {
  1186. float tempValue = (float)m_GenConfig[ConfKey::CcosFocusSmall];
  1187. m_DoseUnit.m_FocusSmall = tempValue;
  1188. }
  1189. if (m_GenConfig.GetKeyCount(ConfKey::CcosFocusLarge) > 0)
  1190. {
  1191. float tempValue = (float)m_GenConfig[ConfKey::CcosFocusLarge];
  1192. m_DoseUnit.m_FocusLarge = tempValue;
  1193. }
  1194. if (m_GenConfig.GetKeyCount("GenCtrlMode") > 0)
  1195. {
  1196. m_nCtlMode = (float)m_GenConfig["GenCtrlMode"];//default 2
  1197. float tempValue = (float)m_GenConfig[ConfKey::CcosFocusLarge];
  1198. }
  1199. if (m_GenConfig.GetKeyCount("USECECMD") > 0)
  1200. {
  1201. m_bUseCECmd = (bool)m_GenConfig["USECECMD"];
  1202. }
  1203. m_bIsConfigLoaded = true;
  1204. return 0;
  1205. }
  1206. bool nsGEN::PSGHDDevice::ECHO(void)
  1207. {
  1208. return HWSend("ECH", 3);
  1209. }
  1210. bool nsGEN::PSGHDDevice::StartHardwareStatusThread()
  1211. {
  1212. if (!m_pHardwareStatusThread.joinable())
  1213. {
  1214. m_pHardwareStatusThread = std::thread(HardwareStatusThread, this);
  1215. return true;
  1216. }
  1217. return false;
  1218. }
  1219. void PSGHDDevice::HardwareStatusThread(PSGHDDevice* pParam)
  1220. {
  1221. if (pParam == nullptr)
  1222. {
  1223. return;
  1224. }
  1225. PSGHDDevice* pCurGen = pParam;
  1226. int messageIndex = 0;
  1227. while (pCurGen->m_bExtraFlag)
  1228. {
  1229. // 获取当前循环时间并休眠
  1230. int currentLoopTime = pCurGen->m_iLoopTime;
  1231. Sleep(currentLoopTime);
  1232. // 每5次循环发送状态查询命令
  1233. if (messageIndex % 5 == 0&& !pCurGen->m_bSleepState)
  1234. {
  1235. pCurGen->HWSend("RHE", 3);
  1236. Sleep(100);
  1237. pCurGen->HWSend("RST", 3);
  1238. Sleep(100);
  1239. pCurGen->HWSend("EOK", 3);
  1240. }
  1241. messageIndex++;
  1242. // 防止messageIndex无限增长导致溢出
  1243. if (messageIndex >= INT_MAX - 10)
  1244. {
  1245. messageIndex = 0;
  1246. }
  1247. }
  1248. // 线程退出时重置心跳标志
  1249. }
  1250. //-----------------------------------------------------------------------------
  1251. // PSGHDDriver
  1252. //-----------------------------------------------------------------------------
  1253. nsGEN::PSGHDDriver::PSGHDDriver()
  1254. : m_scfWrapper(std::make_shared<SCFWrapper>())
  1255. {
  1256. m_pAttribute.reset(new ResDataObject());
  1257. m_pDescription.reset(new ResDataObject());
  1258. }
  1259. nsGEN::PSGHDDriver::~PSGHDDriver()
  1260. {
  1261. Disconnect();
  1262. }
  1263. void nsGEN::PSGHDDriver::Prepare()
  1264. {
  1265. // 初始化日志系统
  1266. std::string strLogPath = GetProcessDirectory() + R"(/Conf/log_config.xml)";
  1267. std::string LogHost = "DevPSGHD";
  1268. std::string moduleName = "DevPSGHD";
  1269. bool ret = initLogModule(
  1270. LogHost, // 主机名(用于日志路径中的{host}占位符)
  1271. moduleName, // 唯一模块名
  1272. strLogPath, // 配置文件路径
  1273. true // 是否输出到控制台(可选)
  1274. );
  1275. if (!ret) {
  1276. std::cerr << "Log init failed!" << std::endl;
  1277. return;
  1278. }
  1279. PSGHDSetLocalModuleName(moduleName);
  1280. m_SCFDllName = GetConnectDLL(m_ConfigFileName);
  1281. // 绑定当前动态库的模块名(调用自身实现的接口)
  1282. FINFO("Prepare is OK.SCFDllName is {$}", m_SCFDllName);
  1283. }
  1284. std::string nsGEN::PSGHDDriver::DriverProbe()
  1285. {
  1286. FINFO("DriverProbe in \n");
  1287. ResDataObject r_config, HardwareInfo;
  1288. if (r_config.loadFile(m_ConfigFileName.c_str()))
  1289. {
  1290. HardwareInfo.add("MajorID", r_config["CONFIGURATION"]["MajorID"]);
  1291. HardwareInfo.add("MinorID", r_config["CONFIGURATION"]["MinorID"]);
  1292. HardwareInfo.add("VendorID", r_config["CONFIGURATION"]["VendorID"]);
  1293. HardwareInfo.add("ProductID", r_config["CONFIGURATION"]["ProductID"]);
  1294. HardwareInfo.add("SerialID", r_config["CONFIGURATION"]["SerialID"]);
  1295. }
  1296. else
  1297. {
  1298. HardwareInfo.add("MajorID", "Generator");
  1299. HardwareInfo.add("MinorID", "Dr");
  1300. HardwareInfo.add("VendorID", "PSGHD");
  1301. HardwareInfo.add("ProductID", "HF");
  1302. HardwareInfo.add("SerialID", "Drv");
  1303. }
  1304. string ret = HardwareInfo.encode();
  1305. return ret;
  1306. }
  1307. bool nsGEN::PSGHDDriver::ReConnection()
  1308. {
  1309. Disconnect();
  1310. FINFO("ReConnection:SCF Disconnect");
  1311. ResDataObject Connection = GetConnectParam(m_ConfigFileName);
  1312. FINFO("ReConnection:{$} \n", Connection.encode());
  1313. auto erCode = m_scfWrapper->Connect(Connection, &PSGHDDriver::callbackPackageProcess, SCF_PACKET_TRANSFER, 3000);
  1314. if (erCode == SCF_SUCCEED)
  1315. {
  1316. Sleep(1000);
  1317. // 重新设置数据接收回调
  1318. m_scfWrapper->SetDataReceivedCallback([this](const char* data, uint32_t length) {
  1319. this->Dequeue(data, length);
  1320. });
  1321. // 启动自动接收
  1322. m_scfWrapper->StartAutoReceive();
  1323. return true;
  1324. }
  1325. else
  1326. {
  1327. FINFO("ReConnection failed");
  1328. }
  1329. return false;
  1330. }
  1331. bool nsGEN::PSGHDDriver::Connect()
  1332. {
  1333. std::lock_guard<std::mutex> lock(m_connectionMutex);
  1334. const auto currentState = m_connectionState.load();
  1335. auto now = std::chrono::steady_clock::now();
  1336. // 1. 处理可重试的失败状态
  1337. if (currentState == ConnectionState::Failed) {
  1338. if ((now - m_lastConnectionAttempt) >= RETRY_INTERVAL && m_connectionRetryCount < MAX_RETRY_COUNT) {
  1339. m_connectionState = ConnectionState::Disconnected;
  1340. }
  1341. else {
  1342. return false; // 不满足重试条件,直接返回
  1343. }
  1344. }
  1345. // 2. 检查无效状态(正在连接/已连接但实际有效)
  1346. if (currentState == ConnectionState::Connecting) {
  1347. FINFO("Already connecting (type: {$})",
  1348. m_currentConnType == ConnectionType::Serial ? "Serial" : "Ethernet");
  1349. return true;
  1350. }
  1351. if (currentState == ConnectionState::Connected && m_scfWrapper && m_scfWrapper->IsConnected()) {
  1352. FINFO("Already connected (type: {$})",
  1353. m_currentConnType == ConnectionType::Serial ? "Serial" : "Ethernet");
  1354. return true;
  1355. }
  1356. // 3. 检查重试间隔
  1357. if (m_connectionRetryCount > 0 && (now - m_lastConnectionAttempt) < RETRY_INTERVAL) {
  1358. FINFO("Retry in {$}s (type: {$})",
  1359. std::chrono::duration_cast<std::chrono::seconds>(RETRY_INTERVAL - (now - m_lastConnectionAttempt)).count(),
  1360. m_currentConnType == ConnectionType::Serial ? "Serial" : "Ethernet");
  1361. return false;
  1362. }
  1363. ResDataObject connParam = GetConnectParam(m_ConfigFileName);
  1364. std::string connPortStr = "";
  1365. std::string connTypeStr = (std::string)connParam["type"]; // 从配置读取type字段
  1366. m_currentConnType = (connTypeStr == "COM") ? ConnectionType::Serial : ConnectionType::Ethernet;
  1367. if (m_currentConnType == ConnectionType::Serial)
  1368. {
  1369. connPortStr = (std::string)connParam["port"];// 从配置读取port字段
  1370. // 查找配置端口在现有端口列表中的位置
  1371. auto it = std::find(m_serialPorts.begin(), m_serialPorts.end(), connPortStr);
  1372. if (it == m_serialPorts.end()) {
  1373. // 配置的端口不在列表中,添加到首位
  1374. FINFO("Configured serial port {$} not found, adding to front of port list", connPortStr);
  1375. m_serialPorts.insert(m_serialPorts.begin(), connPortStr);
  1376. }
  1377. else if (it != m_serialPorts.begin()) {
  1378. // 配置的端口存在但不在首位,移动到首位
  1379. FINFO("Moving configured serial port {$} to front of port list", connPortStr);
  1380. m_serialPorts.erase(it);
  1381. m_serialPorts.insert(m_serialPorts.begin(), connPortStr);
  1382. }
  1383. }
  1384. // 4. 执行连接流程
  1385. m_connectionState = ConnectionState::Connecting;
  1386. m_lastConnectionAttempt = now;
  1387. std::string connInfo;
  1388. try {
  1389. if (m_currentConnType == ConnectionType::Serial) {
  1390. // 串口连接:使用当前索引的端口
  1391. std::string currentPort = m_serialPorts[m_currentSerialPortIndex];
  1392. connParam.update("port", currentPort.c_str()); // 将当前尝试的端口写入参数
  1393. connInfo = "Serial (port: " + currentPort + ")";
  1394. }
  1395. else {
  1396. // 网口连接:直接使用配置参数
  1397. connInfo = "Ethernet (ip: " + std::string(connParam["ip"]) + ")";
  1398. }
  1399. FINFO("Enter Connect ({$}), config: {$}", connInfo, connParam.encode());
  1400. if (!m_scfWrapper->Initialize(m_SCFDllName)) {
  1401. FINFO("Init failed: {$}", m_scfWrapper->GetLastError());
  1402. m_connectionState = ConnectionState::Failed;
  1403. return false;
  1404. }
  1405. m_scfWrapper->SetDataReceivedCallback([this](const char* data, uint32_t length) {
  1406. this->Dequeue(data, length);
  1407. });
  1408. auto erCode = m_scfWrapper->Connect(connParam, &PSGHDDriver::callbackPackageProcess, SCF_NORMAL_TRANSFER, 3000);
  1409. if (erCode != SCF_SUCCEED || !m_scfWrapper->StartAutoReceive()) {
  1410. FINFO("Connect failed (code: {$}) for {$}", erCode, connInfo);
  1411. m_scfWrapper->Disconnect();
  1412. m_connectionState = ConnectionState::Failed;
  1413. // 串口连接:未遍历完所有端口时,优先切换端口重试(不计入总重试次数)
  1414. if (m_currentConnType == ConnectionType::Serial) {
  1415. int nextIndex = (m_currentSerialPortIndex + 1) % m_serialPorts.size();
  1416. // 判断是否已遍历所有端口(当前索引是最后一个时,nextIndex会回到0)
  1417. bool allPortsTried = (nextIndex == 0);
  1418. if (!allPortsTried) {
  1419. // 未遍历完所有端口:切换到下一端口,不增加重试计数
  1420. m_currentSerialPortIndex = nextIndex;
  1421. m_connectionRetryCount = 0;
  1422. FINFO("Trying next serial port: {$}", m_serialPorts[nextIndex]);
  1423. return false; // 触发外部线程立即尝试下一端口
  1424. }
  1425. else {
  1426. // 已遍历所有端口:重置到第一个端口,增加重试计数(进入间隔等待)
  1427. m_currentSerialPortIndex = 0;
  1428. m_connectionRetryCount++;
  1429. FINFO("All serial ports tried, retry count: {$}/{$}", m_connectionRetryCount, MAX_RETRY_COUNT);
  1430. return false;
  1431. }
  1432. }
  1433. // 所有端口失败(串口)或网口失败,才增加总重试计数
  1434. m_connectionRetryCount++;
  1435. return false;
  1436. }
  1437. // 连接成功:重置状态
  1438. m_connectionState = ConnectionState::Connected;
  1439. m_connectionRetryCount = 0;
  1440. m_currentSerialPortIndex = 0; // 重置串口端口索引
  1441. FINFO("Connected successfully ({$})", connInfo);
  1442. return true;
  1443. }
  1444. catch (const std::exception& e) {
  1445. FINFO("Exception for {$}: {$}", connInfo, e.what());
  1446. m_connectionState = ConnectionState::Failed;
  1447. m_connectionRetryCount++;
  1448. return false;
  1449. }
  1450. }
  1451. auto nsGEN::PSGHDDriver::CreateDevice(int index) -> std::unique_ptr <IODevice>
  1452. {
  1453. FINFO("CreateDevice in\n");
  1454. m_pDevice = new PSGHDDevice(EventCenter, m_scfWrapper, m_ConfigFileName);
  1455. auto dev = std::unique_ptr <IODevice>(new IODevice(m_pDevice));
  1456. FINFO("CreateDevice out\n");
  1457. return dev;
  1458. }
  1459. void nsGEN::PSGHDDriver::FireNotify(int code, std::string key, std::string content)
  1460. {
  1461. EventCenter->OnNotify(code, key, content);
  1462. }
  1463. bool nsGEN::PSGHDDriver::isConnected() const
  1464. {
  1465. const auto state = m_connectionState.load();
  1466. // 1. 连接中/实际已连接:返回true(无需重连)
  1467. if (state == ConnectionState::Connecting || (m_scfWrapper && m_scfWrapper->IsConnected())) {
  1468. FINFO(state == ConnectionState::Connecting ? "Connecting in progress" : "Already connected");
  1469. return true;
  1470. }
  1471. // 2. 失败状态处理:判断是否允许重试
  1472. if (state == ConnectionState::Failed) {
  1473. auto now = std::chrono::steady_clock::now();
  1474. const auto timeSinceLast = now - m_lastConnectionAttempt;
  1475. // 2.1 达到最大重试次数,但超过重置间隔:重置计数,允许重新重试
  1476. if (m_connectionRetryCount >= MAX_RETRY_COUNT && timeSinceLast >= RESET_RETRY_AFTER) {
  1477. FINFO("Max retries reached, resetting count after {$}s",
  1478. std::chrono::duration_cast<std::chrono::seconds>(timeSinceLast).count());
  1479. m_connectionRetryCount = 0; // 重置计数(因mutable修饰,const函数可修改)
  1480. }
  1481. // 2.2 不适合重连(时间未到 或 次数仍超限):返回true阻止重连
  1482. if (timeSinceLast < RETRY_INTERVAL || m_connectionRetryCount >= MAX_RETRY_COUNT) {
  1483. FINFO(timeSinceLast < RETRY_INTERVAL ?
  1484. "Retry later ({$}s)" : "Max retries, waiting {$}s to reset",
  1485. std::chrono::duration_cast<std::chrono::seconds>(
  1486. timeSinceLast < RETRY_INTERVAL ? RETRY_INTERVAL - timeSinceLast : RESET_RETRY_AFTER - timeSinceLast
  1487. ).count()
  1488. );
  1489. return true;
  1490. }
  1491. }
  1492. // 3. 其他情况(适合重连):返回false触发Connect()
  1493. return false;
  1494. }
  1495. std::string nsGEN::PSGHDDriver::GetResource()
  1496. {
  1497. FDEBUG("GetResource");
  1498. ResDataObject r_config, temp;
  1499. if (!temp.loadFile(m_ConfigFileName.c_str()))
  1500. {
  1501. return "";
  1502. }
  1503. m_ConfigAll = temp;
  1504. r_config = temp["CONFIGURATION"];
  1505. m_Configurations = r_config;
  1506. ResDataObject DescriptionTemp;
  1507. ResDataObject DescriptionSend;
  1508. ResDataObject m_DescriptionSend;
  1509. ResDataObject ListTemp;
  1510. string strTemp = ""; //用于读取字符串配置信息
  1511. string strIndex = ""; //用于读取配置信息中的List项
  1512. int nTemp = -1; //用于读取整型配置信息
  1513. char sstream[10] = { 0 }; //用于转换值
  1514. string strValue = ""; //用于存储配置的值
  1515. string strType = ""; //用于存储配置的类型 int/float/string...
  1516. /***
  1517. * 1. 通过循环,将所有配置项写到pDeviceConfig
  1518. * 2. 记录配置项的内部key以及配置类型,类型对应了不同配置文件路径,用于读写真实值
  1519. ***/
  1520. try
  1521. {
  1522. //便利ConfigToolInfo 中 所有的AttributeInfo 属性段
  1523. int nConfigInfoCount = (int)m_Configurations["ConfigToolInfo"].GetKeyCount("AttributeInfo");
  1524. m_pAttribute->clear();
  1525. m_pDescription->clear();
  1526. for (int nInfoIndex = 0; nInfoIndex < nConfigInfoCount; nInfoIndex++)
  1527. {
  1528. DescriptionTemp.clear();
  1529. DescriptionSend.clear();
  1530. ListTemp.clear();
  1531. //AttributeType
  1532. strTemp = (string)m_Configurations["ConfigToolInfo"][nInfoIndex]["AttributeDescripition"]["Type"];
  1533. DescriptionTemp.add(ConfKey::CcosType, strTemp.c_str());//CcosGeneratorAttribute
  1534. DescriptionSend.add(ConfKey::CcosType, strTemp.c_str());//CcosGeneratorAttribute
  1535. strType = strTemp; //记录配置项的类型
  1536. //AttributeKey
  1537. //1. 根据AttributeType,内部key和配置路径,拿到当前的真实值
  1538. strTemp = (string)m_Configurations["ConfigToolInfo"][nInfoIndex]["InnerKey"];
  1539. nTemp = (int)m_Configurations["ConfigToolInfo"][nInfoIndex]["PathID"];
  1540. GetDeviceConfigValue(r_config, strTemp.c_str(), nTemp, strValue); //得到strValue的值
  1541. //printf("********************************innerkey=%s --strValue = %s\n", strTemp.c_str(), strValue.c_str());
  1542. //2. 赋值
  1543. strTemp = (string)m_Configurations["ConfigToolInfo"][nInfoIndex]["AttributeKey"];
  1544. if ("int" == strType)
  1545. {
  1546. (*m_pAttribute).add(strTemp.c_str(), atoi(strValue.c_str()));
  1547. }
  1548. else if ("float" == strType)
  1549. {
  1550. (*m_pAttribute).add(strTemp.c_str(), atoi(strValue.c_str()));
  1551. }
  1552. else //其它先按string类型处理
  1553. {
  1554. (*m_pAttribute).add(strTemp.c_str(), strValue.c_str());
  1555. }
  1556. //printf("********************************outkey =%s --strValue = %s\n", strTemp.c_str(), strValue.c_str());
  1557. //AttributeAccess
  1558. strTemp = (string)m_Configurations["ConfigToolInfo"][nInfoIndex]["AttributeDescripition"]["Access"];
  1559. DescriptionTemp.add(ConfKey::CcosAccess, strTemp.c_str());
  1560. DescriptionSend.add(ConfKey::CcosAccess, strTemp.c_str());
  1561. /*
  1562. //AttributeRangeMin
  1563. strTemp = (string)m_Configurations["ConfigToolInfo"][nInfoIndex]["AttributeDescripition"]["RangeMin"];
  1564. if (strTemp != "") //不需要的配置项为空
  1565. {
  1566. DescriptionTemp.add(ConfKey::CcosRangeMin, strTemp.c_str());
  1567. }
  1568. //AttributeRangeMax
  1569. strTemp = (string)m_Configurations["ConfigToolInfo"][nInfoIndex]["AttributeDescripition"]["RangeMax"];
  1570. if (strTemp != "") //不需要的配置项为空
  1571. {
  1572. DescriptionTemp.add(ConfKey::CcosRangeMax, strTemp.c_str());
  1573. }
  1574. */
  1575. //AttributeList
  1576. nTemp = m_Configurations["ConfigToolInfo"][nInfoIndex]["AttributeDescripition"]["ListNum"];
  1577. if (nTemp > 0) //ListNum不大于0时说明不需要list配置
  1578. {
  1579. for (int nListIndex = 0; nListIndex < nTemp; nListIndex++)
  1580. {
  1581. strTemp = (string)m_Configurations["ConfigToolInfo"][nInfoIndex]["AttributeDescripition"]["ListInfo"][nListIndex];
  1582. auto temKey = std::to_string(nListIndex);
  1583. ListTemp.add(temKey.c_str(), strTemp.c_str());
  1584. }
  1585. DescriptionTemp.add(ConfKey::CcosList, ListTemp);
  1586. DescriptionSend.add(ConfKey::CcosList, ListTemp.encode());
  1587. }
  1588. //AttributeRequired
  1589. strTemp = (string)m_Configurations["ConfigToolInfo"][nInfoIndex]["AttributeDescripition"]["Required"];
  1590. DescriptionTemp.add(ConfKey::CcosRequired, strTemp.c_str());
  1591. DescriptionSend.add(ConfKey::CcosRequired, strTemp.c_str());
  1592. //AttributeDefaultValue
  1593. strTemp = (string)m_Configurations["ConfigToolInfo"][nInfoIndex]["AttributeDescripition"]["DefaultValue"];
  1594. if (strTemp != "") //不需要的配置项为空
  1595. {
  1596. DescriptionTemp.add(ConfKey::CcosDefaultValue, strTemp.c_str());
  1597. DescriptionSend.add(ConfKey::CcosDefaultValue, strTemp.c_str());
  1598. }
  1599. strTemp = (string)m_Configurations["ConfigToolInfo"][nInfoIndex]["AttributeKey"];
  1600. (*m_pDescription).add(strTemp.c_str(), DescriptionTemp);
  1601. m_DescriptionSend.add(strTemp.c_str(), DescriptionSend.encode());
  1602. }
  1603. }
  1604. catch (ResDataObjectExption& e)
  1605. {
  1606. FERROR("Get config error: {$}", e.what());
  1607. return "";
  1608. }
  1609. ResDataObject resDeviceResource;
  1610. resDeviceResource.add(ConfKey::CcosGeneratorAttribute, (*m_pAttribute));
  1611. resDeviceResource.add(ConfKey::CcosGeneratorDescription, (*m_pDescription));
  1612. ResDataObject DescriptionTempEx;
  1613. DescriptionTempEx.add(ConfKey::CcosGeneratorConfig, resDeviceResource);
  1614. m_DeviceConfig.clear();
  1615. m_DeviceConfig = DescriptionTempEx;
  1616. //Debug("local ************* get resource over {$}", DescriptionTempEx.encode());
  1617. //printf("local ************* get resource over %s \n", DescriptionTempEx.encode());
  1618. resDeviceResource.clear();
  1619. resDeviceResource.add(ConfKey::CcosGeneratorAttribute, (*m_pAttribute));
  1620. resDeviceResource.add(ConfKey::CcosGeneratorDescription, m_DescriptionSend);
  1621. DescriptionTempEx.clear();
  1622. DescriptionTempEx.add(ConfKey::CcosGeneratorConfig, resDeviceResource);
  1623. m_DeviceConfigSend.clear();
  1624. m_DeviceConfigSend = DescriptionTempEx;
  1625. string res = m_DeviceConfigSend.encode();
  1626. //printf("%s", res.c_str());
  1627. //Debug("get resource over {$}", DescriptionTempEx.encode());
  1628. //("************* get resource over %s \n", DescriptionTempEx.encode());
  1629. return res;
  1630. }
  1631. std::string nsGEN::PSGHDDriver::DeviceProbe()
  1632. {
  1633. FINFO("std::string nsGEN::PSGHDDriver::DeviceProbe() in\n");
  1634. ResDataObject r_config, HardwareInfo;
  1635. if (r_config.loadFile(m_ConfigFileName.c_str()))
  1636. {
  1637. HardwareInfo.add("MajorID", r_config["CONFIGURATION"]["MajorID"]);
  1638. HardwareInfo.add("MinorID", r_config["CONFIGURATION"]["MinorID"]);
  1639. HardwareInfo.add("VendorID", r_config["CONFIGURATION"]["VendorID"]);
  1640. HardwareInfo.add("ProductID", r_config["CONFIGURATION"]["ProductID"]);
  1641. HardwareInfo.add("SerialID", r_config["CONFIGURATION"]["SerialID"]);
  1642. }
  1643. else
  1644. {
  1645. HardwareInfo.add("MajorID", "Generator");
  1646. HardwareInfo.add("MinorID", "Dr");
  1647. HardwareInfo.add("VendorID", "PSGHD");
  1648. HardwareInfo.add("ProductID", "HF");
  1649. HardwareInfo.add("SerialID", "Dev");
  1650. }
  1651. string ret = HardwareInfo.encode();
  1652. FINFO("std::string nsGEN::PSGHDDriver::DeviceProbe() out\n");
  1653. return ret;
  1654. }
  1655. void nsGEN::PSGHDDriver::Disconnect()
  1656. {
  1657. if (m_scfWrapper) {
  1658. m_scfWrapper->StopAutoReceive();
  1659. m_scfWrapper->Disconnect();
  1660. }
  1661. }
  1662. void nsGEN::PSGHDDriver::Dequeue(const char* Packet, DWORD Length)
  1663. {
  1664. DecodeFrame(Packet, Length);
  1665. }
  1666. PACKET_RET nsGEN::PSGHDDriver::callbackPackageProcess(const char* RecData, uint32_t nLength, uint32_t& PacketLength)
  1667. {
  1668. // 日志:进入数据包处理函数,记录输入长度
  1669. FINFO("[PSGHDDriver] 开始处理数据包,输入长度: [{$}]", nLength);
  1670. if (nLength < 3)
  1671. {
  1672. // 日志:数据包长度不足
  1673. FINFO("[PSGHDDriver] 数据包长度小于3,无效数据包,返回PACKET_USELESS");
  1674. return PACKET_USELESS;
  1675. }
  1676. // 查找STX (0x02)
  1677. int startIndex = -1;
  1678. for (uint32_t i = 0; i < nLength; i++)
  1679. {
  1680. if (RecData[i] == 0x02)
  1681. {
  1682. startIndex = i;
  1683. break;
  1684. }
  1685. }
  1686. if (startIndex == -1)
  1687. {
  1688. // 日志:未找到STX标记
  1689. FINFO("[PSGHDDriver] 未找到STX(0x02)标记,返回PACKET_USELESS");
  1690. return PACKET_USELESS;
  1691. }
  1692. // 日志:找到STX标记
  1693. FINFO("[PSGHDDriver] 找到STX(0x02)标记,位置: [{$}]", startIndex);
  1694. // 查找CRLF (0x0D, 0x0A)
  1695. int endIndex = -1;
  1696. for (uint32_t i = startIndex + 1; i < nLength - 1; i++)
  1697. {
  1698. if (RecData[i] == 0x0D && RecData[i + 1] == 0x0A)
  1699. {
  1700. endIndex = i;
  1701. break;
  1702. }
  1703. }
  1704. if (endIndex == -1)
  1705. {
  1706. // 日志:未找到CRLF结束标记
  1707. FINFO("[PSGHDDriver] 未找到CRLF(0x0D,0x0A)结束标记,返回PACKET_NOPACKET");
  1708. return PACKET_NOPACKET;
  1709. }
  1710. // 日志:找到CRLF标记
  1711. FINFO("[PSGHDDriver] 找到CRLF(0x0D,0x0A)标记,位置: [{$}]", endIndex);
  1712. // 计算数据包长度
  1713. PacketLength = endIndex + 2 - startIndex;
  1714. FINFO("[PSGHDDriver] 数据包处理完成,有效长度: [{$}],返回PACKET_ISPACKET", PacketLength);
  1715. return PACKET_ISPACKET;
  1716. }
  1717. bool nsGEN::PSGHDDriver::GetDeviceConfig(std::string& Cfg)
  1718. {
  1719. Cfg = m_DeviceConfigSend.encode();
  1720. printf("GetDeviceConfig over , %s", Cfg.c_str());
  1721. return true;
  1722. }
  1723. bool nsGEN::PSGHDDriver::SetDeviceConfig(std::string Cfg)
  1724. {
  1725. FINFO("--Func-- SetDeviceConfig {$}\n", Cfg.c_str());
  1726. printf("\n--Func-- SetDeviceConfig %s\n", Cfg.c_str());
  1727. ResDataObject DeviceConfig;
  1728. DeviceConfig.decode(Cfg.c_str());
  1729. ResDataObject DescriptionTempEx;
  1730. DescriptionTempEx = DeviceConfig["DeviceConfig"]["Attribute"];
  1731. FDEBUG("Attribute:{$}", DescriptionTempEx.encode());
  1732. bool bSaveFile = false; //true:重新保存配置文件
  1733. string strAccess = "";
  1734. for (int i = 0; i < DescriptionTempEx.size(); i++)
  1735. {
  1736. string strKey = DescriptionTempEx.GetKey(i);
  1737. FINFO("{$}", strKey.c_str());
  1738. printf("%s\n", strKey.c_str());
  1739. try
  1740. {
  1741. if (m_pAttribute->GetFirstOf(strKey.c_str()) >= 0)
  1742. {
  1743. strAccess = (string)(*m_pDescription)[strKey.c_str()]["Access"];
  1744. if ("RW" == strAccess)
  1745. {
  1746. //修改对应配置,在其他单元的配置项要同时调用其修改函数修改真实值
  1747. //1. 修改内存中的值,用于给上层发消息
  1748. (*m_pAttribute)[strKey.c_str()] = DescriptionTempEx[i];
  1749. //2. 拿到Innerkey
  1750. int nConfigInfoCount = (int)m_Configurations["ConfigToolInfo"].GetKeyCount("AttributeInfo");
  1751. FINFO("nConfigInfoCount {$}", nConfigInfoCount);
  1752. string strTemp = ""; //存储AttributeKey
  1753. for (int nInfoIndex = 0; nInfoIndex < nConfigInfoCount; nInfoIndex++)
  1754. {
  1755. strTemp = (string)m_Configurations["ConfigToolInfo"][nInfoIndex]["AttributeKey"];
  1756. if (strTemp == strKey)
  1757. {
  1758. strTemp = (string)m_Configurations["ConfigToolInfo"][nInfoIndex]["InnerKey"];
  1759. break;
  1760. }
  1761. }
  1762. //3. 修改配置文件中的值
  1763. if (SetDeviceConfigValue(m_Configurations, strTemp.c_str(), 1, DescriptionTempEx[i]))
  1764. {
  1765. FDEBUG("SetDeviceConfigValue over");
  1766. bSaveFile = true;
  1767. }
  1768. }
  1769. else
  1770. {
  1771. FINFO("{$} is not a RW configuration item", strKey.c_str());
  1772. }
  1773. }
  1774. else
  1775. {
  1776. FINFO("without this attribute {$}", strKey.c_str());
  1777. }
  1778. }
  1779. catch (ResDataObjectExption& e)
  1780. {
  1781. printf("\nSetDriverConfig crashed: %s\n", e.what());
  1782. FERROR("SetDriverConfig crashed: {$}", e.what());
  1783. return false;
  1784. }
  1785. }
  1786. if (bSaveFile)
  1787. {
  1788. //3. 重新保存配置文件
  1789. SaveConfigFile(true);
  1790. }
  1791. return true;
  1792. }
  1793. bool nsGEN::PSGHDDriver::SaveConfigFile(bool bSendNotify)
  1794. {
  1795. m_ConfigAll["CONFIGURATION"] = m_Configurations;
  1796. bool bRt = m_ConfigAll.SaveFile(m_ConfigFileName.c_str());
  1797. FINFO("SaveConfigFile over {$}", bRt);
  1798. return true;
  1799. }
  1800. bool nsGEN::PSGHDDriver::GetDeviceConfigValue(ResDataObject config, const char* pInnerKey, int nPathID, string& strValue)
  1801. {
  1802. strValue = "";
  1803. string strTemp = pInnerKey;
  1804. if (1 == nPathID) //从DriverConfig路径下每个DPC自己的配置文件读取
  1805. {
  1806. int pos = 0;
  1807. ResDataObject resTemp = config;
  1808. while ((pos = strTemp.find_first_of(',')) != string::npos)
  1809. {
  1810. string Key = strTemp.substr(0, pos);
  1811. string TempValue = resTemp[Key.c_str()].encode();
  1812. // printf("-TempValue=== %s", TempValue.c_str());
  1813. resTemp.clear();
  1814. resTemp.decode(TempValue.c_str());
  1815. strTemp = strTemp.substr(pos + 1, strTemp.length() - pos - 1);
  1816. //printf("-************--%s", strTemp.c_str());
  1817. }
  1818. if (strTemp != "")
  1819. {
  1820. strValue = (string)resTemp[strTemp.c_str()];
  1821. }
  1822. else
  1823. {
  1824. strValue = (string)resTemp;
  1825. }
  1826. }
  1827. //printf("------------%s", strValue.c_str());
  1828. return true;
  1829. }
  1830. bool nsGEN::PSGHDDriver::SetDeviceConfigValue(ResDataObject& config, const char* pInnerKey, int nPathID, const char* szValue)
  1831. {
  1832. string strTemp = pInnerKey;
  1833. FINFO("Begin to change {$} item value to {$}", pInnerKey, szValue);
  1834. if (1 == nPathID) //从DriverConfig路径下每个DPC自己的配置文件读取
  1835. {
  1836. try {
  1837. int pos = 0;
  1838. ResDataObject* resTemp = &config;
  1839. while ((pos = strTemp.find_first_of(',')) != string::npos)
  1840. {
  1841. string Key = strTemp.substr(0, pos);
  1842. resTemp = &(*resTemp)[Key.c_str()];
  1843. strTemp = strTemp.substr(pos + 1, strTemp.length() - pos - 1);
  1844. }
  1845. if (strTemp != "")
  1846. {
  1847. (*resTemp)[strTemp.c_str()] = szValue;
  1848. }
  1849. else
  1850. {
  1851. *resTemp = szValue;
  1852. }
  1853. }
  1854. catch (ResDataObjectExption& e)
  1855. {
  1856. FERROR("SetDriverConfigvalue crashed: {$}", e.what());
  1857. return false;
  1858. }
  1859. }
  1860. return true;
  1861. }
  1862. //-----------------------------------------------------------------------------
  1863. // GetIODriver & CreateIODriver
  1864. //-----------------------------------------------------------------------------
  1865. static nsGEN::PSGHDDriver gIODriver;
  1866. extern "C" CCOS::Dev::IODriver * GetIODriver() // 返回静态对象的引用, 调用者不能删除 !
  1867. {
  1868. return &gIODriver;
  1869. }
  1870. extern "C" CCOS::Dev::IODriver * CreateIODriver() // 返回新对象, 调用者必须自行删除此对象 !
  1871. {
  1872. pIODriver = new nsGEN::PSGHDDriver();
  1873. return pIODriver;
  1874. }