HouseBin.cs 146 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000
  1. using DBEntity;
  2. using Dm;
  3. using Google.Protobuf;
  4. using ivf_tl_CameraHelper;
  5. using IvfTl.Control.Entity;
  6. using IvfTl.Control.Entity.DBEntitys;
  7. using IvfTl.Control.Entity.DTO;
  8. using IvfTl.Control.Entity.DTO.ApiResultDTO;
  9. using IvfTl.Control.Entity.DTO.ControllerResults;
  10. using IvfTl.Control.Entity.GlobalEntitys;
  11. using IvfTl.Control.Entity.GlobalEnums;
  12. using ivf_tl_SerialHelper.Util;
  13. using ivf_tl_UtilHelper;
  14. using IvfTl.Hardware;
  15. using IvfTl.Hardware.Impl;
  16. using IvfTl.AutoFocus.Calib;
  17. using IvfTl.AutoFocus.Layout;
  18. using IvfTl.AutoFocus.Storage;
  19. using Newtonsoft.Json;
  20. using SQLitePCL;
  21. using System;
  22. using System.Diagnostics;
  23. using System.Drawing.Imaging;
  24. using System.IO;
  25. using System.Net.Http.Json;
  26. using System.Runtime.InteropServices;
  27. using static System.Formats.Asn1.AsnWriter;
  28. namespace ivf_tl_Com
  29. {
  30. /// <summary>
  31. /// 仓室通信
  32. /// </summary>
  33. public class HouseBin
  34. {
  35. public event Func<int, int, bool> ChangeBufferBottleBinEvent;
  36. public event Func<HouseBin, int, bool> HouseBinChangeBufferBottleBinEvent;
  37. public event Action<int, DateTime, string, LogEnum> HouseLogEvent;
  38. public event Action<string, LogEnum> TLLogEvent;
  39. public event Action<Exception, string, string, LogEnum> ExceptionLogEvent;
  40. public event Action<HouseHistoryData> OnHistoryEvent;
  41. /// <summary>
  42. /// 服务器获取仓室自动对焦数据,housesn、autfocusTime
  43. /// </summary>
  44. public event Func<int, Dictionary<int, DateTime?>, List<HouseWellPhoto>> GetAutoFocusServiceEvent;
  45. /// <summary>
  46. /// 数据库获取仓室自动对焦数据,housesn、autfocusTime
  47. /// </summary>
  48. public event Func<int, Dictionary<int, DateTime?>, List<HouseWellPhoto>> GetAutoFocusDBEvent;
  49. /// <summary>
  50. /// M2-04 标定结果存储入口(写本地 calibration.json 真相源 + 镜像 house_autofocus_calibration)。
  51. /// 由 control 端(AppData)在 InitHouseBinEvent 时注入并配置 JsonPath/DbMirror;
  52. /// 为空则本地对焦不落库/不写 JSON(不影响对焦本身)。日常对焦路径以 scene=1 调用(append)。
  53. /// </summary>
  54. public CalibrationStore AutofocusStore { get; set; }
  55. /// <summary>
  56. /// 服务器获取仓室拍照数据,housesn、autfocusTime
  57. /// </summary>
  58. public event Func<int, Dictionary<int, DateTime?>, PositionInfoResultDTO> GetCCDServiceEvent;
  59. /// <summary>
  60. /// 数据库获取仓室拍照数据,housesn、autfocusTime
  61. /// </summary>
  62. public event Func<int, Dictionary<int, DateTime?>, List<HouseWellPhoto>> GetCCDDBEvent;
  63. /// <summary>
  64. /// 上传图片事件
  65. /// </summary>
  66. public event Action<ImageDTO> UploadImageEvent;
  67. /// <summary>
  68. /// 图片保存到数据库
  69. /// </summary>
  70. public event Action<ImageDTO> SavePicDbEvent;
  71. /// <summary>
  72. /// 修改仓室自动对焦状态
  73. /// </summary>
  74. public event Action<bool, int> UpdateAutofocusStateEvent;
  75. /// <summary>
  76. /// 调试模式准备好事件
  77. /// </summary>
  78. public event Action<string, int> DebugOkEvent;
  79. /// <summary>
  80. /// 舱室运行状态上报 舱室、串口、拍照、排气
  81. /// </summary>
  82. public event Action<int, int, int, int, int, int> HouseStateEvent;
  83. public event Action<int, int, int> CCDStateEvent;
  84. /// <summary>
  85. /// 排队换气
  86. /// </summary>
  87. public bool QueueAir { get; set; } = false;
  88. /// <summary>
  89. /// 准备换气
  90. /// </summary>
  91. public bool ReadyAir { get; set; } = false;
  92. /// <summary>
  93. /// 换气完成
  94. /// </summary>
  95. public bool EndAir { get; set; } = false;
  96. /// <summary>
  97. /// 缓冲瓶进气阀打开状态
  98. /// </summary>
  99. public bool OpenBuffer { get; set; } = false;
  100. public bool StartAir = false;
  101. public int CamNum { get; set; } = 0;
  102. public int TongQi = 1000 * 60 * 2;
  103. public int VentNum = 10;
  104. public int VentPre = 20;
  105. public int VentWaitTimeB = 1500;
  106. public int VentWaitTimeD = 1500;
  107. public int AutoWaitTime = 600000;
  108. public int CCDAutoWaitTime = 600000;
  109. public int CCDFailedWaitTime = 15000;
  110. public int CCDFailedNumber = 3;
  111. public bool ReCa = false;
  112. Stopwatch CCDAutoStopwatch = new Stopwatch();
  113. public bool CCDError = false;
  114. /// <summary>
  115. /// 是否排队换气
  116. /// </summary>
  117. public bool IsPai = false;
  118. /// <summary>
  119. /// 是否退出换气
  120. /// </summary>
  121. public bool StopPai = false;
  122. public string TakePhotoFailed = string.Empty;
  123. public HouseBin(TLSetting _setting, House _house, Dish _dish, Balance _balance, List<HouseWellSetting> _wellSettings)
  124. {
  125. if (_house == null)
  126. {
  127. return;
  128. }
  129. for (int i = 1; i <= 16; i++) LastAutoFocusTimeDic.Add(i, null);
  130. this.PortName = _house.housePort;
  131. // M1-03 HAL: 向统一硬件访问层借用该 COM 口的唯一 ComBin(杜绝同口重复 Open)。
  132. // RawComBin 返回 HAL 内部包装的具体 ComBin,保留采集端原有事件/调用面不变(代码隔离)。
  133. this.ComBin = (ComBin)HardwareAccessLayer.Instance.GetSerial(_house.houseSn, _house.housePort).RawComBin;
  134. // T1.4 双保险:把本舱 houseSn→port→相机 index 补登记到 HAL _houses。正常路径由 ScanDevices()
  135. // (登录后 MainWindow 调)填表;此处补 ScanDevices 现场漏扫(握手失败)的舱,使其借用仍可用,不覆盖已发现的舱。
  136. HardwareAccessLayer.Instance.RegisterHouse(_house.houseSn, _house.housePort,
  137. (_house.openCcd == 1 && _house.ccdId != -1) ? _house.ccdId : -1);
  138. ComBin.CommandLogEvent += ComBin_CommandLogEvent;
  139. ComBin.ErrorLogEvent += ComBin_ErrorLogEvent;
  140. ComBin.ExceptionLogEvent += ComBin_ExceptionLogEvent;
  141. ComBin.ComStateEvent += ComBin_ComStateEvent;
  142. this.FirstClearest = _house.autoFocus;
  143. this.IsNewAirSwap = _setting.newAirSwap;
  144. this.isWuTu = _house.noImagePreview;
  145. this.House = _house;
  146. this.Dish = _dish;
  147. this.Balance = _balance;
  148. this.TLSetting = _setting;
  149. this._wellSettings = _wellSettings;
  150. TargetTemp = _house.temperatureLowerHeatingPlate;
  151. //this.photoSerrings = _photoSetting;
  152. //this.wellSettings = _wellSettings;
  153. }
  154. private void ComBin_ComStateEvent(int obj)
  155. {
  156. comState = obj;
  157. HouseStateEvent?.Invoke(House.houseSn, -1, comState, -1, -1, -1);
  158. }
  159. private void ComBin_ExceptionLogEvent(Exception arg1, string arg2, string arg3, LogEnum arg4)
  160. {
  161. ExceptionLogEvent?.Invoke(arg1, arg2, arg3, arg4);
  162. }
  163. private void ComBin_ErrorLogEvent(string arg1, LogEnum arg2)
  164. {
  165. TLLogEvent?.Invoke(arg1, arg2);
  166. }
  167. private void ComBin_CommandLogEvent(int arg1, DateTime arg2, string arg3, LogEnum arg4)
  168. {
  169. HouseLogEvent?.Invoke(arg1, arg2, arg3, arg4);
  170. }
  171. private void Camera_CommandLogEvent(DateTime arg2, string arg3, LogEnum arg4)
  172. {
  173. HouseLogEvent?.Invoke(House.houseSn, arg2, arg3, arg4);
  174. }
  175. #region 字段
  176. public string PortName = null; // M5-03 只读监控需跨程序集读取,由 private 改 public
  177. /// <summary>
  178. /// 串口通信类
  179. /// </summary>
  180. public ComBin ComBin = null;
  181. private Camera Camera = null;
  182. #endregion
  183. #region 运行情况字段
  184. /// <summary>
  185. /// 运行流程
  186. /// </summary>
  187. public string RunState = "未知";
  188. /// <summary>
  189. /// 当前气压状态
  190. /// </summary>
  191. public State ValveState = State.未知;
  192. /// <summary>
  193. /// 工作线程
  194. /// </summary>
  195. public WorkingType WorkingType = WorkingType.DoNothing;
  196. private State _IsDoorOpen = State.关闭;
  197. /// <summary>
  198. /// 当前舱门状态
  199. /// </summary>
  200. public State IsDoorOpen
  201. {
  202. get { return _IsDoorOpen; }
  203. set
  204. {
  205. if (_IsDoorOpen != value)
  206. {
  207. _IsDoorOpen = value;
  208. DoorStateChanged(value);
  209. }
  210. }
  211. }
  212. /// <summary>
  213. /// 是否为第一次平衡
  214. /// </summary>
  215. public bool FirstAir = true;
  216. /// <summary>
  217. /// 是否自动对焦
  218. /// </summary>
  219. public bool FirstClearest = false;
  220. /// <summary>
  221. /// 最后一次自动对焦时间
  222. /// </summary>
  223. private Dictionary<int, DateTime?> LastAutoFocusTimeDic = new Dictionary<int, DateTime?>();
  224. /// <summary>
  225. /// 是否停止自动对焦
  226. /// </summary>
  227. private bool IsStopClearest = false;
  228. /// <summary>
  229. /// 是否停止拍照
  230. /// </summary>
  231. private bool IsStopCCD = false;
  232. /// <summary>
  233. /// 是否停止换气
  234. /// </summary>
  235. private bool IsStopAirSwap = false;
  236. /// <summary>
  237. /// 是否开启新版换气
  238. /// </summary>
  239. private bool IsNewAirSwap = false;
  240. /// <summary>
  241. /// 是否开启无图
  242. /// </summary>
  243. private bool isWuTu = false;
  244. /// <summary>
  245. /// 是否调试模式
  246. /// </summary>
  247. public bool IsDebug = false;
  248. /// <summary>
  249. /// 审计B1:前台(调试/对焦)借用本舱闸门时由 HAL 的 OnPauseCapture 置 true,
  250. /// 采集主循环每节拍据此让路(停发采集命令、让出 ComBin);归还后 OnResumeCapture 置 false 恢复。
  251. /// 与 MQTT 机制的 IsDebug 独立(互不覆盖),MainThread 让路判断取两者之或。
  252. /// </summary>
  253. public volatile bool CapturePausedByGate = false;
  254. /// <summary>
  255. /// 审计B1:闸门事件是否已订阅(幂等保护,避免重复 StartTask 时多次 += 累积回调)。
  256. /// </summary>
  257. private bool _gateSubscribed = false;
  258. /// <summary>
  259. /// 调试模式准备好
  260. /// </summary>
  261. public bool isDebugOk = false;
  262. /// <summary>
  263. /// 抠图成功数
  264. /// </summary>
  265. int KouTuSuccessNum = 0;
  266. /// <summary>
  267. /// 抠图失败数
  268. /// </summary>
  269. int KouTuDefultNum = 0;
  270. /// <summary>
  271. /// 当前下位机水平电机位置
  272. /// </summary>
  273. private int currentHorizontalMotor = -1;
  274. /// <summary>
  275. /// 当前下位机垂直电机位置
  276. /// </summary>
  277. private int currentVerticalMotor = -1;
  278. /// <summary>
  279. /// 舱室运行最后一次检测时间
  280. /// </summary>
  281. private DateTime LastRunTime = DateTime.Now;
  282. /// <summary>
  283. /// 舱室运行异常 0正常 1异常
  284. /// </summary>
  285. private int houseState = -1;
  286. /// <summary>
  287. /// 串口通信状态 0正常 1异常
  288. /// </summary>
  289. private int comState = -1;
  290. /// <summary>
  291. /// 拍照失败异常,0正常 1异常
  292. /// </summary>
  293. private int CCDState = -1;
  294. private int ErrorWell = -1;
  295. /// <summary>
  296. /// 获取拍照位置失败次数
  297. /// </summary>
  298. private int GetCCDDefeatNum = 0;
  299. /// <summary>
  300. /// 排气失败异常,0正常 1异常
  301. /// </summary>
  302. private int PaiQiState = -1;
  303. #endregion
  304. #region 数据
  305. public House House = null;
  306. public Dish Dish { get; set; } = null;
  307. public Balance Balance { get; set; } = null;
  308. private TLSetting TLSetting = null;
  309. /// <summary>
  310. /// 正常拍照位置
  311. /// </summary>
  312. private List<HouseWellPhoto> _ccdPhoto = new List<HouseWellPhoto>();
  313. /// <summary>
  314. /// 自动对焦拍照位置
  315. /// </summary>
  316. private List<HouseWellPhoto> _autoFocusPhoto = new List<HouseWellPhoto>();
  317. /// <summary>
  318. /// 仓室水平位置集合
  319. /// </summary>
  320. private List<HouseWellSetting> _wellSettings = new List<HouseWellSetting>();
  321. private decimal _Pressure = 0m;
  322. /// <summary>
  323. /// 气压
  324. /// </summary>
  325. public decimal Pressure
  326. {
  327. get { return _Pressure; }
  328. set { _Pressure = value; }
  329. }
  330. /// <summary>
  331. /// 当前温度
  332. /// </summary>
  333. public decimal Temperature = 0m;
  334. /// <summary>
  335. /// 上盖板传感器温度
  336. /// </summary>
  337. public decimal Temperature1 = 0m;
  338. /// <summary>
  339. /// 下盖板传感器温度
  340. /// </summary>
  341. public decimal Temperature2 = 0m;
  342. /// <summary>
  343. /// 玻璃片下方温度
  344. /// </summary>
  345. public decimal Temperature3 = 0m;
  346. /// <summary>
  347. /// 下位机的温度补偿值
  348. /// </summary>
  349. public decimal TargetTemp = 0m;
  350. #endregion
  351. /// <summary>
  352. /// 审计B1:订阅本舱借用闸门的暂停/恢复采集事件。
  353. /// 时序:此处由 StartTask 起始调用,此时 HAL 已 ScanDevices 发现本舱,GetHouseGate 可取到 gate。
  354. /// 容错:取不到 gate(时序/未发现)或订阅异常,只记日志、不抛,绝不崩采集线程。
  355. /// 幂等:_gateSubscribed 防止重复 StartTask 时累积多次回调。
  356. /// 死锁防护:OnPause 只置标志、OnResume 只清标志,回调体内绝不获取锁/不发串口,
  357. /// 让路判断仅在 MainThread 循环顶部生效——对焦支线(同舱同线程,Acquire 后本就在跑)
  358. /// 的 Acquire 虽会触发 OnPause,但该置位只在下一节拍循环顶部被读取,
  359. /// 而此时对焦支线的 using 已 Dispose 归还→OnResume 已清标志,故不会自我暂停、无死锁。
  360. /// </summary>
  361. private void SubscribeGateCapturePause()
  362. {
  363. try
  364. {
  365. if (_gateSubscribed) return;
  366. if (House == null) return;
  367. var gate = HardwareAccessLayer.Instance.GetHouseGate(House.houseSn);
  368. if (gate == null)
  369. {
  370. HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[{House.houseSn}][{this.PortName}][审计B1:未取到舱借用闸门,采集暂停事件未接线(前台借用时采集端可能不让路)]", LogEnum.HouseInfo);
  371. return;
  372. }
  373. gate.OnPauseCapture += OnGatePauseCapture;
  374. gate.OnResumeCapture += OnGateResumeCapture;
  375. _gateSubscribed = true;
  376. HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[{House.houseSn}][{this.PortName}][审计B1:已订阅舱借用闸门 暂停/恢复采集 事件]", LogEnum.HouseInfo);
  377. }
  378. catch (Exception ex)
  379. {
  380. // 订阅失败不影响采集主流程:仅前台借用时无法自动让路,记异常便于排障。
  381. ExceptionLogEvent?.Invoke(ex, $"[{House.houseSn}][{PortName}][审计B1:订阅借用闸门暂停事件失败]", null, LogEnum.RunException);
  382. }
  383. }
  384. // 审计B1:前台借用→暂停采集。仅置标志(volatile),不持锁、不发串口,保证回调轻量无死锁。
  385. private void OnGatePauseCapture()
  386. {
  387. CapturePausedByGate = true;
  388. HouseLogEvent?.Invoke(House != null ? House.houseSn : -1, DateTime.Now, $"[{(House != null ? House.houseSn : -1)}][{this.PortName}][审计B1:前台借用,采集主循环让路(停发命令)]", LogEnum.HouseInfo);
  389. }
  390. // 审计B1:借用归还→恢复采集。仅清标志。
  391. private void OnGateResumeCapture()
  392. {
  393. CapturePausedByGate = false;
  394. HouseLogEvent?.Invoke(House != null ? House.houseSn : -1, DateTime.Now, $"[{(House != null ? House.houseSn : -1)}][{this.PortName}][审计B1:借用归还,采集恢复]", LogEnum.HouseInfo);
  395. }
  396. /// <summary>
  397. /// 仓室开始运行
  398. /// </summary>
  399. public void StartTask()
  400. {
  401. Task.Run(() =>
  402. {
  403. try
  404. {
  405. if (House == null)
  406. {
  407. return;
  408. }
  409. // 审计B1:订阅本舱借用闸门的"暂停/恢复采集"事件。
  410. // 前台(调试/对焦)Acquire 时 HAL 触发 OnPauseCapture → 本舱采集主循环让路(停发命令、让出 ComBin);
  411. // 归还触发 OnResumeCapture → 恢复采集。取不到 gate 或异常都不崩采集线程(容错)。
  412. SubscribeGateCapturePause();
  413. HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[{House.houseSn}][{this.PortName}]开始初始化", LogEnum.HouseInfo);
  414. if (House.openPort == 0)
  415. {
  416. HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[{House.houseSn}][{this.PortName}]仓室串口未打开,结束初始化", LogEnum.HouseInfo);
  417. HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[{House.houseSn}][{this.PortName}]仓室串口未打开,结束初始化", LogEnum.RunError);
  418. return;
  419. }
  420. var openPort = ComBin.OpenPort();
  421. HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[{House.houseSn}][{this.PortName}]仓室串口打开结果{openPort}", LogEnum.HouseInfo);
  422. if (!openPort)
  423. {
  424. TLLogEvent?.Invoke($"[{House.houseSn}][{this.PortName}]仓室串口打开失败,结束初始化", LogEnum.RunError);
  425. return;
  426. }
  427. if (House.openCcd == 1 && House.ccdId != -1)
  428. {
  429. // M1-03 HAL: 向 HAL 借用该 index 的唯一相机(杜绝同相机重复 Init / 句柄争用)。
  430. this.Camera = (Camera)HardwareAccessLayer.Instance.GetCamera(House.ccdId, House.ccdWidth, House.ccdHeight, House.ccdExposure).RawCamera;
  431. this.Camera.ExceptionLogEvent += ComBin_ExceptionLogEvent;
  432. this.Camera.HouseLogEvent += Camera_CommandLogEvent;
  433. int cameraInit = this.Camera.Init();
  434. HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[{House.houseSn}][{this.PortName}]相机初始化结果{cameraInit}[注:0表示成功]", LogEnum.HouseInfo);
  435. if (cameraInit != 0)
  436. {
  437. TLLogEvent?.Invoke($"[{House.houseSn}][{this.PortName}]相机初始化结果{cameraInit},结束初始化[注:0表示成功]", LogEnum.RunError);
  438. return;
  439. }
  440. int cameraSetMode = this.Camera.SetOpMode();
  441. HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[{House.houseSn}][{this.PortName}]相机连续模式设置结果{cameraSetMode}[注:0表示成功]", LogEnum.HouseInfo);
  442. if (cameraSetMode != 0)
  443. {
  444. TLLogEvent?.Invoke($"[{House.houseSn}][{this.PortName}]相机连续模式设置结果{cameraSetMode},结束初始化[注:0表示成功]", LogEnum.RunError);
  445. return;
  446. }
  447. Camera.GetRgbData();
  448. Camera.SavePreMem();
  449. }
  450. else
  451. {
  452. TLLogEvent?.Invoke($"[{House.houseSn}][{this.PortName}]仓室相机未打开,结束初始化", LogEnum.HouseInfo);
  453. return;
  454. }
  455. CommandSource commandSource = CommandSource.taskThread;
  456. this.RunState = "握手准备";
  457. //握手
  458. var custom = new CustomProtocol();
  459. custom.commandSource = commandSource;
  460. ComBin.ShakeHandsWait(custom);
  461. ComBin.CloseLEDWait(custom);
  462. //关闭进气阀
  463. ComBin.CloseIntakeValveWait(custom, TLSetting.valueDelay);
  464. ComBin.CloseExhaustValveWait(custom, TLSetting.valueDelay);
  465. HouseState(commandSource, custom, 0);
  466. if (Pressure < TLSetting.pressureAlarmMin)
  467. {
  468. ValveState = State.待补气;
  469. }
  470. else
  471. {
  472. ValveState = State.正常;
  473. }
  474. this.RunState = "水平电机自检";
  475. //水平电机自检
  476. ComBin.HorizontalMotorResetWait(custom, TLSetting.motorDelay);
  477. this.RunState = "垂直电机自检";
  478. //垂直电机自检
  479. ComBin.VerticalMotorResetWait(custom, TLSetting.motorDelay);
  480. HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[{House.houseSn}][{this.PortName}] 初始化完成,仓室开始运行", LogEnum.HouseInfo);
  481. MainThread();
  482. RunAlarmTask();
  483. RunHistoryTask();
  484. }
  485. catch (Exception ex)
  486. {
  487. ExceptionLogEvent?.Invoke(ex, $"[{House.houseSn}][{PortName}]初始化", null, LogEnum.RunException);
  488. }
  489. });
  490. }
  491. Dictionary<int, DateTime?> wellList = new Dictionary<int, DateTime?>();
  492. /// <summary>
  493. /// 主线程
  494. /// </summary>
  495. public void MainThread()
  496. {
  497. Task.Factory.StartNew(() =>
  498. {
  499. Stopwatch BmpSaveIntervalStopwatch = Stopwatch.StartNew();//拍照线程计时器
  500. Stopwatch AirSwapTimeStopwatch = Stopwatch.StartNew();//换气间隔计时器
  501. Stopwatch StartDishStopwatch = new Stopwatch();
  502. bool isAir = false;
  503. LastRunTime = DateTime.Now;
  504. while (true)
  505. {
  506. try
  507. {
  508. LastRunTime = DateTime.Now;
  509. // 审计B1:IsDebug=MQTT调试机制;CapturePausedByGate=前台(调试/对焦)经HAL闸门借用本舱。
  510. // 任一为真都让路——本节拍不发任何采集/电机命令、让出 ComBin 给借用方独占。
  511. if (IsDebug || CapturePausedByGate)
  512. {
  513. HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[{House.houseSn}][{this.PortName}]{(IsDebug ? "调试状态" : "前台借用让路")}", LogEnum.HouseInfo);
  514. this.RunState = IsDebug ? "调试状态" : "前台借用让路";
  515. // 仅 MQTT 调试机制(IsDebug)首次进入时发归位电机命令;
  516. // 闸门借用让路(CapturePausedByGate)绝不发串口——串口此刻已被借用方独占。
  517. if (IsDebug && !isDebugOk)
  518. {
  519. isDebugOk = true;
  520. DebugOkEvent?.Invoke(TLSetting.tlSn, House.houseSn);
  521. var custom = new CustomProtocol();//指令包
  522. ComBin.HorizontalMotorAbsoluteWait(custom, TLSetting.motorDelay, 70000);
  523. ComBin.HorizontalMotorResetWait(custom, TLSetting.motorDelay);
  524. }
  525. Thread.Sleep(1000 * 3);
  526. continue;
  527. }
  528. if (isDebugOk) isDebugOk = false;
  529. this.RunState = "空闲监测";
  530. if (Balance != null && Balance.id > 0) this.RunState = "温压监测平衡";
  531. if (Dish != null && Dish.id > 0) this.RunState = "温压监测";
  532. if (ReCa)
  533. {
  534. //CloseCamera($"[{House.houseSn}][{PortName}]");
  535. //OpenCamera($"[{House.houseSn}][{PortName}]");
  536. //ReCa = false;
  537. }
  538. //温压检测中补气
  539. ParamFun();
  540. if (Pressure < TLSetting.pressureAlarmMin) ValveState = State.待补气;
  541. else ValveState = State.正常;
  542. //仓门未关闭不进行任何操作
  543. if (IsDoorOpen != State.关闭) continue;
  544. HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[{House.houseSn}][FirstClearest:{FirstClearest}][{this.PortName}][当前状态:{this.RunState}][换气间隔:{StringHelper.TimeToString(AirSwapTimeStopwatch.Elapsed)}][拍照间隔:{StringHelper.TimeToString(BmpSaveIntervalStopwatch.Elapsed)}][对焦间隔:{StringHelper.TimeToString(StartDishStopwatch.Elapsed)}]", LogEnum.HouseInfo);
  545. //当前舱室有培养记录,那么就需要自动对焦和拍照以及换气
  546. if (Dish != null && Dish.id > 0)
  547. {
  548. if (IsPai)
  549. {
  550. if (StartAir)
  551. {
  552. AirSwapQueueFun();
  553. StartAir = false;
  554. if (FirstClearest)
  555. {
  556. isAir = true;
  557. StartDishStopwatch.Restart();
  558. }
  559. }
  560. }
  561. else
  562. {
  563. if (StartAir)
  564. {
  565. AirSwapTimeStopwatch.Restart();
  566. AirSwapFun();
  567. StartAir = false;
  568. }
  569. }
  570. if (AirSwapTimeStopwatch.ElapsedMilliseconds >= (TLSetting.airSwapFrequency * 60 * 1000))
  571. {
  572. AirSwapTimeStopwatch.Restart();
  573. AirSwapFun();
  574. }
  575. if (!FirstClearest)//不自动对焦
  576. {
  577. if (BmpSaveIntervalStopwatch.ElapsedMilliseconds >= (TLSetting.photoIntervalPerRound * 60 * 1000))
  578. {
  579. if (!StartCCD()) continue;
  580. BmpSaveIntervalStopwatch.Restart();
  581. ccdThreadFun();
  582. }
  583. continue;
  584. }
  585. if (IsPai)
  586. {
  587. if (isAir && StartDishStopwatch.ElapsedMilliseconds < AutoWaitTime)
  588. {
  589. continue;
  590. }
  591. isAir = false;
  592. StartDishStopwatch.Reset();
  593. }
  594. if (CCDState == 1 && CCDAutoStopwatch.ElapsedMilliseconds < CCDAutoWaitTime)
  595. {
  596. continue;
  597. }
  598. if (!StartAutoFocus()) continue;
  599. CCDAutoStopwatch.Restart();
  600. FirstClearest = false;
  601. if (GetClearest(CommandSource.AutoFocusThread))
  602. {
  603. if (AirSwapTimeStopwatch.ElapsedMilliseconds >= (TLSetting.airSwapFrequency * 60 * 1000))
  604. {
  605. AirSwapTimeStopwatch.Restart();
  606. AirSwapFun();
  607. }
  608. if (!StartCCD()) continue;
  609. BmpSaveIntervalStopwatch.Restart();
  610. ccdThreadFun();
  611. }
  612. else
  613. {
  614. FirstClearest = true;
  615. if (AirSwapTimeStopwatch.ElapsedMilliseconds >= (TLSetting.airSwapFrequency * 60 * 1000))
  616. {
  617. AirSwapTimeStopwatch.Restart();
  618. AirSwapFun();
  619. }
  620. }
  621. continue;
  622. }
  623. //平衡的情况处理
  624. if (Balance != null && Balance.id > 0)
  625. {
  626. if (StartAir)
  627. {
  628. AirSwapTimeStopwatch.Restart();
  629. if (IsPai)
  630. {
  631. AirSwapQueueFun();
  632. }
  633. else
  634. {
  635. AirSwapFun();
  636. }
  637. StartAir = false;
  638. }
  639. if (FirstAir)//第一次平衡
  640. {
  641. FirstAir = false;
  642. AirSwapTimeStopwatch.Restart();
  643. AirSwapFun();
  644. continue;
  645. }
  646. if (AirSwapTimeStopwatch.ElapsedMilliseconds >= (TLSetting.airSwapFrequency * 60 * 1000))
  647. {
  648. AirSwapTimeStopwatch.Restart();
  649. AirSwapFun();
  650. continue;
  651. }
  652. continue;
  653. }
  654. BmpSaveIntervalStopwatch.Restart();
  655. AirSwapTimeStopwatch.Restart();
  656. }
  657. catch (Exception ex)
  658. {
  659. ExceptionLogEvent?.Invoke(ex, $"[{House.houseSn}][{PortName}]主线程", null, LogEnum.RunException);
  660. }
  661. }
  662. }, TaskCreationOptions.LongRunning);
  663. }
  664. /// <summary>
  665. /// 运行情况监测线程
  666. /// </summary>
  667. public void RunAlarmTask()
  668. {
  669. Task.Factory.StartNew(async () =>
  670. {
  671. var time2 = (10 * 60 * 1000);
  672. while (true)
  673. {
  674. await Task.Delay(1000 * 60 * 5);
  675. try
  676. {
  677. var time1 = (DateTime.Now - LastRunTime).TotalMilliseconds;
  678. if (time1 > time2)
  679. {
  680. if (houseState != 1)
  681. {
  682. houseState = 1;
  683. HouseStateEvent?.Invoke(House.houseSn, houseState, -1, -1, -1, -1);
  684. }
  685. continue;
  686. }
  687. if (houseState == 0) continue;
  688. houseState = 0;
  689. HouseStateEvent?.Invoke(House.houseSn, houseState, -1, -1, -1, -1);
  690. }
  691. catch (Exception ex)
  692. {
  693. ExceptionLogEvent?.Invoke(ex, $"[{House.houseSn}][{PortName}]运行情况监测线程", null, LogEnum.RunException);
  694. }
  695. }
  696. }, TaskCreationOptions.LongRunning);
  697. }
  698. /// <summary>
  699. /// 历史数据上报线程
  700. /// </summary>
  701. public void RunHistoryTask()
  702. {
  703. HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[{House.houseSn}][{this.PortName}]历史数据上报线程启动", LogEnum.HouseInfo);
  704. Task.Factory.StartNew(async () =>
  705. {
  706. await Task.Delay(1000 * 60);
  707. int seconds = 1;
  708. HouseHistoryData currentData = null;
  709. while (true)
  710. {
  711. try
  712. {
  713. await Task.Delay(1000);
  714. if (this.WorkingType == WorkingType.AirSwapWorking)
  715. {
  716. currentData = GetHouseHistoryData(this);
  717. if (currentData != null) OnHistoryEvent?.Invoke(currentData);
  718. }
  719. else
  720. {
  721. if (seconds++ >= TLSetting.historyCurveInterval)
  722. {
  723. seconds = 1;
  724. currentData = GetHouseHistoryData(this);
  725. if (currentData != null) OnHistoryEvent?.Invoke(currentData);
  726. }
  727. }
  728. }
  729. catch (Exception ex)
  730. {
  731. ExceptionLogEvent?.Invoke(ex, $"[{House.houseSn}][{PortName}]历史数据上报线程", null, LogEnum.RunException);
  732. }
  733. }
  734. }, TaskCreationOptions.LongRunning);
  735. }
  736. private HouseHistoryData GetHouseHistoryData(HouseBin currentHouseBin)
  737. {
  738. if (currentHouseBin == null) return null;
  739. if (currentHouseBin.House == null) return null;
  740. int newHouse = 0;
  741. if (currentHouseBin.Balance != null && currentHouseBin.Balance.id > 0) newHouse = 2;
  742. if (currentHouseBin.Dish != null && currentHouseBin.Dish.id > 0) newHouse = 1;
  743. return new HouseHistoryData()
  744. {
  745. tlSn = TLSetting.tlSn,
  746. houseSn = currentHouseBin.House.houseSn,
  747. pressure = currentHouseBin.Pressure,
  748. temperature = currentHouseBin.Temperature,
  749. houseDoor = currentHouseBin.IsDoorOpen == State.打开 ? 1 : 0,
  750. airSwap = currentHouseBin.WorkingType == WorkingType.AirSwapWorking ? 1 : 0,
  751. temperatureLowerCover = currentHouseBin.Temperature2,
  752. temperatureUpperCover = currentHouseBin.Temperature1,
  753. temperatureLowerGlass = currentHouseBin.Temperature3,
  754. cultureState = newHouse,
  755. };
  756. }
  757. /// <summary>
  758. /// 关闭相机
  759. /// </summary>
  760. /// <param name="Content"></param>
  761. /// <returns></returns>
  762. public bool CloseCamera(string Content)
  763. {
  764. try
  765. {
  766. bool isdis = Camera.DisPose();
  767. HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[{House.houseSn}][{this.PortName}][释放相机内存结果:{isdis}]", LogEnum.HouseInfo);
  768. int unin = Camera.UnInit();
  769. HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[{House.houseSn}][{this.PortName}][卸载相机结果:{unin}]", LogEnum.HouseInfo);
  770. return true;
  771. }
  772. catch (Exception ex)
  773. {
  774. ExceptionLogEvent?.Invoke(ex, $"[{House.houseSn}][{PortName}]关闭相机", null, LogEnum.RunException);
  775. return false;
  776. }
  777. }
  778. /// <summary>
  779. /// 重新开启相机
  780. /// </summary>
  781. /// <param name="content"></param>
  782. /// <returns></returns>
  783. public bool OpenCamera(string content)
  784. {
  785. try
  786. {
  787. byte[] SaveRgbData = new byte[3];
  788. if (this.Camera != null)
  789. {
  790. //SaveRgbData[0] = this.Camera.SaveRgbData[0];
  791. //SaveRgbData[1] = this.Camera.SaveRgbData[1];
  792. //SaveRgbData[2] = this.Camera.SaveRgbData[2];
  793. SaveRgbData = new byte[Camera.LastSourceBufferHash.Length];
  794. Buffer.BlockCopy(Camera.LastSourceBufferHash, 0, SaveRgbData, 0, Camera.LastSourceBufferHash.Length);
  795. }
  796. Camera = null;
  797. // M1-03 HAL: 重开相机也向 HAL 借用同一 index 的唯一实例(不再 new,杜绝句柄争用)。
  798. // 因是单例同一对象,先 -= 再 += 防止重复订阅事件。
  799. this.Camera = (Camera)HardwareAccessLayer.Instance.GetCamera(House.ccdId, House.ccdWidth, House.ccdHeight, House.ccdExposure).RawCamera;
  800. this.Camera.ExceptionLogEvent -= ComBin_ExceptionLogEvent;
  801. this.Camera.HouseLogEvent -= Camera_CommandLogEvent;
  802. this.Camera.ExceptionLogEvent += ComBin_ExceptionLogEvent;
  803. this.Camera.HouseLogEvent += Camera_CommandLogEvent;
  804. int cameraInit = this.Camera.Init();
  805. //this.Camera.SaveRgbData[0] = SaveRgbData[0];
  806. //this.Camera.SaveRgbData[1] = SaveRgbData[1];
  807. //this.Camera.SaveRgbData[2] = SaveRgbData[2];
  808. Camera.LastSourceBufferHash = new byte[SaveRgbData.Length];
  809. Buffer.BlockCopy(SaveRgbData, 0, Camera.LastSourceBufferHash, 0, SaveRgbData.Length);
  810. SaveRgbData = null;
  811. HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[{House.houseSn}][{this.PortName}]相机初始化结果{cameraInit}[注:0表示成功]", LogEnum.HouseInfo);
  812. if (cameraInit != 0)
  813. {
  814. TLLogEvent?.Invoke($"[{House.houseSn}][{this.PortName}]相机初始化结果{cameraInit},结束初始化[注:0表示成功]", LogEnum.RunError);
  815. return false;
  816. }
  817. int cameraSetMode = this.Camera.SetOpMode();
  818. HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[{House.houseSn}][{this.PortName}]相机连续模式设置结果{cameraSetMode}[注:0表示成功]", LogEnum.HouseInfo);
  819. if (cameraSetMode != 0)
  820. {
  821. TLLogEvent?.Invoke($"[{House.houseSn}][{this.PortName}]相机连续模式设置结果{cameraSetMode},结束初始化[注:0表示成功]", LogEnum.RunError);
  822. return false;
  823. }
  824. return true;
  825. }
  826. catch (Exception ex)
  827. {
  828. ExceptionLogEvent?.Invoke(ex, $"[{House.houseSn}][{PortName}]重新开启相机", null, LogEnum.RunException);
  829. return false;
  830. }
  831. }
  832. #region 换气
  833. /// <summary>
  834. /// 换气
  835. /// </summary>
  836. /// <exception cref="NotImplementedException"></exception>
  837. private void AirSwapFun()
  838. {
  839. if (!IsPai) AirSwapOldFun();
  840. //HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[{House.houseSn}][{this.PortName}][关闭旧版换气]", LogEnum.HouseInfo);
  841. //return;
  842. //if (IsNewAirSwap)
  843. //{
  844. // AirSwapNewFun();
  845. //}
  846. //else
  847. //{
  848. // AirSwapOldFun();
  849. //}
  850. }
  851. private void AirSwapOldFun()
  852. {
  853. try
  854. {
  855. LastRunTime = DateTime.Now;
  856. WorkingType = WorkingType.AirSwapWorking;
  857. Stopwatch AirThreadStopwatch = Stopwatch.StartNew();
  858. var custom = new CustomProtocol();//指令包
  859. custom.commandSource = CommandSource.airSwapThread;
  860. HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[{House.houseSn}][{this.PortName}][换气开始时间:{DateTime.Now}]", LogEnum.HouseInfo);
  861. this.RunState = "气体交换";
  862. if (Balance != null && Balance.id > 0) this.RunState = "气体交换平衡";
  863. int num = 1;
  864. Stopwatch airStopwatch = Stopwatch.StartNew();
  865. var maxMilliseconds = TLSetting.ventilationDelay * 1000;
  866. while (num <= TLSetting.airSwapTime)//6
  867. {
  868. LastRunTime = DateTime.Now;
  869. if (IsStopAirSwap) break;
  870. num++;
  871. //打开排气阀
  872. ComBin.OpenExhaustValveWait(custom, TLSetting.valueDelay);
  873. airStopwatch.Restart();
  874. var milliseconds = airStopwatch.ElapsedMilliseconds;
  875. while (milliseconds <= maxMilliseconds)
  876. {
  877. if (IsStopAirSwap) break;
  878. HouseState(CommandSource.airSwapThread, custom, 50);
  879. milliseconds = airStopwatch.ElapsedMilliseconds;
  880. }
  881. ComBin.CloseExhaustValveWait(custom, TLSetting.valueDelay);
  882. HouseState(CommandSource.airSwapThread, custom, 0);
  883. //执行补气操作
  884. if (TLSetting.pressureAlarmMin > Pressure && this.IsDoorOpen == State.关闭)
  885. AerationNew(CommandSource.airSwapThread, custom);
  886. }
  887. airStopwatch.Stop();
  888. ComBin.CloseExhaustValveWait(custom, TLSetting.valueDelay);
  889. HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[{House.houseSn}][{this.PortName}][换气结束时间:{DateTime.Now}][换气耗时:{StringHelper.TimeToString(AirThreadStopwatch.Elapsed)}]", LogEnum.HouseInfo);
  890. AirThreadStopwatch.Stop();
  891. WorkingType = WorkingType.DoNothing;
  892. // D1-10:换气物理动作审计(每次换气会话一行,非每次阀动作;远离串口字节循环)。全 try 兜底。
  893. try
  894. {
  895. Aivfo.OperationLog.OperationLogger.Log("换气", "周期换气",
  896. input: new { houseSn = House.houseSn, port = PortName, airSwapTime = TLSetting.airSwapTime },
  897. result: "成功",
  898. elapsedMs: (long)AirThreadStopwatch.Elapsed.TotalMilliseconds,
  899. houseSn: House.houseSn, tlSn: TLSetting?.tlSn);
  900. }
  901. catch { }
  902. }
  903. catch (Exception ex)
  904. {
  905. ExceptionLogEvent?.Invoke(ex, $"[{House.houseSn}][{PortName}]换气", null, LogEnum.RunException);
  906. try
  907. {
  908. Aivfo.OperationLog.OperationLogger.Log("换气", "周期换气",
  909. input: new { houseSn = House.houseSn, port = PortName },
  910. result: "失败", error: ex.GetType().Name + ": " + ex.Message,
  911. houseSn: House.houseSn, tlSn: TLSetting?.tlSn);
  912. }
  913. catch { }
  914. }
  915. }
  916. private void AirSwapNewFun()
  917. {
  918. LastRunTime = DateTime.Now;
  919. Stopwatch AirThreadStopwatch = Stopwatch.StartNew();
  920. Stopwatch airStopwatch = Stopwatch.StartNew();
  921. WorkingType = WorkingType.AirSwapWorking;
  922. bool? changB = false;
  923. try
  924. {
  925. var custom = new CustomProtocol();//指令包
  926. custom.commandSource = CommandSource.airSwapThread;
  927. HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[{House.houseSn}][{this.PortName}][换气开始时间:{DateTime.Now}]", LogEnum.HouseInfo);
  928. this.RunState = "气体交换";
  929. if (Balance != null && Balance.id > 0) this.RunState = "气体交换平衡";
  930. int num = 1;
  931. bool isAlarm = false;
  932. var maxMilliseconds = TongQi;
  933. //打开排气阀
  934. ComBin.OpenExhaustValveWait(custom, TLSetting.valueDelay);
  935. HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[{House.houseSn}][{this.PortName}][打开舱室排气阀时间:{DateTime.Now}]", LogEnum.HouseInfo);
  936. //打开进气阀
  937. ComBin.OpenIntakeValveWait(custom, TLSetting.valueDelay);
  938. HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[{House.houseSn}][{this.PortName}][打开舱室进气阀时间:{DateTime.Now}]", LogEnum.HouseInfo);
  939. //打开缓冲瓶进气阀
  940. changB = ChangeBufferBottleBinEvent?.Invoke(House.houseSn, 1);
  941. HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[{House.houseSn}][{this.PortName}][缓冲瓶打开进气阀时间:{DateTime.Now}][结果:{changB}]", LogEnum.HouseInfo);
  942. //等待换气冲刷
  943. airStopwatch.Restart();
  944. var milliseconds = airStopwatch.ElapsedMilliseconds;
  945. while (milliseconds <= maxMilliseconds)
  946. {
  947. HouseState(CommandSource.airSwapThread, custom, 100);
  948. if (IsStopAirSwap) break;
  949. milliseconds = airStopwatch.ElapsedMilliseconds;
  950. }
  951. //关闭缓冲瓶进气阀
  952. changB = ChangeBufferBottleBinEvent?.Invoke(House.houseSn, 0);
  953. HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[{House.houseSn}][{this.PortName}][缓冲瓶关闭进气阀时间:{DateTime.Now}][结果:{changB}]", LogEnum.HouseInfo);
  954. //关闭舱室进气阀
  955. ComBin.CloseIntakeValveWait(custom, TLSetting.valueDelay);
  956. HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[{House.houseSn}][{this.PortName}][关闭舱室进气阀时间:{DateTime.Now}][结果:{changB}]", LogEnum.HouseInfo);
  957. //关闭舱室排气阀
  958. ComBin.CloseExhaustValveWait(custom, TLSetting.valueDelay);
  959. HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[{House.houseSn}][{this.PortName}][关闭舱室排气阀时间:{DateTime.Now}][结果:{changB}]", LogEnum.HouseInfo);
  960. //执行补气操作
  961. if (TLSetting.pressureAlarmMin > Pressure && this.IsDoorOpen == State.关闭)
  962. AerationNew(CommandSource.airSwapThread, custom);
  963. HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[{House.houseSn}][{this.PortName}][换气结束时间:{DateTime.Now}][换气耗时:{StringHelper.TimeToString(AirThreadStopwatch.Elapsed)}]", LogEnum.HouseInfo);
  964. }
  965. catch (Exception ex)
  966. {
  967. ExceptionLogEvent?.Invoke(ex, $"[{House.houseSn}][{PortName}]新版换气", null, LogEnum.RunException);
  968. }
  969. finally
  970. {
  971. airStopwatch.Stop();
  972. AirThreadStopwatch.Stop();
  973. WorkingType = WorkingType.DoNothing;
  974. }
  975. }
  976. /// <summary>
  977. /// 排队换气
  978. /// </summary>
  979. private void AirSwapQueueFun()
  980. {
  981. LastRunTime = DateTime.Now;
  982. Stopwatch AirThreadStopwatch = Stopwatch.StartNew();
  983. Stopwatch airStopwatch = Stopwatch.StartNew();
  984. WorkingType = WorkingType.AirSwapWorking;
  985. bool? changB = false;
  986. try
  987. {
  988. var custom = new CustomProtocol();//指令包
  989. custom.commandSource = CommandSource.airSwapThread;
  990. HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[{House.houseSn}][{this.PortName}][换气开始时间:{DateTime.Now}]", LogEnum.HouseInfo);
  991. int num = 1;
  992. bool isAlarm = false;
  993. var maxMilliseconds = TongQi;
  994. QueueAir = false;
  995. ReadyAir = false;
  996. EndAir = false;
  997. OpenBuffer = false;
  998. changB = HouseBinChangeBufferBottleBinEvent?.Invoke(this, 1);
  999. HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[{House.houseSn}][{this.PortName}][{House.houseSn}号舱室开始换气排队:{DateTime.Now}][结果:{changB}]", LogEnum.HouseInfo);
  1000. if (changB != true)
  1001. {
  1002. HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[{House.houseSn}][{this.PortName}][联系缓冲瓶失败,跳过换气:{DateTime.Now}]", LogEnum.HouseInfo);
  1003. return;
  1004. }
  1005. this.ValveState = State.排队;
  1006. this.RunState = "气体交换";
  1007. if (Balance != null && Balance.id > 0) this.RunState = "气体交换平衡";
  1008. do
  1009. {
  1010. HouseState(CommandSource.airSwapThread, custom, 100);
  1011. if (IsStopAirSwap) break;
  1012. } while (!QueueAir);
  1013. if (IsStopAirSwap)
  1014. {
  1015. changB = HouseBinChangeBufferBottleBinEvent?.Invoke(this, 0);
  1016. HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[{House.houseSn}][{this.PortName}][排队换气终止,跳过换气:{DateTime.Now}][结果:{changB}]", LogEnum.HouseInfo);
  1017. return;
  1018. }
  1019. HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[{House.houseSn}][{this.PortName}][{House.houseSn}号舱室换气排队完成,开始进行准备工作]", LogEnum.HouseInfo);
  1020. //this.RunState = "气体交换";
  1021. //if (Balance != null && Balance.id > 0) this.RunState = "气体交换平衡";
  1022. //打开排气阀
  1023. ComBin.OpenExhaustValveWait(custom, TLSetting.valueDelay);
  1024. HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[{House.houseSn}][{this.PortName}][打开舱室排气阀时间:{DateTime.Now}]", LogEnum.HouseInfo);
  1025. //打开进气阀
  1026. ComBin.OpenIntakeValveWait(custom, TLSetting.valueDelay);
  1027. HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[{House.houseSn}][{this.PortName}][打开舱室进气阀时间:{DateTime.Now}][换气准备工作完成][等待缓冲瓶打开进气阀]", LogEnum.HouseInfo);
  1028. ReadyAir = true;
  1029. do
  1030. {
  1031. HouseState(CommandSource.airSwapThread, custom, 50);
  1032. if (IsStopAirSwap) break;
  1033. } while (!OpenBuffer);
  1034. HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[{House.houseSn}][{this.PortName}][缓冲瓶进气阀已打开,开始冲刷舱室]", LogEnum.HouseInfo);
  1035. //等待换气冲刷
  1036. this.ValveState = State.冲刷;
  1037. //this.RunState = "气体交换冲刷";
  1038. //if (Balance != null && Balance.id > 0) this.RunState = "气体交换平衡冲刷";
  1039. airStopwatch.Restart();
  1040. while (airStopwatch.ElapsedMilliseconds <= maxMilliseconds)
  1041. {
  1042. HouseState(CommandSource.airSwapThread, custom, 100);
  1043. if (IsStopAirSwap) break;
  1044. }
  1045. ReadyAir = false;
  1046. //this.RunState = "气体交换";
  1047. //if (Balance != null && Balance.id > 0) this.RunState = "气体交换平衡";
  1048. HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[{House.houseSn}][{this.PortName}][冲刷完成,等待关闭缓冲瓶进气阀]", LogEnum.HouseInfo);
  1049. do
  1050. {
  1051. HouseState(CommandSource.airSwapThread, custom, 50);
  1052. } while (!EndAir);
  1053. HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[{House.houseSn}][{this.PortName}][关闭缓冲瓶进气阀]", LogEnum.HouseInfo);
  1054. //关闭缓冲瓶进气阀
  1055. //changB = ChangeBufferBottleBinEvent?.Invoke(House.houseSn, 0);
  1056. //HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[{House.houseSn}][{this.PortName}][缓冲瓶关闭进气阀时间:{DateTime.Now}][结果:{changB}]", LogEnum.HouseInfo);
  1057. //关闭舱室进气阀
  1058. ComBin.CloseIntakeValveWait(custom, TLSetting.valueDelay);
  1059. HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[{House.houseSn}][{this.PortName}][关闭舱室进气阀时间:{DateTime.Now}][结果:{changB}]", LogEnum.HouseInfo);
  1060. //关闭舱室排气阀
  1061. ComBin.CloseExhaustValveWait(custom, TLSetting.valueDelay);
  1062. HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[{House.houseSn}][{this.PortName}][关闭舱室排气阀时间:{DateTime.Now}][结果:{changB}]", LogEnum.HouseInfo);
  1063. HouseState(CommandSource.airSwapThread, custom, 50);
  1064. if (Pressure < TLSetting.pressureAlarmMin) this.ValveState = State.待补气;
  1065. else this.ValveState = State.正常;
  1066. //执行补气操作
  1067. if (TLSetting.pressureAlarmMin > Pressure && this.IsDoorOpen == State.关闭)
  1068. AerationNew(CommandSource.airSwapThread, custom);
  1069. HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[{House.houseSn}][{this.PortName}][换气结束时间:{DateTime.Now}][换气耗时:{StringHelper.TimeToString(AirThreadStopwatch.Elapsed)}]", LogEnum.HouseInfo);
  1070. }
  1071. catch (Exception ex)
  1072. {
  1073. ExceptionLogEvent?.Invoke(ex, $"[{House.houseSn}][{PortName}]新版换气", null, LogEnum.RunException);
  1074. }
  1075. finally
  1076. {
  1077. airStopwatch.Stop();
  1078. AirThreadStopwatch.Stop();
  1079. WorkingType = WorkingType.DoNothing;
  1080. }
  1081. }
  1082. #endregion
  1083. #region 温压检测、补气、仓室状态
  1084. /// <summary>
  1085. /// 温压监测
  1086. /// </summary>
  1087. /// <exception cref="NotImplementedException"></exception>
  1088. private void ParamFun()
  1089. {
  1090. try
  1091. {
  1092. LastRunTime = DateTime.Now;
  1093. var nameString = this.RunState;
  1094. Stopwatch ParamThreadStopwatch = Stopwatch.StartNew();
  1095. HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[{House.houseSn}][{this.PortName}][{nameString}开始时间:{DateTime.Now}]", LogEnum.HouseInfo);
  1096. CustomProtocol custom = new CustomProtocol();
  1097. custom.commandSource = CommandSource.paramThread;
  1098. HouseState(CommandSource.paramThread, custom, 500);
  1099. if (IsPai)
  1100. {
  1101. if (IsDoorOpen == State.关闭 && Pressure >= TLSetting.pressureAlarmMin)
  1102. {
  1103. if ((Dish != null && Dish.id > 0))
  1104. {
  1105. PaiQi(custom, CommandSource.paramThread, VentWaitTimeD);
  1106. }
  1107. else if ((Balance != null && Balance.id > 0))
  1108. {
  1109. PaiQi(custom, CommandSource.paramThread, VentWaitTimeB);
  1110. }
  1111. }
  1112. }
  1113. if (IsDoorOpen == State.关闭 && Pressure < TLSetting.pressureAlarmMin)
  1114. {
  1115. if ((Dish != null && Dish.id > 0) || (Balance != null && Balance.id > 0))
  1116. {
  1117. AerationNew(CommandSource.paramThread, custom);
  1118. }
  1119. }
  1120. //读仓门状态
  1121. IsDoorOpen = ComBin.DoorStatusWait(custom);
  1122. Thread.Sleep(500);
  1123. HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[{House.houseSn}][{this.PortName}][{nameString}结束时间:{DateTime.Now}][耗时:{StringHelper.TimeToString(ParamThreadStopwatch.Elapsed)}]", LogEnum.HouseInfo);
  1124. ParamThreadStopwatch.Stop();
  1125. }
  1126. catch (Exception ex)
  1127. {
  1128. ExceptionLogEvent?.Invoke(ex, $"[{House.houseSn}][{PortName}]温压监测", null, LogEnum.RunException);
  1129. }
  1130. }
  1131. /// <summary>
  1132. /// 补气
  1133. /// </summary>
  1134. /// <param name="commandSource"></param>
  1135. /// <param name="custom"></param>
  1136. /// <param name="isAlarm"></param>
  1137. private void AerationNew(CommandSource commandSource, CustomProtocol custom)
  1138. {
  1139. try
  1140. {
  1141. Stopwatch AerationStopwatch = Stopwatch.StartNew();
  1142. HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[{House.houseSn}][{this.PortName}][补气开始时间:{DateTime.Now}]", LogEnum.HouseInfo);
  1143. custom.commandSource = commandSource;
  1144. ValveState = State.补气;
  1145. decimal oldPressure = 0m;
  1146. for (int i = 1; i <= TLSetting.houseAerationNum; i++)
  1147. {
  1148. if (IsDoorOpen != State.关闭 || Pressure >= TLSetting.pressureAlarmMin) break;
  1149. oldPressure = Pressure;
  1150. ComBin.HouseAerationWait(custom);
  1151. Thread.Sleep(TLSetting.aerationDelay * 1000);
  1152. HouseState(commandSource, custom, 0);
  1153. HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[{House.houseSn}][{this.PortName}]补气完成[{oldPressure}->{Pressure}]", LogEnum.HouseInfo);
  1154. }
  1155. this.ValveState = State.正常;
  1156. if (Pressure < TLSetting.pressureAlarmMin) this.ValveState = State.待补气;
  1157. HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[{House.houseSn}][{this.PortName}][补气结束时间:{DateTime.Now}][耗时:{StringHelper.TimeToString(AerationStopwatch.Elapsed)}]", LogEnum.HouseInfo);
  1158. AerationStopwatch.Stop();
  1159. // D1-10:补气物理动作审计(每次补气会话一行)。全 try 兜底。
  1160. try
  1161. {
  1162. Aivfo.OperationLog.OperationLogger.Log("补气", "缺压补气",
  1163. input: new { houseSn = House.houseSn, port = PortName, pressureAlarmMin = TLSetting.pressureAlarmMin },
  1164. output: new { pressure = Pressure, valveState = ValveState.ToString() },
  1165. result: "成功",
  1166. elapsedMs: (long)AerationStopwatch.Elapsed.TotalMilliseconds,
  1167. houseSn: House.houseSn, tlSn: TLSetting?.tlSn);
  1168. }
  1169. catch { }
  1170. }
  1171. catch (Exception ex)
  1172. {
  1173. ExceptionLogEvent?.Invoke(ex, $"[{House.houseSn}][{PortName}]补气", null, LogEnum.RunException);
  1174. try
  1175. {
  1176. Aivfo.OperationLog.OperationLogger.Log("补气", "缺压补气",
  1177. input: new { houseSn = House.houseSn, port = PortName },
  1178. result: "失败", error: ex.GetType().Name + ": " + ex.Message,
  1179. houseSn: House.houseSn, tlSn: TLSetting?.tlSn);
  1180. }
  1181. catch { }
  1182. }
  1183. }
  1184. /// <summary>
  1185. /// 排气
  1186. /// </summary>
  1187. /// <param name="custom"></param>
  1188. /// <param name="commandSource"></param>
  1189. private void PaiQi(CustomProtocol custom, CommandSource commandSource, int waitTime)
  1190. {
  1191. Stopwatch AerationStopwatch = Stopwatch.StartNew();
  1192. Stopwatch VentWaitStopwatch = Stopwatch.StartNew();
  1193. try
  1194. {
  1195. HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[{House.houseSn}][{this.PortName}][排气开始时间:{DateTime.Now}]", LogEnum.HouseInfo);
  1196. ValveState = State.排气;
  1197. decimal oldPressure = 0m;
  1198. for (int i = 1; i <= VentNum; i++)
  1199. {
  1200. if (IsDoorOpen != State.关闭 || Pressure <= VentPre) break;
  1201. oldPressure = Pressure;
  1202. ComBin.HouseVentWait(custom);
  1203. VentWaitStopwatch.Restart();
  1204. do
  1205. {
  1206. Thread.Sleep(500);
  1207. HouseState(commandSource, custom, 0);
  1208. } while (VentWaitStopwatch.ElapsedMilliseconds < waitTime);
  1209. HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[{House.houseSn}][{this.PortName}]排气完成[{oldPressure}->{Pressure}]", LogEnum.HouseInfo);
  1210. }
  1211. if (Pressure > VentPre)
  1212. {
  1213. if (PaiQiState != 1)
  1214. {
  1215. PaiQiState = 1;
  1216. HouseStateEvent?.Invoke(House.houseSn, houseState, -1, -1, -1, 1);
  1217. }
  1218. }
  1219. else
  1220. {
  1221. if (PaiQiState != 0)
  1222. {
  1223. PaiQiState = 0;
  1224. HouseStateEvent?.Invoke(House.houseSn, houseState, -1, -1, -1, 0);
  1225. }
  1226. }
  1227. this.ValveState = State.正常;
  1228. if (Pressure < TLSetting.pressureAlarmMin) this.ValveState = State.待补气;
  1229. HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[{House.houseSn}][{this.PortName}][排气结束时间:{DateTime.Now}][耗时:{StringHelper.TimeToString(AerationStopwatch.Elapsed)}]", LogEnum.HouseInfo);
  1230. }
  1231. catch (Exception ex)
  1232. {
  1233. ExceptionLogEvent?.Invoke(ex, $"[{House.houseSn}][{PortName}]补气", null, LogEnum.RunException);
  1234. }
  1235. finally
  1236. {
  1237. AerationStopwatch.Stop();
  1238. VentWaitStopwatch.Stop();
  1239. }
  1240. }
  1241. /// <summary>
  1242. /// 读取仓室的仓门状态、温度、压力
  1243. /// </summary>
  1244. public void HouseState(CommandSource commandSource, CustomProtocol custom, int waitTime)
  1245. {
  1246. custom.commandSource = commandSource;
  1247. //读仓门状态
  1248. IsDoorOpen = ComBin.DoorStatusWait(custom);
  1249. if (waitTime > 0) Thread.Sleep(waitTime);
  1250. //仓室温度(下盖板温度)
  1251. Temperature2 = ComBin.TemperatureWait(custom);
  1252. Temperature = Temperature2 - TargetTemp + 37;
  1253. if (waitTime > 0) Thread.Sleep(waitTime);
  1254. //上盖板温度
  1255. Temperature1 = ComBin.ShangTemperatureWait(custom);
  1256. if (waitTime > 0) Thread.Sleep(waitTime);
  1257. //玻璃片下方温度
  1258. Temperature3 = ComBin.BoLiTemperatureWait(custom);
  1259. if (waitTime > 0) Thread.Sleep(waitTime);
  1260. //仓室压力
  1261. Pressure = ComBin.PressureWait(custom);
  1262. if (waitTime > 0) Thread.Sleep(waitTime);
  1263. }
  1264. public bool IsCCD()
  1265. {
  1266. var newList = Dish.Embryo.Where(x => x.state == (int)EmbryoState.None).Select(x => x.wellSn).ToList();
  1267. if (newList != null && newList.Any())
  1268. {
  1269. wellList.Clear();
  1270. foreach (var item in newList)
  1271. {
  1272. wellList.Add(item, LastAutoFocusTimeDic[item]);
  1273. }
  1274. return true;
  1275. }
  1276. return false;
  1277. }
  1278. int GetCCDAutoNum = 2;
  1279. /// <summary>
  1280. /// 是否自动对焦
  1281. /// </summary>
  1282. /// <returns></returns>
  1283. private bool StartAutoFocus()
  1284. {
  1285. if (!IsCCD())
  1286. {
  1287. HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[{House.houseSn}][{this.PortName}][胚胎不需要自动对焦(所有胚胎状态不为0) [tlSN:{Dish.tlSn}] [DishID:{Dish.id}]]", LogEnum.HouseInfo);
  1288. return false;
  1289. }
  1290. _autoFocusPhoto.Clear();
  1291. // ════════════════════════════════════════════════════════════════
  1292. // M2-06 场景B产线启用安全门(设备级开关 tl_setting.local_autofocus_enabled)。
  1293. // 依据:计划 M2-06 小节、03 §2(场景B 稳定后再启用)/§6(三上线前置:74000伪峰/真胚胎峰比/EEPROM回写)。
  1294. // 算法严谨性未在真机验证通过前,默认关闭(=0)走【降级】,避免错误对焦污染真实胚胎拍摄;
  1295. // 三前置有结论后人工置 1=启用,走下方 M2-03 本地四步标定对焦(场景B 正式上线)。
  1296. // 启用(=1):fall through → M2-03 本地 CalibrationEngine 对焦。
  1297. // 关闭(=0,默认安全):降级——按 scene=0 出厂基准 FocusZ 填 _autoFocusPhoto,沿用既有/基准位置拍照,
  1298. // 不做实际对焦;无基准的 well 跳过(不污染拍摄)。明确日志便于现场判断。
  1299. // ⚠ 待验证 V-060/V-061/V-062/V-063:场景B放皿自动对焦出图、降级行为正确不污染拍摄、开关生效、三前置关联。
  1300. // ════════════════════════════════════════════════════════════════
  1301. bool localAfEnabled = TLSetting != null && TLSetting.localAutofocusEnabled == 1;
  1302. if (!localAfEnabled)
  1303. {
  1304. // 安全门关闭:降级到基准/既有位置拍照(不做本地实际对焦)。
  1305. string tlSnDg = TLSetting != null ? TLSetting.tlSn : (Dish != null ? Dish.tlSn : null);
  1306. int filled = 0;
  1307. foreach (var well in wellList.Keys)
  1308. {
  1309. int? baseZ = AutofocusStore != null && AutofocusStore.BaselineReader != null
  1310. ? AutofocusStore.BaselineReader(tlSnDg, House.houseSn, well)
  1311. : null;
  1312. if (baseZ.HasValue && baseZ.Value > 0)
  1313. {
  1314. _autoFocusPhoto.Add(new HouseWellPhoto { wellSn = well, verticalMotorPosition = baseZ.Value });
  1315. filled++;
  1316. }
  1317. else
  1318. {
  1319. // M2-06 修复(A1):scene=0 基准取不到时,回退该 well 既有清晰拍摄 Z(eepromClearPosition,与 operate verNewValue 默认同源),避免默认安全门关闭时不拍照。
  1320. var wsDg = _wellSettings != null ? _wellSettings.FirstOrDefault(x => x.wellSn == well) : null;
  1321. if (wsDg != null && wsDg.eepromClearPosition > 0)
  1322. {
  1323. _autoFocusPhoto.Add(new HouseWellPhoto { wellSn = well, verticalMotorPosition = wsDg.eepromClearPosition });
  1324. filled++;
  1325. HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[{House.houseSn}][{this.PortName}][本地自动对焦未启用(安全门关闭),{well}号well无scene=0基准,回退eepromClearPosition={wsDg.eepromClearPosition}拍照] [tlSN:{tlSnDg}]", LogEnum.HouseInfo);
  1326. }
  1327. else
  1328. {
  1329. HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[{House.houseSn}][{this.PortName}][本地自动对焦未启用(安全门关闭),{well}号well无scene=0基准且无eepromClearPosition,跳过该well] [tlSN:{tlSnDg}]", LogEnum.HouseInfo);
  1330. }
  1331. }
  1332. }
  1333. if (filled > 0)
  1334. {
  1335. GetCCDDefeatNum = 0;
  1336. HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[{House.houseSn}][{this.PortName}][本地自动对焦未启用(安全门关闭),按scene=0基准位置拍照,已填充{filled}个well] [tlSN:{tlSnDg}] [DishID:{(Dish != null ? Dish.id : 0)}]", LogEnum.HouseInfo);
  1337. return true;
  1338. }
  1339. GetCCDDefeatNum++;
  1340. HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[{House.houseSn}][{this.PortName}][本地自动对焦未启用(安全门关闭),且无任何scene=0基准位置可用,本轮不拍照] [tlSN:{tlSnDg}] [DishID:{(Dish != null ? Dish.id : 0)}]", LogEnum.HouseInfo);
  1341. return false;
  1342. }
  1343. // ────────────────────────────────────────────────────────────────
  1344. // M2-03 本地自动对焦:对本舱 wellList 逐 well 调本地 CalibrationEngine 算 FocusZ,填 _autoFocusPhoto。
  1345. // (仅当 M2-06 安全门启用 local_autofocus_enabled=1 时执行;关闭时已在上方降级 return。)
  1346. // 取代原"先服务器(GetAutoFocusServiceEvent)后本地DB(GetAutoFocusDBEvent)"的云端/DB 取数链。
  1347. // 老事件 GetAutoFocusServiceEvent/GetAutoFocusDBEvent 声明保留(死代码隔离/兜底,默认不走)。
  1348. // verticalMotorPosition 承载 FocusZ 锚点(与原 clearPosition 同位,下游 :1555/:1707 按 wellSn 取)。
  1349. // HAL 借用:Acquire(AutoFocus) 前台优先,HAL 暂停本舱采集;using 归还后自动 ResumeCapture。
  1350. // ⚠ 待验证 V-046/V-049:本地对焦驱动拍照闭环、HAL 借用与采集互斥(关联 V-003/V-023)。
  1351. // 标定结果落 JSON/库镜像由 M2-04 完成(此处暂未接入存储入口)。
  1352. // ────────────────────────────────────────────────────────────────
  1353. try
  1354. {
  1355. var gate = HardwareAccessLayer.Instance.GetHouseGate(House.houseSn);
  1356. if (gate == null)
  1357. {
  1358. HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[{House.houseSn}][{this.PortName}][本地自动对焦:未取到舱借用闸门,跳过本轮] [tlSN:{Dish.tlSn}] [DishID:{Dish.id}]]", LogEnum.HouseInfo);
  1359. return false;
  1360. }
  1361. // 前台优先借用本舱(串口+相机),HAL 暂停 control 采集;拿不到则本轮跳过(让路)。
  1362. using (var lease = gate.Acquire(HardwareUser.AutoFocus, TLSetting != null ? Math.Max(30000, TLSetting.motorDelay * 16) : 30000))
  1363. {
  1364. if (lease == null)
  1365. {
  1366. HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[{House.houseSn}][{this.PortName}][本地自动对焦:申请硬件借用超时(采集占用),跳过本轮] [tlSN:{Dish.tlSn}] [DishID:{Dish.id}]]", LogEnum.HouseInfo);
  1367. return false;
  1368. }
  1369. if (lease.Serial == null || lease.Camera == null)
  1370. {
  1371. HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[{House.houseSn}][{this.PortName}][本地自动对焦:借用到的串口/相机为空,跳过本轮] [tlSN:{Dish.tlSn}] [DishID:{Dish.id}]]", LogEnum.HouseInfo);
  1372. return false;
  1373. }
  1374. var engine = new CalibrationEngine(lease.Serial, lease.Camera)
  1375. {
  1376. Log = msg => HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[{House.houseSn}][{this.PortName}][本地对焦]{msg}", LogEnum.HouseInfo)
  1377. };
  1378. foreach (var well in wellList.Keys)
  1379. {
  1380. if (IsStopClearest || FirstClearest) break;
  1381. try
  1382. {
  1383. // EEPROM 仅作扫描中心(参考),不进配置解析链、不回写(§2.5)。
  1384. int hpos = lease.Serial.ReadWellHorizontalPosWait(well);
  1385. int zZero = lease.Serial.ReadWellFocusZeroWait(well);
  1386. var wc = engine.CalibrateWell(well, Math.Max(0, hpos), Math.Max(0, zZero));
  1387. if (wc == null)
  1388. {
  1389. HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[{House.houseSn}][{this.PortName}][{well}号well本地对焦无结果,跳过该well]", LogEnum.HouseInfo);
  1390. continue;
  1391. }
  1392. _autoFocusPhoto.Add(new HouseWellPhoto { wellSn = well, verticalMotorPosition = wc.FocusZ });
  1393. // M2-04:标定结果落 JSON 真相源 + 镜像 house_autofocus_calibration。
  1394. // 日常对焦(放皿/门/定时触发)走 scene=1 append;调试页一键基准 scene=0(M2-05 接入)。
  1395. // 存储失败不崩对焦线程(CalibrationStore 内部已 try/catch 吞异常并记日志)。
  1396. try
  1397. {
  1398. AutofocusStore?.SaveCalibration(wc,
  1399. TLSetting != null ? TLSetting.tlSn : (Dish != null ? Dish.tlSn : null),
  1400. House.houseSn, well, scene: 1,
  1401. port: House.housePort, ccdSn: House.ccdSn);
  1402. }
  1403. catch (Exception exStore)
  1404. {
  1405. ExceptionLogEvent?.Invoke(exStore, $"[{House.houseSn}][{this.PortName}][{well}号well标定结果存储失败]", null, LogEnum.RunException);
  1406. }
  1407. }
  1408. catch (Exception exWell)
  1409. {
  1410. // 单 well 对焦失败不崩采集线程:记日志/告警,继续下一 well。
  1411. ExceptionLogEvent?.Invoke(exWell, $"[{House.houseSn}][{this.PortName}][{well}号well本地自动对焦失败]", null, LogEnum.RunException);
  1412. }
  1413. }
  1414. } // lease.Dispose() → 归还借用,HAL 恢复采集
  1415. }
  1416. catch (Exception ex)
  1417. {
  1418. // 本地对焦整体异常(借用/构造引擎等)不崩采集线程:记日志,本轮按失败处理。
  1419. ExceptionLogEvent?.Invoke(ex, $"[{House.houseSn}][{this.PortName}][本地自动对焦异常]", null, LogEnum.RunException);
  1420. return false;
  1421. }
  1422. if (_autoFocusPhoto != null && _autoFocusPhoto.Any())
  1423. {
  1424. GetCCDDefeatNum = 0;
  1425. return true;
  1426. }
  1427. GetCCDDefeatNum++;
  1428. HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[{House.houseSn}][{this.PortName}][第{GetCCDDefeatNum}次本地自动对焦未获取到位置数据] [tlSN:{Dish.tlSn}] [DishID:{Dish.id}]]", LogEnum.HouseInfo);
  1429. return false;
  1430. }
  1431. /// <summary>
  1432. /// 是否拍照
  1433. /// </summary>
  1434. /// <returns></returns>
  1435. private bool StartCCD()
  1436. {
  1437. if (!IsCCD())
  1438. {
  1439. HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[{House.houseSn}][{this.PortName}][胚胎不需要拍照(所有胚胎状态不为0) [tlSN:{Dish.tlSn}] [DishID:{Dish.id}]]", LogEnum.HouseInfo);
  1440. return false;
  1441. }
  1442. _ccdPhoto.Clear();
  1443. var resultDTO = GetCCDServiceEvent?.Invoke(House.houseSn, wellList);
  1444. if (resultDTO != null && resultDTO.complete == 0)
  1445. {
  1446. foreach (var item in resultDTO.positionVOList)
  1447. {
  1448. _ccdPhoto.Add(ConvertHelper.ConvertToHouseWellPhoto(item));
  1449. }
  1450. if (_ccdPhoto.Any())
  1451. {
  1452. GetCCDDefeatNum = 0;
  1453. return true;
  1454. }
  1455. else
  1456. {
  1457. GetCCDDefeatNum++;
  1458. HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[{House.houseSn}][{this.PortName}][第{GetCCDDefeatNum}次获取到拍照位置数据:服务器返回自动对焦完成,但是无拍照位置数据] [tlSN:{Dish.tlSn}] [DishID:{Dish.id}]]", LogEnum.HouseInfo);
  1459. }
  1460. }
  1461. else
  1462. {
  1463. if (resultDTO == null)
  1464. {
  1465. GetCCDDefeatNum++;
  1466. HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[{House.houseSn}][{this.PortName}][第{GetCCDDefeatNum}次获取到拍照位置数据:服务器返回空] [tlSN:{Dish.tlSn}] [DishID:{Dish.id}]]", LogEnum.HouseInfo);
  1467. }
  1468. else
  1469. {
  1470. if (resultDTO.complete == 1)
  1471. {
  1472. GetCCDDefeatNum++;
  1473. HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[{House.houseSn}][{this.PortName}][第{GetCCDDefeatNum}次获取拍照位置数据:服务器返回自动对焦未完成] [tlSN:{Dish.tlSn}] [DishID:{Dish.id}]]", LogEnum.HouseInfo);
  1474. }
  1475. }
  1476. }
  1477. if (GetCCDDefeatNum >= GetCCDAutoNum)
  1478. {
  1479. HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[{House.houseSn}][{this.PortName}][从本地数据库获取拍照位置数据] [tlSN:{Dish.tlSn}] [DishID:{Dish.id}]]", LogEnum.HouseInfo);
  1480. GetCCDDefeatNum = 0;
  1481. _ccdPhoto = GetCCDDBEvent?.Invoke(House.houseSn, wellList);
  1482. if (_ccdPhoto != null && _ccdPhoto.Any())
  1483. {
  1484. return true;
  1485. }
  1486. HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[{House.houseSn}][{this.PortName}][本地数据库获取拍照位置数据失败] [tlSN:{Dish.tlSn}] [DishID:{Dish.id}]]", LogEnum.HouseInfo);
  1487. }
  1488. return false;
  1489. }
  1490. #endregion
  1491. #region 自动对焦流程
  1492. private object AutoFocusWellsLock = new object();
  1493. /// <summary>
  1494. /// 单个自动对焦well
  1495. /// </summary>
  1496. public List<int> AutoFocusWells = new List<int>();
  1497. /// <summary>
  1498. /// 自动对焦流程
  1499. /// </summary>
  1500. /// <param name="commandSource"></param>
  1501. public bool GetClearest(CommandSource commandSource)
  1502. {
  1503. bool rs = false;
  1504. UpdateAutofocusStateEvent?.Invoke(true, House.houseSn);
  1505. if (AutoFocusWellAny())
  1506. {
  1507. rs = SingleEmbryoAutofocus(commandSource);
  1508. }
  1509. else
  1510. {
  1511. rs = AllEmbryoAutofocus(commandSource);
  1512. if (!rs)
  1513. {
  1514. AutoFocusWellClear();
  1515. }
  1516. }
  1517. if (rs)
  1518. {
  1519. UpdateAutofocusStateEvent?.Invoke(false, House.houseSn);
  1520. }
  1521. return rs;
  1522. }
  1523. /// <summary>
  1524. /// 自动对焦
  1525. /// </summary>
  1526. /// <param name="taskThread"></param>
  1527. /// <returns></returns>
  1528. /// <exception cref="NotImplementedException"></exception>
  1529. private bool AllEmbryoAutofocus(CommandSource commandSource)
  1530. {
  1531. LastRunTime = DateTime.Now;
  1532. if (House.openCcd == 0)
  1533. {
  1534. HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[{House.houseSn}][{PortName}][未打开相机,跳过自动对焦操作]", LogEnum.HouseInfo);
  1535. return true;
  1536. }
  1537. bool isSuccess = true;
  1538. Stopwatch AutofocusThreadStopwatch = Stopwatch.StartNew();
  1539. var custom = new CustomProtocol();//指令包
  1540. custom.commandSource = commandSource;
  1541. this.RunState = "自动对焦";
  1542. WorkingType = WorkingType.AutoFocusWorking;
  1543. var pictureId = 1;
  1544. try
  1545. {
  1546. int AutofocusEmbryoCount = 0;
  1547. foreach (var item in this.Dish.Embryo)
  1548. {
  1549. if (item.state == 0)
  1550. {
  1551. AutofocusEmbryoCount++;
  1552. }
  1553. }
  1554. var embryoList = this.Dish.Embryo.OrderBy(x => x.wellSn);
  1555. HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[{House.houseSn}][{this.PortName}][胚胎数:{AutofocusEmbryoCount}/{this.Dish.embryoCount}][自动对焦开始时间:{DateTime.Now}]", LogEnum.HouseInfo);
  1556. if (AutofocusEmbryoCount > 0)
  1557. {
  1558. HouseState(commandSource, custom, 0);
  1559. //水平电机复位运动
  1560. ComBin.HorizontalMotorResetWait(custom, TLSetting.motorDelay);
  1561. HouseState(commandSource, custom, 0);
  1562. if (isWuTu)
  1563. {
  1564. var startNoView = Camera.Usb2StartCapture();
  1565. HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[{House.houseSn}][{PortName}][无图预览开启结果:{startNoView}]", LogEnum.HouseInfo);
  1566. }
  1567. //打开CCD补光LED
  1568. ComBin.OpenLEDWait(custom);
  1569. foreach (var itemEmbryo in embryoList)
  1570. {
  1571. DateTime SavePictrueTime = DateTime.Now;
  1572. LastRunTime = DateTime.Now;
  1573. if (IsStopClearest || FirstClearest)
  1574. {
  1575. isSuccess = false;
  1576. break;
  1577. }
  1578. if (itemEmbryo.state != 0)
  1579. {
  1580. continue;
  1581. }
  1582. var currentHorSetting = _wellSettings.FirstOrDefault(x => x.wellSn == itemEmbryo.wellSn);
  1583. if (currentHorSetting == null)
  1584. {
  1585. HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[{House.houseSn}][{PortName}][未获取到{itemEmbryo.wellSn}号well的水平电机位置]", LogEnum.HouseInfo);
  1586. continue;
  1587. }
  1588. var currentAutoFocus = _autoFocusPhoto.FirstOrDefault(x => x.wellSn == itemEmbryo.wellSn);
  1589. if (currentAutoFocus == null)
  1590. {
  1591. HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[{House.houseSn}][{PortName}][未获取到{itemEmbryo.wellSn}号well的自动对焦位置]", LogEnum.HouseInfo);
  1592. continue;
  1593. }
  1594. if (IsDoorOpen == State.关闭 && TLSetting.pressureAlarmMin > Pressure)
  1595. AerationNew(commandSource, custom);
  1596. ComBin.HorizontalMotorAbsoluteWait(custom, TLSetting.motorDelay, currentHorSetting.horizontalMotorPosition);
  1597. HouseState(commandSource, custom, 0);
  1598. //垂直电机复位运动
  1599. ComBin.VerticalMotorResetWait(custom, TLSetting.motorDelay);
  1600. HouseState(commandSource, custom, 0);
  1601. // ────────────────────────────────────────────────────────────────
  1602. // M2-03 改造点2:N 层拍摄位置改用 M2-02 PhotoLayerCalculator(§2.4 公式 + §2.5 就近优先),
  1603. // 取代旧公式(verticalMotorPosition + spacePulse*i,无下移、值缺时硬编码128)。
  1604. // focusZ = currentAutoFocus.verticalMotorPosition (本地对焦算出的最清晰层锚点)
  1605. // 配置就近优先:well(currentHorSetting) 覆盖 → 设备级(TLSetting) → 缺层间距抛 FocusConfigMissingException
  1606. // 层间距未配置 → 写告警日志 + 本 well 本轮跳过(§2.5 不兜底)。
  1607. // ⚠ 待验证 V-046/V-048:层公式真机下发一致(关联 V-002/V-024)、配置缺失对焦失败不崩。
  1608. // ────────────────────────────────────────────────────────────────
  1609. int[] layerPositions;
  1610. try
  1611. {
  1612. var rawCfg = new FocusLayerRawConfig
  1613. {
  1614. WellSpacingPulse = currentHorSetting.focusLayerSpacingPulse,
  1615. WellLayerCount = currentHorSetting.focusLayerCount,
  1616. WellMoveDownLayer = currentHorSetting.moveDownLayer, // well 级下移复用 move_down_layer
  1617. DeviceSpacingPulse = TLSetting.focusLayerSpacingPulse,
  1618. DeviceLayerCount = TLSetting.focusLayerCount,
  1619. DeviceLayerDown = TLSetting.focusLayerDown,
  1620. TlSn = Dish?.tlSn,
  1621. HouseSn = House.houseSn,
  1622. WellSn = itemEmbryo.wellSn
  1623. };
  1624. var layerCfg = PhotoLayerCalculator.Resolve(rawCfg);
  1625. layerPositions = PhotoLayerCalculator.ComputeLayerPositions(
  1626. currentAutoFocus.verticalMotorPosition, layerCfg, TLSetting.verticalMotorPulseMax);
  1627. }
  1628. catch (FocusConfigMissingException exCfg)
  1629. {
  1630. // 配置缺失:本 well 本轮跳过,不用魔法数兜底、不崩采集线程(§2.5)。
  1631. HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[{House.houseSn}][{PortName}][{itemEmbryo.wellSn}号well对焦层配置缺失,跳过该well:{exCfg.Message}]", LogEnum.HouseInfo);
  1632. isSuccess = false;
  1633. continue;
  1634. }
  1635. int currentVer = 0;
  1636. int nextVer = 0;
  1637. bool isEnd = false;
  1638. for (int i = 0; i < layerPositions.Length; i++)
  1639. {
  1640. isEnd = false;
  1641. currentVer = 0;
  1642. nextVer = 0;
  1643. LastRunTime = DateTime.Now;
  1644. this.RunState = $"自动对焦({itemEmbryo.wellSn}-{i + 1})";
  1645. if (IsStopClearest || FirstClearest)
  1646. {
  1647. isSuccess = false;
  1648. break;
  1649. }
  1650. // M2-03:第 i 层绝对 Z 由 PhotoLayerCalculator 算出(含下移偏移 + verticalMotorPulseMax 钳位)。
  1651. currentVer = layerPositions[i];
  1652. nextVer = (i + 1 < layerPositions.Length) ? layerPositions[i + 1] : currentVer;
  1653. if (currentVer > TLSetting.verticalMotorPulseMax) break;
  1654. if (i == (layerPositions.Length - 1) || nextVer > TLSetting.verticalMotorPulseMax) isEnd = true;
  1655. ComBin.VerticalMotorAbsoluteWait(custom, TLSetting.motorDelay, currentVer, currentHorSetting.horizontalMotorPosition, pictureId++, itemEmbryo.wellSn, (i + 1));
  1656. HouseState(commandSource, custom, 0);
  1657. currentHorizontalMotor = ComBin.ReadHorizontalMotorWait(custom);
  1658. currentVerticalMotor = ComBin.ReadVerticalMotorWait(custom);
  1659. var AutofocusResult = Autofocus(custom, isEnd, itemEmbryo, SavePictrueTime, layerPositions.Length, (i + 1));
  1660. if (!AutofocusResult) isSuccess = false;
  1661. if (isEnd && AutofocusResult) LastAutoFocusTimeDic[itemEmbryo.wellSn] = SavePictrueTime;
  1662. HouseState(commandSource, custom, 0);
  1663. if (CCDState == 1)
  1664. {
  1665. HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[{itemEmbryo.wellSn}号well第{i + 1}层拍照异常,结束当前well自动对焦]", LogEnum.HouseInfo);
  1666. break;
  1667. }
  1668. }
  1669. if (CCDState == 1)
  1670. {
  1671. HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[{itemEmbryo.wellSn}号well拍照异常,终止全胚胎自动对焦流程]", LogEnum.HouseInfo);
  1672. break;
  1673. }
  1674. }
  1675. ComBin.CloseLEDWait(custom);
  1676. if (isWuTu)
  1677. {
  1678. var stopNoView = Camera.Usb2StopCapture();
  1679. HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[{House.houseSn}][{PortName}][无图预览关闭结果:{stopNoView}]", LogEnum.HouseInfo);
  1680. }
  1681. ComBin.HorizontalMotorResetWait(custom, TLSetting.motorDelay);
  1682. if (isSuccess) HouseState(commandSource, custom, 0);
  1683. }
  1684. }
  1685. catch (Exception ex)
  1686. {
  1687. ExceptionLogEvent?.Invoke(ex, $"[{House.houseSn}][{this.PortName}]自动对焦", null, LogEnum.RunException);
  1688. isSuccess = false;
  1689. }
  1690. finally
  1691. {
  1692. WorkingType = WorkingType.DoNothing;
  1693. HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[{House.houseSn}][{this.PortName}][自动对焦结果:{isSuccess}][自动对焦结束时间:{DateTime.Now}][全程耗时:{ivf_tl_UtilHelper.StringHelper.TimeToString(AutofocusThreadStopwatch.Elapsed)}]", LogEnum.HouseInfo);
  1694. AutofocusThreadStopwatch.Stop();
  1695. }
  1696. return isSuccess;
  1697. }
  1698. /// <summary>
  1699. /// 单个胚胎自动对焦
  1700. /// </summary>
  1701. /// <param name="item"></param>
  1702. /// <param name="custom"></param>
  1703. /// <returns></returns>
  1704. public bool SingleEmbryoAutofocus(CommandSource commandSource)
  1705. {
  1706. LastRunTime = DateTime.Now;
  1707. if (House.openCcd == 0)
  1708. {
  1709. HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[{House.houseSn}][{PortName}][未打开相机,跳过自动对焦操作]", LogEnum.HouseInfo);
  1710. return true;
  1711. }
  1712. bool isSuccess = true;
  1713. int currentVer = 0;
  1714. int nextVer = 0;
  1715. bool isEnd = false;
  1716. int pictureId = 1;
  1717. Stopwatch AutofocusThreadStopwatch = Stopwatch.StartNew();
  1718. try
  1719. {
  1720. this.RunState = "自动对焦";
  1721. WorkingType = WorkingType.AutoFocusWorking;
  1722. HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[{House.houseSn}][{this.PortName}][对焦well:{string.Join(",", AutoFocusWells)}][部分well自动对焦开始时间:{DateTime.Now}]", LogEnum.HouseInfo);
  1723. var custom = new CustomProtocol();
  1724. custom.commandSource = commandSource;
  1725. HouseState(commandSource, custom, 0);
  1726. //水平电机复位运动
  1727. ComBin.HorizontalMotorResetWait(custom, TLSetting.motorDelay);
  1728. HouseState(commandSource, custom, 0);
  1729. if (isWuTu)
  1730. {
  1731. var startNoView = Camera.Usb2StartCapture();
  1732. HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[{House.houseSn}][{PortName}][无图预览开启结果:{startNoView}]", LogEnum.HouseInfo);
  1733. }
  1734. ComBin.OpenLEDWait(custom);
  1735. do
  1736. {
  1737. DateTime SavePictrueTime = DateTime.Now;
  1738. LastRunTime = DateTime.Now;
  1739. int well = AutoFocusWellFirst();
  1740. var embryoItem = this.Dish.Embryo.FirstOrDefault(x => x.wellSn == well);
  1741. if (embryoItem == null)
  1742. {
  1743. HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[{House.houseSn}][{PortName}][当前well:{well}][没有找到对应的胚胎]", LogEnum.HouseInfo);
  1744. continue;
  1745. }
  1746. if (embryoItem.state != (int)EmbryoState.None)
  1747. {
  1748. HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[{House.houseSn}][{PortName}][当前well:{well}][胚胎状态不为0:{embryoItem.state},{embryoItem.id}]", LogEnum.HouseInfo);
  1749. continue;
  1750. }
  1751. if (IsStopClearest || FirstClearest)
  1752. {
  1753. isSuccess = false;
  1754. break;
  1755. }
  1756. var currentHorSetting = _wellSettings.FirstOrDefault(x => x.wellSn == embryoItem.wellSn);
  1757. if (currentHorSetting == null)
  1758. {
  1759. HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[{House.houseSn}][{PortName}][未获取到{embryoItem.wellSn}号well的水平电机位置]", LogEnum.HouseInfo);
  1760. continue;
  1761. }
  1762. var currentAutoFocus = _autoFocusPhoto.FirstOrDefault(x => x.wellSn == embryoItem.wellSn);
  1763. if (currentAutoFocus == null)
  1764. {
  1765. HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[{House.houseSn}][{PortName}][未获取到{embryoItem.wellSn}号well的自动对焦位置]", LogEnum.HouseInfo);
  1766. continue;
  1767. }
  1768. //水平电机绝对运动
  1769. ComBin.HorizontalMotorAbsoluteWait(custom, TLSetting.motorDelay, currentHorSetting.horizontalMotorPosition);
  1770. HouseState(commandSource, custom, 0);
  1771. //垂直电机复位运动
  1772. ComBin.VerticalMotorResetWait(custom, TLSetting.motorDelay);
  1773. HouseState(commandSource, custom, 0);
  1774. if (IsDoorOpen == State.关闭 && TLSetting.pressureAlarmMin > Pressure)
  1775. AerationNew(commandSource, custom);
  1776. if (currentAutoFocus.verticalMotorPosition >= TLSetting.verticalMotorPulseMax)
  1777. {
  1778. DeleteAutoFocusWell(embryoItem.wellSn);
  1779. HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[{House.houseSn}][{PortName}][{embryoItem.wellSn}号well自动对焦起点大于最高位置 {currentAutoFocus.verticalMotorPosition}>{TLSetting.verticalMotorPulseMax}]", LogEnum.HouseInfo);
  1780. }
  1781. else
  1782. {
  1783. // ────────────────────────────────────────────────────────────────
  1784. // V-050:本路径(单/部分胚胎手动对焦)N 层位置统一改用 M2-02 PhotoLayerCalculator
  1785. // (§2.4 公式 + §2.5 就近优先),与主路径 AllEmbryoAutofocus 一致,
  1786. // 取代旧公式(verticalMotorPosition + spacePulse*j / 硬编码128,无下移)。
  1787. // focusZ 锚点 = currentAutoFocus.verticalMotorPosition(本 well 对焦算出的清晰层)。
  1788. // 就近优先:well(currentHorSetting) 覆盖 → 设备级(TLSetting) → 缺层间距抛
  1789. // FocusConfigMissingException,本 well 跳过(continue 外层 well 循环),不兜底、不崩。
  1790. // ⚠ 待验证 V-050:与主路径层公式真机一致、配置缺失不崩。
  1791. // ────────────────────────────────────────────────────────────────
  1792. int[] layerPositions;
  1793. try
  1794. {
  1795. var rawCfg = new FocusLayerRawConfig
  1796. {
  1797. WellSpacingPulse = currentHorSetting.focusLayerSpacingPulse,
  1798. WellLayerCount = currentHorSetting.focusLayerCount,
  1799. WellMoveDownLayer = currentHorSetting.moveDownLayer, // well 级下移复用 move_down_layer
  1800. DeviceSpacingPulse = TLSetting.focusLayerSpacingPulse,
  1801. DeviceLayerCount = TLSetting.focusLayerCount,
  1802. DeviceLayerDown = TLSetting.focusLayerDown,
  1803. TlSn = Dish?.tlSn,
  1804. HouseSn = House.houseSn,
  1805. WellSn = embryoItem.wellSn
  1806. };
  1807. var layerCfg = PhotoLayerCalculator.Resolve(rawCfg);
  1808. layerPositions = PhotoLayerCalculator.ComputeLayerPositions(
  1809. currentAutoFocus.verticalMotorPosition, layerCfg, TLSetting.verticalMotorPulseMax);
  1810. }
  1811. catch (FocusConfigMissingException exCfg)
  1812. {
  1813. // 配置缺失:本 well 本轮跳过,不用魔法数兜底、不崩采集线程(§2.5)。
  1814. HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[{House.houseSn}][{PortName}][{embryoItem.wellSn}号well对焦层配置缺失,跳过该well:{exCfg.Message}]", LogEnum.HouseInfo);
  1815. isSuccess = false;
  1816. continue;
  1817. }
  1818. for (int j = 0; j < layerPositions.Length; j++)
  1819. {
  1820. isEnd = false;
  1821. currentVer = 0;
  1822. nextVer = 0;
  1823. LastRunTime = DateTime.Now;
  1824. if (IsStopClearest || FirstClearest)
  1825. {
  1826. isSuccess = false;
  1827. break;
  1828. }
  1829. this.RunState = $"自动对焦({embryoItem.wellSn}-{j + 1})";
  1830. // V-050:第 j 层绝对 Z 由 PhotoLayerCalculator 算出(含下移偏移 + verticalMotorPulseMax 钳位)。
  1831. currentVer = layerPositions[j];
  1832. nextVer = (j + 1 < layerPositions.Length) ? layerPositions[j + 1] : currentVer;
  1833. if (currentVer > TLSetting.verticalMotorPulseMax)
  1834. {
  1835. //DeleteAutoFocusWell(embryoItem.wellSn);
  1836. //LastAutoFocusTimeDic[embryoItem.wellSn] = SavePictrueTime;
  1837. break;
  1838. }
  1839. if (j == (layerPositions.Length - 1) || nextVer > TLSetting.verticalMotorPulseMax) isEnd = true;
  1840. ComBin.VerticalMotorAbsoluteWait(custom, TLSetting.motorDelay, currentVer, currentHorSetting.horizontalMotorPosition, pictureId++, embryoItem.wellSn, (j + 1));
  1841. HouseState(commandSource, custom, 0);
  1842. currentHorizontalMotor = ComBin.ReadHorizontalMotorWait(custom);
  1843. currentVerticalMotor = ComBin.ReadVerticalMotorWait(custom);
  1844. //抓图
  1845. var AutofocusResult = Autofocus(custom, isEnd, embryoItem, SavePictrueTime, layerPositions.Length, (j + 1));
  1846. HouseState(commandSource, custom, 0);
  1847. if (CCDState == 1)
  1848. {
  1849. HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[{embryoItem.wellSn}号well第{j + 1}层拍照异常,结束当前well自动对焦]", LogEnum.HouseInfo);
  1850. break;
  1851. }
  1852. if (isEnd)
  1853. {
  1854. DeleteAutoFocusWell(embryoItem.wellSn);
  1855. if (AutofocusResult) LastAutoFocusTimeDic[embryoItem.wellSn] = SavePictrueTime;
  1856. }
  1857. }
  1858. if (CCDState == 1)
  1859. {
  1860. isSuccess = false;
  1861. HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[{embryoItem.wellSn}号well拍照异常,终止部分胚胎自动对焦流程]", LogEnum.HouseInfo);
  1862. break;
  1863. }
  1864. }
  1865. } while (AutoFocusWellAny());
  1866. //关闭CCD补光LED
  1867. ComBin.CloseLEDWait(custom);
  1868. if (isWuTu)
  1869. {
  1870. var stopNoView = Camera.Usb2StopCapture();
  1871. HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[{House.houseSn}][{PortName}][无图预览关闭结果:{stopNoView}]", LogEnum.HouseInfo);
  1872. }
  1873. ComBin.HorizontalMotorResetWait(custom, TLSetting.motorDelay);
  1874. if (isSuccess)
  1875. {
  1876. HouseState(commandSource, custom, 0);
  1877. }
  1878. }
  1879. catch (Exception ex)
  1880. {
  1881. ExceptionLogEvent?.Invoke(ex, $"[{House.houseSn}][{this.PortName}]部分Well自动对焦", null, LogEnum.RunException);
  1882. isSuccess = false;
  1883. }
  1884. finally
  1885. {
  1886. WorkingType = WorkingType.DoNothing;
  1887. HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[{House.houseSn}][{this.PortName}][自动对焦结果:{isSuccess}][部分well自动对焦结束时间:{DateTime.Now}][全程耗时:{ivf_tl_UtilHelper.StringHelper.TimeToString(AutofocusThreadStopwatch.Elapsed)}]", LogEnum.HouseInfo);
  1888. AutofocusThreadStopwatch.Stop();
  1889. }
  1890. return isSuccess;
  1891. }
  1892. public void AddAutoFocusWell(int well)
  1893. {
  1894. lock (AutoFocusWellsLock)
  1895. {
  1896. if (!AutoFocusWells.Contains(well))
  1897. {
  1898. AutoFocusWells.Add(well);
  1899. }
  1900. }
  1901. }
  1902. public void DeleteAutoFocusWell(int well)
  1903. {
  1904. lock (AutoFocusWellsLock)
  1905. {
  1906. if (AutoFocusWells.Contains(well))
  1907. {
  1908. AutoFocusWells.Remove(well);
  1909. }
  1910. }
  1911. }
  1912. public bool AutoFocusWellAny()
  1913. {
  1914. lock (AutoFocusWellsLock)
  1915. {
  1916. return AutoFocusWells.Any();
  1917. }
  1918. }
  1919. public void AutoFocusWellClear()
  1920. {
  1921. lock (AutoFocusWellsLock)
  1922. {
  1923. AutoFocusWells.Clear();
  1924. }
  1925. }
  1926. public int AutoFocusWellFirst()
  1927. {
  1928. lock (AutoFocusWellsLock)
  1929. {
  1930. return AutoFocusWells.OrderBy(x => x).First();
  1931. }
  1932. }
  1933. #endregion
  1934. #region 拍照流程
  1935. /// <summary>
  1936. /// 拍照
  1937. /// </summary>
  1938. /// <exception cref="NotImplementedException"></exception>
  1939. public void ccdThreadFun()
  1940. {
  1941. LastRunTime = DateTime.Now;
  1942. if (House.openCcd == 0)
  1943. {
  1944. HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[{House.houseSn}][{PortName}][未打开相机,跳过拍照操作]", LogEnum.HouseInfo);
  1945. return;
  1946. }
  1947. var custom = new CustomProtocol();//指令包
  1948. custom.commandSource = CommandSource.ccdThread;
  1949. Stopwatch CCDThreadStopwatch = Stopwatch.StartNew();
  1950. var pictureId = 1;//图片编号,1-176号
  1951. try
  1952. {
  1953. this.RunState = "胚胎拍照";
  1954. WorkingType = WorkingType.CCDWorking;
  1955. int AutofocusEmbryoCount = 0;
  1956. foreach (var item in this.Dish.Embryo)
  1957. {
  1958. if (item.state == 0)
  1959. {
  1960. AutofocusEmbryoCount++;
  1961. }
  1962. }
  1963. CCDThreadStopwatch.Restart();
  1964. HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[{House.houseSn}][{PortName}][拍照开始时间:{DateTime.Now}][胚胎数:{AutofocusEmbryoCount}/{this.Dish.embryoCount}]", LogEnum.HouseInfo);
  1965. if (AutofocusEmbryoCount == 0) return;
  1966. HouseState(CommandSource.ccdThread, custom, 0);
  1967. //水平电机复位运动
  1968. ComBin.HorizontalMotorResetWait(custom, TLSetting.motorDelay);
  1969. HouseState(CommandSource.ccdThread, custom, 0);
  1970. var embryoList = this.Dish.Embryo.OrderBy(x => x.wellSn);
  1971. int currentPicNum = 1;
  1972. int allPicNum = House.photographPictureNumber;
  1973. if (isWuTu)
  1974. {
  1975. var startNoView = Camera.Usb2StartCapture();
  1976. HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[{House.houseSn}][{PortName}][无图预览开启结果:{startNoView}]", LogEnum.HouseInfo);
  1977. }
  1978. ComBin.OpenLEDWait(custom);
  1979. foreach (var item in embryoList)
  1980. {
  1981. LastRunTime = DateTime.Now;
  1982. if (IsStopCCD) break;
  1983. if (item.state != 0) continue;
  1984. var currentHorSetting = _wellSettings.FirstOrDefault(x => x.wellSn == item.wellSn);
  1985. if (currentHorSetting == null)
  1986. {
  1987. HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[{House.houseSn}][{PortName}][未获取到{item.wellSn}号well的水平电机位置]", LogEnum.HouseInfo);
  1988. continue;
  1989. }
  1990. if (IsDoorOpen == State.关闭 && TLSetting.pressureAlarmMin > Pressure) AerationNew(CommandSource.ccdThread, custom);
  1991. ComBin.HorizontalMotorAbsoluteWait(custom, TLSetting.motorDelay, currentHorSetting.horizontalMotorPosition);
  1992. HouseState(CommandSource.ccdThread, custom, 0);
  1993. //垂直电机复位运动
  1994. ComBin.VerticalMotorResetWait(custom, TLSetting.motorDelay);
  1995. HouseState(CommandSource.ccdThread, custom, 0);
  1996. currentPicNum = 1;
  1997. var newList = _ccdPhoto.Where(x => x.wellSn == item.wellSn && x.clearest <= (allPicNum - 1) / 2 && x.clearest >= (-(allPicNum - 1) / 2)).OrderBy(x => x.clearest).ToList();
  1998. DateTime SavePictrueTime = DateTime.Now;
  1999. int newListCount = newList.Count;
  2000. bool isEnd = false;
  2001. for (int i = 0; i < newListCount; i++)
  2002. {
  2003. isEnd = false;
  2004. LastRunTime = DateTime.Now;
  2005. if (IsStopCCD) break;
  2006. var motorItem = newList[i];
  2007. if (i < (newListCount - 1))
  2008. {
  2009. var nextItem = newList[i + 1];
  2010. if (nextItem.verticalMotorPosition > TLSetting.verticalMotorPulseMax) isEnd = true;
  2011. }
  2012. if (i == (newListCount - 1)) isEnd = true;
  2013. if (motorItem.verticalMotorPosition > TLSetting.verticalMotorPulseMax) break;
  2014. this.RunState = $"胚胎拍照({item.wellSn}-{currentPicNum})";
  2015. ComBin.VerticalMotorAbsoluteWait(custom, TLSetting.motorDelay, motorItem.verticalMotorPosition, currentHorSetting.horizontalMotorPosition, pictureId++, item.wellSn, motorItem.clearest);
  2016. currentHorizontalMotor = ComBin.ReadHorizontalMotorWait(custom);
  2017. currentVerticalMotor = ComBin.ReadVerticalMotorWait(custom);
  2018. Photograph(custom, motorItem.clearest, allPicNum, item, SavePictrueTime, motorItem.positionType, isEnd);
  2019. currentPicNum++;
  2020. HouseState(CommandSource.ccdThread, custom, 0);
  2021. if (CCDState == 1)
  2022. {
  2023. HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[{item.wellSn}号well第{i + 1}层拍照异常,结束当前well拍照]", LogEnum.HouseInfo);
  2024. break;
  2025. }
  2026. }
  2027. if (CCDState == 1)
  2028. {
  2029. HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[{item.wellSn}号well拍照异常,终止当前拍照流程]", LogEnum.HouseInfo);
  2030. break;
  2031. }
  2032. }
  2033. ComBin.CloseLEDWait(custom);
  2034. if (isWuTu)
  2035. {
  2036. var stopNoView = Camera.Usb2StopCapture();
  2037. HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[{House.houseSn}][{PortName}][无图预览关闭结果:{stopNoView}]", LogEnum.HouseInfo);
  2038. }
  2039. ComBin.HorizontalMotorResetWait(custom, TLSetting.motorDelay);
  2040. HouseState(CommandSource.ccdThread, custom, 0);
  2041. }
  2042. catch (Exception ex)
  2043. {
  2044. ExceptionLogEvent?.Invoke(ex, $"[{House.houseSn}][{PortName}]拍照线程", null, LogEnum.RunException);
  2045. }
  2046. finally
  2047. {
  2048. WorkingType = WorkingType.DoNothing;
  2049. HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[{House.houseSn}][{PortName}][拍照结束时间:{DateTime.Now}][共计{(pictureId - 1)}张图][全程耗时:{StringHelper.TimeToString(CCDThreadStopwatch.Elapsed)}]", LogEnum.HouseInfo);
  2050. CCDThreadStopwatch.Stop();
  2051. }
  2052. }
  2053. #endregion
  2054. #region 图片处理
  2055. /// <summary>
  2056. /// 抓图操作 0表示成功
  2057. /// </summary>
  2058. /// <returns></returns>
  2059. public int GetRgbDataFun(string content, int wellSn)
  2060. {
  2061. CustomProtocol custom = new CustomProtocol();
  2062. Stopwatch stopwatch = new Stopwatch();
  2063. try
  2064. {
  2065. if (House.openCcd == 0)
  2066. {
  2067. HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[仓室相机关闭,跳过抓图]", LogEnum.HouseRunRecord);
  2068. return -1;
  2069. }
  2070. HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[开始抓图][注:0表示成功]", LogEnum.HouseRunRecord);
  2071. int GetRgbData = -1;
  2072. bool isOpen = true;
  2073. for (int i = 1; i <= CCDFailedNumber; i++)
  2074. {
  2075. if (Dish == null || Dish.id <= 0)
  2076. {
  2077. HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[没有培养记录,中断拍照操作]", LogEnum.HouseRunRecord);
  2078. break;
  2079. }
  2080. if (isOpen)
  2081. {
  2082. if (isWuTu)
  2083. {
  2084. GetRgbData = Camera.GetRawData();//获取字节流
  2085. HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[第{i}次无图预览抓拍结果:{GetRgbData}][注:0表示成功]", LogEnum.HouseRunRecord);
  2086. if (GetRgbData == 0)
  2087. {
  2088. GetRgbData = Camera.RawToRgb();
  2089. HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[rawToRgb结果:{GetRgbData}][注:0表示成功]", LogEnum.HouseRunRecord);
  2090. }
  2091. }
  2092. else
  2093. {
  2094. if (CCDError)
  2095. {
  2096. GetRgbData = 20;
  2097. }
  2098. else
  2099. {
  2100. GetRgbData = Camera.GetRgbData();//获取字节流
  2101. }
  2102. HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[第{i}次抓拍结果:{GetRgbData}][注:0表示成功]", LogEnum.HouseRunRecord);
  2103. }
  2104. }
  2105. if (GetRgbData == 0)
  2106. {
  2107. if (CCDState != 0)
  2108. {
  2109. CCDState = 0;
  2110. CCDAutoStopwatch.Reset();
  2111. HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[拍照成功,取消拍照异常报警]", LogEnum.HouseInfo);
  2112. CCDStateEvent?.Invoke(House.houseSn, CCDState, ErrorWell);
  2113. //HouseStateEvent?.Invoke(House.houseSn, -1, -1, CCDState, ErrorWell, -1);
  2114. }
  2115. break;
  2116. }
  2117. if (i == CCDFailedNumber)
  2118. {
  2119. if (CCDState != 1)
  2120. {
  2121. CCDState = 1;
  2122. CCDAutoStopwatch.Start();
  2123. HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[拍照连续失败{CCDFailedNumber}次,拍照异常报警]", LogEnum.HouseInfo);
  2124. TLLogEvent?.Invoke($"[拍照连续失败{CCDFailedNumber}次,拍照异常报警]", LogEnum.RunError);
  2125. CCDStateEvent?.Invoke(House.houseSn, CCDState, wellSn);
  2126. //HouseStateEvent?.Invoke(House.houseSn, -1, -1, CCDState, wellSn, -1);
  2127. ErrorWell = wellSn;
  2128. }
  2129. }
  2130. else
  2131. {
  2132. //this.RunState = $"拍照失败,等待{CCDFailedWaitTime / 1000}S";
  2133. this.RunState = $"take photos failed,wait for {CCDFailedWaitTime / 1000} S";
  2134. stopwatch.Restart();
  2135. do
  2136. {
  2137. HouseState(CommandSource.ccdThread, custom, 500);
  2138. } while (stopwatch.ElapsedMilliseconds < CCDFailedWaitTime);
  2139. }
  2140. //HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[第{i}次关闭相机结果:{CloseCamera(content)}]", LogEnum.HouseRunRecord);
  2141. //isOpen = OpenCamera(content);
  2142. //HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[第{i}次开启相机结果:{isOpen}]", LogEnum.HouseRunRecord);
  2143. }
  2144. return GetRgbData;
  2145. }
  2146. catch (Exception ex)
  2147. {
  2148. ExceptionLogEvent?.Invoke(ex, $"[{House.houseSn}][{PortName}]抓图", null, LogEnum.RunException);
  2149. return -1;
  2150. }
  2151. finally
  2152. {
  2153. stopwatch.Stop();
  2154. }
  2155. }
  2156. /// <summary>
  2157. /// 新的抓图操作,0表示成功
  2158. /// </summary>
  2159. /// <param name="content"></param>
  2160. /// <param name="wellSn"></param>
  2161. /// <returns></returns>
  2162. public int GetRgbDataFunNew(string content, int wellSn)
  2163. {
  2164. CustomProtocol custom = new CustomProtocol();
  2165. Stopwatch stopwatch = new Stopwatch();
  2166. int rsData = -1;
  2167. try
  2168. {
  2169. if (House.openCcd == 0)
  2170. {
  2171. HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[仓室相机关闭,跳过抓图]", LogEnum.HouseRunRecord);
  2172. return -1;
  2173. }
  2174. HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[开始抓图][注:0表示成功]", LogEnum.HouseRunRecord);
  2175. int GetRgbData = -1;
  2176. bool isOpen = true;
  2177. for (int i = 1; i <= CCDFailedNumber; i++)
  2178. {
  2179. if (Dish == null || Dish.id <= 0)
  2180. {
  2181. HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[没有培养记录,中断拍照操作]", LogEnum.HouseRunRecord);
  2182. break;
  2183. }
  2184. if (isOpen && Camera != null && Camera.IsStart)
  2185. {
  2186. if (isWuTu)
  2187. {
  2188. GetRgbData = Camera.GetRawData();//获取字节流
  2189. HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[第{i}次无图预览抓拍结果:{GetRgbData}][注:0表示成功]", LogEnum.HouseRunRecord);
  2190. if (GetRgbData == 0)
  2191. {
  2192. GetRgbData = Camera.RawToRgb();
  2193. HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[rawToRgb结果:{GetRgbData}][注:0表示成功]", LogEnum.HouseRunRecord);
  2194. if (GetRgbData != 0)
  2195. {
  2196. TLLogEvent?.Invoke($"{content}[第{i}次rawToRgb结果:{GetRgbData}][注:0表示成功]", LogEnum.RunError);
  2197. }
  2198. else
  2199. {
  2200. Camera.UpdataSourceBuffer();
  2201. }
  2202. }
  2203. else
  2204. {
  2205. TLLogEvent?.Invoke($"{content}[第{i}次无图预览抓拍结果:{GetRgbData}][注:0表示成功]", LogEnum.RunError);
  2206. }
  2207. }
  2208. else
  2209. {
  2210. if (CCDError)
  2211. {
  2212. GetRgbData = 20;
  2213. }
  2214. else
  2215. {
  2216. GetRgbData = Camera.GetRgbData();//获取字节流
  2217. }
  2218. HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[第{i}次抓拍结果:{GetRgbData}][注:0表示成功]", LogEnum.HouseRunRecord);
  2219. if (GetRgbData != 0)
  2220. {
  2221. TLLogEvent?.Invoke($"{content}[第{i}次抓拍结果:{GetRgbData}][注:0表示成功]", LogEnum.RunError);
  2222. }
  2223. else
  2224. {
  2225. Camera.UpdataSourceBuffer();
  2226. }
  2227. }
  2228. }
  2229. if (GetRgbData == 0 && Camera.CheckRgbData())
  2230. {
  2231. HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[第{i}次抓拍校验成功]", LogEnum.HouseRunRecord);
  2232. rsData = 0;
  2233. if (CCDState != 0)
  2234. {
  2235. CCDState = 0;
  2236. CCDAutoStopwatch.Reset();
  2237. HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[拍照成功,取消拍照异常报警]", LogEnum.HouseInfo);
  2238. CCDStateEvent?.Invoke(House.houseSn, CCDState, ErrorWell);
  2239. //HouseStateEvent?.Invoke(House.houseSn, -1, -1, CCDState, ErrorWell, -1);
  2240. }
  2241. break;
  2242. }
  2243. else
  2244. {
  2245. isOpen = false;
  2246. HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[第{i}次抓拍校验失败][GetRgbData:{GetRgbData}][Camera != null:{Camera != null}]", LogEnum.HouseRunRecord);
  2247. if (i == CCDFailedNumber)
  2248. {
  2249. if (CCDState != 1)
  2250. {
  2251. CCDState = 1;
  2252. CCDAutoStopwatch.Start();
  2253. HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[拍照连续失败{CCDFailedNumber}次,拍照异常报警]", LogEnum.HouseInfo);
  2254. TLLogEvent?.Invoke($"[{content}][拍照连续失败{CCDFailedNumber}次,拍照异常报警]", LogEnum.RunError);
  2255. CCDStateEvent?.Invoke(House.houseSn, CCDState, wellSn);
  2256. //HouseStateEvent?.Invoke(House.houseSn, -1, -1, CCDState, wellSn, -1);
  2257. ErrorWell = wellSn;
  2258. }
  2259. }
  2260. else
  2261. {
  2262. //this.RunState = $"拍照失败,等待{CCDFailedWaitTime / 1000}S";
  2263. //this.RunState = $"take photos failed,wait for{CCDFailedWaitTime / 1000} S";
  2264. this.RunState = $"{TakePhotoFailed}{CCDFailedWaitTime / 1000}S";
  2265. stopwatch.Restart();
  2266. do
  2267. {
  2268. HouseState(CommandSource.ccdThread, custom, 500);
  2269. } while (stopwatch.ElapsedMilliseconds < CCDFailedWaitTime);
  2270. if (Camera != null && Camera.IsInit && Camera.GetCamNum() == CamNum)
  2271. {
  2272. HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[第{i}次关闭相机结果:{CloseCamera(content)}]", LogEnum.HouseRunRecord);
  2273. isOpen = OpenCamera(content);
  2274. HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[第{i}次开启相机结果:{isOpen}]", LogEnum.HouseRunRecord);
  2275. }
  2276. else
  2277. {
  2278. if (Camera == null)
  2279. {
  2280. HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"{content}[相机不满足重新加载条件][Camera == null]", LogEnum.HouseRunRecord);
  2281. }
  2282. else
  2283. {
  2284. HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"{content}[相机不满足重新加载条件][Camera.IsInit:{Camera.IsInit}][{CamNum}]", LogEnum.HouseRunRecord);
  2285. }
  2286. }
  2287. }
  2288. }
  2289. }
  2290. return rsData;
  2291. }
  2292. catch (Exception ex)
  2293. {
  2294. ExceptionLogEvent?.Invoke(ex, $"[{House.houseSn}][{PortName}]抓图", null, LogEnum.RunException);
  2295. return -1;
  2296. }
  2297. finally
  2298. {
  2299. stopwatch.Stop();
  2300. }
  2301. }
  2302. /// <summary>
  2303. /// 拍照抓图
  2304. /// </summary>
  2305. public void Photograph(CustomProtocol customProtocol, int currentPicNum, int allPicNum, Embryo itemEmbryo, DateTime savePictureTime, int positionType, bool isEnd)
  2306. {
  2307. Stopwatch CCDOperateStopwatch = Stopwatch.StartNew();
  2308. string content = null;
  2309. bool isSuccess = true;
  2310. try
  2311. {
  2312. content = $"[{House.houseSn}][{PortName}][{customProtocol.commandNumber}][{customProtocol.commandType.ToString()}][图片ID:{customProtocol.pictureId}][图片位置:{customProtocol.well}-{currentPicNum}][水平电机:{customProtocol.HorizontalMotorPulse}][垂直电机:{customProtocol.VerticalMotorPulse}][下位机水平:{currentHorizontalMotor}][下位机垂直:{currentVerticalMotor}]";
  2313. if (customProtocol.HorizontalMotorPulse != currentHorizontalMotor || customProtocol.VerticalMotorPulse != currentVerticalMotor)
  2314. {
  2315. TLLogEvent?.Invoke($"{content}垂直电机或水平电机位置和下位机位置不一致", LogEnum.RunError);
  2316. }
  2317. HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"{content}[胚胎拍照图片处理开始]", LogEnum.HouseRunRecord);
  2318. if (itemEmbryo.state != 0)
  2319. {
  2320. HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"{content}[当前胚胎状态:{itemEmbryo.state},跳过抓拍]", LogEnum.HouseRunRecord);
  2321. return;
  2322. }
  2323. var startElapsed = CCDOperateStopwatch.Elapsed;
  2324. int GetRgbData = -1;
  2325. GetRgbData = GetRgbDataFunNew(content, itemEmbryo.wellSn);
  2326. var endElapsed = CCDOperateStopwatch.Elapsed;
  2327. HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[抓图耗时:{StringHelper.TimeToString(endElapsed - startElapsed)}][抓图结果:{GetRgbData}]", LogEnum.HouseRunRecord);
  2328. if (GetRgbData != 0)
  2329. {
  2330. TLLogEvent?.Invoke($"{content}抓图失败[抓图结果:{GetRgbData}]", LogEnum.RunError);
  2331. return;
  2332. }
  2333. startElapsed = CCDOperateStopwatch.Elapsed;
  2334. string path = PathHelper.GetEmbryoPicSaveDirectory();
  2335. PathHelper.MakeDirectory(path);
  2336. string fileName = $"{House.houseSn}_{itemEmbryo.wellSn}_{Dish.id}_{itemEmbryo.id}_{DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss")}_{customProtocol.HorizontalMotorPulse}_{customProtocol.VerticalMotorPulse}.jpg";
  2337. string fullName = $"{path}{fileName}";
  2338. var imageDTO = GetImageDTO(itemEmbryo, fileName, path, savePictureTime.ToString("yyyy-MM-dd HH:mm:ss"), 0, allPicNum, currentPicNum, customProtocol.VerticalMotorPulse, customProtocol.HorizontalMotorPulse, positionType == 1 ? 1 : 0, isEnd);
  2339. SavePicDbEvent?.Invoke(imageDTO);
  2340. int saveResult = SaveImage(Camera.SourceBuffer, House.ccdWidth, House.ccdHeight, fullName);
  2341. endElapsed = CCDOperateStopwatch.Elapsed;
  2342. HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[图片保存耗时:{StringHelper.TimeToString(endElapsed - startElapsed)}][图片保存结果:{saveResult}][注:0表示失败,-1表示异常]", LogEnum.HouseRunRecord);
  2343. if (saveResult != 1)
  2344. {
  2345. TLLogEvent?.Invoke($"{content}图片保存失败[图片保存结果:{saveResult}][注:0表示失败,-1表示异常]", LogEnum.RunError);
  2346. return;
  2347. }
  2348. var imageBytes = AivfoHelper.GetImageData1(fullName);
  2349. if (imageBytes == null)
  2350. {
  2351. TLLogEvent?.Invoke($"{content}图片不存在:{fullName}", LogEnum.RunError);
  2352. return;
  2353. }
  2354. imageDTO.ImageData = ByteString.CopyFrom(imageBytes);
  2355. UploadImageEvent?.Invoke(imageDTO);
  2356. }
  2357. catch (Exception ex)
  2358. {
  2359. ExceptionLogEvent?.Invoke(ex, $"[{House.houseSn}][{PortName}][{customProtocol.commandNumber}][{customProtocol.commandType.ToString()}]胚胎拍照图片处理", content, LogEnum.RunException);
  2360. isSuccess = false;
  2361. }
  2362. finally
  2363. {
  2364. HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"{content}[图片处理结果:{isSuccess}][胚胎拍照图片处理耗时:{StringHelper.TimeToString(CCDOperateStopwatch.Elapsed)}][End]", LogEnum.HouseRunRecord);
  2365. CCDOperateStopwatch.Stop();
  2366. }
  2367. }
  2368. /// <summary>
  2369. /// 自动对焦抓图
  2370. /// </summary>
  2371. /// <param name="customProtocol">指令数据</param>
  2372. /// <param name="isEnd">是否是最后一张</param>
  2373. /// <param name="leftOffset">左边裁剪像素</param>
  2374. /// <param name="bttOffset">下边裁剪像素</param>
  2375. /// <param name="itemEmbryo">当前抓拍胚胎</param>
  2376. /// <param name="saveDateTime">本轮自动对焦开始时间</param>
  2377. public bool Autofocus(CustomProtocol customProtocol, bool isEnd, Embryo itemEmbryo, DateTime saveDateTime, int totlayer, int currlayer)
  2378. {
  2379. Stopwatch AutofocusOperateStopwatch = Stopwatch.StartNew();
  2380. string content = null;
  2381. bool isSuccess = true;
  2382. try
  2383. {
  2384. int currentver = customProtocol.VerticalMotorPulse;
  2385. content = $"[{House.houseSn}][{PortName}][{customProtocol.commandNumber}][{customProtocol.commandType.ToString()}][图片编号:{customProtocol.pictureId}][图片位置:{customProtocol.well}-{customProtocol.focal}][水平电机:{customProtocol.HorizontalMotorPulse}][垂直电机:{customProtocol.VerticalMotorPulse}][下位机水平:{currentHorizontalMotor}][下位机垂直:{currentVerticalMotor}]";
  2386. if (customProtocol.HorizontalMotorPulse != currentHorizontalMotor || customProtocol.VerticalMotorPulse != currentVerticalMotor)
  2387. {
  2388. TLLogEvent?.Invoke($"{content}垂直电机或水平电机位置和下位机位置不一致", LogEnum.RunError);
  2389. }
  2390. HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"{content}[自动对焦图片处理开始]", LogEnum.HouseRunRecord);
  2391. if (itemEmbryo.state != 0)
  2392. {
  2393. HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"{content}[当前胚胎状态:{itemEmbryo.state},跳过抓拍]", LogEnum.HouseRunRecord);
  2394. return false;
  2395. }
  2396. var startElapsed = AutofocusOperateStopwatch.Elapsed;
  2397. int GetRgbData = GetRgbDataFunNew(content, itemEmbryo.wellSn);
  2398. var endElapsed = AutofocusOperateStopwatch.Elapsed;
  2399. HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[自动对焦抓图耗时:{StringHelper.TimeToString(endElapsed - startElapsed)}][抓图结果:{GetRgbData}]", LogEnum.HouseRunRecord);
  2400. if (GetRgbData != 0)
  2401. {
  2402. TLLogEvent?.Invoke($"{content}自动对焦抓图失败", LogEnum.RunError);
  2403. return false;
  2404. }
  2405. startElapsed = AutofocusOperateStopwatch.Elapsed;
  2406. var path = PathHelper.GetAutoFocusSaveDirectory();
  2407. PathHelper.MakeDirectory(path);//创建目录
  2408. string fileName = $"{House.houseSn}_{itemEmbryo.wellSn}_{Dish.id}_{itemEmbryo.id}_{DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss")}_{customProtocol.HorizontalMotorPulse}_{currentver}.jpg";
  2409. string fullName = $"{path}{fileName}";
  2410. var imagedto = GetImageDTO(itemEmbryo, fileName, path, saveDateTime.ToString("yyyy-MM-dd HH:mm:ss"), 1, totlayer, currlayer, currentver, customProtocol.HorizontalMotorPulse, 0, isEnd);
  2411. SavePicDbEvent?.Invoke(imagedto);
  2412. int score = SaveImage(Camera.SourceBuffer, House.ccdWidth, House.ccdHeight, fullName);
  2413. endElapsed = AutofocusOperateStopwatch.Elapsed;
  2414. HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[图片保存耗时:{StringHelper.TimeToString(endElapsed - startElapsed)}][图片保存结果:{score}][注:0表示失败,-1表示异常]", LogEnum.HouseRunRecord);
  2415. if (score != 1)
  2416. {
  2417. TLLogEvent?.Invoke($"{content}图片保存失败[图片保存结果:{score}][注:0表示失败,-1表示异常]", LogEnum.RunError);
  2418. return false;
  2419. }
  2420. var imageBytes = AivfoHelper.GetImageData1(fullName);
  2421. if (imageBytes == null)
  2422. {
  2423. TLLogEvent?.Invoke($"{content}图片不存在:{fullName}", LogEnum.RunError);
  2424. return false;
  2425. }
  2426. imagedto.ImageData = ByteString.CopyFrom(imageBytes);
  2427. UploadImageEvent?.Invoke(imagedto);
  2428. return true;
  2429. }
  2430. catch (Exception ex)
  2431. {
  2432. ExceptionLogEvent?.Invoke(ex, $"[{House.houseSn}][{PortName}][{customProtocol.commandNumber}][{customProtocol.commandType.ToString()}]自动对焦图片处理", null, LogEnum.RunException);
  2433. isSuccess = false;
  2434. return false;
  2435. }
  2436. finally
  2437. {
  2438. HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"{content}[图片处理结果:{isSuccess}][自动对焦图片处理耗时:{StringHelper.TimeToString(AutofocusOperateStopwatch.Elapsed)}]", LogEnum.HouseRunRecord);
  2439. AutofocusOperateStopwatch.Stop();
  2440. }
  2441. }
  2442. /// <summary>
  2443. /// 抠图 0表示失败 -1表示异常
  2444. /// </summary>
  2445. /// <param name="imgData"></param>
  2446. /// <param name="width"></param>
  2447. /// <param name="height"></param>
  2448. /// <param name="path"></param>
  2449. /// <param name="sourcePath"></param>
  2450. /// <param name="isSave"></param>
  2451. /// <param name="aa"></param>
  2452. /// <param name="letoffset"></param>
  2453. /// <returns></returns>
  2454. public string ImageProcessing(byte[] imgData, int width, int height, string path, string sourcePath, int isSave, string wellname, string devTime, int leftOffset, int bttOffset)
  2455. {
  2456. try
  2457. {
  2458. IntPtr ptr = AivfoHelper.ImageProcessing(imgData, width, height, path, sourcePath, isSave, wellname, devTime, leftOffset, bttOffset);
  2459. if (ptr == IntPtr.Zero)
  2460. {
  2461. return null;
  2462. }
  2463. else
  2464. {
  2465. return Marshal.PtrToStringAnsi(ptr);
  2466. }
  2467. }
  2468. catch (Exception ex)
  2469. {
  2470. ExceptionLogEvent?.Invoke(ex, $"[{House.houseSn}][{PortName}]图片抠图", $"[sourcePath={sourcePath}][{leftOffset} {bttOffset} 0][isSave={isSave}]", LogEnum.RunException);
  2471. return null;
  2472. }
  2473. }
  2474. /// <summary>
  2475. /// 保存图片 1是成功 0失败
  2476. /// </summary>
  2477. /// <param name="bitmapData"></param>
  2478. /// <param name="width"></param>
  2479. /// <param name="height"></param>
  2480. /// <param name="fileName"></param>
  2481. /// <returns></returns>
  2482. public int SaveImage(byte[] bitmapData, int width, int height, string fileName)
  2483. {
  2484. try
  2485. {
  2486. int a = AivfoHelper.Save2(bitmapData, width, height, fileName);
  2487. return a;
  2488. }
  2489. catch (Exception ex)
  2490. {
  2491. ExceptionLogEvent?.Invoke(ex, $"[{House.houseSn}][{PortName}]图片保存", $"[fileName:{fileName}]", LogEnum.RunException);
  2492. return -1;
  2493. }
  2494. }
  2495. /// <summary>
  2496. /// 评分 0表示失败 -1表示异常
  2497. /// </summary>
  2498. /// <param name="bitmapData"></param>
  2499. /// <param name="w"></param>
  2500. /// <param name="h"></param>
  2501. /// <param name="dir"></param>
  2502. /// <param name="id"></param>
  2503. /// <param name="dir1"></param>
  2504. /// <param name="letoffset"></param>
  2505. /// <returns></returns>
  2506. public double GetScore(byte[] bitmapData, int w, int h, string dir, int id, string dir1, int leftOffset, int bttOffset)
  2507. {
  2508. try
  2509. {
  2510. var a = AivfoHelper.GetImageScoreAndSaveImage(bitmapData, w, h, dir, id, dir1, leftOffset, bttOffset);
  2511. return a;
  2512. }
  2513. catch (Exception ex)
  2514. {
  2515. ExceptionLogEvent?.Invoke(ex, $"[{House.houseSn}][{PortName}]图片打分", $"[dir1={dir1}][{leftOffset} {bttOffset}]", LogEnum.RunException);
  2516. return -1d;
  2517. }
  2518. }
  2519. /// <summary>
  2520. /// 抠图失败处理 0表示失败 -1表示异常
  2521. /// </summary>
  2522. /// <returns></returns>
  2523. public int KouTuShiBai(string fileName, string wellName, string fayuString)
  2524. {
  2525. try
  2526. {
  2527. int i = AivfoHelper.Save1(fileName, wellName, fayuString);
  2528. return i;
  2529. }
  2530. catch (Exception ex)
  2531. {
  2532. ExceptionLogEvent?.Invoke(ex, $"[{House.houseSn}][{PortName}]抠图失败处理", null, LogEnum.RunException);
  2533. return -1;
  2534. }
  2535. }
  2536. /// <summary>
  2537. /// 获取图片信息
  2538. /// </summary>
  2539. /// <param name="embryo">当前胚胎</param>
  2540. /// <param name="fileName">图片名称</param>
  2541. /// <param name="filePath">图片路径</param>
  2542. /// <param name="dateTime">自动对焦时间/图片时间</param>
  2543. /// <param name="PhotographType">1 自动对焦 0 CCD拍照</param>
  2544. /// <param name="TotalLayer">总层数</param>
  2545. /// <param name="PictureLayer">当前层数</param>
  2546. /// <param name="ver">垂直电机位置</param>
  2547. /// <param name="hor">水平电机位置</param>
  2548. /// <param name="Clearest">0不是 1最清晰</param>
  2549. /// <param name="isend">是否结束</param>
  2550. /// <returns></returns>
  2551. private ImageDTO GetImageDTO(Embryo embryo, string fileName, string filePath, string dateTime, int PhotographType, int TotalLayer, int PictureLayer, int ver, int hor, int Clearest, bool isend)
  2552. {
  2553. try
  2554. {
  2555. ImageDTO imageDTO = new ImageDTO();
  2556. imageDTO.CcdSn = House.ccdSn;
  2557. imageDTO.Clearest = Clearest;
  2558. imageDTO.EmbryoCultureRecordId = (ulong)embryo.dishId;
  2559. imageDTO.EmbryoId = (ulong)embryo.id;
  2560. imageDTO.End = isend ? 1 : 0;
  2561. imageDTO.FertilizationTime = embryo.startTime.ToString("yyyy-MM-dd HH:mm:ss");
  2562. imageDTO.HorizontalPosition = hor;
  2563. imageDTO.HouseSn = House.houseSn;
  2564. imageDTO.ImageTime = dateTime;
  2565. imageDTO.PhotographType = PhotographType;
  2566. imageDTO.PictureLayer = PictureLayer;
  2567. imageDTO.ShootingPosition = ver;
  2568. imageDTO.SourceImageName = fileName;
  2569. imageDTO.SourceImagePath = filePath;
  2570. imageDTO.SourceImageWidth = House.ccdWidth;
  2571. imageDTO.SourceImageHeight = House.ccdHeight;
  2572. imageDTO.TlSn = TLSetting.tlSn;
  2573. imageDTO.WellSn = embryo.wellSn;
  2574. imageDTO.TotalLayer = TotalLayer;
  2575. return imageDTO;
  2576. }
  2577. catch (Exception ex)
  2578. {
  2579. ExceptionLogEvent?.Invoke(ex, $"GetImageDTO", null, LogEnum.RunException);
  2580. return null;
  2581. }
  2582. }
  2583. #endregion
  2584. #region 状态变化
  2585. /// <summary>
  2586. /// 舱门状态变化
  2587. /// </summary>
  2588. public void DoorStateChanged(State newDoorValue)
  2589. {
  2590. if (newDoorValue == State.关闭)
  2591. {
  2592. HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[{House.houseSn}][{this.PortName}][关闭舱门:{DateTime.Now}]", LogEnum.HouseInfo);
  2593. //关闭舱门自动对焦
  2594. FirstClearest = true;
  2595. IsStopClearest = false;
  2596. IsStopCCD = false;
  2597. IsStopAirSwap = false;
  2598. StartAir = true;
  2599. }
  2600. else
  2601. {
  2602. HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[{House.houseSn}][{this.PortName}][打开舱门:{DateTime.Now}]", LogEnum.HouseInfo);
  2603. IsStopClearest = true;
  2604. IsStopCCD = true;
  2605. IsStopAirSwap = true;
  2606. AutoFocusWellClear();
  2607. }
  2608. }
  2609. /// <summary>
  2610. /// 开始平衡
  2611. /// </summary>
  2612. public void StartBlance(Balance _balance)
  2613. {
  2614. FirstClearest = true;
  2615. FirstAir = true;
  2616. IsStopClearest = false;
  2617. IsStopCCD = false;
  2618. IsStopAirSwap = false;
  2619. this.Balance = _balance;
  2620. }
  2621. /// <summary>
  2622. /// 结束平衡
  2623. /// </summary>
  2624. public void StopBlance()
  2625. {
  2626. IsStopClearest = true;
  2627. IsStopCCD = true;
  2628. IsStopAirSwap = true;
  2629. Balance = null;
  2630. //排气报警
  2631. HouseStateEvent?.Invoke(House.houseSn, houseState, -1, -1, -1, 0);
  2632. }
  2633. /// <summary>
  2634. /// 开始培养
  2635. /// </summary>
  2636. public void StartDish(Dish newDish)
  2637. {
  2638. FirstClearest = true;
  2639. IsStopClearest = false;
  2640. IsStopCCD = false;
  2641. IsStopAirSwap = false;
  2642. Dish = newDish;
  2643. AutoFocusWellClear();
  2644. if (Balance != null && Balance.id > 0) Balance = null;
  2645. for (int i = 1; i <= 16; i++) LastAutoFocusTimeDic[i] = null;
  2646. }
  2647. /// <summary>
  2648. /// 结束培养
  2649. /// </summary>
  2650. public void StopDish()
  2651. {
  2652. IsStopClearest = true;
  2653. IsStopCCD = true;
  2654. IsStopAirSwap = true;
  2655. Dish = null;
  2656. FirstClearest = true;
  2657. //排气报警
  2658. HouseStateEvent?.Invoke(House.houseSn, houseState, -1, -1, -1, 0);
  2659. //拍照报警
  2660. CCDStateEvent?.Invoke(House.houseSn, 0, -1);
  2661. //HouseStateEvent?.Invoke(House.houseSn, -1, -1, 0, -1, -1);
  2662. }
  2663. /// <summary>
  2664. /// 改变胚胎状态
  2665. /// </summary>
  2666. /// <param name="embryo"></param>
  2667. public void ChangeEmbryoState(Embryo embryo)
  2668. {
  2669. if (Dish == null && Dish.id <= 0) return;
  2670. var changeEmbryo = Dish.Embryo.FirstOrDefault(x => x.id == embryo.id);
  2671. if (changeEmbryo == null) return;
  2672. changeEmbryo.state = embryo.state;
  2673. changeEmbryo.stateTime = embryo.stateTime;
  2674. }
  2675. /// <summary>
  2676. /// 舱室更新设置
  2677. /// </summary>
  2678. /// <param name="tLInitControllerResult"></param>
  2679. public void UpdataHouseSetting(TLInitControllerResult tLInitControllerResult)
  2680. {
  2681. try
  2682. {
  2683. this.IsNewAirSwap = tLInitControllerResult.TLSetting.newAirSwap;
  2684. this.TLSetting = tLInitControllerResult.TLSetting;
  2685. var newHouse = tLInitControllerResult.HouseList.FirstOrDefault(x => x.houseSn == House.houseSn);
  2686. if (newHouse == null)
  2687. {
  2688. TLLogEvent?.Invoke($"{House.houseSn}号舱室更新设置未找到新的舱室设置", LogEnum.RunError);
  2689. }
  2690. else
  2691. {
  2692. this.House = newHouse;
  2693. }
  2694. var newList = tLInitControllerResult.HouseWellList.Where(x => x.houseSn == House.houseSn).ToList();
  2695. if (newList != null && newList.Any())
  2696. {
  2697. this._wellSettings = newList;
  2698. }
  2699. else
  2700. {
  2701. TLLogEvent?.Invoke($"{House.houseSn}号舱室更新设置未找到新的Well设置列表", LogEnum.RunError);
  2702. }
  2703. }
  2704. catch (Exception ex)
  2705. {
  2706. ExceptionLogEvent?.Invoke(ex, $"UpdataHouseSetting", null, LogEnum.RunException);
  2707. }
  2708. }
  2709. /// <summary>
  2710. /// 开启舱室对焦
  2711. /// </summary>
  2712. public void HouseAutoFocus()
  2713. {
  2714. FirstClearest = true;
  2715. AutoFocusWellClear();
  2716. }
  2717. /// <summary>
  2718. /// well自动对焦
  2719. /// </summary>
  2720. /// <param name="wellList"></param>
  2721. public void WellAutoFocus(List<int> wellList)
  2722. {
  2723. bool b = false;
  2724. if (Dish != null && Dish.id > 0)
  2725. {
  2726. var embryoWellList = Dish.Embryo.Select(x => x.wellSn).ToList();
  2727. foreach (var item in wellList)
  2728. {
  2729. if (embryoWellList.Contains(item))
  2730. {
  2731. b = true;
  2732. AddAutoFocusWell(item);
  2733. }
  2734. }
  2735. }
  2736. if (b) FirstClearest = true;
  2737. }
  2738. #endregion
  2739. }
  2740. }