CCOS.Dev.Generator.PSG_HD.cpp 78 KB

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