CCOS.Dev.Generator.PSG_HD.cpp 77 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468
  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. // 无操作处理函数
  925. auto HWNotProcess = [](const char* value, int length) -> void
  926. {
  927. FINFO("HWNotProcess: Command data (len: {$}) no need to process", length);
  928. };
  929. // 处理VREF响应 (电压参考)
  930. auto HWVREF = [this](const char* data, int length) -> void
  931. {
  932. // 需至少4字节数据(XXXX)
  933. if (length < 4) {
  934. FINFO("HWVREF: Invalid data length ({$} < 4), skip", length);
  935. return;
  936. }
  937. char kvStr[5] = { 0 };
  938. strncpy(kvStr, data, 4);
  939. int kvValue = atoi(kvStr);
  940. float actualKV = kvValue / 10.0f; // 转换为kV
  941. m_DoseUnit.m_KV->Update(actualKV);
  942. FireNotify(AttrKey::KV, m_DoseUnit.m_KV->JSGet());
  943. FINFO("HWVREF: Parsed actual KV = {$} kV", actualKV);
  944. };
  945. // 处理IREF响应 (电流参考)
  946. auto HWIREF = [this](const char* data, int length) -> void
  947. {
  948. if (length < 4) { // 需4字节(XXXX)
  949. FINFO("HWIREF: Invalid data length ({$} < 4), skip", length);
  950. return;
  951. }
  952. char maStr[5] = { 0 };
  953. strncpy(maStr, data, 4); // 直接取data
  954. int maValue = atoi(maStr);
  955. float actualMA = maValue / 100.0f; // 转换为mA
  956. m_DoseUnit.m_MA->Update(actualMA);
  957. FireNotify(AttrKey::MA, m_DoseUnit.m_MA->JSGet());
  958. float tempMa = m_DoseUnit.m_MA->Get();
  959. float tempMs = m_DoseUnit.m_MS->Get();
  960. float tempMAS = tempMa * tempMs / 1000.0f;
  961. if (tempMAS > 0)
  962. {
  963. m_DoseUnit.m_MAS->Update(tempMAS);
  964. FireNotify(AttrKey::MAS, m_DoseUnit.m_MAS->JSGet());
  965. }
  966. FINFO("HWIREF: Parsed actual MA = {$} mA", actualMA);
  967. };
  968. // 处理ENBL响应 (X射线使能)
  969. auto HWENBL = [this](const char* data, int length) -> void
  970. {
  971. if (length < 1) { // 需1字节(X)
  972. FINFO("HWENBL: Invalid data length ({$} < 1), skip", length);
  973. return;
  974. }
  975. // 直接取data[0](无需跳过"ENBL ")
  976. char enblStr = data[0];
  977. bool isEnabled = (enblStr == '1');
  978. FINFO("HWENBL: X-ray enable status = {$}", isEnabled ? "Enabled" : "Disabled");
  979. };
  980. // 处理WDTE响应 (看门狗定时器)
  981. auto HWWDTE = [this](const char* data, int length) -> void
  982. {
  983. if (length < 1) { // 需1字节(X)
  984. FINFO("HWWDTE: Invalid data length ({$} < 1), skip", length);
  985. return;
  986. }
  987. char wdtStr = data[0]; // 直接取data[0]
  988. bool isWdtEnabled = (wdtStr == '1');
  989. FINFO("HWWDTE: Watchdog status = {$}", isWdtEnabled ? "Enabled" : "Disabled");
  990. };
  991. // 处理WDTT响应 (看门狗定时器重置)
  992. auto HWWDTT = [this](const char* data, int length) -> void
  993. {
  994. if (length < 1) { // 基础长度校验
  995. FINFO("HWWDTT: Invalid data length ({$} < 1), skip", length);
  996. return;
  997. }
  998. FINFO("HWWDTT: Watchdog timer reset response received");
  999. };
  1000. // 处理CLR响应 (故障清除)
  1001. auto HWCLR = [this](const char* data, int length) -> void
  1002. {
  1003. if (length < 1) {
  1004. FINFO("HWCLR: Invalid data length ({$} < 1), skip", length);
  1005. return;
  1006. }
  1007. FINFO("HWCLR: Received fault clear response, performing fault clearing");
  1008. };
  1009. // 处理SMS响应 (曝光时间)
  1010. auto HWSMS = [this](const char* data, int length) -> void
  1011. {
  1012. if (length < 7) { // 需7字节(XXXXXXX)
  1013. FINFO("HWSMS: Invalid data length ({$} < 7), skip", length);
  1014. return;
  1015. }
  1016. char smsStr[8] = { 0 };
  1017. strncpy(smsStr, data, 7); // 直接取data
  1018. long timeValue = atol(smsStr);
  1019. float exposureTime = timeValue * 0.01f; // 转换为ms
  1020. m_DoseUnit.m_MS->Update(exposureTime);
  1021. FireNotify(AttrKey::MS, m_DoseUnit.m_MS->JSGet());
  1022. float tempMa = m_DoseUnit.m_MA->Get();
  1023. float tempMs = m_DoseUnit.m_MS->Get();
  1024. float tempMAS = tempMa * tempMs / 1000.0f;
  1025. if (tempMAS > 0)
  1026. {
  1027. m_DoseUnit.m_MAS->Update(tempMAS);
  1028. FireNotify(AttrKey::MAS, m_DoseUnit.m_MAS->JSGet());
  1029. }
  1030. FINFO("HWSMS: Parsed exposure time = {$} ms", exposureTime);
  1031. };
  1032. // 处理FLT响应 (故障状态)
  1033. auto HWFLT = [this](const char* data, int length) -> void
  1034. {
  1035. if (length < 3) { // 需3字节(XXX)
  1036. FINFO("HWFLT: Invalid data length ({$} < 3), skip", length);
  1037. return;
  1038. }
  1039. char faultStr[4] = { 0 };
  1040. strncpy(faultStr, data, 3);
  1041. int faultCode = atoi(faultStr);
  1042. if (faultCode != 0)
  1043. {
  1044. static const std::unordered_map<int, std::string> errorMessages = {
  1045. {2, "Charging circuit abnormal"}, {3, "Storage chip damaged"}, {136, "Filament current 1 exceeds limit"},
  1046. {140, "Anode kV exceeds limit, exposure aborted abnormally"}, {142, "High-voltage generator or tube arcing, exposure aborted abnormally"},
  1047. {165, "Bus voltage too low during high-voltage generator startup"}, {205, "Second-stage handswitch pressed during high-voltage generator wake-up or startup"},
  1048. {206, "High-voltage generator low battery, please charge"}, {208, "Exposure interval too short, please expose later"},
  1049. {209, "Parameter adjustment forbidden during exposure"}, {210, "First-stage handswitch repeated triggering, please use a single handswitch for exposure operation"},
  1050. {216, "Battery being charged"}, {218, "kV parameter exceeds limit"}, {219, "mA parameter exceeds limit"},
  1051. {220, "ms parameter exceeds limit"}, {229, "High-voltage generator power exceeds limit"}, {230, "Tube power exceeds limit"},
  1052. {231, "Frame rate parameter exceeds limit"}, {249, "High-voltage generator bus voltage exceeds limit"}, {255, "kV establishment timeout"},
  1053. {259, "Handswitch released in advance during exposure"}, {260, "Parameter adjustment forbidden during exposure"}, {263, "kV too high during exposure, exposure aborted abnormally"},
  1054. {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"}
  1055. };
  1056. static const std::unordered_set<int> firstSixErrors = { 2, 3, 136, 140, 142, 165 };
  1057. char errorCodeStr[20];
  1058. snprintf(errorCodeStr, sizeof(errorCodeStr), "PSGHD_FLT_%d", faultCode);
  1059. int level = 1;
  1060. auto it = errorMessages.find(faultCode);
  1061. if (it != errorMessages.end())
  1062. {
  1063. if (firstSixErrors.count(faultCode))
  1064. m_MSGUnit->AddErrorMessage(errorCodeStr, level, it->second.c_str());
  1065. else
  1066. m_MSGUnit->AddWarnMessage(errorCodeStr, level, it->second.c_str());
  1067. FINFO("HWFLT: Fault code {$} detected - {$}", faultCode, it->second.c_str());
  1068. }
  1069. else
  1070. {
  1071. FINFO("HWFLT: Unknow Fault code {$}", faultCode);
  1072. m_MSGUnit->AddWarnMessage(errorCodeStr, level, "Unknow Fault");
  1073. }
  1074. }
  1075. else
  1076. {
  1077. char errorCodeStr[20];
  1078. snprintf(errorCodeStr, sizeof(errorCodeStr), "PSGHD_FLT_0");
  1079. int level = 1;
  1080. m_MSGUnit->DelWarnMessage(errorCodeStr, level, "");
  1081. m_MSGUnit->DelErrorMessage(errorCodeStr, level, "");
  1082. FINFO("HWFLT: Fault cleared (fault code 0)");
  1083. }
  1084. };
  1085. // 处理工作相位响应 (RST<aaa>)
  1086. auto HWPhase = [this](const char* data, int length) -> void
  1087. {
  1088. if (length < 3) { // 需3字节(aaa)
  1089. FINFO("HWPhase: Invalid data length ({$} < 3), skip", length);
  1090. return;
  1091. }
  1092. // 设备首次连接时禁止曝光!
  1093. if (m_isFirstHWPhase) {
  1094. SetExpDisable();
  1095. m_isFirstHWPhase = false;
  1096. }
  1097. char phaseCodeStr[4] = { 0 };
  1098. strncpy(phaseCodeStr, data, 3);
  1099. int phaseCode = atoi(phaseCodeStr);
  1100. auto updateAndNotify = [this](nsGEN::AttrKey::GENERATOR_STATUS status)
  1101. {
  1102. if (m_DoseUnit.m_GenState->Update(status))
  1103. {
  1104. FireNotify(AttrKey::GENSTATE, m_DoseUnit.m_GenState->JSGet());
  1105. FINFO("HWPhase: Generator status updated to {$}", static_cast<int>(status));
  1106. }
  1107. };
  1108. switch (phaseCode)
  1109. {
  1110. case 1: updateAndNotify(nsGEN::AttrKey::GENERATOR_STATUS_INIT); break;
  1111. case 7: updateAndNotify(nsGEN::AttrKey::GENERATOR_STATUS_ERROR); break;
  1112. case 9: case 11: updateAndNotify(nsGEN::AttrKey::GENERATOR_STATUS_EXP); break;
  1113. default: FINFO("HWPhase: Unsupported phase code {$}", phaseCode); break;
  1114. }
  1115. };
  1116. auto HWVMON = [this](const char* data, int length) -> void
  1117. {
  1118. if (length < 4) { // 需4字节(XXXX)
  1119. FINFO("HWVMON: Invalid data length ({$} < 4), skip", length);
  1120. return;
  1121. }
  1122. char vmonStr[5] = { 0 };
  1123. strncpy(vmonStr, data, 4); // 直接取data
  1124. int vmonValue = atoi(vmonStr);
  1125. float actualVMON = vmonValue / 10.0f; // 转换为kV
  1126. m_DoseUnit.m_PostKV->Update(actualVMON);
  1127. FireNotify(AttrKey::POSTKV, m_DoseUnit.m_PostKV->JSGet());
  1128. FINFO("HWVMON: Parsed monitoring KV = {$} kV", actualVMON);
  1129. };
  1130. auto HWIMON = [this](const char* data, int length) -> void
  1131. {
  1132. if (length < 4) { // 需4字节(XXXX)
  1133. FINFO("HWIMON: Invalid data length ({$} < 4), skip", length);
  1134. return;
  1135. }
  1136. char imonStr[5] = { 0 };
  1137. strncpy(imonStr, data, 4); // 直接取data
  1138. int imonValue = atoi(imonStr);
  1139. float actualIMON = imonValue / 100.0f; // 转换为mA
  1140. m_DoseUnit.m_PostMA->Update(actualIMON);
  1141. FireNotify(AttrKey::POSTMA, m_DoseUnit.m_PostMA->JSGet());
  1142. FINFO("HWIMON: Parsed monitoring MA = {$} mA", actualIMON);
  1143. };
  1144. auto HWRAT = [this](const char* data, int length) -> void
  1145. {
  1146. if (length < 7) { // 需7字节(XXXXXXX)
  1147. FINFO("HWRAT: Invalid data length ({$} < 7), skip", length);
  1148. return;
  1149. }
  1150. char ratStr[8] = { 0 };
  1151. strncpy(ratStr, data, 7); // 直接取data
  1152. int ratio = atoi(ratStr);
  1153. float actualRatio = ratio / 100.0f;
  1154. m_DoseUnit.m_PostMS->Update(actualRatio);
  1155. FireNotify(m_DoseUnit.m_PostMS->GetKey(), m_DoseUnit.m_PostMS->JSGet());
  1156. FINFO("HWRAT: Parsed ratio parameter = {$}", actualRatio);
  1157. };
  1158. auto HWPOW = [this](const char* data, int length) -> void
  1159. {
  1160. if (length < 1) { // 需1字节(X)
  1161. FINFO("HWPOW: Invalid data length ({$} < 1), skip", length);
  1162. return;
  1163. }
  1164. char powStr = data[0]; // 直接取data[0]
  1165. bool isPowerOn = (powStr == '1');
  1166. FINFO("HWPOW: Power status = {$}", isPowerOn ? "On" : "Off");
  1167. };
  1168. auto HWEOK = [this](const char* data, int length) -> void
  1169. {
  1170. if (length < 1) { // 需1字节(X)
  1171. FINFO("HWEOK: Invalid data length ({$} < 1), skip", length);
  1172. return;
  1173. }
  1174. char eokStr = data[0]; // 直接取data[0]
  1175. bool isReady = (eokStr == '1');
  1176. if (isReady)
  1177. {
  1178. if (m_DoseUnit.m_GenState->Update(nsGEN::AttrKey::GENERATOR_STATUS_STANDBY))
  1179. {
  1180. //FireNotify(AttrKey::GENSTATE, m_DoseUnit.m_GenState->JSGet());
  1181. FINFO("HWEOK: Device ready, status updated to STANDBY");
  1182. }
  1183. }
  1184. else
  1185. {
  1186. if (m_DoseUnit.m_GenState->Update(nsGEN::AttrKey::GENERATOR_STATUS_SLEEP))
  1187. {
  1188. //FireNotify(AttrKey::GENSTATE, m_DoseUnit.m_GenState->JSGet());
  1189. FINFO("HWEOK: Device not ready, status updated to SLEEP");
  1190. }
  1191. }
  1192. };
  1193. auto HWDSW = [this](const char* data, int length) -> void
  1194. {
  1195. if (length < 1) { // 需1字节(X)
  1196. FINFO("HWDSW: Invalid data length ({$} < 1), skip", length);
  1197. return;
  1198. }
  1199. char eokStr = data[0]; // 直接取data[0]
  1200. bool isReady = (eokStr == '1');
  1201. if (isReady && m_DoseUnit.m_GenState->Get()== nsGEN::AttrKey::GENERATOR_STATUS_STANDBY)
  1202. {
  1203. FireNotify(AttrKey::GENSTATE, m_DoseUnit.m_GenState->JSGet());
  1204. FINFO("HWDSW: Device ready, status updated to STANDBY");
  1205. }
  1206. else
  1207. {
  1208. m_DoseUnit.m_GenState->Update(nsGEN::AttrKey::GENERATOR_STATUS_SLEEP);
  1209. FireNotify(AttrKey::GENSTATE, m_DoseUnit.m_GenState->JSGet());
  1210. FINFO("HWDSW: Device not ready, status updated to SLEEP");
  1211. }
  1212. };
  1213. auto HWECD = [this](const char* data, int length) -> void
  1214. {
  1215. if (length < 3) { // 需3字节(XXX)
  1216. FINFO("HWECD: Invalid data length ({$} < 3), skip", length);
  1217. return;
  1218. }
  1219. char ecdStr[4] = { 0 };
  1220. strncpy(ecdStr, data, 3); // 直接取data
  1221. int countdown = atoi(ecdStr);
  1222. FINFO("HWECD: High-voltage OK light countdown = {$}s", countdown);
  1223. };
  1224. auto HWSOC = [this](const char* data, int length) -> void
  1225. {
  1226. if (length < 3) { // 需3字节(XXX)
  1227. FINFO("HWSOC: Invalid data length ({$} < 3), skip", length);
  1228. return;
  1229. }
  1230. char socStr[4] = { 0 };
  1231. strncpy(socStr, data, 3); // 直接取data
  1232. int remainingPower = atoi(socStr);
  1233. FINFO("HWSOC: Generator remaining power = {$}%", remainingPower);
  1234. };
  1235. auto HWFLX = [this](const char* data, int length) -> void
  1236. {
  1237. if (length < 1) { // 需1字节(X)
  1238. FINFO("HWFLX: Invalid data length ({$} < 1), skip", length);
  1239. return;
  1240. }
  1241. char flxStr[2] = { 0 };
  1242. strncpy(flxStr, data, 1);
  1243. int fluoroMode = atoi(flxStr);
  1244. FINFO("HWFLX: Fluorescence mode detected = {$}", fluoroMode);
  1245. if (fluoroMode == 2)
  1246. {
  1247. m_DoseUnit.m_GenSynState->Update(AttrKey::GENERATOR_RAD_XRAYON);
  1248. FireNotify(m_DoseUnit.m_GenSynState->GetKey(), m_DoseUnit.m_GenSynState->JSGet());
  1249. FINFO("HWFLX: X-ray turned ON (mode 2)");
  1250. }
  1251. else if (fluoroMode == 1)
  1252. {
  1253. m_DoseUnit.m_GenSynState->Update(AttrKey::GENERATOR_RAD_READY);
  1254. m_hGenPostEvent->ResetEvent();
  1255. FireNotify(m_DoseUnit.m_GenSynState->GetKey(), m_DoseUnit.m_GenSynState->JSGet());
  1256. FINFO("HWFLX: X-ray ready (mode 1)");
  1257. }
  1258. else if (fluoroMode == 0)
  1259. {
  1260. m_bGenBusy = false;
  1261. m_DoseUnit.m_GenSynState->Update(AttrKey::GENERATOR_RAD_XRAYOFF);
  1262. FireNotify(m_DoseUnit.m_GenSynState->GetKey(), m_DoseUnit.m_GenSynState->JSGet());
  1263. FINFO("HWFLX: X-ray turned OFF (mode 0)");
  1264. }
  1265. };
  1266. auto HWFLP = [this](const char* data, int length) -> void
  1267. {
  1268. if (length < 1) { // 需1字节(X)
  1269. FINFO("HWFLP: Invalid data length ({$} < 1), skip", length);
  1270. return;
  1271. }
  1272. char flxStr[2] = { 0 };
  1273. strncpy(flxStr, data, 1);
  1274. int nValue = atoi(flxStr);
  1275. FINFO("HWFLP: Fluorescence mode detected = {$}", nValue);
  1276. if (nValue == 2)
  1277. {
  1278. FINFO("HWFLP: Received value 2 - No action");
  1279. }
  1280. else if (nValue == 1)
  1281. {
  1282. m_DoseUnit.m_GenSynState->Update(AttrKey::GENERATOR_RAD_PREPARE);
  1283. FINFO("HWFLP: Radiography prepare state - {$}", m_DoseUnit.m_GenSynState->JSGet().c_str());
  1284. FireNotify(m_DoseUnit.m_GenSynState->GetKey(), m_DoseUnit.m_GenSynState->JSGet());
  1285. }
  1286. else if (nValue == 0)
  1287. {
  1288. m_DoseUnit.m_GenSynState->Update(AttrKey::GENERATOR_RAD_OFF);
  1289. FINFO("HWFLP: Radiography off state - {$}", m_DoseUnit.m_GenSynState->JSGet().c_str());
  1290. FireNotify(m_DoseUnit.m_GenSynState->GetKey(), m_DoseUnit.m_GenSynState->JSGet());
  1291. m_bGenBusy = false;
  1292. }
  1293. };
  1294. auto HWVER = [this](const char* data, int length) -> void
  1295. {
  1296. if (length < 6) { // 需6字节(XXXXXX)
  1297. FINFO("HWVER: Invalid data length ({$} < 6), skip", length);
  1298. return;
  1299. }
  1300. char verStr[7] = { 0 };
  1301. strncpy(verStr, data, 6); // 直接取data
  1302. std::string version(verStr);
  1303. FINFO("HWVER: Generator version = {$}", version);
  1304. };
  1305. auto HWVSN = [this](const char* data, int length) -> void
  1306. {
  1307. if (length < 8) { // 需8字节(XXXXXXXX)
  1308. FINFO("HWVSN: Invalid data length ({$} < 8), skip", length);
  1309. return;
  1310. }
  1311. char vsnStr[9] = { 0 };
  1312. strncpy(vsnStr, data, 8); // 直接取data
  1313. std::string serialNumber(vsnStr);
  1314. FINFO("HWVSN: Generator serial number = {$}", serialNumber);
  1315. };
  1316. auto HWMAS = [this](const char* data, int length) -> void
  1317. {
  1318. if (length < 3) { // 至少3字节(避免atof解析错误)
  1319. FINFO("HWMAS: Invalid data length ({$} < 3), skip", length);
  1320. return;
  1321. }
  1322. float fmas = atof(data) / 100.0f; // 直接用data解析
  1323. if (m_DoseUnit.m_MAS->Update(fmas))
  1324. {
  1325. FireNotify(AttrKey::MAS, m_DoseUnit.m_MAS->JSGet());
  1326. FINFO("HWMAS: Parsed MAS value = {$}", fmas);
  1327. }
  1328. };
  1329. auto HWAP = [this](const char* data, int length) -> void
  1330. {
  1331. if (length < 3) { // 至少3字节(避免atof解析错误)
  1332. FINFO("HWAP: Invalid data length ({$} < 3), skip", length);
  1333. return;
  1334. }
  1335. float fmas = atof(data) / 100.0f; // 直接用data解析
  1336. m_DoseUnit.m_PostMAS->Update(fmas);
  1337. FireNotify(AttrKey::POSTMAS, m_DoseUnit.m_PostMAS->JSGet());
  1338. FINFO("HWAP: Parsed POSTMAS value = {$}", fmas);
  1339. };
  1340. auto HWWS = [this](const char* data, int length) -> void
  1341. {
  1342. if (length < 1) { // 需1字节以上(避免atoi解析错误)
  1343. FINFO("HWWS: Invalid data length ({$} < 1), skip", length);
  1344. return;
  1345. }
  1346. int nValue = atoi(data); // 直接用data解析
  1347. m_DoseUnit.m_WS->Update(nValue);
  1348. FireNotify(m_DoseUnit.m_WS->GetKey(), m_DoseUnit.m_WS->JSGet());
  1349. FINFO("HWWS: Parsed WS parameter = {$}", nValue);
  1350. };
  1351. auto HWEHE = [this](const char* data, int length) -> void
  1352. {
  1353. if (length < 1) { // 需1字节以上
  1354. FINFO("HWEHE: Invalid data length ({$} < 1), skip", length);
  1355. return;
  1356. }
  1357. m_iHeartBeats = 0;
  1358. int nhe = atoi(data); // 直接用data解析
  1359. if (m_DoseUnit.m_HE->Update(nhe))
  1360. {
  1361. FireNotify(m_DoseUnit.m_HE->GetKey(), m_DoseUnit.m_HE->JSGet());
  1362. FINFO("HWEHE: Parsed HE parameter = {$}", nhe);
  1363. }
  1364. };
  1365. arFrame.clear();
  1366. // 指令映射表补充
  1367. arFrame.push_back(tFrameMapping("VREF ", 5, HWVREF));
  1368. arFrame.push_back(tFrameMapping("IREF ", 5, HWIREF));
  1369. arFrame.push_back(tFrameMapping("VMON ", 5, HWVMON));
  1370. arFrame.push_back(tFrameMapping("IMON ", 5, HWIMON));
  1371. arFrame.push_back(tFrameMapping("ENBL ", 5, HWENBL));
  1372. arFrame.push_back(tFrameMapping("RST ", 4, HWPhase));
  1373. arFrame.push_back(tFrameMapping("SMS ", 4, HWSMS));
  1374. arFrame.push_back(tFrameMapping("RAT ", 4, HWRAT));
  1375. arFrame.push_back(tFrameMapping("POW ", 4, HWPOW));
  1376. arFrame.push_back(tFrameMapping("EOK ", 4, HWEOK));
  1377. arFrame.push_back(tFrameMapping("ECD ", 4, HWECD));
  1378. arFrame.push_back(tFrameMapping("FLX ", 4, HWFLX));
  1379. arFrame.push_back(tFrameMapping("FLT ", 4, HWFLT));
  1380. arFrame.push_back(tFrameMapping("RHE ", 4, HWEHE));
  1381. arFrame.push_back(tFrameMapping("VER ", 4, HWVER));
  1382. arFrame.push_back(tFrameMapping("VSN ", 4, HWVSN));
  1383. arFrame.push_back(tFrameMapping("DSW ", 4, HWDSW));
  1384. arFrame.push_back(tFrameMapping("CLR", 4, HWCLR));
  1385. arFrame.push_back(tFrameMapping("EC", 2, HWNotProcess));
  1386. arFrame.push_back(tFrameMapping("PW", 2, HWNotProcess));
  1387. arFrame.push_back(tFrameMapping("MX", 2, HWMAS));
  1388. arFrame.push_back(tFrameMapping("WS", 2, HWWS));
  1389. }
  1390. bool nsGEN::PSGHDDevice::ReConnect()
  1391. {
  1392. FINFO("Enter PSG_reConnect");
  1393. m_SCF->Disconnect();
  1394. if (!pIODriver)
  1395. {
  1396. FINFO("PSG_reConnect:Driver null");
  1397. }
  1398. else
  1399. {
  1400. // 需要将 pIODriver 转换为 PSGHDDriver*
  1401. PSGHDDriver* driver = dynamic_cast<PSGHDDriver*>(pIODriver.get());
  1402. if (driver && driver->ReConnection())
  1403. {
  1404. FireErrorMessage(false, 1, "lost Connect");
  1405. m_bConnectFlag = true;
  1406. FINFO("PSG_reConnect success");
  1407. return true;
  1408. }
  1409. else
  1410. {
  1411. FINFO("PSG_reConnect failed");
  1412. }
  1413. }
  1414. return false;
  1415. }
  1416. int nsGEN::PSGHDDevice::GetGenState()
  1417. {
  1418. if (m_DoseUnit.m_GenState != NULL)
  1419. {
  1420. return m_DoseUnit.m_GenState->Get();
  1421. }
  1422. else
  1423. {
  1424. return 0;
  1425. }
  1426. }
  1427. int nsGEN::PSGHDDevice::LoadConfig(string configfile)
  1428. {
  1429. FINFO("=====================LoadConfig=========================");
  1430. // 检查文件是否存在
  1431. std::ifstream file(configfile);
  1432. if (!file) {
  1433. // 文件不存在,直接返回空的Connection对象
  1434. FINFO("Config file does not exist: {$}", configfile.c_str());
  1435. return -1;
  1436. }
  1437. if (m_bIsConfigLoaded)
  1438. {
  1439. FINFO("Configuration already loaded.");
  1440. return 0;
  1441. }
  1442. ResDataObject temp;
  1443. temp.loadFile(configfile.c_str());
  1444. m_GenConfig = temp["CONFIGURATION"];
  1445. TransJsonText(m_GenConfig);
  1446. if (m_GenConfig.GetKeyCount("loopEnable") > 0)
  1447. {
  1448. m_bExtraFlag = (int)m_GenConfig["loopEnable"];
  1449. }
  1450. if (m_GenConfig.GetKeyCount(ConfKey::CcosTubeInfo) > 0)
  1451. {
  1452. string tempValue = (string)m_GenConfig[ConfKey::CcosTubeInfo];
  1453. m_DoseUnit.m_TubeInfo.reset(new TUBEINFOMould(tempValue));
  1454. FireNotify(AttrKey::TUBEINFO, m_DoseUnit.m_TubeInfo->JSGet());
  1455. }
  1456. if (m_GenConfig.GetKeyCount(ConfKey::CcosFocusSmall) > 0)
  1457. {
  1458. float tempValue = (float)m_GenConfig[ConfKey::CcosFocusSmall];
  1459. m_DoseUnit.m_FocusSmall = tempValue;
  1460. }
  1461. if (m_GenConfig.GetKeyCount(ConfKey::CcosFocusLarge) > 0)
  1462. {
  1463. float tempValue = (float)m_GenConfig[ConfKey::CcosFocusLarge];
  1464. m_DoseUnit.m_FocusLarge = tempValue;
  1465. }
  1466. if (m_GenConfig.GetKeyCount("GenCtrlMode") > 0)
  1467. {
  1468. m_nCtlMode = (float)m_GenConfig["GenCtrlMode"];//default 2
  1469. float tempValue = (float)m_GenConfig[ConfKey::CcosFocusLarge];
  1470. }
  1471. if (m_GenConfig.GetKeyCount("USECECMD") > 0)
  1472. {
  1473. m_bUseCECmd = (bool)m_GenConfig["USECECMD"];
  1474. }
  1475. m_bIsConfigLoaded = true;
  1476. return 0;
  1477. }
  1478. bool nsGEN::PSGHDDevice::ECHO(void)
  1479. {
  1480. return HWSend("ECH", 3);
  1481. }
  1482. bool nsGEN::PSGHDDevice::StartHardwareStatusThread()
  1483. {
  1484. if (!m_pHardwareStatusThread.joinable())
  1485. {
  1486. m_pHardwareStatusThread = std::thread(HardwareStatusThread, this);
  1487. return true;
  1488. }
  1489. return false;
  1490. }
  1491. void PSGHDDevice::HardwareStatusThread(PSGHDDevice* pParam)
  1492. {
  1493. if (pParam == nullptr)
  1494. {
  1495. return;
  1496. }
  1497. PSGHDDevice* pCurGen = pParam;
  1498. int messageIndex = 0;
  1499. while (pCurGen->m_bExtraFlag)
  1500. {
  1501. // 获取当前循环时间并休眠
  1502. int currentLoopTime = pCurGen->m_iLoopTime;
  1503. Sleep(currentLoopTime);
  1504. // 每5次循环发送状态查询命令
  1505. if (messageIndex % 5 == 0&& !pCurGen->m_bSleepState)
  1506. {
  1507. pCurGen->HWSend("RHE", 3);
  1508. Sleep(100);
  1509. pCurGen->HWSend("RST", 3);
  1510. Sleep(100);
  1511. pCurGen->HWSend("EOK", 3);
  1512. }
  1513. messageIndex++;
  1514. // 防止messageIndex无限增长导致溢出
  1515. if (messageIndex >= INT_MAX - 10)
  1516. {
  1517. messageIndex = 0;
  1518. }
  1519. }
  1520. // 线程退出时重置心跳标志
  1521. }
  1522. //-----------------------------------------------------------------------------
  1523. // PSGHDDriver
  1524. //-----------------------------------------------------------------------------
  1525. nsGEN::PSGHDDriver::PSGHDDriver()
  1526. : m_scfWrapper(std::make_shared<SCFWrapper>())
  1527. {
  1528. m_pAttribute.reset(new ResDataObject());
  1529. m_pDescription.reset(new ResDataObject());
  1530. }
  1531. nsGEN::PSGHDDriver::~PSGHDDriver()
  1532. {
  1533. Disconnect();
  1534. }
  1535. void nsGEN::PSGHDDriver::Prepare()
  1536. {
  1537. // 初始化日志系统
  1538. std::string strLogPath = GetProcessDirectory() + R"(/Conf/log_config.xml)";
  1539. std::string LogHost = "DevPSGHD";
  1540. std::string moduleName = "DevPSGHD";
  1541. bool ret = initLogModule(
  1542. LogHost, // 主机名(用于日志路径中的{host}占位符)
  1543. moduleName, // 唯一模块名
  1544. strLogPath, // 配置文件路径
  1545. true // 是否输出到控制台(可选)
  1546. );
  1547. if (!ret) {
  1548. std::cerr << "Log init failed!" << std::endl;
  1549. return;
  1550. }
  1551. PSGHDSetLocalModuleName(moduleName);
  1552. m_SCFDllName = GetConnectDLL(m_ConfigFileName);
  1553. // 绑定当前动态库的模块名(调用自身实现的接口)
  1554. FINFO("Prepare is OK.SCFDllName is {$}", m_SCFDllName);
  1555. }
  1556. std::string nsGEN::PSGHDDriver::DriverProbe()
  1557. {
  1558. FINFO("DriverProbe in \n");
  1559. ResDataObject r_config, HardwareInfo;
  1560. if (r_config.loadFile(m_ConfigFileName.c_str()))
  1561. {
  1562. HardwareInfo.add("MajorID", r_config["CONFIGURATION"]["MajorID"]);
  1563. HardwareInfo.add("MinorID", r_config["CONFIGURATION"]["MinorID"]);
  1564. HardwareInfo.add("VendorID", r_config["CONFIGURATION"]["VendorID"]);
  1565. HardwareInfo.add("ProductID", r_config["CONFIGURATION"]["ProductID"]);
  1566. HardwareInfo.add("SerialID", r_config["CONFIGURATION"]["SerialID"]);
  1567. }
  1568. else
  1569. {
  1570. HardwareInfo.add("MajorID", "Generator");
  1571. HardwareInfo.add("MinorID", "Dr");
  1572. HardwareInfo.add("VendorID", "PSGHD");
  1573. HardwareInfo.add("ProductID", "HF");
  1574. HardwareInfo.add("SerialID", "Drv");
  1575. }
  1576. string ret = HardwareInfo.encode();
  1577. return ret;
  1578. }
  1579. bool nsGEN::PSGHDDriver::ReConnection()
  1580. {
  1581. Disconnect();
  1582. FINFO("ReConnection:SCF Disconnect");
  1583. ResDataObject Connection = GetConnectParam(m_ConfigFileName);
  1584. FINFO("ReConnection:{$} \n", Connection.encode());
  1585. auto erCode = m_scfWrapper->Connect(Connection, &PSGHDDriver::callbackPackageProcess, SCF_PACKET_TRANSFER, 3000);
  1586. if (erCode == SCF_SUCCEED)
  1587. {
  1588. Sleep(1000);
  1589. // 重新设置数据接收回调
  1590. m_scfWrapper->SetDataReceivedCallback([this](const char* data, uint32_t length) {
  1591. this->Dequeue(data, length);
  1592. });
  1593. // 启动自动接收
  1594. m_scfWrapper->StartAutoReceive();
  1595. return true;
  1596. }
  1597. else
  1598. {
  1599. FINFO("ReConnection failed");
  1600. }
  1601. return false;
  1602. }
  1603. bool nsGEN::PSGHDDriver::Connect()
  1604. {
  1605. std::lock_guard<std::mutex> lock(m_connectionMutex);
  1606. const auto currentState = m_connectionState.load();
  1607. auto now = std::chrono::steady_clock::now();
  1608. // 1. 处理可重试的失败状态
  1609. if (currentState == ConnectionState::Failed) {
  1610. if ((now - m_lastConnectionAttempt) >= RETRY_INTERVAL && m_connectionRetryCount < MAX_RETRY_COUNT) {
  1611. m_connectionState = ConnectionState::Disconnected;
  1612. }
  1613. else {
  1614. return false; // 不满足重试条件,直接返回
  1615. }
  1616. }
  1617. // 2. 检查无效状态(正在连接/已连接但实际有效)
  1618. if (currentState == ConnectionState::Connecting) {
  1619. FINFO("Already connecting (type: {$})",
  1620. m_currentConnType == ConnectionType::Serial ? "Serial" : "Ethernet");
  1621. return true;
  1622. }
  1623. if (currentState == ConnectionState::Connected && m_scfWrapper && m_scfWrapper->IsConnected()) {
  1624. FINFO("Already connected (type: {$})",
  1625. m_currentConnType == ConnectionType::Serial ? "Serial" : "Ethernet");
  1626. return true;
  1627. }
  1628. // 3. 检查重试间隔
  1629. if (m_connectionRetryCount > 0 && (now - m_lastConnectionAttempt) < RETRY_INTERVAL) {
  1630. FINFO("Retry in {$}s (type: {$})",
  1631. std::chrono::duration_cast<std::chrono::seconds>(RETRY_INTERVAL - (now - m_lastConnectionAttempt)).count(),
  1632. m_currentConnType == ConnectionType::Serial ? "Serial" : "Ethernet");
  1633. return false;
  1634. }
  1635. ResDataObject connParam = GetConnectParam(m_ConfigFileName);
  1636. std::string connPortStr = "";
  1637. std::string connTypeStr = (std::string)connParam["type"]; // 从配置读取type字段
  1638. m_currentConnType = (connTypeStr == "COM") ? ConnectionType::Serial : ConnectionType::Ethernet;
  1639. if (m_currentConnType == ConnectionType::Serial)
  1640. {
  1641. connPortStr = (std::string)connParam["port"];// 从配置读取port字段
  1642. // 查找配置端口在现有端口列表中的位置
  1643. auto it = std::find(m_serialPorts.begin(), m_serialPorts.end(), connPortStr);
  1644. if (it == m_serialPorts.end()) {
  1645. // 配置的端口不在列表中,添加到首位
  1646. FINFO("Configured serial port {$} not found, adding to front of port list", connPortStr);
  1647. m_serialPorts.insert(m_serialPorts.begin(), connPortStr);
  1648. }
  1649. else if (it != m_serialPorts.begin()) {
  1650. // 配置的端口存在但不在首位,移动到首位
  1651. FINFO("Moving configured serial port {$} to front of port list", connPortStr);
  1652. m_serialPorts.erase(it);
  1653. m_serialPorts.insert(m_serialPorts.begin(), connPortStr);
  1654. }
  1655. }
  1656. // 4. 执行连接流程
  1657. m_connectionState = ConnectionState::Connecting;
  1658. m_lastConnectionAttempt = now;
  1659. std::string connInfo;
  1660. try {
  1661. if (m_currentConnType == ConnectionType::Serial) {
  1662. // 串口连接:使用当前索引的端口
  1663. std::string currentPort = m_serialPorts[m_currentSerialPortIndex];
  1664. connParam.update("port", currentPort.c_str()); // 将当前尝试的端口写入参数
  1665. connInfo = "Serial (port: " + currentPort + ")";
  1666. }
  1667. else {
  1668. // 网口连接:直接使用配置参数
  1669. connInfo = "Ethernet (ip: " + std::string(connParam["ip"]) + ")";
  1670. }
  1671. FINFO("Enter Connect ({$}), config: {$}", connInfo, connParam.encode());
  1672. if (!m_scfWrapper->Initialize(m_SCFDllName)) {
  1673. FINFO("Init failed: {$}", m_scfWrapper->GetLastError());
  1674. m_connectionState = ConnectionState::Failed;
  1675. return false;
  1676. }
  1677. m_scfWrapper->SetDataReceivedCallback([this](const char* data, uint32_t length) {
  1678. this->Dequeue(data, length);
  1679. });
  1680. auto erCode = m_scfWrapper->Connect(connParam, &PSGHDDriver::callbackPackageProcess, SCF_NORMAL_TRANSFER, 3000);
  1681. if (erCode != SCF_SUCCEED || !m_scfWrapper->StartAutoReceive()) {
  1682. FINFO("Connect failed (code: {$}) for {$}", erCode, connInfo);
  1683. m_scfWrapper->Disconnect();
  1684. m_connectionState = ConnectionState::Failed;
  1685. // 串口连接:未遍历完所有端口时,优先切换端口重试(不计入总重试次数)
  1686. if (m_currentConnType == ConnectionType::Serial) {
  1687. int nextIndex = (m_currentSerialPortIndex + 1) % m_serialPorts.size();
  1688. // 判断是否已遍历所有端口(当前索引是最后一个时,nextIndex会回到0)
  1689. bool allPortsTried = (nextIndex == 0);
  1690. if (!allPortsTried) {
  1691. // 未遍历完所有端口:切换到下一端口,不增加重试计数
  1692. m_currentSerialPortIndex = nextIndex;
  1693. m_connectionRetryCount = 0;
  1694. FINFO("Trying next serial port: {$}", m_serialPorts[nextIndex]);
  1695. return false; // 触发外部线程立即尝试下一端口
  1696. }
  1697. else {
  1698. // 已遍历所有端口:重置到第一个端口,增加重试计数(进入间隔等待)
  1699. m_currentSerialPortIndex = 0;
  1700. m_connectionRetryCount++;
  1701. FINFO("All serial ports tried, retry count: {$}/{$}", m_connectionRetryCount, MAX_RETRY_COUNT);
  1702. return false;
  1703. }
  1704. }
  1705. // 所有端口失败(串口)或网口失败,才增加总重试计数
  1706. m_connectionRetryCount++;
  1707. return false;
  1708. }
  1709. // 连接成功:重置状态
  1710. m_connectionState = ConnectionState::Connected;
  1711. m_connectionRetryCount = 0;
  1712. m_currentSerialPortIndex = 0; // 重置串口端口索引
  1713. FINFO("Connected successfully ({$})", connInfo);
  1714. return true;
  1715. }
  1716. catch (const std::exception& e) {
  1717. FINFO("Exception for {$}: {$}", connInfo, e.what());
  1718. m_connectionState = ConnectionState::Failed;
  1719. m_connectionRetryCount++;
  1720. return false;
  1721. }
  1722. }
  1723. auto nsGEN::PSGHDDriver::CreateDevice(int index) -> std::unique_ptr <IODevice>
  1724. {
  1725. FINFO("CreateDevice in\n");
  1726. m_pDevice = new PSGHDDevice(EventCenter, m_scfWrapper, m_ConfigFileName);
  1727. auto dev = std::unique_ptr <IODevice>(new IODevice(m_pDevice));
  1728. FINFO("CreateDevice out\n");
  1729. return dev;
  1730. }
  1731. void nsGEN::PSGHDDriver::FireNotify(int code, std::string key, std::string content)
  1732. {
  1733. EventCenter->OnNotify(code, key, content);
  1734. }
  1735. bool nsGEN::PSGHDDriver::isConnected() const
  1736. {
  1737. const auto state = m_connectionState.load();
  1738. // 1. 连接中/实际已连接:返回true(无需重连)
  1739. if (state == ConnectionState::Connecting || (m_scfWrapper && m_scfWrapper->IsConnected())) {
  1740. //FINFO(state == ConnectionState::Connecting ? "Connecting in progress" : "Al
  1741. // ready connected");
  1742. return true;
  1743. }
  1744. // 2. 失败状态处理:判断是否允许重试
  1745. if (state == ConnectionState::Failed) {
  1746. auto now = std::chrono::steady_clock::now();
  1747. const auto timeSinceLast = now - m_lastConnectionAttempt;
  1748. // 2.1 达到最大重试次数,但超过重置间隔:重置计数,允许重新重试
  1749. if (m_connectionRetryCount >= MAX_RETRY_COUNT && timeSinceLast >= RESET_RETRY_AFTER) {
  1750. FINFO("Max retries reached, resetting count after {$}s",
  1751. std::chrono::duration_cast<std::chrono::seconds>(timeSinceLast).count());
  1752. m_connectionRetryCount = 0; // 重置计数(因mutable修饰,const函数可修改)
  1753. }
  1754. // 2.2 不适合重连(时间未到 或 次数仍超限):返回true阻止重连
  1755. if (timeSinceLast < RETRY_INTERVAL || m_connectionRetryCount >= MAX_RETRY_COUNT) {
  1756. FINFO(timeSinceLast < RETRY_INTERVAL ?
  1757. "Retry later ({$}s)" : "Max retries, waiting {$}s to reset",
  1758. std::chrono::duration_cast<std::chrono::seconds>(
  1759. timeSinceLast < RETRY_INTERVAL ? RETRY_INTERVAL - timeSinceLast : RESET_RETRY_AFTER - timeSinceLast
  1760. ).count()
  1761. );
  1762. return true;
  1763. }
  1764. }
  1765. // 3. 其他情况(适合重连):返回false触发Connect()
  1766. return false;
  1767. }
  1768. std::string nsGEN::PSGHDDriver::GetResource()
  1769. {
  1770. FDEBUG("GetResource");
  1771. ResDataObject r_config, temp;
  1772. if (!temp.loadFile(m_ConfigFileName.c_str()))
  1773. {
  1774. return "";
  1775. }
  1776. m_ConfigAll = temp;
  1777. r_config = temp["CONFIGURATION"];
  1778. m_Configurations = r_config;
  1779. ResDataObject DescriptionTemp;
  1780. ResDataObject DescriptionSend;
  1781. ResDataObject m_DescriptionSend;
  1782. ResDataObject ListTemp;
  1783. string strTemp = ""; //用于读取字符串配置信息
  1784. string strIndex = ""; //用于读取配置信息中的List项
  1785. int nTemp = -1; //用于读取整型配置信息
  1786. char sstream[10] = { 0 }; //用于转换值
  1787. string strValue = ""; //用于存储配置的值
  1788. string strType = ""; //用于存储配置的类型 int/float/string...
  1789. /***
  1790. * 1. 通过循环,将所有配置项写到pDeviceConfig
  1791. * 2. 记录配置项的内部key以及配置类型,类型对应了不同配置文件路径,用于读写真实值
  1792. ***/
  1793. try
  1794. {
  1795. //便利ConfigToolInfo 中 所有的AttributeInfo 属性段
  1796. int nConfigInfoCount = (int)m_Configurations["ConfigToolInfo"].GetKeyCount("AttributeInfo");
  1797. m_pAttribute->clear();
  1798. m_pDescription->clear();
  1799. for (int nInfoIndex = 0; nInfoIndex < nConfigInfoCount; nInfoIndex++)
  1800. {
  1801. DescriptionTemp.clear();
  1802. DescriptionSend.clear();
  1803. ListTemp.clear();
  1804. //AttributeType
  1805. strTemp = (string)m_Configurations["ConfigToolInfo"][nInfoIndex]["AttributeDescripition"]["Type"];
  1806. DescriptionTemp.add(ConfKey::CcosType, strTemp.c_str());//CcosGeneratorAttribute
  1807. DescriptionSend.add(ConfKey::CcosType, strTemp.c_str());//CcosGeneratorAttribute
  1808. strType = strTemp; //记录配置项的类型
  1809. //AttributeKey
  1810. //1. 根据AttributeType,内部key和配置路径,拿到当前的真实值
  1811. strTemp = (string)m_Configurations["ConfigToolInfo"][nInfoIndex]["InnerKey"];
  1812. nTemp = (int)m_Configurations["ConfigToolInfo"][nInfoIndex]["PathID"];
  1813. GetDeviceConfigValue(r_config, strTemp.c_str(), nTemp, strValue); //得到strValue的值
  1814. //printf("********************************innerkey=%s --strValue = %s\n", strTemp.c_str(), strValue.c_str());
  1815. //2. 赋值
  1816. strTemp = (string)m_Configurations["ConfigToolInfo"][nInfoIndex]["AttributeKey"];
  1817. if ("int" == strType)
  1818. {
  1819. (*m_pAttribute).add(strTemp.c_str(), atoi(strValue.c_str()));
  1820. }
  1821. else if ("float" == strType)
  1822. {
  1823. (*m_pAttribute).add(strTemp.c_str(), atoi(strValue.c_str()));
  1824. }
  1825. else //其它先按string类型处理
  1826. {
  1827. (*m_pAttribute).add(strTemp.c_str(), strValue.c_str());
  1828. }
  1829. //printf("********************************outkey =%s --strValue = %s\n", strTemp.c_str(), strValue.c_str());
  1830. //AttributeAccess
  1831. strTemp = (string)m_Configurations["ConfigToolInfo"][nInfoIndex]["AttributeDescripition"]["Access"];
  1832. DescriptionTemp.add(ConfKey::CcosAccess, strTemp.c_str());
  1833. DescriptionSend.add(ConfKey::CcosAccess, strTemp.c_str());
  1834. /*
  1835. //AttributeRangeMin
  1836. strTemp = (string)m_Configurations["ConfigToolInfo"][nInfoIndex]["AttributeDescripition"]["RangeMin"];
  1837. if (strTemp != "") //不需要的配置项为空
  1838. {
  1839. DescriptionTemp.add(ConfKey::CcosRangeMin, strTemp.c_str());
  1840. }
  1841. //AttributeRangeMax
  1842. strTemp = (string)m_Configurations["ConfigToolInfo"][nInfoIndex]["AttributeDescripition"]["RangeMax"];
  1843. if (strTemp != "") //不需要的配置项为空
  1844. {
  1845. DescriptionTemp.add(ConfKey::CcosRangeMax, strTemp.c_str());
  1846. }
  1847. */
  1848. //AttributeList
  1849. nTemp = m_Configurations["ConfigToolInfo"][nInfoIndex]["AttributeDescripition"]["ListNum"];
  1850. if (nTemp > 0) //ListNum不大于0时说明不需要list配置
  1851. {
  1852. for (int nListIndex = 0; nListIndex < nTemp; nListIndex++)
  1853. {
  1854. strTemp = (string)m_Configurations["ConfigToolInfo"][nInfoIndex]["AttributeDescripition"]["ListInfo"][nListIndex];
  1855. auto temKey = std::to_string(nListIndex);
  1856. ListTemp.add(temKey.c_str(), strTemp.c_str());
  1857. }
  1858. DescriptionTemp.add(ConfKey::CcosList, ListTemp);
  1859. DescriptionSend.add(ConfKey::CcosList, ListTemp.encode());
  1860. }
  1861. //AttributeRequired
  1862. strTemp = (string)m_Configurations["ConfigToolInfo"][nInfoIndex]["AttributeDescripition"]["Required"];
  1863. DescriptionTemp.add(ConfKey::CcosRequired, strTemp.c_str());
  1864. DescriptionSend.add(ConfKey::CcosRequired, strTemp.c_str());
  1865. //AttributeDefaultValue
  1866. strTemp = (string)m_Configurations["ConfigToolInfo"][nInfoIndex]["AttributeDescripition"]["DefaultValue"];
  1867. if (strTemp != "") //不需要的配置项为空
  1868. {
  1869. DescriptionTemp.add(ConfKey::CcosDefaultValue, strTemp.c_str());
  1870. DescriptionSend.add(ConfKey::CcosDefaultValue, strTemp.c_str());
  1871. }
  1872. strTemp = (string)m_Configurations["ConfigToolInfo"][nInfoIndex]["AttributeKey"];
  1873. (*m_pDescription).add(strTemp.c_str(), DescriptionTemp);
  1874. m_DescriptionSend.add(strTemp.c_str(), DescriptionSend.encode());
  1875. }
  1876. }
  1877. catch (ResDataObjectExption& e)
  1878. {
  1879. FERROR("Get config error: {$}", e.what());
  1880. return "";
  1881. }
  1882. ResDataObject resDeviceResource;
  1883. resDeviceResource.add(ConfKey::CcosGeneratorAttribute, (*m_pAttribute));
  1884. resDeviceResource.add(ConfKey::CcosGeneratorDescription, (*m_pDescription));
  1885. ResDataObject DescriptionTempEx;
  1886. DescriptionTempEx.add(ConfKey::CcosGeneratorConfig, resDeviceResource);
  1887. m_DeviceConfig.clear();
  1888. m_DeviceConfig = DescriptionTempEx;
  1889. //Debug("local ************* get resource over {$}", DescriptionTempEx.encode());
  1890. //printf("local ************* get resource over %s \n", DescriptionTempEx.encode());
  1891. resDeviceResource.clear();
  1892. resDeviceResource.add(ConfKey::CcosGeneratorAttribute, (*m_pAttribute));
  1893. resDeviceResource.add(ConfKey::CcosGeneratorDescription, m_DescriptionSend);
  1894. DescriptionTempEx.clear();
  1895. DescriptionTempEx.add(ConfKey::CcosGeneratorConfig, resDeviceResource);
  1896. m_DeviceConfigSend.clear();
  1897. m_DeviceConfigSend = DescriptionTempEx;
  1898. string res = m_DeviceConfigSend.encode();
  1899. //printf("%s", res.c_str());
  1900. //Debug("get resource over {$}", DescriptionTempEx.encode());
  1901. //("************* get resource over %s \n", DescriptionTempEx.encode());
  1902. return res;
  1903. }
  1904. std::string nsGEN::PSGHDDriver::DeviceProbe()
  1905. {
  1906. FINFO("std::string nsGEN::PSGHDDriver::DeviceProbe() in\n");
  1907. ResDataObject r_config, HardwareInfo;
  1908. if (r_config.loadFile(m_ConfigFileName.c_str()))
  1909. {
  1910. HardwareInfo.add("MajorID", r_config["CONFIGURATION"]["MajorID"]);
  1911. HardwareInfo.add("MinorID", r_config["CONFIGURATION"]["MinorID"]);
  1912. HardwareInfo.add("VendorID", r_config["CONFIGURATION"]["VendorID"]);
  1913. HardwareInfo.add("ProductID", r_config["CONFIGURATION"]["ProductID"]);
  1914. HardwareInfo.add("SerialID", r_config["CONFIGURATION"]["SerialID"]);
  1915. }
  1916. else
  1917. {
  1918. HardwareInfo.add("MajorID", "Generator");
  1919. HardwareInfo.add("MinorID", "Dr");
  1920. HardwareInfo.add("VendorID", "PSGHD");
  1921. HardwareInfo.add("ProductID", "HF");
  1922. HardwareInfo.add("SerialID", "Dev");
  1923. }
  1924. string ret = HardwareInfo.encode();
  1925. FINFO("std::string nsGEN::PSGHDDriver::DeviceProbe() out\n");
  1926. return ret;
  1927. }
  1928. void nsGEN::PSGHDDriver::Disconnect()
  1929. {
  1930. if (m_scfWrapper) {
  1931. m_scfWrapper->StopAutoReceive();
  1932. m_scfWrapper->Disconnect();
  1933. }
  1934. }
  1935. void nsGEN::PSGHDDriver::Dequeue(const char* Packet, DWORD Length)
  1936. {
  1937. DecodeFrame(Packet, Length);
  1938. }
  1939. PACKET_RET nsGEN::PSGHDDriver::callbackPackageProcess(const char* RecData, uint32_t nLength, uint32_t& PacketLength)
  1940. {
  1941. // 日志:进入数据包处理函数,记录输入长度
  1942. FINFO("[PSGHDDriver] 开始处理数据包,输入长度: [{$}]", nLength);
  1943. if (nLength < 3)
  1944. {
  1945. // 日志:数据包长度不足
  1946. FINFO("[PSGHDDriver] 数据包长度小于3,无效数据包,返回PACKET_USELESS");
  1947. return PACKET_USELESS;
  1948. }
  1949. // 查找STX (0x02)
  1950. int startIndex = -1;
  1951. for (uint32_t i = 0; i < nLength; i++)
  1952. {
  1953. if (RecData[i] == 0x02)
  1954. {
  1955. startIndex = i;
  1956. break;
  1957. }
  1958. }
  1959. if (startIndex == -1)
  1960. {
  1961. // 日志:未找到STX标记
  1962. FINFO("[PSGHDDriver] 未找到STX(0x02)标记,返回PACKET_USELESS");
  1963. return PACKET_USELESS;
  1964. }
  1965. // 日志:找到STX标记
  1966. FINFO("[PSGHDDriver] 找到STX(0x02)标记,位置: [{$}]", startIndex);
  1967. // 查找CRLF (0x0D, 0x0A)
  1968. int endIndex = -1;
  1969. for (uint32_t i = startIndex + 1; i < nLength - 1; i++)
  1970. {
  1971. if (RecData[i] == 0x0D && RecData[i + 1] == 0x0A)
  1972. {
  1973. endIndex = i;
  1974. break;
  1975. }
  1976. }
  1977. if (endIndex == -1)
  1978. {
  1979. // 日志:未找到CRLF结束标记
  1980. FINFO("[PSGHDDriver] 未找到CRLF(0x0D,0x0A)结束标记,返回PACKET_NOPACKET");
  1981. return PACKET_NOPACKET;
  1982. }
  1983. // 日志:找到CRLF标记
  1984. FINFO("[PSGHDDriver] 找到CRLF(0x0D,0x0A)标记,位置: [{$}]", endIndex);
  1985. // 计算数据包长度
  1986. PacketLength = endIndex + 2 - startIndex;
  1987. FINFO("[PSGHDDriver] 数据包处理完成,有效长度: [{$}],返回PACKET_ISPACKET", PacketLength);
  1988. return PACKET_ISPACKET;
  1989. }
  1990. bool nsGEN::PSGHDDriver::GetDeviceConfig(std::string& Cfg)
  1991. {
  1992. Cfg = m_DeviceConfigSend.encode();
  1993. printf("GetDeviceConfig over , %s", Cfg.c_str());
  1994. return true;
  1995. }
  1996. bool nsGEN::PSGHDDriver::SetDeviceConfig(std::string Cfg)
  1997. {
  1998. FINFO("--Func-- SetDeviceConfig {$}\n", Cfg.c_str());
  1999. printf("\n--Func-- SetDeviceConfig %s\n", Cfg.c_str());
  2000. ResDataObject DeviceConfig;
  2001. DeviceConfig.decode(Cfg.c_str());
  2002. ResDataObject DescriptionTempEx;
  2003. DescriptionTempEx = DeviceConfig["DeviceConfig"]["Attribute"];
  2004. FDEBUG("Attribute:{$}", DescriptionTempEx.encode());
  2005. bool bSaveFile = false; //true:重新保存配置文件
  2006. string strAccess = "";
  2007. for (int i = 0; i < DescriptionTempEx.size(); i++)
  2008. {
  2009. string strKey = DescriptionTempEx.GetKey(i);
  2010. FINFO("{$}", strKey.c_str());
  2011. printf("%s\n", strKey.c_str());
  2012. try
  2013. {
  2014. if (m_pAttribute->GetFirstOf(strKey.c_str()) >= 0)
  2015. {
  2016. strAccess = (string)(*m_pDescription)[strKey.c_str()]["Access"];
  2017. if ("RW" == strAccess)
  2018. {
  2019. //修改对应配置,在其他单元的配置项要同时调用其修改函数修改真实值
  2020. //1. 修改内存中的值,用于给上层发消息
  2021. (*m_pAttribute)[strKey.c_str()] = DescriptionTempEx[i];
  2022. //2. 拿到Innerkey
  2023. int nConfigInfoCount = (int)m_Configurations["ConfigToolInfo"].GetKeyCount("AttributeInfo");
  2024. FINFO("nConfigInfoCount {$}", nConfigInfoCount);
  2025. string strTemp = ""; //存储AttributeKey
  2026. for (int nInfoIndex = 0; nInfoIndex < nConfigInfoCount; nInfoIndex++)
  2027. {
  2028. strTemp = (string)m_Configurations["ConfigToolInfo"][nInfoIndex]["AttributeKey"];
  2029. if (strTemp == strKey)
  2030. {
  2031. strTemp = (string)m_Configurations["ConfigToolInfo"][nInfoIndex]["InnerKey"];
  2032. break;
  2033. }
  2034. }
  2035. //3. 修改配置文件中的值
  2036. if (SetDeviceConfigValue(m_Configurations, strTemp.c_str(), 1, DescriptionTempEx[i]))
  2037. {
  2038. FDEBUG("SetDeviceConfigValue over");
  2039. bSaveFile = true;
  2040. }
  2041. }
  2042. else
  2043. {
  2044. FINFO("{$} is not a RW configuration item", strKey.c_str());
  2045. }
  2046. }
  2047. else
  2048. {
  2049. FINFO("without this attribute {$}", strKey.c_str());
  2050. }
  2051. }
  2052. catch (ResDataObjectExption& e)
  2053. {
  2054. printf("\nSetDriverConfig crashed: %s\n", e.what());
  2055. FERROR("SetDriverConfig crashed: {$}", e.what());
  2056. return false;
  2057. }
  2058. }
  2059. if (bSaveFile)
  2060. {
  2061. //3. 重新保存配置文件
  2062. SaveConfigFile(true);
  2063. }
  2064. return true;
  2065. }
  2066. bool nsGEN::PSGHDDriver::SaveConfigFile(bool bSendNotify)
  2067. {
  2068. m_ConfigAll["CONFIGURATION"] = m_Configurations;
  2069. bool bRt = m_ConfigAll.SaveFile(m_ConfigFileName.c_str());
  2070. FINFO("SaveConfigFile over {$}", bRt);
  2071. return true;
  2072. }
  2073. bool nsGEN::PSGHDDriver::GetDeviceConfigValue(ResDataObject config, const char* pInnerKey, int nPathID, string& strValue)
  2074. {
  2075. strValue = "";
  2076. string strTemp = pInnerKey;
  2077. if (1 == nPathID) //从DriverConfig路径下每个DPC自己的配置文件读取
  2078. {
  2079. int pos = 0;
  2080. ResDataObject resTemp = config;
  2081. while ((pos = strTemp.find_first_of(',')) != string::npos)
  2082. {
  2083. string Key = strTemp.substr(0, pos);
  2084. string TempValue = resTemp[Key.c_str()].encode();
  2085. // printf("-TempValue=== %s", TempValue.c_str());
  2086. resTemp.clear();
  2087. resTemp.decode(TempValue.c_str());
  2088. strTemp = strTemp.substr(pos + 1, strTemp.length() - pos - 1);
  2089. //printf("-************--%s", strTemp.c_str());
  2090. }
  2091. if (strTemp != "")
  2092. {
  2093. strValue = (string)resTemp[strTemp.c_str()];
  2094. }
  2095. else
  2096. {
  2097. strValue = (string)resTemp;
  2098. }
  2099. }
  2100. //printf("------------%s", strValue.c_str());
  2101. return true;
  2102. }
  2103. bool nsGEN::PSGHDDriver::SetDeviceConfigValue(ResDataObject& config, const char* pInnerKey, int nPathID, const char* szValue)
  2104. {
  2105. string strTemp = pInnerKey;
  2106. FINFO("Begin to change {$} item value to {$}", pInnerKey, szValue);
  2107. if (1 == nPathID) //从DriverConfig路径下每个DPC自己的配置文件读取
  2108. {
  2109. try {
  2110. int pos = 0;
  2111. ResDataObject* resTemp = &config;
  2112. while ((pos = strTemp.find_first_of(',')) != string::npos)
  2113. {
  2114. string Key = strTemp.substr(0, pos);
  2115. resTemp = &(*resTemp)[Key.c_str()];
  2116. strTemp = strTemp.substr(pos + 1, strTemp.length() - pos - 1);
  2117. }
  2118. if (strTemp != "")
  2119. {
  2120. (*resTemp)[strTemp.c_str()] = szValue;
  2121. }
  2122. else
  2123. {
  2124. *resTemp = szValue;
  2125. }
  2126. }
  2127. catch (ResDataObjectExption& e)
  2128. {
  2129. FERROR("SetDriverConfigvalue crashed: {$}", e.what());
  2130. return false;
  2131. }
  2132. }
  2133. return true;
  2134. }
  2135. //-----------------------------------------------------------------------------
  2136. // GetIODriver & CreateIODriver
  2137. //-----------------------------------------------------------------------------
  2138. static nsGEN::PSGHDDriver gIODriver;
  2139. extern "C" CCOS::Dev::IODriver * GetIODriver() // 返回静态对象的引用, 调用者不能删除 !
  2140. {
  2141. return &gIODriver;
  2142. }
  2143. extern "C" CCOS::Dev::IODriver * CreateIODriver() // 返回新对象, 调用者必须自行删除此对象 !
  2144. {
  2145. pIODriver = new nsGEN::PSGHDDriver();
  2146. return pIODriver;
  2147. }