| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592 |
- using CommunityToolkit.Mvvm.ComponentModel;
- using ivf_tl_Entity.CameraEntitys;
- using ivf_tl_Entity.ComEntitys;
- using ivf_tl_Entity.DebugEntitys;
- using ivf_tl_Entity.DTO;
- using ivf_tl_Entity.GlobalEnums;
- using ivf_tl_Operate.Converts;
- using ivf_tl_Services;
- using IvfTl.Hardware;
- using IvfTl.Hardware.Impl;
- using IvfTl.AutoFocus.Calib;
- using IvfTl.AutoFocus.Layout;
- using IvfTl.AutoFocus.Storage;
- using Newtonsoft.Json;
- using Newtonsoft.Json.Linq;
- using System;
- using System.Collections.Generic;
- using System.Collections.ObjectModel;
- using System.Configuration;
- using System.DirectoryServices.ActiveDirectory;
- using System.IO;
- using System.Linq;
- using System.Reflection.Metadata;
- using System.Text;
- using System.Threading.Tasks;
- using System.Windows;
- using static ivf_tl_Operate.CustomUserControls.RecordBox;
- using System.Windows.Documents;
- namespace ivf_tl_Operate.ViewModel
- {
- public partial class HouseDebugPageViewModel : ObservableObject
- {
- public event Action<string> MessageEvent;
- public event Action<string, int, int> AddPicEvent;
- public event Action OpenVideoEvent;
- // M1-B2:调试页不再 new ComBin/new Camera 开第二个物理串口/相机。
- // 全部硬件动作走借用到的 HAL 句柄(_halLease.Serial / _halLease.Camera)——与采集端同一物理实例,
- // 配合 T1.3(前台借用时采集端暂停让出 ComBin),端口/相机占用根除(审计 B2)。
- /// <summary>借用到的串口句柄(与采集端同一实例);未持借用时为 null。</summary>
- private IvfTl.Hardware.ISerialChannel Serial => _halLease?.Serial;
- /// <summary>借用到的相机句柄(与采集端同一实例);未持借用时为 null。</summary>
- private IvfTl.Hardware.ICamera Cam => _halLease?.Camera;
- /// <summary>
- /// M1-03 HAL 前台借用凭证。打开调试页时向 HAL 申请该舱独占借用(HardwareUser.OperateDebug),
- /// HAL 自动暂停 control 对该舱的后台采集;关闭调试页 Dispose 归还,HAL 恢复采集。
- /// ⚠ 待验证 V-024:借用→暂停采集→归还恢复时序(调试取图 vs 后台采集切换不占用/不死锁,01 §3 M1 必过)。
- /// 说明(代码隔离 + 范围控制):调试页 ComBin/Camera 仍用 operate 侧 ivf_tl_Entity 具体类型——
- /// 因调试栈方法更全(Write*EEPROM / 电机正反向 / RawToRgb 等),control 侧 SerialHelper ComBin 未覆盖,
- /// 折叠进 HAL ISerialChannel 属 M2 统一。M1 通过 HAL 借用闸门保证"同舱同一时刻单一使用者",
- /// 杜绝与后台采集同时 Open 同 COM 口/Init 同相机。
- /// </summary>
- private IHardwareLease _halLease = null;
- /// <summary>
- /// 当前housesn
- /// </summary>
- public int CurrentHouseId { get; set; } = 1;
- /// <summary>
- /// 当前ccdID
- /// </summary>
- public int CurrentCCDId { get; set; } = 0;
- /// <summary>
- /// 所有舱室
- /// </summary>
- public List<HouseInfo> HouseList { get; set; } = new List<HouseInfo>();
- /// <summary>
- /// 仪器设置
- /// </summary>
- public TLSetting tLSetting { get; set; } = new TLSetting();
- /// <summary>
- /// 自动对焦和拍照位置
- /// </summary>
- public List<HousePhotographLocation> ccdPhoto = new List<HousePhotographLocation>();
- /// <summary>
- /// 水平电机位置
- /// </summary>
- public List<HouseWellSetting> houseWellSettingList = new List<HouseWellSetting>();
- [ObservableProperty]
- private ObservableCollection<string> messageInfoList = new ObservableCollection<string>();
- [ObservableProperty]
- private decimal temperature = 0m;
- [ObservableProperty]
- private decimal pressure = 0m;
- [ObservableProperty]
- private string doorState = null;
- [ObservableProperty]
- private string ledState = null;
- [ObservableProperty]
- private int currentWell = 0;
- [ObservableProperty]
- private int currentFocal = 0;
- /// <summary>
- /// 结束抓图
- /// </summary>
- public bool IsStop { get; set; } = false;
- /// <summary>
- /// M2-05 一键标定中止标志(工程师可中止;每 well 间检查)。
- /// </summary>
- public bool IsStopCalibrate { get; set; } = false;
- /// <summary>
- /// M2-05 一键标定是否进行中(UI 据此禁用重复触发)。
- /// </summary>
- [ObservableProperty]
- private bool isCalibrating = false;
- /// <summary>
- /// M2-05 场景A 一键标定 16 well 实时结果(合格绿/伪峰红,含 FocusZ/峰比/偏移)。
- /// View 绑定此集合做 4x4 实时呈现(沿用调试页内呈现,不另开 CalibWindow)。
- /// </summary>
- public ObservableCollection<WellCalibUiItem> CalibResults { get; } = new ObservableCollection<WellCalibUiItem>();
- /// <summary>
- /// 垂直电机当前位置
- /// </summary>
- [ObservableProperty]
- private int currentVer = 0;
- /// <summary>
- /// 水平电机当前位置
- /// </summary>
- [ObservableProperty]
- private int currentHor = 0;
- [ObservableProperty]
- private HouseInfo currentHouse = null;
- [ObservableProperty]
- private int houseVentTimeE = 0;
- public HouseDebugPageViewModel()
- {
- //HouseList = AppData.Instance.HttpHelper.GetSettingHouseApi(AppData.Instance.TlSn);
- //CurrentHouse = HouseList.FirstOrDefault(x => x.houseSn == 1);
- }
- private void ExLog(Exception ex, string name)
- {
- AppData.Instance.LogHelper.ExceptionLog(ex, $"HouseDebugPageViewModel.{name}", LogEnum.RunException);
- }
- private void ErrorLog(string message, LogEnum logType)
- {
- AppData.Instance.LogHelper.TLLog($"HouseDebugPageViewModel.{message}", logType);
- }
- public void Start(ref string errora)
- {
- try
- {
- SerialBin serialBin = new SerialBin();
- serialBin.TLLogEvent += AppData.Instance.LogHelper.TLLog;
- serialBin.ExceptionLogEvent += AppData.Instance.LogHelper.ExceptionLog;
- serialBin.HouseLogEvent += AppData.Instance.LogHelper.HouseLog;
- var errorList = serialBin.UpdataCamera();
- AppData.Instance.LogHelper.TLLog($"ccdidsn:{JsonConvert.SerializeObject(serialBin.CCDidSn)}", LogEnum.RunRecord);
- if (errorList.Any())
- {
- errora = $"获取相机Id和CCDSN错误{JsonConvert.SerializeObject(errorList)}";
- AppData.Instance.LogHelper.TLLog(errora, LogEnum.RunRecord);
- return;
- }
- errorList = serialBin.Start(ConfigurationManager.AppSettings["autoFocus"].ToString());
- AppData.Instance.LogHelper.TLLog($"舱室信息:{JsonConvert.SerializeObject(serialBin.SerialModels)}", LogEnum.RunRecord);
- AppData.Instance.LogHelper.TLLog($"E方数据:{JsonConvert.SerializeObject(serialBin.HouseEEPROInfos)}", LogEnum.RunRecord);
- if (errorList.Any())
- {
- errora = $"获取串口信息错误{JsonConvert.SerializeObject(errorList)}";
- AppData.Instance.LogHelper.TLLog(errora, LogEnum.RunRecord);
- return;
- }
- var modelCount = serialBin.SerialModels.Count;
- if (modelCount != 11)
- {
- //string messageinfo = $"检测到{modelCount}个模块,是否继续运行?";
- string messageinfo = $" Detected {modelCount} cabin, are you sure to run?";
- MessageBoxResult aaa = MessageBox.Show(messageinfo, KeyToStringConvert.GetLanguageStringByKey("C0171"), MessageBoxButton.YesNo, MessageBoxImage.Question, MessageBoxResult.No, MessageBoxOptions.DefaultDesktopOnly);
- if (aaa != MessageBoxResult.Yes)
- {
- errora = "结束";
- return;
- }
- }
- List<int> listIntRunHoues = serialBin.SerialModels.Select(x => x.houseSn).ToList();
- TLInitData tLInitData = new TLInitData();
- tLInitData.tlSn = $"NEO-1-{serialBin.TLNum}";
- tLInitData.softwareVersion = "V2.0.0";
- tLInitData.verticalMotorPulseMax = 125000;
- tLInitData.houseLinkDataList = serialBin.SerialModels.OrderBy(x => x.houseSn).ToList();
- foreach (var item in serialBin.HouseEEPROInfos)
- {
- item.tlSn = tLInitData.tlSn;
- }
- tLInitData.houseEEPROInitDTOList = serialBin.HouseEEPROInfos.OrderBy(x => x.houseSn).ToList();
- AppData.Instance.LogHelper.TLLog($"舱室信息:{JsonConvert.SerializeObject(tLInitData)}", LogEnum.RunRecord);
- SettingDataApiData settingDataApiData = AppData.Instance.HttpHelper.GetSettingDataApi(tLInitData);
- if (settingDataApiData == null)
- {
- errora = $"{tLInitData.tlSn}获取仪器设置失败";
- return;
- }
- AppData.Instance.LogHelper.TLLog(JsonConvert.SerializeObject(settingDataApiData), LogEnum.RunRecord);
- tLSetting = AppData.Instance.ConvertHelper.ConvertToTLSetting(settingDataApiData.tlInfo, settingDataApiData.tlSetting);
- ccdPhoto = settingDataApiData.housePhotographLocation;
- houseWellSettingList = settingDataApiData.houseWellSettingList;
- HouseList = settingDataApiData.houseList;
- CurrentHouse = HouseList.FirstOrDefault(x => x.houseSn == 1);
- }
- catch (Exception ex)
- {
- AppData.Instance.LogHelper.ExceptionLog(ex, $"调试模式初始化", LogEnum.RunException);
- errora = $"调试模式初始化异常:{ex.Message}";
- }
- }
- public async Task ComHouseInit()
- {
- await Task.Run(async () =>
- {
- try
- {
- var currentHouse = HouseList.FirstOrDefault(x => x.houseSn == CurrentHouseId);
- // M1-03/B2 HAL: 向 HAL 申请该舱前台借用——HAL 暂停 control 对本舱采集(T1.3)并让采集端让出串口/相机,
- // 调试页随后复用借用到的同一物理句柄(lease.Serial/lease.Camera),不再 new 第二个 ComBin/Camera 开同口/同相机。
- try
- {
- var gate = HardwareAccessLayer.Instance.GetHouseGate(currentHouse.houseSn);
- _halLease = gate.Acquire(HardwareUser.OperateDebug);
- if (_halLease == null)
- {
- AddMessageInfo($"[{currentHouse.houseSn}]该舱正被占用(采集/对焦),借用超时,稍后重试");
- return;
- }
- }
- catch (Exception le)
- {
- AddMessageInfo($"[{currentHouse.houseSn}]HAL 借用异常:{le.Message}");
- return;
- }
- if (Serial == null)
- {
- AddMessageInfo($"[{currentHouse.houseSn}]借用到的串口句柄为空(HAL 未 ScanDevices 到本舱?),无法进入调试");
- return;
- }
- if (!Serial.IsOpen)
- {
- // 物理口由采集端持有并保持打开;T1.3 暂停只停发不关口。此处兜底再开一次(幂等)。
- if (!Serial.Open())
- {
- AddMessageInfo($"[{currentHouse.houseSn}][{currentHouse.housePort}]借用串口未打开且兜底打开失败");
- return;
- }
- }
- AddMessageInfo($"[{currentHouse.houseSn}][{currentHouse.housePort}]调试已复用采集端串口句柄(同一物理口)");
- // 相机:复用借用到的同一相机句柄。采集端通常已 Init+SetOpMode;仅在未 Init 时兜底 Init,
- // 然后统一设单帧采集模式(mode=0)供调试抓图,避免重复 Init 扰动采集端相机。
- if (Cam == null)
- {
- AddMessageInfo($"[{currentHouse.houseSn}]本舱无相机句柄(buffer/无相机舱?),跳过相机初始化");
- }
- else
- {
- if (!Cam.IsInit)
- {
- int cameraInit = Cam.Init();
- AddMessageInfo($"[CCD模块初始化]CCDID={CurrentCCDId},SN={currentHouse.ccdSn} 初始化结果:{cameraInit}[0=成功]");
- if (cameraInit != 0) return;
- }
- int cameraSetMode = Cam.SetOpMode();
- AddMessageInfo($"[CCD模块初始化]开启图像捕捉结果:{cameraSetMode}[0=成功]");
- if (cameraSetMode != 0) return;
- }
- var currentHorSetting = houseWellSettingList.FirstOrDefault(x => x.houseSn == currentHouse.houseSn && x.wellSn == 1);
- if (currentHorSetting == null)
- {
- AddMessageInfo($"[{currentHouse.houseSn}][{currentHouse.housePort}][未获取到1号well的水平电机位置]");
- return;
- }
- //OpenVideoEvent?.Invoke();
- var verNewValue = currentHorSetting.eepromClearPosition;
- var cc = ccdPhoto.FirstOrDefault(x => x.houseSn == currentHouse.houseSn && x.wellSn == 1);
- if (cc != null)
- {
- verNewValue = cc.clearestPosition;
- }
- Serial.ShakeHandsWait();
- OpenLed();
- Serial.HorizontalResetWait(tLSetting.motorDelay);
- CurrentHor = 0;
- CurrentWell = 0;
- Serial.HorizontalMoveToWait(currentHorSetting.horizontalMotorPosition, tLSetting.motorDelay);
- CurrentHor = currentHorSetting.horizontalMotorPosition;
- CurrentWell = 1;
- Serial.VerticalResetWait(tLSetting.motorDelay);
- CurrentVer = 0;
- CurrentFocal = 0;
- Serial.VerticalMoveToWait(verNewValue, tLSetting.motorDelay);
- CurrentVer = verNewValue;
- CurrentFocal = 1;
- RedTem();
- RedPre();
- RedDoor();
- RedVentTime();
- return;
- }
- catch (Exception ex)
- {
- AppData.Instance.LogHelper.ExceptionLog(ex, "调试模式初始化", LogEnum.RunException);
- AddMessageInfo($"初始化异常:{ex.Message}");
- return;
- }
- });
- }
- public bool ComHouseUnit()
- {
- try
- {
- // M1-B2:物理串口/相机由采集端(control)持有,调试只归还借用,绝不 ClosePort/UnInit 关物理口——
- // 否则会把采集端的口/相机一并关掉。归还后 HAL 触发 ResumeCapture 恢复本舱采集(T1.3)。
- if (_halLease != null)
- {
- try { _halLease.Dispose(); } catch { }
- _halLease = null;
- AddMessageInfo($"[{CurrentHouseId}]已归还借用,恢复后台采集");
- }
- return true;
- }
- catch (Exception ex)
- {
- AppData.Instance.LogHelper.ExceptionLog(ex, "调试模式卸载", LogEnum.RunException);
- AddMessageInfo($"卸载异常:{ex.Message}");
- return false;
- }
- }
- /// <summary>
- /// 读温度
- /// </summary>
- public void RedTem()
- {
- if (Serial == null) return;
- Temperature = Serial.TemperatureWait();
- }
- /// <summary>
- /// 读压力
- /// </summary>
- public void RedPre()
- {
- if (Serial == null) return;
- Pressure = Serial.PressureWait();
- }
- /// <summary>
- /// 读舱门
- /// </summary>
- public void RedDoor()
- {
- if (Serial == null) return;
- string DoorStateString = Serial.DoorStatusWait().ToString();
- if(DoorStateString == "关闭")
- {
- DoorState = KeyToStringConvert.GetLanguageStringByKey("C0305");
- }
- if (DoorStateString == "打开")
- {
- DoorState = KeyToStringConvert.GetLanguageStringByKey("C0306");
- }
- }
- /// <summary>
- /// 打开Led灯
- /// </summary>
- public void OpenLed()
- {
- if (Serial == null) return;
- // M8-G3-1:LED 开关为串口设备命令入口,补操作日志埋点(module=对焦调试)。
- Aivfo.OperationLog.OperationLogger.Run("对焦调试", "打开LED灯",
- () => Serial.OpenLedWait(),
- input: new { houseSn = CurrentHouseId });
- LedState = KeyToStringConvert.GetLanguageStringByKey("C0306");
- //LedState = "开启";
- }
- /// <summary>
- /// 关闭Led灯
- /// </summary>
- public void CloseLed()
- {
- if (Serial == null) return;
- // M8-G3-1:LED 开关为串口设备命令入口,补操作日志埋点(module=对焦调试)。
- Aivfo.OperationLog.OperationLogger.Run("对焦调试", "关闭LED灯",
- () => Serial.CloseLedWait(),
- input: new { houseSn = CurrentHouseId });
- //LedState = "关闭";
- LedState = KeyToStringConvert.GetLanguageStringByKey("C0305");
- }
- /// <summary>
- /// 打开进气阀
- /// </summary>
- public void OpenIntake()
- {
- if (Serial == null) return;
- // M8-G3-1:进气阀开关为串口设备命令入口,补操作日志埋点(module=对焦调试)。
- Aivfo.OperationLog.OperationLogger.Run("对焦调试", "打开进气阀",
- () => Serial.OpenIntakeValveWait(),
- input: new { houseSn = CurrentHouseId });
- }
- /// <summary>
- /// 关闭进气阀
- /// </summary>
- public void CloseIntake()
- {
- if (Serial == null) return;
- // M8-G3-1:进气阀开关为串口设备命令入口,补操作日志埋点(module=对焦调试)。
- Aivfo.OperationLog.OperationLogger.Run("对焦调试", "关闭进气阀",
- () => Serial.CloseIntakeValveWait(),
- input: new { houseSn = CurrentHouseId });
- }
- /// <summary>
- /// 打开排气阀
- /// </summary>
- public void OpenExhaust()
- {
- if (Serial == null) return;
- // M8-G3-1:排气阀开关为串口设备命令入口,补操作日志埋点(module=对焦调试)。
- Aivfo.OperationLog.OperationLogger.Run("对焦调试", "打开排气阀",
- () => Serial.OpenExhaustValveWait(),
- input: new { houseSn = CurrentHouseId });
- }
- /// <summary>
- /// 关闭排气阀
- /// </summary>
- public void CloseExhaust()
- {
- if (Serial == null) return;
- // M8-G3-1:排气阀开关为串口设备命令入口,补操作日志埋点(module=对焦调试)。
- Aivfo.OperationLog.OperationLogger.Run("对焦调试", "关闭排气阀",
- () => Serial.CloseExhaustValveWait(),
- input: new { houseSn = CurrentHouseId });
- }
- /// <summary>
- /// 舱室补气
- /// </summary>
- public void HouseAeration()
- {
- if (Serial == null) return;
- // M8-G3-1:舱室补气为串口设备命令入口,补操作日志埋点(module=对焦调试)。
- Aivfo.OperationLog.OperationLogger.Run("对焦调试", "舱室补气",
- () => Serial.HouseAerationWait(),
- input: new { houseSn = CurrentHouseId });
- }
- /// <summary>
- /// 舱室排气
- /// </summary>
- public void HouseVent()
- {
- if (Serial == null) return;
- // M8-G3-1:舱室排气为串口设备命令入口,补操作日志埋点(module=对焦调试)。
- Aivfo.OperationLog.OperationLogger.Run("对焦调试", "舱室排气",
- () => Serial.HouseVentWait(),
- input: new { houseSn = CurrentHouseId });
- }
- /// <summary>
- /// 写舱室进气阀时间
- /// </summary>
- /// <param name="newValue"></param>
- public void WriteOpenIntakeTime(int newValue)
- {
- if (Serial == null) return;
- // M1-B2:走 lease.Serial→control ComBin(builder 与 operate 逐字节一致)。⚠ 待真机 V-010(写E方回包判定)。
- // M8-G3-1:写舱室进气阀时间为写 EEPROM 设备命令入口,补操作日志埋点(module=对焦调试)。
- Aivfo.OperationLog.OperationLogger.Run("对焦调试", "写舱室进气阀时间",
- () => Serial.WriteOpenIntakeTimeWait(newValue, isBuffer: false),
- input: new { houseSn = CurrentHouseId, newValue });
- }
- /// <summary>
- /// 写舱室排气阀时间
- /// </summary>
- /// <param name="newValue"></param>
- public void WriteOpenVentTime(int newValue)
- {
- if (Serial == null) return;
- // M-01 已补:control 端补齐写排气阀时间 E方命令(builder 地址 00 03 08,与合并前 operate 逐字节一致),
- // 经 lease.Serial→control ComBin 真正下发下位机。
- // M8-G3-1:写舱室排气阀时间为写 EEPROM 设备命令入口,补操作日志埋点(module=对焦调试)。
- var written = Aivfo.OperationLog.OperationLogger.Run("对焦调试", "写舱室排气阀时间",
- () => Serial.WriteOpenVentTimeWait(newValue),
- input: new { houseSn = CurrentHouseId, newValue });
- if (!written)
- {
- AddMessageInfo($"[排气阀时间]下发失败,仅本地暂存{newValue}");
- }
- HouseVentTimeE = newValue;
- }
- /// <summary>
- /// 读舱室排气阀打开时间
- /// </summary>
- public void RedVentTime()
- {
- if (Serial == null) return;
- // M-02 已补:control 端补齐读排气阀时间 E方命令(地址 00 03 08);读不到(-1)则保持原值不覆盖。
- int v = Serial.ReadOpenVentTimeWait();
- if (v >= 0) HouseVentTimeE = v;
- }
- /// <summary>
- /// 写垂直电机间隔脉冲
- /// </summary>
- /// <param name="newValue"></param>
- public void WriteOVerSpace(int newValue)
- {
- if (Serial == null) return;
- // M1-B2:走 lease.Serial→control ComBin(builder 与 operate 逐字节一致)。⚠ 待真机 V-010。
- // M8-G3-1:写垂直电机间隔脉冲为写 EEPROM 设备命令入口,补操作日志埋点(module=对焦调试)。
- Aivfo.OperationLog.OperationLogger.Run("对焦调试", "写垂直电机间隔脉冲",
- () => Serial.WriteScanStepWait(newValue),
- input: new { houseSn = CurrentHouseId, newValue });
- }
- /// <summary>
- /// 保存水平电机位置
- /// </summary>
- /// <param name="newValue"></param>
- public void SaveWellHor()
- {
- if (Serial == null) return;
- // M8-P3b:手调保存水平电机位置(关键命令入口,module=对焦调试)。
- // M1-B2:走 lease.Serial.WriteWellHorizontalPosWait→control ComBin(builder 逐字节一致)。⚠ 待真机 V-010。
- Aivfo.OperationLog.OperationLogger.Run("对焦调试", "手调保存水平电机位置",
- () => Serial.WriteWellHorizontalPosWait(CurrentWell, CurrentHor),
- input: new { houseSn = CurrentHouseId, well = CurrentWell, hor = CurrentHor });
- }
- #region 电机运动
- /// <summary>
- /// 水平电机复位
- /// </summary>
- public void HorizontalMotorReset()
- {
- if (Serial == null) return;
- // M8-P3b:电机控制命令埋点(module=对焦调试)。
- Aivfo.OperationLog.OperationLogger.Run("对焦调试", "水平电机复位",
- () => Serial.HorizontalResetWait(tLSetting.motorDelay),
- input: new { houseSn = CurrentHouseId });
- CurrentHor = 0;
- CurrentWell = 0;
- }
- /// <summary>
- /// 水平电机正向
- /// </summary>
- public void HorizontalMotorForward(int value)
- {
- if (Serial == null) return;
- // M8-G3-1:电机控制命令入口,补操作日志埋点(module=对焦调试)。
- Aivfo.OperationLog.OperationLogger.Run("对焦调试", "水平电机正向",
- () => Serial.HorizontalForwardWait(value, tLSetting.motorDelay),
- input: new { houseSn = CurrentHouseId, value });
- CurrentHor += value;
- }
- /// <summary>
- /// 水平电机反向
- /// </summary>
- public void HorizontalMotorBackward(int value)
- {
- if (Serial == null) return;
- // M8-G3-1:电机控制命令入口,补操作日志埋点(module=对焦调试)。
- Aivfo.OperationLog.OperationLogger.Run("对焦调试", "水平电机反向",
- () => Serial.HorizontalBackwardWait(value, tLSetting.motorDelay),
- input: new { houseSn = CurrentHouseId, value });
- CurrentHor -= value;
- }
- /// <summary>
- /// 水平电机到目标well
- /// </summary>
- /// <param name="newWell"></param>
- public void HorizontalMotorToWell(int newWell)
- {
- if (Serial == null) return;
- var currentHorSetting = houseWellSettingList.FirstOrDefault(x => x.houseSn == CurrentHouseId && x.wellSn == newWell);
- if (currentHorSetting == null)
- {
- AddMessageInfo($"[未获取到{newWell}号well的水平电机位置]");
- return;
- }
- // M8-G3-1:电机控制命令入口,补操作日志埋点(module=对焦调试)。
- Aivfo.OperationLog.OperationLogger.Run("对焦调试", "水平电机到well",
- () => Serial.HorizontalMoveToWait(currentHorSetting.horizontalMotorPosition, tLSetting.motorDelay),
- input: new { houseSn = CurrentHouseId, well = newWell, hor = currentHorSetting.horizontalMotorPosition });
- CurrentHor = currentHorSetting.horizontalMotorPosition;
- CurrentWell = newWell;
- }
- /// <summary>
- /// 垂直电机复位
- /// </summary>
- public void VerticalMotorReset()
- {
- if (Serial == null) return;
- // M8-P3b:电机控制命令埋点(module=对焦调试)。
- Aivfo.OperationLog.OperationLogger.Run("对焦调试", "垂直电机复位",
- () => Serial.VerticalResetWait(tLSetting.motorDelay),
- input: new { houseSn = CurrentHouseId });
- CurrentVer = 0;
- }
- /// <summary>
- /// 垂直电机正向运动
- /// </summary>
- public void VerticalMotorForward(int newValue)
- {
- if (Serial == null) return;
- // M8-G3-1:电机控制命令入口,补操作日志埋点(module=对焦调试)。
- Aivfo.OperationLog.OperationLogger.Run("对焦调试", "垂直电机正向",
- () => Serial.VerticalForwardWait(newValue, tLSetting.motorDelay),
- input: new { houseSn = CurrentHouseId, newValue });
- CurrentVer += newValue;
- }
- /// <summary>
- /// 垂直电机反向运动
- /// </summary>
- public void VerticalMotorBackward(int newValue)
- {
- if (Serial == null) return;
- // M8-G3-1:电机控制命令入口,补操作日志埋点(module=对焦调试)。
- Aivfo.OperationLog.OperationLogger.Run("对焦调试", "垂直电机反向",
- () => Serial.VerticalBackwardWait(newValue, tLSetting.motorDelay),
- input: new { houseSn = CurrentHouseId, newValue });
- CurrentVer -= newValue;
- }
- /// <summary>
- /// 垂直电机绝对运动
- /// </summary>
- public void VerticalMotorAbsolute(int newValue)
- {
- if (Serial == null) return;
- // M8-G3-1:电机控制命令入口,补操作日志埋点(module=对焦调试)。
- Aivfo.OperationLog.OperationLogger.Run("对焦调试", "垂直电机绝对运动",
- () => Serial.VerticalMoveToWait(newValue, tLSetting.motorDelay),
- input: new { houseSn = CurrentHouseId, newValue });
- CurrentVer = newValue;
- }
- /// <summary>
- /// 一键电机准备
- /// </summary>
- public void MototReady()
- {
- if (Serial == null) return;
- var currentHorSetting = houseWellSettingList.FirstOrDefault(x => x.houseSn == CurrentHouseId && x.wellSn == 1);
- if (currentHorSetting == null)
- {
- AddMessageInfo($"[未获取到1号well的水平电机位置]");
- return;
- }
- var verNewValue = currentHorSetting.eepromClearPosition;
- var cc = ccdPhoto.FirstOrDefault(x => x.houseSn == CurrentHouseId && x.wellSn == 1);
- if (cc != null)
- {
- verNewValue = cc.clearestPosition;
- }
- // M8-G3-1:一键电机准备为多步串口动作流程,用 Begin scope 串联各子动作(module=对焦调试)。
- using var _op = Aivfo.OperationLog.OperationLogger.Begin("对焦调试", "一键电机准备",
- houseSn: CurrentHouseId);
- try { _op.Input(new { houseSn = CurrentHouseId, targetHor = currentHorSetting.horizontalMotorPosition, targetVer = verNewValue }); } catch { }
- Serial.HorizontalResetWait(tLSetting.motorDelay);
- CurrentHor = 0;
- CurrentWell = 0;
- Serial.HorizontalMoveToWait(currentHorSetting.horizontalMotorPosition, tLSetting.motorDelay);
- CurrentHor = currentHorSetting.horizontalMotorPosition;
- CurrentWell = 1;
- Serial.VerticalResetWait(tLSetting.motorDelay);
- CurrentVer = 0;
- CurrentFocal = 0;
- Serial.VerticalMoveToWait(verNewValue, tLSetting.motorDelay);
- CurrentVer = verNewValue;
- CurrentFocal = 1;
- }
- /// <summary>
- /// 单张抓拍
- /// </summary>
- public bool SavePic(string fullName)
- {
- try
- {
- if (GetPicData() == 0)
- {
- if (Cam == null) return false;
- // M8-G3-1:单张抓拍落盘为相机采图+保存命令入口,补操作日志埋点(module=对焦调试)。
- // 批量抓图(水平抓图/清晰图层抓图)经 Begin scope 调用时,本埋点自动成为其子埋点(父子链)。
- return Aivfo.OperationLog.OperationLogger.Run("对焦调试", "单张抓拍",
- () => Cam.SavePic(fullName, CurrentHouse.ccdWidth, CurrentHouse.ccdHeight),
- input: new { houseSn = CurrentHouseId, well = CurrentWell, focal = CurrentFocal, hor = CurrentHor, ver = CurrentVer });
- }
- return false;
- }
- catch (Exception ex)
- {
- AppData.Instance.LogHelper.ExceptionLog(ex, $"单张抓拍", LogEnum.RunException);
- AddMessageInfo($"单张抓拍异常:{ex.Message}");
- return false;
- }
- }
- /// <summary>
- /// 水平抓图
- /// </summary>
- public void ShuiPingZhuaPai()
- {
- try
- {
- IsStop = false;
- if (Serial == null) return;
- if (IsStop) return;
- // M8-G3-1:水平抓图为多步循环采图流程,用 Begin scope 串联各 well 抓拍子埋点(module=对焦调试)。
- using var _op = Aivfo.OperationLog.OperationLogger.Begin("对焦调试", "水平抓图",
- houseSn: CurrentHouseId);
- try { _op.Input(new { houseSn = CurrentHouseId }); } catch { }
- Serial.HorizontalResetWait(tLSetting.motorDelay);
- CurrentHor = 0;
- CurrentWell = 0;
- HouseWellSetting currentHorSetting = null;
- string dtnow = string.Format("{0:yyyy-MM-dd-HH-mm-ss}", DateTime.Now); //24小时制
- string path = AppData.Instance.LogHelper.GetDeBugShuiPingDirectory(CurrentHouse.houseSn, dtnow);
- if (!Directory.Exists(path))
- {
- Directory.CreateDirectory(path);
- }
- for (int i = 1; i <= 16; i++)
- {
- currentHorSetting = houseWellSettingList.FirstOrDefault(x => x.houseSn == CurrentHouseId && x.wellSn == i);
- if (currentHorSetting == null)
- {
- AddMessageInfo($"[未获取到1号well的水平电机位置]");
- continue;
- }
- if (IsStop) return;
- if (Serial == null) return;
- Serial.HorizontalMoveToWait(currentHorSetting.horizontalMotorPosition, tLSetting.motorDelay);
- if (IsStop) return;
- CurrentHor = currentHorSetting.horizontalMotorPosition;
- CurrentWell = i;
- string filename = $"{dtnow}-house{CurrentHouse.houseSn}-well{CurrentWell}-{CurrentFocal}-{CurrentHor}-{CurrentVer}.jpg";
- string fullName = $"{path}{filename}";
- if (Cam == null) return;
- if (SavePic(fullName))
- {
- AddPic(fullName);
- }
- }
- }
- catch (Exception ex)
- {
- AppData.Instance.LogHelper.ExceptionLog(ex, $"水平抓拍", LogEnum.RunException);
- AddMessageInfo($"水平抓拍异常:{ex.Message}");
- }
- }
- /// <summary>
- /// 清晰图层抓图
- /// </summary>
- public async Task AutoFocusPic(int focalCount, int xun)
- {
- await Task.Run(async () =>
- {
- try
- {
- IsStop = false;
- var startAutoFocus = -1;
- var cc = ccdPhoto.FirstOrDefault(x => x.houseSn == CurrentHouseId && x.wellSn == CurrentWell);
- if (cc == null)
- {
- AddMessageInfo($"[未获取到{CurrentWell}号well的自动对焦起点]");
- return;
- }
- // M8-G3-1:清晰图层抓图为多步循环采图流程,用 Begin scope 串联各层抓拍子埋点(module=对焦调试)。
- using var _op = Aivfo.OperationLog.OperationLogger.Begin("对焦调试", "清晰图层抓图",
- houseSn: CurrentHouseId);
- try { _op.Input(new { houseSn = CurrentHouseId, well = CurrentWell, focalCount, xun }); } catch { }
- startAutoFocus = cc.autoFocusPosition;
- string dtnow = string.Format("{0:yyyy-MM-dd-HH-mm-ss}", DateTime.Now); //24小时制
- string path = null;
- string fullName = null;
- for (int k = 0; k < xun; k++)
- {
- if (IsStop) return;
- if (Serial == null) return;
- Serial.VerticalResetWait(tLSetting.motorDelay);
- CurrentVer = 0;
- CurrentFocal = 0;
- var verSpacePulse = 128;
- if (CurrentHouse.verticalMotorSpacePulse.HasValue) verSpacePulse = CurrentHouse.verticalMotorSpacePulse.Value;
- path = $"{AppData.Instance.LogHelper.GetDeBugQingXiDirectory(CurrentHouse.houseSn, CurrentWell, dtnow)}{(k + 1)}_{CurrentHor}";
- if (!Directory.Exists(path)) Directory.CreateDirectory(path);
- for (int i = 0; i < focalCount; i++)
- {
- CurrentFocal = i + 1;
- var currentVerValue = startAutoFocus + (i * verSpacePulse);
- if (IsStop) return;
- if (Serial == null) return;
- if(currentVerValue > tLSetting.verticalMotorPulseMax)
- {
- AddMessageInfo($"清晰图层抓图超出垂直电机上限:{tLSetting.verticalMotorPulseMax}");
- return;
- }
- Serial.VerticalMoveToWait(currentVerValue, tLSetting.motorDelay);
- CurrentVer = currentVerValue;
- fullName = $"{path}\\{currentVerValue}.jpg";
- if (IsStop) return;
- if (Cam == null) return;
- if (SavePic(fullName)) AddPic(fullName);
- }
- }
- }
- catch (Exception ex)
- {
- AppData.Instance.LogHelper.ExceptionLog(ex, $"清晰图层抓图", LogEnum.RunException);
- AddMessageInfo($"清晰图层抓图异常:{ex.Message}");
- }
- });
- }
- /// <summary>
- /// 抓图
- /// </summary>
- public int GetPicData()
- {
- try
- {
- if (Cam == null) return -1;
- int GetRgbData = -1;
- bool isWuTu = false;
- if (isWuTu)
- {
- GetRgbData = Cam.GrabRaw();//获取字节流
- AddMessageInfo($"[抓拍结果:{GetRgbData}][注:0表示成功]");
- if (GetRgbData == 0)
- {
- GetRgbData = Cam.RawToRgb();
- AddMessageInfo($"[rawToRgb结果:{GetRgbData}][注:0表示成功]");
- }
- }
- else
- {
- GetRgbData = Cam.GrabRgb();//获取字节流
- AddMessageInfo($"[抓拍结果:{GetRgbData}][注:0表示成功]");
- }
- return GetRgbData;
- }
- catch (Exception ex)
- {
- AppData.Instance.LogHelper.ExceptionLog(ex, $"调试模式抓拍", LogEnum.RunException);
- AddMessageInfo($"相机抓拍异常:{ex.Message}");
- return -1;
- }
- }
- #endregion
- #region 相机操作
- /// <summary>
- /// 设置曝光值
- /// </summary>
- /// <param name="newExporuse"></param>
- public void SetExposure(int newExporuse)
- {
- if (Cam == null) { AddMessageInfo("设置曝光失败:相机句柄为空"); return; }
- // M8-G3-1:设置相机曝光为相机设备命令入口,补操作日志埋点(module=对焦调试)。
- var ret = Aivfo.OperationLog.OperationLogger.Run("对焦调试", "设置相机曝光值",
- () => Cam.SetExposure(newExporuse),
- input: new { houseSn = CurrentHouseId, ccdId = CurrentCCDId, newExporuse });
- AddMessageInfo($"设置曝光结果:{ret}");
- }
- /// <summary>
- /// 打开实时预览(贴宿主窗口句柄)。M1-B2:走借用到的 lease.Camera(StartPreview),不再触碰具体 Camera。
- /// 返回 0 成功;相机句柄为空返回 -1。
- /// </summary>
- public int StartPreview(IntPtr hostControl, int left, int top, int width, int height)
- {
- if (Cam == null) return -1;
- return Cam.StartPreview(hostControl, left, top, width, height);
- }
- /// <summary>关闭实时预览。返回 0 成功;相机句柄为空返回 -1。</summary>
- public int StopPreview()
- {
- if (Cam == null) return -1;
- return Cam.StopPreview();
- }
- //public bool OpenVideo(IntPtr mControlPtr, int left, int top, int width, int height)
- //{
- // try
- // {
- // var a = camera.Usb2Start(mControlPtr, left, top, width, height);
- // AddMessageInfo($"图像打开结果[0表示成功]:{a}");
- // return a == 0;
- // }
- // catch (Exception ex)
- // {
- // ExLog(ex, "OpenVideo");
- // AddMessageInfo($"图像打开异常:{ex.Message}");
- // return false;
- // }
- //}
- //public bool CloseVideo()
- //{
- // try
- // {
- // var a = camera.Usb2Stop();
- // AddMessageInfo($"图像关闭结果[0表示成功]:{a}");
- // return a == 0;
- // }
- // catch (Exception ex)
- // {
- // ExLog(ex, "CloseVideo");
- // AddMessageInfo($"图像关闭异常:{ex.Message}");
- // return false;
- // }
- //}
- #endregion
- #region 参数保存
- /// <summary>
- /// 保存舱室参数
- /// </summary>
- /// <returns></returns>
- public bool SetHouseInfo()
- {
- try
- {
- if (CurrentHouse == null) return true;
- string body = JsonConvert.SerializeObject(new
- {
- tlSn = CurrentHouse.tlSn,
- houseSn = CurrentHouse.houseSn,
- ccdExposure = CurrentHouse.ccdExposure,
- inletValveOpeningTime = CurrentHouse.inletValveOpeningTime,
- verticalMotorSpacePulse = CurrentHouse.verticalMotorSpacePulse,
- });
- return AppData.Instance.HttpHelper.HouseDebuggingApi(body);
- }
- catch (Exception ex)
- {
- ExLog(ex, "SetHouseExposure");
- return false;
- }
- }
- /// <summary>
- /// 保存当前well位置
- /// </summary>
- /// <returns></returns>
- public bool SetWellMotorPosition()
- {
- try
- {
- if (CurrentHouse == null)
- {
- AddMessageInfo("获取舱室信息失败");
- }
- string body = JsonConvert.SerializeObject(new
- {
- horizontalMotorPosition = CurrentHor,
- houseSn = CurrentHouse.houseSn,
- tlSn = CurrentHouse.tlSn,
- wellSn = CurrentWell,
- });
- return AppData.Instance.HttpHelper.WellUpdateApi(body);
- }
- catch (Exception ex)
- {
- ExLog(ex, "SetWellMotorPosition");
- return false;
- }
- }
- /// <summary>
- /// 保存自动对焦起点
- /// </summary>
- /// <returns></returns>
- public bool SetWellAutoFocus()
- {
- try
- {
- if (CurrentHouse == null)
- {
- AddMessageInfo("获取舱室信息失败");
- }
- string body = JsonConvert.SerializeObject(new
- {
- verticalMotorPosition = CurrentVer,
- houseSn = CurrentHouse.houseSn,
- tlSn = CurrentHouse.tlSn,
- wellSn = CurrentWell,
- });
- return AppData.Instance.HttpHelper.WellUpdateApi(body);
- }
- catch (Exception ex)
- {
- ExLog(ex, "SetWellAutoFocus");
- return false;
- }
- }
- #endregion
- private void ComBin_ExceptionLogEvent(Exception exception, string arg2, string arg3, LogEnum @enum)
- {
- AppData.Instance.LogHelper.ExceptionLog(exception, $"{arg2}{arg3}", @enum);
- }
- private void ComBin_ErrorLogEvent(string arg1, LogEnum @enum)
- {
- AppData.Instance.LogHelper.TLLog(arg1, @enum);
- }
- private void ComBin_CommandLogEvent(int arg1, DateTime time, string arg3, LogEnum @enum)
- {
- AppData.Instance.LogHelper.HouseLog(arg1, time, arg3, @enum);
- }
- public void AddMessageInfo(string mess)
- {
- MessageEvent?.Invoke(mess);
- }
- public void AddPic(string picFullName)
- {
- AddPicEvent?.Invoke(picFullName, CurrentWell, CurrentFocal);
- }
- #region M2-05 场景A 一键全自动标定(沙盒)
- /// <summary>
- /// M2-05 场景A 工程师调试页一键全自动标定(人盯安全沙盒,03 §2/§7.1)。
- /// 流程:对选中 well 列表逐 well 跑 M2-01 四步标定引擎(CalibrationEngine) →
- /// 收集 WellCalib → 实时 UI 合格绿/伪峰红 → 结果作出厂基准 scene=0 落库 + 写 calibration.json。
- ///
- /// 硬件复用:调试页 ComHouseInit 已经 Acquire(OperateDebug) 前台借用(HAL 暂停 control 采集),
- /// 借用到的 lease.Serial/lease.Camera 即与采集端同一物理句柄(M1-B2)。标定引擎直接用这两个 HAL 接口,
- /// 不再 new ComBin/Camera、不二次 Open/Init 同 COM 口/相机。互斥由调试页持有的前台借用保证。
- /// 中止:IsStopCalibrate 标志,每 well 间检查,工程师可随时中止,已完成 well 结果保留。
- /// 异常:单 well 失败/存储失败不崩 UI,记日志继续;整体异常兜底,IsCalibrating 复位。
- ///
- /// ⚠ 待验证 V-055..V-059:16well 跑通(关联 V-004 算法严谨性)/合格绿伪峰红/基准scene0落库+JSON/
- /// 借用期间采集暂停/中止响应。
- /// </summary>
- /// <param name="wells">勾选的 well 列表(空/null 视为全 16 well)。</param>
- public async Task OneClickCalibrate(IEnumerable<int> wells = null)
- {
- await Task.Run(() =>
- {
- if (IsCalibrating)
- {
- AddMessageInfo("[一键标定]已在标定中,请勿重复触发");
- return;
- }
- if (Serial == null || Cam == null)
- {
- AddMessageInfo("[一键标定]请先初始化舱室(串口/相机未就绪)");
- return;
- }
- if (CurrentHouse == null)
- {
- AddMessageInfo("[一键标定]未获取到舱室信息");
- return;
- }
- IsCalibrating = true;
- IsStopCalibrate = false;
- // M8-P3b:一键标定为关键命令入口,建立操作日志 scope(统一 traceId 串联本次标定内的 HTTP/串口/相机埋点)。
- using var _opScope = Aivfo.OperationLog.OperationLogger.Begin("对焦调试", "一键标定",
- houseSn: CurrentHouseId);
- try { _opScope.Input(new { houseSn = CurrentHouseId }); } catch { }
- // 勾选 well:未传则默认 16 well;去重、按序、限定 1-16。
- var wellList = (wells != null ? wells : Enumerable.Range(1, 16))
- .Where(w => w >= 1 && w <= 16).Distinct().OrderBy(w => w).ToList();
- if (wellList.Count == 0) wellList = Enumerable.Range(1, 16).ToList();
- // 合格判据阈值:tl_setting.focus_peak_ratio_threshold,缺省 1.2(03 §7.1)。
- double peakThreshold = (tLSetting != null && tLSetting.focusPeakRatioThreshold.HasValue)
- ? (double)tLSetting.focusPeakRatioThreshold.Value : 1.2;
- ResetCalibResults(wellList);
- // 标定结果存储:calibration.json 真相源(12 §2.7/03 §4,IncludeFields=true 由 CalibrationFile.Load 保证)。
- // operate 端无 SqlSugar 直连(走 HttpHelper),故 DbMirror=null:仅写 JSON 真相源;
- // house_autofocus_calibration 的 scene=0 基准 upsert 由 control 端 AppData.AutofocusStore 镜像(M2-04)。
- var store = new CalibrationStore
- {
- JsonPath = System.IO.Path.Combine(
- System.AppDomain.CurrentDomain.BaseDirectory, @"DependFile\AutoFocus\calibration.json"),
- Source = "OPERATE_DEBUG_SCENE0",
- Log = msg => AddMessageInfo($"[一键标定]{msg}"),
- // DbMirror 为空 → 只写 JSON 不镜像库(operate 无 DB 直连)。
- };
- try
- {
- var jsonDir = System.IO.Path.GetDirectoryName(store.JsonPath);
- if (!string.IsNullOrEmpty(jsonDir) && !System.IO.Directory.Exists(jsonDir))
- System.IO.Directory.CreateDirectory(jsonDir);
- }
- catch (Exception exDir)
- {
- AddMessageInfo($"[一键标定]创建 calibration.json 目录失败(将仅 UI 显示):{exDir.Message}");
- }
- string tlSn = (tLSetting != null && !string.IsNullOrEmpty(tLSetting.tlSn))
- ? tLSetting.tlSn : (CurrentHouse.tlSn ?? AppData.Instance.TlSn);
- try
- {
- // M1-B2:借用到的 lease.Serial/lease.Camera 本就是 HAL 接口(ISerialChannel/ICamera),
- // 直接喂给 M2-01 引擎,无需再经 DebugSerial/CameraAdapter 包 operate 具体类型(已退役)。
- var serial = Serial;
- var cam = Cam;
- var engine = new CalibrationEngine(serial, cam)
- {
- Log = msg => AddMessageInfo(msg)
- };
- AddMessageInfo($"[一键标定]开始:舱{CurrentHouse.houseSn} 共 {wellList.Count} well,合格峰比阈值={peakThreshold:F2}");
- foreach (var well in wellList)
- {
- if (IsStopCalibrate)
- {
- AddMessageInfo("[一键标定]已被中止,停止后续 well");
- break;
- }
- UpdateCalibResult(well, item => { item.State = WellCalibState.Running; item.Note = "标定中..."; });
- CurrentWell = well;
- try
- {
- // EEPROM 仅作扫描中心(参考),不进配置解析链、不回写(§2.5)。
- int hpos = serial.ReadWellHorizontalPosWait(well);
- int zZero = serial.ReadWellFocusZeroWait(well);
- var wc = engine.CalibrateWell(well, Math.Max(0, hpos), Math.Max(0, zZero));
- if (wc == null)
- {
- UpdateCalibResult(well, item =>
- {
- item.State = WellCalibState.Failed;
- item.Note = "无结果";
- });
- AddMessageInfo($"[一键标定]{well}号 well 无标定结果");
- continue;
- }
- // 合格判据:circleFound && peakRatio>阈值 → 绿;否则(未检圆/伪峰/弱峰) → 红。
- bool qualified = wc.CircleFound && wc.PeakRatio > peakThreshold;
- UpdateCalibResult(well, item =>
- {
- item.State = qualified ? WellCalibState.Qualified : WellCalibState.FakePeak;
- item.FocusZ = wc.FocusZ;
- item.PeakRatio = wc.PeakRatio;
- item.CenterOffsetPct = wc.CenterOffsetPct;
- item.CircleFound = wc.CircleFound;
- item.Exposure = wc.Exposure;
- item.Note = qualified
- ? $"合格 Z={wc.FocusZ} 峰比={wc.PeakRatio:F2}"
- : $"伪峰 Z={wc.FocusZ} 峰比={wc.PeakRatio:F2} {(wc.CircleFound ? "" : "未检圆")}{wc.Note}";
- });
- AddMessageInfo($"[一键标定]{well}号 well {(qualified ? "✓合格(绿)" : "✗伪峰(红)")} " +
- $"FocusZ={wc.FocusZ} 峰比={wc.PeakRatio:F2} 偏移={wc.CenterOffsetPct:F1}%");
- // 出厂基准 scene=0 落库 + 写 calibration.json(存储失败不崩 UI,CalibrationStore 内部已吞异常)。
- try
- {
- store.SaveCalibration(wc, tlSn, CurrentHouse.houseSn, well, scene: 0,
- port: CurrentHouse.housePort, ccdSn: CurrentHouse.ccdSn);
- }
- catch (Exception exStore)
- {
- AddMessageInfo($"[一键标定]{well}号 well 结果存档失败:{exStore.Message}");
- }
- }
- catch (Exception exWell)
- {
- // 单 well 异常不崩 UI:记日志/标红,继续下一 well。
- UpdateCalibResult(well, item =>
- {
- item.State = WellCalibState.Failed;
- item.Note = $"异常:{exWell.Message}";
- });
- ExLog(exWell, $"OneClickCalibrate.well{well}");
- AddMessageInfo($"[一键标定]{well}号 well 标定异常:{exWell.Message}");
- }
- }
- int okCount = CalibResults.Count(x => x.State == WellCalibState.Qualified);
- AddMessageInfo($"[一键标定]结束:合格 {okCount}/{wellList.Count}(结果已存档为出厂基准 scene=0 + calibration.json)");
- // M8-P3b:记录标定结果到操作日志 scope。
- try { _opScope.Output(new { okCount, total = wellList.Count }).Success(); } catch { }
- }
- catch (Exception ex)
- {
- ExLog(ex, "OneClickCalibrate");
- AddMessageInfo($"[一键标定]整体异常:{ex.Message}");
- // M8-P3b:标定整体异常标记失败。
- try { _opScope.Fail(ex.GetType().Name + ": " + ex.Message); } catch { }
- }
- finally
- {
- IsCalibrating = false;
- }
- });
- }
- /// <summary>工程师中止一键标定。</summary>
- public void StopCalibrate()
- {
- IsStopCalibrate = true;
- AddMessageInfo("[一键标定]收到中止请求,将在当前 well 结束后停止");
- }
- private void ResetCalibResults(List<int> wells)
- {
- void build()
- {
- CalibResults.Clear();
- foreach (var w in wells)
- CalibResults.Add(new WellCalibUiItem { Well = w, State = WellCalibState.Pending, Note = "待标定" });
- }
- // 集合改动需在 UI 线程(ObservableCollection 绑定)。
- var disp = System.Windows.Application.Current?.Dispatcher;
- if (disp != null && !disp.CheckAccess()) disp.Invoke(build); else build();
- }
- private void UpdateCalibResult(int well, Action<WellCalibUiItem> mutate)
- {
- void apply()
- {
- var item = CalibResults.FirstOrDefault(x => x.Well == well);
- if (item == null)
- {
- item = new WellCalibUiItem { Well = well };
- CalibResults.Add(item);
- }
- mutate(item);
- }
- var disp = System.Windows.Application.Current?.Dispatcher;
- if (disp != null && !disp.CheckAccess()) disp.Invoke(apply); else apply();
- }
- #endregion
- #region M2-07 对焦后手动微调拍摄层(层数/层间距/下移)持久化 well 级
- /// <summary>
- /// M2-07 手调"实际拍摄层数"(well 级覆盖)。空字符串=留空继承设备级(保存写 null)。
- /// View TextBox 双向绑定;校验在保存/预览时做(层数≥1)。
- /// </summary>
- [ObservableProperty] private string manualLayerCount = "";
- /// <summary>
- /// M2-07 手调"实际拍摄层间距脉冲"(well 级覆盖)。空=继承设备级(写 null)。校验:>0。
- /// </summary>
- [ObservableProperty] private string manualLayerSpacing = "";
- /// <summary>
- /// M2-07 手调"对焦起点下移层数"(复用 move_down_layer)。空=继承设备级。
- /// 校验:≥0 且 <层数(下移层须落在拍摄范围内,§2.4 清晰层=第 down 层)。
- /// </summary>
- [ObservableProperty] private string manualMoveDown = "";
- /// <summary>
- /// M2-07 实时预览各层绝对 Z 位置(调 M2-02 ComputeLayerPositions 生成,关联 V-045)。
- /// View 绑定此集合显示 N 层位置列表,让工程师看到手调效果。
- /// </summary>
- public ObservableCollection<LayerPreviewItem> LayerPreview { get; } = new ObservableCollection<LayerPreviewItem>();
- /// <summary>
- /// M2-07 预览/手调锚点 well(默认随水平电机当前 well / 一键标定取 CurrentWell)。
- /// </summary>
- [ObservableProperty] private int manualTuneWell = 1;
- /// <summary>
- /// 取该 well 当前生效的"实际拍摄层"配置(well 级覆盖优先,空则回退设备级),
- /// 回填三个手调输入框 + 触发一次预览。供"载入当前值"按钮调用。
- /// </summary>
- public void LoadManualLayerSetting(int well)
- {
- ManualTuneWell = well;
- var ws = houseWellSettingList.FirstOrDefault(x => x.houseSn == CurrentHouseId && x.wellSn == well);
- // well 级覆盖非空显示 well 值,否则显示继承的设备级值作占位(§2.5 就近优先)。
- int? wellCount = ws?.focusLayerCount;
- int? wellSpacing = ws?.focusLayerSpacingPulse;
- // 下移复用 moveDownLayer(well 级为非空 int 列;0 视为有效覆盖值)。
- int? wellDown = ws != null ? (int?)ws.moveDownLayer : null;
- ManualLayerCount = (wellCount ?? tLSetting?.focusLayerCount)?.ToString() ?? "";
- ManualLayerSpacing = (wellSpacing ?? tLSetting?.focusLayerSpacingPulse)?.ToString() ?? "";
- ManualMoveDown = (wellDown ?? tLSetting?.focusLayerDown)?.ToString() ?? "";
- PreviewManualLayers();
- }
- /// <summary>
- /// 取该 well 最近标定的 FocusZ 作预览锚点(M2-05 一键标定结果 CalibResults 优先;
- /// 回退 ccdPhoto 的 clearestPosition 即 scene0/1 库下发的清晰位置)。
- /// 返回 null 表示无标定可用(须提示先标定)。
- /// </summary>
- private int? GetPreviewFocusZ(int well)
- {
- var calib = CalibResults.FirstOrDefault(x => x.Well == well
- && (x.State == WellCalibState.Qualified || x.State == WellCalibState.FakePeak));
- if (calib != null && calib.FocusZ > 0) return calib.FocusZ;
- // 回退:调试页加载的清晰位置(scene0/1 库值 clearestPosition)。
- var cc = ccdPhoto.FirstOrDefault(x => x.houseSn == CurrentHouseId && x.wellSn == well);
- if (cc != null && cc.clearestPosition > 0) return cc.clearestPosition;
- return null;
- }
- /// <summary>
- /// 解析三个手调输入框(空=继承设备级取回退值),返回有效 (count,spacing,down) 或 null(非法/缺失)。
- /// validateMsg 携带校验失败原因。
- /// </summary>
- private (int count, int spacing, int down)? ResolveEffectiveTune(out string validateMsg)
- {
- validateMsg = null;
- // 解析层数:空→设备级回退;非空→必须 int。
- int? count;
- if (string.IsNullOrWhiteSpace(ManualLayerCount)) count = tLSetting?.focusLayerCount;
- else if (int.TryParse(ManualLayerCount.Trim(), out int c)) count = c;
- else { validateMsg = "层数只能输入整数"; return null; }
- int? spacing;
- if (string.IsNullOrWhiteSpace(ManualLayerSpacing)) spacing = tLSetting?.focusLayerSpacingPulse;
- else if (int.TryParse(ManualLayerSpacing.Trim(), out int s)) spacing = s;
- else { validateMsg = "层间距只能输入整数"; return null; }
- int? down;
- if (string.IsNullOrWhiteSpace(ManualMoveDown)) down = tLSetting?.focusLayerDown;
- else if (int.TryParse(ManualMoveDown.Trim(), out int d)) down = d;
- else { validateMsg = "下移层数只能输入整数"; return null; }
- if (!count.HasValue) { validateMsg = "层数未配置(设备级也为空),请填层数或先初始化设备级"; return null; }
- if (!spacing.HasValue) { validateMsg = "层间距未配置(设备级也为空),请填层间距或先初始化设备级(§2.5 不兜底)"; return null; }
- if (!down.HasValue) { validateMsg = "下移层数未配置(设备级也为空),请填下移层数"; return null; }
- // 校验:层数≥1、间距>0、下移≥0 且 <层数(下移层须落在拍摄范围内)。
- if (count.Value < 1) { validateMsg = "层数必须 ≥ 1"; return null; }
- if (spacing.Value <= 0) { validateMsg = "层间距必须 > 0"; return null; }
- if (down.Value < 0) { validateMsg = "下移层数必须 ≥ 0"; return null; }
- if (down.Value >= count.Value) { validateMsg = $"下移层数必须 < 层数({count.Value}),否则清晰层落在拍摄范围外"; return null; }
- return (count.Value, spacing.Value, down.Value);
- }
- /// <summary>
- /// M2-07 实时预览:用该 well 标定 FocusZ + 当前手调值,调 M2-02
- /// ComputeLayerPositions(focusZ, cfg, pulseMax) 生成各层绝对 Z,刷新 LayerPreview(关联 V-045)。
- /// 无标定锚点 → 清空预览并提示先标定;校验非法 → 清空预览并提示。
- /// </summary>
- public void PreviewManualLayers()
- {
- try
- {
- var focusZ = GetPreviewFocusZ(ManualTuneWell);
- if (!focusZ.HasValue)
- {
- SetLayerPreview(null);
- AddMessageInfo($"[手调拍摄层]well{ManualTuneWell} 无标定结果,请先对该 well 标定(或确认已下发清晰位置)再预览");
- return;
- }
- var eff = ResolveEffectiveTune(out string msg);
- if (eff == null)
- {
- SetLayerPreview(null);
- AddMessageInfo($"[手调拍摄层]预览失败:{msg}");
- return;
- }
- var cfg = new FocusLayerConfig
- {
- LayerCount = eff.Value.count,
- LayerSpacingPulse = eff.Value.spacing,
- LayerDown = eff.Value.down,
- };
- int pulseMax = tLSetting != null ? tLSetting.verticalMotorPulseMax : 0;
- int[] positions = PhotoLayerCalculator.ComputeLayerPositions(focusZ.Value, cfg, pulseMax);
- var items = new List<LayerPreviewItem>();
- for (int i = 0; i < positions.Length; i++)
- {
- items.Add(new LayerPreviewItem
- {
- LayerIndex = i,
- ZPulse = positions[i],
- IsFocusLayer = (i == eff.Value.down), // 第 down 层 = 清晰层(FocusZ 锚点)
- });
- }
- SetLayerPreview(items);
- AddMessageInfo($"[手调拍摄层]well{ManualTuneWell} 预览:锚点FocusZ={focusZ.Value} 层数={eff.Value.count} " +
- $"间距={eff.Value.spacing} 下移={eff.Value.down} → 第0层Z={positions[0]} 第{positions.Length - 1}层Z={positions[positions.Length - 1]}");
- }
- catch (Exception ex)
- {
- SetLayerPreview(null);
- ExLog(ex, "PreviewManualLayers");
- AddMessageInfo($"[手调拍摄层]预览异常:{ex.Message}");
- }
- }
- /// <summary>
- /// M2-07 保存为该 well 默认:校验通过后,把手调值写 house_well_setting well 级覆盖
- /// (focus_layer_spacing_pulse/focus_layer_count + 复用 move_down_layer)。
- /// 复用现有 operate 端 well 设置保存通道 HttpHelper.WellUpdateApi(同 SetWellMotorPosition/SetWellAutoFocus),
- /// 走 /api/tl/control/setting/house/well/update。留空字段=继承设备级(写 null)。
- /// 下次该 well 经 §2.5 就近优先(PhotoLayerCalculator.Resolve)沿用 well 覆盖值。
- /// 返回 true=保存成功。
- /// </summary>
- public bool SaveManualLayerTune()
- {
- try
- {
- if (CurrentHouse == null)
- {
- AddMessageInfo("[手调拍摄层]未获取到舱室信息");
- return false;
- }
- // M8-G3-1:保存手调拍摄层为"本地校验/计算 + HTTP 持久化 + 内存同步"打包的关键业务操作,
- // 用 Begin scope 给一个父操作名(统一 traceId 串联其内的 WellUpdateApi HTTP 埋点;module=对焦调试)。
- using var _op = Aivfo.OperationLog.OperationLogger.Begin("对焦调试", "保存手调拍摄层设置",
- houseSn: CurrentHouseId);
- // 校验:层数≥1、间距>0、下移≥0 且 <层数;非法不保存。
- var eff = ResolveEffectiveTune(out string msg);
- if (eff == null)
- {
- AddMessageInfo($"[手调拍摄层]保存被拦截(非法值):{msg}");
- try { _op.Output(new { rejected = msg }).Fail("校验未通过:" + msg); } catch { }
- return false;
- }
- // 留空字段=继承设备级 → 写 null(well 级覆盖留空,§2.5)。非空字段写实际值。
- int? wellCount = string.IsNullOrWhiteSpace(ManualLayerCount) ? (int?)null : int.Parse(ManualLayerCount.Trim());
- int? wellSpacing = string.IsNullOrWhiteSpace(ManualLayerSpacing) ? (int?)null : int.Parse(ManualLayerSpacing.Trim());
- // 下移复用 move_down_layer(库列非空);留空时回退取生效值(eff.down)写回,不破坏旧列语义。
- int wellMoveDown = string.IsNullOrWhiteSpace(ManualMoveDown) ? eff.Value.down : int.Parse(ManualMoveDown.Trim());
- try { _op.Input(new { houseSn = CurrentHouseId, well = ManualTuneWell, wellCount, wellSpacing, wellMoveDown }); } catch { }
- // 复用现有 well 设置保存通道:与 SetWellMotorPosition/SetWellAutoFocus 同一 WellUpdateApi。
- // 后端按 tlSn/houseSn/wellSn 定位 house_well_setting 行做部分更新(仅本次携带的字段)。
- string body = JsonConvert.SerializeObject(new
- {
- tlSn = CurrentHouse.tlSn,
- houseSn = CurrentHouse.houseSn,
- wellSn = ManualTuneWell,
- focusLayerSpacingPulse = wellSpacing, // null=继承设备级
- focusLayerCount = wellCount, // null=继承设备级
- moveDownLayer = wellMoveDown, // 复用既有列(下移)
- });
- bool ok = AppData.Instance.HttpHelper.WellUpdateApi(body);
- if (!ok)
- {
- AddMessageInfo("[手调拍摄层]保存失败(接口返回失败)");
- try { _op.Fail("WellUpdateApi 返回失败"); } catch { }
- return false;
- }
- // 本地内存同步,使"下次该 well 沿用"在不重载设置时也即时生效(预览/取数一致)。
- var ws = houseWellSettingList.FirstOrDefault(x => x.houseSn == CurrentHouseId && x.wellSn == ManualTuneWell);
- if (ws != null)
- {
- ws.focusLayerCount = wellCount;
- ws.focusLayerSpacingPulse = wellSpacing;
- ws.moveDownLayer = wellMoveDown;
- }
- AddMessageInfo($"[手调拍摄层]well{ManualTuneWell} 已存为默认:层数={(wellCount?.ToString() ?? "继承")} " +
- $"间距={(wellSpacing?.ToString() ?? "继承")} 下移={wellMoveDown}(写 house_well_setting well 级覆盖,留空继承设备级)");
- try { _op.Output(new { ok = true }).Success(); } catch { }
- return true;
- }
- catch (Exception ex)
- {
- ExLog(ex, "SaveManualLayerTune");
- AddMessageInfo($"[手调拍摄层]保存异常:{ex.Message}");
- return false;
- }
- }
- private void SetLayerPreview(List<LayerPreviewItem> items)
- {
- void build()
- {
- LayerPreview.Clear();
- if (items != null)
- foreach (var it in items) LayerPreview.Add(it);
- }
- var disp = System.Windows.Application.Current?.Dispatcher;
- if (disp != null && !disp.CheckAccess()) disp.Invoke(build); else build();
- }
- #endregion
- }
- }
|