CCOS.Dev.Generator.PSG_HD.cpp 67 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178
  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. // 构造协议格式:<STX>CMD<SP>ARG;<CS><CR><LF>
  601. char strSendCommand[100] = { 0 };
  602. int len = 0;
  603. strSendCommand[len++] = 0x02; // STX
  604. // 复制命令部分
  605. memcpy(strSendCommand + len, strCommand, length);
  606. len += length;
  607. // 添加分号
  608. strSendCommand[len++] = ';';
  609. // 计算校验和(从STX后开始到分号';')
  610. uint16_t sum = 0;
  611. for (int i = 1; i < len; i++)
  612. {
  613. sum += (uint8_t)strSendCommand[i];
  614. }
  615. uint8_t checksum = (uint8_t)(sum & 0xFF);
  616. checksum = 0x100 - checksum;
  617. checksum &= 0x7F;
  618. checksum |= 0x40;
  619. // 添加校验和
  620. strSendCommand[len++] = checksum;
  621. strSendCommand[len++] = 0x0D; // CR
  622. strSendCommand[len++] = 0x0A; // LF
  623. // 打印数据包前16字节的十六进制(含控制字符)便于调试
  624. /*std::string hexStr;
  625. int printLen = std::min(len, 16);
  626. for (int i = 0; i < printLen; i++) {
  627. char buf[4];
  628. snprintf(buf, sizeof(buf), "%02X ", (uint8_t)strSendCommand[i]);
  629. hexStr += buf;
  630. }
  631. if (len > 16) hexStr += "...";
  632. FINFO("Packet (hex, total len: {$}) - [{$}]", len, hexStr);*/
  633. // 发送
  634. unsigned int retLength;
  635. if (m_SCF->Lock(1000) == WAIT_OBJECT_0)
  636. {
  637. int result = m_SCF->SendPacket(strSendCommand, len, nTimeOut, retLength);
  638. m_SCF->Unlock();
  639. if (result == SCF_SUCCEED) {
  640. // 打印发送命令的关键信息(命令内容+完整包长度)
  641. FINFO("Command to send - [{$}] (raw command length: {$}) - Success - Sent {$} bytes",
  642. std::string(strCommand, length), len, retLength);
  643. return RET_STATUS::RET_SUCCEED;
  644. }
  645. else {
  646. FINFO("HWSend: Failed - SendPacket returned error code: {$}", result);
  647. return RET_STATUS::RET_FAILED;
  648. }
  649. }
  650. else
  651. {
  652. FINFO("HWSend: Failed - Could not acquire lock within 1000ms");
  653. return RET_STATUS::RET_FAILED;
  654. }
  655. return RET_STATUS::RET_SUCCEED;
  656. }
  657. void nsGEN::PSGHDDevice::FireNotify(string key, int context)
  658. {
  659. char szInfo[64] = { 0 };
  660. snprintf(szInfo, sizeof(szInfo), "%d", context); // Linux 标准函数
  661. std::string str = szInfo;
  662. EventCenter->OnNotify(1, key, str);
  663. }
  664. void nsGEN::PSGHDDevice::FireNotify(std::string key, float context)
  665. {
  666. char szInfo[16] = { 0 };
  667. snprintf(szInfo, sizeof(szInfo), "%.2f", context); // Linux 标准函数
  668. std::string str = szInfo;
  669. EventCenter->OnNotify(1, key, str);
  670. }
  671. void nsGEN::PSGHDDevice::FireNotify(std::string key, std::string context)
  672. {
  673. EventCenter->OnNotify(1, key, context);
  674. }
  675. void nsGEN::PSGHDDevice::FireErrorMessage(const bool Act, const int Code, const char* ResInfo)
  676. {
  677. string ErrorCode("PSGHD_ERR_");
  678. ErrorCode += std::to_string(Code);
  679. int level = PSG_HD_REGULATION_LEVEL::REG_ERRO;
  680. if (Act)
  681. {
  682. FINFO("add {$}:{$}", ErrorCode.c_str(), ResInfo);
  683. m_MSGUnit->AddErrorMessage(ErrorCode.c_str(), level, ResInfo);
  684. }
  685. else
  686. {
  687. FINFO("del {$}:{$}", ErrorCode.c_str(), ResInfo);
  688. m_MSGUnit->DelErrorMessage(ErrorCode.c_str(), level, ResInfo);
  689. }
  690. }
  691. void nsGEN::PSGHDDevice::FireWarnMessage(const bool Act, const int Code, const char* ResInfo)
  692. {
  693. string ErrorCode("PSGHD_WAR_");
  694. ErrorCode += std::to_string(Code);
  695. int level = PSG_HD_REGULATION_LEVEL::REG_WARN;
  696. if (Act)
  697. {
  698. FINFO("add {$}:{$}", ErrorCode.c_str(), ResInfo);
  699. m_MSGUnit->AddWarnMessage(ErrorCode.c_str(), level, ResInfo);
  700. }
  701. else
  702. {
  703. FINFO("del {$}:{$}", ErrorCode.c_str(), ResInfo);
  704. m_MSGUnit->DelWarnMessage(ErrorCode.c_str(), level, ResInfo);
  705. }
  706. }
  707. void nsGEN::PSGHDDevice::OnCallBack()
  708. {
  709. // 无操作处理函数
  710. auto HWNotProcess = [](const char* value, int length) -> void
  711. {
  712. FINFO("HWNotProcess: Command data (len: {$}) no need to process", length);
  713. };
  714. // 处理VREF响应 (电压参考)
  715. auto HWVREF = [this](const char* data, int length) -> void
  716. {
  717. // 需至少4字节数据(XXXX)
  718. if (length < 4) {
  719. FINFO("HWVREF: Invalid data length ({$} < 4), skip", length);
  720. return;
  721. }
  722. char kvStr[5] = { 0 };
  723. strncpy(kvStr, data, 4);
  724. int kvValue = atoi(kvStr);
  725. float actualKV = kvValue / 10.0f; // 转换为kV
  726. m_DoseUnit.m_KV->Update(actualKV);
  727. FireNotify(AttrKey::KV, m_DoseUnit.m_KV->JSGet());
  728. FINFO("HWVREF: Parsed actual KV = {$} kV", actualKV);
  729. };
  730. // 处理IREF响应 (电流参考)
  731. auto HWIREF = [this](const char* data, int length) -> void
  732. {
  733. if (length < 4) { // 需4字节(XXXX)
  734. FINFO("HWIREF: Invalid data length ({$} < 4), skip", length);
  735. return;
  736. }
  737. char maStr[5] = { 0 };
  738. strncpy(maStr, data, 4); // 直接取data
  739. int maValue = atoi(maStr);
  740. float actualMA = maValue / 100.0f; // 转换为mA
  741. m_DoseUnit.m_MA->Update(actualMA);
  742. FireNotify(AttrKey::MA, m_DoseUnit.m_MA->JSGet());
  743. FINFO("HWIREF: Parsed actual MA = {$} mA", actualMA);
  744. };
  745. // 处理ENBL响应 (X射线使能)
  746. auto HWENBL = [this](const char* data, int length) -> void
  747. {
  748. if (length < 1) { // 需1字节(X)
  749. FINFO("HWENBL: Invalid data length ({$} < 1), skip", length);
  750. return;
  751. }
  752. // 直接取data[0](无需跳过"ENBL ")
  753. char enblStr = data[0];
  754. bool isEnabled = (enblStr == '1');
  755. FINFO("HWENBL: X-ray enable status = {$}", isEnabled ? "Enabled" : "Disabled");
  756. };
  757. // 处理WDTE响应 (看门狗定时器)
  758. auto HWWDTE = [this](const char* data, int length) -> void
  759. {
  760. if (length < 1) { // 需1字节(X)
  761. FINFO("HWWDTE: Invalid data length ({$} < 1), skip", length);
  762. return;
  763. }
  764. char wdtStr = data[0]; // 直接取data[0]
  765. bool isWdtEnabled = (wdtStr == '1');
  766. FINFO("HWWDTE: Watchdog status = {$}", isWdtEnabled ? "Enabled" : "Disabled");
  767. };
  768. // 处理WDTT响应 (看门狗定时器重置)
  769. auto HWWDTT = [this](const char* data, int length) -> void
  770. {
  771. if (length < 1) { // 基础长度校验
  772. FINFO("HWWDTT: Invalid data length ({$} < 1), skip", length);
  773. return;
  774. }
  775. FINFO("HWWDTT: Watchdog timer reset response received");
  776. };
  777. // 处理CLR响应 (故障清除)
  778. auto HWCLR = [this](const char* data, int length) -> void
  779. {
  780. if (length < 1) {
  781. FINFO("HWCLR: Invalid data length ({$} < 1), skip", length);
  782. return;
  783. }
  784. FINFO("HWCLR: Received fault clear response, performing fault clearing");
  785. };
  786. // 处理SMS响应 (曝光时间)
  787. auto HWSMS = [this](const char* data, int length) -> void
  788. {
  789. if (length < 7) { // 需7字节(XXXXXXX)
  790. FINFO("HWSMS: Invalid data length ({$} < 7), skip", length);
  791. return;
  792. }
  793. char smsStr[8] = { 0 };
  794. strncpy(smsStr, data, 7); // 直接取data
  795. long timeValue = atol(smsStr);
  796. float exposureTime = timeValue * 0.01f; // 转换为ms
  797. m_DoseUnit.m_MS->Update(exposureTime);
  798. FireNotify(AttrKey::MS, m_DoseUnit.m_MS->JSGet());
  799. FINFO("HWSMS: Parsed exposure time = {$} ms", exposureTime);
  800. };
  801. // 处理FLT响应 (故障状态)
  802. auto HWFLT = [this](const char* data, int length) -> void
  803. {
  804. if (length < 3) { // 需3字节(XXX)
  805. FINFO("HWFLT: Invalid data length ({$} < 3), skip", length);
  806. return;
  807. }
  808. char faultStr[4] = { 0 };
  809. strncpy(faultStr, data, 3);
  810. int faultCode = atoi(faultStr);
  811. if (faultCode != 0)
  812. {
  813. static const std::unordered_map<int, std::string> errorMessages = {
  814. {2, "Charging circuit abnormal"}, {3, "Storage chip damaged"}, {136, "Filament current 1 exceeds limit"},
  815. {140, "Anode kV exceeds limit, exposure aborted abnormally"}, {142, "High-voltage generator or tube arcing, exposure aborted abnormally"},
  816. {165, "Bus voltage too low during high-voltage generator startup"}, {205, "Second-stage handswitch pressed during high-voltage generator wake-up or startup"},
  817. {206, "High-voltage generator low battery, please charge"}, {208, "Exposure interval too short, please expose later"},
  818. {209, "Parameter adjustment forbidden during exposure"}, {210, "First-stage handswitch repeated triggering, please use a single handswitch for exposure operation"},
  819. {216, "Battery being charged"}, {218, "kV parameter exceeds limit"}, {219, "mA parameter exceeds limit"},
  820. {220, "ms parameter exceeds limit"}, {229, "High-voltage generator power exceeds limit"}, {230, "Tube power exceeds limit"},
  821. {231, "Frame rate parameter exceeds limit"}, {249, "High-voltage generator bus voltage exceeds limit"}, {255, "kV establishment timeout"},
  822. {259, "Handswitch released in advance during exposure"}, {260, "Parameter adjustment forbidden during exposure"}, {263, "kV too high during exposure, exposure aborted abnormally"},
  823. {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"}
  824. };
  825. static const std::unordered_set<int> firstSixErrors = { 2, 3, 136, 140, 142, 165 };
  826. char errorCodeStr[20];
  827. snprintf(errorCodeStr, sizeof(errorCodeStr), "PSGHD_FLT_%d", faultCode);
  828. int level = 1;
  829. auto it = errorMessages.find(faultCode);
  830. if (it != errorMessages.end())
  831. {
  832. if (firstSixErrors.count(faultCode))
  833. m_MSGUnit->AddErrorMessage(errorCodeStr, level, it->second.c_str());
  834. else
  835. m_MSGUnit->AddWarnMessage(errorCodeStr, level, it->second.c_str());
  836. FINFO("HWFLT: Fault code {$} detected - {$}", faultCode, it->second.c_str());
  837. }
  838. }
  839. else
  840. {
  841. char errorCodeStr[20];
  842. snprintf(errorCodeStr, sizeof(errorCodeStr), "PSGHD_FLT_0");
  843. int level = 1;
  844. m_MSGUnit->DelWarnMessage(errorCodeStr, level, "");
  845. m_MSGUnit->DelErrorMessage(errorCodeStr, level, "");
  846. FINFO("HWFLT: Fault cleared (fault code 0)");
  847. }
  848. };
  849. // 处理工作相位响应 (RST<aaa>)
  850. auto HWPhase = [this](const char* data, int length) -> void
  851. {
  852. if (length < 3) { // 需3字节(aaa)
  853. FINFO("HWPhase: Invalid data length ({$} < 3), skip", length);
  854. return;
  855. }
  856. // 设备首次连接时禁止曝光!
  857. if (m_isFirstHWPhase) {
  858. SetExpDisable();
  859. m_isFirstHWPhase = false;
  860. }
  861. char phaseCodeStr[4] = { 0 };
  862. strncpy(phaseCodeStr, data, 3);
  863. int phaseCode = atoi(phaseCodeStr);
  864. auto updateAndNotify = [this](nsGEN::AttrKey::GENERATOR_STATUS status)
  865. {
  866. if (m_DoseUnit.m_GenState->Update(status))
  867. {
  868. FireNotify(AttrKey::GENSTATE, m_DoseUnit.m_GenState->JSGet());
  869. FINFO("HWPhase: Generator status updated to {$}", static_cast<int>(status));
  870. }
  871. };
  872. switch (phaseCode)
  873. {
  874. case 1: updateAndNotify(nsGEN::AttrKey::GENERATOR_STATUS_INIT); break;
  875. case 7: updateAndNotify(nsGEN::AttrKey::GENERATOR_STATUS_ERROR); break;
  876. case 9: case 11: updateAndNotify(nsGEN::AttrKey::GENERATOR_STATUS_EXP); break;
  877. default: FINFO("HWPhase: Unsupported phase code {$}", phaseCode); break;
  878. }
  879. };
  880. auto HWVMON = [this](const char* data, int length) -> void
  881. {
  882. if (length < 4) { // 需4字节(XXXX)
  883. FINFO("HWVMON: Invalid data length ({$} < 4), skip", length);
  884. return;
  885. }
  886. char vmonStr[5] = { 0 };
  887. strncpy(vmonStr, data, 4); // 直接取data
  888. int vmonValue = atoi(vmonStr);
  889. float actualVMON = vmonValue / 10.0f; // 转换为kV
  890. m_DoseUnit.m_PostKV->Update(actualVMON);
  891. FireNotify(AttrKey::POSTKV, m_DoseUnit.m_PostKV->JSGet());
  892. FINFO("HWVMON: Parsed monitoring KV = {$} kV", actualVMON);
  893. };
  894. auto HWIMON = [this](const char* data, int length) -> void
  895. {
  896. if (length < 4) { // 需4字节(XXXX)
  897. FINFO("HWIMON: Invalid data length ({$} < 4), skip", length);
  898. return;
  899. }
  900. char imonStr[5] = { 0 };
  901. strncpy(imonStr, data, 4); // 直接取data
  902. int imonValue = atoi(imonStr);
  903. float actualIMON = imonValue / 100.0f; // 转换为mA
  904. m_DoseUnit.m_PostMA->Update(actualIMON);
  905. FireNotify(AttrKey::POSTMA, m_DoseUnit.m_PostMA->JSGet());
  906. FINFO("HWIMON: Parsed monitoring MA = {$} mA", actualIMON);
  907. };
  908. auto HWRAT = [this](const char* data, int length) -> void
  909. {
  910. if (length < 7) { // 需7字节(XXXXXXX)
  911. FINFO("HWRAT: Invalid data length ({$} < 7), skip", length);
  912. return;
  913. }
  914. char ratStr[8] = { 0 };
  915. strncpy(ratStr, data, 7); // 直接取data
  916. int ratio = atoi(ratStr);
  917. float actualRatio = ratio / 100.0f;
  918. m_DoseUnit.m_PostMS->Update(actualRatio);
  919. FireNotify(m_DoseUnit.m_PostMS->GetKey(), m_DoseUnit.m_PostMS->JSGet());
  920. FINFO("HWRAT: Parsed ratio parameter = {$}", actualRatio);
  921. };
  922. auto HWPOW = [this](const char* data, int length) -> void
  923. {
  924. if (length < 1) { // 需1字节(X)
  925. FINFO("HWPOW: Invalid data length ({$} < 1), skip", length);
  926. return;
  927. }
  928. char powStr = data[0]; // 直接取data[0]
  929. bool isPowerOn = (powStr == '1');
  930. FINFO("HWPOW: Power status = {$}", isPowerOn ? "On" : "Off");
  931. };
  932. auto HWEOK = [this](const char* data, int length) -> void
  933. {
  934. if (length < 1) { // 需1字节(X)
  935. FINFO("HWEOK: Invalid data length ({$} < 1), skip", length);
  936. return;
  937. }
  938. char eokStr = data[0]; // 直接取data[0]
  939. bool isReady = (eokStr == '1');
  940. if (isReady)
  941. {
  942. if (m_DoseUnit.m_GenState->Update(nsGEN::AttrKey::GENERATOR_STATUS_STANDBY))
  943. {
  944. //FireNotify(AttrKey::GENSTATE, m_DoseUnit.m_GenState->JSGet());
  945. FINFO("HWEOK: Device ready, status updated to STANDBY");
  946. }
  947. }
  948. else
  949. {
  950. if (m_DoseUnit.m_GenState->Update(nsGEN::AttrKey::GENERATOR_STATUS_SLEEP))
  951. {
  952. //FireNotify(AttrKey::GENSTATE, m_DoseUnit.m_GenState->JSGet());
  953. FINFO("HWEOK: Device not ready, status updated to SLEEP");
  954. }
  955. }
  956. };
  957. auto HWDSW = [this](const char* data, int length) -> void
  958. {
  959. if (length < 1) { // 需1字节(X)
  960. FINFO("HWDSW: Invalid data length ({$} < 1), skip", length);
  961. return;
  962. }
  963. char eokStr = data[0]; // 直接取data[0]
  964. bool isReady = (eokStr == '1');
  965. if (isReady && m_DoseUnit.m_GenState->Get()== nsGEN::AttrKey::GENERATOR_STATUS_STANDBY)
  966. {
  967. FireNotify(AttrKey::GENSTATE, m_DoseUnit.m_GenState->JSGet());
  968. FINFO("HWDSW: Device ready, status updated to STANDBY");
  969. }
  970. else
  971. {
  972. m_DoseUnit.m_GenState->Update(nsGEN::AttrKey::GENERATOR_STATUS_SLEEP);
  973. FireNotify(AttrKey::GENSTATE, m_DoseUnit.m_GenState->JSGet());
  974. FINFO("HWDSW: Device not ready, status updated to SLEEP");
  975. }
  976. };
  977. auto HWECD = [this](const char* data, int length) -> void
  978. {
  979. if (length < 3) { // 需3字节(XXX)
  980. FINFO("HWECD: Invalid data length ({$} < 3), skip", length);
  981. return;
  982. }
  983. char ecdStr[4] = { 0 };
  984. strncpy(ecdStr, data, 3); // 直接取data
  985. int countdown = atoi(ecdStr);
  986. FINFO("HWECD: High-voltage OK light countdown = {$}s", countdown);
  987. };
  988. auto HWSOC = [this](const char* data, int length) -> void
  989. {
  990. if (length < 3) { // 需3字节(XXX)
  991. FINFO("HWSOC: Invalid data length ({$} < 3), skip", length);
  992. return;
  993. }
  994. char socStr[4] = { 0 };
  995. strncpy(socStr, data, 3); // 直接取data
  996. int remainingPower = atoi(socStr);
  997. FINFO("HWSOC: Generator remaining power = {$}%", remainingPower);
  998. };
  999. auto HWFLX = [this](const char* data, int length) -> void
  1000. {
  1001. if (length < 1) { // 需1字节(X)
  1002. FINFO("HWFLX: Invalid data length ({$} < 1), skip", length);
  1003. return;
  1004. }
  1005. char flxStr[2] = { 0 };
  1006. strncpy(flxStr, data, 1);
  1007. int fluoroMode = atoi(flxStr);
  1008. FINFO("HWFLX: Fluorescence mode detected = {$}", fluoroMode);
  1009. if (fluoroMode == 2)
  1010. {
  1011. m_DoseUnit.m_GenSynState->Update(AttrKey::GENERATOR_RAD_XRAYON);
  1012. FireNotify(m_DoseUnit.m_GenSynState->GetKey(), m_DoseUnit.m_GenSynState->JSGet());
  1013. FINFO("HWFLX: X-ray turned ON (mode 2)");
  1014. }
  1015. else if (fluoroMode == 1)
  1016. {
  1017. m_DoseUnit.m_GenSynState->Update(AttrKey::GENERATOR_RAD_READY);
  1018. m_hGenPostEvent->ResetEvent();
  1019. FireNotify(m_DoseUnit.m_GenSynState->GetKey(), m_DoseUnit.m_GenSynState->JSGet());
  1020. FINFO("HWFLX: X-ray ready (mode 1)");
  1021. }
  1022. else if (fluoroMode == 0)
  1023. {
  1024. m_bGenBusy = false;
  1025. m_DoseUnit.m_GenSynState->Update(AttrKey::GENERATOR_RAD_XRAYOFF);
  1026. FireNotify(m_DoseUnit.m_GenSynState->GetKey(), m_DoseUnit.m_GenSynState->JSGet());
  1027. FINFO("HWFLX: X-ray turned OFF (mode 0)");
  1028. }
  1029. };
  1030. auto HWVER = [this](const char* data, int length) -> void
  1031. {
  1032. if (length < 6) { // 需6字节(XXXXXX)
  1033. FINFO("HWVER: Invalid data length ({$} < 6), skip", length);
  1034. return;
  1035. }
  1036. char verStr[7] = { 0 };
  1037. strncpy(verStr, data, 6); // 直接取data
  1038. std::string version(verStr);
  1039. FINFO("HWVER: Generator version = {$}", version);
  1040. };
  1041. auto HWVSN = [this](const char* data, int length) -> void
  1042. {
  1043. if (length < 8) { // 需8字节(XXXXXXXX)
  1044. FINFO("HWVSN: Invalid data length ({$} < 8), skip", length);
  1045. return;
  1046. }
  1047. char vsnStr[9] = { 0 };
  1048. strncpy(vsnStr, data, 8); // 直接取data
  1049. std::string serialNumber(vsnStr);
  1050. FINFO("HWVSN: Generator serial number = {$}", serialNumber);
  1051. };
  1052. auto HWMAS = [this](const char* data, int length) -> void
  1053. {
  1054. if (length < 3) { // 至少3字节(避免atof解析错误)
  1055. FINFO("HWMAS: Invalid data length ({$} < 3), skip", length);
  1056. return;
  1057. }
  1058. float fmas = atof(data) / 100.0f; // 直接用data解析
  1059. if (m_DoseUnit.m_MAS->Update(fmas))
  1060. {
  1061. FireNotify(AttrKey::MAS, m_DoseUnit.m_MAS->JSGet());
  1062. FINFO("HWMAS: Parsed MAS value = {$}", fmas);
  1063. }
  1064. };
  1065. auto HWAP = [this](const char* data, int length) -> void
  1066. {
  1067. if (length < 3) { // 至少3字节(避免atof解析错误)
  1068. FINFO("HWAP: Invalid data length ({$} < 3), skip", length);
  1069. return;
  1070. }
  1071. float fmas = atof(data) / 100.0f; // 直接用data解析
  1072. m_DoseUnit.m_PostMAS->Update(fmas);
  1073. FireNotify(AttrKey::POSTMAS, m_DoseUnit.m_PostMAS->JSGet());
  1074. FINFO("HWAP: Parsed POSTMAS value = {$}", fmas);
  1075. };
  1076. auto HWWS = [this](const char* data, int length) -> void
  1077. {
  1078. if (length < 1) { // 需1字节以上(避免atoi解析错误)
  1079. FINFO("HWWS: Invalid data length ({$} < 1), skip", length);
  1080. return;
  1081. }
  1082. int nValue = atoi(data); // 直接用data解析
  1083. m_DoseUnit.m_WS->Update(nValue);
  1084. FireNotify(m_DoseUnit.m_WS->GetKey(), m_DoseUnit.m_WS->JSGet());
  1085. FINFO("HWWS: Parsed WS parameter = {$}", nValue);
  1086. };
  1087. auto HWEHE = [this](const char* data, int length) -> void
  1088. {
  1089. if (length < 1) { // 需1字节以上
  1090. FINFO("HWEHE: Invalid data length ({$} < 1), skip", length);
  1091. return;
  1092. }
  1093. m_iHeartBeats = 0;
  1094. int nhe = atoi(data); // 直接用data解析
  1095. if (m_DoseUnit.m_HE->Update(nhe))
  1096. {
  1097. FireNotify(m_DoseUnit.m_HE->GetKey(), m_DoseUnit.m_HE->JSGet());
  1098. FINFO("HWEHE: Parsed HE parameter = {$}", nhe);
  1099. }
  1100. };
  1101. arFrame.clear();
  1102. // 指令映射表补充
  1103. arFrame.push_back(tFrameMapping("VREF ", 5, HWVREF));
  1104. arFrame.push_back(tFrameMapping("IREF ", 5, HWIREF));
  1105. arFrame.push_back(tFrameMapping("VMON ", 5, HWVMON));
  1106. arFrame.push_back(tFrameMapping("IMON ", 5, HWIMON));
  1107. arFrame.push_back(tFrameMapping("ENBL ", 5, HWENBL));
  1108. arFrame.push_back(tFrameMapping("RST ", 4, HWPhase));
  1109. arFrame.push_back(tFrameMapping("SMS ", 4, HWSMS));
  1110. arFrame.push_back(tFrameMapping("RAT ", 4, HWRAT));
  1111. arFrame.push_back(tFrameMapping("POW ", 4, HWPOW));
  1112. arFrame.push_back(tFrameMapping("EOK ", 4, HWEOK));
  1113. arFrame.push_back(tFrameMapping("ECD ", 4, HWECD));
  1114. arFrame.push_back(tFrameMapping("FLX ", 4, HWFLX));
  1115. arFrame.push_back(tFrameMapping("FLT ", 4, HWFLT));
  1116. arFrame.push_back(tFrameMapping("RHE ", 4, HWEHE));
  1117. arFrame.push_back(tFrameMapping("VER ", 4, HWVER));
  1118. arFrame.push_back(tFrameMapping("VSN ", 4, HWVSN));
  1119. arFrame.push_back(tFrameMapping("CLR", 4, HWCLR));
  1120. arFrame.push_back(tFrameMapping("EC", 2, HWNotProcess));
  1121. arFrame.push_back(tFrameMapping("PW", 2, HWNotProcess));
  1122. arFrame.push_back(tFrameMapping("MX", 2, HWMAS));
  1123. arFrame.push_back(tFrameMapping("WS", 2, HWWS));
  1124. }
  1125. bool nsGEN::PSGHDDevice::ReConnect()
  1126. {
  1127. FINFO("Enter PSG_reConnect");
  1128. m_SCF->Disconnect();
  1129. if (!pIODriver)
  1130. {
  1131. FINFO("PSG_reConnect:Driver null");
  1132. }
  1133. else
  1134. {
  1135. // 需要将 pIODriver 转换为 PSGHDDriver*
  1136. PSGHDDriver* driver = dynamic_cast<PSGHDDriver*>(pIODriver.get());
  1137. if (driver && driver->ReConnection())
  1138. {
  1139. FireErrorMessage(false, 1, "lost Connect");
  1140. m_bConnectFlag = true;
  1141. FINFO("PSG_reConnect success");
  1142. return true;
  1143. }
  1144. else
  1145. {
  1146. FINFO("PSG_reConnect failed");
  1147. }
  1148. }
  1149. return false;
  1150. }
  1151. int nsGEN::PSGHDDevice::GetGenState()
  1152. {
  1153. if (m_DoseUnit.m_GenState != NULL)
  1154. {
  1155. return m_DoseUnit.m_GenState->Get();
  1156. }
  1157. else
  1158. {
  1159. return 0;
  1160. }
  1161. }
  1162. int nsGEN::PSGHDDevice::LoadConfig(string configfile)
  1163. {
  1164. FINFO("=====================LoadConfig=========================");
  1165. // 检查文件是否存在
  1166. std::ifstream file(configfile);
  1167. if (!file) {
  1168. // 文件不存在,直接返回空的Connection对象
  1169. FINFO("Config file does not exist: {$}", configfile.c_str());
  1170. return -1;
  1171. }
  1172. if (m_bIsConfigLoaded)
  1173. {
  1174. FINFO("Configuration already loaded.");
  1175. return 0;
  1176. }
  1177. ResDataObject temp;
  1178. temp.loadFile(configfile.c_str());
  1179. m_GenConfig = temp["CONFIGURATION"];
  1180. TransJsonText(m_GenConfig);
  1181. if (m_GenConfig.GetKeyCount("loopEnable") > 0)
  1182. {
  1183. m_bExtraFlag = (int)m_GenConfig["loopEnable"];
  1184. }
  1185. if (m_GenConfig.GetKeyCount(ConfKey::CcosTubeInfo) > 0)
  1186. {
  1187. string tempValue = (string)m_GenConfig[ConfKey::CcosTubeInfo];
  1188. m_DoseUnit.m_TubeInfo.reset(new TUBEINFOMould(tempValue));
  1189. FireNotify(AttrKey::TUBEINFO, m_DoseUnit.m_TubeInfo->JSGet());
  1190. }
  1191. if (m_GenConfig.GetKeyCount(ConfKey::CcosFocusSmall) > 0)
  1192. {
  1193. float tempValue = (float)m_GenConfig[ConfKey::CcosFocusSmall];
  1194. m_DoseUnit.m_FocusSmall = tempValue;
  1195. }
  1196. if (m_GenConfig.GetKeyCount(ConfKey::CcosFocusLarge) > 0)
  1197. {
  1198. float tempValue = (float)m_GenConfig[ConfKey::CcosFocusLarge];
  1199. m_DoseUnit.m_FocusLarge = tempValue;
  1200. }
  1201. if (m_GenConfig.GetKeyCount("GenCtrlMode") > 0)
  1202. {
  1203. m_nCtlMode = (float)m_GenConfig["GenCtrlMode"];//default 2
  1204. float tempValue = (float)m_GenConfig[ConfKey::CcosFocusLarge];
  1205. }
  1206. if (m_GenConfig.GetKeyCount("USECECMD") > 0)
  1207. {
  1208. m_bUseCECmd = (bool)m_GenConfig["USECECMD"];
  1209. }
  1210. m_bIsConfigLoaded = true;
  1211. return 0;
  1212. }
  1213. bool nsGEN::PSGHDDevice::ECHO(void)
  1214. {
  1215. return HWSend("ECH", 3);
  1216. }
  1217. bool nsGEN::PSGHDDevice::StartHardwareStatusThread()
  1218. {
  1219. if (!m_pHardwareStatusThread.joinable())
  1220. {
  1221. m_pHardwareStatusThread = std::thread(HardwareStatusThread, this);
  1222. return true;
  1223. }
  1224. return false;
  1225. }
  1226. void PSGHDDevice::HardwareStatusThread(PSGHDDevice* pParam)
  1227. {
  1228. if (pParam == nullptr)
  1229. {
  1230. return;
  1231. }
  1232. PSGHDDevice* pCurGen = pParam;
  1233. int messageIndex = 0;
  1234. while (pCurGen->m_bExtraFlag)
  1235. {
  1236. // 获取当前循环时间并休眠
  1237. int currentLoopTime = pCurGen->m_iLoopTime;
  1238. Sleep(currentLoopTime);
  1239. // 每5次循环发送状态查询命令
  1240. if (messageIndex % 5 == 0&& !pCurGen->m_bSleepState)
  1241. {
  1242. pCurGen->HWSend("RHE", 3);
  1243. Sleep(100);
  1244. pCurGen->HWSend("RST", 3);
  1245. Sleep(100);
  1246. pCurGen->HWSend("EOK", 3);
  1247. }
  1248. messageIndex++;
  1249. // 防止messageIndex无限增长导致溢出
  1250. if (messageIndex >= INT_MAX - 10)
  1251. {
  1252. messageIndex = 0;
  1253. }
  1254. }
  1255. // 线程退出时重置心跳标志
  1256. }
  1257. //-----------------------------------------------------------------------------
  1258. // PSGHDDriver
  1259. //-----------------------------------------------------------------------------
  1260. nsGEN::PSGHDDriver::PSGHDDriver()
  1261. : m_scfWrapper(std::make_shared<SCFWrapper>())
  1262. {
  1263. m_pAttribute.reset(new ResDataObject());
  1264. m_pDescription.reset(new ResDataObject());
  1265. }
  1266. nsGEN::PSGHDDriver::~PSGHDDriver()
  1267. {
  1268. Disconnect();
  1269. }
  1270. void nsGEN::PSGHDDriver::Prepare()
  1271. {
  1272. // 初始化日志系统
  1273. std::string strLogPath = GetProcessDirectory() + R"(/Conf/log_config.xml)";
  1274. std::string LogHost = "DevPSGHD";
  1275. std::string moduleName = "DevPSGHD";
  1276. bool ret = initLogModule(
  1277. LogHost, // 主机名(用于日志路径中的{host}占位符)
  1278. moduleName, // 唯一模块名
  1279. strLogPath, // 配置文件路径
  1280. true // 是否输出到控制台(可选)
  1281. );
  1282. if (!ret) {
  1283. std::cerr << "Log init failed!" << std::endl;
  1284. return;
  1285. }
  1286. PSGHDSetLocalModuleName(moduleName);
  1287. m_SCFDllName = GetConnectDLL(m_ConfigFileName);
  1288. // 绑定当前动态库的模块名(调用自身实现的接口)
  1289. FINFO("Prepare is OK.SCFDllName is {$}", m_SCFDllName);
  1290. }
  1291. std::string nsGEN::PSGHDDriver::DriverProbe()
  1292. {
  1293. FINFO("DriverProbe in \n");
  1294. ResDataObject r_config, HardwareInfo;
  1295. if (r_config.loadFile(m_ConfigFileName.c_str()))
  1296. {
  1297. HardwareInfo.add("MajorID", r_config["CONFIGURATION"]["MajorID"]);
  1298. HardwareInfo.add("MinorID", r_config["CONFIGURATION"]["MinorID"]);
  1299. HardwareInfo.add("VendorID", r_config["CONFIGURATION"]["VendorID"]);
  1300. HardwareInfo.add("ProductID", r_config["CONFIGURATION"]["ProductID"]);
  1301. HardwareInfo.add("SerialID", r_config["CONFIGURATION"]["SerialID"]);
  1302. }
  1303. else
  1304. {
  1305. HardwareInfo.add("MajorID", "Generator");
  1306. HardwareInfo.add("MinorID", "Dr");
  1307. HardwareInfo.add("VendorID", "PSGHD");
  1308. HardwareInfo.add("ProductID", "HF");
  1309. HardwareInfo.add("SerialID", "Drv");
  1310. }
  1311. string ret = HardwareInfo.encode();
  1312. return ret;
  1313. }
  1314. bool nsGEN::PSGHDDriver::ReConnection()
  1315. {
  1316. Disconnect();
  1317. FINFO("ReConnection:SCF Disconnect");
  1318. ResDataObject Connection = GetConnectParam(m_ConfigFileName);
  1319. FINFO("ReConnection:{$} \n", Connection.encode());
  1320. auto erCode = m_scfWrapper->Connect(Connection, &PSGHDDriver::callbackPackageProcess, SCF_PACKET_TRANSFER, 3000);
  1321. if (erCode == SCF_SUCCEED)
  1322. {
  1323. Sleep(1000);
  1324. // 重新设置数据接收回调
  1325. m_scfWrapper->SetDataReceivedCallback([this](const char* data, uint32_t length) {
  1326. this->Dequeue(data, length);
  1327. });
  1328. // 启动自动接收
  1329. m_scfWrapper->StartAutoReceive();
  1330. return true;
  1331. }
  1332. else
  1333. {
  1334. FINFO("ReConnection failed");
  1335. }
  1336. return false;
  1337. }
  1338. bool nsGEN::PSGHDDriver::Connect()
  1339. {
  1340. std::lock_guard<std::mutex> lock(m_connectionMutex);
  1341. const auto currentState = m_connectionState.load();
  1342. auto now = std::chrono::steady_clock::now();
  1343. // 1. 处理可重试的失败状态
  1344. if (currentState == ConnectionState::Failed) {
  1345. if ((now - m_lastConnectionAttempt) >= RETRY_INTERVAL && m_connectionRetryCount < MAX_RETRY_COUNT) {
  1346. m_connectionState = ConnectionState::Disconnected;
  1347. }
  1348. else {
  1349. return false; // 不满足重试条件,直接返回
  1350. }
  1351. }
  1352. // 2. 检查无效状态(正在连接/已连接但实际有效)
  1353. if (currentState == ConnectionState::Connecting) {
  1354. FINFO("Already connecting (type: {$})",
  1355. m_currentConnType == ConnectionType::Serial ? "Serial" : "Ethernet");
  1356. return true;
  1357. }
  1358. if (currentState == ConnectionState::Connected && m_scfWrapper && m_scfWrapper->IsConnected()) {
  1359. FINFO("Already connected (type: {$})",
  1360. m_currentConnType == ConnectionType::Serial ? "Serial" : "Ethernet");
  1361. return true;
  1362. }
  1363. // 3. 检查重试间隔
  1364. if (m_connectionRetryCount > 0 && (now - m_lastConnectionAttempt) < RETRY_INTERVAL) {
  1365. FINFO("Retry in {$}s (type: {$})",
  1366. std::chrono::duration_cast<std::chrono::seconds>(RETRY_INTERVAL - (now - m_lastConnectionAttempt)).count(),
  1367. m_currentConnType == ConnectionType::Serial ? "Serial" : "Ethernet");
  1368. return false;
  1369. }
  1370. ResDataObject connParam = GetConnectParam(m_ConfigFileName);
  1371. std::string connPortStr = "";
  1372. std::string connTypeStr = (std::string)connParam["type"]; // 从配置读取type字段
  1373. m_currentConnType = (connTypeStr == "COM") ? ConnectionType::Serial : ConnectionType::Ethernet;
  1374. if (m_currentConnType == ConnectionType::Serial)
  1375. {
  1376. connPortStr = (std::string)connParam["port"];// 从配置读取port字段
  1377. // 查找配置端口在现有端口列表中的位置
  1378. auto it = std::find(m_serialPorts.begin(), m_serialPorts.end(), connPortStr);
  1379. if (it == m_serialPorts.end()) {
  1380. // 配置的端口不在列表中,添加到首位
  1381. FINFO("Configured serial port {$} not found, adding to front of port list", connPortStr);
  1382. m_serialPorts.insert(m_serialPorts.begin(), connPortStr);
  1383. }
  1384. else if (it != m_serialPorts.begin()) {
  1385. // 配置的端口存在但不在首位,移动到首位
  1386. FINFO("Moving configured serial port {$} to front of port list", connPortStr);
  1387. m_serialPorts.erase(it);
  1388. m_serialPorts.insert(m_serialPorts.begin(), connPortStr);
  1389. }
  1390. }
  1391. // 4. 执行连接流程
  1392. m_connectionState = ConnectionState::Connecting;
  1393. m_lastConnectionAttempt = now;
  1394. std::string connInfo;
  1395. try {
  1396. if (m_currentConnType == ConnectionType::Serial) {
  1397. // 串口连接:使用当前索引的端口
  1398. std::string currentPort = m_serialPorts[m_currentSerialPortIndex];
  1399. connParam.update("port", currentPort.c_str()); // 将当前尝试的端口写入参数
  1400. connInfo = "Serial (port: " + currentPort + ")";
  1401. }
  1402. else {
  1403. // 网口连接:直接使用配置参数
  1404. connInfo = "Ethernet (ip: " + std::string(connParam["ip"]) + ")";
  1405. }
  1406. FINFO("Enter Connect ({$}), config: {$}", connInfo, connParam.encode());
  1407. if (!m_scfWrapper->Initialize(m_SCFDllName)) {
  1408. FINFO("Init failed: {$}", m_scfWrapper->GetLastError());
  1409. m_connectionState = ConnectionState::Failed;
  1410. return false;
  1411. }
  1412. m_scfWrapper->SetDataReceivedCallback([this](const char* data, uint32_t length) {
  1413. this->Dequeue(data, length);
  1414. });
  1415. auto erCode = m_scfWrapper->Connect(connParam, &PSGHDDriver::callbackPackageProcess, SCF_NORMAL_TRANSFER, 3000);
  1416. if (erCode != SCF_SUCCEED || !m_scfWrapper->StartAutoReceive()) {
  1417. FINFO("Connect failed (code: {$}) for {$}", erCode, connInfo);
  1418. m_scfWrapper->Disconnect();
  1419. m_connectionState = ConnectionState::Failed;
  1420. // 串口连接:未遍历完所有端口时,优先切换端口重试(不计入总重试次数)
  1421. if (m_currentConnType == ConnectionType::Serial) {
  1422. int nextIndex = (m_currentSerialPortIndex + 1) % m_serialPorts.size();
  1423. // 判断是否已遍历所有端口(当前索引是最后一个时,nextIndex会回到0)
  1424. bool allPortsTried = (nextIndex == 0);
  1425. if (!allPortsTried) {
  1426. // 未遍历完所有端口:切换到下一端口,不增加重试计数
  1427. m_currentSerialPortIndex = nextIndex;
  1428. m_connectionRetryCount = 0;
  1429. FINFO("Trying next serial port: {$}", m_serialPorts[nextIndex]);
  1430. return false; // 触发外部线程立即尝试下一端口
  1431. }
  1432. else {
  1433. // 已遍历所有端口:重置到第一个端口,增加重试计数(进入间隔等待)
  1434. m_currentSerialPortIndex = 0;
  1435. m_connectionRetryCount++;
  1436. FINFO("All serial ports tried, retry count: {$}/{$}", m_connectionRetryCount, MAX_RETRY_COUNT);
  1437. return false;
  1438. }
  1439. }
  1440. // 所有端口失败(串口)或网口失败,才增加总重试计数
  1441. m_connectionRetryCount++;
  1442. return false;
  1443. }
  1444. // 连接成功:重置状态
  1445. m_connectionState = ConnectionState::Connected;
  1446. m_connectionRetryCount = 0;
  1447. m_currentSerialPortIndex = 0; // 重置串口端口索引
  1448. FINFO("Connected successfully ({$})", connInfo);
  1449. return true;
  1450. }
  1451. catch (const std::exception& e) {
  1452. FINFO("Exception for {$}: {$}", connInfo, e.what());
  1453. m_connectionState = ConnectionState::Failed;
  1454. m_connectionRetryCount++;
  1455. return false;
  1456. }
  1457. }
  1458. auto nsGEN::PSGHDDriver::CreateDevice(int index) -> std::unique_ptr <IODevice>
  1459. {
  1460. FINFO("CreateDevice in\n");
  1461. m_pDevice = new PSGHDDevice(EventCenter, m_scfWrapper, m_ConfigFileName);
  1462. auto dev = std::unique_ptr <IODevice>(new IODevice(m_pDevice));
  1463. FINFO("CreateDevice out\n");
  1464. return dev;
  1465. }
  1466. void nsGEN::PSGHDDriver::FireNotify(int code, std::string key, std::string content)
  1467. {
  1468. EventCenter->OnNotify(code, key, content);
  1469. }
  1470. bool nsGEN::PSGHDDriver::isConnected() const
  1471. {
  1472. const auto state = m_connectionState.load();
  1473. // 1. 连接中/实际已连接:返回true(无需重连)
  1474. if (state == ConnectionState::Connecting || (m_scfWrapper && m_scfWrapper->IsConnected())) {
  1475. FINFO(state == ConnectionState::Connecting ? "Connecting in progress" : "Already connected");
  1476. return true;
  1477. }
  1478. // 2. 失败状态处理:判断是否允许重试
  1479. if (state == ConnectionState::Failed) {
  1480. auto now = std::chrono::steady_clock::now();
  1481. const auto timeSinceLast = now - m_lastConnectionAttempt;
  1482. // 2.1 达到最大重试次数,但超过重置间隔:重置计数,允许重新重试
  1483. if (m_connectionRetryCount >= MAX_RETRY_COUNT && timeSinceLast >= RESET_RETRY_AFTER) {
  1484. FINFO("Max retries reached, resetting count after {$}s",
  1485. std::chrono::duration_cast<std::chrono::seconds>(timeSinceLast).count());
  1486. m_connectionRetryCount = 0; // 重置计数(因mutable修饰,const函数可修改)
  1487. }
  1488. // 2.2 不适合重连(时间未到 或 次数仍超限):返回true阻止重连
  1489. if (timeSinceLast < RETRY_INTERVAL || m_connectionRetryCount >= MAX_RETRY_COUNT) {
  1490. FINFO(timeSinceLast < RETRY_INTERVAL ?
  1491. "Retry later ({$}s)" : "Max retries, waiting {$}s to reset",
  1492. std::chrono::duration_cast<std::chrono::seconds>(
  1493. timeSinceLast < RETRY_INTERVAL ? RETRY_INTERVAL - timeSinceLast : RESET_RETRY_AFTER - timeSinceLast
  1494. ).count()
  1495. );
  1496. return true;
  1497. }
  1498. }
  1499. // 3. 其他情况(适合重连):返回false触发Connect()
  1500. return false;
  1501. }
  1502. std::string nsGEN::PSGHDDriver::GetResource()
  1503. {
  1504. FDEBUG("GetResource");
  1505. ResDataObject r_config, temp;
  1506. if (!temp.loadFile(m_ConfigFileName.c_str()))
  1507. {
  1508. return "";
  1509. }
  1510. m_ConfigAll = temp;
  1511. r_config = temp["CONFIGURATION"];
  1512. m_Configurations = r_config;
  1513. ResDataObject DescriptionTemp;
  1514. ResDataObject DescriptionSend;
  1515. ResDataObject m_DescriptionSend;
  1516. ResDataObject ListTemp;
  1517. string strTemp = ""; //用于读取字符串配置信息
  1518. string strIndex = ""; //用于读取配置信息中的List项
  1519. int nTemp = -1; //用于读取整型配置信息
  1520. char sstream[10] = { 0 }; //用于转换值
  1521. string strValue = ""; //用于存储配置的值
  1522. string strType = ""; //用于存储配置的类型 int/float/string...
  1523. /***
  1524. * 1. 通过循环,将所有配置项写到pDeviceConfig
  1525. * 2. 记录配置项的内部key以及配置类型,类型对应了不同配置文件路径,用于读写真实值
  1526. ***/
  1527. try
  1528. {
  1529. //便利ConfigToolInfo 中 所有的AttributeInfo 属性段
  1530. int nConfigInfoCount = (int)m_Configurations["ConfigToolInfo"].GetKeyCount("AttributeInfo");
  1531. m_pAttribute->clear();
  1532. m_pDescription->clear();
  1533. for (int nInfoIndex = 0; nInfoIndex < nConfigInfoCount; nInfoIndex++)
  1534. {
  1535. DescriptionTemp.clear();
  1536. DescriptionSend.clear();
  1537. ListTemp.clear();
  1538. //AttributeType
  1539. strTemp = (string)m_Configurations["ConfigToolInfo"][nInfoIndex]["AttributeDescripition"]["Type"];
  1540. DescriptionTemp.add(ConfKey::CcosType, strTemp.c_str());//CcosGeneratorAttribute
  1541. DescriptionSend.add(ConfKey::CcosType, strTemp.c_str());//CcosGeneratorAttribute
  1542. strType = strTemp; //记录配置项的类型
  1543. //AttributeKey
  1544. //1. 根据AttributeType,内部key和配置路径,拿到当前的真实值
  1545. strTemp = (string)m_Configurations["ConfigToolInfo"][nInfoIndex]["InnerKey"];
  1546. nTemp = (int)m_Configurations["ConfigToolInfo"][nInfoIndex]["PathID"];
  1547. GetDeviceConfigValue(r_config, strTemp.c_str(), nTemp, strValue); //得到strValue的值
  1548. //printf("********************************innerkey=%s --strValue = %s\n", strTemp.c_str(), strValue.c_str());
  1549. //2. 赋值
  1550. strTemp = (string)m_Configurations["ConfigToolInfo"][nInfoIndex]["AttributeKey"];
  1551. if ("int" == strType)
  1552. {
  1553. (*m_pAttribute).add(strTemp.c_str(), atoi(strValue.c_str()));
  1554. }
  1555. else if ("float" == strType)
  1556. {
  1557. (*m_pAttribute).add(strTemp.c_str(), atoi(strValue.c_str()));
  1558. }
  1559. else //其它先按string类型处理
  1560. {
  1561. (*m_pAttribute).add(strTemp.c_str(), strValue.c_str());
  1562. }
  1563. //printf("********************************outkey =%s --strValue = %s\n", strTemp.c_str(), strValue.c_str());
  1564. //AttributeAccess
  1565. strTemp = (string)m_Configurations["ConfigToolInfo"][nInfoIndex]["AttributeDescripition"]["Access"];
  1566. DescriptionTemp.add(ConfKey::CcosAccess, strTemp.c_str());
  1567. DescriptionSend.add(ConfKey::CcosAccess, strTemp.c_str());
  1568. /*
  1569. //AttributeRangeMin
  1570. strTemp = (string)m_Configurations["ConfigToolInfo"][nInfoIndex]["AttributeDescripition"]["RangeMin"];
  1571. if (strTemp != "") //不需要的配置项为空
  1572. {
  1573. DescriptionTemp.add(ConfKey::CcosRangeMin, strTemp.c_str());
  1574. }
  1575. //AttributeRangeMax
  1576. strTemp = (string)m_Configurations["ConfigToolInfo"][nInfoIndex]["AttributeDescripition"]["RangeMax"];
  1577. if (strTemp != "") //不需要的配置项为空
  1578. {
  1579. DescriptionTemp.add(ConfKey::CcosRangeMax, strTemp.c_str());
  1580. }
  1581. */
  1582. //AttributeList
  1583. nTemp = m_Configurations["ConfigToolInfo"][nInfoIndex]["AttributeDescripition"]["ListNum"];
  1584. if (nTemp > 0) //ListNum不大于0时说明不需要list配置
  1585. {
  1586. for (int nListIndex = 0; nListIndex < nTemp; nListIndex++)
  1587. {
  1588. strTemp = (string)m_Configurations["ConfigToolInfo"][nInfoIndex]["AttributeDescripition"]["ListInfo"][nListIndex];
  1589. auto temKey = std::to_string(nListIndex);
  1590. ListTemp.add(temKey.c_str(), strTemp.c_str());
  1591. }
  1592. DescriptionTemp.add(ConfKey::CcosList, ListTemp);
  1593. DescriptionSend.add(ConfKey::CcosList, ListTemp.encode());
  1594. }
  1595. //AttributeRequired
  1596. strTemp = (string)m_Configurations["ConfigToolInfo"][nInfoIndex]["AttributeDescripition"]["Required"];
  1597. DescriptionTemp.add(ConfKey::CcosRequired, strTemp.c_str());
  1598. DescriptionSend.add(ConfKey::CcosRequired, strTemp.c_str());
  1599. //AttributeDefaultValue
  1600. strTemp = (string)m_Configurations["ConfigToolInfo"][nInfoIndex]["AttributeDescripition"]["DefaultValue"];
  1601. if (strTemp != "") //不需要的配置项为空
  1602. {
  1603. DescriptionTemp.add(ConfKey::CcosDefaultValue, strTemp.c_str());
  1604. DescriptionSend.add(ConfKey::CcosDefaultValue, strTemp.c_str());
  1605. }
  1606. strTemp = (string)m_Configurations["ConfigToolInfo"][nInfoIndex]["AttributeKey"];
  1607. (*m_pDescription).add(strTemp.c_str(), DescriptionTemp);
  1608. m_DescriptionSend.add(strTemp.c_str(), DescriptionSend.encode());
  1609. }
  1610. }
  1611. catch (ResDataObjectExption& e)
  1612. {
  1613. FERROR("Get config error: {$}", e.what());
  1614. return "";
  1615. }
  1616. ResDataObject resDeviceResource;
  1617. resDeviceResource.add(ConfKey::CcosGeneratorAttribute, (*m_pAttribute));
  1618. resDeviceResource.add(ConfKey::CcosGeneratorDescription, (*m_pDescription));
  1619. ResDataObject DescriptionTempEx;
  1620. DescriptionTempEx.add(ConfKey::CcosGeneratorConfig, resDeviceResource);
  1621. m_DeviceConfig.clear();
  1622. m_DeviceConfig = DescriptionTempEx;
  1623. //Debug("local ************* get resource over {$}", DescriptionTempEx.encode());
  1624. //printf("local ************* get resource over %s \n", DescriptionTempEx.encode());
  1625. resDeviceResource.clear();
  1626. resDeviceResource.add(ConfKey::CcosGeneratorAttribute, (*m_pAttribute));
  1627. resDeviceResource.add(ConfKey::CcosGeneratorDescription, m_DescriptionSend);
  1628. DescriptionTempEx.clear();
  1629. DescriptionTempEx.add(ConfKey::CcosGeneratorConfig, resDeviceResource);
  1630. m_DeviceConfigSend.clear();
  1631. m_DeviceConfigSend = DescriptionTempEx;
  1632. string res = m_DeviceConfigSend.encode();
  1633. //printf("%s", res.c_str());
  1634. //Debug("get resource over {$}", DescriptionTempEx.encode());
  1635. //("************* get resource over %s \n", DescriptionTempEx.encode());
  1636. return res;
  1637. }
  1638. std::string nsGEN::PSGHDDriver::DeviceProbe()
  1639. {
  1640. FINFO("std::string nsGEN::PSGHDDriver::DeviceProbe() in\n");
  1641. ResDataObject r_config, HardwareInfo;
  1642. if (r_config.loadFile(m_ConfigFileName.c_str()))
  1643. {
  1644. HardwareInfo.add("MajorID", r_config["CONFIGURATION"]["MajorID"]);
  1645. HardwareInfo.add("MinorID", r_config["CONFIGURATION"]["MinorID"]);
  1646. HardwareInfo.add("VendorID", r_config["CONFIGURATION"]["VendorID"]);
  1647. HardwareInfo.add("ProductID", r_config["CONFIGURATION"]["ProductID"]);
  1648. HardwareInfo.add("SerialID", r_config["CONFIGURATION"]["SerialID"]);
  1649. }
  1650. else
  1651. {
  1652. HardwareInfo.add("MajorID", "Generator");
  1653. HardwareInfo.add("MinorID", "Dr");
  1654. HardwareInfo.add("VendorID", "PSGHD");
  1655. HardwareInfo.add("ProductID", "HF");
  1656. HardwareInfo.add("SerialID", "Dev");
  1657. }
  1658. string ret = HardwareInfo.encode();
  1659. FINFO("std::string nsGEN::PSGHDDriver::DeviceProbe() out\n");
  1660. return ret;
  1661. }
  1662. void nsGEN::PSGHDDriver::Disconnect()
  1663. {
  1664. if (m_scfWrapper) {
  1665. m_scfWrapper->StopAutoReceive();
  1666. m_scfWrapper->Disconnect();
  1667. }
  1668. }
  1669. void nsGEN::PSGHDDriver::Dequeue(const char* Packet, DWORD Length)
  1670. {
  1671. DecodeFrame(Packet, Length);
  1672. }
  1673. PACKET_RET nsGEN::PSGHDDriver::callbackPackageProcess(const char* RecData, uint32_t nLength, uint32_t& PacketLength)
  1674. {
  1675. // 日志:进入数据包处理函数,记录输入长度
  1676. FINFO("[PSGHDDriver] 开始处理数据包,输入长度: [{$}]", nLength);
  1677. if (nLength < 3)
  1678. {
  1679. // 日志:数据包长度不足
  1680. FINFO("[PSGHDDriver] 数据包长度小于3,无效数据包,返回PACKET_USELESS");
  1681. return PACKET_USELESS;
  1682. }
  1683. // 查找STX (0x02)
  1684. int startIndex = -1;
  1685. for (uint32_t i = 0; i < nLength; i++)
  1686. {
  1687. if (RecData[i] == 0x02)
  1688. {
  1689. startIndex = i;
  1690. break;
  1691. }
  1692. }
  1693. if (startIndex == -1)
  1694. {
  1695. // 日志:未找到STX标记
  1696. FINFO("[PSGHDDriver] 未找到STX(0x02)标记,返回PACKET_USELESS");
  1697. return PACKET_USELESS;
  1698. }
  1699. // 日志:找到STX标记
  1700. FINFO("[PSGHDDriver] 找到STX(0x02)标记,位置: [{$}]", startIndex);
  1701. // 查找CRLF (0x0D, 0x0A)
  1702. int endIndex = -1;
  1703. for (uint32_t i = startIndex + 1; i < nLength - 1; i++)
  1704. {
  1705. if (RecData[i] == 0x0D && RecData[i + 1] == 0x0A)
  1706. {
  1707. endIndex = i;
  1708. break;
  1709. }
  1710. }
  1711. if (endIndex == -1)
  1712. {
  1713. // 日志:未找到CRLF结束标记
  1714. FINFO("[PSGHDDriver] 未找到CRLF(0x0D,0x0A)结束标记,返回PACKET_NOPACKET");
  1715. return PACKET_NOPACKET;
  1716. }
  1717. // 日志:找到CRLF标记
  1718. FINFO("[PSGHDDriver] 找到CRLF(0x0D,0x0A)标记,位置: [{$}]", endIndex);
  1719. // 计算数据包长度
  1720. PacketLength = endIndex + 2 - startIndex;
  1721. FINFO("[PSGHDDriver] 数据包处理完成,有效长度: [{$}],返回PACKET_ISPACKET", PacketLength);
  1722. return PACKET_ISPACKET;
  1723. }
  1724. bool nsGEN::PSGHDDriver::GetDeviceConfig(std::string& Cfg)
  1725. {
  1726. Cfg = m_DeviceConfigSend.encode();
  1727. printf("GetDeviceConfig over , %s", Cfg.c_str());
  1728. return true;
  1729. }
  1730. bool nsGEN::PSGHDDriver::SetDeviceConfig(std::string Cfg)
  1731. {
  1732. FINFO("--Func-- SetDeviceConfig {$}\n", Cfg.c_str());
  1733. printf("\n--Func-- SetDeviceConfig %s\n", Cfg.c_str());
  1734. ResDataObject DeviceConfig;
  1735. DeviceConfig.decode(Cfg.c_str());
  1736. ResDataObject DescriptionTempEx;
  1737. DescriptionTempEx = DeviceConfig["DeviceConfig"]["Attribute"];
  1738. FDEBUG("Attribute:{$}", DescriptionTempEx.encode());
  1739. bool bSaveFile = false; //true:重新保存配置文件
  1740. string strAccess = "";
  1741. for (int i = 0; i < DescriptionTempEx.size(); i++)
  1742. {
  1743. string strKey = DescriptionTempEx.GetKey(i);
  1744. FINFO("{$}", strKey.c_str());
  1745. printf("%s\n", strKey.c_str());
  1746. try
  1747. {
  1748. if (m_pAttribute->GetFirstOf(strKey.c_str()) >= 0)
  1749. {
  1750. strAccess = (string)(*m_pDescription)[strKey.c_str()]["Access"];
  1751. if ("RW" == strAccess)
  1752. {
  1753. //修改对应配置,在其他单元的配置项要同时调用其修改函数修改真实值
  1754. //1. 修改内存中的值,用于给上层发消息
  1755. (*m_pAttribute)[strKey.c_str()] = DescriptionTempEx[i];
  1756. //2. 拿到Innerkey
  1757. int nConfigInfoCount = (int)m_Configurations["ConfigToolInfo"].GetKeyCount("AttributeInfo");
  1758. FINFO("nConfigInfoCount {$}", nConfigInfoCount);
  1759. string strTemp = ""; //存储AttributeKey
  1760. for (int nInfoIndex = 0; nInfoIndex < nConfigInfoCount; nInfoIndex++)
  1761. {
  1762. strTemp = (string)m_Configurations["ConfigToolInfo"][nInfoIndex]["AttributeKey"];
  1763. if (strTemp == strKey)
  1764. {
  1765. strTemp = (string)m_Configurations["ConfigToolInfo"][nInfoIndex]["InnerKey"];
  1766. break;
  1767. }
  1768. }
  1769. //3. 修改配置文件中的值
  1770. if (SetDeviceConfigValue(m_Configurations, strTemp.c_str(), 1, DescriptionTempEx[i]))
  1771. {
  1772. FDEBUG("SetDeviceConfigValue over");
  1773. bSaveFile = true;
  1774. }
  1775. }
  1776. else
  1777. {
  1778. FINFO("{$} is not a RW configuration item", strKey.c_str());
  1779. }
  1780. }
  1781. else
  1782. {
  1783. FINFO("without this attribute {$}", strKey.c_str());
  1784. }
  1785. }
  1786. catch (ResDataObjectExption& e)
  1787. {
  1788. printf("\nSetDriverConfig crashed: %s\n", e.what());
  1789. FERROR("SetDriverConfig crashed: {$}", e.what());
  1790. return false;
  1791. }
  1792. }
  1793. if (bSaveFile)
  1794. {
  1795. //3. 重新保存配置文件
  1796. SaveConfigFile(true);
  1797. }
  1798. return true;
  1799. }
  1800. bool nsGEN::PSGHDDriver::SaveConfigFile(bool bSendNotify)
  1801. {
  1802. m_ConfigAll["CONFIGURATION"] = m_Configurations;
  1803. bool bRt = m_ConfigAll.SaveFile(m_ConfigFileName.c_str());
  1804. FINFO("SaveConfigFile over {$}", bRt);
  1805. return true;
  1806. }
  1807. bool nsGEN::PSGHDDriver::GetDeviceConfigValue(ResDataObject config, const char* pInnerKey, int nPathID, string& strValue)
  1808. {
  1809. strValue = "";
  1810. string strTemp = pInnerKey;
  1811. if (1 == nPathID) //从DriverConfig路径下每个DPC自己的配置文件读取
  1812. {
  1813. int pos = 0;
  1814. ResDataObject resTemp = config;
  1815. while ((pos = strTemp.find_first_of(',')) != string::npos)
  1816. {
  1817. string Key = strTemp.substr(0, pos);
  1818. string TempValue = resTemp[Key.c_str()].encode();
  1819. // printf("-TempValue=== %s", TempValue.c_str());
  1820. resTemp.clear();
  1821. resTemp.decode(TempValue.c_str());
  1822. strTemp = strTemp.substr(pos + 1, strTemp.length() - pos - 1);
  1823. //printf("-************--%s", strTemp.c_str());
  1824. }
  1825. if (strTemp != "")
  1826. {
  1827. strValue = (string)resTemp[strTemp.c_str()];
  1828. }
  1829. else
  1830. {
  1831. strValue = (string)resTemp;
  1832. }
  1833. }
  1834. //printf("------------%s", strValue.c_str());
  1835. return true;
  1836. }
  1837. bool nsGEN::PSGHDDriver::SetDeviceConfigValue(ResDataObject& config, const char* pInnerKey, int nPathID, const char* szValue)
  1838. {
  1839. string strTemp = pInnerKey;
  1840. FINFO("Begin to change {$} item value to {$}", pInnerKey, szValue);
  1841. if (1 == nPathID) //从DriverConfig路径下每个DPC自己的配置文件读取
  1842. {
  1843. try {
  1844. int pos = 0;
  1845. ResDataObject* resTemp = &config;
  1846. while ((pos = strTemp.find_first_of(',')) != string::npos)
  1847. {
  1848. string Key = strTemp.substr(0, pos);
  1849. resTemp = &(*resTemp)[Key.c_str()];
  1850. strTemp = strTemp.substr(pos + 1, strTemp.length() - pos - 1);
  1851. }
  1852. if (strTemp != "")
  1853. {
  1854. (*resTemp)[strTemp.c_str()] = szValue;
  1855. }
  1856. else
  1857. {
  1858. *resTemp = szValue;
  1859. }
  1860. }
  1861. catch (ResDataObjectExption& e)
  1862. {
  1863. FERROR("SetDriverConfigvalue crashed: {$}", e.what());
  1864. return false;
  1865. }
  1866. }
  1867. return true;
  1868. }
  1869. //-----------------------------------------------------------------------------
  1870. // GetIODriver & CreateIODriver
  1871. //-----------------------------------------------------------------------------
  1872. static nsGEN::PSGHDDriver gIODriver;
  1873. extern "C" CCOS::Dev::IODriver * GetIODriver() // 返回静态对象的引用, 调用者不能删除 !
  1874. {
  1875. return &gIODriver;
  1876. }
  1877. extern "C" CCOS::Dev::IODriver * CreateIODriver() // 返回新对象, 调用者必须自行删除此对象 !
  1878. {
  1879. pIODriver = new nsGEN::PSGHDDriver();
  1880. return pIODriver;
  1881. }