| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000 |
- using DBEntity;
- using Dm;
- using Google.Protobuf;
- using ivf_tl_CameraHelper;
- using IvfTl.Control.Entity;
- using IvfTl.Control.Entity.DBEntitys;
- using IvfTl.Control.Entity.DTO;
- using IvfTl.Control.Entity.DTO.ApiResultDTO;
- using IvfTl.Control.Entity.DTO.ControllerResults;
- using IvfTl.Control.Entity.GlobalEntitys;
- using IvfTl.Control.Entity.GlobalEnums;
- using ivf_tl_SerialHelper.Util;
- using ivf_tl_UtilHelper;
- using IvfTl.Hardware;
- using IvfTl.Hardware.Impl;
- using IvfTl.AutoFocus.Calib;
- using IvfTl.AutoFocus.Layout;
- using IvfTl.AutoFocus.Storage;
- using Newtonsoft.Json;
- using SQLitePCL;
- using System;
- using System.Diagnostics;
- using System.Drawing.Imaging;
- using System.IO;
- using System.Net.Http.Json;
- using System.Runtime.InteropServices;
- using static System.Formats.Asn1.AsnWriter;
- namespace ivf_tl_Com
- {
- /// <summary>
- /// 仓室通信
- /// </summary>
- public class HouseBin
- {
- public event Func<int, int, bool> ChangeBufferBottleBinEvent;
- public event Func<HouseBin, int, bool> HouseBinChangeBufferBottleBinEvent;
- public event Action<int, DateTime, string, LogEnum> HouseLogEvent;
- public event Action<string, LogEnum> TLLogEvent;
- public event Action<Exception, string, string, LogEnum> ExceptionLogEvent;
- public event Action<HouseHistoryData> OnHistoryEvent;
- /// <summary>
- /// 服务器获取仓室自动对焦数据,housesn、autfocusTime
- /// </summary>
- public event Func<int, Dictionary<int, DateTime?>, List<HouseWellPhoto>> GetAutoFocusServiceEvent;
- /// <summary>
- /// 数据库获取仓室自动对焦数据,housesn、autfocusTime
- /// </summary>
- public event Func<int, Dictionary<int, DateTime?>, List<HouseWellPhoto>> GetAutoFocusDBEvent;
- /// <summary>
- /// M2-04 标定结果存储入口(写本地 calibration.json 真相源 + 镜像 house_autofocus_calibration)。
- /// 由 control 端(AppData)在 InitHouseBinEvent 时注入并配置 JsonPath/DbMirror;
- /// 为空则本地对焦不落库/不写 JSON(不影响对焦本身)。日常对焦路径以 scene=1 调用(append)。
- /// </summary>
- public CalibrationStore AutofocusStore { get; set; }
- /// <summary>
- /// 服务器获取仓室拍照数据,housesn、autfocusTime
- /// </summary>
- public event Func<int, Dictionary<int, DateTime?>, PositionInfoResultDTO> GetCCDServiceEvent;
- /// <summary>
- /// 数据库获取仓室拍照数据,housesn、autfocusTime
- /// </summary>
- public event Func<int, Dictionary<int, DateTime?>, List<HouseWellPhoto>> GetCCDDBEvent;
- /// <summary>
- /// 上传图片事件
- /// </summary>
- public event Action<ImageDTO> UploadImageEvent;
- /// <summary>
- /// 图片保存到数据库
- /// </summary>
- public event Action<ImageDTO> SavePicDbEvent;
- /// <summary>
- /// 修改仓室自动对焦状态
- /// </summary>
- public event Action<bool, int> UpdateAutofocusStateEvent;
- /// <summary>
- /// 调试模式准备好事件
- /// </summary>
- public event Action<string, int> DebugOkEvent;
- /// <summary>
- /// 舱室运行状态上报 舱室、串口、拍照、排气
- /// </summary>
- public event Action<int, int, int, int, int, int> HouseStateEvent;
- public event Action<int, int, int> CCDStateEvent;
- /// <summary>
- /// 排队换气
- /// </summary>
- public bool QueueAir { get; set; } = false;
- /// <summary>
- /// 准备换气
- /// </summary>
- public bool ReadyAir { get; set; } = false;
- /// <summary>
- /// 换气完成
- /// </summary>
- public bool EndAir { get; set; } = false;
- /// <summary>
- /// 缓冲瓶进气阀打开状态
- /// </summary>
- public bool OpenBuffer { get; set; } = false;
- public bool StartAir = false;
- public int CamNum { get; set; } = 0;
- public int TongQi = 1000 * 60 * 2;
- public int VentNum = 10;
- public int VentPre = 20;
- public int VentWaitTimeB = 1500;
- public int VentWaitTimeD = 1500;
- public int AutoWaitTime = 600000;
- public int CCDAutoWaitTime = 600000;
- public int CCDFailedWaitTime = 15000;
- public int CCDFailedNumber = 3;
- public bool ReCa = false;
- Stopwatch CCDAutoStopwatch = new Stopwatch();
- public bool CCDError = false;
- /// <summary>
- /// 是否排队换气
- /// </summary>
- public bool IsPai = false;
- /// <summary>
- /// 是否退出换气
- /// </summary>
- public bool StopPai = false;
- public string TakePhotoFailed = string.Empty;
- public HouseBin(TLSetting _setting, House _house, Dish _dish, Balance _balance, List<HouseWellSetting> _wellSettings)
- {
- if (_house == null)
- {
- return;
- }
- for (int i = 1; i <= 16; i++) LastAutoFocusTimeDic.Add(i, null);
- this.PortName = _house.housePort;
- // M1-03 HAL: 向统一硬件访问层借用该 COM 口的唯一 ComBin(杜绝同口重复 Open)。
- // RawComBin 返回 HAL 内部包装的具体 ComBin,保留采集端原有事件/调用面不变(代码隔离)。
- this.ComBin = (ComBin)HardwareAccessLayer.Instance.GetSerial(_house.houseSn, _house.housePort).RawComBin;
- // T1.4 双保险:把本舱 houseSn→port→相机 index 补登记到 HAL _houses。正常路径由 ScanDevices()
- // (登录后 MainWindow 调)填表;此处补 ScanDevices 现场漏扫(握手失败)的舱,使其借用仍可用,不覆盖已发现的舱。
- HardwareAccessLayer.Instance.RegisterHouse(_house.houseSn, _house.housePort,
- (_house.openCcd == 1 && _house.ccdId != -1) ? _house.ccdId : -1);
- ComBin.CommandLogEvent += ComBin_CommandLogEvent;
- ComBin.ErrorLogEvent += ComBin_ErrorLogEvent;
- ComBin.ExceptionLogEvent += ComBin_ExceptionLogEvent;
- ComBin.ComStateEvent += ComBin_ComStateEvent;
- this.FirstClearest = _house.autoFocus;
- this.IsNewAirSwap = _setting.newAirSwap;
- this.isWuTu = _house.noImagePreview;
- this.House = _house;
- this.Dish = _dish;
- this.Balance = _balance;
- this.TLSetting = _setting;
- this._wellSettings = _wellSettings;
- TargetTemp = _house.temperatureLowerHeatingPlate;
- //this.photoSerrings = _photoSetting;
- //this.wellSettings = _wellSettings;
- }
- private void ComBin_ComStateEvent(int obj)
- {
- comState = obj;
- HouseStateEvent?.Invoke(House.houseSn, -1, comState, -1, -1, -1);
- }
- private void ComBin_ExceptionLogEvent(Exception arg1, string arg2, string arg3, LogEnum arg4)
- {
- ExceptionLogEvent?.Invoke(arg1, arg2, arg3, arg4);
- }
- private void ComBin_ErrorLogEvent(string arg1, LogEnum arg2)
- {
- TLLogEvent?.Invoke(arg1, arg2);
- }
- private void ComBin_CommandLogEvent(int arg1, DateTime arg2, string arg3, LogEnum arg4)
- {
- HouseLogEvent?.Invoke(arg1, arg2, arg3, arg4);
- }
- private void Camera_CommandLogEvent(DateTime arg2, string arg3, LogEnum arg4)
- {
- HouseLogEvent?.Invoke(House.houseSn, arg2, arg3, arg4);
- }
- #region 字段
- public string PortName = null; // M5-03 只读监控需跨程序集读取,由 private 改 public
- /// <summary>
- /// 串口通信类
- /// </summary>
- public ComBin ComBin = null;
- private Camera Camera = null;
- #endregion
- #region 运行情况字段
- /// <summary>
- /// 运行流程
- /// </summary>
- public string RunState = "未知";
- /// <summary>
- /// 当前气压状态
- /// </summary>
- public State ValveState = State.未知;
- /// <summary>
- /// 工作线程
- /// </summary>
- public WorkingType WorkingType = WorkingType.DoNothing;
- private State _IsDoorOpen = State.关闭;
- /// <summary>
- /// 当前舱门状态
- /// </summary>
- public State IsDoorOpen
- {
- get { return _IsDoorOpen; }
- set
- {
- if (_IsDoorOpen != value)
- {
- _IsDoorOpen = value;
- DoorStateChanged(value);
- }
- }
- }
- /// <summary>
- /// 是否为第一次平衡
- /// </summary>
- public bool FirstAir = true;
- /// <summary>
- /// 是否自动对焦
- /// </summary>
- public bool FirstClearest = false;
- /// <summary>
- /// 最后一次自动对焦时间
- /// </summary>
- private Dictionary<int, DateTime?> LastAutoFocusTimeDic = new Dictionary<int, DateTime?>();
- /// <summary>
- /// 是否停止自动对焦
- /// </summary>
- private bool IsStopClearest = false;
- /// <summary>
- /// 是否停止拍照
- /// </summary>
- private bool IsStopCCD = false;
- /// <summary>
- /// 是否停止换气
- /// </summary>
- private bool IsStopAirSwap = false;
- /// <summary>
- /// 是否开启新版换气
- /// </summary>
- private bool IsNewAirSwap = false;
- /// <summary>
- /// 是否开启无图
- /// </summary>
- private bool isWuTu = false;
- /// <summary>
- /// 是否调试模式
- /// </summary>
- public bool IsDebug = false;
- /// <summary>
- /// 审计B1:前台(调试/对焦)借用本舱闸门时由 HAL 的 OnPauseCapture 置 true,
- /// 采集主循环每节拍据此让路(停发采集命令、让出 ComBin);归还后 OnResumeCapture 置 false 恢复。
- /// 与 MQTT 机制的 IsDebug 独立(互不覆盖),MainThread 让路判断取两者之或。
- /// </summary>
- public volatile bool CapturePausedByGate = false;
- /// <summary>
- /// 审计B1:闸门事件是否已订阅(幂等保护,避免重复 StartTask 时多次 += 累积回调)。
- /// </summary>
- private bool _gateSubscribed = false;
- /// <summary>
- /// 调试模式准备好
- /// </summary>
- public bool isDebugOk = false;
- /// <summary>
- /// 抠图成功数
- /// </summary>
- int KouTuSuccessNum = 0;
- /// <summary>
- /// 抠图失败数
- /// </summary>
- int KouTuDefultNum = 0;
- /// <summary>
- /// 当前下位机水平电机位置
- /// </summary>
- private int currentHorizontalMotor = -1;
- /// <summary>
- /// 当前下位机垂直电机位置
- /// </summary>
- private int currentVerticalMotor = -1;
- /// <summary>
- /// 舱室运行最后一次检测时间
- /// </summary>
- private DateTime LastRunTime = DateTime.Now;
- /// <summary>
- /// 舱室运行异常 0正常 1异常
- /// </summary>
- private int houseState = -1;
- /// <summary>
- /// 串口通信状态 0正常 1异常
- /// </summary>
- private int comState = -1;
- /// <summary>
- /// 拍照失败异常,0正常 1异常
- /// </summary>
- private int CCDState = -1;
- private int ErrorWell = -1;
- /// <summary>
- /// 获取拍照位置失败次数
- /// </summary>
- private int GetCCDDefeatNum = 0;
- /// <summary>
- /// 排气失败异常,0正常 1异常
- /// </summary>
- private int PaiQiState = -1;
- #endregion
- #region 数据
- public House House = null;
- public Dish Dish { get; set; } = null;
- public Balance Balance { get; set; } = null;
- private TLSetting TLSetting = null;
- /// <summary>
- /// 正常拍照位置
- /// </summary>
- private List<HouseWellPhoto> _ccdPhoto = new List<HouseWellPhoto>();
- /// <summary>
- /// 自动对焦拍照位置
- /// </summary>
- private List<HouseWellPhoto> _autoFocusPhoto = new List<HouseWellPhoto>();
- /// <summary>
- /// 仓室水平位置集合
- /// </summary>
- private List<HouseWellSetting> _wellSettings = new List<HouseWellSetting>();
- private decimal _Pressure = 0m;
- /// <summary>
- /// 气压
- /// </summary>
- public decimal Pressure
- {
- get { return _Pressure; }
- set { _Pressure = value; }
- }
- /// <summary>
- /// 当前温度
- /// </summary>
- public decimal Temperature = 0m;
- /// <summary>
- /// 上盖板传感器温度
- /// </summary>
- public decimal Temperature1 = 0m;
- /// <summary>
- /// 下盖板传感器温度
- /// </summary>
- public decimal Temperature2 = 0m;
- /// <summary>
- /// 玻璃片下方温度
- /// </summary>
- public decimal Temperature3 = 0m;
- /// <summary>
- /// 下位机的温度补偿值
- /// </summary>
- public decimal TargetTemp = 0m;
- #endregion
- /// <summary>
- /// 审计B1:订阅本舱借用闸门的暂停/恢复采集事件。
- /// 时序:此处由 StartTask 起始调用,此时 HAL 已 ScanDevices 发现本舱,GetHouseGate 可取到 gate。
- /// 容错:取不到 gate(时序/未发现)或订阅异常,只记日志、不抛,绝不崩采集线程。
- /// 幂等:_gateSubscribed 防止重复 StartTask 时累积多次回调。
- /// 死锁防护:OnPause 只置标志、OnResume 只清标志,回调体内绝不获取锁/不发串口,
- /// 让路判断仅在 MainThread 循环顶部生效——对焦支线(同舱同线程,Acquire 后本就在跑)
- /// 的 Acquire 虽会触发 OnPause,但该置位只在下一节拍循环顶部被读取,
- /// 而此时对焦支线的 using 已 Dispose 归还→OnResume 已清标志,故不会自我暂停、无死锁。
- /// </summary>
- private void SubscribeGateCapturePause()
- {
- try
- {
- if (_gateSubscribed) return;
- if (House == null) return;
- var gate = HardwareAccessLayer.Instance.GetHouseGate(House.houseSn);
- if (gate == null)
- {
- HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[{House.houseSn}][{this.PortName}][审计B1:未取到舱借用闸门,采集暂停事件未接线(前台借用时采集端可能不让路)]", LogEnum.HouseInfo);
- return;
- }
- gate.OnPauseCapture += OnGatePauseCapture;
- gate.OnResumeCapture += OnGateResumeCapture;
- _gateSubscribed = true;
- HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[{House.houseSn}][{this.PortName}][审计B1:已订阅舱借用闸门 暂停/恢复采集 事件]", LogEnum.HouseInfo);
- }
- catch (Exception ex)
- {
- // 订阅失败不影响采集主流程:仅前台借用时无法自动让路,记异常便于排障。
- ExceptionLogEvent?.Invoke(ex, $"[{House.houseSn}][{PortName}][审计B1:订阅借用闸门暂停事件失败]", null, LogEnum.RunException);
- }
- }
- // 审计B1:前台借用→暂停采集。仅置标志(volatile),不持锁、不发串口,保证回调轻量无死锁。
- private void OnGatePauseCapture()
- {
- CapturePausedByGate = true;
- HouseLogEvent?.Invoke(House != null ? House.houseSn : -1, DateTime.Now, $"[{(House != null ? House.houseSn : -1)}][{this.PortName}][审计B1:前台借用,采集主循环让路(停发命令)]", LogEnum.HouseInfo);
- }
- // 审计B1:借用归还→恢复采集。仅清标志。
- private void OnGateResumeCapture()
- {
- CapturePausedByGate = false;
- HouseLogEvent?.Invoke(House != null ? House.houseSn : -1, DateTime.Now, $"[{(House != null ? House.houseSn : -1)}][{this.PortName}][审计B1:借用归还,采集恢复]", LogEnum.HouseInfo);
- }
- /// <summary>
- /// 仓室开始运行
- /// </summary>
- public void StartTask()
- {
- Task.Run(() =>
- {
- try
- {
- if (House == null)
- {
- return;
- }
- // 审计B1:订阅本舱借用闸门的"暂停/恢复采集"事件。
- // 前台(调试/对焦)Acquire 时 HAL 触发 OnPauseCapture → 本舱采集主循环让路(停发命令、让出 ComBin);
- // 归还触发 OnResumeCapture → 恢复采集。取不到 gate 或异常都不崩采集线程(容错)。
- SubscribeGateCapturePause();
- HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[{House.houseSn}][{this.PortName}]开始初始化", LogEnum.HouseInfo);
- if (House.openPort == 0)
- {
- HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[{House.houseSn}][{this.PortName}]仓室串口未打开,结束初始化", LogEnum.HouseInfo);
- HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[{House.houseSn}][{this.PortName}]仓室串口未打开,结束初始化", LogEnum.RunError);
- return;
- }
- var openPort = ComBin.OpenPort();
- HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[{House.houseSn}][{this.PortName}]仓室串口打开结果{openPort}", LogEnum.HouseInfo);
- if (!openPort)
- {
- TLLogEvent?.Invoke($"[{House.houseSn}][{this.PortName}]仓室串口打开失败,结束初始化", LogEnum.RunError);
- return;
- }
- if (House.openCcd == 1 && House.ccdId != -1)
- {
- // M1-03 HAL: 向 HAL 借用该 index 的唯一相机(杜绝同相机重复 Init / 句柄争用)。
- this.Camera = (Camera)HardwareAccessLayer.Instance.GetCamera(House.ccdId, House.ccdWidth, House.ccdHeight, House.ccdExposure).RawCamera;
- this.Camera.ExceptionLogEvent += ComBin_ExceptionLogEvent;
- this.Camera.HouseLogEvent += Camera_CommandLogEvent;
- int cameraInit = this.Camera.Init();
- HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[{House.houseSn}][{this.PortName}]相机初始化结果{cameraInit}[注:0表示成功]", LogEnum.HouseInfo);
- if (cameraInit != 0)
- {
- TLLogEvent?.Invoke($"[{House.houseSn}][{this.PortName}]相机初始化结果{cameraInit},结束初始化[注:0表示成功]", LogEnum.RunError);
- return;
- }
- int cameraSetMode = this.Camera.SetOpMode();
- HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[{House.houseSn}][{this.PortName}]相机连续模式设置结果{cameraSetMode}[注:0表示成功]", LogEnum.HouseInfo);
- if (cameraSetMode != 0)
- {
- TLLogEvent?.Invoke($"[{House.houseSn}][{this.PortName}]相机连续模式设置结果{cameraSetMode},结束初始化[注:0表示成功]", LogEnum.RunError);
- return;
- }
- Camera.GetRgbData();
- Camera.SavePreMem();
- }
- else
- {
- TLLogEvent?.Invoke($"[{House.houseSn}][{this.PortName}]仓室相机未打开,结束初始化", LogEnum.HouseInfo);
- return;
- }
- CommandSource commandSource = CommandSource.taskThread;
- this.RunState = "握手准备";
- //握手
- var custom = new CustomProtocol();
- custom.commandSource = commandSource;
- ComBin.ShakeHandsWait(custom);
- ComBin.CloseLEDWait(custom);
- //关闭进气阀
- ComBin.CloseIntakeValveWait(custom, TLSetting.valueDelay);
- ComBin.CloseExhaustValveWait(custom, TLSetting.valueDelay);
- HouseState(commandSource, custom, 0);
- if (Pressure < TLSetting.pressureAlarmMin)
- {
- ValveState = State.待补气;
- }
- else
- {
- ValveState = State.正常;
- }
- this.RunState = "水平电机自检";
- //水平电机自检
- ComBin.HorizontalMotorResetWait(custom, TLSetting.motorDelay);
- this.RunState = "垂直电机自检";
- //垂直电机自检
- ComBin.VerticalMotorResetWait(custom, TLSetting.motorDelay);
- HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[{House.houseSn}][{this.PortName}] 初始化完成,仓室开始运行", LogEnum.HouseInfo);
- MainThread();
- RunAlarmTask();
- RunHistoryTask();
- }
- catch (Exception ex)
- {
- ExceptionLogEvent?.Invoke(ex, $"[{House.houseSn}][{PortName}]初始化", null, LogEnum.RunException);
- }
- });
- }
- Dictionary<int, DateTime?> wellList = new Dictionary<int, DateTime?>();
- /// <summary>
- /// 主线程
- /// </summary>
- public void MainThread()
- {
- Task.Factory.StartNew(() =>
- {
- Stopwatch BmpSaveIntervalStopwatch = Stopwatch.StartNew();//拍照线程计时器
- Stopwatch AirSwapTimeStopwatch = Stopwatch.StartNew();//换气间隔计时器
- Stopwatch StartDishStopwatch = new Stopwatch();
- bool isAir = false;
- LastRunTime = DateTime.Now;
- while (true)
- {
- try
- {
- LastRunTime = DateTime.Now;
- // 审计B1:IsDebug=MQTT调试机制;CapturePausedByGate=前台(调试/对焦)经HAL闸门借用本舱。
- // 任一为真都让路——本节拍不发任何采集/电机命令、让出 ComBin 给借用方独占。
- if (IsDebug || CapturePausedByGate)
- {
- HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[{House.houseSn}][{this.PortName}]{(IsDebug ? "调试状态" : "前台借用让路")}", LogEnum.HouseInfo);
- this.RunState = IsDebug ? "调试状态" : "前台借用让路";
- // 仅 MQTT 调试机制(IsDebug)首次进入时发归位电机命令;
- // 闸门借用让路(CapturePausedByGate)绝不发串口——串口此刻已被借用方独占。
- if (IsDebug && !isDebugOk)
- {
- isDebugOk = true;
- DebugOkEvent?.Invoke(TLSetting.tlSn, House.houseSn);
- var custom = new CustomProtocol();//指令包
- ComBin.HorizontalMotorAbsoluteWait(custom, TLSetting.motorDelay, 70000);
- ComBin.HorizontalMotorResetWait(custom, TLSetting.motorDelay);
- }
- Thread.Sleep(1000 * 3);
- continue;
- }
- if (isDebugOk) isDebugOk = false;
- this.RunState = "空闲监测";
- if (Balance != null && Balance.id > 0) this.RunState = "温压监测平衡";
- if (Dish != null && Dish.id > 0) this.RunState = "温压监测";
- if (ReCa)
- {
- //CloseCamera($"[{House.houseSn}][{PortName}]");
- //OpenCamera($"[{House.houseSn}][{PortName}]");
- //ReCa = false;
- }
- //温压检测中补气
- ParamFun();
- if (Pressure < TLSetting.pressureAlarmMin) ValveState = State.待补气;
- else ValveState = State.正常;
- //仓门未关闭不进行任何操作
- if (IsDoorOpen != State.关闭) continue;
- 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);
- //当前舱室有培养记录,那么就需要自动对焦和拍照以及换气
- if (Dish != null && Dish.id > 0)
- {
- if (IsPai)
- {
- if (StartAir)
- {
- AirSwapQueueFun();
- StartAir = false;
- if (FirstClearest)
- {
- isAir = true;
- StartDishStopwatch.Restart();
- }
- }
- }
- else
- {
- if (StartAir)
- {
- AirSwapTimeStopwatch.Restart();
- AirSwapFun();
- StartAir = false;
- }
- }
- if (AirSwapTimeStopwatch.ElapsedMilliseconds >= (TLSetting.airSwapFrequency * 60 * 1000))
- {
- AirSwapTimeStopwatch.Restart();
- AirSwapFun();
- }
- if (!FirstClearest)//不自动对焦
- {
- if (BmpSaveIntervalStopwatch.ElapsedMilliseconds >= (TLSetting.photoIntervalPerRound * 60 * 1000))
- {
- if (!StartCCD()) continue;
- BmpSaveIntervalStopwatch.Restart();
- ccdThreadFun();
- }
- continue;
- }
- if (IsPai)
- {
- if (isAir && StartDishStopwatch.ElapsedMilliseconds < AutoWaitTime)
- {
- continue;
- }
- isAir = false;
- StartDishStopwatch.Reset();
- }
- if (CCDState == 1 && CCDAutoStopwatch.ElapsedMilliseconds < CCDAutoWaitTime)
- {
- continue;
- }
- if (!StartAutoFocus()) continue;
- CCDAutoStopwatch.Restart();
- FirstClearest = false;
- if (GetClearest(CommandSource.AutoFocusThread))
- {
- if (AirSwapTimeStopwatch.ElapsedMilliseconds >= (TLSetting.airSwapFrequency * 60 * 1000))
- {
- AirSwapTimeStopwatch.Restart();
- AirSwapFun();
- }
- if (!StartCCD()) continue;
- BmpSaveIntervalStopwatch.Restart();
- ccdThreadFun();
- }
- else
- {
- FirstClearest = true;
- if (AirSwapTimeStopwatch.ElapsedMilliseconds >= (TLSetting.airSwapFrequency * 60 * 1000))
- {
- AirSwapTimeStopwatch.Restart();
- AirSwapFun();
- }
- }
- continue;
- }
- //平衡的情况处理
- if (Balance != null && Balance.id > 0)
- {
- if (StartAir)
- {
- AirSwapTimeStopwatch.Restart();
- if (IsPai)
- {
- AirSwapQueueFun();
- }
- else
- {
- AirSwapFun();
- }
- StartAir = false;
- }
- if (FirstAir)//第一次平衡
- {
- FirstAir = false;
- AirSwapTimeStopwatch.Restart();
- AirSwapFun();
- continue;
- }
- if (AirSwapTimeStopwatch.ElapsedMilliseconds >= (TLSetting.airSwapFrequency * 60 * 1000))
- {
- AirSwapTimeStopwatch.Restart();
- AirSwapFun();
- continue;
- }
- continue;
- }
- BmpSaveIntervalStopwatch.Restart();
- AirSwapTimeStopwatch.Restart();
- }
- catch (Exception ex)
- {
- ExceptionLogEvent?.Invoke(ex, $"[{House.houseSn}][{PortName}]主线程", null, LogEnum.RunException);
- }
- }
- }, TaskCreationOptions.LongRunning);
- }
- /// <summary>
- /// 运行情况监测线程
- /// </summary>
- public void RunAlarmTask()
- {
- Task.Factory.StartNew(async () =>
- {
- var time2 = (10 * 60 * 1000);
- while (true)
- {
- await Task.Delay(1000 * 60 * 5);
- try
- {
- var time1 = (DateTime.Now - LastRunTime).TotalMilliseconds;
- if (time1 > time2)
- {
- if (houseState != 1)
- {
- houseState = 1;
- HouseStateEvent?.Invoke(House.houseSn, houseState, -1, -1, -1, -1);
- }
- continue;
- }
- if (houseState == 0) continue;
- houseState = 0;
- HouseStateEvent?.Invoke(House.houseSn, houseState, -1, -1, -1, -1);
- }
- catch (Exception ex)
- {
- ExceptionLogEvent?.Invoke(ex, $"[{House.houseSn}][{PortName}]运行情况监测线程", null, LogEnum.RunException);
- }
- }
- }, TaskCreationOptions.LongRunning);
- }
- /// <summary>
- /// 历史数据上报线程
- /// </summary>
- public void RunHistoryTask()
- {
- HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[{House.houseSn}][{this.PortName}]历史数据上报线程启动", LogEnum.HouseInfo);
- Task.Factory.StartNew(async () =>
- {
- await Task.Delay(1000 * 60);
- int seconds = 1;
- HouseHistoryData currentData = null;
- while (true)
- {
- try
- {
- await Task.Delay(1000);
- if (this.WorkingType == WorkingType.AirSwapWorking)
- {
- currentData = GetHouseHistoryData(this);
- if (currentData != null) OnHistoryEvent?.Invoke(currentData);
- }
- else
- {
- if (seconds++ >= TLSetting.historyCurveInterval)
- {
- seconds = 1;
- currentData = GetHouseHistoryData(this);
- if (currentData != null) OnHistoryEvent?.Invoke(currentData);
- }
- }
- }
- catch (Exception ex)
- {
- ExceptionLogEvent?.Invoke(ex, $"[{House.houseSn}][{PortName}]历史数据上报线程", null, LogEnum.RunException);
- }
- }
- }, TaskCreationOptions.LongRunning);
- }
- private HouseHistoryData GetHouseHistoryData(HouseBin currentHouseBin)
- {
- if (currentHouseBin == null) return null;
- if (currentHouseBin.House == null) return null;
- int newHouse = 0;
- if (currentHouseBin.Balance != null && currentHouseBin.Balance.id > 0) newHouse = 2;
- if (currentHouseBin.Dish != null && currentHouseBin.Dish.id > 0) newHouse = 1;
- return new HouseHistoryData()
- {
- tlSn = TLSetting.tlSn,
- houseSn = currentHouseBin.House.houseSn,
- pressure = currentHouseBin.Pressure,
- temperature = currentHouseBin.Temperature,
- houseDoor = currentHouseBin.IsDoorOpen == State.打开 ? 1 : 0,
- airSwap = currentHouseBin.WorkingType == WorkingType.AirSwapWorking ? 1 : 0,
- temperatureLowerCover = currentHouseBin.Temperature2,
- temperatureUpperCover = currentHouseBin.Temperature1,
- temperatureLowerGlass = currentHouseBin.Temperature3,
- cultureState = newHouse,
- };
- }
- /// <summary>
- /// 关闭相机
- /// </summary>
- /// <param name="Content"></param>
- /// <returns></returns>
- public bool CloseCamera(string Content)
- {
- try
- {
- bool isdis = Camera.DisPose();
- HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[{House.houseSn}][{this.PortName}][释放相机内存结果:{isdis}]", LogEnum.HouseInfo);
- int unin = Camera.UnInit();
- HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[{House.houseSn}][{this.PortName}][卸载相机结果:{unin}]", LogEnum.HouseInfo);
- return true;
- }
- catch (Exception ex)
- {
- ExceptionLogEvent?.Invoke(ex, $"[{House.houseSn}][{PortName}]关闭相机", null, LogEnum.RunException);
- return false;
- }
- }
- /// <summary>
- /// 重新开启相机
- /// </summary>
- /// <param name="content"></param>
- /// <returns></returns>
- public bool OpenCamera(string content)
- {
- try
- {
- byte[] SaveRgbData = new byte[3];
- if (this.Camera != null)
- {
- //SaveRgbData[0] = this.Camera.SaveRgbData[0];
- //SaveRgbData[1] = this.Camera.SaveRgbData[1];
- //SaveRgbData[2] = this.Camera.SaveRgbData[2];
- SaveRgbData = new byte[Camera.LastSourceBufferHash.Length];
- Buffer.BlockCopy(Camera.LastSourceBufferHash, 0, SaveRgbData, 0, Camera.LastSourceBufferHash.Length);
- }
- Camera = null;
- // M1-03 HAL: 重开相机也向 HAL 借用同一 index 的唯一实例(不再 new,杜绝句柄争用)。
- // 因是单例同一对象,先 -= 再 += 防止重复订阅事件。
- this.Camera = (Camera)HardwareAccessLayer.Instance.GetCamera(House.ccdId, House.ccdWidth, House.ccdHeight, House.ccdExposure).RawCamera;
- this.Camera.ExceptionLogEvent -= ComBin_ExceptionLogEvent;
- this.Camera.HouseLogEvent -= Camera_CommandLogEvent;
- this.Camera.ExceptionLogEvent += ComBin_ExceptionLogEvent;
- this.Camera.HouseLogEvent += Camera_CommandLogEvent;
- int cameraInit = this.Camera.Init();
- //this.Camera.SaveRgbData[0] = SaveRgbData[0];
- //this.Camera.SaveRgbData[1] = SaveRgbData[1];
- //this.Camera.SaveRgbData[2] = SaveRgbData[2];
- Camera.LastSourceBufferHash = new byte[SaveRgbData.Length];
- Buffer.BlockCopy(SaveRgbData, 0, Camera.LastSourceBufferHash, 0, SaveRgbData.Length);
- SaveRgbData = null;
- HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[{House.houseSn}][{this.PortName}]相机初始化结果{cameraInit}[注:0表示成功]", LogEnum.HouseInfo);
- if (cameraInit != 0)
- {
- TLLogEvent?.Invoke($"[{House.houseSn}][{this.PortName}]相机初始化结果{cameraInit},结束初始化[注:0表示成功]", LogEnum.RunError);
- return false;
- }
- int cameraSetMode = this.Camera.SetOpMode();
- HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[{House.houseSn}][{this.PortName}]相机连续模式设置结果{cameraSetMode}[注:0表示成功]", LogEnum.HouseInfo);
- if (cameraSetMode != 0)
- {
- TLLogEvent?.Invoke($"[{House.houseSn}][{this.PortName}]相机连续模式设置结果{cameraSetMode},结束初始化[注:0表示成功]", LogEnum.RunError);
- return false;
- }
- return true;
- }
- catch (Exception ex)
- {
- ExceptionLogEvent?.Invoke(ex, $"[{House.houseSn}][{PortName}]重新开启相机", null, LogEnum.RunException);
- return false;
- }
- }
- #region 换气
- /// <summary>
- /// 换气
- /// </summary>
- /// <exception cref="NotImplementedException"></exception>
- private void AirSwapFun()
- {
- if (!IsPai) AirSwapOldFun();
- //HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[{House.houseSn}][{this.PortName}][关闭旧版换气]", LogEnum.HouseInfo);
- //return;
- //if (IsNewAirSwap)
- //{
- // AirSwapNewFun();
- //}
- //else
- //{
- // AirSwapOldFun();
- //}
- }
- private void AirSwapOldFun()
- {
- try
- {
- LastRunTime = DateTime.Now;
- WorkingType = WorkingType.AirSwapWorking;
- Stopwatch AirThreadStopwatch = Stopwatch.StartNew();
- var custom = new CustomProtocol();//指令包
- custom.commandSource = CommandSource.airSwapThread;
- HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[{House.houseSn}][{this.PortName}][换气开始时间:{DateTime.Now}]", LogEnum.HouseInfo);
- this.RunState = "气体交换";
- if (Balance != null && Balance.id > 0) this.RunState = "气体交换平衡";
- int num = 1;
- Stopwatch airStopwatch = Stopwatch.StartNew();
- var maxMilliseconds = TLSetting.ventilationDelay * 1000;
- while (num <= TLSetting.airSwapTime)//6
- {
- LastRunTime = DateTime.Now;
- if (IsStopAirSwap) break;
- num++;
- //打开排气阀
- ComBin.OpenExhaustValveWait(custom, TLSetting.valueDelay);
- airStopwatch.Restart();
- var milliseconds = airStopwatch.ElapsedMilliseconds;
- while (milliseconds <= maxMilliseconds)
- {
- if (IsStopAirSwap) break;
- HouseState(CommandSource.airSwapThread, custom, 50);
- milliseconds = airStopwatch.ElapsedMilliseconds;
- }
- ComBin.CloseExhaustValveWait(custom, TLSetting.valueDelay);
- HouseState(CommandSource.airSwapThread, custom, 0);
- //执行补气操作
- if (TLSetting.pressureAlarmMin > Pressure && this.IsDoorOpen == State.关闭)
- AerationNew(CommandSource.airSwapThread, custom);
- }
- airStopwatch.Stop();
- ComBin.CloseExhaustValveWait(custom, TLSetting.valueDelay);
- HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[{House.houseSn}][{this.PortName}][换气结束时间:{DateTime.Now}][换气耗时:{StringHelper.TimeToString(AirThreadStopwatch.Elapsed)}]", LogEnum.HouseInfo);
- AirThreadStopwatch.Stop();
- WorkingType = WorkingType.DoNothing;
- // D1-10:换气物理动作审计(每次换气会话一行,非每次阀动作;远离串口字节循环)。全 try 兜底。
- try
- {
- Aivfo.OperationLog.OperationLogger.Log("换气", "周期换气",
- input: new { houseSn = House.houseSn, port = PortName, airSwapTime = TLSetting.airSwapTime },
- result: "成功",
- elapsedMs: (long)AirThreadStopwatch.Elapsed.TotalMilliseconds,
- houseSn: House.houseSn, tlSn: TLSetting?.tlSn);
- }
- catch { }
- }
- catch (Exception ex)
- {
- ExceptionLogEvent?.Invoke(ex, $"[{House.houseSn}][{PortName}]换气", null, LogEnum.RunException);
- try
- {
- Aivfo.OperationLog.OperationLogger.Log("换气", "周期换气",
- input: new { houseSn = House.houseSn, port = PortName },
- result: "失败", error: ex.GetType().Name + ": " + ex.Message,
- houseSn: House.houseSn, tlSn: TLSetting?.tlSn);
- }
- catch { }
- }
- }
- private void AirSwapNewFun()
- {
- LastRunTime = DateTime.Now;
- Stopwatch AirThreadStopwatch = Stopwatch.StartNew();
- Stopwatch airStopwatch = Stopwatch.StartNew();
- WorkingType = WorkingType.AirSwapWorking;
- bool? changB = false;
- try
- {
- var custom = new CustomProtocol();//指令包
- custom.commandSource = CommandSource.airSwapThread;
- HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[{House.houseSn}][{this.PortName}][换气开始时间:{DateTime.Now}]", LogEnum.HouseInfo);
- this.RunState = "气体交换";
- if (Balance != null && Balance.id > 0) this.RunState = "气体交换平衡";
- int num = 1;
- bool isAlarm = false;
- var maxMilliseconds = TongQi;
- //打开排气阀
- ComBin.OpenExhaustValveWait(custom, TLSetting.valueDelay);
- HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[{House.houseSn}][{this.PortName}][打开舱室排气阀时间:{DateTime.Now}]", LogEnum.HouseInfo);
- //打开进气阀
- ComBin.OpenIntakeValveWait(custom, TLSetting.valueDelay);
- HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[{House.houseSn}][{this.PortName}][打开舱室进气阀时间:{DateTime.Now}]", LogEnum.HouseInfo);
- //打开缓冲瓶进气阀
- changB = ChangeBufferBottleBinEvent?.Invoke(House.houseSn, 1);
- HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[{House.houseSn}][{this.PortName}][缓冲瓶打开进气阀时间:{DateTime.Now}][结果:{changB}]", LogEnum.HouseInfo);
- //等待换气冲刷
- airStopwatch.Restart();
- var milliseconds = airStopwatch.ElapsedMilliseconds;
- while (milliseconds <= maxMilliseconds)
- {
- HouseState(CommandSource.airSwapThread, custom, 100);
- if (IsStopAirSwap) break;
- milliseconds = airStopwatch.ElapsedMilliseconds;
- }
- //关闭缓冲瓶进气阀
- changB = ChangeBufferBottleBinEvent?.Invoke(House.houseSn, 0);
- HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[{House.houseSn}][{this.PortName}][缓冲瓶关闭进气阀时间:{DateTime.Now}][结果:{changB}]", LogEnum.HouseInfo);
- //关闭舱室进气阀
- ComBin.CloseIntakeValveWait(custom, TLSetting.valueDelay);
- HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[{House.houseSn}][{this.PortName}][关闭舱室进气阀时间:{DateTime.Now}][结果:{changB}]", LogEnum.HouseInfo);
- //关闭舱室排气阀
- ComBin.CloseExhaustValveWait(custom, TLSetting.valueDelay);
- HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[{House.houseSn}][{this.PortName}][关闭舱室排气阀时间:{DateTime.Now}][结果:{changB}]", LogEnum.HouseInfo);
- //执行补气操作
- if (TLSetting.pressureAlarmMin > Pressure && this.IsDoorOpen == State.关闭)
- AerationNew(CommandSource.airSwapThread, custom);
- HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[{House.houseSn}][{this.PortName}][换气结束时间:{DateTime.Now}][换气耗时:{StringHelper.TimeToString(AirThreadStopwatch.Elapsed)}]", LogEnum.HouseInfo);
- }
- catch (Exception ex)
- {
- ExceptionLogEvent?.Invoke(ex, $"[{House.houseSn}][{PortName}]新版换气", null, LogEnum.RunException);
- }
- finally
- {
- airStopwatch.Stop();
- AirThreadStopwatch.Stop();
- WorkingType = WorkingType.DoNothing;
- }
- }
- /// <summary>
- /// 排队换气
- /// </summary>
- private void AirSwapQueueFun()
- {
- LastRunTime = DateTime.Now;
- Stopwatch AirThreadStopwatch = Stopwatch.StartNew();
- Stopwatch airStopwatch = Stopwatch.StartNew();
- WorkingType = WorkingType.AirSwapWorking;
- bool? changB = false;
- try
- {
- var custom = new CustomProtocol();//指令包
- custom.commandSource = CommandSource.airSwapThread;
- HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[{House.houseSn}][{this.PortName}][换气开始时间:{DateTime.Now}]", LogEnum.HouseInfo);
- int num = 1;
- bool isAlarm = false;
- var maxMilliseconds = TongQi;
- QueueAir = false;
- ReadyAir = false;
- EndAir = false;
- OpenBuffer = false;
- changB = HouseBinChangeBufferBottleBinEvent?.Invoke(this, 1);
- HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[{House.houseSn}][{this.PortName}][{House.houseSn}号舱室开始换气排队:{DateTime.Now}][结果:{changB}]", LogEnum.HouseInfo);
- if (changB != true)
- {
- HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[{House.houseSn}][{this.PortName}][联系缓冲瓶失败,跳过换气:{DateTime.Now}]", LogEnum.HouseInfo);
- return;
- }
- this.ValveState = State.排队;
- this.RunState = "气体交换";
- if (Balance != null && Balance.id > 0) this.RunState = "气体交换平衡";
- do
- {
- HouseState(CommandSource.airSwapThread, custom, 100);
- if (IsStopAirSwap) break;
- } while (!QueueAir);
- if (IsStopAirSwap)
- {
- changB = HouseBinChangeBufferBottleBinEvent?.Invoke(this, 0);
- HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[{House.houseSn}][{this.PortName}][排队换气终止,跳过换气:{DateTime.Now}][结果:{changB}]", LogEnum.HouseInfo);
- return;
- }
- HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[{House.houseSn}][{this.PortName}][{House.houseSn}号舱室换气排队完成,开始进行准备工作]", LogEnum.HouseInfo);
- //this.RunState = "气体交换";
- //if (Balance != null && Balance.id > 0) this.RunState = "气体交换平衡";
- //打开排气阀
- ComBin.OpenExhaustValveWait(custom, TLSetting.valueDelay);
- HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[{House.houseSn}][{this.PortName}][打开舱室排气阀时间:{DateTime.Now}]", LogEnum.HouseInfo);
- //打开进气阀
- ComBin.OpenIntakeValveWait(custom, TLSetting.valueDelay);
- HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[{House.houseSn}][{this.PortName}][打开舱室进气阀时间:{DateTime.Now}][换气准备工作完成][等待缓冲瓶打开进气阀]", LogEnum.HouseInfo);
- ReadyAir = true;
- do
- {
- HouseState(CommandSource.airSwapThread, custom, 50);
- if (IsStopAirSwap) break;
- } while (!OpenBuffer);
- HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[{House.houseSn}][{this.PortName}][缓冲瓶进气阀已打开,开始冲刷舱室]", LogEnum.HouseInfo);
- //等待换气冲刷
- this.ValveState = State.冲刷;
- //this.RunState = "气体交换冲刷";
- //if (Balance != null && Balance.id > 0) this.RunState = "气体交换平衡冲刷";
- airStopwatch.Restart();
- while (airStopwatch.ElapsedMilliseconds <= maxMilliseconds)
- {
- HouseState(CommandSource.airSwapThread, custom, 100);
- if (IsStopAirSwap) break;
- }
- ReadyAir = false;
- //this.RunState = "气体交换";
- //if (Balance != null && Balance.id > 0) this.RunState = "气体交换平衡";
- HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[{House.houseSn}][{this.PortName}][冲刷完成,等待关闭缓冲瓶进气阀]", LogEnum.HouseInfo);
- do
- {
- HouseState(CommandSource.airSwapThread, custom, 50);
- } while (!EndAir);
- HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[{House.houseSn}][{this.PortName}][关闭缓冲瓶进气阀]", LogEnum.HouseInfo);
- //关闭缓冲瓶进气阀
- //changB = ChangeBufferBottleBinEvent?.Invoke(House.houseSn, 0);
- //HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[{House.houseSn}][{this.PortName}][缓冲瓶关闭进气阀时间:{DateTime.Now}][结果:{changB}]", LogEnum.HouseInfo);
- //关闭舱室进气阀
- ComBin.CloseIntakeValveWait(custom, TLSetting.valueDelay);
- HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[{House.houseSn}][{this.PortName}][关闭舱室进气阀时间:{DateTime.Now}][结果:{changB}]", LogEnum.HouseInfo);
- //关闭舱室排气阀
- ComBin.CloseExhaustValveWait(custom, TLSetting.valueDelay);
- HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[{House.houseSn}][{this.PortName}][关闭舱室排气阀时间:{DateTime.Now}][结果:{changB}]", LogEnum.HouseInfo);
- HouseState(CommandSource.airSwapThread, custom, 50);
- if (Pressure < TLSetting.pressureAlarmMin) this.ValveState = State.待补气;
- else this.ValveState = State.正常;
- //执行补气操作
- if (TLSetting.pressureAlarmMin > Pressure && this.IsDoorOpen == State.关闭)
- AerationNew(CommandSource.airSwapThread, custom);
- HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[{House.houseSn}][{this.PortName}][换气结束时间:{DateTime.Now}][换气耗时:{StringHelper.TimeToString(AirThreadStopwatch.Elapsed)}]", LogEnum.HouseInfo);
- }
- catch (Exception ex)
- {
- ExceptionLogEvent?.Invoke(ex, $"[{House.houseSn}][{PortName}]新版换气", null, LogEnum.RunException);
- }
- finally
- {
- airStopwatch.Stop();
- AirThreadStopwatch.Stop();
- WorkingType = WorkingType.DoNothing;
- }
- }
- #endregion
- #region 温压检测、补气、仓室状态
- /// <summary>
- /// 温压监测
- /// </summary>
- /// <exception cref="NotImplementedException"></exception>
- private void ParamFun()
- {
- try
- {
- LastRunTime = DateTime.Now;
- var nameString = this.RunState;
- Stopwatch ParamThreadStopwatch = Stopwatch.StartNew();
- HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[{House.houseSn}][{this.PortName}][{nameString}开始时间:{DateTime.Now}]", LogEnum.HouseInfo);
- CustomProtocol custom = new CustomProtocol();
- custom.commandSource = CommandSource.paramThread;
- HouseState(CommandSource.paramThread, custom, 500);
- if (IsPai)
- {
- if (IsDoorOpen == State.关闭 && Pressure >= TLSetting.pressureAlarmMin)
- {
- if ((Dish != null && Dish.id > 0))
- {
- PaiQi(custom, CommandSource.paramThread, VentWaitTimeD);
- }
- else if ((Balance != null && Balance.id > 0))
- {
- PaiQi(custom, CommandSource.paramThread, VentWaitTimeB);
- }
- }
- }
- if (IsDoorOpen == State.关闭 && Pressure < TLSetting.pressureAlarmMin)
- {
- if ((Dish != null && Dish.id > 0) || (Balance != null && Balance.id > 0))
- {
- AerationNew(CommandSource.paramThread, custom);
- }
- }
- //读仓门状态
- IsDoorOpen = ComBin.DoorStatusWait(custom);
- Thread.Sleep(500);
- HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[{House.houseSn}][{this.PortName}][{nameString}结束时间:{DateTime.Now}][耗时:{StringHelper.TimeToString(ParamThreadStopwatch.Elapsed)}]", LogEnum.HouseInfo);
- ParamThreadStopwatch.Stop();
- }
- catch (Exception ex)
- {
- ExceptionLogEvent?.Invoke(ex, $"[{House.houseSn}][{PortName}]温压监测", null, LogEnum.RunException);
- }
- }
- /// <summary>
- /// 补气
- /// </summary>
- /// <param name="commandSource"></param>
- /// <param name="custom"></param>
- /// <param name="isAlarm"></param>
- private void AerationNew(CommandSource commandSource, CustomProtocol custom)
- {
- try
- {
- Stopwatch AerationStopwatch = Stopwatch.StartNew();
- HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[{House.houseSn}][{this.PortName}][补气开始时间:{DateTime.Now}]", LogEnum.HouseInfo);
- custom.commandSource = commandSource;
- ValveState = State.补气;
- decimal oldPressure = 0m;
- for (int i = 1; i <= TLSetting.houseAerationNum; i++)
- {
- if (IsDoorOpen != State.关闭 || Pressure >= TLSetting.pressureAlarmMin) break;
- oldPressure = Pressure;
- ComBin.HouseAerationWait(custom);
- Thread.Sleep(TLSetting.aerationDelay * 1000);
- HouseState(commandSource, custom, 0);
- HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[{House.houseSn}][{this.PortName}]补气完成[{oldPressure}->{Pressure}]", LogEnum.HouseInfo);
- }
- this.ValveState = State.正常;
- if (Pressure < TLSetting.pressureAlarmMin) this.ValveState = State.待补气;
- HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[{House.houseSn}][{this.PortName}][补气结束时间:{DateTime.Now}][耗时:{StringHelper.TimeToString(AerationStopwatch.Elapsed)}]", LogEnum.HouseInfo);
- AerationStopwatch.Stop();
- // D1-10:补气物理动作审计(每次补气会话一行)。全 try 兜底。
- try
- {
- Aivfo.OperationLog.OperationLogger.Log("补气", "缺压补气",
- input: new { houseSn = House.houseSn, port = PortName, pressureAlarmMin = TLSetting.pressureAlarmMin },
- output: new { pressure = Pressure, valveState = ValveState.ToString() },
- result: "成功",
- elapsedMs: (long)AerationStopwatch.Elapsed.TotalMilliseconds,
- houseSn: House.houseSn, tlSn: TLSetting?.tlSn);
- }
- catch { }
- }
- catch (Exception ex)
- {
- ExceptionLogEvent?.Invoke(ex, $"[{House.houseSn}][{PortName}]补气", null, LogEnum.RunException);
- try
- {
- Aivfo.OperationLog.OperationLogger.Log("补气", "缺压补气",
- input: new { houseSn = House.houseSn, port = PortName },
- result: "失败", error: ex.GetType().Name + ": " + ex.Message,
- houseSn: House.houseSn, tlSn: TLSetting?.tlSn);
- }
- catch { }
- }
- }
- /// <summary>
- /// 排气
- /// </summary>
- /// <param name="custom"></param>
- /// <param name="commandSource"></param>
- private void PaiQi(CustomProtocol custom, CommandSource commandSource, int waitTime)
- {
- Stopwatch AerationStopwatch = Stopwatch.StartNew();
- Stopwatch VentWaitStopwatch = Stopwatch.StartNew();
- try
- {
- HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[{House.houseSn}][{this.PortName}][排气开始时间:{DateTime.Now}]", LogEnum.HouseInfo);
- ValveState = State.排气;
- decimal oldPressure = 0m;
- for (int i = 1; i <= VentNum; i++)
- {
- if (IsDoorOpen != State.关闭 || Pressure <= VentPre) break;
- oldPressure = Pressure;
- ComBin.HouseVentWait(custom);
- VentWaitStopwatch.Restart();
- do
- {
- Thread.Sleep(500);
- HouseState(commandSource, custom, 0);
- } while (VentWaitStopwatch.ElapsedMilliseconds < waitTime);
- HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[{House.houseSn}][{this.PortName}]排气完成[{oldPressure}->{Pressure}]", LogEnum.HouseInfo);
- }
- if (Pressure > VentPre)
- {
- if (PaiQiState != 1)
- {
- PaiQiState = 1;
- HouseStateEvent?.Invoke(House.houseSn, houseState, -1, -1, -1, 1);
- }
- }
- else
- {
- if (PaiQiState != 0)
- {
- PaiQiState = 0;
- HouseStateEvent?.Invoke(House.houseSn, houseState, -1, -1, -1, 0);
- }
- }
- this.ValveState = State.正常;
- if (Pressure < TLSetting.pressureAlarmMin) this.ValveState = State.待补气;
- HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[{House.houseSn}][{this.PortName}][排气结束时间:{DateTime.Now}][耗时:{StringHelper.TimeToString(AerationStopwatch.Elapsed)}]", LogEnum.HouseInfo);
- }
- catch (Exception ex)
- {
- ExceptionLogEvent?.Invoke(ex, $"[{House.houseSn}][{PortName}]补气", null, LogEnum.RunException);
- }
- finally
- {
- AerationStopwatch.Stop();
- VentWaitStopwatch.Stop();
- }
- }
- /// <summary>
- /// 读取仓室的仓门状态、温度、压力
- /// </summary>
- public void HouseState(CommandSource commandSource, CustomProtocol custom, int waitTime)
- {
- custom.commandSource = commandSource;
- //读仓门状态
- IsDoorOpen = ComBin.DoorStatusWait(custom);
- if (waitTime > 0) Thread.Sleep(waitTime);
- //仓室温度(下盖板温度)
- Temperature2 = ComBin.TemperatureWait(custom);
- Temperature = Temperature2 - TargetTemp + 37;
- if (waitTime > 0) Thread.Sleep(waitTime);
- //上盖板温度
- Temperature1 = ComBin.ShangTemperatureWait(custom);
- if (waitTime > 0) Thread.Sleep(waitTime);
- //玻璃片下方温度
- Temperature3 = ComBin.BoLiTemperatureWait(custom);
- if (waitTime > 0) Thread.Sleep(waitTime);
- //仓室压力
- Pressure = ComBin.PressureWait(custom);
- if (waitTime > 0) Thread.Sleep(waitTime);
- }
- public bool IsCCD()
- {
- var newList = Dish.Embryo.Where(x => x.state == (int)EmbryoState.None).Select(x => x.wellSn).ToList();
- if (newList != null && newList.Any())
- {
- wellList.Clear();
- foreach (var item in newList)
- {
- wellList.Add(item, LastAutoFocusTimeDic[item]);
- }
- return true;
- }
- return false;
- }
- int GetCCDAutoNum = 2;
- /// <summary>
- /// 是否自动对焦
- /// </summary>
- /// <returns></returns>
- private bool StartAutoFocus()
- {
- if (!IsCCD())
- {
- HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[{House.houseSn}][{this.PortName}][胚胎不需要自动对焦(所有胚胎状态不为0) [tlSN:{Dish.tlSn}] [DishID:{Dish.id}]]", LogEnum.HouseInfo);
- return false;
- }
- _autoFocusPhoto.Clear();
- // ════════════════════════════════════════════════════════════════
- // M2-06 场景B产线启用安全门(设备级开关 tl_setting.local_autofocus_enabled)。
- // 依据:计划 M2-06 小节、03 §2(场景B 稳定后再启用)/§6(三上线前置:74000伪峰/真胚胎峰比/EEPROM回写)。
- // 算法严谨性未在真机验证通过前,默认关闭(=0)走【降级】,避免错误对焦污染真实胚胎拍摄;
- // 三前置有结论后人工置 1=启用,走下方 M2-03 本地四步标定对焦(场景B 正式上线)。
- // 启用(=1):fall through → M2-03 本地 CalibrationEngine 对焦。
- // 关闭(=0,默认安全):降级——按 scene=0 出厂基准 FocusZ 填 _autoFocusPhoto,沿用既有/基准位置拍照,
- // 不做实际对焦;无基准的 well 跳过(不污染拍摄)。明确日志便于现场判断。
- // ⚠ 待验证 V-060/V-061/V-062/V-063:场景B放皿自动对焦出图、降级行为正确不污染拍摄、开关生效、三前置关联。
- // ════════════════════════════════════════════════════════════════
- bool localAfEnabled = TLSetting != null && TLSetting.localAutofocusEnabled == 1;
- if (!localAfEnabled)
- {
- // 安全门关闭:降级到基准/既有位置拍照(不做本地实际对焦)。
- string tlSnDg = TLSetting != null ? TLSetting.tlSn : (Dish != null ? Dish.tlSn : null);
- int filled = 0;
- foreach (var well in wellList.Keys)
- {
- int? baseZ = AutofocusStore != null && AutofocusStore.BaselineReader != null
- ? AutofocusStore.BaselineReader(tlSnDg, House.houseSn, well)
- : null;
- if (baseZ.HasValue && baseZ.Value > 0)
- {
- _autoFocusPhoto.Add(new HouseWellPhoto { wellSn = well, verticalMotorPosition = baseZ.Value });
- filled++;
- }
- else
- {
- // M2-06 修复(A1):scene=0 基准取不到时,回退该 well 既有清晰拍摄 Z(eepromClearPosition,与 operate verNewValue 默认同源),避免默认安全门关闭时不拍照。
- var wsDg = _wellSettings != null ? _wellSettings.FirstOrDefault(x => x.wellSn == well) : null;
- if (wsDg != null && wsDg.eepromClearPosition > 0)
- {
- _autoFocusPhoto.Add(new HouseWellPhoto { wellSn = well, verticalMotorPosition = wsDg.eepromClearPosition });
- filled++;
- HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[{House.houseSn}][{this.PortName}][本地自动对焦未启用(安全门关闭),{well}号well无scene=0基准,回退eepromClearPosition={wsDg.eepromClearPosition}拍照] [tlSN:{tlSnDg}]", LogEnum.HouseInfo);
- }
- else
- {
- HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[{House.houseSn}][{this.PortName}][本地自动对焦未启用(安全门关闭),{well}号well无scene=0基准且无eepromClearPosition,跳过该well] [tlSN:{tlSnDg}]", LogEnum.HouseInfo);
- }
- }
- }
- if (filled > 0)
- {
- GetCCDDefeatNum = 0;
- HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[{House.houseSn}][{this.PortName}][本地自动对焦未启用(安全门关闭),按scene=0基准位置拍照,已填充{filled}个well] [tlSN:{tlSnDg}] [DishID:{(Dish != null ? Dish.id : 0)}]", LogEnum.HouseInfo);
- return true;
- }
- GetCCDDefeatNum++;
- HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[{House.houseSn}][{this.PortName}][本地自动对焦未启用(安全门关闭),且无任何scene=0基准位置可用,本轮不拍照] [tlSN:{tlSnDg}] [DishID:{(Dish != null ? Dish.id : 0)}]", LogEnum.HouseInfo);
- return false;
- }
- // ────────────────────────────────────────────────────────────────
- // M2-03 本地自动对焦:对本舱 wellList 逐 well 调本地 CalibrationEngine 算 FocusZ,填 _autoFocusPhoto。
- // (仅当 M2-06 安全门启用 local_autofocus_enabled=1 时执行;关闭时已在上方降级 return。)
- // 取代原"先服务器(GetAutoFocusServiceEvent)后本地DB(GetAutoFocusDBEvent)"的云端/DB 取数链。
- // 老事件 GetAutoFocusServiceEvent/GetAutoFocusDBEvent 声明保留(死代码隔离/兜底,默认不走)。
- // verticalMotorPosition 承载 FocusZ 锚点(与原 clearPosition 同位,下游 :1555/:1707 按 wellSn 取)。
- // HAL 借用:Acquire(AutoFocus) 前台优先,HAL 暂停本舱采集;using 归还后自动 ResumeCapture。
- // ⚠ 待验证 V-046/V-049:本地对焦驱动拍照闭环、HAL 借用与采集互斥(关联 V-003/V-023)。
- // 标定结果落 JSON/库镜像由 M2-04 完成(此处暂未接入存储入口)。
- // ────────────────────────────────────────────────────────────────
- try
- {
- var gate = HardwareAccessLayer.Instance.GetHouseGate(House.houseSn);
- if (gate == null)
- {
- HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[{House.houseSn}][{this.PortName}][本地自动对焦:未取到舱借用闸门,跳过本轮] [tlSN:{Dish.tlSn}] [DishID:{Dish.id}]]", LogEnum.HouseInfo);
- return false;
- }
- // 前台优先借用本舱(串口+相机),HAL 暂停 control 采集;拿不到则本轮跳过(让路)。
- using (var lease = gate.Acquire(HardwareUser.AutoFocus, TLSetting != null ? Math.Max(30000, TLSetting.motorDelay * 16) : 30000))
- {
- if (lease == null)
- {
- HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[{House.houseSn}][{this.PortName}][本地自动对焦:申请硬件借用超时(采集占用),跳过本轮] [tlSN:{Dish.tlSn}] [DishID:{Dish.id}]]", LogEnum.HouseInfo);
- return false;
- }
- if (lease.Serial == null || lease.Camera == null)
- {
- HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[{House.houseSn}][{this.PortName}][本地自动对焦:借用到的串口/相机为空,跳过本轮] [tlSN:{Dish.tlSn}] [DishID:{Dish.id}]]", LogEnum.HouseInfo);
- return false;
- }
- var engine = new CalibrationEngine(lease.Serial, lease.Camera)
- {
- Log = msg => HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[{House.houseSn}][{this.PortName}][本地对焦]{msg}", LogEnum.HouseInfo)
- };
- foreach (var well in wellList.Keys)
- {
- if (IsStopClearest || FirstClearest) break;
- try
- {
- // EEPROM 仅作扫描中心(参考),不进配置解析链、不回写(§2.5)。
- int hpos = lease.Serial.ReadWellHorizontalPosWait(well);
- int zZero = lease.Serial.ReadWellFocusZeroWait(well);
- var wc = engine.CalibrateWell(well, Math.Max(0, hpos), Math.Max(0, zZero));
- if (wc == null)
- {
- HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[{House.houseSn}][{this.PortName}][{well}号well本地对焦无结果,跳过该well]", LogEnum.HouseInfo);
- continue;
- }
- _autoFocusPhoto.Add(new HouseWellPhoto { wellSn = well, verticalMotorPosition = wc.FocusZ });
- // M2-04:标定结果落 JSON 真相源 + 镜像 house_autofocus_calibration。
- // 日常对焦(放皿/门/定时触发)走 scene=1 append;调试页一键基准 scene=0(M2-05 接入)。
- // 存储失败不崩对焦线程(CalibrationStore 内部已 try/catch 吞异常并记日志)。
- try
- {
- AutofocusStore?.SaveCalibration(wc,
- TLSetting != null ? TLSetting.tlSn : (Dish != null ? Dish.tlSn : null),
- House.houseSn, well, scene: 1,
- port: House.housePort, ccdSn: House.ccdSn);
- }
- catch (Exception exStore)
- {
- ExceptionLogEvent?.Invoke(exStore, $"[{House.houseSn}][{this.PortName}][{well}号well标定结果存储失败]", null, LogEnum.RunException);
- }
- }
- catch (Exception exWell)
- {
- // 单 well 对焦失败不崩采集线程:记日志/告警,继续下一 well。
- ExceptionLogEvent?.Invoke(exWell, $"[{House.houseSn}][{this.PortName}][{well}号well本地自动对焦失败]", null, LogEnum.RunException);
- }
- }
- } // lease.Dispose() → 归还借用,HAL 恢复采集
- }
- catch (Exception ex)
- {
- // 本地对焦整体异常(借用/构造引擎等)不崩采集线程:记日志,本轮按失败处理。
- ExceptionLogEvent?.Invoke(ex, $"[{House.houseSn}][{this.PortName}][本地自动对焦异常]", null, LogEnum.RunException);
- return false;
- }
- if (_autoFocusPhoto != null && _autoFocusPhoto.Any())
- {
- GetCCDDefeatNum = 0;
- return true;
- }
- GetCCDDefeatNum++;
- HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[{House.houseSn}][{this.PortName}][第{GetCCDDefeatNum}次本地自动对焦未获取到位置数据] [tlSN:{Dish.tlSn}] [DishID:{Dish.id}]]", LogEnum.HouseInfo);
- return false;
- }
- /// <summary>
- /// 是否拍照
- /// </summary>
- /// <returns></returns>
- private bool StartCCD()
- {
- if (!IsCCD())
- {
- HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[{House.houseSn}][{this.PortName}][胚胎不需要拍照(所有胚胎状态不为0) [tlSN:{Dish.tlSn}] [DishID:{Dish.id}]]", LogEnum.HouseInfo);
- return false;
- }
- _ccdPhoto.Clear();
- var resultDTO = GetCCDServiceEvent?.Invoke(House.houseSn, wellList);
- if (resultDTO != null && resultDTO.complete == 0)
- {
- foreach (var item in resultDTO.positionVOList)
- {
- _ccdPhoto.Add(ConvertHelper.ConvertToHouseWellPhoto(item));
- }
- if (_ccdPhoto.Any())
- {
- GetCCDDefeatNum = 0;
- return true;
- }
- else
- {
- GetCCDDefeatNum++;
- HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[{House.houseSn}][{this.PortName}][第{GetCCDDefeatNum}次获取到拍照位置数据:服务器返回自动对焦完成,但是无拍照位置数据] [tlSN:{Dish.tlSn}] [DishID:{Dish.id}]]", LogEnum.HouseInfo);
- }
- }
- else
- {
- if (resultDTO == null)
- {
- GetCCDDefeatNum++;
- HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[{House.houseSn}][{this.PortName}][第{GetCCDDefeatNum}次获取到拍照位置数据:服务器返回空] [tlSN:{Dish.tlSn}] [DishID:{Dish.id}]]", LogEnum.HouseInfo);
- }
- else
- {
- if (resultDTO.complete == 1)
- {
- GetCCDDefeatNum++;
- HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[{House.houseSn}][{this.PortName}][第{GetCCDDefeatNum}次获取拍照位置数据:服务器返回自动对焦未完成] [tlSN:{Dish.tlSn}] [DishID:{Dish.id}]]", LogEnum.HouseInfo);
- }
- }
- }
- if (GetCCDDefeatNum >= GetCCDAutoNum)
- {
- HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[{House.houseSn}][{this.PortName}][从本地数据库获取拍照位置数据] [tlSN:{Dish.tlSn}] [DishID:{Dish.id}]]", LogEnum.HouseInfo);
- GetCCDDefeatNum = 0;
- _ccdPhoto = GetCCDDBEvent?.Invoke(House.houseSn, wellList);
- if (_ccdPhoto != null && _ccdPhoto.Any())
- {
- return true;
- }
- HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[{House.houseSn}][{this.PortName}][本地数据库获取拍照位置数据失败] [tlSN:{Dish.tlSn}] [DishID:{Dish.id}]]", LogEnum.HouseInfo);
- }
- return false;
- }
- #endregion
- #region 自动对焦流程
- private object AutoFocusWellsLock = new object();
- /// <summary>
- /// 单个自动对焦well
- /// </summary>
- public List<int> AutoFocusWells = new List<int>();
- /// <summary>
- /// 自动对焦流程
- /// </summary>
- /// <param name="commandSource"></param>
- public bool GetClearest(CommandSource commandSource)
- {
- bool rs = false;
- UpdateAutofocusStateEvent?.Invoke(true, House.houseSn);
- if (AutoFocusWellAny())
- {
- rs = SingleEmbryoAutofocus(commandSource);
- }
- else
- {
- rs = AllEmbryoAutofocus(commandSource);
- if (!rs)
- {
- AutoFocusWellClear();
- }
- }
- if (rs)
- {
- UpdateAutofocusStateEvent?.Invoke(false, House.houseSn);
- }
- return rs;
- }
- /// <summary>
- /// 自动对焦
- /// </summary>
- /// <param name="taskThread"></param>
- /// <returns></returns>
- /// <exception cref="NotImplementedException"></exception>
- private bool AllEmbryoAutofocus(CommandSource commandSource)
- {
- LastRunTime = DateTime.Now;
- if (House.openCcd == 0)
- {
- HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[{House.houseSn}][{PortName}][未打开相机,跳过自动对焦操作]", LogEnum.HouseInfo);
- return true;
- }
- bool isSuccess = true;
- Stopwatch AutofocusThreadStopwatch = Stopwatch.StartNew();
- var custom = new CustomProtocol();//指令包
- custom.commandSource = commandSource;
- this.RunState = "自动对焦";
- WorkingType = WorkingType.AutoFocusWorking;
- var pictureId = 1;
- try
- {
- int AutofocusEmbryoCount = 0;
- foreach (var item in this.Dish.Embryo)
- {
- if (item.state == 0)
- {
- AutofocusEmbryoCount++;
- }
- }
- var embryoList = this.Dish.Embryo.OrderBy(x => x.wellSn);
- HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[{House.houseSn}][{this.PortName}][胚胎数:{AutofocusEmbryoCount}/{this.Dish.embryoCount}][自动对焦开始时间:{DateTime.Now}]", LogEnum.HouseInfo);
- if (AutofocusEmbryoCount > 0)
- {
- HouseState(commandSource, custom, 0);
- //水平电机复位运动
- ComBin.HorizontalMotorResetWait(custom, TLSetting.motorDelay);
- HouseState(commandSource, custom, 0);
- if (isWuTu)
- {
- var startNoView = Camera.Usb2StartCapture();
- HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[{House.houseSn}][{PortName}][无图预览开启结果:{startNoView}]", LogEnum.HouseInfo);
- }
- //打开CCD补光LED
- ComBin.OpenLEDWait(custom);
- foreach (var itemEmbryo in embryoList)
- {
- DateTime SavePictrueTime = DateTime.Now;
- LastRunTime = DateTime.Now;
- if (IsStopClearest || FirstClearest)
- {
- isSuccess = false;
- break;
- }
- if (itemEmbryo.state != 0)
- {
- continue;
- }
- var currentHorSetting = _wellSettings.FirstOrDefault(x => x.wellSn == itemEmbryo.wellSn);
- if (currentHorSetting == null)
- {
- HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[{House.houseSn}][{PortName}][未获取到{itemEmbryo.wellSn}号well的水平电机位置]", LogEnum.HouseInfo);
- continue;
- }
- var currentAutoFocus = _autoFocusPhoto.FirstOrDefault(x => x.wellSn == itemEmbryo.wellSn);
- if (currentAutoFocus == null)
- {
- HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[{House.houseSn}][{PortName}][未获取到{itemEmbryo.wellSn}号well的自动对焦位置]", LogEnum.HouseInfo);
- continue;
- }
- if (IsDoorOpen == State.关闭 && TLSetting.pressureAlarmMin > Pressure)
- AerationNew(commandSource, custom);
- ComBin.HorizontalMotorAbsoluteWait(custom, TLSetting.motorDelay, currentHorSetting.horizontalMotorPosition);
- HouseState(commandSource, custom, 0);
- //垂直电机复位运动
- ComBin.VerticalMotorResetWait(custom, TLSetting.motorDelay);
- HouseState(commandSource, custom, 0);
- // ────────────────────────────────────────────────────────────────
- // M2-03 改造点2:N 层拍摄位置改用 M2-02 PhotoLayerCalculator(§2.4 公式 + §2.5 就近优先),
- // 取代旧公式(verticalMotorPosition + spacePulse*i,无下移、值缺时硬编码128)。
- // focusZ = currentAutoFocus.verticalMotorPosition (本地对焦算出的最清晰层锚点)
- // 配置就近优先:well(currentHorSetting) 覆盖 → 设备级(TLSetting) → 缺层间距抛 FocusConfigMissingException
- // 层间距未配置 → 写告警日志 + 本 well 本轮跳过(§2.5 不兜底)。
- // ⚠ 待验证 V-046/V-048:层公式真机下发一致(关联 V-002/V-024)、配置缺失对焦失败不崩。
- // ────────────────────────────────────────────────────────────────
- int[] layerPositions;
- try
- {
- var rawCfg = new FocusLayerRawConfig
- {
- WellSpacingPulse = currentHorSetting.focusLayerSpacingPulse,
- WellLayerCount = currentHorSetting.focusLayerCount,
- WellMoveDownLayer = currentHorSetting.moveDownLayer, // well 级下移复用 move_down_layer
- DeviceSpacingPulse = TLSetting.focusLayerSpacingPulse,
- DeviceLayerCount = TLSetting.focusLayerCount,
- DeviceLayerDown = TLSetting.focusLayerDown,
- TlSn = Dish?.tlSn,
- HouseSn = House.houseSn,
- WellSn = itemEmbryo.wellSn
- };
- var layerCfg = PhotoLayerCalculator.Resolve(rawCfg);
- layerPositions = PhotoLayerCalculator.ComputeLayerPositions(
- currentAutoFocus.verticalMotorPosition, layerCfg, TLSetting.verticalMotorPulseMax);
- }
- catch (FocusConfigMissingException exCfg)
- {
- // 配置缺失:本 well 本轮跳过,不用魔法数兜底、不崩采集线程(§2.5)。
- HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[{House.houseSn}][{PortName}][{itemEmbryo.wellSn}号well对焦层配置缺失,跳过该well:{exCfg.Message}]", LogEnum.HouseInfo);
- isSuccess = false;
- continue;
- }
- int currentVer = 0;
- int nextVer = 0;
- bool isEnd = false;
- for (int i = 0; i < layerPositions.Length; i++)
- {
- isEnd = false;
- currentVer = 0;
- nextVer = 0;
- LastRunTime = DateTime.Now;
- this.RunState = $"自动对焦({itemEmbryo.wellSn}-{i + 1})";
- if (IsStopClearest || FirstClearest)
- {
- isSuccess = false;
- break;
- }
- // M2-03:第 i 层绝对 Z 由 PhotoLayerCalculator 算出(含下移偏移 + verticalMotorPulseMax 钳位)。
- currentVer = layerPositions[i];
- nextVer = (i + 1 < layerPositions.Length) ? layerPositions[i + 1] : currentVer;
- if (currentVer > TLSetting.verticalMotorPulseMax) break;
- if (i == (layerPositions.Length - 1) || nextVer > TLSetting.verticalMotorPulseMax) isEnd = true;
- ComBin.VerticalMotorAbsoluteWait(custom, TLSetting.motorDelay, currentVer, currentHorSetting.horizontalMotorPosition, pictureId++, itemEmbryo.wellSn, (i + 1));
- HouseState(commandSource, custom, 0);
- currentHorizontalMotor = ComBin.ReadHorizontalMotorWait(custom);
- currentVerticalMotor = ComBin.ReadVerticalMotorWait(custom);
- var AutofocusResult = Autofocus(custom, isEnd, itemEmbryo, SavePictrueTime, layerPositions.Length, (i + 1));
- if (!AutofocusResult) isSuccess = false;
- if (isEnd && AutofocusResult) LastAutoFocusTimeDic[itemEmbryo.wellSn] = SavePictrueTime;
- HouseState(commandSource, custom, 0);
- if (CCDState == 1)
- {
- HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[{itemEmbryo.wellSn}号well第{i + 1}层拍照异常,结束当前well自动对焦]", LogEnum.HouseInfo);
- break;
- }
- }
- if (CCDState == 1)
- {
- HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[{itemEmbryo.wellSn}号well拍照异常,终止全胚胎自动对焦流程]", LogEnum.HouseInfo);
- break;
- }
- }
- ComBin.CloseLEDWait(custom);
- if (isWuTu)
- {
- var stopNoView = Camera.Usb2StopCapture();
- HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[{House.houseSn}][{PortName}][无图预览关闭结果:{stopNoView}]", LogEnum.HouseInfo);
- }
- ComBin.HorizontalMotorResetWait(custom, TLSetting.motorDelay);
- if (isSuccess) HouseState(commandSource, custom, 0);
- }
- }
- catch (Exception ex)
- {
- ExceptionLogEvent?.Invoke(ex, $"[{House.houseSn}][{this.PortName}]自动对焦", null, LogEnum.RunException);
- isSuccess = false;
- }
- finally
- {
- WorkingType = WorkingType.DoNothing;
- HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[{House.houseSn}][{this.PortName}][自动对焦结果:{isSuccess}][自动对焦结束时间:{DateTime.Now}][全程耗时:{ivf_tl_UtilHelper.StringHelper.TimeToString(AutofocusThreadStopwatch.Elapsed)}]", LogEnum.HouseInfo);
- AutofocusThreadStopwatch.Stop();
- }
- return isSuccess;
- }
- /// <summary>
- /// 单个胚胎自动对焦
- /// </summary>
- /// <param name="item"></param>
- /// <param name="custom"></param>
- /// <returns></returns>
- public bool SingleEmbryoAutofocus(CommandSource commandSource)
- {
- LastRunTime = DateTime.Now;
- if (House.openCcd == 0)
- {
- HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[{House.houseSn}][{PortName}][未打开相机,跳过自动对焦操作]", LogEnum.HouseInfo);
- return true;
- }
- bool isSuccess = true;
- int currentVer = 0;
- int nextVer = 0;
- bool isEnd = false;
- int pictureId = 1;
- Stopwatch AutofocusThreadStopwatch = Stopwatch.StartNew();
- try
- {
- this.RunState = "自动对焦";
- WorkingType = WorkingType.AutoFocusWorking;
- HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[{House.houseSn}][{this.PortName}][对焦well:{string.Join(",", AutoFocusWells)}][部分well自动对焦开始时间:{DateTime.Now}]", LogEnum.HouseInfo);
- var custom = new CustomProtocol();
- custom.commandSource = commandSource;
- HouseState(commandSource, custom, 0);
- //水平电机复位运动
- ComBin.HorizontalMotorResetWait(custom, TLSetting.motorDelay);
- HouseState(commandSource, custom, 0);
- if (isWuTu)
- {
- var startNoView = Camera.Usb2StartCapture();
- HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[{House.houseSn}][{PortName}][无图预览开启结果:{startNoView}]", LogEnum.HouseInfo);
- }
- ComBin.OpenLEDWait(custom);
- do
- {
- DateTime SavePictrueTime = DateTime.Now;
- LastRunTime = DateTime.Now;
- int well = AutoFocusWellFirst();
- var embryoItem = this.Dish.Embryo.FirstOrDefault(x => x.wellSn == well);
- if (embryoItem == null)
- {
- HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[{House.houseSn}][{PortName}][当前well:{well}][没有找到对应的胚胎]", LogEnum.HouseInfo);
- continue;
- }
- if (embryoItem.state != (int)EmbryoState.None)
- {
- HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[{House.houseSn}][{PortName}][当前well:{well}][胚胎状态不为0:{embryoItem.state},{embryoItem.id}]", LogEnum.HouseInfo);
- continue;
- }
- if (IsStopClearest || FirstClearest)
- {
- isSuccess = false;
- break;
- }
- var currentHorSetting = _wellSettings.FirstOrDefault(x => x.wellSn == embryoItem.wellSn);
- if (currentHorSetting == null)
- {
- HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[{House.houseSn}][{PortName}][未获取到{embryoItem.wellSn}号well的水平电机位置]", LogEnum.HouseInfo);
- continue;
- }
- var currentAutoFocus = _autoFocusPhoto.FirstOrDefault(x => x.wellSn == embryoItem.wellSn);
- if (currentAutoFocus == null)
- {
- HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[{House.houseSn}][{PortName}][未获取到{embryoItem.wellSn}号well的自动对焦位置]", LogEnum.HouseInfo);
- continue;
- }
- //水平电机绝对运动
- ComBin.HorizontalMotorAbsoluteWait(custom, TLSetting.motorDelay, currentHorSetting.horizontalMotorPosition);
- HouseState(commandSource, custom, 0);
- //垂直电机复位运动
- ComBin.VerticalMotorResetWait(custom, TLSetting.motorDelay);
- HouseState(commandSource, custom, 0);
- if (IsDoorOpen == State.关闭 && TLSetting.pressureAlarmMin > Pressure)
- AerationNew(commandSource, custom);
- if (currentAutoFocus.verticalMotorPosition >= TLSetting.verticalMotorPulseMax)
- {
- DeleteAutoFocusWell(embryoItem.wellSn);
- HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[{House.houseSn}][{PortName}][{embryoItem.wellSn}号well自动对焦起点大于最高位置 {currentAutoFocus.verticalMotorPosition}>{TLSetting.verticalMotorPulseMax}]", LogEnum.HouseInfo);
- }
- else
- {
- // ────────────────────────────────────────────────────────────────
- // V-050:本路径(单/部分胚胎手动对焦)N 层位置统一改用 M2-02 PhotoLayerCalculator
- // (§2.4 公式 + §2.5 就近优先),与主路径 AllEmbryoAutofocus 一致,
- // 取代旧公式(verticalMotorPosition + spacePulse*j / 硬编码128,无下移)。
- // focusZ 锚点 = currentAutoFocus.verticalMotorPosition(本 well 对焦算出的清晰层)。
- // 就近优先:well(currentHorSetting) 覆盖 → 设备级(TLSetting) → 缺层间距抛
- // FocusConfigMissingException,本 well 跳过(continue 外层 well 循环),不兜底、不崩。
- // ⚠ 待验证 V-050:与主路径层公式真机一致、配置缺失不崩。
- // ────────────────────────────────────────────────────────────────
- int[] layerPositions;
- try
- {
- var rawCfg = new FocusLayerRawConfig
- {
- WellSpacingPulse = currentHorSetting.focusLayerSpacingPulse,
- WellLayerCount = currentHorSetting.focusLayerCount,
- WellMoveDownLayer = currentHorSetting.moveDownLayer, // well 级下移复用 move_down_layer
- DeviceSpacingPulse = TLSetting.focusLayerSpacingPulse,
- DeviceLayerCount = TLSetting.focusLayerCount,
- DeviceLayerDown = TLSetting.focusLayerDown,
- TlSn = Dish?.tlSn,
- HouseSn = House.houseSn,
- WellSn = embryoItem.wellSn
- };
- var layerCfg = PhotoLayerCalculator.Resolve(rawCfg);
- layerPositions = PhotoLayerCalculator.ComputeLayerPositions(
- currentAutoFocus.verticalMotorPosition, layerCfg, TLSetting.verticalMotorPulseMax);
- }
- catch (FocusConfigMissingException exCfg)
- {
- // 配置缺失:本 well 本轮跳过,不用魔法数兜底、不崩采集线程(§2.5)。
- HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[{House.houseSn}][{PortName}][{embryoItem.wellSn}号well对焦层配置缺失,跳过该well:{exCfg.Message}]", LogEnum.HouseInfo);
- isSuccess = false;
- continue;
- }
- for (int j = 0; j < layerPositions.Length; j++)
- {
- isEnd = false;
- currentVer = 0;
- nextVer = 0;
- LastRunTime = DateTime.Now;
- if (IsStopClearest || FirstClearest)
- {
- isSuccess = false;
- break;
- }
- this.RunState = $"自动对焦({embryoItem.wellSn}-{j + 1})";
- // V-050:第 j 层绝对 Z 由 PhotoLayerCalculator 算出(含下移偏移 + verticalMotorPulseMax 钳位)。
- currentVer = layerPositions[j];
- nextVer = (j + 1 < layerPositions.Length) ? layerPositions[j + 1] : currentVer;
- if (currentVer > TLSetting.verticalMotorPulseMax)
- {
- //DeleteAutoFocusWell(embryoItem.wellSn);
- //LastAutoFocusTimeDic[embryoItem.wellSn] = SavePictrueTime;
- break;
- }
- if (j == (layerPositions.Length - 1) || nextVer > TLSetting.verticalMotorPulseMax) isEnd = true;
- ComBin.VerticalMotorAbsoluteWait(custom, TLSetting.motorDelay, currentVer, currentHorSetting.horizontalMotorPosition, pictureId++, embryoItem.wellSn, (j + 1));
- HouseState(commandSource, custom, 0);
- currentHorizontalMotor = ComBin.ReadHorizontalMotorWait(custom);
- currentVerticalMotor = ComBin.ReadVerticalMotorWait(custom);
- //抓图
- var AutofocusResult = Autofocus(custom, isEnd, embryoItem, SavePictrueTime, layerPositions.Length, (j + 1));
- HouseState(commandSource, custom, 0);
- if (CCDState == 1)
- {
- HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[{embryoItem.wellSn}号well第{j + 1}层拍照异常,结束当前well自动对焦]", LogEnum.HouseInfo);
- break;
- }
- if (isEnd)
- {
- DeleteAutoFocusWell(embryoItem.wellSn);
- if (AutofocusResult) LastAutoFocusTimeDic[embryoItem.wellSn] = SavePictrueTime;
- }
- }
- if (CCDState == 1)
- {
- isSuccess = false;
- HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[{embryoItem.wellSn}号well拍照异常,终止部分胚胎自动对焦流程]", LogEnum.HouseInfo);
- break;
- }
- }
- } while (AutoFocusWellAny());
- //关闭CCD补光LED
- ComBin.CloseLEDWait(custom);
- if (isWuTu)
- {
- var stopNoView = Camera.Usb2StopCapture();
- HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[{House.houseSn}][{PortName}][无图预览关闭结果:{stopNoView}]", LogEnum.HouseInfo);
- }
- ComBin.HorizontalMotorResetWait(custom, TLSetting.motorDelay);
- if (isSuccess)
- {
- HouseState(commandSource, custom, 0);
- }
- }
- catch (Exception ex)
- {
- ExceptionLogEvent?.Invoke(ex, $"[{House.houseSn}][{this.PortName}]部分Well自动对焦", null, LogEnum.RunException);
- isSuccess = false;
- }
- finally
- {
- WorkingType = WorkingType.DoNothing;
- HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[{House.houseSn}][{this.PortName}][自动对焦结果:{isSuccess}][部分well自动对焦结束时间:{DateTime.Now}][全程耗时:{ivf_tl_UtilHelper.StringHelper.TimeToString(AutofocusThreadStopwatch.Elapsed)}]", LogEnum.HouseInfo);
- AutofocusThreadStopwatch.Stop();
- }
- return isSuccess;
- }
- public void AddAutoFocusWell(int well)
- {
- lock (AutoFocusWellsLock)
- {
- if (!AutoFocusWells.Contains(well))
- {
- AutoFocusWells.Add(well);
- }
- }
- }
- public void DeleteAutoFocusWell(int well)
- {
- lock (AutoFocusWellsLock)
- {
- if (AutoFocusWells.Contains(well))
- {
- AutoFocusWells.Remove(well);
- }
- }
- }
- public bool AutoFocusWellAny()
- {
- lock (AutoFocusWellsLock)
- {
- return AutoFocusWells.Any();
- }
- }
- public void AutoFocusWellClear()
- {
- lock (AutoFocusWellsLock)
- {
- AutoFocusWells.Clear();
- }
- }
- public int AutoFocusWellFirst()
- {
- lock (AutoFocusWellsLock)
- {
- return AutoFocusWells.OrderBy(x => x).First();
- }
- }
- #endregion
- #region 拍照流程
- /// <summary>
- /// 拍照
- /// </summary>
- /// <exception cref="NotImplementedException"></exception>
- public void ccdThreadFun()
- {
- LastRunTime = DateTime.Now;
- if (House.openCcd == 0)
- {
- HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[{House.houseSn}][{PortName}][未打开相机,跳过拍照操作]", LogEnum.HouseInfo);
- return;
- }
- var custom = new CustomProtocol();//指令包
- custom.commandSource = CommandSource.ccdThread;
- Stopwatch CCDThreadStopwatch = Stopwatch.StartNew();
- var pictureId = 1;//图片编号,1-176号
- try
- {
- this.RunState = "胚胎拍照";
- WorkingType = WorkingType.CCDWorking;
- int AutofocusEmbryoCount = 0;
- foreach (var item in this.Dish.Embryo)
- {
- if (item.state == 0)
- {
- AutofocusEmbryoCount++;
- }
- }
- CCDThreadStopwatch.Restart();
- HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[{House.houseSn}][{PortName}][拍照开始时间:{DateTime.Now}][胚胎数:{AutofocusEmbryoCount}/{this.Dish.embryoCount}]", LogEnum.HouseInfo);
- if (AutofocusEmbryoCount == 0) return;
- HouseState(CommandSource.ccdThread, custom, 0);
- //水平电机复位运动
- ComBin.HorizontalMotorResetWait(custom, TLSetting.motorDelay);
- HouseState(CommandSource.ccdThread, custom, 0);
- var embryoList = this.Dish.Embryo.OrderBy(x => x.wellSn);
- int currentPicNum = 1;
- int allPicNum = House.photographPictureNumber;
- if (isWuTu)
- {
- var startNoView = Camera.Usb2StartCapture();
- HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[{House.houseSn}][{PortName}][无图预览开启结果:{startNoView}]", LogEnum.HouseInfo);
- }
- ComBin.OpenLEDWait(custom);
- foreach (var item in embryoList)
- {
- LastRunTime = DateTime.Now;
- if (IsStopCCD) break;
- if (item.state != 0) continue;
- var currentHorSetting = _wellSettings.FirstOrDefault(x => x.wellSn == item.wellSn);
- if (currentHorSetting == null)
- {
- HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[{House.houseSn}][{PortName}][未获取到{item.wellSn}号well的水平电机位置]", LogEnum.HouseInfo);
- continue;
- }
- if (IsDoorOpen == State.关闭 && TLSetting.pressureAlarmMin > Pressure) AerationNew(CommandSource.ccdThread, custom);
- ComBin.HorizontalMotorAbsoluteWait(custom, TLSetting.motorDelay, currentHorSetting.horizontalMotorPosition);
- HouseState(CommandSource.ccdThread, custom, 0);
- //垂直电机复位运动
- ComBin.VerticalMotorResetWait(custom, TLSetting.motorDelay);
- HouseState(CommandSource.ccdThread, custom, 0);
- currentPicNum = 1;
- var newList = _ccdPhoto.Where(x => x.wellSn == item.wellSn && x.clearest <= (allPicNum - 1) / 2 && x.clearest >= (-(allPicNum - 1) / 2)).OrderBy(x => x.clearest).ToList();
- DateTime SavePictrueTime = DateTime.Now;
- int newListCount = newList.Count;
- bool isEnd = false;
- for (int i = 0; i < newListCount; i++)
- {
- isEnd = false;
- LastRunTime = DateTime.Now;
- if (IsStopCCD) break;
- var motorItem = newList[i];
- if (i < (newListCount - 1))
- {
- var nextItem = newList[i + 1];
- if (nextItem.verticalMotorPosition > TLSetting.verticalMotorPulseMax) isEnd = true;
- }
- if (i == (newListCount - 1)) isEnd = true;
- if (motorItem.verticalMotorPosition > TLSetting.verticalMotorPulseMax) break;
- this.RunState = $"胚胎拍照({item.wellSn}-{currentPicNum})";
- ComBin.VerticalMotorAbsoluteWait(custom, TLSetting.motorDelay, motorItem.verticalMotorPosition, currentHorSetting.horizontalMotorPosition, pictureId++, item.wellSn, motorItem.clearest);
- currentHorizontalMotor = ComBin.ReadHorizontalMotorWait(custom);
- currentVerticalMotor = ComBin.ReadVerticalMotorWait(custom);
- Photograph(custom, motorItem.clearest, allPicNum, item, SavePictrueTime, motorItem.positionType, isEnd);
- currentPicNum++;
- HouseState(CommandSource.ccdThread, custom, 0);
- if (CCDState == 1)
- {
- HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[{item.wellSn}号well第{i + 1}层拍照异常,结束当前well拍照]", LogEnum.HouseInfo);
- break;
- }
- }
- if (CCDState == 1)
- {
- HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[{item.wellSn}号well拍照异常,终止当前拍照流程]", LogEnum.HouseInfo);
- break;
- }
- }
- ComBin.CloseLEDWait(custom);
- if (isWuTu)
- {
- var stopNoView = Camera.Usb2StopCapture();
- HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[{House.houseSn}][{PortName}][无图预览关闭结果:{stopNoView}]", LogEnum.HouseInfo);
- }
- ComBin.HorizontalMotorResetWait(custom, TLSetting.motorDelay);
- HouseState(CommandSource.ccdThread, custom, 0);
- }
- catch (Exception ex)
- {
- ExceptionLogEvent?.Invoke(ex, $"[{House.houseSn}][{PortName}]拍照线程", null, LogEnum.RunException);
- }
- finally
- {
- WorkingType = WorkingType.DoNothing;
- HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[{House.houseSn}][{PortName}][拍照结束时间:{DateTime.Now}][共计{(pictureId - 1)}张图][全程耗时:{StringHelper.TimeToString(CCDThreadStopwatch.Elapsed)}]", LogEnum.HouseInfo);
- CCDThreadStopwatch.Stop();
- }
- }
- #endregion
- #region 图片处理
- /// <summary>
- /// 抓图操作 0表示成功
- /// </summary>
- /// <returns></returns>
- public int GetRgbDataFun(string content, int wellSn)
- {
- CustomProtocol custom = new CustomProtocol();
- Stopwatch stopwatch = new Stopwatch();
- try
- {
- if (House.openCcd == 0)
- {
- HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[仓室相机关闭,跳过抓图]", LogEnum.HouseRunRecord);
- return -1;
- }
- HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[开始抓图][注:0表示成功]", LogEnum.HouseRunRecord);
- int GetRgbData = -1;
- bool isOpen = true;
- for (int i = 1; i <= CCDFailedNumber; i++)
- {
- if (Dish == null || Dish.id <= 0)
- {
- HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[没有培养记录,中断拍照操作]", LogEnum.HouseRunRecord);
- break;
- }
- if (isOpen)
- {
- if (isWuTu)
- {
- GetRgbData = Camera.GetRawData();//获取字节流
- HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[第{i}次无图预览抓拍结果:{GetRgbData}][注:0表示成功]", LogEnum.HouseRunRecord);
- if (GetRgbData == 0)
- {
- GetRgbData = Camera.RawToRgb();
- HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[rawToRgb结果:{GetRgbData}][注:0表示成功]", LogEnum.HouseRunRecord);
- }
- }
- else
- {
- if (CCDError)
- {
- GetRgbData = 20;
- }
- else
- {
- GetRgbData = Camera.GetRgbData();//获取字节流
- }
- HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[第{i}次抓拍结果:{GetRgbData}][注:0表示成功]", LogEnum.HouseRunRecord);
- }
- }
- if (GetRgbData == 0)
- {
- if (CCDState != 0)
- {
- CCDState = 0;
- CCDAutoStopwatch.Reset();
- HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[拍照成功,取消拍照异常报警]", LogEnum.HouseInfo);
- CCDStateEvent?.Invoke(House.houseSn, CCDState, ErrorWell);
- //HouseStateEvent?.Invoke(House.houseSn, -1, -1, CCDState, ErrorWell, -1);
- }
- break;
- }
- if (i == CCDFailedNumber)
- {
- if (CCDState != 1)
- {
- CCDState = 1;
- CCDAutoStopwatch.Start();
- HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[拍照连续失败{CCDFailedNumber}次,拍照异常报警]", LogEnum.HouseInfo);
- TLLogEvent?.Invoke($"[拍照连续失败{CCDFailedNumber}次,拍照异常报警]", LogEnum.RunError);
- CCDStateEvent?.Invoke(House.houseSn, CCDState, wellSn);
- //HouseStateEvent?.Invoke(House.houseSn, -1, -1, CCDState, wellSn, -1);
- ErrorWell = wellSn;
- }
- }
- else
- {
- //this.RunState = $"拍照失败,等待{CCDFailedWaitTime / 1000}S";
- this.RunState = $"take photos failed,wait for {CCDFailedWaitTime / 1000} S";
- stopwatch.Restart();
- do
- {
- HouseState(CommandSource.ccdThread, custom, 500);
- } while (stopwatch.ElapsedMilliseconds < CCDFailedWaitTime);
- }
- //HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[第{i}次关闭相机结果:{CloseCamera(content)}]", LogEnum.HouseRunRecord);
- //isOpen = OpenCamera(content);
- //HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[第{i}次开启相机结果:{isOpen}]", LogEnum.HouseRunRecord);
- }
- return GetRgbData;
- }
- catch (Exception ex)
- {
- ExceptionLogEvent?.Invoke(ex, $"[{House.houseSn}][{PortName}]抓图", null, LogEnum.RunException);
- return -1;
- }
- finally
- {
- stopwatch.Stop();
- }
- }
- /// <summary>
- /// 新的抓图操作,0表示成功
- /// </summary>
- /// <param name="content"></param>
- /// <param name="wellSn"></param>
- /// <returns></returns>
- public int GetRgbDataFunNew(string content, int wellSn)
- {
- CustomProtocol custom = new CustomProtocol();
- Stopwatch stopwatch = new Stopwatch();
- int rsData = -1;
- try
- {
- if (House.openCcd == 0)
- {
- HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[仓室相机关闭,跳过抓图]", LogEnum.HouseRunRecord);
- return -1;
- }
- HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[开始抓图][注:0表示成功]", LogEnum.HouseRunRecord);
- int GetRgbData = -1;
- bool isOpen = true;
- for (int i = 1; i <= CCDFailedNumber; i++)
- {
- if (Dish == null || Dish.id <= 0)
- {
- HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[没有培养记录,中断拍照操作]", LogEnum.HouseRunRecord);
- break;
- }
- if (isOpen && Camera != null && Camera.IsStart)
- {
- if (isWuTu)
- {
- GetRgbData = Camera.GetRawData();//获取字节流
- HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[第{i}次无图预览抓拍结果:{GetRgbData}][注:0表示成功]", LogEnum.HouseRunRecord);
- if (GetRgbData == 0)
- {
- GetRgbData = Camera.RawToRgb();
- HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[rawToRgb结果:{GetRgbData}][注:0表示成功]", LogEnum.HouseRunRecord);
- if (GetRgbData != 0)
- {
- TLLogEvent?.Invoke($"{content}[第{i}次rawToRgb结果:{GetRgbData}][注:0表示成功]", LogEnum.RunError);
- }
- else
- {
- Camera.UpdataSourceBuffer();
- }
- }
- else
- {
- TLLogEvent?.Invoke($"{content}[第{i}次无图预览抓拍结果:{GetRgbData}][注:0表示成功]", LogEnum.RunError);
- }
- }
- else
- {
- if (CCDError)
- {
- GetRgbData = 20;
- }
- else
- {
- GetRgbData = Camera.GetRgbData();//获取字节流
- }
- HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[第{i}次抓拍结果:{GetRgbData}][注:0表示成功]", LogEnum.HouseRunRecord);
- if (GetRgbData != 0)
- {
- TLLogEvent?.Invoke($"{content}[第{i}次抓拍结果:{GetRgbData}][注:0表示成功]", LogEnum.RunError);
- }
- else
- {
- Camera.UpdataSourceBuffer();
- }
- }
- }
- if (GetRgbData == 0 && Camera.CheckRgbData())
- {
- HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[第{i}次抓拍校验成功]", LogEnum.HouseRunRecord);
- rsData = 0;
- if (CCDState != 0)
- {
- CCDState = 0;
- CCDAutoStopwatch.Reset();
- HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[拍照成功,取消拍照异常报警]", LogEnum.HouseInfo);
- CCDStateEvent?.Invoke(House.houseSn, CCDState, ErrorWell);
- //HouseStateEvent?.Invoke(House.houseSn, -1, -1, CCDState, ErrorWell, -1);
- }
- break;
- }
- else
- {
- isOpen = false;
- HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[第{i}次抓拍校验失败][GetRgbData:{GetRgbData}][Camera != null:{Camera != null}]", LogEnum.HouseRunRecord);
- if (i == CCDFailedNumber)
- {
- if (CCDState != 1)
- {
- CCDState = 1;
- CCDAutoStopwatch.Start();
- HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[拍照连续失败{CCDFailedNumber}次,拍照异常报警]", LogEnum.HouseInfo);
- TLLogEvent?.Invoke($"[{content}][拍照连续失败{CCDFailedNumber}次,拍照异常报警]", LogEnum.RunError);
- CCDStateEvent?.Invoke(House.houseSn, CCDState, wellSn);
- //HouseStateEvent?.Invoke(House.houseSn, -1, -1, CCDState, wellSn, -1);
- ErrorWell = wellSn;
- }
- }
- else
- {
- //this.RunState = $"拍照失败,等待{CCDFailedWaitTime / 1000}S";
- //this.RunState = $"take photos failed,wait for{CCDFailedWaitTime / 1000} S";
- this.RunState = $"{TakePhotoFailed}{CCDFailedWaitTime / 1000}S";
- stopwatch.Restart();
- do
- {
- HouseState(CommandSource.ccdThread, custom, 500);
- } while (stopwatch.ElapsedMilliseconds < CCDFailedWaitTime);
- if (Camera != null && Camera.IsInit && Camera.GetCamNum() == CamNum)
- {
- HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[第{i}次关闭相机结果:{CloseCamera(content)}]", LogEnum.HouseRunRecord);
- isOpen = OpenCamera(content);
- HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[第{i}次开启相机结果:{isOpen}]", LogEnum.HouseRunRecord);
- }
- else
- {
- if (Camera == null)
- {
- HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"{content}[相机不满足重新加载条件][Camera == null]", LogEnum.HouseRunRecord);
- }
- else
- {
- HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"{content}[相机不满足重新加载条件][Camera.IsInit:{Camera.IsInit}][{CamNum}]", LogEnum.HouseRunRecord);
- }
- }
- }
- }
- }
- return rsData;
- }
- catch (Exception ex)
- {
- ExceptionLogEvent?.Invoke(ex, $"[{House.houseSn}][{PortName}]抓图", null, LogEnum.RunException);
- return -1;
- }
- finally
- {
- stopwatch.Stop();
- }
- }
- /// <summary>
- /// 拍照抓图
- /// </summary>
- public void Photograph(CustomProtocol customProtocol, int currentPicNum, int allPicNum, Embryo itemEmbryo, DateTime savePictureTime, int positionType, bool isEnd)
- {
- Stopwatch CCDOperateStopwatch = Stopwatch.StartNew();
- string content = null;
- bool isSuccess = true;
- try
- {
- content = $"[{House.houseSn}][{PortName}][{customProtocol.commandNumber}][{customProtocol.commandType.ToString()}][图片ID:{customProtocol.pictureId}][图片位置:{customProtocol.well}-{currentPicNum}][水平电机:{customProtocol.HorizontalMotorPulse}][垂直电机:{customProtocol.VerticalMotorPulse}][下位机水平:{currentHorizontalMotor}][下位机垂直:{currentVerticalMotor}]";
- if (customProtocol.HorizontalMotorPulse != currentHorizontalMotor || customProtocol.VerticalMotorPulse != currentVerticalMotor)
- {
- TLLogEvent?.Invoke($"{content}垂直电机或水平电机位置和下位机位置不一致", LogEnum.RunError);
- }
- HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"{content}[胚胎拍照图片处理开始]", LogEnum.HouseRunRecord);
- if (itemEmbryo.state != 0)
- {
- HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"{content}[当前胚胎状态:{itemEmbryo.state},跳过抓拍]", LogEnum.HouseRunRecord);
- return;
- }
- var startElapsed = CCDOperateStopwatch.Elapsed;
- int GetRgbData = -1;
- GetRgbData = GetRgbDataFunNew(content, itemEmbryo.wellSn);
- var endElapsed = CCDOperateStopwatch.Elapsed;
- HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[抓图耗时:{StringHelper.TimeToString(endElapsed - startElapsed)}][抓图结果:{GetRgbData}]", LogEnum.HouseRunRecord);
- if (GetRgbData != 0)
- {
- TLLogEvent?.Invoke($"{content}抓图失败[抓图结果:{GetRgbData}]", LogEnum.RunError);
- return;
- }
- startElapsed = CCDOperateStopwatch.Elapsed;
- string path = PathHelper.GetEmbryoPicSaveDirectory();
- PathHelper.MakeDirectory(path);
- string fileName = $"{House.houseSn}_{itemEmbryo.wellSn}_{Dish.id}_{itemEmbryo.id}_{DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss")}_{customProtocol.HorizontalMotorPulse}_{customProtocol.VerticalMotorPulse}.jpg";
- string fullName = $"{path}{fileName}";
- 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);
- SavePicDbEvent?.Invoke(imageDTO);
- int saveResult = SaveImage(Camera.SourceBuffer, House.ccdWidth, House.ccdHeight, fullName);
- endElapsed = CCDOperateStopwatch.Elapsed;
- HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[图片保存耗时:{StringHelper.TimeToString(endElapsed - startElapsed)}][图片保存结果:{saveResult}][注:0表示失败,-1表示异常]", LogEnum.HouseRunRecord);
- if (saveResult != 1)
- {
- TLLogEvent?.Invoke($"{content}图片保存失败[图片保存结果:{saveResult}][注:0表示失败,-1表示异常]", LogEnum.RunError);
- return;
- }
- var imageBytes = AivfoHelper.GetImageData1(fullName);
- if (imageBytes == null)
- {
- TLLogEvent?.Invoke($"{content}图片不存在:{fullName}", LogEnum.RunError);
- return;
- }
- imageDTO.ImageData = ByteString.CopyFrom(imageBytes);
- UploadImageEvent?.Invoke(imageDTO);
- }
- catch (Exception ex)
- {
- ExceptionLogEvent?.Invoke(ex, $"[{House.houseSn}][{PortName}][{customProtocol.commandNumber}][{customProtocol.commandType.ToString()}]胚胎拍照图片处理", content, LogEnum.RunException);
- isSuccess = false;
- }
- finally
- {
- HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"{content}[图片处理结果:{isSuccess}][胚胎拍照图片处理耗时:{StringHelper.TimeToString(CCDOperateStopwatch.Elapsed)}][End]", LogEnum.HouseRunRecord);
- CCDOperateStopwatch.Stop();
- }
- }
- /// <summary>
- /// 自动对焦抓图
- /// </summary>
- /// <param name="customProtocol">指令数据</param>
- /// <param name="isEnd">是否是最后一张</param>
- /// <param name="leftOffset">左边裁剪像素</param>
- /// <param name="bttOffset">下边裁剪像素</param>
- /// <param name="itemEmbryo">当前抓拍胚胎</param>
- /// <param name="saveDateTime">本轮自动对焦开始时间</param>
- public bool Autofocus(CustomProtocol customProtocol, bool isEnd, Embryo itemEmbryo, DateTime saveDateTime, int totlayer, int currlayer)
- {
- Stopwatch AutofocusOperateStopwatch = Stopwatch.StartNew();
- string content = null;
- bool isSuccess = true;
- try
- {
- int currentver = customProtocol.VerticalMotorPulse;
- content = $"[{House.houseSn}][{PortName}][{customProtocol.commandNumber}][{customProtocol.commandType.ToString()}][图片编号:{customProtocol.pictureId}][图片位置:{customProtocol.well}-{customProtocol.focal}][水平电机:{customProtocol.HorizontalMotorPulse}][垂直电机:{customProtocol.VerticalMotorPulse}][下位机水平:{currentHorizontalMotor}][下位机垂直:{currentVerticalMotor}]";
- if (customProtocol.HorizontalMotorPulse != currentHorizontalMotor || customProtocol.VerticalMotorPulse != currentVerticalMotor)
- {
- TLLogEvent?.Invoke($"{content}垂直电机或水平电机位置和下位机位置不一致", LogEnum.RunError);
- }
- HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"{content}[自动对焦图片处理开始]", LogEnum.HouseRunRecord);
- if (itemEmbryo.state != 0)
- {
- HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"{content}[当前胚胎状态:{itemEmbryo.state},跳过抓拍]", LogEnum.HouseRunRecord);
- return false;
- }
- var startElapsed = AutofocusOperateStopwatch.Elapsed;
- int GetRgbData = GetRgbDataFunNew(content, itemEmbryo.wellSn);
- var endElapsed = AutofocusOperateStopwatch.Elapsed;
- HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[自动对焦抓图耗时:{StringHelper.TimeToString(endElapsed - startElapsed)}][抓图结果:{GetRgbData}]", LogEnum.HouseRunRecord);
- if (GetRgbData != 0)
- {
- TLLogEvent?.Invoke($"{content}自动对焦抓图失败", LogEnum.RunError);
- return false;
- }
- startElapsed = AutofocusOperateStopwatch.Elapsed;
- var path = PathHelper.GetAutoFocusSaveDirectory();
- PathHelper.MakeDirectory(path);//创建目录
- string fileName = $"{House.houseSn}_{itemEmbryo.wellSn}_{Dish.id}_{itemEmbryo.id}_{DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss")}_{customProtocol.HorizontalMotorPulse}_{currentver}.jpg";
- string fullName = $"{path}{fileName}";
- var imagedto = GetImageDTO(itemEmbryo, fileName, path, saveDateTime.ToString("yyyy-MM-dd HH:mm:ss"), 1, totlayer, currlayer, currentver, customProtocol.HorizontalMotorPulse, 0, isEnd);
- SavePicDbEvent?.Invoke(imagedto);
- int score = SaveImage(Camera.SourceBuffer, House.ccdWidth, House.ccdHeight, fullName);
- endElapsed = AutofocusOperateStopwatch.Elapsed;
- HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[图片保存耗时:{StringHelper.TimeToString(endElapsed - startElapsed)}][图片保存结果:{score}][注:0表示失败,-1表示异常]", LogEnum.HouseRunRecord);
- if (score != 1)
- {
- TLLogEvent?.Invoke($"{content}图片保存失败[图片保存结果:{score}][注:0表示失败,-1表示异常]", LogEnum.RunError);
- return false;
- }
- var imageBytes = AivfoHelper.GetImageData1(fullName);
- if (imageBytes == null)
- {
- TLLogEvent?.Invoke($"{content}图片不存在:{fullName}", LogEnum.RunError);
- return false;
- }
- imagedto.ImageData = ByteString.CopyFrom(imageBytes);
- UploadImageEvent?.Invoke(imagedto);
- return true;
- }
- catch (Exception ex)
- {
- ExceptionLogEvent?.Invoke(ex, $"[{House.houseSn}][{PortName}][{customProtocol.commandNumber}][{customProtocol.commandType.ToString()}]自动对焦图片处理", null, LogEnum.RunException);
- isSuccess = false;
- return false;
- }
- finally
- {
- HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"{content}[图片处理结果:{isSuccess}][自动对焦图片处理耗时:{StringHelper.TimeToString(AutofocusOperateStopwatch.Elapsed)}]", LogEnum.HouseRunRecord);
- AutofocusOperateStopwatch.Stop();
- }
- }
- /// <summary>
- /// 抠图 0表示失败 -1表示异常
- /// </summary>
- /// <param name="imgData"></param>
- /// <param name="width"></param>
- /// <param name="height"></param>
- /// <param name="path"></param>
- /// <param name="sourcePath"></param>
- /// <param name="isSave"></param>
- /// <param name="aa"></param>
- /// <param name="letoffset"></param>
- /// <returns></returns>
- public string ImageProcessing(byte[] imgData, int width, int height, string path, string sourcePath, int isSave, string wellname, string devTime, int leftOffset, int bttOffset)
- {
- try
- {
- IntPtr ptr = AivfoHelper.ImageProcessing(imgData, width, height, path, sourcePath, isSave, wellname, devTime, leftOffset, bttOffset);
- if (ptr == IntPtr.Zero)
- {
- return null;
- }
- else
- {
- return Marshal.PtrToStringAnsi(ptr);
- }
- }
- catch (Exception ex)
- {
- ExceptionLogEvent?.Invoke(ex, $"[{House.houseSn}][{PortName}]图片抠图", $"[sourcePath={sourcePath}][{leftOffset} {bttOffset} 0][isSave={isSave}]", LogEnum.RunException);
- return null;
- }
- }
- /// <summary>
- /// 保存图片 1是成功 0失败
- /// </summary>
- /// <param name="bitmapData"></param>
- /// <param name="width"></param>
- /// <param name="height"></param>
- /// <param name="fileName"></param>
- /// <returns></returns>
- public int SaveImage(byte[] bitmapData, int width, int height, string fileName)
- {
- try
- {
- int a = AivfoHelper.Save2(bitmapData, width, height, fileName);
- return a;
- }
- catch (Exception ex)
- {
- ExceptionLogEvent?.Invoke(ex, $"[{House.houseSn}][{PortName}]图片保存", $"[fileName:{fileName}]", LogEnum.RunException);
- return -1;
- }
- }
- /// <summary>
- /// 评分 0表示失败 -1表示异常
- /// </summary>
- /// <param name="bitmapData"></param>
- /// <param name="w"></param>
- /// <param name="h"></param>
- /// <param name="dir"></param>
- /// <param name="id"></param>
- /// <param name="dir1"></param>
- /// <param name="letoffset"></param>
- /// <returns></returns>
- public double GetScore(byte[] bitmapData, int w, int h, string dir, int id, string dir1, int leftOffset, int bttOffset)
- {
- try
- {
- var a = AivfoHelper.GetImageScoreAndSaveImage(bitmapData, w, h, dir, id, dir1, leftOffset, bttOffset);
- return a;
- }
- catch (Exception ex)
- {
- ExceptionLogEvent?.Invoke(ex, $"[{House.houseSn}][{PortName}]图片打分", $"[dir1={dir1}][{leftOffset} {bttOffset}]", LogEnum.RunException);
- return -1d;
- }
- }
- /// <summary>
- /// 抠图失败处理 0表示失败 -1表示异常
- /// </summary>
- /// <returns></returns>
- public int KouTuShiBai(string fileName, string wellName, string fayuString)
- {
- try
- {
- int i = AivfoHelper.Save1(fileName, wellName, fayuString);
- return i;
- }
- catch (Exception ex)
- {
- ExceptionLogEvent?.Invoke(ex, $"[{House.houseSn}][{PortName}]抠图失败处理", null, LogEnum.RunException);
- return -1;
- }
- }
- /// <summary>
- /// 获取图片信息
- /// </summary>
- /// <param name="embryo">当前胚胎</param>
- /// <param name="fileName">图片名称</param>
- /// <param name="filePath">图片路径</param>
- /// <param name="dateTime">自动对焦时间/图片时间</param>
- /// <param name="PhotographType">1 自动对焦 0 CCD拍照</param>
- /// <param name="TotalLayer">总层数</param>
- /// <param name="PictureLayer">当前层数</param>
- /// <param name="ver">垂直电机位置</param>
- /// <param name="hor">水平电机位置</param>
- /// <param name="Clearest">0不是 1最清晰</param>
- /// <param name="isend">是否结束</param>
- /// <returns></returns>
- 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)
- {
- try
- {
- ImageDTO imageDTO = new ImageDTO();
- imageDTO.CcdSn = House.ccdSn;
- imageDTO.Clearest = Clearest;
- imageDTO.EmbryoCultureRecordId = (ulong)embryo.dishId;
- imageDTO.EmbryoId = (ulong)embryo.id;
- imageDTO.End = isend ? 1 : 0;
- imageDTO.FertilizationTime = embryo.startTime.ToString("yyyy-MM-dd HH:mm:ss");
- imageDTO.HorizontalPosition = hor;
- imageDTO.HouseSn = House.houseSn;
- imageDTO.ImageTime = dateTime;
- imageDTO.PhotographType = PhotographType;
- imageDTO.PictureLayer = PictureLayer;
- imageDTO.ShootingPosition = ver;
- imageDTO.SourceImageName = fileName;
- imageDTO.SourceImagePath = filePath;
- imageDTO.SourceImageWidth = House.ccdWidth;
- imageDTO.SourceImageHeight = House.ccdHeight;
- imageDTO.TlSn = TLSetting.tlSn;
- imageDTO.WellSn = embryo.wellSn;
- imageDTO.TotalLayer = TotalLayer;
- return imageDTO;
- }
- catch (Exception ex)
- {
- ExceptionLogEvent?.Invoke(ex, $"GetImageDTO", null, LogEnum.RunException);
- return null;
- }
- }
- #endregion
- #region 状态变化
- /// <summary>
- /// 舱门状态变化
- /// </summary>
- public void DoorStateChanged(State newDoorValue)
- {
- if (newDoorValue == State.关闭)
- {
- HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[{House.houseSn}][{this.PortName}][关闭舱门:{DateTime.Now}]", LogEnum.HouseInfo);
- //关闭舱门自动对焦
- FirstClearest = true;
- IsStopClearest = false;
- IsStopCCD = false;
- IsStopAirSwap = false;
- StartAir = true;
- }
- else
- {
- HouseLogEvent?.Invoke(House.houseSn, DateTime.Now, $"[{House.houseSn}][{this.PortName}][打开舱门:{DateTime.Now}]", LogEnum.HouseInfo);
- IsStopClearest = true;
- IsStopCCD = true;
- IsStopAirSwap = true;
- AutoFocusWellClear();
- }
- }
- /// <summary>
- /// 开始平衡
- /// </summary>
- public void StartBlance(Balance _balance)
- {
- FirstClearest = true;
- FirstAir = true;
- IsStopClearest = false;
- IsStopCCD = false;
- IsStopAirSwap = false;
- this.Balance = _balance;
- }
- /// <summary>
- /// 结束平衡
- /// </summary>
- public void StopBlance()
- {
- IsStopClearest = true;
- IsStopCCD = true;
- IsStopAirSwap = true;
- Balance = null;
- //排气报警
- HouseStateEvent?.Invoke(House.houseSn, houseState, -1, -1, -1, 0);
- }
- /// <summary>
- /// 开始培养
- /// </summary>
- public void StartDish(Dish newDish)
- {
- FirstClearest = true;
- IsStopClearest = false;
- IsStopCCD = false;
- IsStopAirSwap = false;
- Dish = newDish;
- AutoFocusWellClear();
- if (Balance != null && Balance.id > 0) Balance = null;
- for (int i = 1; i <= 16; i++) LastAutoFocusTimeDic[i] = null;
- }
- /// <summary>
- /// 结束培养
- /// </summary>
- public void StopDish()
- {
- IsStopClearest = true;
- IsStopCCD = true;
- IsStopAirSwap = true;
- Dish = null;
- FirstClearest = true;
- //排气报警
- HouseStateEvent?.Invoke(House.houseSn, houseState, -1, -1, -1, 0);
- //拍照报警
- CCDStateEvent?.Invoke(House.houseSn, 0, -1);
- //HouseStateEvent?.Invoke(House.houseSn, -1, -1, 0, -1, -1);
- }
- /// <summary>
- /// 改变胚胎状态
- /// </summary>
- /// <param name="embryo"></param>
- public void ChangeEmbryoState(Embryo embryo)
- {
- if (Dish == null && Dish.id <= 0) return;
- var changeEmbryo = Dish.Embryo.FirstOrDefault(x => x.id == embryo.id);
- if (changeEmbryo == null) return;
- changeEmbryo.state = embryo.state;
- changeEmbryo.stateTime = embryo.stateTime;
- }
- /// <summary>
- /// 舱室更新设置
- /// </summary>
- /// <param name="tLInitControllerResult"></param>
- public void UpdataHouseSetting(TLInitControllerResult tLInitControllerResult)
- {
- try
- {
- this.IsNewAirSwap = tLInitControllerResult.TLSetting.newAirSwap;
- this.TLSetting = tLInitControllerResult.TLSetting;
- var newHouse = tLInitControllerResult.HouseList.FirstOrDefault(x => x.houseSn == House.houseSn);
- if (newHouse == null)
- {
- TLLogEvent?.Invoke($"{House.houseSn}号舱室更新设置未找到新的舱室设置", LogEnum.RunError);
- }
- else
- {
- this.House = newHouse;
- }
- var newList = tLInitControllerResult.HouseWellList.Where(x => x.houseSn == House.houseSn).ToList();
- if (newList != null && newList.Any())
- {
- this._wellSettings = newList;
- }
- else
- {
- TLLogEvent?.Invoke($"{House.houseSn}号舱室更新设置未找到新的Well设置列表", LogEnum.RunError);
- }
- }
- catch (Exception ex)
- {
- ExceptionLogEvent?.Invoke(ex, $"UpdataHouseSetting", null, LogEnum.RunException);
- }
- }
- /// <summary>
- /// 开启舱室对焦
- /// </summary>
- public void HouseAutoFocus()
- {
- FirstClearest = true;
- AutoFocusWellClear();
- }
- /// <summary>
- /// well自动对焦
- /// </summary>
- /// <param name="wellList"></param>
- public void WellAutoFocus(List<int> wellList)
- {
- bool b = false;
- if (Dish != null && Dish.id > 0)
- {
- var embryoWellList = Dish.Embryo.Select(x => x.wellSn).ToList();
- foreach (var item in wellList)
- {
- if (embryoWellList.Contains(item))
- {
- b = true;
- AddAutoFocusWell(item);
- }
- }
- }
- if (b) FirstClearest = true;
- }
- #endregion
- }
- }
|