123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178 |
- // CCOS.Dev.GEN.PSGHD.cpp : 定义 DLL 应用程序的导出函数。
- #include <assert.h>
- #include <functional>
- #include <unordered_map>
- #include <fstream>
- #include <cmath>
- #include <climits>
- #include <unordered_set>
- #include <algorithm>
- #include "LogicDevice.h"
- using namespace std::placeholders;
- #include "LogLocalHelper.h"
- #include "Log4CPP.h"
- #include "Helper.JSON.hpp"
- #include "CCOS.Dev.Generator.PSG_HD.h"
- using namespace CCOS::Dev::Detail::Generator;
- namespace nsGEN = CCOS::Dev::Detail::Generator;
- const uint8_t STX = 0x02, CR = 0x0D, LF = 0x0A;
- const char TERM = ';';
- static nsGEN::PSGHDDriver* pIODriver = nullptr;
- #define PSGHD_LARGE_POWER 5
- #define PSGHD_SMALL_POWER 1.1
- #define PSGHD_MAX_HEAT 225
- #define PSGHD_MIN_MA 1.0
- #define PSGHD_MAX_MA 1000.0
- #define PSGHD_MIN_MS 1.0
- #define PSGHD_MAX_MS 10001.0
- //设置相关常量
- #define PSGHD_LoopDefHBTime 1000
- #define PSGHD_LoopExpHBTime 500
- static const int msTimeOut_Lock = 500; //通讯接口锁定时间
- #define PSGHD_Com_NormalLen 150
- #define PSGHD_ETX 0x03
- #define PSGHD_RESOK "$"
- #define Sleep(ms) std::this_thread::sleep_for(std::chrono::milliseconds(ms))
- static const auto COM_SCFDllName = "libSerialSCF.so";
- static const auto TCP_SCFDllName = "libTcpipSCF.so";
- static const float msSteps[] = {
- 100, 120, 160, 200, 250, 320, 400, 500, 630, 800,
- 1000, 1250, 1600, 2000
- };
- static const float maSteps[] = {
- 1.00f, 1.25f, 1.6f, 2.00f, 2.50f, 3.00f
- };
- static const size_t msStepCount = sizeof(msSteps) / sizeof(msSteps[0]);
- static const size_t maStepCount = sizeof(maSteps) / sizeof(maSteps[0]);
- //Log4CPP::Logger* gLogger = nullptr;
- struct tFrameMapping
- {
- static const int MaxLen = 7; // 前缀不能超过 7 个字符 !
- using cbFun = std::function <void(const char*, int)>;
- char strHead[MaxLen];
- int NbOfCharOfHead;
- cbFun fun;
- // 关键修改:将char*改为const char*,兼容字符串常量
- tFrameMapping(const char* str, int len, cbFun f)
- {
- assert(len < MaxLen); // len最大只能是4
- for (int i = 0; i < len; i++)
- strHead[i] = str[i];
- NbOfCharOfHead = len;
- fun = f;
- }
- };
- // 响应操作对照表
- static std::list <tFrameMapping> arFrame;
- static bool DecodeFrame(const char* data, int len) {
- if (!data || len < 8) {
- FINFO("DecodeFrame: Invalid input");
- return false;
- }
- int pos = 0;
- bool hasValid = false;
- while (pos < len) {
- while (pos < len && (uint8_t)data[pos] != STX) pos++;
- if (pos >= len) {
- FINFO("DecodeFrame: No STX found");
- break;
- }
- int start = pos;
- int end = -1;
- for (int i = start + 1; i < len - 1; i++) {
- if ((uint8_t)data[i] == CR && (uint8_t)data[i + 1] == LF) {
- end = i + 1;
- break;
- }
- }
- if (end == -1) {
- FINFO("DecodeFrame: Incomplete cmd (no CRLF)");
- break;
- }
- int cmdLen = end - start + 1;
- auto match = [&](const tFrameMapping& item) {
- if (item.NbOfCharOfHead >= cmdLen) return false;
- for (int i = 0; i < item.NbOfCharOfHead; i++) {
- if (data[start + 1 + i] != item.strHead[i]) return false;
- }
- return true;
- };
- auto it = std::find_if(arFrame.begin(), arFrame.end(), match);
- if (it != arFrame.end()) {
- // Extract ARG (between header and ';')
- int argStart = start + 1 + it->NbOfCharOfHead;
- int argEnd = -1;
- for (int i = argStart; i < end; i++) {
- if (data[i] == TERM) {
- argEnd = i;
- break;
- }
- }
- if (argEnd > argStart) {
- it->fun(data + argStart, argEnd - argStart);
- FINFO("DecodeFrame: Parsed cmd: [{$}], ARG len: {$}", it->strHead, argEnd - argStart);
- hasValid = true;
- }
- else FINFO("DecodeFrame: Cmd missing ';'");
- }
- else FINFO("DecodeFrame: No matching header");
- pos = end + 1; // Next cmd start
- }
- return hasValid;
- }
- //-----------------------------------------------------------------------------
- // PSGHDDevice
- //-----------------------------------------------------------------------------
- atomic<int> nsGEN::PSGHDDevice::m_iLoopTime = PSGHD_LoopDefHBTime;
- atomic<bool> nsGEN::PSGHDDevice::m_bExtraFlag = false;
- nsGEN::PSGHDDevice::PSGHDDevice(std::shared_ptr <IOEventCenter> center, std::shared_ptr<SCFWrapper> SCF, string configfile)
- : super(center)
- , superGen()
- ,m_SCF(SCF)
- , m_bConnectFlag(false)
- {
- m_bExtraFlag = true;
- //初始化
- m_bExpEnable = false;
- m_iLoopTime.store(PSGHD_LoopDefHBTime);
- for (int i = 0; i < 18; i++)
- {
- m_bFaultList[i] = false;
- }
- m_iMaxPower = PSGHD_LARGE_POWER; //KW
- MaxHeatContent = PSGHD_MAX_HEAT; //KJ
- FINFO("\n===============log begin : version:0.0.0.0 ===================\n");
- //设置发生器属性集合各个值的范围及精度
- m_DoseUnit.m_KV.reset(new KVMould(0.0, 39.0, 151.0, 1.0));
- m_DoseUnit.m_MA.reset(new MAMould(0.0, PSGHD_MIN_MA, PSGHD_MAX_MA, 0.1));
- m_DoseUnit.m_MS.reset(new MSMould(0.0, PSGHD_MIN_MS, PSGHD_MAX_MS, 0.01));
- m_DoseUnit.m_MAS.reset(new MASMould(0.0, 0.1, 1000.0, 0.01));
- m_DoseUnit.m_Techmode.reset(new TECHMODEMould(AttrKey::TECHMODE_TYPE::TECHMODE_NOAEC_2P, AttrKey::TECHMODE_NOAEC_3P, AttrKey::TECHMODE_AEC_MAS_MA, 1));
- m_DoseUnit.m_WS.reset(new WORKSTATIONMould(1, 0, 5, 1));
- m_DoseUnit.m_Focus.reset(new FOCUSMould(AttrKey::FOCUS_TYPE::FOCUS_LARGE, AttrKey::FOCUS_SMALL, AttrKey::FOCUS_LARGE, 1));
- m_DoseUnit.m_AECField.reset(new AECFIELDMould(0, 0, 111, 1));
- m_DoseUnit.m_AECFilm.reset(new AECFILMMould(0, 0, 2, 1));
- m_DoseUnit.m_AECDensity.reset(new AECDENSITYMould(0, -3, 3, 1));
- m_DoseUnit.m_GenHE.reset(new GENHEATMould(0, 0, 100, 1));
- m_DoseUnit.m_HE.reset(new TUBEHEATMould(0, 0, 100, 1));
- m_DoseUnit.m_GenSynState.reset(new GENSYNSTATEMould(AttrKey::GENERATOR_RAD_OFF, AttrKey::GENERATOR_SYNC_ERR, AttrKey::GENERATOR_SYNC_MAX, 1));
- m_DoseUnit.m_GenState.reset(new GENSTATEMould(0, AttrKey::GENERATOR_STATUS_SHUTDOWN, AttrKey::GENERATOR_STATUS_MAX, 1));
- m_DoseUnit.m_GenTotalExpNumber.reset(new TOTALEXPNUMMould(0, 0, 9999, 1));
- m_DoseUnit.m_GenTotalAcqTimes.reset(new TOTALACQTIMESMould(0, 0, 9999, 1));
- m_DoseUnit.m_GenTubeCoolWaitTimes.reset(new TUBECOOLTIMEMould(0, 0, 9999, 1));
- m_DoseUnit.m_GenTubeOverLoadNumber.reset(new TUBEOVERLOADNUMMould(0, 0, 9999, 1));
- m_DoseUnit.m_GenCurrentExpNumber.reset(new CUREXPNUMMould(0, 0, 9999, 1));
- m_DoseUnit.m_ExpMode.reset(new EXPMODEMould(AttrKey::EXPMODE_TYPE::Single));
- m_DoseUnit.m_FrameRate.reset(new FRAMERATEMould(0, 0, 16, 1));
- m_DoseUnit.m_FLMode.reset(new FLUModeMould(AttrKey::GENERATOR_FLUMode::GENERATOR_FLMODE_NOTFLU));
- m_DoseUnit.m_BatteryChargeState.reset(new BATTERYCHARGSTATEMould(0, 0, 1, 1));
- m_DoseUnit.m_TubeTargetMaterial.reset(new TUBETARGETMATERIALMould(AttrKey::TUBETARGETMATERIAL_TYPE::MO));
- m_DoseUnit.m_TubeAngle.reset(new TUBEANGLEMould(0, -45, 45, 1));
- m_DoseUnit.m_FLIntTime.reset(new FLUIntTimeMould(0.0, 0.0, 100.0, 0.1));
- m_DoseUnit.m_FLAccTime.reset(new FLAccTimeMould(0.0, 0.0, 999.0, 0.1));
- m_DoseUnit.m_FLKV.reset(new FLUKVMould(0, 40, 125, 1));
- m_DoseUnit.m_FLMS.reset(new FLUMSMould(10.0, 10.0, 999999.0, 0.01));
- m_DoseUnit.m_FLMA.reset(new FLUMAMould(0.5, 0.5, 99.0, 0.1));
- m_DoseUnit.m_ABSStatus.reset(new FLUABSStatusMould(0, 0, 2, 1));
- m_DoseUnit.m_PPS.reset(new PPSMould(0.5,0.5, 30, 0.1));
- m_DoseUnit.m_DoseLevel.reset(new FLUDoseLevelMould(0, 0, 2, 1));
- m_DoseUnit.m_FLMode.reset(new FLUModeMould(0, 0, 4, 1));
- m_DoseUnit.m_Curve.reset(new FLUCurveMould(0, 0, 3, 1));
-
- //Actual exposure parameters 值
- m_DoseUnit.m_PostKV.reset(new POSTKVMould(0.0, 40.0, 120.0, 1.0));
- m_DoseUnit.m_PostMA.reset(new POSTMAMould(0.0, 1.0, 1000.0, 0.1));
- m_DoseUnit.m_PostMS.reset(new POSTMSMould(0.0, 1.0, 10000.0, 0.01));
- m_DoseUnit.m_PostMAS.reset(new POSTMASMould(0.0, 0.5, 1000.0, 0.01));
- //发生器告警及错误消息
- m_MSGUnit.reset(new nsDetail::MSGUnit(center, nsGEN::GeneratorUnitType));
-
- m_hGenPostEvent = LinuxEvent::CreateEvent(LinuxEvent::MANUAL_RESET, false);
- //配置响应操作对照表 供发生器回传的数据触发相应的操作
- OnCallBack();
- //将发生器可以对外提供的指令注册集进行补充
- Register();
- LoadConfig(configfile);
-
- //启动硬件状态轮询进程
- StartHardwareStatusThread();
- }
- nsGEN::PSGHDDevice::~PSGHDDevice()
- {
- m_bExtraFlag = false;
- if (m_pHardwareStatusThread.joinable()) {
- m_pHardwareStatusThread.join();
- }
- FINFO("\n===============log end ===================\n");
- arFrame.clear();
- }
- std::string nsGEN::PSGHDDevice::GetGUID() const
- {
- FINFO("===============GetGUID : {$} ===================\n", GeneratorUnitType);
- return GeneratorUnitType;
- }
- void nsGEN::PSGHDDevice::Register()
- {
- auto Disp = m_Dispatch.Lock().As();
- superGen::Register(Disp);
- superGen::RegisterRAD(Disp);
- superGen::RegisterAEC(Disp);
- superGen::RegisterExpEnable(Disp);
- superGen::RegisterGeneratortoSyncStatus(Disp);
- superGen::RegisterFluoro(Disp);
- Disp->Get.Push(m_MSGUnit->GetKey().c_str(), [this](std::string& out) { out = m_MSGUnit->JSGet(); return RET_STATUS::RET_SUCCEED; });
- Disp->Get.Push(AttrKey::DENHEAT, [this](std::string& out) { out = m_DoseUnit.m_GenHE->JSGet(); return RET_STATUS::RET_SUCCEED; });
- auto fun_Clear_DAP = [this](auto in, auto& out)
- {
- return Clear_DAP();
- };
- Disp->Action.Push("Clear_DAP", fun_Clear_DAP);
- auto fun_GetValue_DAP = [this](auto in, auto& out)
- {
- float value = 0;
- RET_STATUS ret = GetValue_DAP(value);
- out = ToJSON(value);
- return ret;
- };
- Disp->Action.Push("GetValue_DAP", fun_GetValue_DAP);
- }
- RET_STATUS nsGEN::PSGHDDevice::IncKV()
- {
- FINFO("Enter PSGHDDevice::IncKV()\n");
- if (!m_DoseUnit.m_KV->CanInc()) return RET_STATUS::RET_SUCCEED;
- m_DoseUnit.m_KV->Inc();
- return SetKV(m_DoseUnit.m_KV->Get());
- }
- RET_STATUS nsGEN::PSGHDDevice::DecKV()
- {
- if (!m_DoseUnit.m_KV->CanDec()) return RET_STATUS::RET_SUCCEED;
- m_DoseUnit.m_KV->Dec();
- return SetKV(m_DoseUnit.m_KV->Get());
- }
- RET_STATUS nsGEN::PSGHDDevice::SetKV(float value)
- {
- if (!m_DoseUnit.m_KV->Verify(value)) return RET_STATUS::RET_SUCCEED;
- char temp[50] = { 0 };
- int kvValue = (int)(value * 10); // 转换为协议单位(100V)
- snprintf(temp, sizeof(temp), "VREF %04d", kvValue);
- return HWSend(temp, strlen(temp));
- }
- RET_STATUS nsGEN::PSGHDDevice::IncMA()
- {
- float currentMA = m_DoseUnit.m_MA->Get();
- // 查找当前值在档位中的位置
- size_t currentIndex = maStepCount;
- for (size_t i = 0; i < maStepCount; ++i) {
- if (fabs(maSteps[i] - currentMA) < 1e-6f) {
- currentIndex = i;
- break;
- }
- }
- if (currentIndex >= maStepCount - 1) {
- return RET_STATUS::RET_SUCCEED; // 已经是最大值
- }
- return SetMA(maSteps[currentIndex + 1]);
- }
- RET_STATUS nsGEN::PSGHDDevice::DecMA()
- {
- float currentMA = m_DoseUnit.m_MA->Get();
- // 查找当前值在档位中的位置
- size_t currentIndex = maStepCount;
- for (size_t i = 0; i < maStepCount; ++i) {
- if (fabs(maSteps[i] - currentMA) < 1e-6f) {
- currentIndex = i;
- break;
- }
- }
- if (currentIndex == 0 || currentIndex >= maStepCount) {
- return RET_STATUS::RET_SUCCEED; // 已经是最小值或无效值
- }
- return SetMA(maSteps[currentIndex - 1]);
- }
- RET_STATUS nsGEN::PSGHDDevice::SetMA(float value)
- {
- // 找到最接近的合法档位值
- size_t closestIndex = 0;
- float minDiff = fabsf(maSteps[0] - value);
- for (size_t i = 1; i < maStepCount; ++i) {
- float diff = fabsf(maSteps[i] - value);
- if (diff < minDiff) {
- minDiff = diff;
- closestIndex = i;
- }
- }
- // 转换为协议单位并发送命令
- char command[50] = { 0 };
- snprintf(command, sizeof(command), "IREF %04d", (int)(maSteps[closestIndex] * 100));
- return HWSend(command, strlen(command));
- }
- RET_STATUS nsGEN::PSGHDDevice::IncMS()
- {
- float currentMS = m_DoseUnit.m_MS->Get();
- // 查找当前值在档位中的位置
- size_t currentIndex = msStepCount;
- for (size_t i = 0; i < msStepCount; ++i) {
- if (fabs(msSteps[i] - currentMS) < 1e-6f) {
- currentIndex = i;
- break;
- }
- }
- if (currentIndex >= msStepCount - 1) {
- return RET_STATUS::RET_SUCCEED; // 已经是最大值
- }
- return SetMS(msSteps[currentIndex + 1]);
- }
- RET_STATUS nsGEN::PSGHDDevice::DecMS()
- {
- float currentMS = m_DoseUnit.m_MS->Get();
- // 查找当前值在档位中的位置
- size_t currentIndex = msStepCount;
- for (size_t i = 0; i < msStepCount; ++i) {
- if (fabs(msSteps[i] - currentMS) < 1e-6f) {
- currentIndex = i;
- break;
- }
- }
- if (currentIndex == 0 || currentIndex >= msStepCount) {
- return RET_STATUS::RET_SUCCEED; // 已经是最小值或无效值
- }
- return SetMS(msSteps[currentIndex - 1]);
- }
- RET_STATUS nsGEN::PSGHDDevice::SetMS(float value)
- {
- // 找到最接近的合法档位值
- size_t closestIndex = 0;
- float minDiff = fabsf(msSteps[0] - value);
- for (size_t i = 1; i < msStepCount; ++i) {
- float diff = fabsf(msSteps[i] - value);
- if (diff < minDiff) {
- minDiff = diff;
- closestIndex = i;
- }
- }
- // 发送命令
- char command[50] = { 0 };
- snprintf(command, sizeof(command), "SMS %07d", static_cast<int>(msSteps[closestIndex] * 100));
- return HWSend(command, strlen(command));
- }
- RET_STATUS nsGEN::PSGHDDevice::IncMAS()
- {
- return RET_STATUS::RET_SUCCEED;
- }
- RET_STATUS nsGEN::PSGHDDevice::DecMAS()
- {
- return RET_STATUS::RET_SUCCEED;
- }
- RET_STATUS nsGEN::PSGHDDevice::SetMAS(float value)
- {
- return RET_STATUS::RET_SUCCEED;
- }
- RET_STATUS nsGEN::PSGHDDevice::SetTechmode(int value)
- {
- return RET_STATUS::RET_SUCCEED;
- }
- RET_STATUS nsGEN::PSGHDDevice::SetEXAMMode(std::string value)
- {
- return RET_STATUS::RET_SUCCEED;
- }
- RET_STATUS nsGEN::PSGHDDevice::SetAPR(const _tAPRArgs& t)
- {
- m_bGenBusy = true;
- 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);
- SetKV(t.fKV);
- Sleep(50);
- SetMA(t.fMA);
- Sleep(80);
- SetMS(t.fMS);
- m_bGenBusy = false;
- return RET_STATUS::RET_SUCCEED;
- }
- RET_STATUS nsGEN::PSGHDDevice::RefreshData()
- {
- if (!m_bGenBusy)
- {
- }
- return RET_STATUS::RET_SUCCEED;
- }
- RET_STATUS nsGEN::PSGHDDevice::SetFocus(int value)
- {
- if (!m_DoseUnit.m_Focus->Verify(value)) return RET_STATUS::RET_SUCCEED;
- return RET_STATUS::RET_SUCCEED;
- }
- RET_STATUS nsGEN::PSGHDDevice::Reset()
- {
- FINFO("clear all errors \n");
- char errorCodeStr[20];
- snprintf(errorCodeStr, sizeof(errorCodeStr), "PSGHD_FLT_0");
- int level = 1;
- m_MSGUnit->DelWarnMessage(errorCodeStr, level, "");
- m_MSGUnit->DelErrorMessage(errorCodeStr, level, "");
- FINFO("HWFLT: Fault cleared (fault code 0)");
- return HWSend("CLR",3);//仅重置错误状态
- }
- RET_STATUS nsGEN::PSGHDDevice::ActiveSyncMode(_tSyncModeArgs value)
- {
- FINFO("value.strSyncMode: {$}, value.strSyncValue: {$}, value.strWS: {$} \n", value.strSyncMode, value.strSyncValue, value.strWS);
- int nSyncModeValue = atoi(value.strSyncValue.c_str());
- return RET_STATUS::RET_SUCCEED;
- }
- RET_STATUS nsGEN::PSGHDDevice::SetCollimatorLight(unsigned short value)
- {
- FINFO("Attempting to set collimator light value:{$}", value);
- return HWSend("COL", 3);
- }
- RET_STATUS nsGEN::PSGHDDevice::SetDeviceSleepState(const int value)
- {
- m_bSleepState = (bool)value;
- FINFO("Attempting to set device sleep state: {$}({$})",
- value, m_bSleepState ? "sleeping" : "awake");
- return RET_STATUS::RET_SUCCEED;
- }
- RET_STATUS nsGEN::PSGHDDevice::QueryHE(int& value)
- {
- return RET_STATUS::RET_SUCCEED;
- }
- void nsGEN::PSGHDDevice::SubscribeSelf(ccos_mqtt_connection* conn)
- {
- //订阅GEN所有Action
- //SubscribeTopic(conn, "CCOS/DEVICE/Generator/Action/#"); Moduld层默认订阅了这个Action,如果这边也订阅的话就会执行两遍Action,可能会出问题
- }
- RET_STATUS nsGEN::PSGHDDevice::SetAECDensity(int value)
- {
- if (!m_DoseUnit.m_AECDensity->Verify(value)) return RET_STATUS::RET_SUCCEED;
- if (m_DoseUnit.m_Techmode->Get() == AttrKey::TECHMODE_V2TYPE::ET_AEC) return RET_STATUS::RET_FAILED;
- int nAECDensity = m_DoseUnit.m_AECDensity->Get();
- if (value < m_DoseUnit.m_AECDensity->Get())
- {
- if (value < m_DoseUnit.m_AECDensity->Get() - 1)
- {
- nAECDensity = (int)value;
- }
- else
- {
- nAECDensity = nAECDensity - 1;
- }
- }
- else if (value > m_DoseUnit.m_AECDensity->Get())
- {
- if (value > m_DoseUnit.m_AECDensity->Get() + 1)
- {
- nAECDensity = (int)value;
- }
- else
- {
- nAECDensity = nAECDensity + 1;
- }
- }
- m_DoseUnit.m_AECDensity->Update(value);
- char temp[50] = { 0 };
- if (nAECDensity >= 0)
- {
- snprintf(temp, sizeof(temp), "FN+%01d", (int)nAECDensity);
- }
- else
- {
- snprintf(temp, sizeof(temp), "FN-%01d", (int)nAECDensity);
- }
- return HWSend(temp, strlen(temp));
- }
- RET_STATUS nsGEN::PSGHDDevice::SetAECField(int value)
- {
- if (!m_DoseUnit.m_AECField->Verify(value)) return RET_STATUS::RET_SUCCEED;
- if (m_DoseUnit.m_Techmode->Get() == AttrKey::TECHMODE_V2TYPE::ET_MAS) return RET_STATUS::RET_FAILED;
- m_DoseUnit.m_AECField->Update(value);
- char temp[50] = { 0 };
- snprintf(temp, sizeof(temp), "FI%03d", (int)value);
- return HWSend(temp, strlen(temp));
- }
- RET_STATUS nsGEN::PSGHDDevice::SetAECFilm(int value)
- {
- if (!m_DoseUnit.m_AECFilm->Verify(value)) return RET_STATUS::RET_SUCCEED;
- if (m_DoseUnit.m_Techmode->Get() == AttrKey::TECHMODE_V2TYPE::ET_MAS) return RET_STATUS::RET_FAILED;
- m_DoseUnit.m_AECFilm->Update(value);
- char temp[50] = { 0 };
- snprintf(temp, sizeof(temp), "FS%03d", (int)value);
- return HWSend(temp, strlen(temp));
- }
- RET_STATUS nsGEN::PSGHDDevice::SetWS(const string value)
- {
- FINFO("Enter SetWS {$}", value);
- int tempws = 0;
- if (value == "Table") tempws = (int)m_GenConfig["WSTable"];
- else if (value == "Wall") tempws = (int)m_GenConfig["WSWall"];
- else if (value == "Direct") tempws = (int)m_GenConfig["WSConventional"];
- else if (value == "Free") tempws = (int)m_GenConfig["WSFree"];
- else if (value == "Tomo") tempws = (int)m_GenConfig["WSTomo"];
- m_DoseUnit.m_WS->Update(tempws);
- char temp[50] = { 0 };
- snprintf(temp, sizeof(temp), "WS%01d", tempws);
- return HWSend(temp, strlen(temp));
- }
- RET_STATUS nsGEN::PSGHDDevice::QueryPostKV(float& value)
- {
- return RET_STATUS::RET_SUCCEED;
- }
- RET_STATUS nsGEN::PSGHDDevice::QueryPostMA(float& value)
- {
- return RET_STATUS::RET_SUCCEED;
- }
- RET_STATUS nsGEN::PSGHDDevice::QueryPostMS(float& value)
- {
- return RET_STATUS::RET_SUCCEED;
- }
- RET_STATUS nsGEN::PSGHDDevice::QueryPostMAS(float& value)
- {
- return RET_STATUS::RET_SUCCEED;
- }
- RET_STATUS nsGEN::PSGHDDevice::StartMove() //发生器无此设置
- {
- return RET_STATUS::RET_SUCCEED;
- }
- RET_STATUS nsGEN::PSGHDDevice::EndMove() //发生器无此设置
- {
- return RET_STATUS::RET_SUCCEED;
- }
- RET_STATUS nsGEN::PSGHDDevice::SetGenSynState(int value)
- {
- FINFO("Enter SetGenSynState...{$} \n", value);
- //if (AttrKey::GENERATOR_RAD_XRAYON == value)
- //{
- // FINFO("SetGenSynState be call.this is soft syn mode.");
- // HWSend("XR2",3);
- // m_DoseUnit.m_GenSynState->Update(AttrKey::GENERATOR_RAD_XRAYON);
- // FireNotify(m_DoseUnit.m_GenSynState->GetKey(), m_DoseUnit.m_GenSynState->JSGet());
- //}
- //else if(AttrKey::GENERATOR_FLU_XRAYON == value)
- //{
- // FINFO("SetGenSynState be call.this is soft syn mode.");
- // //HWSend("FLX2", 4);
- // //m_DoseUnit.m_GenSynState->Update(AttrKey::GENERATOR_FLU_XRAYON);
- // //FireNotify(m_DoseUnit.m_GenSynState->GetKey(), m_DoseUnit.m_GenSynState->JSGet());
- //}
- return RET_STATUS::RET_SUCCEED;
- }
- RET_STATUS nsGEN::PSGHDDevice::SetGenState(int value)
- {
- return RET_STATUS::RET_SUCCEED;
- }
- RET_STATUS nsGEN::PSGHDDevice::SetExpMode(std::string value)
- {
- FINFO("Enter SetExpMode...{$} \n",value.c_str());
- m_DoseUnit.m_ExpMode->Update(value);
- FireNotify(AttrKey::GENSTATE, m_DoseUnit.m_GenState->JSGet());
- return RET_STATUS::RET_SUCCEED;
- }
- RET_STATUS nsGEN::PSGHDDevice::SetFrameRate(float frameRate)
- {
- return RET_STATUS::RET_SUCCEED;
- }
- RET_STATUS nsGEN::PSGHDDevice::SetExpEnable()
- {
- FINFO("SetExpEnable in\n");
- return HWSend("DSW 1", 5);
- }
- RET_STATUS nsGEN::PSGHDDevice::SetExpDisable()
- {
- FINFO("SetExpDisable in\n");
- return HWSend("DSW 0", 5);
- }
- RET_STATUS nsGEN::PSGHDDevice::PrepareAcquisition()
- {
- FireNotify(AttrKey::GENSTATE, m_DoseUnit.m_GenState->JSGet());
- return RET_STATUS::RET_SUCCEED;
- }
- //-----------------------------------------------------------------------------
- // ProcessCmd
- //-----------------------------------------------------------------------------
- void nsGEN::PSGHDDevice::ProcessClientData(const char* pData, unsigned long nDataLength, void* lparam)
- {
- PSGHDDevice* pCurGen = (PSGHDDevice*)lparam;
- pCurGen->HWSend(pData, nDataLength);
- }
- RET_STATUS nsGEN::PSGHDDevice::HWSend(const char* strCommand, int length, bool reSend, int nTimeOut)
- {
- if (!m_SCF) {
- FINFO("Failed - Serial communication interface not initialized");
- return RET_STATUS::RET_FAILED;
- }
- if (!m_SCF->IsConnected())
- {
- FINFO("Failed - Device not connected");
- return RET_STATUS::RET_FAILED;
- }
- // 构造协议格式:<STX>CMD<SP>ARG;<CS><CR><LF>
- char strSendCommand[100] = { 0 };
- int len = 0;
- strSendCommand[len++] = 0x02; // STX
- // 复制命令部分
- memcpy(strSendCommand + len, strCommand, length);
- len += length;
- // 添加分号
- strSendCommand[len++] = ';';
- // 计算校验和(从STX后开始到分号';')
- uint16_t sum = 0;
- for (int i = 1; i < len; i++)
- {
- sum += (uint8_t)strSendCommand[i];
- }
- uint8_t checksum = (uint8_t)(sum & 0xFF);
- checksum = 0x100 - checksum;
- checksum &= 0x7F;
- checksum |= 0x40;
- // 添加校验和
- strSendCommand[len++] = checksum;
- strSendCommand[len++] = 0x0D; // CR
- strSendCommand[len++] = 0x0A; // LF
- // 打印数据包前16字节的十六进制(含控制字符)便于调试
- /*std::string hexStr;
- int printLen = std::min(len, 16);
- for (int i = 0; i < printLen; i++) {
- char buf[4];
- snprintf(buf, sizeof(buf), "%02X ", (uint8_t)strSendCommand[i]);
- hexStr += buf;
- }
- if (len > 16) hexStr += "...";
- FINFO("Packet (hex, total len: {$}) - [{$}]", len, hexStr);*/
- // 发送
- unsigned int retLength;
- if (m_SCF->Lock(1000) == WAIT_OBJECT_0)
- {
- int result = m_SCF->SendPacket(strSendCommand, len, nTimeOut, retLength);
- m_SCF->Unlock();
- if (result == SCF_SUCCEED) {
- // 打印发送命令的关键信息(命令内容+完整包长度)
- FINFO("Command to send - [{$}] (raw command length: {$}) - Success - Sent {$} bytes",
- std::string(strCommand, length), len, retLength);
- return RET_STATUS::RET_SUCCEED;
- }
- else {
- FINFO("HWSend: Failed - SendPacket returned error code: {$}", result);
- return RET_STATUS::RET_FAILED;
- }
- }
- else
- {
- FINFO("HWSend: Failed - Could not acquire lock within 1000ms");
- return RET_STATUS::RET_FAILED;
- }
- return RET_STATUS::RET_SUCCEED;
- }
- void nsGEN::PSGHDDevice::FireNotify(string key, int context)
- {
- char szInfo[64] = { 0 };
- snprintf(szInfo, sizeof(szInfo), "%d", context); // Linux 标准函数
- std::string str = szInfo;
- EventCenter->OnNotify(1, key, str);
- }
- void nsGEN::PSGHDDevice::FireNotify(std::string key, float context)
- {
- char szInfo[16] = { 0 };
- snprintf(szInfo, sizeof(szInfo), "%.2f", context); // Linux 标准函数
- std::string str = szInfo;
- EventCenter->OnNotify(1, key, str);
- }
- void nsGEN::PSGHDDevice::FireNotify(std::string key, std::string context)
- {
- EventCenter->OnNotify(1, key, context);
- }
- void nsGEN::PSGHDDevice::FireErrorMessage(const bool Act, const int Code, const char* ResInfo)
- {
- string ErrorCode("PSGHD_ERR_");
- ErrorCode += std::to_string(Code);
- int level = PSG_HD_REGULATION_LEVEL::REG_ERRO;
- if (Act)
- {
- FINFO("add {$}:{$}", ErrorCode.c_str(), ResInfo);
- m_MSGUnit->AddErrorMessage(ErrorCode.c_str(), level, ResInfo);
- }
- else
- {
- FINFO("del {$}:{$}", ErrorCode.c_str(), ResInfo);
- m_MSGUnit->DelErrorMessage(ErrorCode.c_str(), level, ResInfo);
- }
- }
- void nsGEN::PSGHDDevice::FireWarnMessage(const bool Act, const int Code, const char* ResInfo)
- {
- string ErrorCode("PSGHD_WAR_");
- ErrorCode += std::to_string(Code);
- int level = PSG_HD_REGULATION_LEVEL::REG_WARN;
- if (Act)
- {
- FINFO("add {$}:{$}", ErrorCode.c_str(), ResInfo);
- m_MSGUnit->AddWarnMessage(ErrorCode.c_str(), level, ResInfo);
- }
- else
- {
- FINFO("del {$}:{$}", ErrorCode.c_str(), ResInfo);
- m_MSGUnit->DelWarnMessage(ErrorCode.c_str(), level, ResInfo);
- }
- }
- void nsGEN::PSGHDDevice::OnCallBack()
- {
- // 无操作处理函数
- auto HWNotProcess = [](const char* value, int length) -> void
- {
- FINFO("HWNotProcess: Command data (len: {$}) no need to process", length);
- };
- // 处理VREF响应 (电压参考)
- auto HWVREF = [this](const char* data, int length) -> void
- {
- // 需至少4字节数据(XXXX)
- if (length < 4) {
- FINFO("HWVREF: Invalid data length ({$} < 4), skip", length);
- return;
- }
- char kvStr[5] = { 0 };
- strncpy(kvStr, data, 4);
- int kvValue = atoi(kvStr);
- float actualKV = kvValue / 10.0f; // 转换为kV
- m_DoseUnit.m_KV->Update(actualKV);
- FireNotify(AttrKey::KV, m_DoseUnit.m_KV->JSGet());
- FINFO("HWVREF: Parsed actual KV = {$} kV", actualKV);
- };
- // 处理IREF响应 (电流参考)
- auto HWIREF = [this](const char* data, int length) -> void
- {
- if (length < 4) { // 需4字节(XXXX)
- FINFO("HWIREF: Invalid data length ({$} < 4), skip", length);
- return;
- }
- char maStr[5] = { 0 };
- strncpy(maStr, data, 4); // 直接取data
- int maValue = atoi(maStr);
- float actualMA = maValue / 100.0f; // 转换为mA
- m_DoseUnit.m_MA->Update(actualMA);
- FireNotify(AttrKey::MA, m_DoseUnit.m_MA->JSGet());
- FINFO("HWIREF: Parsed actual MA = {$} mA", actualMA);
- };
- // 处理ENBL响应 (X射线使能)
- auto HWENBL = [this](const char* data, int length) -> void
- {
- if (length < 1) { // 需1字节(X)
- FINFO("HWENBL: Invalid data length ({$} < 1), skip", length);
- return;
- }
- // 直接取data[0](无需跳过"ENBL ")
- char enblStr = data[0];
- bool isEnabled = (enblStr == '1');
- FINFO("HWENBL: X-ray enable status = {$}", isEnabled ? "Enabled" : "Disabled");
- };
- // 处理WDTE响应 (看门狗定时器)
- auto HWWDTE = [this](const char* data, int length) -> void
- {
- if (length < 1) { // 需1字节(X)
- FINFO("HWWDTE: Invalid data length ({$} < 1), skip", length);
- return;
- }
- char wdtStr = data[0]; // 直接取data[0]
- bool isWdtEnabled = (wdtStr == '1');
- FINFO("HWWDTE: Watchdog status = {$}", isWdtEnabled ? "Enabled" : "Disabled");
- };
- // 处理WDTT响应 (看门狗定时器重置)
- auto HWWDTT = [this](const char* data, int length) -> void
- {
- if (length < 1) { // 基础长度校验
- FINFO("HWWDTT: Invalid data length ({$} < 1), skip", length);
- return;
- }
- FINFO("HWWDTT: Watchdog timer reset response received");
- };
- // 处理CLR响应 (故障清除)
- auto HWCLR = [this](const char* data, int length) -> void
- {
- if (length < 1) {
- FINFO("HWCLR: Invalid data length ({$} < 1), skip", length);
- return;
- }
- FINFO("HWCLR: Received fault clear response, performing fault clearing");
- };
- // 处理SMS响应 (曝光时间)
- auto HWSMS = [this](const char* data, int length) -> void
- {
- if (length < 7) { // 需7字节(XXXXXXX)
- FINFO("HWSMS: Invalid data length ({$} < 7), skip", length);
- return;
- }
- char smsStr[8] = { 0 };
- strncpy(smsStr, data, 7); // 直接取data
- long timeValue = atol(smsStr);
- float exposureTime = timeValue * 0.01f; // 转换为ms
- m_DoseUnit.m_MS->Update(exposureTime);
- FireNotify(AttrKey::MS, m_DoseUnit.m_MS->JSGet());
- FINFO("HWSMS: Parsed exposure time = {$} ms", exposureTime);
- };
- // 处理FLT响应 (故障状态)
- auto HWFLT = [this](const char* data, int length) -> void
- {
- if (length < 3) { // 需3字节(XXX)
- FINFO("HWFLT: Invalid data length ({$} < 3), skip", length);
- return;
- }
- char faultStr[4] = { 0 };
- strncpy(faultStr, data, 3);
- int faultCode = atoi(faultStr);
- if (faultCode != 0)
- {
- static const std::unordered_map<int, std::string> errorMessages = {
- {2, "Charging circuit abnormal"}, {3, "Storage chip damaged"}, {136, "Filament current 1 exceeds limit"},
- {140, "Anode kV exceeds limit, exposure aborted abnormally"}, {142, "High-voltage generator or tube arcing, exposure aborted abnormally"},
- {165, "Bus voltage too low during high-voltage generator startup"}, {205, "Second-stage handswitch pressed during high-voltage generator wake-up or startup"},
- {206, "High-voltage generator low battery, please charge"}, {208, "Exposure interval too short, please expose later"},
- {209, "Parameter adjustment forbidden during exposure"}, {210, "First-stage handswitch repeated triggering, please use a single handswitch for exposure operation"},
- {216, "Battery being charged"}, {218, "kV parameter exceeds limit"}, {219, "mA parameter exceeds limit"},
- {220, "ms parameter exceeds limit"}, {229, "High-voltage generator power exceeds limit"}, {230, "Tube power exceeds limit"},
- {231, "Frame rate parameter exceeds limit"}, {249, "High-voltage generator bus voltage exceeds limit"}, {255, "kV establishment timeout"},
- {259, "Handswitch released in advance during exposure"}, {260, "Parameter adjustment forbidden during exposure"}, {263, "kV too high during exposure, exposure aborted abnormally"},
- {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"}
- };
- static const std::unordered_set<int> firstSixErrors = { 2, 3, 136, 140, 142, 165 };
- char errorCodeStr[20];
- snprintf(errorCodeStr, sizeof(errorCodeStr), "PSGHD_FLT_%d", faultCode);
- int level = 1;
- auto it = errorMessages.find(faultCode);
- if (it != errorMessages.end())
- {
- if (firstSixErrors.count(faultCode))
- m_MSGUnit->AddErrorMessage(errorCodeStr, level, it->second.c_str());
- else
- m_MSGUnit->AddWarnMessage(errorCodeStr, level, it->second.c_str());
- FINFO("HWFLT: Fault code {$} detected - {$}", faultCode, it->second.c_str());
- }
- }
- else
- {
- char errorCodeStr[20];
- snprintf(errorCodeStr, sizeof(errorCodeStr), "PSGHD_FLT_0");
- int level = 1;
- m_MSGUnit->DelWarnMessage(errorCodeStr, level, "");
- m_MSGUnit->DelErrorMessage(errorCodeStr, level, "");
- FINFO("HWFLT: Fault cleared (fault code 0)");
- }
- };
- // 处理工作相位响应 (RST<aaa>)
- auto HWPhase = [this](const char* data, int length) -> void
- {
- if (length < 3) { // 需3字节(aaa)
- FINFO("HWPhase: Invalid data length ({$} < 3), skip", length);
- return;
- }
- // 设备首次连接时禁止曝光!
- if (m_isFirstHWPhase) {
- SetExpDisable();
- m_isFirstHWPhase = false;
- }
- char phaseCodeStr[4] = { 0 };
- strncpy(phaseCodeStr, data, 3);
- int phaseCode = atoi(phaseCodeStr);
- auto updateAndNotify = [this](nsGEN::AttrKey::GENERATOR_STATUS status)
- {
- if (m_DoseUnit.m_GenState->Update(status))
- {
- FireNotify(AttrKey::GENSTATE, m_DoseUnit.m_GenState->JSGet());
- FINFO("HWPhase: Generator status updated to {$}", static_cast<int>(status));
- }
- };
- switch (phaseCode)
- {
- case 1: updateAndNotify(nsGEN::AttrKey::GENERATOR_STATUS_INIT); break;
- case 7: updateAndNotify(nsGEN::AttrKey::GENERATOR_STATUS_ERROR); break;
- case 9: case 11: updateAndNotify(nsGEN::AttrKey::GENERATOR_STATUS_EXP); break;
- default: FINFO("HWPhase: Unsupported phase code {$}", phaseCode); break;
- }
- };
- auto HWVMON = [this](const char* data, int length) -> void
- {
- if (length < 4) { // 需4字节(XXXX)
- FINFO("HWVMON: Invalid data length ({$} < 4), skip", length);
- return;
- }
- char vmonStr[5] = { 0 };
- strncpy(vmonStr, data, 4); // 直接取data
- int vmonValue = atoi(vmonStr);
- float actualVMON = vmonValue / 10.0f; // 转换为kV
- m_DoseUnit.m_PostKV->Update(actualVMON);
- FireNotify(AttrKey::POSTKV, m_DoseUnit.m_PostKV->JSGet());
- FINFO("HWVMON: Parsed monitoring KV = {$} kV", actualVMON);
- };
- auto HWIMON = [this](const char* data, int length) -> void
- {
- if (length < 4) { // 需4字节(XXXX)
- FINFO("HWIMON: Invalid data length ({$} < 4), skip", length);
- return;
- }
- char imonStr[5] = { 0 };
- strncpy(imonStr, data, 4); // 直接取data
- int imonValue = atoi(imonStr);
- float actualIMON = imonValue / 100.0f; // 转换为mA
- m_DoseUnit.m_PostMA->Update(actualIMON);
- FireNotify(AttrKey::POSTMA, m_DoseUnit.m_PostMA->JSGet());
- FINFO("HWIMON: Parsed monitoring MA = {$} mA", actualIMON);
- };
- auto HWRAT = [this](const char* data, int length) -> void
- {
- if (length < 7) { // 需7字节(XXXXXXX)
- FINFO("HWRAT: Invalid data length ({$} < 7), skip", length);
- return;
- }
- char ratStr[8] = { 0 };
- strncpy(ratStr, data, 7); // 直接取data
- int ratio = atoi(ratStr);
- float actualRatio = ratio / 100.0f;
- m_DoseUnit.m_PostMS->Update(actualRatio);
- FireNotify(m_DoseUnit.m_PostMS->GetKey(), m_DoseUnit.m_PostMS->JSGet());
- FINFO("HWRAT: Parsed ratio parameter = {$}", actualRatio);
- };
- auto HWPOW = [this](const char* data, int length) -> void
- {
- if (length < 1) { // 需1字节(X)
- FINFO("HWPOW: Invalid data length ({$} < 1), skip", length);
- return;
- }
- char powStr = data[0]; // 直接取data[0]
- bool isPowerOn = (powStr == '1');
- FINFO("HWPOW: Power status = {$}", isPowerOn ? "On" : "Off");
- };
- auto HWEOK = [this](const char* data, int length) -> void
- {
- if (length < 1) { // 需1字节(X)
- FINFO("HWEOK: Invalid data length ({$} < 1), skip", length);
- return;
- }
- char eokStr = data[0]; // 直接取data[0]
- bool isReady = (eokStr == '1');
- if (isReady)
- {
- if (m_DoseUnit.m_GenState->Update(nsGEN::AttrKey::GENERATOR_STATUS_STANDBY))
- {
- //FireNotify(AttrKey::GENSTATE, m_DoseUnit.m_GenState->JSGet());
- FINFO("HWEOK: Device ready, status updated to STANDBY");
- }
- }
- else
- {
- if (m_DoseUnit.m_GenState->Update(nsGEN::AttrKey::GENERATOR_STATUS_SLEEP))
- {
- //FireNotify(AttrKey::GENSTATE, m_DoseUnit.m_GenState->JSGet());
- FINFO("HWEOK: Device not ready, status updated to SLEEP");
- }
- }
- };
- auto HWDSW = [this](const char* data, int length) -> void
- {
- if (length < 1) { // 需1字节(X)
- FINFO("HWDSW: Invalid data length ({$} < 1), skip", length);
- return;
- }
- char eokStr = data[0]; // 直接取data[0]
- bool isReady = (eokStr == '1');
- if (isReady && m_DoseUnit.m_GenState->Get()== nsGEN::AttrKey::GENERATOR_STATUS_STANDBY)
- {
- FireNotify(AttrKey::GENSTATE, m_DoseUnit.m_GenState->JSGet());
- FINFO("HWDSW: Device ready, status updated to STANDBY");
- }
- else
- {
- m_DoseUnit.m_GenState->Update(nsGEN::AttrKey::GENERATOR_STATUS_SLEEP);
- FireNotify(AttrKey::GENSTATE, m_DoseUnit.m_GenState->JSGet());
- FINFO("HWDSW: Device not ready, status updated to SLEEP");
- }
- };
- auto HWECD = [this](const char* data, int length) -> void
- {
- if (length < 3) { // 需3字节(XXX)
- FINFO("HWECD: Invalid data length ({$} < 3), skip", length);
- return;
- }
- char ecdStr[4] = { 0 };
- strncpy(ecdStr, data, 3); // 直接取data
- int countdown = atoi(ecdStr);
- FINFO("HWECD: High-voltage OK light countdown = {$}s", countdown);
- };
- auto HWSOC = [this](const char* data, int length) -> void
- {
- if (length < 3) { // 需3字节(XXX)
- FINFO("HWSOC: Invalid data length ({$} < 3), skip", length);
- return;
- }
- char socStr[4] = { 0 };
- strncpy(socStr, data, 3); // 直接取data
- int remainingPower = atoi(socStr);
- FINFO("HWSOC: Generator remaining power = {$}%", remainingPower);
- };
- auto HWFLX = [this](const char* data, int length) -> void
- {
- if (length < 1) { // 需1字节(X)
- FINFO("HWFLX: Invalid data length ({$} < 1), skip", length);
- return;
- }
- char flxStr[2] = { 0 };
- strncpy(flxStr, data, 1);
- int fluoroMode = atoi(flxStr);
- FINFO("HWFLX: Fluorescence mode detected = {$}", fluoroMode);
- if (fluoroMode == 2)
- {
- m_DoseUnit.m_GenSynState->Update(AttrKey::GENERATOR_RAD_XRAYON);
- FireNotify(m_DoseUnit.m_GenSynState->GetKey(), m_DoseUnit.m_GenSynState->JSGet());
- FINFO("HWFLX: X-ray turned ON (mode 2)");
- }
- else if (fluoroMode == 1)
- {
- m_DoseUnit.m_GenSynState->Update(AttrKey::GENERATOR_RAD_READY);
- m_hGenPostEvent->ResetEvent();
- FireNotify(m_DoseUnit.m_GenSynState->GetKey(), m_DoseUnit.m_GenSynState->JSGet());
- FINFO("HWFLX: X-ray ready (mode 1)");
- }
- else if (fluoroMode == 0)
- {
- m_bGenBusy = false;
- m_DoseUnit.m_GenSynState->Update(AttrKey::GENERATOR_RAD_XRAYOFF);
- FireNotify(m_DoseUnit.m_GenSynState->GetKey(), m_DoseUnit.m_GenSynState->JSGet());
- FINFO("HWFLX: X-ray turned OFF (mode 0)");
- }
- };
- auto HWVER = [this](const char* data, int length) -> void
- {
- if (length < 6) { // 需6字节(XXXXXX)
- FINFO("HWVER: Invalid data length ({$} < 6), skip", length);
- return;
- }
- char verStr[7] = { 0 };
- strncpy(verStr, data, 6); // 直接取data
- std::string version(verStr);
- FINFO("HWVER: Generator version = {$}", version);
- };
- auto HWVSN = [this](const char* data, int length) -> void
- {
- if (length < 8) { // 需8字节(XXXXXXXX)
- FINFO("HWVSN: Invalid data length ({$} < 8), skip", length);
- return;
- }
- char vsnStr[9] = { 0 };
- strncpy(vsnStr, data, 8); // 直接取data
- std::string serialNumber(vsnStr);
- FINFO("HWVSN: Generator serial number = {$}", serialNumber);
- };
- auto HWMAS = [this](const char* data, int length) -> void
- {
- if (length < 3) { // 至少3字节(避免atof解析错误)
- FINFO("HWMAS: Invalid data length ({$} < 3), skip", length);
- return;
- }
- float fmas = atof(data) / 100.0f; // 直接用data解析
- if (m_DoseUnit.m_MAS->Update(fmas))
- {
- FireNotify(AttrKey::MAS, m_DoseUnit.m_MAS->JSGet());
- FINFO("HWMAS: Parsed MAS value = {$}", fmas);
- }
- };
- auto HWAP = [this](const char* data, int length) -> void
- {
- if (length < 3) { // 至少3字节(避免atof解析错误)
- FINFO("HWAP: Invalid data length ({$} < 3), skip", length);
- return;
- }
- float fmas = atof(data) / 100.0f; // 直接用data解析
- m_DoseUnit.m_PostMAS->Update(fmas);
- FireNotify(AttrKey::POSTMAS, m_DoseUnit.m_PostMAS->JSGet());
- FINFO("HWAP: Parsed POSTMAS value = {$}", fmas);
- };
- auto HWWS = [this](const char* data, int length) -> void
- {
- if (length < 1) { // 需1字节以上(避免atoi解析错误)
- FINFO("HWWS: Invalid data length ({$} < 1), skip", length);
- return;
- }
- int nValue = atoi(data); // 直接用data解析
- m_DoseUnit.m_WS->Update(nValue);
- FireNotify(m_DoseUnit.m_WS->GetKey(), m_DoseUnit.m_WS->JSGet());
- FINFO("HWWS: Parsed WS parameter = {$}", nValue);
- };
- auto HWEHE = [this](const char* data, int length) -> void
- {
- if (length < 1) { // 需1字节以上
- FINFO("HWEHE: Invalid data length ({$} < 1), skip", length);
- return;
- }
- m_iHeartBeats = 0;
- int nhe = atoi(data); // 直接用data解析
- if (m_DoseUnit.m_HE->Update(nhe))
- {
- FireNotify(m_DoseUnit.m_HE->GetKey(), m_DoseUnit.m_HE->JSGet());
- FINFO("HWEHE: Parsed HE parameter = {$}", nhe);
- }
- };
- arFrame.clear();
- // 指令映射表补充
- arFrame.push_back(tFrameMapping("VREF ", 5, HWVREF));
- arFrame.push_back(tFrameMapping("IREF ", 5, HWIREF));
- arFrame.push_back(tFrameMapping("VMON ", 5, HWVMON));
- arFrame.push_back(tFrameMapping("IMON ", 5, HWIMON));
- arFrame.push_back(tFrameMapping("ENBL ", 5, HWENBL));
- arFrame.push_back(tFrameMapping("RST ", 4, HWPhase));
- arFrame.push_back(tFrameMapping("SMS ", 4, HWSMS));
- arFrame.push_back(tFrameMapping("RAT ", 4, HWRAT));
- arFrame.push_back(tFrameMapping("POW ", 4, HWPOW));
- arFrame.push_back(tFrameMapping("EOK ", 4, HWEOK));
- arFrame.push_back(tFrameMapping("ECD ", 4, HWECD));
- arFrame.push_back(tFrameMapping("FLX ", 4, HWFLX));
- arFrame.push_back(tFrameMapping("FLT ", 4, HWFLT));
- arFrame.push_back(tFrameMapping("RHE ", 4, HWEHE));
- arFrame.push_back(tFrameMapping("VER ", 4, HWVER));
- arFrame.push_back(tFrameMapping("VSN ", 4, HWVSN));
- arFrame.push_back(tFrameMapping("CLR", 4, HWCLR));
- arFrame.push_back(tFrameMapping("EC", 2, HWNotProcess));
- arFrame.push_back(tFrameMapping("PW", 2, HWNotProcess));
- arFrame.push_back(tFrameMapping("MX", 2, HWMAS));
- arFrame.push_back(tFrameMapping("WS", 2, HWWS));
- }
- bool nsGEN::PSGHDDevice::ReConnect()
- {
- FINFO("Enter PSG_reConnect");
- m_SCF->Disconnect();
- if (!pIODriver)
- {
- FINFO("PSG_reConnect:Driver null");
- }
- else
- {
- // 需要将 pIODriver 转换为 PSGHDDriver*
- PSGHDDriver* driver = dynamic_cast<PSGHDDriver*>(pIODriver.get());
- if (driver && driver->ReConnection())
- {
- FireErrorMessage(false, 1, "lost Connect");
- m_bConnectFlag = true;
- FINFO("PSG_reConnect success");
- return true;
- }
- else
- {
- FINFO("PSG_reConnect failed");
- }
- }
- return false;
- }
- int nsGEN::PSGHDDevice::GetGenState()
- {
- if (m_DoseUnit.m_GenState != NULL)
- {
- return m_DoseUnit.m_GenState->Get();
- }
- else
- {
- return 0;
- }
- }
- int nsGEN::PSGHDDevice::LoadConfig(string configfile)
- {
- FINFO("=====================LoadConfig=========================");
- // 检查文件是否存在
- std::ifstream file(configfile);
- if (!file) {
- // 文件不存在,直接返回空的Connection对象
- FINFO("Config file does not exist: {$}", configfile.c_str());
- return -1;
- }
- if (m_bIsConfigLoaded)
- {
- FINFO("Configuration already loaded.");
- return 0;
- }
- ResDataObject temp;
- temp.loadFile(configfile.c_str());
- m_GenConfig = temp["CONFIGURATION"];
- TransJsonText(m_GenConfig);
- if (m_GenConfig.GetKeyCount("loopEnable") > 0)
- {
- m_bExtraFlag = (int)m_GenConfig["loopEnable"];
- }
- if (m_GenConfig.GetKeyCount(ConfKey::CcosTubeInfo) > 0)
- {
- string tempValue = (string)m_GenConfig[ConfKey::CcosTubeInfo];
- m_DoseUnit.m_TubeInfo.reset(new TUBEINFOMould(tempValue));
- FireNotify(AttrKey::TUBEINFO, m_DoseUnit.m_TubeInfo->JSGet());
- }
- if (m_GenConfig.GetKeyCount(ConfKey::CcosFocusSmall) > 0)
- {
- float tempValue = (float)m_GenConfig[ConfKey::CcosFocusSmall];
- m_DoseUnit.m_FocusSmall = tempValue;
- }
- if (m_GenConfig.GetKeyCount(ConfKey::CcosFocusLarge) > 0)
- {
- float tempValue = (float)m_GenConfig[ConfKey::CcosFocusLarge];
- m_DoseUnit.m_FocusLarge = tempValue;
- }
- if (m_GenConfig.GetKeyCount("GenCtrlMode") > 0)
- {
- m_nCtlMode = (float)m_GenConfig["GenCtrlMode"];//default 2
- float tempValue = (float)m_GenConfig[ConfKey::CcosFocusLarge];
- }
- if (m_GenConfig.GetKeyCount("USECECMD") > 0)
- {
- m_bUseCECmd = (bool)m_GenConfig["USECECMD"];
- }
- m_bIsConfigLoaded = true;
- return 0;
- }
- bool nsGEN::PSGHDDevice::ECHO(void)
- {
- return HWSend("ECH", 3);
- }
- bool nsGEN::PSGHDDevice::StartHardwareStatusThread()
- {
- if (!m_pHardwareStatusThread.joinable())
- {
- m_pHardwareStatusThread = std::thread(HardwareStatusThread, this);
- return true;
- }
- return false;
- }
- void PSGHDDevice::HardwareStatusThread(PSGHDDevice* pParam)
- {
- if (pParam == nullptr)
- {
- return;
- }
- PSGHDDevice* pCurGen = pParam;
- int messageIndex = 0;
- while (pCurGen->m_bExtraFlag)
- {
- // 获取当前循环时间并休眠
- int currentLoopTime = pCurGen->m_iLoopTime;
- Sleep(currentLoopTime);
- // 每5次循环发送状态查询命令
- if (messageIndex % 5 == 0&& !pCurGen->m_bSleepState)
- {
- pCurGen->HWSend("RHE", 3);
- Sleep(100);
- pCurGen->HWSend("RST", 3);
- Sleep(100);
- pCurGen->HWSend("EOK", 3);
- }
- messageIndex++;
- // 防止messageIndex无限增长导致溢出
- if (messageIndex >= INT_MAX - 10)
- {
- messageIndex = 0;
- }
- }
- // 线程退出时重置心跳标志
- }
- //-----------------------------------------------------------------------------
- // PSGHDDriver
- //-----------------------------------------------------------------------------
- nsGEN::PSGHDDriver::PSGHDDriver()
- : m_scfWrapper(std::make_shared<SCFWrapper>())
- {
- m_pAttribute.reset(new ResDataObject());
- m_pDescription.reset(new ResDataObject());
- }
- nsGEN::PSGHDDriver::~PSGHDDriver()
- {
- Disconnect();
- }
- void nsGEN::PSGHDDriver::Prepare()
- {
- // 初始化日志系统
- std::string strLogPath = GetProcessDirectory() + R"(/Conf/log_config.xml)";
- std::string LogHost = "DevPSGHD";
- std::string moduleName = "DevPSGHD";
- bool ret = initLogModule(
- LogHost, // 主机名(用于日志路径中的{host}占位符)
- moduleName, // 唯一模块名
- strLogPath, // 配置文件路径
- true // 是否输出到控制台(可选)
- );
- if (!ret) {
- std::cerr << "Log init failed!" << std::endl;
- return;
- }
- PSGHDSetLocalModuleName(moduleName);
- m_SCFDllName = GetConnectDLL(m_ConfigFileName);
- // 绑定当前动态库的模块名(调用自身实现的接口)
- FINFO("Prepare is OK.SCFDllName is {$}", m_SCFDllName);
- }
- std::string nsGEN::PSGHDDriver::DriverProbe()
- {
- FINFO("DriverProbe in \n");
- ResDataObject r_config, HardwareInfo;
- if (r_config.loadFile(m_ConfigFileName.c_str()))
- {
- HardwareInfo.add("MajorID", r_config["CONFIGURATION"]["MajorID"]);
- HardwareInfo.add("MinorID", r_config["CONFIGURATION"]["MinorID"]);
- HardwareInfo.add("VendorID", r_config["CONFIGURATION"]["VendorID"]);
- HardwareInfo.add("ProductID", r_config["CONFIGURATION"]["ProductID"]);
- HardwareInfo.add("SerialID", r_config["CONFIGURATION"]["SerialID"]);
- }
- else
- {
- HardwareInfo.add("MajorID", "Generator");
- HardwareInfo.add("MinorID", "Dr");
- HardwareInfo.add("VendorID", "PSGHD");
- HardwareInfo.add("ProductID", "HF");
- HardwareInfo.add("SerialID", "Drv");
- }
- string ret = HardwareInfo.encode();
- return ret;
- }
- bool nsGEN::PSGHDDriver::ReConnection()
- {
- Disconnect();
- FINFO("ReConnection:SCF Disconnect");
- ResDataObject Connection = GetConnectParam(m_ConfigFileName);
- FINFO("ReConnection:{$} \n", Connection.encode());
- auto erCode = m_scfWrapper->Connect(Connection, &PSGHDDriver::callbackPackageProcess, SCF_PACKET_TRANSFER, 3000);
- if (erCode == SCF_SUCCEED)
- {
- Sleep(1000);
- // 重新设置数据接收回调
- m_scfWrapper->SetDataReceivedCallback([this](const char* data, uint32_t length) {
- this->Dequeue(data, length);
- });
- // 启动自动接收
- m_scfWrapper->StartAutoReceive();
- return true;
- }
- else
- {
- FINFO("ReConnection failed");
- }
- return false;
- }
- bool nsGEN::PSGHDDriver::Connect()
- {
- std::lock_guard<std::mutex> lock(m_connectionMutex);
- const auto currentState = m_connectionState.load();
- auto now = std::chrono::steady_clock::now();
- // 1. 处理可重试的失败状态
- if (currentState == ConnectionState::Failed) {
- if ((now - m_lastConnectionAttempt) >= RETRY_INTERVAL && m_connectionRetryCount < MAX_RETRY_COUNT) {
- m_connectionState = ConnectionState::Disconnected;
- }
- else {
- return false; // 不满足重试条件,直接返回
- }
- }
- // 2. 检查无效状态(正在连接/已连接但实际有效)
- if (currentState == ConnectionState::Connecting) {
- FINFO("Already connecting (type: {$})",
- m_currentConnType == ConnectionType::Serial ? "Serial" : "Ethernet");
- return true;
- }
- if (currentState == ConnectionState::Connected && m_scfWrapper && m_scfWrapper->IsConnected()) {
- FINFO("Already connected (type: {$})",
- m_currentConnType == ConnectionType::Serial ? "Serial" : "Ethernet");
- return true;
- }
- // 3. 检查重试间隔
- if (m_connectionRetryCount > 0 && (now - m_lastConnectionAttempt) < RETRY_INTERVAL) {
- FINFO("Retry in {$}s (type: {$})",
- std::chrono::duration_cast<std::chrono::seconds>(RETRY_INTERVAL - (now - m_lastConnectionAttempt)).count(),
- m_currentConnType == ConnectionType::Serial ? "Serial" : "Ethernet");
- return false;
- }
- ResDataObject connParam = GetConnectParam(m_ConfigFileName);
- std::string connPortStr = "";
- std::string connTypeStr = (std::string)connParam["type"]; // 从配置读取type字段
- m_currentConnType = (connTypeStr == "COM") ? ConnectionType::Serial : ConnectionType::Ethernet;
- if (m_currentConnType == ConnectionType::Serial)
- {
- connPortStr = (std::string)connParam["port"];// 从配置读取port字段
- // 查找配置端口在现有端口列表中的位置
- auto it = std::find(m_serialPorts.begin(), m_serialPorts.end(), connPortStr);
- if (it == m_serialPorts.end()) {
- // 配置的端口不在列表中,添加到首位
- FINFO("Configured serial port {$} not found, adding to front of port list", connPortStr);
- m_serialPorts.insert(m_serialPorts.begin(), connPortStr);
- }
- else if (it != m_serialPorts.begin()) {
- // 配置的端口存在但不在首位,移动到首位
- FINFO("Moving configured serial port {$} to front of port list", connPortStr);
- m_serialPorts.erase(it);
- m_serialPorts.insert(m_serialPorts.begin(), connPortStr);
- }
- }
- // 4. 执行连接流程
- m_connectionState = ConnectionState::Connecting;
- m_lastConnectionAttempt = now;
- std::string connInfo;
- try {
- if (m_currentConnType == ConnectionType::Serial) {
- // 串口连接:使用当前索引的端口
- std::string currentPort = m_serialPorts[m_currentSerialPortIndex];
- connParam.update("port", currentPort.c_str()); // 将当前尝试的端口写入参数
- connInfo = "Serial (port: " + currentPort + ")";
- }
- else {
- // 网口连接:直接使用配置参数
- connInfo = "Ethernet (ip: " + std::string(connParam["ip"]) + ")";
- }
- FINFO("Enter Connect ({$}), config: {$}", connInfo, connParam.encode());
- if (!m_scfWrapper->Initialize(m_SCFDllName)) {
- FINFO("Init failed: {$}", m_scfWrapper->GetLastError());
- m_connectionState = ConnectionState::Failed;
- return false;
- }
- m_scfWrapper->SetDataReceivedCallback([this](const char* data, uint32_t length) {
- this->Dequeue(data, length);
- });
- auto erCode = m_scfWrapper->Connect(connParam, &PSGHDDriver::callbackPackageProcess, SCF_NORMAL_TRANSFER, 3000);
- if (erCode != SCF_SUCCEED || !m_scfWrapper->StartAutoReceive()) {
- FINFO("Connect failed (code: {$}) for {$}", erCode, connInfo);
- m_scfWrapper->Disconnect();
- m_connectionState = ConnectionState::Failed;
- // 串口连接:未遍历完所有端口时,优先切换端口重试(不计入总重试次数)
- if (m_currentConnType == ConnectionType::Serial) {
- int nextIndex = (m_currentSerialPortIndex + 1) % m_serialPorts.size();
- // 判断是否已遍历所有端口(当前索引是最后一个时,nextIndex会回到0)
- bool allPortsTried = (nextIndex == 0);
- if (!allPortsTried) {
- // 未遍历完所有端口:切换到下一端口,不增加重试计数
- m_currentSerialPortIndex = nextIndex;
- m_connectionRetryCount = 0;
- FINFO("Trying next serial port: {$}", m_serialPorts[nextIndex]);
- return false; // 触发外部线程立即尝试下一端口
- }
- else {
- // 已遍历所有端口:重置到第一个端口,增加重试计数(进入间隔等待)
- m_currentSerialPortIndex = 0;
- m_connectionRetryCount++;
- FINFO("All serial ports tried, retry count: {$}/{$}", m_connectionRetryCount, MAX_RETRY_COUNT);
- return false;
- }
- }
- // 所有端口失败(串口)或网口失败,才增加总重试计数
- m_connectionRetryCount++;
- return false;
- }
- // 连接成功:重置状态
- m_connectionState = ConnectionState::Connected;
- m_connectionRetryCount = 0;
- m_currentSerialPortIndex = 0; // 重置串口端口索引
- FINFO("Connected successfully ({$})", connInfo);
- return true;
- }
- catch (const std::exception& e) {
- FINFO("Exception for {$}: {$}", connInfo, e.what());
- m_connectionState = ConnectionState::Failed;
- m_connectionRetryCount++;
- return false;
- }
- }
- auto nsGEN::PSGHDDriver::CreateDevice(int index) -> std::unique_ptr <IODevice>
- {
- FINFO("CreateDevice in\n");
- m_pDevice = new PSGHDDevice(EventCenter, m_scfWrapper, m_ConfigFileName);
- auto dev = std::unique_ptr <IODevice>(new IODevice(m_pDevice));
- FINFO("CreateDevice out\n");
- return dev;
- }
- void nsGEN::PSGHDDriver::FireNotify(int code, std::string key, std::string content)
- {
- EventCenter->OnNotify(code, key, content);
- }
- bool nsGEN::PSGHDDriver::isConnected() const
- {
- const auto state = m_connectionState.load();
- // 1. 连接中/实际已连接:返回true(无需重连)
- if (state == ConnectionState::Connecting || (m_scfWrapper && m_scfWrapper->IsConnected())) {
- FINFO(state == ConnectionState::Connecting ? "Connecting in progress" : "Already connected");
- return true;
- }
- // 2. 失败状态处理:判断是否允许重试
- if (state == ConnectionState::Failed) {
- auto now = std::chrono::steady_clock::now();
- const auto timeSinceLast = now - m_lastConnectionAttempt;
- // 2.1 达到最大重试次数,但超过重置间隔:重置计数,允许重新重试
- if (m_connectionRetryCount >= MAX_RETRY_COUNT && timeSinceLast >= RESET_RETRY_AFTER) {
- FINFO("Max retries reached, resetting count after {$}s",
- std::chrono::duration_cast<std::chrono::seconds>(timeSinceLast).count());
- m_connectionRetryCount = 0; // 重置计数(因mutable修饰,const函数可修改)
- }
- // 2.2 不适合重连(时间未到 或 次数仍超限):返回true阻止重连
- if (timeSinceLast < RETRY_INTERVAL || m_connectionRetryCount >= MAX_RETRY_COUNT) {
- FINFO(timeSinceLast < RETRY_INTERVAL ?
- "Retry later ({$}s)" : "Max retries, waiting {$}s to reset",
- std::chrono::duration_cast<std::chrono::seconds>(
- timeSinceLast < RETRY_INTERVAL ? RETRY_INTERVAL - timeSinceLast : RESET_RETRY_AFTER - timeSinceLast
- ).count()
- );
- return true;
- }
- }
- // 3. 其他情况(适合重连):返回false触发Connect()
- return false;
- }
- std::string nsGEN::PSGHDDriver::GetResource()
- {
- FDEBUG("GetResource");
- ResDataObject r_config, temp;
- if (!temp.loadFile(m_ConfigFileName.c_str()))
- {
- return "";
- }
- m_ConfigAll = temp;
- r_config = temp["CONFIGURATION"];
- m_Configurations = r_config;
- ResDataObject DescriptionTemp;
- ResDataObject DescriptionSend;
- ResDataObject m_DescriptionSend;
- ResDataObject ListTemp;
- string strTemp = ""; //用于读取字符串配置信息
- string strIndex = ""; //用于读取配置信息中的List项
- int nTemp = -1; //用于读取整型配置信息
- char sstream[10] = { 0 }; //用于转换值
- string strValue = ""; //用于存储配置的值
- string strType = ""; //用于存储配置的类型 int/float/string...
- /***
- * 1. 通过循环,将所有配置项写到pDeviceConfig
- * 2. 记录配置项的内部key以及配置类型,类型对应了不同配置文件路径,用于读写真实值
- ***/
- try
- {
- //便利ConfigToolInfo 中 所有的AttributeInfo 属性段
- int nConfigInfoCount = (int)m_Configurations["ConfigToolInfo"].GetKeyCount("AttributeInfo");
- m_pAttribute->clear();
- m_pDescription->clear();
- for (int nInfoIndex = 0; nInfoIndex < nConfigInfoCount; nInfoIndex++)
- {
- DescriptionTemp.clear();
- DescriptionSend.clear();
- ListTemp.clear();
- //AttributeType
- strTemp = (string)m_Configurations["ConfigToolInfo"][nInfoIndex]["AttributeDescripition"]["Type"];
- DescriptionTemp.add(ConfKey::CcosType, strTemp.c_str());//CcosGeneratorAttribute
- DescriptionSend.add(ConfKey::CcosType, strTemp.c_str());//CcosGeneratorAttribute
- strType = strTemp; //记录配置项的类型
- //AttributeKey
- //1. 根据AttributeType,内部key和配置路径,拿到当前的真实值
- strTemp = (string)m_Configurations["ConfigToolInfo"][nInfoIndex]["InnerKey"];
- nTemp = (int)m_Configurations["ConfigToolInfo"][nInfoIndex]["PathID"];
- GetDeviceConfigValue(r_config, strTemp.c_str(), nTemp, strValue); //得到strValue的值
- //printf("********************************innerkey=%s --strValue = %s\n", strTemp.c_str(), strValue.c_str());
- //2. 赋值
- strTemp = (string)m_Configurations["ConfigToolInfo"][nInfoIndex]["AttributeKey"];
- if ("int" == strType)
- {
- (*m_pAttribute).add(strTemp.c_str(), atoi(strValue.c_str()));
- }
- else if ("float" == strType)
- {
- (*m_pAttribute).add(strTemp.c_str(), atoi(strValue.c_str()));
- }
- else //其它先按string类型处理
- {
- (*m_pAttribute).add(strTemp.c_str(), strValue.c_str());
- }
- //printf("********************************outkey =%s --strValue = %s\n", strTemp.c_str(), strValue.c_str());
- //AttributeAccess
- strTemp = (string)m_Configurations["ConfigToolInfo"][nInfoIndex]["AttributeDescripition"]["Access"];
- DescriptionTemp.add(ConfKey::CcosAccess, strTemp.c_str());
- DescriptionSend.add(ConfKey::CcosAccess, strTemp.c_str());
- /*
- //AttributeRangeMin
- strTemp = (string)m_Configurations["ConfigToolInfo"][nInfoIndex]["AttributeDescripition"]["RangeMin"];
- if (strTemp != "") //不需要的配置项为空
- {
- DescriptionTemp.add(ConfKey::CcosRangeMin, strTemp.c_str());
- }
- //AttributeRangeMax
- strTemp = (string)m_Configurations["ConfigToolInfo"][nInfoIndex]["AttributeDescripition"]["RangeMax"];
- if (strTemp != "") //不需要的配置项为空
- {
- DescriptionTemp.add(ConfKey::CcosRangeMax, strTemp.c_str());
- }
- */
- //AttributeList
- nTemp = m_Configurations["ConfigToolInfo"][nInfoIndex]["AttributeDescripition"]["ListNum"];
- if (nTemp > 0) //ListNum不大于0时说明不需要list配置
- {
- for (int nListIndex = 0; nListIndex < nTemp; nListIndex++)
- {
- strTemp = (string)m_Configurations["ConfigToolInfo"][nInfoIndex]["AttributeDescripition"]["ListInfo"][nListIndex];
- auto temKey = std::to_string(nListIndex);
- ListTemp.add(temKey.c_str(), strTemp.c_str());
- }
- DescriptionTemp.add(ConfKey::CcosList, ListTemp);
- DescriptionSend.add(ConfKey::CcosList, ListTemp.encode());
- }
- //AttributeRequired
- strTemp = (string)m_Configurations["ConfigToolInfo"][nInfoIndex]["AttributeDescripition"]["Required"];
- DescriptionTemp.add(ConfKey::CcosRequired, strTemp.c_str());
- DescriptionSend.add(ConfKey::CcosRequired, strTemp.c_str());
- //AttributeDefaultValue
- strTemp = (string)m_Configurations["ConfigToolInfo"][nInfoIndex]["AttributeDescripition"]["DefaultValue"];
- if (strTemp != "") //不需要的配置项为空
- {
- DescriptionTemp.add(ConfKey::CcosDefaultValue, strTemp.c_str());
- DescriptionSend.add(ConfKey::CcosDefaultValue, strTemp.c_str());
- }
- strTemp = (string)m_Configurations["ConfigToolInfo"][nInfoIndex]["AttributeKey"];
- (*m_pDescription).add(strTemp.c_str(), DescriptionTemp);
- m_DescriptionSend.add(strTemp.c_str(), DescriptionSend.encode());
- }
- }
- catch (ResDataObjectExption& e)
- {
- FERROR("Get config error: {$}", e.what());
- return "";
- }
- ResDataObject resDeviceResource;
- resDeviceResource.add(ConfKey::CcosGeneratorAttribute, (*m_pAttribute));
- resDeviceResource.add(ConfKey::CcosGeneratorDescription, (*m_pDescription));
- ResDataObject DescriptionTempEx;
- DescriptionTempEx.add(ConfKey::CcosGeneratorConfig, resDeviceResource);
- m_DeviceConfig.clear();
- m_DeviceConfig = DescriptionTempEx;
- //Debug("local ************* get resource over {$}", DescriptionTempEx.encode());
- //printf("local ************* get resource over %s \n", DescriptionTempEx.encode());
- resDeviceResource.clear();
- resDeviceResource.add(ConfKey::CcosGeneratorAttribute, (*m_pAttribute));
- resDeviceResource.add(ConfKey::CcosGeneratorDescription, m_DescriptionSend);
- DescriptionTempEx.clear();
- DescriptionTempEx.add(ConfKey::CcosGeneratorConfig, resDeviceResource);
- m_DeviceConfigSend.clear();
- m_DeviceConfigSend = DescriptionTempEx;
- string res = m_DeviceConfigSend.encode();
- //printf("%s", res.c_str());
- //Debug("get resource over {$}", DescriptionTempEx.encode());
- //("************* get resource over %s \n", DescriptionTempEx.encode());
- return res;
- }
- std::string nsGEN::PSGHDDriver::DeviceProbe()
- {
- FINFO("std::string nsGEN::PSGHDDriver::DeviceProbe() in\n");
- ResDataObject r_config, HardwareInfo;
- if (r_config.loadFile(m_ConfigFileName.c_str()))
- {
- HardwareInfo.add("MajorID", r_config["CONFIGURATION"]["MajorID"]);
- HardwareInfo.add("MinorID", r_config["CONFIGURATION"]["MinorID"]);
- HardwareInfo.add("VendorID", r_config["CONFIGURATION"]["VendorID"]);
- HardwareInfo.add("ProductID", r_config["CONFIGURATION"]["ProductID"]);
- HardwareInfo.add("SerialID", r_config["CONFIGURATION"]["SerialID"]);
- }
- else
- {
- HardwareInfo.add("MajorID", "Generator");
- HardwareInfo.add("MinorID", "Dr");
- HardwareInfo.add("VendorID", "PSGHD");
- HardwareInfo.add("ProductID", "HF");
- HardwareInfo.add("SerialID", "Dev");
- }
- string ret = HardwareInfo.encode();
- FINFO("std::string nsGEN::PSGHDDriver::DeviceProbe() out\n");
- return ret;
- }
- void nsGEN::PSGHDDriver::Disconnect()
- {
- if (m_scfWrapper) {
- m_scfWrapper->StopAutoReceive();
- m_scfWrapper->Disconnect();
- }
- }
- void nsGEN::PSGHDDriver::Dequeue(const char* Packet, DWORD Length)
- {
- DecodeFrame(Packet, Length);
- }
- PACKET_RET nsGEN::PSGHDDriver::callbackPackageProcess(const char* RecData, uint32_t nLength, uint32_t& PacketLength)
- {
- // 日志:进入数据包处理函数,记录输入长度
- FINFO("[PSGHDDriver] 开始处理数据包,输入长度: [{$}]", nLength);
- if (nLength < 3)
- {
- // 日志:数据包长度不足
- FINFO("[PSGHDDriver] 数据包长度小于3,无效数据包,返回PACKET_USELESS");
- return PACKET_USELESS;
- }
- // 查找STX (0x02)
- int startIndex = -1;
- for (uint32_t i = 0; i < nLength; i++)
- {
- if (RecData[i] == 0x02)
- {
- startIndex = i;
- break;
- }
- }
- if (startIndex == -1)
- {
- // 日志:未找到STX标记
- FINFO("[PSGHDDriver] 未找到STX(0x02)标记,返回PACKET_USELESS");
- return PACKET_USELESS;
- }
- // 日志:找到STX标记
- FINFO("[PSGHDDriver] 找到STX(0x02)标记,位置: [{$}]", startIndex);
- // 查找CRLF (0x0D, 0x0A)
- int endIndex = -1;
- for (uint32_t i = startIndex + 1; i < nLength - 1; i++)
- {
- if (RecData[i] == 0x0D && RecData[i + 1] == 0x0A)
- {
- endIndex = i;
- break;
- }
- }
- if (endIndex == -1)
- {
- // 日志:未找到CRLF结束标记
- FINFO("[PSGHDDriver] 未找到CRLF(0x0D,0x0A)结束标记,返回PACKET_NOPACKET");
- return PACKET_NOPACKET;
- }
- // 日志:找到CRLF标记
- FINFO("[PSGHDDriver] 找到CRLF(0x0D,0x0A)标记,位置: [{$}]", endIndex);
- // 计算数据包长度
- PacketLength = endIndex + 2 - startIndex;
- FINFO("[PSGHDDriver] 数据包处理完成,有效长度: [{$}],返回PACKET_ISPACKET", PacketLength);
- return PACKET_ISPACKET;
- }
- bool nsGEN::PSGHDDriver::GetDeviceConfig(std::string& Cfg)
- {
- Cfg = m_DeviceConfigSend.encode();
- printf("GetDeviceConfig over , %s", Cfg.c_str());
- return true;
- }
- bool nsGEN::PSGHDDriver::SetDeviceConfig(std::string Cfg)
- {
- FINFO("--Func-- SetDeviceConfig {$}\n", Cfg.c_str());
- printf("\n--Func-- SetDeviceConfig %s\n", Cfg.c_str());
- ResDataObject DeviceConfig;
- DeviceConfig.decode(Cfg.c_str());
- ResDataObject DescriptionTempEx;
- DescriptionTempEx = DeviceConfig["DeviceConfig"]["Attribute"];
- FDEBUG("Attribute:{$}", DescriptionTempEx.encode());
- bool bSaveFile = false; //true:重新保存配置文件
- string strAccess = "";
- for (int i = 0; i < DescriptionTempEx.size(); i++)
- {
- string strKey = DescriptionTempEx.GetKey(i);
- FINFO("{$}", strKey.c_str());
- printf("%s\n", strKey.c_str());
- try
- {
- if (m_pAttribute->GetFirstOf(strKey.c_str()) >= 0)
- {
- strAccess = (string)(*m_pDescription)[strKey.c_str()]["Access"];
- if ("RW" == strAccess)
- {
- //修改对应配置,在其他单元的配置项要同时调用其修改函数修改真实值
- //1. 修改内存中的值,用于给上层发消息
- (*m_pAttribute)[strKey.c_str()] = DescriptionTempEx[i];
- //2. 拿到Innerkey
- int nConfigInfoCount = (int)m_Configurations["ConfigToolInfo"].GetKeyCount("AttributeInfo");
- FINFO("nConfigInfoCount {$}", nConfigInfoCount);
- string strTemp = ""; //存储AttributeKey
- for (int nInfoIndex = 0; nInfoIndex < nConfigInfoCount; nInfoIndex++)
- {
- strTemp = (string)m_Configurations["ConfigToolInfo"][nInfoIndex]["AttributeKey"];
- if (strTemp == strKey)
- {
- strTemp = (string)m_Configurations["ConfigToolInfo"][nInfoIndex]["InnerKey"];
- break;
- }
- }
- //3. 修改配置文件中的值
- if (SetDeviceConfigValue(m_Configurations, strTemp.c_str(), 1, DescriptionTempEx[i]))
- {
- FDEBUG("SetDeviceConfigValue over");
- bSaveFile = true;
- }
- }
- else
- {
- FINFO("{$} is not a RW configuration item", strKey.c_str());
- }
- }
- else
- {
- FINFO("without this attribute {$}", strKey.c_str());
- }
- }
- catch (ResDataObjectExption& e)
- {
- printf("\nSetDriverConfig crashed: %s\n", e.what());
- FERROR("SetDriverConfig crashed: {$}", e.what());
- return false;
- }
- }
- if (bSaveFile)
- {
- //3. 重新保存配置文件
- SaveConfigFile(true);
- }
- return true;
- }
- bool nsGEN::PSGHDDriver::SaveConfigFile(bool bSendNotify)
- {
- m_ConfigAll["CONFIGURATION"] = m_Configurations;
- bool bRt = m_ConfigAll.SaveFile(m_ConfigFileName.c_str());
- FINFO("SaveConfigFile over {$}", bRt);
- return true;
- }
- bool nsGEN::PSGHDDriver::GetDeviceConfigValue(ResDataObject config, const char* pInnerKey, int nPathID, string& strValue)
- {
- strValue = "";
- string strTemp = pInnerKey;
- if (1 == nPathID) //从DriverConfig路径下每个DPC自己的配置文件读取
- {
- int pos = 0;
- ResDataObject resTemp = config;
- while ((pos = strTemp.find_first_of(',')) != string::npos)
- {
- string Key = strTemp.substr(0, pos);
- string TempValue = resTemp[Key.c_str()].encode();
- // printf("-TempValue=== %s", TempValue.c_str());
- resTemp.clear();
- resTemp.decode(TempValue.c_str());
- strTemp = strTemp.substr(pos + 1, strTemp.length() - pos - 1);
- //printf("-************--%s", strTemp.c_str());
- }
- if (strTemp != "")
- {
- strValue = (string)resTemp[strTemp.c_str()];
- }
- else
- {
- strValue = (string)resTemp;
- }
- }
- //printf("------------%s", strValue.c_str());
- return true;
- }
- bool nsGEN::PSGHDDriver::SetDeviceConfigValue(ResDataObject& config, const char* pInnerKey, int nPathID, const char* szValue)
- {
- string strTemp = pInnerKey;
- FINFO("Begin to change {$} item value to {$}", pInnerKey, szValue);
- if (1 == nPathID) //从DriverConfig路径下每个DPC自己的配置文件读取
- {
- try {
- int pos = 0;
- ResDataObject* resTemp = &config;
- while ((pos = strTemp.find_first_of(',')) != string::npos)
- {
- string Key = strTemp.substr(0, pos);
- resTemp = &(*resTemp)[Key.c_str()];
- strTemp = strTemp.substr(pos + 1, strTemp.length() - pos - 1);
- }
- if (strTemp != "")
- {
- (*resTemp)[strTemp.c_str()] = szValue;
- }
- else
- {
- *resTemp = szValue;
- }
- }
- catch (ResDataObjectExption& e)
- {
- FERROR("SetDriverConfigvalue crashed: {$}", e.what());
- return false;
- }
- }
- return true;
- }
- //-----------------------------------------------------------------------------
- // GetIODriver & CreateIODriver
- //-----------------------------------------------------------------------------
- static nsGEN::PSGHDDriver gIODriver;
- extern "C" CCOS::Dev::IODriver * GetIODriver() // 返回静态对象的引用, 调用者不能删除 !
- {
- return &gIODriver;
- }
- extern "C" CCOS::Dev::IODriver * CreateIODriver() // 返回新对象, 调用者必须自行删除此对象 !
- {
- pIODriver = new nsGEN::PSGHDDriver();
- return pIODriver;
- }
|