Detector_TiRayDR.cpp 99 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377
  1. #include "Detector_TiRayDR.h"
  2. #include "CCOS.Dev.FPD.TiRayDR.h"
  3. #include "MyPingip.h"
  4. #include <dlfcn.h>
  5. #include <pthread.h>
  6. #include "LogLocalHelper.h"
  7. #include "Log4CPP.h"
  8. using EventListenerType = void(*)(TiRayEvent, void*);
  9. Detector_TiRayDR* g_pDetector = nullptr;
  10. // 函数声明
  11. static std::string generateReadableTimestamp();
  12. //extern Log4CPP::Logger* mLog::gLogger;
  13. /****************************************/
  14. int (*GetSdkVersion_Ptr)(void);
  15. TiRayError(*Scan_Ptr)(ResultCallback fn, const char* interfaceIp, int scanDuration);
  16. TiRayError(*SetIp_Ptr)(const char* detectorSN, const char* upperIp, const char* lowerIp, const char* interfaceIp);
  17. TiRayError(*Startup_Ptr)(TiRayModel model, EventCallback fn, const StartupOption * option);
  18. void (*Stop_Ptr)();
  19. TiRayError(*Execute_Ptr)(int detectorId, int commandId, TiRayVariant argv[], int argc);
  20. TiRayError(*ApplyPreset_Ptr)(int detectorId, TiRayVariant argv[], int argc, ResultCallback fn);
  21. TiRayError(*GenerateTemplate_Ptr)(TemplateType type, TiRayVariant images[], int count, void* templateBuffer, int bufferSize);
  22. static int g_load_error = 0;
  23. static void LoadOneFunc(void* hInstLib, void** pFunction, const char* funcName)
  24. {
  25. *pFunction = dlsym(hInstLib, funcName);
  26. const char* dlsym_error = dlerror();
  27. if (dlsym_error != NULL) {
  28. printf("Failed to load %s. Error = %s", funcName, dlsym_error);
  29. g_load_error = 1;
  30. }
  31. }
  32. void OnEvent(TiRayEvent eventType, TiRayVariant argv[], int argc) {
  33. if (argc > 0) {
  34. auto arg = new std::vector<TiRayVariant>(argc);
  35. for (int i = 0; i < argc; i++) {
  36. if (argv[i].Type == TiRayVariant::TiRayBuffer) {
  37. arg->at(i).Type = TiRayVariant::TiRayBuffer;
  38. arg->at(i).DataLen = argv[i].DataLen;
  39. arg->at(i).DataValue = new char[argv[i].DataLen];
  40. memcpy(arg->at(i).DataValue, argv[i].DataValue, argv[i].DataLen);
  41. }
  42. else {
  43. memcpy(&arg->at(i), &argv[i], sizeof(TiRayVariant));
  44. }
  45. }
  46. }
  47. }
  48. #define LOAD_ONE_FUNC(handle, funcName) LoadOneFunc(handle, (void**)&(funcName##_Ptr), #funcName)
  49. /****************************************/
  50. Detector_TiRayDR::Detector_TiRayDR()
  51. :m_nPanelCount{},
  52. m_nCurrentPanelID{0},
  53. m_nImageWidth{},
  54. m_nImageHeight{},
  55. m_nWidthOffset{},
  56. m_nHeightOffset{},
  57. m_nRawImgWidth{},
  58. m_nRawImgHeight{},
  59. m_nCalibrationRounds{},
  60. m_nCalibCurrentCalibrationRound{},
  61. m_nCalibCurrentExposureIndex{},
  62. m_nExposureNumCurrentRound{},
  63. m_hTiRayDRModule{},
  64. m_hReconnectThread{},
  65. m_hFPDScanThread{},
  66. m_hRadAcquisitionThread{},
  67. m_hStatusMonitorThread{},
  68. m_hAcquisitionCheckThread{0},
  69. m_bAcquisitionCheckThreadRunning{false},
  70. m_pRawImgBuffer{},
  71. m_pImgBuffer{},
  72. m_pZSKKCalib{},
  73. m_strDetectorType{},
  74. m_strSerialNum{},
  75. m_strCurrentSessionTimestamp{},
  76. m_nSessionFrameCounter{0},
  77. m_bIsAcquiring{false},
  78. m_bAcquisitionCompleted{false},
  79. m_bWaitingForNextExposure{false},
  80. m_nImageNum{},
  81. m_nDetectorID{},
  82. m_nNotifyStatusTimePeriod{},
  83. m_pStPanelStatus{},
  84. m_nReconnectTimePeriod(5000),
  85. m_nAppStatus(APP_STATUS::APP_STATUS_IDLE),
  86. m_eCaliType(CCOS_CALIBRATION_TYPE_NONE),
  87. m_nSyncMode(SYNC_SOFTWARE),
  88. m_nCalibrationMode(CCOS_CALIBRATION_MODE_ZSKK),
  89. m_bSaveRaw(true),
  90. m_bConnected(false),
  91. m_bAEDReady(false),
  92. m_bAEDWorkFlag(false),
  93. m_bExitRadAcqStatus(false),
  94. m_bMonitorFlag(false),
  95. m_bIsMultiFrame(false),
  96. m_bIpInitialized(false),
  97. m_bFirstConnect(true),
  98. m_nXWindow(0),
  99. m_bCustomXWindow(false)
  100. {
  101. m_pDPC2PanelID = new map<FPDDeviceTiRay*, int>();
  102. m_pPanelID2DPC = new map<int, FPDDeviceTiRay*>();
  103. m_hExitRadAcqStatus = LinuxEvent::CreateEvent(LinuxEvent::AUTO_RESET, FALSE);
  104. m_hInitEvent = LinuxEvent::CreateEvent(LinuxEvent::AUTO_RESET, FALSE);
  105. m_hExitEvent = LinuxEvent::CreateEvent(LinuxEvent::AUTO_RESET, FALSE);
  106. m_hReConnectEvent = LinuxEvent::CreateEvent(LinuxEvent::AUTO_RESET, FALSE);
  107. m_hRadEvent = LinuxEvent::CreateEvent(LinuxEvent::AUTO_RESET, FALSE);
  108. m_hArrayEvent.push_back(m_hInitEvent);
  109. m_hArrayEvent.push_back(m_hExitEvent);
  110. m_hArrayEvent.push_back(m_hReConnectEvent);
  111. m_hArrayEvent.push_back(m_hRadEvent);
  112. m_hToggleEvent = LinuxEvent::CreateEvent(LinuxEvent::AUTO_RESET, FALSE);
  113. }
  114. Detector_TiRayDR::~Detector_TiRayDR()
  115. {
  116. CloseStatusMonitor();
  117. CloseDetectorScan();
  118. if (m_hReconnectThread != 0) {
  119. if (m_bReconnectThreadRunning) {
  120. struct timespec ts;
  121. clock_gettime(CLOCK_REALTIME, &ts);
  122. ts.tv_sec += 2; // 设置2秒超时
  123. // 等待线程结束
  124. pthread_timedjoin_np(m_hReconnectThread, nullptr, &ts);
  125. }
  126. // 如果线程仍在运行,强制取消
  127. if (m_bReconnectThreadRunning) {
  128. pthread_cancel(m_hReconnectThread);
  129. }
  130. m_hReconnectThread = 0;
  131. }
  132. if (m_pRawImgBuffer)
  133. {
  134. delete[] m_pRawImgBuffer;
  135. m_pRawImgBuffer = nullptr;
  136. }
  137. if (m_pImgBuffer)
  138. {
  139. delete[] m_pImgBuffer;
  140. m_pImgBuffer = nullptr;
  141. }
  142. if (m_pZSKKCalib)
  143. {
  144. delete m_pZSKKCalib;
  145. m_pZSKKCalib = nullptr;
  146. }
  147. }
  148. bool Detector_TiRayDR::ScanDetector(string& strDetectorInfo)
  149. {
  150. ResDataObject result;
  151. std::vector<scan_result> scan_results;
  152. // 扫描探测器并收集所有结果
  153. scan([&scan_results](scan_result&& res) {
  154. scan_results.emplace_back(std::move(res));
  155. });
  156. if (scan_results.empty()) {
  157. std::cerr << "[Detector_TiRayDR::ScanDetector] No detectors were found!" << std::endl;
  158. return false;
  159. }
  160. std::cout << "[Detector_TiRayDR::ScanDetector] Scanned " << scan_results.size() << " detector(s):" << std::endl;
  161. for (size_t i = 0; i < scan_results.size(); ++i) {
  162. const auto& res = scan_results[i];
  163. ResDataObject detectorData;
  164. detectorData.add("SerialNumber", res.sn.c_str());
  165. detectorData.add("Model", res.model.c_str());
  166. detectorData.add("TupperIP", res.upper_ip.c_str());
  167. detectorData.add("DetectorIP", res.detector_ip.c_str());
  168. std::string key = "DetectorData_" + std::to_string(i);
  169. result.add(key.c_str(), detectorData);
  170. // 输出当前探测器信息
  171. std::cout << "[Detector_TiRayDR::ScanDetector] Detector " << (i + 1) << ":"
  172. << " Serial number:" << res.sn
  173. << ", Model:" << res.model
  174. << ", tupper IP:" << res.upper_ip
  175. << ", detector IP:" << res.detector_ip << std::endl;
  176. }
  177. try {
  178. strDetectorInfo = result.encode();
  179. }
  180. catch (const std::exception& e) {
  181. std::cerr << "[Detector_TiRayDR::ScanDetector] Encode failed: " << e.what() << std::endl;
  182. return false;
  183. }
  184. return true;
  185. }
  186. bool Detector_TiRayDR::DriverEntry(FPDDeviceTiRay* pDrvDPC, ResDataObject& Configuration)
  187. {
  188. //FINFO("--TiRayDR Func-- DriverEntry Start");
  189. map<FPDDeviceTiRay*, int>::iterator DPCsIter = m_pDPC2PanelID->find(pDrvDPC);
  190. if (DPCsIter != m_pDPC2PanelID->end())
  191. {
  192. //FERROR("This DPC already exist");
  193. return false;
  194. }
  195. CPanelStatus* p = new CPanelStatus();
  196. m_pStPanelStatus[m_nPanelCount] = p;
  197. m_pDPC2PanelID->insert(pair<FPDDeviceTiRay*, int>(pDrvDPC, m_nPanelCount));
  198. m_pPanelID2DPC->insert(pair<int, FPDDeviceTiRay*>(m_nPanelCount, pDrvDPC));
  199. m_nPanelCount++;
  200. m_ModeConfig = Configuration; //记录配置 --目前只有一个平板,多板时应该分别存储
  201. //FINFO("Config: {$}", m_ModeConfig.encode());
  202. try
  203. {
  204. m_nCalibrationMode = (CCOS_CALIBRATION_MODE)(int)m_ModeConfig["CalibMode"];
  205. }
  206. catch (ResDataObjectExption& e)
  207. {
  208. //FERROR("Read configuration failed, Error code: {$}", e.what());
  209. }
  210. //FINFO("TiRayDR DriverEntry Over");
  211. return true;
  212. }
  213. bool Detector_TiRayDR::Connect(FPDDeviceTiRay* pDrvDPC, const char* szWorkPath)
  214. {
  215. FINFO("--TiRayDR Func-- Connect Start");
  216. if ((*m_pDPC2PanelID)[pDrvDPC] != m_nCurrentPanelID)
  217. {
  218. FINFO("Not current DPC, return true");
  219. return true;
  220. }
  221. if (!m_pZSKKCalib)
  222. {
  223. m_pZSKKCalib = new CZSKKCalibrationCtrl();
  224. }
  225. m_strWorkPath = szWorkPath;
  226. if (m_hFPDScanThread == 0)
  227. {
  228. pthread_t threadId;
  229. int result = pthread_create(&threadId, NULL, onFPDScanThread, this);
  230. if (result == 0) {
  231. m_hFPDScanThread = threadId; // 存储线程ID
  232. }
  233. else {
  234. FERROR("Thread creation failed: %d", result);
  235. return false;
  236. }
  237. }
  238. if (m_hInitEvent) {
  239. m_hInitEvent->SetEvent();
  240. }
  241. FINFO("TiRayDR Connect Over");
  242. return true;
  243. }
  244. bool Detector_TiRayDR::Disconnect()
  245. {
  246. FINFO("--TiRayDR Func-- Disconnect Begin");
  247. m_hExitEvent->SetEvent(); //关闭Scan线程
  248. bool result = m_hToggleEvent->Wait(65000);
  249. if (result)
  250. {
  251. FINFO("Leave scan thread over");
  252. }
  253. else
  254. {
  255. FERROR("Till time detectorData");
  256. }
  257. FINFO("Call API Stop");
  258. Stop();
  259. FINFO("TiRayDR Disconnect Over");
  260. return true;
  261. }
  262. void Detector_TiRayDR::EnterExamMode(int nExamMode)
  263. {
  264. switch (nExamMode)
  265. {
  266. case APP_STATUS_WORK_BEGIN:
  267. FINFO("Enter into Exam Windows");
  268. m_nAppStatus = APP_STATUS_WORK_BEGIN;
  269. break;
  270. case APP_STATUS_WORK_END:
  271. FINFO("Quit Exam Windows");
  272. m_nAppStatus = APP_STATUS_WORK_END;
  273. break;
  274. case APP_STATUS_DETSHARE_BEGIN:
  275. FINFO("Enter into Detector Share Windows");
  276. m_nAppStatus = APP_STATUS_DETSHARE_BEGIN;
  277. break;
  278. case APP_STATUS_DETSHAR_END:
  279. FINFO("Quit Detector Share Windows");
  280. m_nAppStatus = APP_STATUS_DETSHAR_END;
  281. break;
  282. case APP_STATUS_CAL_BEGIN:
  283. FINFO("Enter into Calibration Windows");
  284. m_nAppStatus = APP_STATUS_CAL_BEGIN;
  285. break;
  286. case APP_STATUS_CAL_END:
  287. FINFO("Quit Calibration Windows");
  288. m_nAppStatus = APP_STATUS_CAL_END;
  289. break;
  290. case APP_STATUS_WORK_IN_SENSITIVITY:
  291. FINFO("Enter into sensitivity test interface");
  292. m_nAppStatus = APP_STATUS_WORK_IN_SENSITIVITY;
  293. break;
  294. default:
  295. break;
  296. }
  297. }
  298. bool Detector_TiRayDR::SetExposureTimes(int nTimes)
  299. {
  300. FINFO("--TiRayDR Func-- SetExposureTimes Start");
  301. FINFO("SetExposureTimes: {$}", nTimes);
  302. // 参数验证
  303. if (nTimes <= 0)
  304. {
  305. FERROR("Invalid exposure times: {$}, must be greater than 0", nTimes);
  306. return false;
  307. }
  308. // 保存曝光时间参数
  309. m_nXWindow = nTimes;
  310. m_bCustomXWindow = true; // 标记为用户自定义设置
  311. FINFO("Custom exposure time set to: {$}", m_nXWindow);
  312. // 如果探测器已连接,立即写入硬件
  313. if (m_pStPanelStatus[m_nCurrentPanelID]->bConnectState)
  314. {
  315. auto err = write_attribute(Attr_PhotoInterval, m_nXWindow);
  316. if (err != Err_Success)
  317. {
  318. FERROR("Failed to write Attr_PhotoInterval to hardware, error code: {$}", err);
  319. FWARN("Value saved, will be applied when SetAcqMode is called");
  320. }
  321. else
  322. {
  323. FINFO("Attr_PhotoInterval written to hardware successfully: {$}", m_nXWindow);
  324. }
  325. }
  326. else
  327. {
  328. FINFO("Detector not connected yet, exposure time will be applied when SetAcqMode is called");
  329. }
  330. return true;
  331. }
  332. /***
  333. ** 加载指定模式的配置参数
  334. ** modeKey: 模式键名 (如 "RAD", "PF", "DDR", "CF")
  335. ** outXWindow: 输出的XWindow值
  336. ** 返回: 成功返回true,失败返回false
  337. ***/
  338. bool Detector_TiRayDR::LoadModeConfig(const char* modeKey, int& outXWindow)
  339. {
  340. FINFO("Loading config for mode: {$}", modeKey);
  341. // 检查配置是否存在
  342. if (m_ModeConfig["ModeTable"].GetFirstOf(modeKey) == -1)
  343. {
  344. FERROR("ModeTable does not have '{$}' config", modeKey);
  345. return false;
  346. }
  347. try
  348. {
  349. // 从配置读取 XWindow
  350. int configXWindow = (int)m_ModeConfig["ModeTable"][modeKey]["XWindow"];
  351. // 判断是否使用用户自定义值
  352. if (m_bCustomXWindow)
  353. {
  354. outXWindow = m_nXWindow;
  355. FINFO("{$} mode: Using custom XWindow: {$} (config value: {$})",
  356. modeKey, outXWindow, configXWindow);
  357. }
  358. else
  359. {
  360. outXWindow = configXWindow;
  361. m_nXWindow = outXWindow; // 更新成员变量
  362. FINFO("{$} mode: Using XWindow from config: {$}", modeKey, outXWindow);
  363. }
  364. // 读取其他参数并更新
  365. m_nImageWidth = (int)m_ModeConfig["ModeTable"][modeKey]["ImageWidth"];
  366. m_nImageHeight = (int)m_ModeConfig["ModeTable"][modeKey]["ImageHeight"];
  367. m_nWidthOffset = (int)m_ModeConfig["ModeTable"][modeKey]["WidthOffset"];
  368. m_nHeightOffset = (int)m_ModeConfig["ModeTable"][modeKey]["HeightOffset"];
  369. FINFO("{$} mode config loaded - ImageSize: {$}x{$}, Offset: ({$},{$})",
  370. modeKey, m_nImageWidth, m_nImageHeight, m_nWidthOffset, m_nHeightOffset);
  371. // 重新分配图像缓冲区
  372. if (m_pImgBuffer != nullptr)
  373. {
  374. delete[] m_pImgBuffer;
  375. m_pImgBuffer = nullptr;
  376. }
  377. m_pImgBuffer = new WORD[(size_t)m_nImageWidth * (size_t)m_nImageHeight];
  378. FINFO("{$} mode: Reallocated image buffer for {$}x{$}",
  379. modeKey, m_nImageWidth, m_nImageHeight);
  380. return true;
  381. }
  382. catch (ResDataObjectExption& e)
  383. {
  384. FERROR("Failed to read {$} mode config: {$}", modeKey, e.what());
  385. return false;
  386. }
  387. }
  388. /***
  389. ** 根据采集模式申请图像buffer
  390. ***/
  391. bool Detector_TiRayDR::SetAcqMode(int nMode)
  392. {
  393. FINFO("--TiRayDR Func-- SetAcqMode Start");
  394. FINFO("SetAcqMode mode: {$}", nMode);
  395. if (!m_pStPanelStatus[m_nCurrentPanelID]->bConnectState)
  396. {
  397. FERROR("Detector not connected, return");
  398. return false;
  399. }
  400. m_bExitRadAcqStatus = false;
  401. // 从配置中读取图像参数
  402. try
  403. {
  404. m_nImageWidth = (int)m_ModeConfig["ModeTable"][0]["ImageWidth"];
  405. m_nImageHeight = (int)m_ModeConfig["ModeTable"][0]["ImageHeight"];
  406. m_nWidthOffset = (int)m_ModeConfig["ModeTable"][0]["WidthOffset"];
  407. m_nHeightOffset = (int)m_ModeConfig["ModeTable"][0]["HeightOffset"];
  408. FINFO("Image config - Width: {$}, Height: {$}, WidthOffset: {$}, HeightOffset: {$}",
  409. m_nImageWidth, m_nImageHeight, m_nWidthOffset, m_nHeightOffset);
  410. m_bSaveRaw = (int)m_ModeConfig["ModeTable"][0]["IsSaveRaw"];
  411. FINFO("SaveRaw: {$}", m_bSaveRaw);
  412. // 重新分配图像缓冲区
  413. if (m_pImgBuffer != nullptr)
  414. {
  415. delete[] m_pImgBuffer;
  416. m_pImgBuffer = nullptr;
  417. }
  418. m_pImgBuffer = new WORD[(size_t)m_nImageWidth * (size_t)m_nImageHeight];
  419. }
  420. catch (ResDataObjectExption& e)
  421. {
  422. FERROR("Failed to get config: {$}", e.what());
  423. return false;
  424. }
  425. // 根据采集模式设置工作模式
  426. int workMode;
  427. const char* modeName;
  428. // 设置拍摄参数
  429. int nXWindow = (int)m_ModeConfig["ModeTable"][0]["XWindow"];
  430. if (nMode == AcqMode::RAD)
  431. {
  432. workMode = WorkMode_FreeSync;
  433. m_bIsMultiFrame = false; // 单帧点片
  434. modeName = "RAD";
  435. }
  436. else if (nMode == AcqMode::DDR)
  437. {
  438. workMode = WorkMode_DDR;
  439. m_bIsMultiFrame = true; // 多帧图
  440. modeName = "DDR";
  441. // 从配置加载DDR模式参数
  442. if (!LoadModeConfig("DDR", nXWindow))
  443. {
  444. FERROR("Failed to load DDR mode config");
  445. return false;
  446. }
  447. }
  448. else if (nMode == AcqMode::PF)
  449. {
  450. workMode = WorkMode_SyncIn; // 硬件同步输入
  451. m_bIsMultiFrame = true; // 多帧模式
  452. modeName = "PF";
  453. // 从配置加载PF模式参数
  454. if (!LoadModeConfig("PF", nXWindow))
  455. {
  456. FERROR("Failed to load PF mode config");
  457. return false;
  458. }
  459. }
  460. else if (nMode == AcqMode::CF)
  461. {
  462. workMode = WorkMode_SyncOut;
  463. m_bIsMultiFrame = true; // 多帧图
  464. modeName = "CF";
  465. // 从配置加载CF模式参数
  466. if (!LoadModeConfig("CF", nXWindow))
  467. {
  468. FERROR("Failed to load CF mode config");
  469. return false;
  470. }
  471. // 读取并设置PhotoNumber
  472. try
  473. {
  474. int photoNumber = (int)m_ModeConfig["ModeTable"]["CF"]["PhotoNumber"];
  475. FINFO("CF mode: Using PhotoNumber from config: {$}", photoNumber);
  476. auto err = write_attribute(Attr_PhotoNumber, photoNumber);
  477. if (err != Err_Success)
  478. {
  479. FERROR("CF mode: Failed to write Attr_PhotoNumber ({$}), error code: {$}", photoNumber, err);
  480. }
  481. else
  482. {
  483. FINFO("CF mode: Attr_PhotoNumber set to {$} successfully", photoNumber);
  484. }
  485. }
  486. catch (ResDataObjectExption& e)
  487. {
  488. FERROR("Failed to read PhotoNumber from CF config: {$}", e.what());
  489. return false;
  490. }
  491. }
  492. else
  493. {
  494. FERROR("Invalid acquisition mode: {$}", nMode);
  495. return false;
  496. }
  497. FINFO("Setting work mode to {$} (WorkMode: {$})", modeName, workMode);
  498. // 设置工作模式
  499. auto err = write_attribute(Attr_WorkMode, workMode);
  500. if (err != Err_Success)
  501. {
  502. FERROR("Failed to set work mode, error code: {$}", err);
  503. return false;
  504. }
  505. FINFO("Work mode set successfully");
  506. // 设置曝光间隔到硬件
  507. FINFO("Setting Attr_PhotoInterval to: {$}", nXWindow);
  508. err = write_attribute(Attr_PhotoInterval, nXWindow);
  509. if (err != Err_Success)
  510. {
  511. FERROR("Failed to write Attr_PhotoInterval, error code: {$}", err);
  512. return false;
  513. }
  514. FINFO("Attr_PhotoInterval set successfully");
  515. StatusFeedback(EVT_STATUS_PANEL, PANEL_SLEEP);
  516. FINFO("TiRayDR SetAcqMode Over");
  517. return true;
  518. }
  519. bool Detector_TiRayDR::SetSyncMode(int nSyncMode)
  520. {
  521. FINFO("--TiRayDR Func-- SetSyncMode Start");
  522. FINFO("SetSyncMode: {$}", nSyncMode);
  523. std::cout << "--TiRayDR Func-- SetSyncMode Start" << std::endl;
  524. std::cout << "SetSyncMode: " << nSyncMode << std::endl;
  525. int nRes;
  526. TiRayVariant Param[2]{};
  527. Param[0].Type = TiRayVariant::TiRayInt;
  528. Param[0].IntValue = TiRayAttribute::Attr_WorkMode;
  529. Param[1].Type = TiRayVariant::TiRayInt;
  530. if (nSyncMode == 1)
  531. {
  532. Param[1].IntValue = WorkMode::WorkMode_Idle;
  533. m_nSyncMode = SYNC_MODE::SYNC_SOFTWARE;
  534. std::cout << "Setting SyncMode to Software Sync" << std::endl;
  535. nRes = Execute_Ptr(m_nDetectorID, Cmd_WriteAttribute, Param, 2);
  536. if ((TiRayError)nRes != TiRayError::Err_Success)
  537. {
  538. std::cout << "Error: Failed to set SyncMode to Software Sync. Reason: " << nRes << std::endl;
  539. FERROR("Set SyncMode SoftSync, Reason:{$}", nRes);
  540. return false;
  541. }
  542. else
  543. {
  544. std::cout << "Success: Software Sync mode set successfully" << std::endl;
  545. FINFO("Set SoftSync Success");
  546. }
  547. }
  548. else if (nSyncMode == 2)
  549. {
  550. m_nSyncMode = SYNC_MODE::SYNC_HARDWARE;
  551. Param[1].IntValue = WorkMode::WorkMode_SyncIn;
  552. std::cout << "Setting SyncMode to Hardware Sync" << std::endl;
  553. nRes = Execute_Ptr(m_nDetectorID, Cmd_WriteAttribute, Param, 2);
  554. if ((TiRayError)nRes != TiRayError::Err_Success)
  555. {
  556. std::cout << "Error: Failed to set SyncMode to Hardware Sync. Reason: " << nRes << std::endl;
  557. FERROR("Set SyncMode HardSync, Reason:{$}", nRes);
  558. return false;
  559. }
  560. else
  561. {
  562. std::cout << "Success: Hardware Sync mode set successfully" << std::endl;
  563. FINFO("Set HardSync Success");
  564. }
  565. }
  566. else if (nSyncMode == 3)
  567. {
  568. Param[1].IntValue = WorkMode_FreeSync;
  569. m_nSyncMode = SYNC_MODE::SYNC_AED;
  570. std::cout << "Setting SyncMode to AED Sync" << std::endl;
  571. nRes = Execute_Ptr(m_nDetectorID, Cmd_WriteAttribute, Param, 2);
  572. if ((TiRayError)nRes != TiRayError::Err_Success)
  573. {
  574. std::cout << "Error: Failed to set SyncMode to AED Sync. Reason: " << nRes << std::endl;
  575. FERROR("Set SyncMode AED, Reason:{$}", nRes);
  576. return false;
  577. }
  578. else
  579. {
  580. std::cout << "Success: AED Sync mode set successfully" << std::endl;
  581. FINFO("Set AED Success");
  582. }
  583. }
  584. m_pStPanelStatus[m_nCurrentPanelID]->eSyncMode = (SYNC_MODE)m_nSyncMode;
  585. FINFO("TiRayDR SetSyncMode Over");
  586. std::cout << "TiRayDR SetSyncMode Over" << std::endl;
  587. return true;
  588. }
  589. bool Detector_TiRayDR::PrepareAcquisition(FPDDeviceTiRay* pDrvDPC)
  590. {
  591. FINFO("--TiRayDR Func-- PrepareAcquisition Start");
  592. FINFO("PrepareAcquisition start");
  593. if ((*m_pDPC2PanelID)[pDrvDPC] != m_nCurrentPanelID)
  594. {
  595. FERROR("Not current DPC, return");
  596. return false;
  597. }
  598. //未初始化、未连接 不执行
  599. if (!m_pStPanelStatus[m_nCurrentPanelID]->bConnectState)
  600. {
  601. FERROR("Detector not connected, return");
  602. return false;
  603. }
  604. g_pDetector->StatusFeedback(EVT_STATUS_PANEL, PANEL_STANDBY);
  605. // 生成新的会话时间戳,这次拍摄的所有图片都将使用这个时间戳
  606. m_strCurrentSessionTimestamp = generateReadableTimestamp();
  607. FINFO("New session started with timestamp: {$}", m_strCurrentSessionTimestamp);
  608. m_nSessionFrameCounter = 0; // 重置帧计数器
  609. if (m_bIsMultiFrame)
  610. {
  611. // 初始化采集状态
  612. m_bIsAcquiring = true;
  613. m_bAcquisitionCompleted = false;
  614. m_bWaitingForNextExposure = false;
  615. // 启动采集完成检测线程
  616. StartAcquisitionCheckThread();
  617. }
  618. //m_hRadEvent->SetEvent();
  619. FINFO("TiRayDR PrepareAcquisition Over");
  620. return true;
  621. }
  622. bool Detector_TiRayDR::StartAcquisition(FPDDeviceTiRay* pDrvDPC)
  623. {
  624. std::cout << "--TiRayDR Func-- StartAcquisition Start" << std::endl;
  625. FINFO("--TiRayDR Func-- StartAcquisition Start");
  626. if ((*m_pDPC2PanelID)[pDrvDPC] != m_nCurrentPanelID)
  627. {
  628. std::cout << "Not current DPC, return" << std::endl;
  629. FERROR("Not current DPC, return");
  630. return false;
  631. }
  632. //未初始化、未连接 不执行
  633. if (!m_pStPanelStatus[m_nCurrentPanelID]->bConnectState)
  634. {
  635. std::cout << "Detector not connected, return" << std::endl;
  636. FERROR("Detector not connected, return");
  637. return false;
  638. }
  639. //if (m_nSyncMode == SYNC_MODE::SYNC_SOFTWARE)
  640. {
  641. //SetSyncMode(1);
  642. auto err = Execute_Ptr(m_nDetectorID, Cmd_Photo, nullptr, 0);
  643. if (err != Err_Success) {
  644. cout << "[Detector_TiRayDR::StartAcquisition] Failed to Execute_Ptr Cmd_Photo. Error code: " << err << endl;
  645. return false;
  646. }
  647. }
  648. //StatusFeedback(EVT_STATUS_PANEL, PANEL_START_ACQ);
  649. m_bAEDWorkFlag = true;
  650. //StatusFeedback(EVT_STATUS_PANEL, PANEL_XWINDOW_ON);
  651. std::cout << "TiRayDR StartAcquisition Over" << std::endl;
  652. FINFO("TiRayDR StartAcquisition Over");
  653. return true;
  654. }
  655. bool Detector_TiRayDR::StopAcquisition(FPDDeviceTiRay* pDrvDPC)
  656. {
  657. FINFO("--TiRayDR Func-- StopAcquisition Start");
  658. if ((*m_pDPC2PanelID)[pDrvDPC] != m_nCurrentPanelID)
  659. {
  660. FERROR("Not current DPC, return");
  661. return false;
  662. }
  663. if (!m_pStPanelStatus[m_nCurrentPanelID]->bConnectState)
  664. {
  665. FERROR("Detector not connected, return");
  666. return false;
  667. }
  668. FINFO("## Stop Acquisition ##");
  669. StatusFeedback(EVT_STATUS_PANEL, PANEL_STANDBY);
  670. StatusFeedback(EVT_STATUS_PANEL, PANEL_XRAY_OFF);
  671. SetTiRayDPCStatus(eDetStatus::DetStatus_Standby); //停止采集
  672. FINFO("TiRayDR StopAcquisition Over");
  673. return true;
  674. }
  675. bool Detector_TiRayDR::ActiveCalibration(FPDDeviceTiRay* pDrvDPC, CCOS_CALIBRATION_TYPE eType)
  676. {
  677. FINFO("--TiRayDR Func-- ActiveCalibration Start");
  678. if ((*m_pDPC2PanelID)[pDrvDPC] != m_nCurrentPanelID)
  679. {
  680. FERROR("Not current DPC, return");
  681. return false;
  682. }
  683. if (!m_pStPanelStatus[m_nCurrentPanelID]->bConnectState)
  684. {
  685. FERROR("bConnectState is false, Detector not connected, return");
  686. return false;
  687. }
  688. StatusFeedback(EVT_STATUS_CALIBRATIOIN, PANEL_EVENT_START);
  689. m_nAppStatus = APP_STATUS_CAL_BEGIN; //激活校正,置为校正界面
  690. m_eCaliType = eType;
  691. if (CCOS_CALIBRATION_TYPE_DARK == m_eCaliType)
  692. {
  693. FINFO("Active Dark Calibration");
  694. }
  695. if (CCOS_CALIBRATION_TYPE_XRAY == m_eCaliType)
  696. {
  697. FINFO("Active Xray Calibration");
  698. if (m_nCalibrationMode) //厂商校正ActiveCalibration
  699. {
  700. }
  701. //else //ZSKK校正
  702. //{
  703. // if (!m_pZSKKCalib)
  704. // {
  705. // FERROR("ZSKK Calibration object is undefined");
  706. // }
  707. // else
  708. // {
  709. // //加载ZSKK的校正文件
  710. // m_pZSKKCalib->m_strRawImgPath = m_strWorkPath + "/rawdata/";
  711. // m_pZSKKCalib->m_strRefFilePath = m_strWorkPath + "/references/";
  712. // m_pZSKKCalib->m_nFullImgWidth = m_nImageWidth;
  713. // m_pZSKKCalib->m_nFullImgHeight = m_nImageHeight;
  714. // m_pZSKKCalib->m_nReferenceNum = m_nCalibrationRounds;
  715. // m_pZSKKCalib->m_nSaturationValue = 50000;
  716. // //LoadZSKKGainMap 参数为false,意思是开始增益校正
  717. // m_pZSKKCalib->LoadZSKKGainMap(false, m_strDetectorType);
  718. // m_pZSKKCalib->LoadZSKKPixelMap(false, m_strDetectorType);
  719. // FINFO("Load ecom gain and pixel map, references file path: {$}", m_pZSKKCalib->m_strRefFilePath);
  720. // }
  721. //}
  722. }
  723. FINFO("TiRayDR ActiveCalibration Over");
  724. return true;
  725. }
  726. /***
  727. * 接受曝光图像
  728. ***/
  729. bool Detector_TiRayDR::AcceptCalibration()
  730. {
  731. FINFO("--TiRayDR Func-- AcceptCalibration Start");
  732. if (m_nCalibrationMode)//厂商校正AcceptCalibration
  733. {
  734. //不做处理
  735. }
  736. else //ZSKK校正
  737. {
  738. //WORD* pImageBuffer = nullptr;
  739. ////这里要注意使用的image buffer是哪个,裁剪和不裁剪是不一样的
  740. //if (m_nWidthOffset != 0 || m_nHeightOffset != 0)
  741. //{
  742. // pImageBuffer = m_pImgBuffer;
  743. //}
  744. //else
  745. //{
  746. // pImageBuffer = m_pImgBuffer;//之后再做区分,先测试用
  747. //}
  748. //if (m_nCalibCurrentExposureIndex == 1)
  749. //{
  750. // m_pZSKKCalib->AddImageToPixMap(pImageBuffer);
  751. // m_pZSKKCalib->AverageZSKKGainMap(pImageBuffer, m_nCalibCurrentCalibrationRound - 1, true);
  752. //}
  753. //else
  754. //{
  755. // m_pZSKKCalib->AverageZSKKGainMap(pImageBuffer, m_nCalibCurrentCalibrationRound - 1, false); //曝光第几轮
  756. //}
  757. }
  758. FINFO("TiRayDR AcceptCalibration Over");
  759. return true;
  760. }
  761. /***
  762. * 拒绝曝光图像
  763. ***/
  764. bool Detector_TiRayDR::RejectCalibration()
  765. {
  766. const std::string funcTag = "[Detector_TiRayDR::RejectCalibration] ";
  767. // 检查当前是否在进行增益校正
  768. if (m_eCaliType != CCOS_CALIBRATION_TYPE_XRAY)
  769. {
  770. cout << funcTag << "No active gain calibration in progress" << endl;
  771. return false;
  772. }
  773. bool rejected = false;
  774. if (m_bUseGainV2)
  775. {
  776. if (!m_currentDoseImages.empty())
  777. {
  778. m_currentDoseImages.pop_back();
  779. cout << funcTag << "Rejected last image in dose group " << m_currentDoseIndex
  780. << ". Remaining in group: " << m_currentDoseImages.size() << endl;
  781. rejected = true;
  782. }
  783. else
  784. {
  785. cout << funcTag << "No images in current dose group to reject" << endl;
  786. }
  787. }
  788. else
  789. {
  790. if (!m_gainCalibImages.empty())
  791. {
  792. m_gainCalibImages.pop_back(); // 移除最后添加的图像
  793. cout << funcTag << "Rejected last gain image. Remaining: " << m_gainCalibImages.size() << endl;
  794. rejected = true;
  795. }
  796. else
  797. {
  798. cout << funcTag << "No gain images to reject" << endl;
  799. }
  800. }
  801. return rejected;
  802. }
  803. /***
  804. * 设置校正轮数
  805. ***/
  806. bool Detector_TiRayDR::SetCalibRounds(int nCalibRounds)
  807. {
  808. FINFO("--TiRayDR Func-- SetCalibRounds Start");
  809. m_nCalibrationRounds = nCalibRounds;
  810. FINFO("Set reference number: {$}", m_nCalibrationRounds);
  811. FINFO("TiRayDR SetCalibRounds Over");
  812. return true;
  813. }
  814. bool Detector_TiRayDR::GetCalibrationStep(int nCalibCurrentCalibrationRound, int nCalibrationRounds, int nCalibCurrentExposureIndex, int nExposureNumCurrentRound)
  815. {
  816. FINFO("--TiRayDR Func-- GetCalibrationStep Start");
  817. m_nCalibCurrentCalibrationRound = nCalibCurrentCalibrationRound;
  818. m_nCalibrationRounds = nCalibrationRounds;
  819. m_nCalibCurrentExposureIndex = nCalibCurrentExposureIndex;
  820. m_nExposureNumCurrentRound = nExposureNumCurrentRound;
  821. FINFO("Calibration Step===Round: {$}/{$}, ExposureNum: {$}/{$}", nCalibCurrentCalibrationRound, nCalibrationRounds,
  822. nCalibCurrentExposureIndex, nExposureNumCurrentRound);
  823. FINFO("TiRayDR GetCalibrationStep Over");
  824. return true;
  825. }
  826. bool Detector_TiRayDR::PrepareCalibration(FPDDeviceTiRay* pDrvDPC)
  827. {
  828. const std::string funcTag = "[Detector_TiRayDR::PrepareCalibration] ";
  829. std::cout << funcTag << "--TiRayDR Function-- PrepareCalibration started" << std::endl;
  830. if ((*m_pDPC2PanelID)[pDrvDPC] != m_nCurrentPanelID)
  831. {
  832. std::cout << funcTag << "Error: Not current DPC device, returning false" << std::endl;
  833. return false;
  834. }
  835. if (!m_pStPanelStatus[m_nCurrentPanelID]->bConnectState)
  836. {
  837. std::cout << funcTag << "Error: Detector not connected (bConnectState is false), returning false" << std::endl;
  838. return false;
  839. }
  840. auto writeAttrWithLog = [this](const std::string& attrName, int value, int err) {
  841. if (err == Err_Success)
  842. {
  843. std::cout << "[Detector_TiRayDR::PrepareCalibration] Success: Wrote attribute " << attrName << " with value " << value << std::endl;
  844. }
  845. else
  846. {
  847. std::cout << "[Detector_TiRayDR::PrepareCalibration] Error: Failed to write attribute " << attrName << ", error code: " << err << std::endl;
  848. }
  849. return err;
  850. };
  851. if (CCOS_CALIBRATION_TYPE_DARK == m_eCaliType)
  852. {
  853. int ret = DarkAcquisition();
  854. std::cout << funcTag << "Info: DarkAcquisition returned " << ret << std::endl;
  855. if (!ret)
  856. {
  857. std::cout << funcTag << "Info: Sending calibration start status (EVT_STATUS_CALIBRATIOIN, PANEL_EVENT_BEGIN)" << std::endl;
  858. StatusFeedback(EVT_STATUS_CALIBRATIOIN, PANEL_EVENT_BEGIN);
  859. }
  860. }
  861. else if (CCOS_CALIBRATION_TYPE_XRAY == m_eCaliType)
  862. {
  863. std::cout << funcTag << "Info: Preparing X-ray calibration (CCOS_CALIBRATION_TYPE_XRAY)" << std::endl;
  864. int err = write_attribute(Attr_WorkMode, WorkMode_FreeSync);
  865. writeAttrWithLog("Attr_WorkMode", WorkMode_FreeSync, err);
  866. err = write_attribute(Attr_PhotoInterval, 3000);
  867. writeAttrWithLog("Attr_PhotoInterval", 3000, err);
  868. err = write_attribute(Attr_CalibrationMode, CalibrationMode_None);
  869. writeAttrWithLog("Attr_CalibrationMode", CalibrationMode_None, err);
  870. }
  871. std::cout << funcTag << "Info: TiRayDR PrepareCalibration completed" << std::endl;
  872. return true;
  873. }
  874. //软同步调用接口,其它同步模式没有动作
  875. bool Detector_TiRayDR::StartCalibration(FPDDeviceTiRay* pDrvDPC)
  876. {
  877. FINFO("--TiRayDR Func-- StartCalibration Start");
  878. if ((*m_pDPC2PanelID)[pDrvDPC] != m_nCurrentPanelID)
  879. {
  880. FERROR("Not current DPC, return");
  881. return false;
  882. }
  883. //未初始化、未连接 不执行
  884. if (!m_pStPanelStatus[m_nCurrentPanelID]->bConnectState)
  885. {
  886. FERROR("bConnectState is false, Detector not connected, return");
  887. return false;
  888. }
  889. if (CCOS_CALIBRATION_TYPE_DARK == m_eCaliType)
  890. {
  891. FINFO("StartCalibration DARK");
  892. StatusFeedback(EVT_STATUS_CALIBRATIOIN, PANEL_EVENT_END_OK);
  893. m_pStPanelStatus[m_nCurrentPanelID]->eFPDStatus = eDetStatus::DetStatus_Offset;
  894. }
  895. else if (CCOS_CALIBRATION_TYPE_XRAY == m_eCaliType)
  896. {
  897. FINFO("StartCalibration XRAY");
  898. bool ret = StartAcquisition(pDrvDPC);
  899. if (!ret)
  900. {
  901. FERROR("StartCalibration Over");
  902. return false;
  903. }
  904. m_pStPanelStatus[m_nCurrentPanelID]->eFPDStatus = eDetStatus::DetStatus_XrayCalibration;
  905. }
  906. FINFO("TiRayDR StartCalibration Over");
  907. return true;
  908. }
  909. /***
  910. ** 说明:终止校正
  911. ***/
  912. RET_STATUS Detector_TiRayDR::AbortCalibration(FPDDeviceTiRay* pDrvDPC)
  913. {
  914. const std::string funcTag = "[Detector_TiRayDR::AbortCalibration] ";
  915. FINFO("--TiRayDR Func-- AbortCalibration Start");
  916. if (m_eCaliType == CCOS_CALIBRATION_TYPE_XRAY)
  917. {
  918. // 清除增益校正相关数据
  919. m_gainCalibImages.clear();
  920. m_currentDoseImages.clear();
  921. m_gainV2MeanImages.clear();
  922. m_currentDoseIndex = 0;
  923. cout << funcTag << "Aborted " << (!m_bUseGainV2 ? "Gain" : "GainV2")
  924. << " calibration. All related data cleared" << endl;
  925. }
  926. auto err = write_attribute(Attr_CalibrationMode, CalibrationMode_Defect);
  927. if (err == Err_Success)
  928. {
  929. std::cout << funcTag << "Success: Wrote attribute Attr_CalibrationMode with value CalibrationMode_Defect" << std::endl;
  930. }
  931. else
  932. {
  933. std::cout << funcTag << "Error: Failed to write attribute Attr_CalibrationMode, error code: " << err << std::endl;
  934. }
  935. // 恢复初始状态
  936. m_eCaliType = CCOS_CALIBRATION_TYPE_NONE;
  937. m_nAppStatus = APP_STATUS_CAL_END;
  938. FINFO("TiRayDR AbortCalibration Over");
  939. return RET_STATUS::RET_SUCCEED;
  940. }
  941. bool Detector_TiRayDR::StopCalibration(FPDDeviceTiRay* pDrvDPC)
  942. {
  943. FINFO("--TiRayDR Func-- StopCalibration Start");
  944. if ((*m_pDPC2PanelID)[pDrvDPC] != m_nCurrentPanelID)
  945. {
  946. FERROR("Not current DPC, return");
  947. return false;
  948. }
  949. if (!m_pStPanelStatus[m_nCurrentPanelID]->bConnectState)
  950. {
  951. FERROR("bConnectState is false, Detector not connected, return");
  952. return false;
  953. }
  954. m_nAppStatus = APP_STATUS_CAL_END;
  955. FINFO("TiRayDR StopCalibration Over");
  956. return true;
  957. }
  958. /***
  959. ** 说明:结束校正
  960. ** DPC处理完校正报告后调用,此处上传map、报告等文件
  961. ***/
  962. bool Detector_TiRayDR::CompleteCalibration(FPDDeviceTiRay* pDrvDPC)
  963. {
  964. FINFO("--TiRayDR Func-- CompleteCalibration Start");
  965. FINFO("Calib Type {$}", (int)m_eCaliType);
  966. const std::string funcTag = "[Detector_TiRayDR::CompleteCalibration] ";
  967. if (m_eCaliType == CCOS_CALIBRATION_TYPE_DARK)
  968. {
  969. FINFO("DARK Calib over");
  970. }
  971. else if (m_eCaliType == CCOS_CALIBRATION_TYPE_XRAY)
  972. {
  973. FINFO("XRAY Calib over");
  974. m_nAppStatus = APP_STATUS_CAL_END;
  975. }
  976. m_eCaliType = CCOS_CALIBRATION_TYPE_NONE;
  977. auto err = write_attribute(Attr_CalibrationMode, CalibrationMode_Defect);
  978. if (err == Err_Success)
  979. {
  980. std::cout << funcTag << "Success: Wrote attribute Attr_CalibrationMode with value CalibrationMode_Defect" << std::endl;
  981. }
  982. else
  983. {
  984. std::cout << funcTag << "Error: Failed to write attribute Attr_CalibrationMode, error code: " << err << std::endl;
  985. }
  986. FINFO("TiRayDR CompleteCalibration Over");
  987. return true;
  988. }
  989. bool Detector_TiRayDR::SaveCalibrationFile()
  990. {
  991. FINFO("--TiRayDR Func-- SaveCalibrationFile Start");
  992. if (m_nCalibrationMode)//厂商校正
  993. {
  994. //不做处理
  995. }
  996. else
  997. {
  998. FINFO("Save ZSKK Calibration File");
  999. m_pZSKKCalib->StoreZSKKGainMap(m_strDetectorType);
  1000. m_pZSKKCalib->StoreZSKKPixMap(m_strDetectorType);
  1001. }
  1002. //更新配置文件中校正日期和时间
  1003. GlobalTime stCurrentTime = { 0 };
  1004. GetLocalTime(&stCurrentTime);
  1005. FINFO("Current time: {$04d}/{$02d}/{$02d} {$02d}:{$02d}:{$02d}:{$03d}",
  1006. stCurrentTime.wYear, stCurrentTime.wMonth, stCurrentTime.wDay,
  1007. stCurrentTime.wHour, stCurrentTime.wMinute, stCurrentTime.wSecond, stCurrentTime.wMilliseconds);
  1008. FINFO("TiRayDR SaveCalibrationFile Over");
  1009. return true;
  1010. }
  1011. CCOS_CALIBRATION_TYPE Detector_TiRayDR::GetCalibType()
  1012. {
  1013. FINFO("--TiRayDR Func-- GetCalibType Start");
  1014. FINFO("Get Calib Type {$}", (int)m_eCaliType);
  1015. FINFO("TiRayDR GetCalibType Over");
  1016. return m_eCaliType;
  1017. }
  1018. ModelResolveResult Detector_TiRayDR::ResolveModelType(const std::string& detectorType)
  1019. {
  1020. ModelResolveResult result;
  1021. result.isValid = true;
  1022. if (detectorType == "GQ1613") {
  1023. result.model = Model_GQ1613;
  1024. cout << "[Detector_TiRayDR::OpenDetector] Try to start the detector(Model_GQ1613)..." << endl;
  1025. }
  1026. else if (detectorType == "DY1613") {
  1027. result.model = Model_DY1613;
  1028. cout << "[Detector_TiRayDR::OpenDetector] Try to start the detector(Model_DY1613)..." << endl;
  1029. }
  1030. else if (detectorType == "LT1719") {
  1031. result.model = Model_LT1719;
  1032. cout << "[Detector_TiRayDR::OpenDetector] Try to start the detector(Model_LT1719)..." << endl;
  1033. }
  1034. else if (detectorType == "DY4343") {
  1035. result.model = Model_DY4343;
  1036. cout << "[Detector_TiRayDR::OpenDetector] Try to start the detector(Model_DY4343)..." << endl;
  1037. }
  1038. else if (detectorType == "DY2530W") {
  1039. result.model = Model_DY2530W;
  1040. cout << "[Detector_TiRayDR::OpenDetector] Try to start the detector(Model_DY2530W)..." << endl;
  1041. }
  1042. else if (detectorType == "DY2121") {
  1043. result.model = Model_DY2121;
  1044. cout << "[Detector_TiRayDR::OpenDetector] Try to start the detector(Model_DY2121)..." << endl;
  1045. }
  1046. else if (detectorType == "DY4343D") {
  1047. result.model = Model_DY4343D;
  1048. cout << "[Detector_TiRayDR::OpenDetector] Try to start the detector(Model_DY4343D)..." << endl;
  1049. }
  1050. else if (detectorType == "GZ0404") {
  1051. result.model = Model_GZ0404;
  1052. cout << "[Detector_TiRayDR::OpenDetector] Try to start the detector(Model_GZ0404)..." << endl;
  1053. }
  1054. else if (detectorType == "DY3543W") {
  1055. result.model = Model_DY3543W;
  1056. cout << "[Detector_TiRayDR::OpenDetector] Try to start the detector(Model_DY3543W)..." << endl;
  1057. }
  1058. else if (detectorType == "DY4343W") {
  1059. result.model = Model_DY4343W;
  1060. cout << "[Detector_TiRayDR::OpenDetector] Try to start the detector(Model_DY4343W)..." << endl;
  1061. }
  1062. else if (detectorType == "DY3543") {
  1063. result.model = Model_DY3543;
  1064. cout << "[Detector_TiRayDR::OpenDetector] Try to start the detector(Model_DY3543)..." << endl;
  1065. }
  1066. else {
  1067. cout << "[Detector_TiRayDR::OpenDetector] Unsupported detector type: " << detectorType << endl;
  1068. // 使用第一个枚举值作为默认,通过isValid标志判断有效性
  1069. result.model = Model_GQ1613;
  1070. result.isValid = false;
  1071. }
  1072. return result;
  1073. }
  1074. bool Detector_TiRayDR::LoadDll(string strWorkPath)
  1075. {
  1076. FINFO("--TiRayDR Func-- LoadDll Start");
  1077. string strSDKPath = "";
  1078. try
  1079. {
  1080. strSDKPath = (string)m_ModeConfig["SDKPath"];
  1081. }
  1082. catch (ResDataObjectExption& e)
  1083. {
  1084. FERROR("Read configuration failed! reason: {$}", e.what());
  1085. return false;
  1086. }
  1087. string workpath = strWorkPath + strSDKPath;
  1088. string drvpath = workpath + "/TiRayLib.so";
  1089. FINFO("SDK path:{$}", drvpath);
  1090. m_hTiRayDRModule = dlopen(drvpath.c_str(), RTLD_LAZY);
  1091. if (m_hTiRayDRModule == nullptr)
  1092. {
  1093. FERROR("Load {$} failed! FERROR: {$}", drvpath.c_str(), dlerror());
  1094. return false;
  1095. }
  1096. LOAD_ONE_FUNC(m_hTiRayDRModule, GetSdkVersion);
  1097. LOAD_ONE_FUNC(m_hTiRayDRModule, Scan);
  1098. LOAD_ONE_FUNC(m_hTiRayDRModule, SetIp);
  1099. LOAD_ONE_FUNC(m_hTiRayDRModule, Startup);
  1100. LOAD_ONE_FUNC(m_hTiRayDRModule, Stop);
  1101. LOAD_ONE_FUNC(m_hTiRayDRModule, Execute);
  1102. LOAD_ONE_FUNC(m_hTiRayDRModule, ApplyPreset);
  1103. LOAD_ONE_FUNC(m_hTiRayDRModule, GenerateTemplate);
  1104. FINFO("TiRayDR LoadDll Over");
  1105. return true;
  1106. }
  1107. bool Detector_TiRayDR::ReleaseDll()
  1108. {
  1109. FINFO("--TiRayDR Func-- ReleaseDll Start");
  1110. if (m_hTiRayDRModule != nullptr)
  1111. {
  1112. int result = dlclose(m_hTiRayDRModule);
  1113. if (result != 0) {
  1114. const char* error = dlerror();
  1115. if (error) {
  1116. FERROR("Failed to unload library: %s", error);
  1117. }
  1118. else {
  1119. FERROR("Failed to unload library (unknown error)");
  1120. }
  1121. return false;
  1122. }
  1123. m_hTiRayDRModule = nullptr;
  1124. }
  1125. FINFO("TiRayDR ReleaseDll Over");
  1126. return true;
  1127. }
  1128. /***
  1129. ** 连接探测器
  1130. ***/
  1131. bool Detector_TiRayDR::OpenDetector()
  1132. {
  1133. FINFO("--TiRayDR Func-- OpenDetector Start");
  1134. m_strWiredIP = (std::string)m_ModeConfig["DetectorWiredIP"];
  1135. m_strWirelessIP = (std::string)m_ModeConfig["DetectorWirelessIP"];
  1136. m_strLocalIP = (std::string)m_ModeConfig["LocalIP"];
  1137. m_strSerialNum = (std::string)m_ModeConfig["SerialNumber"];
  1138. FINFO("Configuration parameters loaded - Wired IP:{$}, Wireless IP:{$}, Local IP:{$}",
  1139. m_strWiredIP, m_strWirelessIP, m_strLocalIP);
  1140. FINFO("WiredIP: {$}, LocalIP: {$}, WirelessIP: {$}, SerialNumber:{$}", m_strWiredIP, m_strLocalIP, m_strWirelessIP, m_strSerialNum);
  1141. //// 检查连接状态
  1142. //bool wired = CheckConnect(m_strWiredIP);
  1143. //bool wireless = CheckConnect(m_strWirelessIP);
  1144. //FINFO("[Detector_TiRayDR::OpenDetector] Connection status - Wired:{$}, wireless:{$}",
  1145. // wired ? "Connected" : "Not connected",
  1146. // wireless ? "Connected" : "Not Connected");
  1147. FINFO("[Detector_TiRayDR::OpenDetector] Start scanning the detector...");
  1148. std::vector<scan_result> scan_results;
  1149. scan([&scan_results](scan_result&& result) {
  1150. scan_results.emplace_back(std::move(result));
  1151. });
  1152. if (scan_results.empty()) {
  1153. FINFO("[Detector_TiRayDR::OpenDetector] No detectors were found!");
  1154. return false;
  1155. }
  1156. FINFO("[Detector_TiRayDR::OpenDetector] Scanned to {$} detector:", scan_results.size());
  1157. for (auto& res : scan_results) {
  1158. FINFO("[Detector_TiRayDR::OpenDetector] Serial number:{$}, Model:{$}, tupper IP:{$}, detector IP:{$}",
  1159. res.sn, res.model, res.upper_ip, res.detector_ip);
  1160. }
  1161. m_strDetectorType = (string)m_ModeConfig["DetectorType"];
  1162. FINFO("[Detector_TiRayDR::OpenDetector] Target detector type from config: {$}", m_strDetectorType);
  1163. // 选择目标探测器:优先匹配型号,否则使用第一个
  1164. scan_result target_res = scan_results[0];
  1165. bool found_matching = false;
  1166. for (auto& res : scan_results) {
  1167. if (res.model == m_strDetectorType) {
  1168. target_res = res;
  1169. found_matching = true;
  1170. break; // 找到第一个匹配的即可
  1171. }
  1172. }
  1173. if (found_matching) {
  1174. FINFO("[Detector_TiRayDR::OpenDetector] Found matching detector. Model: {$}, Serial: {$}",
  1175. target_res.model, target_res.sn);
  1176. }
  1177. else {
  1178. FINFO("[Detector_TiRayDR::OpenDetector] No matching detector model, using first detected. Model: {$}, Serial: {$}",
  1179. target_res.model, target_res.sn);
  1180. }
  1181. // 初始化启动参数
  1182. string ip = "0.0.0.0";
  1183. StartupOption option{};
  1184. memcpy(option.Ip, ip.c_str(), std::min(ip.size(), sizeof(option.Ip) - 1));
  1185. option.EnableLog = false;
  1186. // 调用解析函数处理设备类型
  1187. ModelResolveResult resolveResult = ResolveModelType(target_res.model);
  1188. if (!resolveResult.isValid) {
  1189. return false;
  1190. }
  1191. // 启动探测器
  1192. auto err = Startup_Ptr(resolveResult.model, on_event_callback, &option);
  1193. if (err != Err_Success) {
  1194. FINFO("[Detector_TiRayDR::OpenDetector] Failed to start the detector");
  1195. return false;
  1196. }
  1197. auto LoadCalibrationFile = [this](int calibrationParam)
  1198. {
  1199. TiRayError err;
  1200. switch (calibrationParam) {
  1201. case 1:
  1202. err = write_attribute(Attr_CalibrationMode, CalibrationMode_None);
  1203. break;
  1204. case 2:
  1205. err = write_attribute(Attr_CalibrationMode, CalibrationMode_Gain);
  1206. break;
  1207. case 3:
  1208. err = write_attribute(Attr_CalibrationMode, CalibrationMode_Offset);
  1209. break;
  1210. case 4:
  1211. err = write_attribute(Attr_CalibrationMode, CalibrationMode_Defect);
  1212. break;
  1213. default:
  1214. FINFO("[Detector_TiRayDR::OpenDetector] Invalid calibration parameter: {$}", calibrationParam);
  1215. return false;
  1216. }
  1217. if (err != Err_Success) {
  1218. FINFO("[Detector_TiRayDR::OpenDetector] Failed to write Attr_CalibrationMode, error code: {$}", err);
  1219. }
  1220. else {
  1221. FINFO("[Detector_TiRayDR::OpenDetector] Succeeded in writing Attr_CalibrationMode");
  1222. }
  1223. return true;
  1224. };
  1225. if (!m_bIpInitialized) {
  1226. FINFO("First connection, setting IP address...");
  1227. auto err = SetIp_Ptr(target_res.sn.c_str(), m_strLocalIP.c_str(), m_strWiredIP.c_str(), nullptr);
  1228. if (err == TiRayError::Err_Success) {
  1229. FINFO("IP setting successful");
  1230. m_bIpInitialized = true;
  1231. }
  1232. else {
  1233. FINFO("IP setting failed, error:{$}", err);
  1234. return false;
  1235. }
  1236. }
  1237. else {
  1238. FINFO("IP already initialized, skip SetIp_Ptr");
  1239. }
  1240. while (!m_bConnected)
  1241. {
  1242. usleep(10000);
  1243. }
  1244. m_pStPanelStatus[m_nCurrentPanelID]->bConnectState = true;
  1245. //FINFO("m_pStPanelStatus[m_nCurrentPanelID]->bConnectState = true");
  1246. //StatusFeedback(EVT_STATUS_PANEL, PANEL_CONNECT);
  1247. //FINFO("Connect detector({$}) success", m_nDetectorID);
  1248. if (m_strDetectorType == "DY4343" || m_strDetectorType == "DY4343D")
  1249. {
  1250. m_bUseGainV2 = true;
  1251. }
  1252. // 读取当前采集模式
  1253. std::string modeKey = (std::string)m_ModeConfig["AcqMode"];
  1254. FINFO("OpenDetector - AcqMode from config: {$}", modeKey);
  1255. // 检查 ModeTable 中是否存在该模式的配置
  1256. if (m_ModeConfig["ModeTable"].GetFirstOf(modeKey.c_str()) == -1)
  1257. {
  1258. FWARN("ModeTable does not have '{$}' config, fallback to RAD", modeKey);
  1259. modeKey = "RAD";
  1260. }
  1261. int syncMode = 3; // 默认 AED 同步模式
  1262. // 从配置读取同步模式
  1263. try
  1264. {
  1265. syncMode = (int)m_ModeConfig["ModeTable"][modeKey.c_str()]["SyncType"];
  1266. // 根据同步模式类型输出日志
  1267. const char* syncModeStr = "Unknown";
  1268. switch (syncMode)
  1269. {
  1270. case 0: syncModeStr = "SYNC_MANUAL"; break;
  1271. case 1: syncModeStr = "SYNC_SOFTWARE"; break;
  1272. case 2: syncModeStr = "SYNC_HARDWARE"; break;
  1273. case 3: syncModeStr = "SYNC_AED"; break;
  1274. case 4: syncModeStr = "SYNC_HARDWARE_DIRECT"; break;
  1275. }
  1276. FINFO("Mode: {$} - Using sync mode {$} ({$})", modeKey, syncMode, syncModeStr);
  1277. }
  1278. catch (ResDataObjectExption& e)
  1279. {
  1280. FWARN("Failed to read SyncType from config for mode '{$}': {$}, using default", modeKey, e.what());
  1281. // 兜底逻辑:根据模式设置默认同步模式
  1282. if (modeKey == "RAD")
  1283. {
  1284. syncMode = 3; // AED 同步
  1285. }
  1286. else
  1287. {
  1288. syncMode = 2; // 硬件同步(带同步盒)
  1289. }
  1290. FINFO("Using fallback sync mode: {$}", syncMode);
  1291. }
  1292. // 从对应模式配置中读取参数
  1293. try
  1294. {
  1295. m_nImageWidth = (int)m_ModeConfig["ModeTable"][modeKey.c_str()]["ImageWidth"];
  1296. m_nImageHeight = (int)m_ModeConfig["ModeTable"][modeKey.c_str()]["ImageHeight"];
  1297. m_nWidthOffset = (int)m_ModeConfig["ModeTable"][modeKey.c_str()]["WidthOffset"];
  1298. m_nHeightOffset = (int)m_ModeConfig["ModeTable"][modeKey.c_str()]["HeightOffset"];
  1299. m_nRawImgWidth = (int)m_ModeConfig["ModeTable"][modeKey.c_str()]["RawImgWidth"];
  1300. m_nRawImgHeight = (int)m_ModeConfig["ModeTable"][modeKey.c_str()]["RawImgHeight"];
  1301. m_bSaveRaw = (int)m_ModeConfig["ModeTable"][modeKey.c_str()]["IsSaveRaw"];
  1302. m_nXWindow = (int)m_ModeConfig["ModeTable"][modeKey.c_str()]["XWindow"];
  1303. FINFO("Loaded config for mode '{$}' - ImageSize: {$}x{$}, RawSize: {$}x{$}, Offset: ({$},{$}), XWindow: {$}, SaveRaw: {$}",
  1304. modeKey, m_nImageWidth, m_nImageHeight, m_nRawImgWidth, m_nRawImgHeight,
  1305. m_nWidthOffset, m_nHeightOffset, m_nXWindow, m_bSaveRaw);
  1306. }
  1307. catch (ResDataObjectExption& e)
  1308. {
  1309. FERROR("Failed to load ModeTable config for '{$}': {$}", modeKey, e.what());
  1310. return false;
  1311. }
  1312. // 分配图像缓冲区
  1313. if (m_pRawImgBuffer == nullptr)
  1314. {
  1315. m_pRawImgBuffer = new WORD[(size_t)m_nRawImgHeight * (size_t)m_nRawImgWidth];
  1316. FINFO("Allocated raw image buffer: {$}x{$}", m_nRawImgWidth, m_nRawImgHeight);
  1317. }
  1318. if (m_pImgBuffer == nullptr)
  1319. {
  1320. m_pImgBuffer = new WORD[(size_t)m_nImageWidth * (size_t)m_nImageHeight];
  1321. FINFO("Allocated processed image buffer: {$}x{$}", m_nImageWidth, m_nImageHeight);
  1322. }
  1323. // 设置同步模式
  1324. SetSyncMode(syncMode);
  1325. // 从配置读取敏感度参数
  1326. int nSensitivity = (int)m_ModeConfig["ModeTable"][modeKey.c_str()]["Sensitivity"];
  1327. FINFO("Initialize parameters - XWindow: {$}, Sensitivity: {$}", m_nXWindow, nSensitivity);
  1328. // 设置曝光间隔到硬件
  1329. err = write_attribute(Attr_PhotoInterval, m_nXWindow);
  1330. if (err != Err_Success)
  1331. {
  1332. FERROR("Failed to write Attr_PhotoInterval. Error code: {$}", err);
  1333. }
  1334. else
  1335. {
  1336. FINFO("Successfully set Attr_PhotoInterval to: {$}", m_nXWindow);
  1337. }
  1338. // 设置拍摄张数(CF 模式需要设置)
  1339. int nPhotoNumber = 1; // 默认单张
  1340. if (modeKey == "CF")
  1341. {
  1342. nPhotoNumber = (int)m_ModeConfig["ModeTable"][modeKey.c_str()]["PhotoNumber"];
  1343. FINFO("CF mode: Setting PhotoNumber to {$}", nPhotoNumber);
  1344. }
  1345. err = write_attribute(Attr_PhotoNumber, nPhotoNumber);
  1346. if (err != Err_Success)
  1347. {
  1348. FWARN("[Detector_TiRayDR::OpenDetector] Failed to write Attr_PhotoNumber. Error code: {$}", err);
  1349. }
  1350. else
  1351. {
  1352. FINFO("[Detector_TiRayDR::OpenDetector] Successfully set Attr_PhotoNumber to: {$}", nPhotoNumber);
  1353. }
  1354. LoadCalibrationFile(4);
  1355. err = write_attribute(Attr_AEDSensitivity, nSensitivity);
  1356. if (err != Err_Success)
  1357. FINFO("[Detector_TiRayDR::OpenDetector] Failed to write Attr_AEDSensitivity. Error code: {$}", err);
  1358. SetTiRayDPCStatus(eDetStatus::DetStatus_Standby);
  1359. FINFO("OpenDetector Over");
  1360. return true;
  1361. }
  1362. bool Detector_TiRayDR::CheckConnect(string strIP)
  1363. {
  1364. CMyPingip obPingIp;
  1365. if (!obPingIp.PingFunction(strIP.c_str()))
  1366. {
  1367. FINFO("ping {$} Failed", strIP);
  1368. return false;
  1369. }
  1370. return true;
  1371. }
  1372. bool Detector_TiRayDR::OpenStatusMonitor()
  1373. {
  1374. FINFO("---Open Status Monitor Thread---");
  1375. if (m_hStatusMonitorThread == 0) // 检查线程是否已创建
  1376. {
  1377. int result = pthread_create(&m_hStatusMonitorThread, NULL, TiRayStatusMonitorThread, this);
  1378. if (result != 0) {
  1379. FERROR("Failed to create status monitor thread: %d", result);
  1380. return false;
  1381. }
  1382. }
  1383. return true;
  1384. }
  1385. void* Detector_TiRayDR::TiRayStatusMonitorThread(PVOID pvoid)
  1386. {
  1387. Detector_TiRayDR* pCurrentPanelOpr = static_cast<Detector_TiRayDR*>(pvoid);
  1388. if (pCurrentPanelOpr == nullptr)
  1389. {
  1390. FERROR("TiRay Status Monitor parameter FERROR");
  1391. return nullptr;
  1392. }
  1393. FINFO("Begin StatusMonitor");
  1394. DWORD dwStatusCheckTime = 5000;
  1395. while (!pCurrentPanelOpr->m_bMonitorFlag)
  1396. {
  1397. pCurrentPanelOpr->StatusMonitor();
  1398. usleep(pCurrentPanelOpr->m_nNotifyStatusTimePeriod*1000);
  1399. }
  1400. return 0;
  1401. }
  1402. bool Detector_TiRayDR::StatusMonitor()
  1403. {
  1404. if (!m_pStPanelStatus[m_nCurrentPanelID]->bConnectState)
  1405. {
  1406. FERROR("Detector not connected, return");
  1407. ErrorFeedback(EVT_ERR_COMMUNICATE, "true");
  1408. return false;
  1409. }
  1410. //StatusType: 1:Temperature 2:Wifi 3:Battery
  1411. //auto ReadStatus = [this](int StatusType)
  1412. //{
  1413. // TiRayVariant TempParam[1]{};
  1414. // TempParam[0].Type = TiRayVariant::TiRayInt;
  1415. //};
  1416. int nTemperature = 0;
  1417. int nWifiQuality = 0;
  1418. int nBatteryLevel = 0;
  1419. TiRayVariant TemperatureParam[1]{};
  1420. TemperatureParam[0].Type = TiRayVariant::TiRayInt;
  1421. TemperatureParam[0].IntValue = 0;
  1422. Execute_Ptr(m_nDetectorID, Cmd_ReadAttribute, TemperatureParam, 1);
  1423. nTemperature = TemperatureParam[0].IntValue;
  1424. TiRayVariant WifiParam[1]{};
  1425. WifiParam[0].Type = TiRayVariant::TiRayInt;
  1426. WifiParam[0].IntValue = nWifiQuality;
  1427. Execute_Ptr(m_nDetectorID, Cmd_ReadAttribute, WifiParam, 1);
  1428. TiRayVariant BatteryParam[1]{};
  1429. BatteryParam[0].Type = TiRayVariant::TiRayInt;
  1430. BatteryParam[0].IntValue = nBatteryLevel;
  1431. Execute_Ptr(m_nDetectorID, Cmd_ReadAttribute, BatteryParam, 1);
  1432. StatusFeedback(EVT_STATUS_TEMPERATURE, 0, "", m_nCurrentPanelID, nTemperature);
  1433. StatusFeedback(EVT_STATUS_BATTERY_VALUE, nBatteryLevel, "", m_nCurrentPanelID);
  1434. StatusFeedback(EVT_STATUS_WIFI, nWifiQuality, "", m_nCurrentPanelID);
  1435. return true;
  1436. }
  1437. bool Detector_TiRayDR::CloseStatusMonitor()
  1438. {
  1439. m_bMonitorFlag = true;
  1440. m_hStatusMonitorThread = 0;
  1441. FINFO("---Close Status Monitor Thread---");
  1442. return true;
  1443. }
  1444. // 启动采集完成检测线程
  1445. bool Detector_TiRayDR::StartAcquisitionCheckThread()
  1446. {
  1447. FINFO("---Start Acquisition Check Thread---");
  1448. if (m_hAcquisitionCheckThread != 0)
  1449. {
  1450. FINFO("Acquisition check thread already running");
  1451. return true;
  1452. }
  1453. m_bAcquisitionCheckThreadRunning = true;
  1454. int result = pthread_create(&m_hAcquisitionCheckThread, nullptr, AcquisitionCheckThread, this);
  1455. if (result != 0)
  1456. {
  1457. FERROR("Failed to create acquisition check thread, error: {$}", result);
  1458. m_bAcquisitionCheckThreadRunning = false;
  1459. return false;
  1460. }
  1461. FINFO("Acquisition check thread started successfully");
  1462. return true;
  1463. }
  1464. // 采集完成检测线程函数
  1465. void* Detector_TiRayDR::AcquisitionCheckThread(PVOID pvoid)
  1466. {
  1467. Detector_TiRayDR* pDetector = (Detector_TiRayDR*)pvoid;
  1468. FINFO("Enter acquisition check thread");
  1469. const int CHECK_INTERVAL_MS = 100; // 每100ms检查一次
  1470. const int ACQUISITION_TIMEOUT_MS = 1500; // 1.5秒超时
  1471. while (pDetector->m_bAcquisitionCheckThreadRunning)
  1472. {
  1473. // 检查是否在采集中且在等待下一次曝光
  1474. if (pDetector->m_bIsAcquiring &&
  1475. pDetector->m_bWaitingForNextExposure &&
  1476. !pDetector->m_bAcquisitionCompleted)
  1477. {
  1478. auto now = std::chrono::steady_clock::now();
  1479. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  1480. now - pDetector->m_lastExposureEndTime).count();
  1481. if (elapsed > ACQUISITION_TIMEOUT_MS)
  1482. {
  1483. // 拍摄完成
  1484. pDetector->m_bAcquisitionCompleted = true;
  1485. pDetector->m_bIsAcquiring = false;
  1486. pDetector->m_bWaitingForNextExposure = false;
  1487. FINFO("=== Acquisition completed (timeout) === Total frames: {$}, Timeout: {$}ms",
  1488. pDetector->m_nSessionFrameCounter, elapsed);
  1489. // 通知上层采集完成
  1490. pDetector->StatusFeedback(EVT_STATUS_PANEL, PANEL_XRAY_OFF);
  1491. // 停止检测线程
  1492. //pDetector->m_bAcquisitionCheckThreadRunning = false;
  1493. }
  1494. }
  1495. // 休眠100ms
  1496. usleep(CHECK_INTERVAL_MS * 1000); // usleep参数为微秒
  1497. }
  1498. FINFO("Leave acquisition check thread");
  1499. return nullptr;
  1500. }
  1501. // 停止采集完成检测线程
  1502. bool Detector_TiRayDR::StopAcquisitionCheckThread()
  1503. {
  1504. FINFO("---Stop Acquisition Check Thread---");
  1505. if (m_hAcquisitionCheckThread == 0)
  1506. {
  1507. return true;
  1508. }
  1509. m_bAcquisitionCheckThreadRunning = false;
  1510. // 等待线程结束
  1511. pthread_join(m_hAcquisitionCheckThread, nullptr);
  1512. m_hAcquisitionCheckThread = 0;
  1513. FINFO("Acquisition check thread stopped");
  1514. return true;
  1515. }
  1516. bool Detector_TiRayDR::CloseDetectorScan()
  1517. {
  1518. m_hExitEvent->SetEvent();
  1519. return false;
  1520. }
  1521. bool Detector_TiRayDR::LoadCalibrationFiles(int nCalibrationMode)
  1522. {
  1523. FINFO("--TiRayDR Func-- LoadCalibrationFiles");
  1524. int nRes;
  1525. TiRayVariant Param[2]{};
  1526. Param[0].Type = TiRayVariant::TiRayInt;
  1527. Param[0].IntValue = TiRayAttribute::Attr_CalibrationMode;
  1528. Param[1].Type = TiRayVariant::TiRayInt;
  1529. if (nCalibrationMode == 1)
  1530. {
  1531. Param[1].IntValue = CalibrationMode::CalibrationMode_None;
  1532. }
  1533. else if (nCalibrationMode == 2)
  1534. {
  1535. Param[1].IntValue = CalibrationMode::CalibrationMode_Gain;
  1536. }
  1537. else if (nCalibrationMode == 3)
  1538. {
  1539. Param[1].IntValue = CalibrationMode::CalibrationMode_Offset;
  1540. }
  1541. else if (nCalibrationMode == 4)
  1542. {
  1543. Param[1].IntValue = CalibrationMode::CalibrationMode_Defect;
  1544. FINFO("All Calibration Mode");
  1545. }
  1546. nRes = Execute_Ptr(m_nDetectorID, Cmd_WriteAttribute, Param, 2);
  1547. if ((TiRayError)nRes != TiRayError::Err_Success)
  1548. {
  1549. FERROR("Use CalibrationMode Failed, Reason:{$}", nRes);
  1550. return false;
  1551. }
  1552. else
  1553. {
  1554. FINFO("Use CalibrationMode Success");
  1555. }
  1556. FINFO("LoadCalibrationFiles Over");
  1557. return true;
  1558. }
  1559. void* Detector_TiRayDR::onFPDScanThread(PVOID pvoid)
  1560. {
  1561. Detector_TiRayDR* pOpr = (Detector_TiRayDR*)pvoid;
  1562. FINFO("Enter scan thread");
  1563. bool bExit = false;
  1564. DWORD dwTimeOut = INFINITE;
  1565. while (!bExit)
  1566. {
  1567. DWORD dwRet = LinuxEvent::WaitForMultipleEvents(pOpr->m_hArrayEvent,dwTimeOut);
  1568. if (WAIT_OBJECT_0 == dwRet) //m_hInitEvent
  1569. {
  1570. pOpr->OnProcessInitFPD();
  1571. }
  1572. else if (WAIT_OBJECT_0 + 1 == dwRet) //m_hExitEvent
  1573. {
  1574. bExit = true;
  1575. }
  1576. else if (WAIT_OBJECT_0 + 2 == dwRet) //m_hReConnectEvent
  1577. {
  1578. pOpr->OnReconnectFPD();
  1579. }
  1580. else if (WAIT_OBJECT_0 + 3 == dwRet) //m_hRadEvent
  1581. {
  1582. FINFO("[Get Rad Event]");
  1583. pOpr->OpenRadAcquisition();
  1584. }
  1585. else if (WAIT_TIMEOUT == dwRet)
  1586. {
  1587. }
  1588. }
  1589. pOpr->m_hToggleEvent->SetEvent();
  1590. FINFO("Leave scan thread");
  1591. return 0;
  1592. }
  1593. void Detector_TiRayDR::OnProcessInitFPD()
  1594. {
  1595. FINFO("--TiRayDR Func-- OnProcessInitFPD");
  1596. StatusFeedback(EVT_STATUS_INIT, PANEL_EVENT_START);
  1597. if (!LoadDll(m_strWorkPath))
  1598. {
  1599. ErrorFeedback(EVT_ERR_INIT_FAILED, "true");
  1600. StatusFeedback(EVT_STATUS_INIT, PANEL_EVENT_END_ERROR); //初始化失败
  1601. return;
  1602. }
  1603. register_event_listener(OnEvent);
  1604. FINFO("Register Event Listener");
  1605. if (!OpenDetector())
  1606. {
  1607. FINFO("Open detector failed, Connect failed");
  1608. ErrorFeedback(EVT_ERR_COMMUNICATE, "true");
  1609. StatusFeedback(EVT_STATUS_INIT, PANEL_EVENT_END); //初始化时连接失败
  1610. m_hReConnectEvent->SetEvent(); //触发重连逻辑
  1611. }
  1612. else
  1613. {
  1614. m_pStPanelStatus[m_nCurrentPanelID]->bInitOver = true;
  1615. StatusFeedback(EVT_STATUS_INIT, PANEL_EVENT_END_OK);
  1616. }
  1617. FINFO("OnProcessInitFPD Over");
  1618. }
  1619. void Detector_TiRayDR::OnReconnectFPD()
  1620. {
  1621. FINFO("OnReconnectFPD start");
  1622. if (m_hReconnectThread == 0)
  1623. {
  1624. m_bReconnectThreadRunning = true;
  1625. int result = pthread_create(&m_hReconnectThread, NULL, onReconnectThread, this);
  1626. if (result != 0) {
  1627. FERROR("Failed to create reconnect thread: %d", result);
  1628. m_hReconnectThread = 0;
  1629. m_bReconnectThreadRunning = false;
  1630. }
  1631. else {
  1632. // 分离线程,使其在退出时自动释放资源
  1633. pthread_detach(m_hReconnectThread);
  1634. FINFO("Reconnect thread created and detached successfully");
  1635. }
  1636. }
  1637. FINFO("OnReconnectFPD end");
  1638. }
  1639. /***
  1640. ** 获取一帧暗场图
  1641. ***/
  1642. int Detector_TiRayDR::DarkAcquisition()
  1643. {
  1644. const std::string funcTag = "[Detector_TiRayDR::DarkAcquisition] ";
  1645. TiRayError err;
  1646. // 设置校准模式为None
  1647. err = write_attribute(Attr_CalibrationMode, CalibrationMode_None);
  1648. if (err != Err_Success) {
  1649. cout << funcTag << "Failed to write Attr_CalibrationMode. Error code: " << err << endl;
  1650. return -1;
  1651. }
  1652. // 设置拍摄间隔
  1653. err = write_attribute(Attr_PhotoInterval, 1000);
  1654. if (err != Err_Success) {
  1655. cout << funcTag << "Failed to write Attr_PhotoInterval. Error code: " << err << endl;
  1656. return -1;
  1657. }
  1658. // 设置工作模式为空闲
  1659. err = write_attribute(Attr_WorkMode, WorkMode_Idle);
  1660. if (err != Err_Success) {
  1661. cout << funcTag << "Failed to write Attr_WorkMode. Error code: " << err << endl;
  1662. return -1;
  1663. }
  1664. // 执行拍摄命令
  1665. err = Execute_Ptr(m_nDetectorID, Cmd_Photo, nullptr, 0);
  1666. if (err != Err_Success) {
  1667. cout << funcTag << "Failed to Execute_Ptr Cmd_Photo. Error code: " << err << endl;
  1668. return -1;
  1669. }
  1670. return 0; // 成功执行返回0
  1671. }
  1672. /***
  1673. ** 裁剪图像
  1674. ** pOutImg: 裁剪后图像; pInImg: 裁剪前图像; nInWidth: 裁剪前图像宽度
  1675. ***/
  1676. bool Detector_TiRayDR::GetEffectiveImage(WORD* pOutImg, WORD* pInImg, int nInWidth)
  1677. {
  1678. if (pOutImg == NULL || pInImg == NULL || nInWidth < 0)
  1679. {
  1680. FERROR("Illegal parameter, can not get effective image");
  1681. return false;
  1682. }
  1683. try
  1684. {
  1685. for (int i = 0; i < m_nImageHeight; i++)
  1686. {
  1687. memcpy(pOutImg + i * m_nImageWidth, pInImg + (i + m_nHeightOffset) * nInWidth + m_nWidthOffset, m_nImageWidth * sizeof(WORD));
  1688. }
  1689. }
  1690. catch (...)
  1691. {
  1692. FERROR("Get effective image crashed");
  1693. return false;
  1694. }
  1695. return true;
  1696. }
  1697. Detector_TiRayDR::eDetStatus Detector_TiRayDR::GetTiRayDPCStatus(int nDetectorIndex)
  1698. {
  1699. if (-1 == nDetectorIndex)
  1700. {
  1701. nDetectorIndex = m_nCurrentPanelID;
  1702. }
  1703. string strStatus = "Unknown";
  1704. switch (m_pStPanelStatus[nDetectorIndex]->eFPDStatus)
  1705. {
  1706. case eDetStatus::DetStatus_NotIni:
  1707. strStatus = "NotIni";
  1708. break;
  1709. case eDetStatus::DetStatus_NotConn:
  1710. strStatus = "NotConn";
  1711. break;
  1712. case eDetStatus::DetStatus_Sleep:
  1713. strStatus = "Sleep";
  1714. break;
  1715. case eDetStatus::DetStatus_Standby:
  1716. strStatus = "Standby";
  1717. break;
  1718. case eDetStatus::DetStatus_Work:
  1719. strStatus = "Work";
  1720. break;
  1721. case eDetStatus::DetStatus_Acquire:
  1722. strStatus = "Acquire";
  1723. break;
  1724. case eDetStatus::DetStatus_Offset:
  1725. strStatus = "Offset";
  1726. break;
  1727. case eDetStatus::DetStatus_XrayCalibration:
  1728. strStatus = "XrayCalibration";
  1729. break;
  1730. default:
  1731. break;
  1732. }
  1733. FINFO("Driver status: {$}", strStatus.c_str());
  1734. return m_pStPanelStatus[nDetectorIndex]->eFPDStatus;
  1735. }
  1736. bool Detector_TiRayDR::SetTiRayDPCStatus(eDetStatus status, int nDetectorIndex)
  1737. {
  1738. if (-1 == nDetectorIndex)
  1739. {
  1740. nDetectorIndex = m_nCurrentPanelID;
  1741. }
  1742. string strStatus = "Unknown";
  1743. bool bSetStatus = true;
  1744. switch (status)
  1745. {
  1746. case eDetStatus::DetStatus_NotIni:
  1747. strStatus = "NotIni";
  1748. break;
  1749. case eDetStatus::DetStatus_NotConn:
  1750. strStatus = "NotConn";
  1751. break;
  1752. case eDetStatus::DetStatus_Sleep:
  1753. strStatus = "Sleep";
  1754. break;
  1755. case eDetStatus::DetStatus_Standby:
  1756. strStatus = "Standby";
  1757. break;
  1758. case eDetStatus::DetStatus_Work:
  1759. strStatus = "Work";
  1760. break;
  1761. case eDetStatus::DetStatus_Acquire:
  1762. strStatus = "Acquire";
  1763. break;
  1764. case eDetStatus::DetStatus_Offset:
  1765. strStatus = "Offset";
  1766. break;
  1767. case eDetStatus::DetStatus_XrayCalibration:
  1768. strStatus = "XrayCalibration";
  1769. break;
  1770. default:
  1771. bSetStatus = false;
  1772. break;
  1773. }
  1774. if (bSetStatus)
  1775. {
  1776. m_pStPanelStatus[nDetectorIndex]->eFPDStatus = status;
  1777. FINFO("Set driver status: {$}", strStatus.c_str());
  1778. }
  1779. else
  1780. {
  1781. FERROR("{$} {$} is a illegal status", strStatus, (int)status);
  1782. }
  1783. return bSetStatus;
  1784. }
  1785. bool Detector_TiRayDR::IsConnected(string strIP)
  1786. {
  1787. FINFO("Check ping {$}", strIP);
  1788. CMyPingip obPingIp;
  1789. if (!obPingIp.PingFunction(strIP.c_str()))
  1790. {
  1791. FINFO("ping {$} Failed", strIP);
  1792. return false;
  1793. }
  1794. return true;
  1795. }
  1796. bool Detector_TiRayDR::CheckConnection()
  1797. {
  1798. return false;
  1799. }
  1800. bool Detector_TiRayDR::ReConnectFPD()
  1801. {
  1802. CloseStatusMonitor();
  1803. return true;
  1804. }
  1805. bool Detector_TiRayDR::OpenRadAcquisition()
  1806. {
  1807. FINFO("---Begin Rad Acquisition Thread---");
  1808. m_bExitRadAcqStatus = true;
  1809. if (m_hRadAcquisitionThread == 0)
  1810. {
  1811. int result = pthread_create(&m_hRadAcquisitionThread, NULL, RadAcquisitionThread, this);
  1812. if (result != 0) {
  1813. FERROR("Failed to create status monitor thread: %d", result);
  1814. return false;
  1815. }
  1816. }
  1817. return true;
  1818. }
  1819. void* Detector_TiRayDR::RadAcquisitionThread(void* pParam)
  1820. {
  1821. Detector_TiRayDR* pCurrentPanelOpr = reinterpret_cast<Detector_TiRayDR*>(pParam);
  1822. if (pCurrentPanelOpr == nullptr)
  1823. {
  1824. FERROR("Query Acq Status Thread parameter FERROR");
  1825. }
  1826. pCurrentPanelOpr->PerformRadAcquisition();
  1827. pCurrentPanelOpr->CloseRadAcquisition();
  1828. return nullptr;
  1829. }
  1830. bool Detector_TiRayDR::PerformRadAcquisition()
  1831. {
  1832. FINFO("## PerformRadAcquisition ##");
  1833. FINFO("Start Acquisition");
  1834. FINFO("DetectorID: {$}", m_nDetectorID);
  1835. //int nRes = Execute_Ptr(m_nDetectorID, Cmd_Photo, nullptr, 0);
  1836. //if ((TiRayError)nRes != TiRayError::Err_Success)
  1837. //{
  1838. // FERROR("Start Acquisition Failed");
  1839. //}
  1840. while (true)
  1841. {
  1842. usleep(100000);
  1843. if (!m_bExitRadAcqStatus)
  1844. {
  1845. break;
  1846. }
  1847. }
  1848. m_hExitRadAcqStatus->SetEvent();
  1849. FINFO("PerformRadAcquisition Over");
  1850. return true;
  1851. }
  1852. bool Detector_TiRayDR::CloseRadAcquisition()
  1853. {
  1854. m_bExitRadAcqStatus = false;
  1855. bool dwResult = false;
  1856. if (m_hExitRadAcqStatus) {
  1857. dwResult = m_hExitRadAcqStatus->Wait(1000);
  1858. }
  1859. if (dwResult)
  1860. {
  1861. FINFO("[Get ExitRadAcqStatus Event]");
  1862. }
  1863. else
  1864. {
  1865. if (m_hRadAcquisitionThread != 0) {
  1866. pthread_cancel(m_hRadAcquisitionThread);
  1867. // 等待线程实际退出
  1868. struct timespec ts;
  1869. clock_gettime(CLOCK_REALTIME, &ts);
  1870. ts.tv_sec += 1; // 等待1秒
  1871. pthread_timedjoin_np(m_hRadAcquisitionThread, nullptr, &ts);
  1872. FWARN("Kill QueryAcqStatus Thread");
  1873. }
  1874. FWARN("Kill QueryAcqStatus Thread");
  1875. }
  1876. m_hRadAcquisitionThread = 0;
  1877. FINFO("---Exit Rad Acq Status Thread---");
  1878. return true;
  1879. }
  1880. /***
  1881. ** 检测接口是否有错误,true:有错;false:没错
  1882. ***/
  1883. bool Detector_TiRayDR::TestError(TiRayError nErrorCode)
  1884. {
  1885. if (nErrorCode == TiRayError::Err_Success)
  1886. {
  1887. return true;
  1888. }
  1889. else
  1890. {
  1891. switch (nErrorCode)
  1892. {
  1893. case TiRayError::Err_SystemFailure:
  1894. {
  1895. FERROR("System Internal Error");
  1896. break;
  1897. }
  1898. case TiRayError::Err_WrongModel:
  1899. {
  1900. FERROR("The specified model is incorrect");
  1901. break;
  1902. }
  1903. case TiRayError::Err_DetectorNonExists:
  1904. {
  1905. FERROR("The specified detector with the given ID dose not exist");
  1906. break;
  1907. }
  1908. case TiRayError::Err_NetworkFailure:
  1909. {
  1910. FERROR("The network communication has failed");
  1911. break;
  1912. }
  1913. case TiRayError::Err_InvalidParam:
  1914. {
  1915. FERROR("The provided parameters are incorrect");
  1916. break;
  1917. }
  1918. case TiRayError::Err_UploadInProgress:
  1919. {
  1920. FERROR("The upload is in progress");
  1921. break;
  1922. }
  1923. default:
  1924. FERROR("Unkonwn Error");
  1925. break;
  1926. }
  1927. return false;
  1928. }
  1929. }
  1930. void Detector_TiRayDR::register_event_listener(const EventListener& fn)
  1931. {
  1932. const auto iter = std::find_if(m_listeners.begin(), m_listeners.end(), [&fn](auto& listener) {
  1933. return listener.template target<EventListenerType>() == fn.template target<EventListenerType>();
  1934. });
  1935. if (iter == m_listeners.end())
  1936. m_listeners.push_back(fn);
  1937. }
  1938. void Detector_TiRayDR::unregister_event_listener(const EventListener& fn)
  1939. {
  1940. const auto iter = std::find_if(m_listeners.begin(), m_listeners.end(), [&fn](auto& listener) {
  1941. return listener.template target<EventListenerType>() == fn.template target<EventListenerType>();
  1942. });
  1943. if (iter == m_listeners.end())
  1944. m_listeners.erase(iter);
  1945. }
  1946. bool Detector_TiRayDR::cropImage(unsigned short* srcData, int srcWidth, int srcHeight,
  1947. unsigned short* destData, int destWidth, int destHeight)
  1948. {
  1949. // 验证指针有效性
  1950. if (srcData == nullptr || destData == nullptr) {
  1951. cout << "[Detector_TiRayDR::cropImage] Error: Source or destination pointer is null" << endl;
  1952. return false;
  1953. }
  1954. // 验证尺寸合法性
  1955. if (destWidth <= 0 || destHeight <= 0 ||
  1956. srcWidth <= 0 || srcHeight <= 0 ||
  1957. destWidth > srcWidth || destHeight > srcHeight)
  1958. {
  1959. cout << "[Detector_TiRayDR::cropImage] Invalid crop size: src("
  1960. << srcWidth << "x" << srcHeight << ") dest("
  1961. << destWidth << "x" << destHeight << ")" << endl;
  1962. return false;
  1963. }
  1964. // 从配置中读取裁剪偏移参数,默认为0(居中裁剪)
  1965. int cropOffsetX = 0, cropOffsetY = 0;
  1966. try {
  1967. cropOffsetX = (int)m_ModeConfig["ModeTable"][0]["WidthOffset"];
  1968. cropOffsetY = (int)m_ModeConfig["ModeTable"][0]["HeightOffset"];
  1969. }
  1970. catch (...) {
  1971. cropOffsetX = cropOffsetY = 0;
  1972. }
  1973. // 计算裁剪起始位置
  1974. int startX = (srcWidth - destWidth) / 2 + cropOffsetX;
  1975. int startY = (srcHeight - destHeight) / 2 + cropOffsetY;
  1976. // 边界检查
  1977. if (startX < 0) startX = 0;
  1978. if (startY < 0) startY = 0;
  1979. // 确保裁剪区域不会超出源图像边界
  1980. if (startX + destWidth > srcWidth) {
  1981. destWidth = srcWidth - startX;
  1982. cout << "[Detector_TiRayDR::cropImage] Adjusted destWidth to " << destWidth
  1983. << " to avoid out-of-bounds access" << endl;
  1984. }
  1985. if (startY + destHeight > srcHeight) {
  1986. destHeight = srcHeight - startY;
  1987. cout << "[Detector_TiRayDR::cropImage] Adjusted destHeight to " << destHeight
  1988. << " to avoid out-of-bounds access" << endl;
  1989. }
  1990. // 逐行复制裁剪区域
  1991. for (int y = 0; y < destHeight; ++y)
  1992. {
  1993. // 计算源图像行起始地址
  1994. const unsigned short* srcRow = srcData + (startY + y) * srcWidth + startX;
  1995. // 计算目标图像行起始地址
  1996. unsigned short* destRow = destData + y * destWidth;
  1997. // 复制一行像素
  1998. memcpy(destRow, srcRow, destWidth * sizeof(unsigned short));
  1999. }
  2000. cout << "[Detector_TiRayDR::cropImage] Successfully cropped image from "
  2001. << srcWidth << "x" << srcHeight << " to " << destWidth << "x" << destHeight
  2002. << " with offset (" << cropOffsetX << "," << cropOffsetY << ") -> start ("
  2003. << startX << "," << startY << ")" << endl;
  2004. return true;
  2005. }
  2006. // 生成可读的时间戳字符串: YYYYMMDD_HHMMSS_mmm
  2007. static std::string generateReadableTimestamp()
  2008. {
  2009. GlobalTime currentTime = { 0 };
  2010. GetLocalTime(&currentTime);
  2011. char timestamp[64];
  2012. snprintf(timestamp, sizeof(timestamp), "%04d%02d%02d_%02d%02d%02d_%03d",
  2013. currentTime.wYear, currentTime.wMonth, currentTime.wDay,
  2014. currentTime.wHour, currentTime.wMinute, currentTime.wSecond,
  2015. currentTime.wMilliseconds);
  2016. return std::string(timestamp);
  2017. }
  2018. std::string Detector_TiRayDR::saveProcessedImage(Detector_TiRayDR& detector, unsigned short* data, size_t size, const std::string& baseTimestamp)
  2019. {
  2020. const size_t MAX_PROC_FILE_COUNT = 20;
  2021. const std::string TMPFS_DIR = "/mnt/tmpfs/";
  2022. const std::string BACKUP_DIR = "/userdata/RawData/";
  2023. const std::string ORIGINAL_DIR = detector.m_strWorkPath + "/RawData/";
  2024. const std::string FILE_PREFIX = "Proc_";
  2025. const uintmax_t MIN_REQUIRED_SPACE = size * 2; // 至少需要两倍图像大小的空间
  2026. std::string procDir;
  2027. bool useTmpfs = false;
  2028. std::string filePath;
  2029. // 辅助函数:检查目录空间是否足够
  2030. auto hasEnoughSpace = [&](const std::string& dirPath) -> bool {
  2031. try {
  2032. if (!std::filesystem::exists(dirPath))
  2033. return false;
  2034. auto fsInfo = std::filesystem::space(dirPath);
  2035. bool hasSpace = fsInfo.available >= MIN_REQUIRED_SPACE;
  2036. return hasSpace;
  2037. }
  2038. catch (const std::filesystem::filesystem_error& e) {
  2039. FINFO("Failed to check space for {$}: {$}", dirPath, e.what());
  2040. return false;
  2041. }
  2042. };
  2043. // 辅助函数:尝试在指定目录保存图像
  2044. auto tryToSaveInDir = [&](const std::string& dirPath, bool isTmpfs) -> bool {
  2045. try {
  2046. std::filesystem::create_directories(dirPath);
  2047. filePath = dirPath + FILE_PREFIX + baseTimestamp + ".raw";
  2048. std::ofstream file(filePath, std::ios::binary);
  2049. if (!file.is_open())
  2050. {
  2051. FINFO("Failed to open file: {$}", filePath);
  2052. return false;
  2053. }
  2054. file.write(reinterpret_cast<const char*>(detector.m_pImgBuffer), size);
  2055. file.close();
  2056. if (file.fail())
  2057. {
  2058. FINFO("Failed to write processed image: {$}", filePath);
  2059. // 尝试删除不完整的文件
  2060. std::filesystem::remove(filePath);
  2061. return false;
  2062. }
  2063. FINFO("Saved processed image: {$}", filePath);
  2064. // 从 baseTimestamp 中提取会话时间戳(去掉 _frameNNN 部分)
  2065. // baseTimestamp 格式: YYYYMMDD_HHMMSS_mmm_frameNNN
  2066. // sessionTimestamp 格式: YYYYMMDD_HHMMSS_mmm
  2067. std::string sessionTimestamp = baseTimestamp;
  2068. size_t framePos = baseTimestamp.find("_frame");
  2069. if (framePos != std::string::npos)
  2070. {
  2071. sessionTimestamp = baseTimestamp.substr(0, framePos);
  2072. }
  2073. // 清理旧文件,但保护当前会话的所有文件
  2074. cleanOldFiles(dirPath, FILE_PREFIX, MAX_PROC_FILE_COUNT, isTmpfs, sessionTimestamp);
  2075. return true;
  2076. }
  2077. catch (const std::filesystem::filesystem_error& e)
  2078. {
  2079. FINFO("File system error in {$}: {$}", dirPath, e.what());
  2080. return false;
  2081. }
  2082. catch (const std::exception& e)
  2083. {
  2084. FINFO("Unexpected error in {$}: {$}", dirPath, e.what());
  2085. return false;
  2086. }
  2087. };
  2088. // 策略1: 优先使用 tmpfs(如果存在且空间足够)
  2089. if (std::filesystem::exists(TMPFS_DIR) && std::filesystem::is_directory(TMPFS_DIR))
  2090. {
  2091. if (hasEnoughSpace(TMPFS_DIR))
  2092. {
  2093. if (tryToSaveInDir(TMPFS_DIR, true))
  2094. return filePath;
  2095. }
  2096. else
  2097. {
  2098. FINFO("tmpfs space insufficient, trying alternatives");
  2099. }
  2100. }
  2101. //// 策略2: 尝试原始目录
  2102. //if (hasEnoughSpace(ORIGINAL_DIR))
  2103. //{
  2104. // if (tryToSaveInDir(ORIGINAL_DIR, false))
  2105. // return filePath;
  2106. //}
  2107. //else
  2108. //{
  2109. // FINFO("Original directory space insufficient, trying backup");
  2110. //}
  2111. // 策略3: 使用备用目录 /userdata/
  2112. FINFO("Using backup directory: {$}", BACKUP_DIR);
  2113. if (tryToSaveInDir(BACKUP_DIR, false))
  2114. return filePath;
  2115. // 所有策略都失败
  2116. FINFO("ERROR: Failed to save processed image in all available directories!");
  2117. return "";
  2118. }
  2119. void Detector_TiRayDR::saveRawImage(Detector_TiRayDR& detector, unsigned short* data, size_t size, const std::string& baseTimestamp)
  2120. {
  2121. const std::string RAW_DIR = detector.m_strWorkPath + "/OriginalData/";
  2122. const std::string BACKUP_RAW_DIR = "/userdata/OriginalData/";
  2123. const std::string FILE_PREFIX = "orig_";
  2124. const size_t MAX_RAW_FILE_COUNT = 20;
  2125. const uintmax_t MIN_REQUIRED_SPACE = size * 2;
  2126. std::string filePath;
  2127. // 辅助函数:尝试保存到指定目录
  2128. auto tryToSaveRawInDir = [&](const std::string& dirPath) -> bool {
  2129. try {
  2130. std::filesystem::create_directories(dirPath);
  2131. filePath = dirPath + FILE_PREFIX + baseTimestamp + ".raw";
  2132. std::ofstream file(filePath, std::ios::binary);
  2133. if (!file.is_open())
  2134. {
  2135. FINFO("Failed to open raw image file: {$}", filePath);
  2136. return false;
  2137. }
  2138. file.write(reinterpret_cast<const char*>(data), size);
  2139. file.close();
  2140. if (file.fail())
  2141. {
  2142. FINFO("Failed to write raw image: {$}", filePath);
  2143. std::filesystem::remove(filePath);
  2144. return false;
  2145. }
  2146. FINFO("Saved raw image: {$}", filePath);
  2147. // 从 baseTimestamp 中提取会话时间戳(去掉 _frameNNN 部分)
  2148. // baseTimestamp 格式: YYYYMMDD_HHMMSS_mmm_frameNNN
  2149. // sessionTimestamp 格式: YYYYMMDD_HHMMSS_mmm
  2150. std::string sessionTimestamp = baseTimestamp;
  2151. size_t framePos = baseTimestamp.find("_frame");
  2152. if (framePos != std::string::npos)
  2153. {
  2154. sessionTimestamp = baseTimestamp.substr(0, framePos);
  2155. }
  2156. // 清理旧的原始图,但保护当前会话的所有文件
  2157. cleanOldFiles(dirPath, FILE_PREFIX, MAX_RAW_FILE_COUNT, false, sessionTimestamp);
  2158. return true;
  2159. }
  2160. catch (const std::filesystem::filesystem_error& e)
  2161. {
  2162. FINFO("File system error in {$}: {$}", dirPath, e.what());
  2163. return false;
  2164. }
  2165. };
  2166. // 尝试主目录
  2167. try {
  2168. auto fsInfo = std::filesystem::space(RAW_DIR);
  2169. if (fsInfo.available >= MIN_REQUIRED_SPACE)
  2170. {
  2171. if (tryToSaveRawInDir(RAW_DIR))
  2172. return;
  2173. }
  2174. else
  2175. {
  2176. FINFO("Primary directory space insufficient, using backup");
  2177. }
  2178. }
  2179. catch (const std::filesystem::filesystem_error& e) {
  2180. FINFO("Failed to check primary directory space: {$}", e.what());
  2181. }
  2182. // 尝试备用目录
  2183. if (!tryToSaveRawInDir(BACKUP_RAW_DIR))
  2184. {
  2185. FINFO("ERROR: Failed to save raw image in all available directories!");
  2186. }
  2187. }
  2188. std::filesystem::space_info getFileSystemInfo(const std::string& dirPath) {
  2189. try {
  2190. return std::filesystem::space(dirPath);
  2191. }
  2192. catch (const std::filesystem::filesystem_error& e) {
  2193. FINFO("Failed to get filesystem info for {$}: {$}", dirPath, e.what());
  2194. return {};
  2195. }
  2196. }
  2197. void Detector_TiRayDR::cleanOldFiles(const std::string& dirPath, const std::string& filePrefix,
  2198. size_t maxCount, bool checkSize, const std::string& currentSessionTimestamp)
  2199. {
  2200. try
  2201. {
  2202. // 检查目录是否存在
  2203. if (!std::filesystem::exists(dirPath) || !std::filesystem::is_directory(dirPath))
  2204. {
  2205. return;
  2206. }
  2207. std::vector<std::filesystem::directory_entry> targetFiles;
  2208. std::vector<std::filesystem::directory_entry> currentSessionFiles;
  2209. for (const auto& entry : std::filesystem::directory_iterator(dirPath))
  2210. {
  2211. // 只处理常规文件
  2212. if (!entry.is_regular_file())
  2213. continue;
  2214. // 检查文件扩展名是否为.raw
  2215. const std::string extension = entry.path().extension().string();
  2216. if (extension != ".raw")
  2217. continue;
  2218. // 检查文件名是否以指定前缀开头
  2219. const std::string filename = entry.path().filename().string();
  2220. if (filename.length() < filePrefix.length())
  2221. continue;
  2222. if (filename.substr(0, filePrefix.length()) == filePrefix)
  2223. {
  2224. // 如果提供了当前会话时间戳,检查文件是否属于当前会话
  2225. bool isCurrentSession = false;
  2226. if (!currentSessionTimestamp.empty())
  2227. {
  2228. // 文件名格式:Proc_YYYYMMDD_HHMMSS_mmm_frameNNN.raw
  2229. // currentSessionTimestamp 格式:YYYYMMDD_HHMMSS_mmm
  2230. // 同一次拍摄的所有图片共享相同的会话时间戳(在PrepareAcquisition时生成)
  2231. // 检查文件名是否以 prefix + currentSessionTimestamp 开头
  2232. std::string expectedPrefix = filePrefix + currentSessionTimestamp;
  2233. if (filename.length() >= expectedPrefix.length())
  2234. {
  2235. std::string fileTimestampPart = filename.substr(0, expectedPrefix.length());
  2236. isCurrentSession = (fileTimestampPart == expectedPrefix);
  2237. }
  2238. }
  2239. if (isCurrentSession)
  2240. {
  2241. // 当前会话的文件,单独保存,不参与清理
  2242. currentSessionFiles.push_back(entry);
  2243. }
  2244. else
  2245. {
  2246. targetFiles.push_back(entry);
  2247. }
  2248. }
  2249. }
  2250. if (!currentSessionFiles.empty())
  2251. {
  2252. FINFO("Protected {$} files from current session (timestamp: {$})", currentSessionFiles.size(), currentSessionTimestamp);
  2253. }
  2254. // 按文件最后修改时间排序(最旧的在前)
  2255. std::sort(targetFiles.begin(), targetFiles.end(),
  2256. [](const std::filesystem::directory_entry& a, const std::filesystem::directory_entry& b)
  2257. {
  2258. return std::filesystem::last_write_time(a) < std::filesystem::last_write_time(b);
  2259. });
  2260. // 1. 先按数量限制清理
  2261. size_t filesToDelete = 0;
  2262. if (targetFiles.size() > maxCount)
  2263. {
  2264. filesToDelete = targetFiles.size() - maxCount;
  2265. // 删除超出数量限制的最旧文件
  2266. for (size_t i = 0; i < filesToDelete; ++i)
  2267. {
  2268. const auto& fileToDelete = targetFiles[i];
  2269. if (!std::filesystem::remove(fileToDelete.path()))
  2270. {
  2271. FINFO("Failed to delete file: {$}", fileToDelete.path().string());
  2272. }
  2273. }
  2274. // 更新目标文件列表(移除已删除的文件)
  2275. targetFiles.erase(targetFiles.begin(), targetFiles.begin() + filesToDelete);
  2276. filesToDelete = 0; // 重置计数器用于大小检查
  2277. }
  2278. // 2. 如果需要,按大小限制清理(仅对tmpfs目录)
  2279. if (checkSize && !targetFiles.empty())
  2280. {
  2281. // 获取文件系统信息
  2282. auto fsInfo = getFileSystemInfo(dirPath);
  2283. if (fsInfo.capacity == 0) // 获取信息失败
  2284. {
  2285. return;
  2286. }
  2287. // 计算最大允许使用空间(预留10%作为缓冲)
  2288. const uintmax_t reservedSpace = fsInfo.capacity / 10; // 10%预留空间
  2289. const uintmax_t maxAllowedSize = fsInfo.capacity - reservedSpace;
  2290. // 计算当前文件总大小
  2291. auto calculateTotalSize = [](const std::vector<std::filesystem::directory_entry>& files) {
  2292. uintmax_t total = 0;
  2293. for (const auto& file : files) {
  2294. total += file.file_size();
  2295. }
  2296. return total;
  2297. };
  2298. uintmax_t currentTotalSize = calculateTotalSize(targetFiles);
  2299. // 如果当前总大小超过限制,继续删除最旧的文件
  2300. while (currentTotalSize > maxAllowedSize && !targetFiles.empty())
  2301. {
  2302. const auto& fileToDelete = targetFiles[0];
  2303. uintmax_t fileSize = fileToDelete.file_size();
  2304. if (std::filesystem::remove(fileToDelete.path()))
  2305. {
  2306. // 更新总量和文件列表
  2307. currentTotalSize -= fileSize;
  2308. targetFiles.erase(targetFiles.begin());
  2309. filesToDelete++;
  2310. }
  2311. else
  2312. {
  2313. FINFO("Failed to delete file: {$}", fileToDelete.path().string());
  2314. break; // 删除失败时停止处理
  2315. }
  2316. }
  2317. }
  2318. if (filesToDelete > 0)
  2319. {
  2320. FINFO("Cleanup completed. Deleted {$} files. Remaining: {$}", filesToDelete, targetFiles.size());
  2321. }
  2322. }
  2323. catch (const std::filesystem::filesystem_error& e)
  2324. {
  2325. FINFO("File system error during cleanup: {$}", e.what());
  2326. }
  2327. catch (const std::exception& e)
  2328. {
  2329. FINFO("Unexpected error during cleanup: {$}", e.what());
  2330. }
  2331. }
  2332. void Detector_TiRayDR::handleHardwareSyncImage(Detector_TiRayDR& detector, TiRayVariant argv[])
  2333. {
  2334. const size_t rawPixelCount = argv[3].DataLen / sizeof(unsigned short);
  2335. detector.m_pRawImgBuffer = reinterpret_cast<unsigned short*>(argv[3].DataValue);
  2336. const size_t rawSize = rawPixelCount * sizeof(unsigned short);
  2337. bool cropSuccess = detector.cropImage(
  2338. detector.m_pRawImgBuffer,
  2339. detector.m_nRawImgWidth, detector.m_nRawImgHeight, // 原始图像宽高
  2340. detector.m_pImgBuffer,
  2341. detector.m_nImageWidth, detector.m_nImageHeight // 目标宽高
  2342. );
  2343. if (!cropSuccess)
  2344. {
  2345. cout << "[Detector_TiRayDR::handleAedSyncImage] Failed to crop image" << endl;
  2346. return;
  2347. }
  2348. const size_t processedSize = detector.m_nImageWidth * detector.m_nImageHeight * sizeof(unsigned short);
  2349. // 使用会话时间戳 + 帧号生成文件名
  2350. detector.m_nSessionFrameCounter++;
  2351. char frameStr[32];
  2352. snprintf(frameStr, sizeof(frameStr), "_frame%03d", detector.m_nSessionFrameCounter);
  2353. const std::string baseTimestamp = detector.m_strCurrentSessionTimestamp + std::string(frameStr);
  2354. std::string processedImagePath = saveProcessedImage(
  2355. detector,
  2356. detector.m_pImgBuffer,
  2357. processedSize,
  2358. baseTimestamp
  2359. );
  2360. if (detector.m_bSaveRaw)
  2361. {
  2362. saveRawImage(
  2363. detector,
  2364. detector.m_pRawImgBuffer,
  2365. rawSize,
  2366. baseTimestamp
  2367. );
  2368. }
  2369. // 应用校准
  2370. // applyCalibration(detector);
  2371. detector.InfoFeedback(EVT_DATA_RAW_IMAGE, -1, 0, 0, processedImagePath.c_str());
  2372. if (!detector.m_bIsMultiFrame)
  2373. {
  2374. FINFO("=== Single frame acquisition completed === Frame count: {$}", detector.m_nSessionFrameCounter);
  2375. detector.StatusFeedback(EVT_STATUS_PANEL, PANEL_XRAY_OFF);
  2376. }
  2377. detector.m_bExitRadAcqStatus = false;
  2378. }
  2379. void Detector_TiRayDR::handleSoftwareSyncImage(Detector_TiRayDR& detector, TiRayVariant argv[])
  2380. {
  2381. const size_t rawPixelCount = argv[3].DataLen / sizeof(unsigned short);
  2382. detector.m_pRawImgBuffer = reinterpret_cast<unsigned short*>(argv[3].DataValue);
  2383. const size_t rawSize = rawPixelCount * sizeof(unsigned short);
  2384. bool cropSuccess = detector.cropImage(
  2385. detector.m_pRawImgBuffer,
  2386. detector.m_nRawImgWidth, detector.m_nRawImgHeight, // 原始图像宽高
  2387. detector.m_pImgBuffer,
  2388. detector.m_nImageWidth, detector.m_nImageHeight // 目标宽高
  2389. );
  2390. if (!cropSuccess)
  2391. {
  2392. cout << "[Detector_TiRayDR::handleSoftwareSyncImage] Failed to crop image" << endl;
  2393. return;
  2394. }
  2395. const size_t processedSize = detector.m_nImageWidth * detector.m_nImageHeight * sizeof(unsigned short);
  2396. // 使用会话时间戳 + 帧号生成文件名
  2397. detector.m_nSessionFrameCounter++;
  2398. char frameStr[32];
  2399. snprintf(frameStr, sizeof(frameStr), "_frame%03d", detector.m_nSessionFrameCounter);
  2400. const std::string baseTimestamp = detector.m_strCurrentSessionTimestamp + std::string(frameStr);
  2401. std::string processedImagePath = saveProcessedImage(
  2402. detector,
  2403. detector.m_pImgBuffer,
  2404. processedSize,
  2405. baseTimestamp
  2406. );
  2407. if (detector.m_bSaveRaw)
  2408. {
  2409. saveRawImage(
  2410. detector,
  2411. detector.m_pRawImgBuffer,
  2412. rawSize,
  2413. baseTimestamp
  2414. );
  2415. }
  2416. detector.InfoFeedback(EVT_DATA_RAW_IMAGE, -1, 0, 0, processedImagePath.c_str());
  2417. // 应用校准
  2418. // applyCalibration(detector);
  2419. if (!detector.m_bIsMultiFrame)
  2420. {
  2421. FINFO("=== Single frame acquisition completed === Frame count: {$}", detector.m_nSessionFrameCounter);
  2422. detector.StatusFeedback(EVT_STATUS_PANEL, PANEL_XRAY_OFF);
  2423. }
  2424. detector.m_bExitRadAcqStatus = false;
  2425. }
  2426. void Detector_TiRayDR::handleAedSyncImage(Detector_TiRayDR& detector, TiRayVariant argv[])
  2427. {
  2428. const size_t rawPixelCount = argv[3].DataLen / sizeof(unsigned short);
  2429. detector.m_pRawImgBuffer = reinterpret_cast<unsigned short*>(argv[3].DataValue);
  2430. const size_t rawSize = rawPixelCount * sizeof(unsigned short);
  2431. bool cropSuccess = detector.cropImage(
  2432. detector.m_pRawImgBuffer,
  2433. detector.m_nRawImgWidth, detector.m_nRawImgHeight, // 原始图像宽高
  2434. detector.m_pImgBuffer,
  2435. detector.m_nImageWidth, detector.m_nImageHeight // 目标宽高
  2436. );
  2437. if (!cropSuccess)
  2438. {
  2439. cout << "[Detector_TiRayDR::handleAedSyncImage] Failed to crop image" << endl;
  2440. return;
  2441. }
  2442. const size_t processedSize = detector.m_nImageWidth * detector.m_nImageHeight * sizeof(unsigned short);
  2443. // 使用会话时间戳 + 帧号生成文件名
  2444. detector.m_nSessionFrameCounter++;
  2445. char frameStr[32];
  2446. snprintf(frameStr, sizeof(frameStr), "_frame%03d", detector.m_nSessionFrameCounter);
  2447. const std::string baseTimestamp = detector.m_strCurrentSessionTimestamp + std::string(frameStr);
  2448. std::string processedImagePath = saveProcessedImage(
  2449. detector,
  2450. detector.m_pImgBuffer,
  2451. processedSize,
  2452. baseTimestamp
  2453. );
  2454. if (detector.m_bSaveRaw)
  2455. {
  2456. saveRawImage(
  2457. detector,
  2458. detector.m_pRawImgBuffer,
  2459. rawSize,
  2460. baseTimestamp
  2461. );
  2462. }
  2463. // applyCalibration(detector);
  2464. detector.InfoFeedback(EVT_DATA_RAW_IMAGE, -1, 0, 0, processedImagePath.c_str());
  2465. detector.m_bAEDWorkFlag = false;
  2466. //usleep(500000);
  2467. if (!detector.m_bIsMultiFrame)
  2468. {
  2469. FINFO("=== Single frame acquisition completed === Frame count: {$}", detector.m_nSessionFrameCounter);
  2470. detector.StatusFeedback(EVT_STATUS_PANEL, PANEL_XRAY_OFF);
  2471. }
  2472. detector.m_bExitRadAcqStatus = false;
  2473. }
  2474. void Detector_TiRayDR::handleDarkCalibration(Detector_TiRayDR& detector, TiRayVariant argv[])
  2475. {
  2476. const std::string funcTag = "[Detector_TiRayDR::handleDarkCalibration] ";
  2477. static int callCount = 0;
  2478. static std::vector<TiRayVariant> datas;
  2479. // 处理当前传入的图像数据
  2480. auto size = argv[3].DataLen;
  2481. auto data = argv[3].DataValue;
  2482. image_info image;
  2483. image.width = argv[0].IntValue;
  2484. image.height = argv[1].IntValue;
  2485. image.data.resize(size);
  2486. memcpy(image.data.data(), data, size);
  2487. // 将当前图像数据存入集合
  2488. TiRayVariant variant;
  2489. variant.Type = TiRayVariant::TiRayBuffer;
  2490. variant.DataLen = static_cast<int>(image.data.size());
  2491. variant.DataValue = image.data.data();
  2492. datas.push_back(variant);
  2493. // 调用次数递增(当前已处理的图像数量)
  2494. callCount++;
  2495. // 若未收集到6张图,调用拍摄命令准备下一张
  2496. if (callCount < 6) {
  2497. auto err = Execute_Ptr(detector.m_nDetectorID, Cmd_Photo, nullptr, 0);
  2498. if (err != Err_Success) {
  2499. cout << funcTag << "Failed to execute Cmd_Photo for next image. Error code: " << err << endl;
  2500. // 重置状态,避免异常累积
  2501. callCount = 0;
  2502. datas.clear();
  2503. return;
  2504. }
  2505. cout << funcTag << "Prepared for " << callCount + 1 << "th image" << endl;
  2506. }
  2507. // 收集到6张图,执行模板生成和上传
  2508. else {
  2509. image_info template_image;
  2510. template_image.data.resize(datas[0].DataLen);
  2511. template_image.width = image.width;
  2512. template_image.height = image.height;
  2513. // 生成模板并检查结果
  2514. auto err = GenerateTemplate_Ptr(TemplateType_Offset, datas.data(), static_cast<int>(datas.size()),
  2515. template_image.data.data(), static_cast<int>(template_image.data.size()));
  2516. if (err != Err_Success) {
  2517. cout << funcTag << "Failed to generate offset template. Error code: " << err << endl;
  2518. }
  2519. else {
  2520. cout << funcTag << "Offset template generated successfully with 6 images" << endl;
  2521. // 上传模板并检查结果
  2522. err = detector.upload(detector.offset, template_image.data.data(), static_cast<int>(template_image.data.size()));
  2523. if (err != Err_Success) {
  2524. cout << funcTag << "Failed to upload offset template. Error code: " << err << endl;
  2525. }
  2526. else {
  2527. cout << funcTag << "Offset template uploaded successfully" << endl;
  2528. }
  2529. }
  2530. // 重置静态变量,为下一次校准做准备
  2531. callCount = 0;
  2532. datas.clear();
  2533. }
  2534. }
  2535. void Detector_TiRayDR::handleGainCalibration(Detector_TiRayDR& detector, TiRayVariant argv[])
  2536. {
  2537. const std::string funcTag = "[Detector_TiRayDR::handleGainCalibration] ";
  2538. int doseCount = 5; // 剂量数量
  2539. int imagesPerDose = 6; // 每个剂量的图像数量
  2540. auto size = argv[3].DataLen;
  2541. auto data = argv[3].DataValue;
  2542. // 创建图像信息并存储
  2543. image_info image;
  2544. image.width = argv[0].IntValue;
  2545. image.height = argv[1].IntValue;
  2546. image.data.resize(size);
  2547. memcpy(image.data.data(), data, size);
  2548. // 根据模式存储图像
  2549. if (!detector.m_bUseGainV2)
  2550. {
  2551. // Gain模式:直接存储所有30张图像
  2552. detector.m_gainCalibImages.push_back(image);
  2553. cout << funcTag << "Gain mode - Collected " << detector.m_gainCalibImages.size()
  2554. << "/" << doseCount * imagesPerDose << " images" << endl;
  2555. // 收集完30张图像后生成并上传模板
  2556. if (detector.m_gainCalibImages.size() == doseCount * imagesPerDose)
  2557. {
  2558. cout << funcTag << "All 30 gain calibration images collected, generating template..." << endl;
  2559. // 准备数据并生成Gain模板
  2560. std::vector<TiRayVariant> datas;
  2561. for (auto& img : detector.m_gainCalibImages)
  2562. {
  2563. TiRayVariant variant;
  2564. variant.Type = TiRayVariant::TiRayBuffer;
  2565. variant.DataLen = static_cast<int>(img.data.size());
  2566. variant.DataValue = img.data.data();
  2567. datas.push_back(variant);
  2568. }
  2569. image_info template_image;
  2570. template_image.width = detector.m_gainCalibImages[0].width;
  2571. template_image.height = detector.m_gainCalibImages[0].height;
  2572. template_image.data.resize(datas[0].DataLen);
  2573. auto err = GenerateTemplate_Ptr(TemplateType_Gain, datas.data(), static_cast<int>(datas.size()),
  2574. template_image.data.data(), static_cast<int>(template_image.data.size()));
  2575. if (err != Err_Success)
  2576. {
  2577. cout << funcTag << "Failed to generate Gain template. Error code: " << err << endl;
  2578. }
  2579. else
  2580. {
  2581. cout << funcTag << "Gain template generated successfully" << endl;
  2582. // 上传模板
  2583. err = detector.upload(detector.gain, template_image.data.data(),
  2584. static_cast<int>(template_image.data.size()));
  2585. if (err != Err_Success)
  2586. {
  2587. cout << funcTag << "Failed to upload Gain template. Error code: " << err << endl;
  2588. }
  2589. else
  2590. {
  2591. cout << funcTag << "Gain template uploaded successfully" << endl;
  2592. }
  2593. }
  2594. // 清空存储的图像,准备下次校正
  2595. detector.m_gainCalibImages.clear();
  2596. }
  2597. }
  2598. else if (detector.m_bUseGainV2)
  2599. {
  2600. // Gainv2模式:按剂量组存储图像
  2601. detector.m_currentDoseImages.push_back(image);
  2602. cout << funcTag << "Gainv2 mode - Collected " << detector.m_currentDoseImages.size()
  2603. << "/" << imagesPerDose << " images for dose " << detector.m_currentDoseIndex + 1 << endl;
  2604. // 收集完当前剂量的6张图像后生成均值图
  2605. if (detector.m_currentDoseImages.size() == imagesPerDose)
  2606. {
  2607. cout << funcTag << "All " << imagesPerDose << " images for dose " << detector.m_currentDoseIndex + 1
  2608. << " collected, generating mean image..." << endl;
  2609. // 生成当前剂量的均值图
  2610. std::vector<TiRayVariant> datas;
  2611. for (auto& img : detector.m_currentDoseImages)
  2612. {
  2613. TiRayVariant variant;
  2614. variant.Type = TiRayVariant::TiRayBuffer;
  2615. variant.DataLen = static_cast<int>(img.data.size());
  2616. variant.DataValue = img.data.data();
  2617. datas.push_back(variant);
  2618. }
  2619. image_info mean_image;
  2620. mean_image.width = detector.m_currentDoseImages[0].width;
  2621. mean_image.height = detector.m_currentDoseImages[0].height;
  2622. mean_image.data.resize(datas[0].DataLen);
  2623. auto err = GenerateTemplate_Ptr(TemplateType_Mean, datas.data(), static_cast<int>(datas.size()),
  2624. mean_image.data.data(), static_cast<int>(mean_image.data.size()));
  2625. if (err != Err_Success)
  2626. {
  2627. cout << funcTag << "Failed to generate mean image for dose " << detector.m_currentDoseIndex + 1
  2628. << ". Error code: " << err << endl;
  2629. // 清空当前剂量数据,重新收集
  2630. detector.m_currentDoseImages.clear();
  2631. return;
  2632. }
  2633. // 保存均值图并重置当前剂量图像集合
  2634. detector.m_gainV2MeanImages.push_back(mean_image);
  2635. detector.m_currentDoseImages.clear();
  2636. detector.m_currentDoseIndex++;
  2637. cout << funcTag << "Mean image for dose " << detector.m_currentDoseIndex
  2638. << " generated successfully. Total mean images: " << detector.m_gainV2MeanImages.size() << endl;
  2639. // 收集完5个剂量的均值图后生成最终模板
  2640. if (detector.m_gainV2MeanImages.size() == doseCount)
  2641. {
  2642. cout << funcTag << "All " << doseCount << " mean images collected, generating final GainV2 template..." << endl;
  2643. // 生成最终的GainV2模板
  2644. std::vector<TiRayVariant> meanDatas;
  2645. for (auto& meanImg : detector.m_gainV2MeanImages)
  2646. {
  2647. TiRayVariant variant;
  2648. variant.Type = TiRayVariant::TiRayBuffer;
  2649. variant.DataLen = static_cast<int>(meanImg.data.size());
  2650. variant.DataValue = meanImg.data.data();
  2651. meanDatas.push_back(variant);
  2652. }
  2653. image_info final_template;
  2654. final_template.width = detector.m_gainV2MeanImages[0].width;
  2655. final_template.height = detector.m_gainV2MeanImages[0].height;
  2656. final_template.data.resize(meanDatas[0].DataLen);
  2657. auto err = GenerateTemplate_Ptr(TemplateType_GainV2, meanDatas.data(), static_cast<int>(meanDatas.size()),
  2658. final_template.data.data(), static_cast<int>(final_template.data.size()));
  2659. if (err != Err_Success)
  2660. {
  2661. cout << funcTag << "Failed to generate GainV2 template. Error code: " << err << endl;
  2662. }
  2663. else
  2664. {
  2665. cout << funcTag << "GainV2 template generated successfully" << endl;
  2666. // 上传模板
  2667. err = detector.upload(detector.gain, final_template.data.data(),
  2668. static_cast<int>(final_template.data.size()));
  2669. if (err != Err_Success)
  2670. {
  2671. cout << funcTag << "Failed to upload GainV2 template. Error code: " << err << endl;
  2672. }
  2673. else
  2674. {
  2675. cout << funcTag << "GainV2 template uploaded successfully" << endl;
  2676. }
  2677. }
  2678. // 重置所有存储和计数器,准备下次校正
  2679. detector.m_gainV2MeanImages.clear();
  2680. detector.m_currentDoseIndex = 0;
  2681. }
  2682. }
  2683. }
  2684. }
  2685. void Detector_TiRayDR::handleImageReceived(Detector_TiRayDR& detector, TiRayVariant argv[])
  2686. {
  2687. // 处理暗校准模式
  2688. if (CCOS_CALIBRATION_TYPE_DARK == detector.m_eCaliType)
  2689. {
  2690. handleDarkCalibration(detector, argv);
  2691. return;
  2692. }
  2693. else if (CCOS_CALIBRATION_TYPE_XRAY == detector.m_eCaliType)
  2694. {
  2695. handleGainCalibration(detector, argv);
  2696. return;
  2697. }
  2698. // 根据同步模式处理图像
  2699. switch (detector.m_nSyncMode)
  2700. {
  2701. case SYNC_MODE::SYNC_AED:
  2702. handleAedSyncImage(detector, argv);
  2703. break;
  2704. case SYNC_MODE::SYNC_SOFTWARE:
  2705. handleSoftwareSyncImage(detector, argv);
  2706. break;
  2707. case SYNC_MODE::SYNC_HARDWARE:
  2708. handleHardwareSyncImage(detector, argv);
  2709. break;
  2710. }
  2711. }
  2712. void Detector_TiRayDR::on_event_callback(int detectorId, TiRayEvent eventType, TiRayVariant argv[], int argc, void* reservedArg, int reservedArgLen)
  2713. {
  2714. auto& detector = *g_pDetector;
  2715. const std::string funcTag = "[Detector_TiRayDR::on_event_callback] ";
  2716. switch (eventType)
  2717. {
  2718. case TiRayEvent::Evt_DetectorConnect:
  2719. {
  2720. detector.m_nDetectorID = detectorId;
  2721. detector.m_bConnected = true;
  2722. detector.m_pStPanelStatus[detector.m_nCurrentPanelID]->bConnectState = true;
  2723. detector.StatusFeedback(EVT_STATUS_PANEL, PANEL_CONNECT);
  2724. cout << funcTag << "Evt_DetectorConnect!!!" << endl;
  2725. FINFO("Evt_DetectorConnect!!");
  2726. break;
  2727. }
  2728. case TiRayEvent::Evt_DetectorDisconnect:
  2729. {
  2730. //if (detector.m_bFirstConnect) {
  2731. // FINFO("Ignore first disconnect event after IP setting");
  2732. // detector.m_bFirstConnect = false; // 标记第一次连接已完成
  2733. // break;
  2734. //}
  2735. detector.m_nDetectorID = INT_MAX;
  2736. detector.m_bConnected = false;
  2737. detector.m_pStPanelStatus[detector.m_nCurrentPanelID]->bConnectState = false;
  2738. detector.StatusFeedback(EVT_STATUS_PANEL, PANEL_CLOSE);
  2739. detector.m_hReConnectEvent->SetEvent();
  2740. cout << funcTag << "Evt_DetectorDisconnect!!!" << endl;
  2741. FINFO("Evt_DetectorDisconnect!!");
  2742. break;
  2743. }
  2744. case TiRayEvent::Evt_WriteAttribute:
  2745. {
  2746. FINFO("WriteAttribute Success");
  2747. break;
  2748. }
  2749. case TiRayEvent::Evt_ReadAttribute:
  2750. {
  2751. FINFO("ReadAttribute Success");
  2752. //const TiRayAttribute attrib = (TiRayAttribute)argv[0].IntValue;
  2753. //if (attrib == Attr_BatteryStatus) {
  2754. // auto battery_level = argv[1].IntValue;
  2755. // auto is_recharging = argv[2].IntValue;
  2756. //}
  2757. break;
  2758. }
  2759. case TiRayEvent::Evt_ImageReceived:
  2760. {
  2761. FINFO("Evt_ImageReceived!!");
  2762. handleImageReceived(detector, argv);
  2763. break;
  2764. }
  2765. case TiRayEvent::Evt_ExposureStatus:
  2766. {
  2767. FINFO("Evt_ExposureStatus: argv {$}, argc {$}", argv[0].IntValue, argc);
  2768. if (argv[0].IntValue == 0)
  2769. {
  2770. // argv 0 = 曝光结束(图像接收完成)
  2771. detector.m_bAEDReady = true;
  2772. // 记录最后一次曝光结束时间,开始等待下一次曝光
  2773. if (detector.m_bIsAcquiring)
  2774. {
  2775. detector.m_lastExposureEndTime = std::chrono::steady_clock::now();
  2776. detector.m_bWaitingForNextExposure = true;
  2777. FINFO("Exposure ended, waiting for next exposure or timeout");
  2778. }
  2779. }
  2780. else if (argv[0].IntValue == 1)
  2781. {
  2782. // argv 1 = 曝光开始(准备接收图像)
  2783. detector.m_bAEDReady = false;
  2784. // 只在第一帧时通知状态变化
  2785. if (detector.m_nSessionFrameCounter == 0)
  2786. {
  2787. detector.StatusFeedback(EVT_STATUS_PANEL, PANEL_START_ACQ);
  2788. detector.StatusFeedback(EVT_STATUS_PANEL, PANEL_XRAY_ON);
  2789. detector.StatusFeedback(EVT_STATUS_PANEL, PANEL_XWINDOW_ON);
  2790. }
  2791. // 收到新的曝光开始,取消等待状态
  2792. if (detector.m_bIsAcquiring)
  2793. {
  2794. detector.m_bWaitingForNextExposure = false;
  2795. detector.m_bAcquisitionCompleted = false; // 有新的曝光,重置完成标志
  2796. FINFO("Exposure started, frame counter will be: {$}", detector.m_nSessionFrameCounter + 1);
  2797. }
  2798. }
  2799. break;
  2800. }
  2801. case TiRayEvent::Evt_UploadProgress:
  2802. cout << funcTag << "Upload progress: " << argv[0].IntValue << "%" << endl;
  2803. break;
  2804. case TiRayEvent::Evt_UpdateFinish:
  2805. cout << funcTag << "Update completed successfully" << endl;
  2806. detector.StatusFeedback(EVT_STATUS_CALIBRATIOIN, PANEL_EVENT_END_OK);
  2807. break;
  2808. case TiRayEvent::Evt_UploadTimeout:
  2809. // 输出上传超时警告
  2810. cout << funcTag << "Warning: Upload timed detectorData" << endl;
  2811. break;
  2812. default:
  2813. FERROR("not support current event ID:{$}", (int)eventType);
  2814. break;
  2815. }
  2816. }
  2817. void Detector_TiRayDR::ConfFeedback(int nEventID, int nDetectorID, const char* pszMsg, int nParam1, float fParam2, int nPtrParamLen, void* pParam)
  2818. {
  2819. if (-1 == nDetectorID)
  2820. {
  2821. nDetectorID = m_nCurrentPanelID;
  2822. }
  2823. ((FPDDeviceTiRay*)(*m_pPanelID2DPC)[nDetectorID])->OnFPDCallback(nDetectorID,
  2824. nEventID, EVT_LEVEL_CONFIGURATION, pszMsg, nParam1, fParam2, nPtrParamLen, pParam);
  2825. }
  2826. void Detector_TiRayDR::InfoFeedback(int nEventID, int nDetectorID, int nParam1, float fParam2, const char* pszMsg, int nPtrParamLen, void* pParam)
  2827. {
  2828. if (-1 == nDetectorID)
  2829. {
  2830. nDetectorID = m_nCurrentPanelID;
  2831. }
  2832. ((FPDDeviceTiRay*)(*m_pPanelID2DPC)[nDetectorID])->OnFPDCallback(nDetectorID,
  2833. nEventID, EVT_LEVEL_INFORMATOION, pszMsg, nParam1, fParam2, nPtrParamLen, pParam);
  2834. }
  2835. void Detector_TiRayDR::StatusFeedback(int nEventID, int nParam1, const char* pszMsg, int nDetectorID, float fParam2, int nPtrParamLen, void* pParam)
  2836. {
  2837. if (-1 == nDetectorID)
  2838. {
  2839. nDetectorID = m_nCurrentPanelID;
  2840. }
  2841. ((FPDDeviceTiRay*)(*m_pPanelID2DPC)[nDetectorID])->OnFPDCallback(nDetectorID,
  2842. nEventID, EVT_LEVEL_STATUS, pszMsg, nParam1, fParam2, nPtrParamLen, pParam);
  2843. }
  2844. void Detector_TiRayDR::DataFeedback(int nEventID, void* pParam, int nParam1, float fParam2, const char* pszMsg, int nPtrParamLen, int nDetectorID)
  2845. {
  2846. if (-1 == nDetectorID)
  2847. {
  2848. nDetectorID = m_nCurrentPanelID;
  2849. }
  2850. ((FPDDeviceTiRay*)(*m_pPanelID2DPC)[nDetectorID])->OnFPDCallback(nDetectorID,
  2851. nEventID, EVT_LEVEL_DATA, pszMsg, nParam1, fParam2, nPtrParamLen, pParam);
  2852. }
  2853. void Detector_TiRayDR::WarnFeedback(int nEventID, const char* pszMsg, int nParam1, float fParam2, int nPtrParamLen, void* pParam, int nDetectorID)
  2854. {
  2855. if (-1 == nDetectorID)
  2856. {
  2857. nDetectorID = m_nCurrentPanelID;
  2858. }
  2859. ((FPDDeviceTiRay*)(*m_pPanelID2DPC)[nDetectorID])->OnFPDCallback(nDetectorID,
  2860. nEventID, EVT_LEVEL_WARNING, pszMsg, nParam1, fParam2, nPtrParamLen, pParam);
  2861. }
  2862. void Detector_TiRayDR::ErrorFeedback(int nEventID, const char* pszMsg, int nDetectorID, int nParam1, float fParam2, int nPtrParamLen, void* pParam)
  2863. {
  2864. if (-1 == nDetectorID)
  2865. {
  2866. nDetectorID = m_nCurrentPanelID;
  2867. }
  2868. ((FPDDeviceTiRay*)(*m_pPanelID2DPC)[nDetectorID])->OnFPDCallback(nDetectorID,
  2869. nEventID, EVT_LEVEL_ERROR, pszMsg, nParam1, fParam2, nPtrParamLen, pParam);
  2870. }
  2871. bool Detector_TiRayDR::UpdateCalibMode(CCOS_CALIBRATION_MODE eCalibMode)
  2872. {
  2873. FINFO("--TiRayDR Func-- UpdateCalibMode");
  2874. FINFO("CalibMode:{$}", (int)eCalibMode);
  2875. m_nCalibrationMode = eCalibMode;
  2876. FINFO("UpdateCalibMode Over");
  2877. return true;
  2878. }
  2879. void Detector_TiRayDR::SetNotifyStatusTimePeriod(int nTime)
  2880. {
  2881. FINFO("--Func TiRay-- SetNotifyStatusTimePeriod Start");
  2882. FINFO("NotifyStatusTimePeriod:{$}", nTime);
  2883. m_nNotifyStatusTimePeriod = nTime;
  2884. FINFO("SetNotifyStatusTimePeriod Over");
  2885. }
  2886. void Detector_TiRayDR::SetReconnectTimePeriod(int nTime)
  2887. {
  2888. FINFO("--Func TiRay-- SetReconnectTimePeriod Start");
  2889. FINFO("ReconnectTimePeriod:{$}", nTime);
  2890. m_nReconnectTimePeriod = nTime;
  2891. FINFO("SetReconnectTimePeriod Over");
  2892. }
  2893. int Detector_TiRayDR::TiRay_GetSdkVersion()
  2894. {
  2895. return GetSdkVersion_Ptr();
  2896. }
  2897. TiRayError Detector_TiRayDR::TiRay_Execute(int detectorId, int commandId, TiRayVariant argv[], int argc)
  2898. {
  2899. return Execute_Ptr(detectorId, commandId, argv, argc);
  2900. }
  2901. TiRayError Detector_TiRayDR::TiRay_ApplyPreset(int detectorId, TiRayVariant argv[], int argc, ResultCallback fn)
  2902. {
  2903. return ApplyPreset_Ptr(detectorId, argv, argc, fn);
  2904. }
  2905. TiRayError Detector_TiRayDR::TiRay_GenerateTemplate(TemplateType type, TiRayVariant images[], int count, void* templateBuffer, int bufferSize)
  2906. {
  2907. return GenerateTemplate_Ptr(type, images, count, templateBuffer, bufferSize);
  2908. }
  2909. TiRayError Detector_TiRayDR::TiRay_Scan(ResultCallback fn, const char* interfaceIp, int scanDuration)
  2910. {
  2911. return Scan_Ptr(fn, interfaceIp, scanDuration);
  2912. }
  2913. TiRayError Detector_TiRayDR::TiRay_SetIp(const char* detectorSN, const char* upperIp, const char* lowerIp, const char* interfaceIp)
  2914. {
  2915. return SetIp_Ptr(detectorSN, upperIp, lowerIp, interfaceIp);
  2916. }
  2917. TiRayError Detector_TiRayDR::TiRay_Startup(TiRayModel model, EventCallback fn, const StartupOption* option)
  2918. {
  2919. return Startup_Ptr(model, fn, option);
  2920. }
  2921. void Detector_TiRayDR::TiRay_Stop()
  2922. {
  2923. Stop_Ptr();
  2924. }
  2925. /***
  2926. ** 说明:重连探测器线程
  2927. ***/
  2928. void* Detector_TiRayDR::onReconnectThread(PVOID pvoid)
  2929. {
  2930. FINFO("Reconnect detector thread start");
  2931. Detector_TiRayDR* pThis = static_cast<Detector_TiRayDR*>(pvoid);
  2932. while (!pThis->m_bConnected)
  2933. {
  2934. pThis->OpenDetector();
  2935. usleep(pThis->m_nReconnectTimePeriod*1000);
  2936. }
  2937. pThis->m_bReconnectThreadRunning = false;
  2938. pThis->m_hReconnectThread = 0; // 重置线程句柄,允许再次创建重连线程
  2939. FINFO("Leave reconnect detector thread");
  2940. return 0;
  2941. }
  2942. TiRayError Detector_TiRayDR::upload(upload_type type, char* data, int size)
  2943. {
  2944. TiRayVariant param[1]{};
  2945. param[0].Type = TiRayVariant::TiRayBuffer;
  2946. param[0].DataValue = data;
  2947. param[0].DataLen = size;
  2948. if (type == offset) {
  2949. return Execute_Ptr(m_nDetectorID, Cmd_UploadOffsetTemplate, param, 1);
  2950. }
  2951. if (type == gain) {
  2952. return Execute_Ptr(m_nDetectorID, Cmd_UploadGainTemplate, param, 1);
  2953. }
  2954. if (type == firmware) {
  2955. return Execute_Ptr(m_nDetectorID, Cmd_UpdateFirmware, param, 1);
  2956. }
  2957. return Err_InvalidParam;
  2958. }