CCOS.Dev.Generator.PSG_HD.cpp 62 KB

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