HouseDebugPageViewModel.cs 85 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832
  1. using CommunityToolkit.Mvvm.ComponentModel;
  2. using ivf_tl_Entity.CameraEntitys;
  3. using ivf_tl_Entity.ComEntitys;
  4. using ivf_tl_Entity.DebugEntitys;
  5. using ivf_tl_Entity.DTO;
  6. using ivf_tl_Entity.GlobalEnums;
  7. using ivf_tl_Operate.Converts;
  8. using ivf_tl_Operate.Debug;
  9. using ivf_tl_Operate.Helpers;
  10. using ivf_tl_Services;
  11. using IvfTl.Hardware;
  12. using IvfTl.Hardware.Impl;
  13. using IvfTl.AutoFocus.Layout;
  14. using Newtonsoft.Json;
  15. using Newtonsoft.Json.Linq;
  16. using System;
  17. using System.Collections.Generic;
  18. using System.Collections.ObjectModel;
  19. using System.Configuration;
  20. using System.DirectoryServices.ActiveDirectory;
  21. using System.IO;
  22. using System.Linq;
  23. using System.Reflection.Metadata;
  24. using System.Text;
  25. using System.Threading.Tasks;
  26. using System.Windows;
  27. using static ivf_tl_Operate.CustomUserControls.RecordBox;
  28. using System.Windows.Documents;
  29. namespace ivf_tl_Operate.ViewModel
  30. {
  31. public partial class HouseDebugPageViewModel : ObservableObject
  32. {
  33. public event Action<string> MessageEvent;
  34. public event Action<string, int, int> AddPicEvent;
  35. public event Action OpenVideoEvent;
  36. // M1-B2:调试页不再 new ComBin/new Camera 开第二个物理串口/相机。
  37. // 全部硬件动作走借用到的 HAL 句柄(_halLease.Serial / _halLease.Camera)——与采集端同一物理实例,
  38. // 配合 T1.3(前台借用时采集端暂停让出 ComBin),端口/相机占用根除(审计 B2)。
  39. /// <summary>借用到的串口句柄(与采集端同一实例);未持借用时为 null。</summary>
  40. private IvfTl.Hardware.ISerialChannel Serial => _halLease?.Serial;
  41. /// <summary>借用到的相机句柄(与采集端同一实例);未持借用时为 null。</summary>
  42. private IvfTl.Hardware.ICamera Cam => _halLease?.Camera;
  43. /// <summary>
  44. /// M1-03 HAL 前台借用凭证。打开调试页时向 HAL 申请该舱独占借用(HardwareUser.OperateDebug),
  45. /// HAL 自动暂停 control 对该舱的后台采集;关闭调试页 Dispose 归还,HAL 恢复采集。
  46. /// ⚠ 待验证 V-024:借用→暂停采集→归还恢复时序(调试取图 vs 后台采集切换不占用/不死锁,01 §3 M1 必过)。
  47. /// 说明(代码隔离 + 范围控制):调试页 ComBin/Camera 仍用 operate 侧 ivf_tl_Entity 具体类型——
  48. /// 因调试栈方法更全(Write*EEPROM / 电机正反向 / RawToRgb 等),control 侧 SerialHelper ComBin 未覆盖,
  49. /// 折叠进 HAL ISerialChannel 属 M2 统一。M1 通过 HAL 借用闸门保证"同舱同一时刻单一使用者",
  50. /// 杜绝与后台采集同时 Open 同 COM 口/Init 同相机。
  51. /// </summary>
  52. private IHardwareLease _halLease = null;
  53. // ── 自动对焦重构 D2-02-T3.4:调试页标定改"经 control 协作",不再 operate 本地自建 CalibrationEngine ──
  54. /// <summary>
  55. /// 调试会话客户端:经 control 本地 HTTP /debug/acquire 借该舱硬件,拿 sessionId(存 CurrentSessionId)。
  56. /// control 独立进程持有真硬件;operate 进程内 HAL 是空壳(从不 ScanDevices),故借硬件/预览/标定全走此 HTTP 协作。
  57. /// 借到后起心跳;ComHouseUnit 归还。会话失效回调提示重进调试。
  58. /// </summary>
  59. private DebugSessionClient _sessionClient;
  60. /// <summary>
  61. /// 16 孔标定协作客户端:复用同一 sessionId,封 control /debug/calibrate/{start,progress,recalibrate,stop}。
  62. /// acquire 成功后构造;ComHouseUnit 释放。
  63. /// </summary>
  64. private CalibrationClient _calibClient;
  65. /// <summary>标定进度轮询任务的取消源(IsRunning 转 false 或停止标定时取消)。</summary>
  66. private System.Threading.CancellationTokenSource _calibPollCts;
  67. /// <summary>
  68. /// 当前housesn
  69. /// </summary>
  70. public int CurrentHouseId { get; set; } = 1;
  71. /// <summary>当前借用会话 id(D2-02 第三阶段 acquire 时赋值;第二阶段预览用)。</summary>
  72. public string CurrentSessionId { get; set; }
  73. /// <summary>
  74. /// 当前ccdID
  75. /// </summary>
  76. public int CurrentCCDId { get; set; } = 0;
  77. /// <summary>
  78. /// 所有舱室
  79. /// </summary>
  80. public List<HouseInfo> HouseList { get; set; } = new List<HouseInfo>();
  81. /// <summary>
  82. /// 仪器设置
  83. /// </summary>
  84. public TLSetting tLSetting { get; set; } = new TLSetting();
  85. /// <summary>
  86. /// 自动对焦和拍照位置
  87. /// </summary>
  88. public List<HousePhotographLocation> ccdPhoto = new List<HousePhotographLocation>();
  89. /// <summary>
  90. /// 水平电机位置
  91. /// </summary>
  92. public List<HouseWellSetting> houseWellSettingList = new List<HouseWellSetting>();
  93. [ObservableProperty]
  94. private ObservableCollection<string> messageInfoList = new ObservableCollection<string>();
  95. [ObservableProperty]
  96. private decimal temperature = 0m;
  97. [ObservableProperty]
  98. private decimal pressure = 0m;
  99. [ObservableProperty]
  100. private string doorState = null;
  101. [ObservableProperty]
  102. private string ledState = null;
  103. [ObservableProperty]
  104. private int currentWell = 0;
  105. [ObservableProperty]
  106. private int currentFocal = 0;
  107. /// <summary>
  108. /// 结束抓图
  109. /// </summary>
  110. public bool IsStop { get; set; } = false;
  111. /// <summary>
  112. /// M2-05 一键标定中止标志(工程师可中止;每 well 间检查)。
  113. /// </summary>
  114. public bool IsStopCalibrate { get; set; } = false;
  115. /// <summary>
  116. /// M2-05 一键标定是否进行中(UI 据此禁用重复触发)。
  117. /// </summary>
  118. [ObservableProperty]
  119. private bool isCalibrating = false;
  120. /// <summary>
  121. /// M2-05 场景A 一键标定 16 well 实时结果(合格绿/伪峰红,含 FocusZ/峰比/偏移)。
  122. /// View 绑定此集合做 4x4 实时呈现(沿用调试页内呈现,不另开 CalibWindow)。
  123. /// </summary>
  124. public ObservableCollection<WellCalibUiItem> CalibResults { get; } = new ObservableCollection<WellCalibUiItem>();
  125. /// <summary>
  126. /// 垂直电机当前位置
  127. /// </summary>
  128. [ObservableProperty]
  129. private int currentVer = 0;
  130. /// <summary>
  131. /// 水平电机当前位置
  132. /// </summary>
  133. [ObservableProperty]
  134. private int currentHor = 0;
  135. [ObservableProperty]
  136. private HouseInfo currentHouse = null;
  137. [ObservableProperty]
  138. private int houseVentTimeE = 0;
  139. public HouseDebugPageViewModel()
  140. {
  141. //HouseList = AppData.Instance.HttpHelper.GetSettingHouseApi(AppData.Instance.TlSn);
  142. //CurrentHouse = HouseList.FirstOrDefault(x => x.houseSn == 1);
  143. }
  144. private void ExLog(Exception ex, string name)
  145. {
  146. AppData.Instance.LogHelper.ExceptionLog(ex, $"HouseDebugPageViewModel.{name}", LogEnum.RunException);
  147. }
  148. private void ErrorLog(string message, LogEnum logType)
  149. {
  150. AppData.Instance.LogHelper.TLLog($"HouseDebugPageViewModel.{message}", logType);
  151. }
  152. public void Start(ref string errora)
  153. {
  154. try
  155. {
  156. SerialBin serialBin = new SerialBin();
  157. serialBin.TLLogEvent += AppData.Instance.LogHelper.TLLog;
  158. serialBin.ExceptionLogEvent += AppData.Instance.LogHelper.ExceptionLog;
  159. serialBin.HouseLogEvent += AppData.Instance.LogHelper.HouseLog;
  160. var errorList = serialBin.UpdataCamera();
  161. AppData.Instance.LogHelper.TLLog($"ccdidsn:{JsonConvert.SerializeObject(serialBin.CCDidSn)}", LogEnum.RunRecord);
  162. if (errorList.Any())
  163. {
  164. errora = $"获取相机Id和CCDSN错误{JsonConvert.SerializeObject(errorList)}";
  165. AppData.Instance.LogHelper.TLLog(errora, LogEnum.RunRecord);
  166. return;
  167. }
  168. errorList = serialBin.Start(ConfigurationManager.AppSettings["autoFocus"].ToString());
  169. AppData.Instance.LogHelper.TLLog($"舱室信息:{JsonConvert.SerializeObject(serialBin.SerialModels)}", LogEnum.RunRecord);
  170. AppData.Instance.LogHelper.TLLog($"E方数据:{JsonConvert.SerializeObject(serialBin.HouseEEPROInfos)}", LogEnum.RunRecord);
  171. if (errorList.Any())
  172. {
  173. errora = $"获取串口信息错误{JsonConvert.SerializeObject(errorList)}";
  174. AppData.Instance.LogHelper.TLLog(errora, LogEnum.RunRecord);
  175. return;
  176. }
  177. var modelCount = serialBin.SerialModels.Count;
  178. if (modelCount != 11)
  179. {
  180. //string messageinfo = $"检测到{modelCount}个模块,是否继续运行?";
  181. string messageinfo = $" Detected {modelCount} cabin, are you sure to run?";
  182. MessageBoxResult aaa = MessageBox.Show(messageinfo, KeyToStringConvert.GetLanguageStringByKey("C0171"), MessageBoxButton.YesNo, MessageBoxImage.Question, MessageBoxResult.No, MessageBoxOptions.DefaultDesktopOnly);
  183. if (aaa != MessageBoxResult.Yes)
  184. {
  185. errora = "结束";
  186. return;
  187. }
  188. }
  189. List<int> listIntRunHoues = serialBin.SerialModels.Select(x => x.houseSn).ToList();
  190. TLInitData tLInitData = new TLInitData();
  191. tLInitData.tlSn = $"NEO-1-{serialBin.TLNum}";
  192. tLInitData.softwareVersion = "V2.0.0";
  193. tLInitData.verticalMotorPulseMax = 125000;
  194. tLInitData.houseLinkDataList = serialBin.SerialModels.OrderBy(x => x.houseSn).ToList();
  195. foreach (var item in serialBin.HouseEEPROInfos)
  196. {
  197. item.tlSn = tLInitData.tlSn;
  198. }
  199. tLInitData.houseEEPROInitDTOList = serialBin.HouseEEPROInfos.OrderBy(x => x.houseSn).ToList();
  200. AppData.Instance.LogHelper.TLLog($"舱室信息:{JsonConvert.SerializeObject(tLInitData)}", LogEnum.RunRecord);
  201. SettingDataApiData settingDataApiData = AppData.Instance.HttpHelper.GetSettingDataApi(tLInitData);
  202. if (settingDataApiData == null)
  203. {
  204. errora = $"{tLInitData.tlSn}获取仪器设置失败";
  205. return;
  206. }
  207. AppData.Instance.LogHelper.TLLog(JsonConvert.SerializeObject(settingDataApiData), LogEnum.RunRecord);
  208. tLSetting = AppData.Instance.ConvertHelper.ConvertToTLSetting(settingDataApiData.tlInfo, settingDataApiData.tlSetting);
  209. ccdPhoto = settingDataApiData.housePhotographLocation;
  210. houseWellSettingList = settingDataApiData.houseWellSettingList;
  211. HouseList = settingDataApiData.houseList;
  212. CurrentHouse = HouseList.FirstOrDefault(x => x.houseSn == 1);
  213. }
  214. catch (Exception ex)
  215. {
  216. AppData.Instance.LogHelper.ExceptionLog(ex, $"调试模式初始化", LogEnum.RunException);
  217. errora = $"调试模式初始化异常:{ex.Message}";
  218. }
  219. }
  220. public async Task ComHouseInit()
  221. {
  222. await Task.Run(async () =>
  223. {
  224. try
  225. {
  226. var currentHouse = HouseList.FirstOrDefault(x => x.houseSn == CurrentHouseId);
  227. if (currentHouse == null)
  228. {
  229. AddMessageInfo($"[{CurrentHouseId}]未获取到舱室信息,无法进入调试");
  230. return;
  231. }
  232. // D2-02-T3.4:先经 control HTTP 协作借该舱调试会话拿 sessionId(预览/标定/会话命令均依赖)。
  233. // control 独立进程持真硬件;operate 进程内 HAL 是空壳(从不 ScanDevices)、下面的本地 lease.Serial 取不到,
  234. // 故借硬件的"真正入口"是这里的 HTTP acquire。放在本地 HAL 借用之前,确保 sessionId 一定先建立。
  235. await AcquireDebugSessionAsync(currentHouse.houseSn);
  236. // M1-03/B2 HAL: 向 HAL 申请该舱前台借用——HAL 暂停 control 对本舱采集(T1.3)并让采集端让出串口/相机,
  237. // 调试页随后复用借用到的同一物理句柄(lease.Serial/lease.Camera),不再 new 第二个 ComBin/Camera 开同口/同相机。
  238. try
  239. {
  240. var gate = HardwareAccessLayer.Instance.GetHouseGate(currentHouse.houseSn);
  241. _halLease = gate.Acquire(HardwareUser.OperateDebug);
  242. if (_halLease == null)
  243. {
  244. AddMessageInfo($"[{currentHouse.houseSn}]该舱正被占用(采集/对焦),借用超时,稍后重试");
  245. return;
  246. }
  247. }
  248. catch (Exception le)
  249. {
  250. AddMessageInfo($"[{currentHouse.houseSn}]HAL 借用异常:{le.Message}");
  251. return;
  252. }
  253. if (Serial == null)
  254. {
  255. AddMessageInfo($"[{currentHouse.houseSn}]借用到的串口句柄为空(HAL 未 ScanDevices 到本舱?),无法进入调试");
  256. return;
  257. }
  258. if (!Serial.IsOpen)
  259. {
  260. // 物理口由采集端持有并保持打开;T1.3 暂停只停发不关口。此处兜底再开一次(幂等)。
  261. if (!Serial.Open())
  262. {
  263. AddMessageInfo($"[{currentHouse.houseSn}][{currentHouse.housePort}]借用串口未打开且兜底打开失败");
  264. return;
  265. }
  266. }
  267. AddMessageInfo($"[{currentHouse.houseSn}][{currentHouse.housePort}]调试已复用采集端串口句柄(同一物理口)");
  268. // 相机:复用借用到的同一相机句柄。采集端通常已 Init+SetOpMode;仅在未 Init 时兜底 Init,
  269. // 然后统一设单帧采集模式(mode=0)供调试抓图,避免重复 Init 扰动采集端相机。
  270. if (Cam == null)
  271. {
  272. AddMessageInfo($"[{currentHouse.houseSn}]本舱无相机句柄(buffer/无相机舱?),跳过相机初始化");
  273. }
  274. else
  275. {
  276. if (!Cam.IsInit)
  277. {
  278. int cameraInit = Cam.Init();
  279. AddMessageInfo($"[CCD模块初始化]CCDID={CurrentCCDId},SN={currentHouse.ccdSn} 初始化结果:{cameraInit}[0=成功]");
  280. if (cameraInit != 0) return;
  281. }
  282. int cameraSetMode = Cam.SetOpMode();
  283. AddMessageInfo($"[CCD模块初始化]开启图像捕捉结果:{cameraSetMode}[0=成功]");
  284. if (cameraSetMode != 0) return;
  285. }
  286. var currentHorSetting = houseWellSettingList.FirstOrDefault(x => x.houseSn == currentHouse.houseSn && x.wellSn == 1);
  287. if (currentHorSetting == null)
  288. {
  289. AddMessageInfo($"[{currentHouse.houseSn}][{currentHouse.housePort}][未获取到1号well的水平电机位置]");
  290. return;
  291. }
  292. //OpenVideoEvent?.Invoke();
  293. var verNewValue = currentHorSetting.eepromClearPosition;
  294. var cc = ccdPhoto.FirstOrDefault(x => x.houseSn == currentHouse.houseSn && x.wellSn == 1);
  295. if (cc != null)
  296. {
  297. verNewValue = cc.clearestPosition;
  298. }
  299. // Task3.4b:进入调试的握手/电机归位/读数序列同走 control(operate Serial 空壳)。
  300. await RunDebugCommandAsync("进入调试-握手", "ShakeHands", null, new { houseSn = currentHouse.houseSn });
  301. await OpenLed();
  302. await RunDebugCommandAsync("进入调试-水平复位", "HorizontalReset", new { motorDelay = tLSetting.motorDelay }, new { houseSn = currentHouse.houseSn });
  303. CurrentHor = 0;
  304. CurrentWell = 0;
  305. await RunDebugCommandAsync("进入调试-水平到位", "HorizontalMoveTo",
  306. new { pos = currentHorSetting.horizontalMotorPosition, motorDelay = tLSetting.motorDelay }, new { houseSn = currentHouse.houseSn });
  307. CurrentHor = currentHorSetting.horizontalMotorPosition;
  308. CurrentWell = 1;
  309. await RunDebugCommandAsync("进入调试-垂直复位", "VerticalReset", new { motorDelay = tLSetting.motorDelay }, new { houseSn = currentHouse.houseSn });
  310. CurrentVer = 0;
  311. CurrentFocal = 0;
  312. await RunDebugCommandAsync("进入调试-垂直到位", "VerticalMoveTo",
  313. new { pos = verNewValue, motorDelay = tLSetting.motorDelay }, new { houseSn = currentHouse.houseSn });
  314. CurrentVer = verNewValue;
  315. CurrentFocal = 1;
  316. await RedTem();
  317. await RedPre();
  318. await RedDoor();
  319. await RedVentTime();
  320. return;
  321. }
  322. catch (Exception ex)
  323. {
  324. AppData.Instance.LogHelper.ExceptionLog(ex, "调试模式初始化", LogEnum.RunException);
  325. AddMessageInfo($"初始化异常:{ex.Message}");
  326. return;
  327. }
  328. });
  329. }
  330. public bool ComHouseUnit()
  331. {
  332. try
  333. {
  334. // D2-02-T3.4:先停标定轮询、归还 control 协作会话(停心跳),再归还本地 HAL 借用。
  335. StopCalibPolling();
  336. ReleaseDebugSession();
  337. // M1-B2:物理串口/相机由采集端(control)持有,调试只归还借用,绝不 ClosePort/UnInit 关物理口——
  338. // 否则会把采集端的口/相机一并关掉。归还后 HAL 触发 ResumeCapture 恢复本舱采集(T1.3)。
  339. if (_halLease != null)
  340. {
  341. try { _halLease.Dispose(); } catch { }
  342. _halLease = null;
  343. AddMessageInfo($"[{CurrentHouseId}]已归还借用,恢复后台采集");
  344. }
  345. return true;
  346. }
  347. catch (Exception ex)
  348. {
  349. AppData.Instance.LogHelper.ExceptionLog(ex, "调试模式卸载", LogEnum.RunException);
  350. AddMessageInfo($"卸载异常:{ex.Message}");
  351. return false;
  352. }
  353. }
  354. #region D2-02-T3.4 调试会话协作(借硬件拿 sessionId / 归还)
  355. /// <summary>
  356. /// 向 control 借该舱调试会话:POST /debug/acquire {houseSn} → 拿 sessionId 存 CurrentSessionId,
  357. /// 并构造 16 孔标定协作客户端 CalibrationClient(复用同一 sessionId)。
  358. /// control 借用成功会起心跳;会话失效(SESSION_EXPIRED)回调提示工程师重进调试。
  359. /// 借不到(BUSY/会话异常)只提示不抛——预览/标定将因 CurrentSessionId 为空而拒绝执行。
  360. /// </summary>
  361. private async Task AcquireDebugSessionAsync(int houseSn)
  362. {
  363. try
  364. {
  365. // 关旧会话(重复初始化时)。
  366. ReleaseDebugSession();
  367. var client = new DebugSessionClient(ControlClient.BaseUrl);
  368. client.OnSessionExpired = () =>
  369. {
  370. CurrentSessionId = null;
  371. AddMessageInfo("⚠ 调试会话已失效(control 端超时回收),请退出后重新进入调试");
  372. };
  373. var r = await client.AcquireAsync(houseSn);
  374. if (!r.Ok || string.IsNullOrEmpty(r.SessionId))
  375. {
  376. try { client.Dispose(); } catch { }
  377. AddMessageInfo($"[{houseSn}]借调试会话失败:{r.Code}/{r.Error}(预览与标定不可用,请确认 control 已托管该舱)");
  378. return;
  379. }
  380. _sessionClient = client;
  381. CurrentSessionId = r.SessionId;
  382. // 标定协作客户端复用同一 baseUrl + sessionId。
  383. _calibClient = new CalibrationClient(ControlClient.BaseUrl, r.SessionId);
  384. string cultMsg = r.Cultivating ? $"(注意:该舱培养中,胚胎 {r.EmbryoCount} 枚)" : "";
  385. AddMessageInfo($"[{houseSn}]调试会话已建立 sessionId={r.SessionId}{cultMsg}");
  386. }
  387. catch (Exception ex)
  388. {
  389. ExLog(ex, "AcquireDebugSessionAsync");
  390. AddMessageInfo($"[{houseSn}]借调试会话异常:{ex.Message}");
  391. }
  392. }
  393. /// <summary>归还调试会话(停心跳、通知 control)并释放协作客户端。幂等。
  394. /// release 的 HTTP POST 放后台跑(避免 control 失联时 HttpClient 默认 100s 超时卡死 UI 线程);
  395. /// DebugSessionClient.ReleaseAsync 在 await POST 前已同步置闸+停心跳,故心跳即时停止、不必等 POST。</summary>
  396. private void ReleaseDebugSession()
  397. {
  398. var calib = _calibClient; _calibClient = null;
  399. if (calib != null) { try { calib.Dispose(); } catch { } }
  400. var sc = _sessionClient; _sessionClient = null;
  401. if (sc != null)
  402. {
  403. // 后台 best-effort 归还+释放;失败也无妨(control 端 TTL 看门狗会超时回收会话)。
  404. Task.Run(async () =>
  405. {
  406. try { await sc.ReleaseAsync(); } catch { }
  407. try { sc.Dispose(); } catch { }
  408. });
  409. }
  410. CurrentSessionId = null;
  411. }
  412. #endregion
  413. // ── 自动对焦重构 D2-02-T3.4b:调试页手动命令统一走 control 的 /debug/command ──
  414. // operate 进程内 HAL 是空壳(从不 ScanDevices)、Serial/Cam 在真机上取不到真硬件;
  415. // control 独立进程持真硬件,故手动电机/光源/阀/EEPROM/曝光全经 _sessionClient.CommandAsync 下发。
  416. // 埋点不丢:沿用 OperationScope(同 M8-G3-1),据 CommandAsync 返回 Ok 记成功/失败。
  417. /// <summary>
  418. /// 统一执行一个调试手动命令:经 control HTTP /debug/command 下发 + 操作日志埋点 + 失败/会话失效提示。
  419. /// 返回 control 的 AcquireResult(读命令的值从 r.Result 取);会话未建立或失败返回 null/!Ok。
  420. /// </summary>
  421. private async Task<AcquireResult> RunDebugCommandAsync(string operation, string op, object args, object input)
  422. {
  423. if (_sessionClient == null || string.IsNullOrEmpty(CurrentSessionId))
  424. {
  425. AddMessageInfo($"[{operation}]未持调试会话,请重新进入调试页");
  426. return null;
  427. }
  428. using var _op = Aivfo.OperationLog.OperationLogger.Begin("对焦调试", operation, houseSn: CurrentHouseId);
  429. try { _op.Input(input); } catch { }
  430. AcquireResult r;
  431. try
  432. {
  433. r = await _sessionClient.CommandAsync(op, args);
  434. }
  435. catch (Exception ex)
  436. {
  437. _op.Fail(ex.GetType().Name + ": " + ex.Message);
  438. AddMessageInfo($"[{operation}]下发异常:{ex.Message}");
  439. return null;
  440. }
  441. if (r == null) { _op.Fail("空响应"); AddMessageInfo($"[{operation}]无响应"); return null; }
  442. if (r.Ok) { _op.Success(r.Result); }
  443. else
  444. {
  445. _op.Fail(r.Code + ": " + r.Error);
  446. if (r.Code == "SESSION_EXPIRED")
  447. AddMessageInfo($"[{operation}]调试会话已失效,请重新进入调试页");
  448. else
  449. AddMessageInfo($"[{operation}]失败:{r.Error}");
  450. }
  451. return r;
  452. }
  453. /// <summary>
  454. /// 读温度
  455. /// </summary>
  456. public async Task RedTem()
  457. {
  458. var r = await RunDebugCommandAsync("读温度", "ReadTemp", null, new { houseSn = CurrentHouseId });
  459. if (r != null && r.Ok && r.Result != null && decimal.TryParse(r.Result.ToString(), out var t)) Temperature = t;
  460. }
  461. /// <summary>
  462. /// 读压力
  463. /// </summary>
  464. public async Task RedPre()
  465. {
  466. var r = await RunDebugCommandAsync("读压力", "ReadPressure", null, new { houseSn = CurrentHouseId });
  467. if (r != null && r.Ok && r.Result != null && decimal.TryParse(r.Result.ToString(), out var p)) Pressure = p;
  468. }
  469. /// <summary>
  470. /// 读舱门
  471. /// </summary>
  472. public async Task RedDoor()
  473. {
  474. var r = await RunDebugCommandAsync("读舱门", "ReadDoor", null, new { houseSn = CurrentHouseId });
  475. if (r == null || !r.Ok) return;
  476. string DoorStateString = r.Result?.ToString();
  477. if(DoorStateString == "关闭")
  478. {
  479. DoorState = KeyToStringConvert.GetLanguageStringByKey("C0305");
  480. }
  481. if (DoorStateString == "打开")
  482. {
  483. DoorState = KeyToStringConvert.GetLanguageStringByKey("C0306");
  484. }
  485. }
  486. /// <summary>
  487. /// 打开Led灯
  488. /// </summary>
  489. public async Task OpenLed()
  490. {
  491. // M8-G3-1:LED 开关为串口设备命令入口,补操作日志埋点(module=对焦调试)。
  492. await RunDebugCommandAsync("打开LED灯", "OpenLed", null, new { houseSn = CurrentHouseId });
  493. LedState = KeyToStringConvert.GetLanguageStringByKey("C0306");
  494. //LedState = "开启";
  495. }
  496. /// <summary>
  497. /// 关闭Led灯
  498. /// </summary>
  499. public async Task CloseLed()
  500. {
  501. // M8-G3-1:LED 开关为串口设备命令入口,补操作日志埋点(module=对焦调试)。
  502. await RunDebugCommandAsync("关闭LED灯", "CloseLed", null, new { houseSn = CurrentHouseId });
  503. //LedState = "关闭";
  504. LedState = KeyToStringConvert.GetLanguageStringByKey("C0305");
  505. }
  506. /// <summary>
  507. /// 打开进气阀
  508. /// </summary>
  509. public async Task OpenIntake()
  510. {
  511. // M8-G3-1:进气阀开关为串口设备命令入口,补操作日志埋点(module=对焦调试)。
  512. await RunDebugCommandAsync("打开进气阀", "OpenIntake", null, new { houseSn = CurrentHouseId });
  513. }
  514. /// <summary>
  515. /// 关闭进气阀
  516. /// </summary>
  517. public async Task CloseIntake()
  518. {
  519. // M8-G3-1:进气阀开关为串口设备命令入口,补操作日志埋点(module=对焦调试)。
  520. await RunDebugCommandAsync("关闭进气阀", "CloseIntake", null, new { houseSn = CurrentHouseId });
  521. }
  522. /// <summary>
  523. /// 打开排气阀
  524. /// </summary>
  525. public async Task OpenExhaust()
  526. {
  527. // M8-G3-1:排气阀开关为串口设备命令入口,补操作日志埋点(module=对焦调试)。
  528. await RunDebugCommandAsync("打开排气阀", "OpenExhaust", null, new { houseSn = CurrentHouseId });
  529. }
  530. /// <summary>
  531. /// 关闭排气阀
  532. /// </summary>
  533. public async Task CloseExhaust()
  534. {
  535. // M8-G3-1:排气阀开关为串口设备命令入口,补操作日志埋点(module=对焦调试)。
  536. await RunDebugCommandAsync("关闭排气阀", "CloseExhaust", null, new { houseSn = CurrentHouseId });
  537. }
  538. /// <summary>
  539. /// 舱室补气
  540. /// </summary>
  541. public async Task HouseAeration()
  542. {
  543. // M8-G3-1:舱室补气为串口设备命令入口,补操作日志埋点(module=对焦调试)。
  544. await RunDebugCommandAsync("舱室补气", "HouseAeration", null, new { houseSn = CurrentHouseId });
  545. }
  546. /// <summary>
  547. /// 舱室排气
  548. /// </summary>
  549. public async Task HouseVent()
  550. {
  551. // M8-G3-1:舱室排气为串口设备命令入口,补操作日志埋点(module=对焦调试)。
  552. await RunDebugCommandAsync("舱室排气", "HouseVent", null, new { houseSn = CurrentHouseId });
  553. }
  554. /// <summary>
  555. /// 写舱室进气阀时间
  556. /// </summary>
  557. /// <param name="newValue"></param>
  558. public async Task WriteOpenIntakeTime(int newValue)
  559. {
  560. // M8-G3-1:写舱室进气阀时间为写 EEPROM 设备命令入口,补操作日志埋点(module=对焦调试)。
  561. await RunDebugCommandAsync("写舱室进气阀时间", "WriteOpenIntakeTime", new { value = newValue },
  562. new { houseSn = CurrentHouseId, newValue });
  563. }
  564. /// <summary>
  565. /// 写舱室排气阀时间
  566. /// </summary>
  567. /// <param name="newValue"></param>
  568. public async Task WriteOpenVentTime(int newValue)
  569. {
  570. // M8-G3-1:写舱室排气阀时间为写 EEPROM 设备命令入口,补操作日志埋点(module=对焦调试)。
  571. var r = await RunDebugCommandAsync("写舱室排气阀时间", "WriteOpenVentTime", new { value = newValue },
  572. new { houseSn = CurrentHouseId, newValue });
  573. if (r == null || !r.Ok)
  574. {
  575. AddMessageInfo($"[排气阀时间]下发失败,仅本地暂存{newValue}");
  576. }
  577. HouseVentTimeE = newValue;
  578. }
  579. /// <summary>
  580. /// 读舱室排气阀打开时间
  581. /// </summary>
  582. public async Task RedVentTime()
  583. {
  584. var r = await RunDebugCommandAsync("读排气阀时间", "ReadVentTime", null, new { houseSn = CurrentHouseId });
  585. if (r != null && r.Ok && r.Result != null && int.TryParse(r.Result.ToString(), out var v) && v >= 0)
  586. HouseVentTimeE = v;
  587. }
  588. /// <summary>
  589. /// 写垂直电机间隔脉冲
  590. /// </summary>
  591. /// <param name="newValue"></param>
  592. public async Task WriteOVerSpace(int newValue)
  593. {
  594. // M8-G3-1:写垂直电机间隔脉冲为写 EEPROM 设备命令入口,补操作日志埋点(module=对焦调试)。
  595. await RunDebugCommandAsync("写垂直电机间隔脉冲", "WriteScanStep", new { value = newValue },
  596. new { houseSn = CurrentHouseId, newValue });
  597. }
  598. /// <summary>
  599. /// 保存水平电机位置
  600. /// </summary>
  601. /// <param name="newValue"></param>
  602. public async Task SaveWellHor()
  603. {
  604. // M8-P3b:手调保存水平电机位置(关键命令入口,module=对焦调试)。
  605. await RunDebugCommandAsync("手调保存水平电机位置", "WriteWellHorizontalPos",
  606. new { well = CurrentWell, hor = CurrentHor },
  607. new { houseSn = CurrentHouseId, well = CurrentWell, hor = CurrentHor });
  608. }
  609. #region 电机运动
  610. /// <summary>
  611. /// 水平电机复位
  612. /// </summary>
  613. public async Task HorizontalMotorReset()
  614. {
  615. // M8-P3b:电机控制命令埋点(module=对焦调试)。
  616. await RunDebugCommandAsync("水平电机复位", "HorizontalReset", new { motorDelay = tLSetting.motorDelay },
  617. new { houseSn = CurrentHouseId });
  618. CurrentHor = 0;
  619. CurrentWell = 0;
  620. }
  621. /// <summary>
  622. /// 水平电机正向
  623. /// </summary>
  624. public async Task HorizontalMotorForward(int value)
  625. {
  626. // M8-G3-1:电机控制命令入口,补操作日志埋点(module=对焦调试)。
  627. await RunDebugCommandAsync("水平电机正向", "HorizontalForward", new { value, motorDelay = tLSetting.motorDelay },
  628. new { houseSn = CurrentHouseId, value });
  629. CurrentHor += value;
  630. }
  631. /// <summary>
  632. /// 水平电机反向
  633. /// </summary>
  634. public async Task HorizontalMotorBackward(int value)
  635. {
  636. // M8-G3-1:电机控制命令入口,补操作日志埋点(module=对焦调试)。
  637. await RunDebugCommandAsync("水平电机反向", "HorizontalBackward", new { value, motorDelay = tLSetting.motorDelay },
  638. new { houseSn = CurrentHouseId, value });
  639. CurrentHor -= value;
  640. }
  641. /// <summary>
  642. /// 水平电机到目标well
  643. /// </summary>
  644. /// <param name="newWell"></param>
  645. public async Task HorizontalMotorToWell(int newWell)
  646. {
  647. var currentHorSetting = houseWellSettingList.FirstOrDefault(x => x.houseSn == CurrentHouseId && x.wellSn == newWell);
  648. if (currentHorSetting == null)
  649. {
  650. AddMessageInfo($"[未获取到{newWell}号well的水平电机位置]");
  651. return;
  652. }
  653. // M8-G3-1:电机控制命令入口,补操作日志埋点(module=对焦调试)。
  654. await RunDebugCommandAsync("水平电机到well", "HorizontalMoveTo",
  655. new { pos = currentHorSetting.horizontalMotorPosition, motorDelay = tLSetting.motorDelay },
  656. new { houseSn = CurrentHouseId, well = newWell, hor = currentHorSetting.horizontalMotorPosition });
  657. CurrentHor = currentHorSetting.horizontalMotorPosition;
  658. CurrentWell = newWell;
  659. }
  660. /// <summary>
  661. /// 垂直电机复位
  662. /// </summary>
  663. public async Task VerticalMotorReset()
  664. {
  665. // M8-P3b:电机控制命令埋点(module=对焦调试)。
  666. await RunDebugCommandAsync("垂直电机复位", "VerticalReset", new { motorDelay = tLSetting.motorDelay },
  667. new { houseSn = CurrentHouseId });
  668. CurrentVer = 0;
  669. }
  670. /// <summary>
  671. /// 垂直电机正向运动
  672. /// </summary>
  673. public async Task VerticalMotorForward(int newValue)
  674. {
  675. // M8-G3-1:电机控制命令入口,补操作日志埋点(module=对焦调试)。
  676. await RunDebugCommandAsync("垂直电机正向", "VerticalForward", new { value = newValue, motorDelay = tLSetting.motorDelay },
  677. new { houseSn = CurrentHouseId, newValue });
  678. CurrentVer += newValue;
  679. }
  680. /// <summary>
  681. /// 垂直电机反向运动
  682. /// </summary>
  683. public async Task VerticalMotorBackward(int newValue)
  684. {
  685. // M8-G3-1:电机控制命令入口,补操作日志埋点(module=对焦调试)。
  686. await RunDebugCommandAsync("垂直电机反向", "VerticalBackward", new { value = newValue, motorDelay = tLSetting.motorDelay },
  687. new { houseSn = CurrentHouseId, newValue });
  688. CurrentVer -= newValue;
  689. }
  690. /// <summary>
  691. /// 垂直电机绝对运动
  692. /// </summary>
  693. public async Task VerticalMotorAbsolute(int newValue)
  694. {
  695. // M8-G3-1:电机控制命令入口,补操作日志埋点(module=对焦调试)。
  696. await RunDebugCommandAsync("垂直电机绝对运动", "VerticalMoveTo", new { pos = newValue, motorDelay = tLSetting.motorDelay },
  697. new { houseSn = CurrentHouseId, newValue });
  698. CurrentVer = newValue;
  699. }
  700. /// <summary>
  701. /// 一键电机准备
  702. /// </summary>
  703. public async Task MototReady()
  704. {
  705. var currentHorSetting = houseWellSettingList.FirstOrDefault(x => x.houseSn == CurrentHouseId && x.wellSn == 1);
  706. if (currentHorSetting == null)
  707. {
  708. AddMessageInfo($"[未获取到1号well的水平电机位置]");
  709. return;
  710. }
  711. var verNewValue = currentHorSetting.eepromClearPosition;
  712. var cc = ccdPhoto.FirstOrDefault(x => x.houseSn == CurrentHouseId && x.wellSn == 1);
  713. if (cc != null)
  714. {
  715. verNewValue = cc.clearestPosition;
  716. }
  717. // M8-G3-1:一键电机准备为多步串口动作流程,各子动作经 control 顺序下发(module=对焦调试)。
  718. using var _op = Aivfo.OperationLog.OperationLogger.Begin("对焦调试", "一键电机准备",
  719. houseSn: CurrentHouseId);
  720. try { _op.Input(new { houseSn = CurrentHouseId, targetHor = currentHorSetting.horizontalMotorPosition, targetVer = verNewValue }); } catch { }
  721. await RunDebugCommandAsync("一键电机准备-水平复位", "HorizontalReset", new { motorDelay = tLSetting.motorDelay }, new { houseSn = CurrentHouseId });
  722. CurrentHor = 0;
  723. CurrentWell = 0;
  724. await RunDebugCommandAsync("一键电机准备-水平到位", "HorizontalMoveTo",
  725. new { pos = currentHorSetting.horizontalMotorPosition, motorDelay = tLSetting.motorDelay }, new { houseSn = CurrentHouseId });
  726. CurrentHor = currentHorSetting.horizontalMotorPosition;
  727. CurrentWell = 1;
  728. await RunDebugCommandAsync("一键电机准备-垂直复位", "VerticalReset", new { motorDelay = tLSetting.motorDelay }, new { houseSn = CurrentHouseId });
  729. CurrentVer = 0;
  730. CurrentFocal = 0;
  731. await RunDebugCommandAsync("一键电机准备-垂直到位", "VerticalMoveTo",
  732. new { pos = verNewValue, motorDelay = tLSetting.motorDelay }, new { houseSn = CurrentHouseId });
  733. CurrentVer = verNewValue;
  734. CurrentFocal = 1;
  735. }
  736. /// <summary>
  737. /// 单张抓拍
  738. /// </summary>
  739. public bool SavePic(string fullName)
  740. {
  741. try
  742. {
  743. if (GetPicData() == 0)
  744. {
  745. if (Cam == null) return false;
  746. // M8-G3-1:单张抓拍落盘为相机采图+保存命令入口,补操作日志埋点(module=对焦调试)。
  747. // 批量抓图(水平抓图/清晰图层抓图)经 Begin scope 调用时,本埋点自动成为其子埋点(父子链)。
  748. return Aivfo.OperationLog.OperationLogger.Run("对焦调试", "单张抓拍",
  749. () => Cam.SavePic(fullName, CurrentHouse.ccdWidth, CurrentHouse.ccdHeight),
  750. input: new { houseSn = CurrentHouseId, well = CurrentWell, focal = CurrentFocal, hor = CurrentHor, ver = CurrentVer });
  751. }
  752. return false;
  753. }
  754. catch (Exception ex)
  755. {
  756. AppData.Instance.LogHelper.ExceptionLog(ex, $"单张抓拍", LogEnum.RunException);
  757. AddMessageInfo($"单张抓拍异常:{ex.Message}");
  758. return false;
  759. }
  760. }
  761. /// <summary>
  762. /// 水平抓图
  763. /// </summary>
  764. public void ShuiPingZhuaPai()
  765. {
  766. try
  767. {
  768. IsStop = false;
  769. if (Serial == null) return;
  770. if (IsStop) return;
  771. // M8-G3-1:水平抓图为多步循环采图流程,用 Begin scope 串联各 well 抓拍子埋点(module=对焦调试)。
  772. using var _op = Aivfo.OperationLog.OperationLogger.Begin("对焦调试", "水平抓图",
  773. houseSn: CurrentHouseId);
  774. try { _op.Input(new { houseSn = CurrentHouseId }); } catch { }
  775. Serial.HorizontalResetWait(tLSetting.motorDelay);
  776. CurrentHor = 0;
  777. CurrentWell = 0;
  778. HouseWellSetting currentHorSetting = null;
  779. string dtnow = string.Format("{0:yyyy-MM-dd-HH-mm-ss}", DateTime.Now); //24小时制
  780. string path = AppData.Instance.LogHelper.GetDeBugShuiPingDirectory(CurrentHouse.houseSn, dtnow);
  781. if (!Directory.Exists(path))
  782. {
  783. Directory.CreateDirectory(path);
  784. }
  785. for (int i = 1; i <= 16; i++)
  786. {
  787. currentHorSetting = houseWellSettingList.FirstOrDefault(x => x.houseSn == CurrentHouseId && x.wellSn == i);
  788. if (currentHorSetting == null)
  789. {
  790. AddMessageInfo($"[未获取到1号well的水平电机位置]");
  791. continue;
  792. }
  793. if (IsStop) return;
  794. if (Serial == null) return;
  795. Serial.HorizontalMoveToWait(currentHorSetting.horizontalMotorPosition, tLSetting.motorDelay);
  796. if (IsStop) return;
  797. CurrentHor = currentHorSetting.horizontalMotorPosition;
  798. CurrentWell = i;
  799. string filename = $"{dtnow}-house{CurrentHouse.houseSn}-well{CurrentWell}-{CurrentFocal}-{CurrentHor}-{CurrentVer}.jpg";
  800. string fullName = $"{path}{filename}";
  801. if (Cam == null) return;
  802. if (SavePic(fullName))
  803. {
  804. AddPic(fullName);
  805. }
  806. }
  807. }
  808. catch (Exception ex)
  809. {
  810. AppData.Instance.LogHelper.ExceptionLog(ex, $"水平抓拍", LogEnum.RunException);
  811. AddMessageInfo($"水平抓拍异常:{ex.Message}");
  812. }
  813. }
  814. /// <summary>
  815. /// 清晰图层抓图
  816. /// </summary>
  817. public async Task AutoFocusPic(int focalCount, int xun)
  818. {
  819. await Task.Run(async () =>
  820. {
  821. try
  822. {
  823. IsStop = false;
  824. var startAutoFocus = -1;
  825. var cc = ccdPhoto.FirstOrDefault(x => x.houseSn == CurrentHouseId && x.wellSn == CurrentWell);
  826. if (cc == null)
  827. {
  828. AddMessageInfo($"[未获取到{CurrentWell}号well的自动对焦起点]");
  829. return;
  830. }
  831. // M8-G3-1:清晰图层抓图为多步循环采图流程,用 Begin scope 串联各层抓拍子埋点(module=对焦调试)。
  832. using var _op = Aivfo.OperationLog.OperationLogger.Begin("对焦调试", "清晰图层抓图",
  833. houseSn: CurrentHouseId);
  834. try { _op.Input(new { houseSn = CurrentHouseId, well = CurrentWell, focalCount, xun }); } catch { }
  835. startAutoFocus = cc.autoFocusPosition;
  836. string dtnow = string.Format("{0:yyyy-MM-dd-HH-mm-ss}", DateTime.Now); //24小时制
  837. string path = null;
  838. string fullName = null;
  839. for (int k = 0; k < xun; k++)
  840. {
  841. if (IsStop) return;
  842. if (Serial == null) return;
  843. Serial.VerticalResetWait(tLSetting.motorDelay);
  844. CurrentVer = 0;
  845. CurrentFocal = 0;
  846. var verSpacePulse = 128;
  847. if (CurrentHouse.verticalMotorSpacePulse.HasValue) verSpacePulse = CurrentHouse.verticalMotorSpacePulse.Value;
  848. path = $"{AppData.Instance.LogHelper.GetDeBugQingXiDirectory(CurrentHouse.houseSn, CurrentWell, dtnow)}{(k + 1)}_{CurrentHor}";
  849. if (!Directory.Exists(path)) Directory.CreateDirectory(path);
  850. for (int i = 0; i < focalCount; i++)
  851. {
  852. CurrentFocal = i + 1;
  853. var currentVerValue = startAutoFocus + (i * verSpacePulse);
  854. if (IsStop) return;
  855. if (Serial == null) return;
  856. if(currentVerValue > tLSetting.verticalMotorPulseMax)
  857. {
  858. AddMessageInfo($"清晰图层抓图超出垂直电机上限:{tLSetting.verticalMotorPulseMax}");
  859. return;
  860. }
  861. Serial.VerticalMoveToWait(currentVerValue, tLSetting.motorDelay);
  862. CurrentVer = currentVerValue;
  863. fullName = $"{path}\\{currentVerValue}.jpg";
  864. if (IsStop) return;
  865. if (Cam == null) return;
  866. if (SavePic(fullName)) AddPic(fullName);
  867. }
  868. }
  869. }
  870. catch (Exception ex)
  871. {
  872. AppData.Instance.LogHelper.ExceptionLog(ex, $"清晰图层抓图", LogEnum.RunException);
  873. AddMessageInfo($"清晰图层抓图异常:{ex.Message}");
  874. }
  875. });
  876. }
  877. /// <summary>
  878. /// 抓图
  879. /// </summary>
  880. public int GetPicData()
  881. {
  882. try
  883. {
  884. if (Cam == null) return -1;
  885. int GetRgbData = -1;
  886. bool isWuTu = false;
  887. if (isWuTu)
  888. {
  889. GetRgbData = Cam.GrabRaw();//获取字节流
  890. AddMessageInfo($"[抓拍结果:{GetRgbData}][注:0表示成功]");
  891. if (GetRgbData == 0)
  892. {
  893. GetRgbData = Cam.RawToRgb();
  894. AddMessageInfo($"[rawToRgb结果:{GetRgbData}][注:0表示成功]");
  895. }
  896. }
  897. else
  898. {
  899. GetRgbData = Cam.GrabRgb();//获取字节流
  900. AddMessageInfo($"[抓拍结果:{GetRgbData}][注:0表示成功]");
  901. }
  902. return GetRgbData;
  903. }
  904. catch (Exception ex)
  905. {
  906. AppData.Instance.LogHelper.ExceptionLog(ex, $"调试模式抓拍", LogEnum.RunException);
  907. AddMessageInfo($"相机抓拍异常:{ex.Message}");
  908. return -1;
  909. }
  910. }
  911. #endregion
  912. #region 相机操作
  913. /// <summary>
  914. /// 设置曝光值
  915. /// </summary>
  916. /// <param name="newExporuse"></param>
  917. public async Task SetExposure(int newExporuse)
  918. {
  919. // M8-G3-1:设置相机曝光为相机设备命令入口,补操作日志埋点(module=对焦调试)。
  920. // Task3.4b:operate 相机空壳,曝光改走 control 借用的真相机(control 端 Execute 新增 SetExposure op)。
  921. var r = await RunDebugCommandAsync("设置相机曝光值", "SetExposure", new { value = newExporuse },
  922. new { houseSn = CurrentHouseId, ccdId = CurrentCCDId, newExporuse });
  923. if (r != null && r.Ok) AddMessageInfo($"设置曝光结果:{r.Result}");
  924. }
  925. /// <summary>
  926. /// 打开实时预览(贴宿主窗口句柄)。M1-B2:走借用到的 lease.Camera(StartPreview),不再触碰具体 Camera。
  927. /// 返回 0 成功;相机句柄为空返回 -1。
  928. /// </summary>
  929. public int StartPreview(IntPtr hostControl, int left, int top, int width, int height)
  930. {
  931. if (Cam == null) return -1;
  932. return Cam.StartPreview(hostControl, left, top, width, height);
  933. }
  934. /// <summary>关闭实时预览。返回 0 成功;相机句柄为空返回 -1。</summary>
  935. public int StopPreview()
  936. {
  937. if (Cam == null) return -1;
  938. return Cam.StopPreview();
  939. }
  940. //public bool OpenVideo(IntPtr mControlPtr, int left, int top, int width, int height)
  941. //{
  942. // try
  943. // {
  944. // var a = camera.Usb2Start(mControlPtr, left, top, width, height);
  945. // AddMessageInfo($"图像打开结果[0表示成功]:{a}");
  946. // return a == 0;
  947. // }
  948. // catch (Exception ex)
  949. // {
  950. // ExLog(ex, "OpenVideo");
  951. // AddMessageInfo($"图像打开异常:{ex.Message}");
  952. // return false;
  953. // }
  954. //}
  955. //public bool CloseVideo()
  956. //{
  957. // try
  958. // {
  959. // var a = camera.Usb2Stop();
  960. // AddMessageInfo($"图像关闭结果[0表示成功]:{a}");
  961. // return a == 0;
  962. // }
  963. // catch (Exception ex)
  964. // {
  965. // ExLog(ex, "CloseVideo");
  966. // AddMessageInfo($"图像关闭异常:{ex.Message}");
  967. // return false;
  968. // }
  969. //}
  970. #endregion
  971. #region 参数保存
  972. /// <summary>
  973. /// 保存舱室参数
  974. /// </summary>
  975. /// <returns></returns>
  976. public bool SetHouseInfo()
  977. {
  978. try
  979. {
  980. if (CurrentHouse == null) return true;
  981. string body = JsonConvert.SerializeObject(new
  982. {
  983. tlSn = CurrentHouse.tlSn,
  984. houseSn = CurrentHouse.houseSn,
  985. ccdExposure = CurrentHouse.ccdExposure,
  986. inletValveOpeningTime = CurrentHouse.inletValveOpeningTime,
  987. verticalMotorSpacePulse = CurrentHouse.verticalMotorSpacePulse,
  988. });
  989. return AppData.Instance.HttpHelper.HouseDebuggingApi(body);
  990. }
  991. catch (Exception ex)
  992. {
  993. ExLog(ex, "SetHouseExposure");
  994. return false;
  995. }
  996. }
  997. /// <summary>
  998. /// 保存当前well位置
  999. /// </summary>
  1000. /// <returns></returns>
  1001. public bool SetWellMotorPosition()
  1002. {
  1003. try
  1004. {
  1005. if (CurrentHouse == null)
  1006. {
  1007. AddMessageInfo("获取舱室信息失败");
  1008. }
  1009. string body = JsonConvert.SerializeObject(new
  1010. {
  1011. horizontalMotorPosition = CurrentHor,
  1012. houseSn = CurrentHouse.houseSn,
  1013. tlSn = CurrentHouse.tlSn,
  1014. wellSn = CurrentWell,
  1015. });
  1016. return AppData.Instance.HttpHelper.WellUpdateApi(body);
  1017. }
  1018. catch (Exception ex)
  1019. {
  1020. ExLog(ex, "SetWellMotorPosition");
  1021. return false;
  1022. }
  1023. }
  1024. /// <summary>
  1025. /// 保存自动对焦起点
  1026. /// </summary>
  1027. /// <returns></returns>
  1028. public bool SetWellAutoFocus()
  1029. {
  1030. try
  1031. {
  1032. if (CurrentHouse == null)
  1033. {
  1034. AddMessageInfo("获取舱室信息失败");
  1035. }
  1036. string body = JsonConvert.SerializeObject(new
  1037. {
  1038. verticalMotorPosition = CurrentVer,
  1039. houseSn = CurrentHouse.houseSn,
  1040. tlSn = CurrentHouse.tlSn,
  1041. wellSn = CurrentWell,
  1042. });
  1043. return AppData.Instance.HttpHelper.WellUpdateApi(body);
  1044. }
  1045. catch (Exception ex)
  1046. {
  1047. ExLog(ex, "SetWellAutoFocus");
  1048. return false;
  1049. }
  1050. }
  1051. #endregion
  1052. private void ComBin_ExceptionLogEvent(Exception exception, string arg2, string arg3, LogEnum @enum)
  1053. {
  1054. AppData.Instance.LogHelper.ExceptionLog(exception, $"{arg2}{arg3}", @enum);
  1055. }
  1056. private void ComBin_ErrorLogEvent(string arg1, LogEnum @enum)
  1057. {
  1058. AppData.Instance.LogHelper.TLLog(arg1, @enum);
  1059. }
  1060. private void ComBin_CommandLogEvent(int arg1, DateTime time, string arg3, LogEnum @enum)
  1061. {
  1062. AppData.Instance.LogHelper.HouseLog(arg1, time, arg3, @enum);
  1063. }
  1064. public void AddMessageInfo(string mess)
  1065. {
  1066. MessageEvent?.Invoke(mess);
  1067. }
  1068. public void AddPic(string picFullName)
  1069. {
  1070. AddPicEvent?.Invoke(picFullName, CurrentWell, CurrentFocal);
  1071. }
  1072. #region 场景A 一键全自动标定(经 control 协作,D2-02-T3.4 重构)
  1073. /// <summary>
  1074. /// 一键全自动标定(D2-02-T3.4 重构为"经 control 协作")。
  1075. /// 旧实现:operate 本地 new CalibrationEngine 逐 well 跑 + CalibrationStore 写 JSON/scene0(已停用)。
  1076. /// 新实现:operate 仅发 /debug/calibrate/start(经 CalibrationClient,复用 acquire 的 sessionId) →
  1077. /// 起轮询 /debug/calibrate/progress(~800ms) 把每孔状态映射到 16 格 UI(合格绿/伪峰橙/失败红 + FocusZ/峰比/偏移)。
  1078. /// 标定由 control 协作端真正执行(持真硬件)、scene=0 基准由 control 端落库。
  1079. /// 前提:ComHouseInit 已成功 acquire(CurrentSessionId 非空、_calibClient 已构造)。
  1080. /// 中止:StopCalibrate → /debug/calibrate/stop + 停轮询。
  1081. ///
  1082. /// ⚠ 待验证(compile-pending,operate.exe 卡死未编译):start/progress/stop 协作往返、16 格映射、合格判定一致。
  1083. /// </summary>
  1084. /// <param name="wells">勾选的 well 列表(空/null 视为全 16 well)。</param>
  1085. public async Task OneClickCalibrate(IEnumerable<int> wells = null)
  1086. {
  1087. if (IsCalibrating)
  1088. {
  1089. AddMessageInfo("[一键标定]已在标定中,请勿重复触发");
  1090. return;
  1091. }
  1092. if (_calibClient == null || string.IsNullOrEmpty(CurrentSessionId))
  1093. {
  1094. AddMessageInfo("[一键标定]未建立调试会话(请先初始化舱室借硬件),无法发起协作标定");
  1095. return;
  1096. }
  1097. if (CurrentHouse == null)
  1098. {
  1099. AddMessageInfo("[一键标定]未获取到舱室信息");
  1100. return;
  1101. }
  1102. // 勾选 well:未传则默认 16 well;去重、按序、限定 1-16。
  1103. var wellList = (wells ?? Enumerable.Range(1, 16))
  1104. .Where(w => w >= 1 && w <= 16).Distinct().OrderBy(w => w).ToList();
  1105. if (wellList.Count == 0) wellList = Enumerable.Range(1, 16).ToList();
  1106. IsCalibrating = true;
  1107. IsStopCalibrate = false;
  1108. try
  1109. {
  1110. // M8-P3b:一键标定发起为关键命令入口,记一条操作日志(start 同步发起;异步轮询单独不再串 scope,
  1111. // 避免 using scope 在方法返回即 Dispose 后被后台轮询误用)。
  1112. using (var _opScope = Aivfo.OperationLog.OperationLogger.Begin("对焦调试", "一键标定发起(协作)", houseSn: CurrentHouseId))
  1113. {
  1114. try { _opScope.Input(new { houseSn = CurrentHouseId, wells = wellList.ToArray() }); } catch { }
  1115. ResetCalibResults(wellList);
  1116. // D2-02-T3.4:标定由 control 协作端执行(scene=0 落库由 control 端处理)。
  1117. // operate 仅发 start + 轮询进度刷新 16 格 UI,不再 operate 本地 new CalibrationEngine/CalibrationStore。
  1118. var r = await _calibClient.StartAsync(wellList);
  1119. if (!r.Ok)
  1120. {
  1121. IsCalibrating = false;
  1122. AddMessageInfo($"[一键标定]发起失败:{r.Code}/{r.Error}");
  1123. try { _opScope.Fail($"start 失败:{r.Code}/{r.Error}"); } catch { }
  1124. return;
  1125. }
  1126. try { _opScope.Output(new { started = true }).Success(); } catch { }
  1127. }
  1128. AddMessageInfo($"[一键标定]已发起(control 协作):舱{CurrentHouse.houseSn} 共 {wellList.Count} well,开始轮询进度...");
  1129. // 起轮询任务,把 control 端进度映射到 16 格 UI;IsRunning 转 false 即停。
  1130. StartCalibPolling();
  1131. }
  1132. catch (Exception ex)
  1133. {
  1134. IsCalibrating = false;
  1135. ExLog(ex, "OneClickCalibrate");
  1136. AddMessageInfo($"[一键标定]整体异常:{ex.Message}");
  1137. }
  1138. }
  1139. /// <summary>
  1140. /// D2-02-T3.4 单孔重标:经 control 协作端对该 well 重新标定一次,并起轮询刷新该格。
  1141. /// </summary>
  1142. public async Task RecalibrateWell(int wellSn)
  1143. {
  1144. if (_calibClient == null || string.IsNullOrEmpty(CurrentSessionId))
  1145. {
  1146. AddMessageInfo("[重标]未建立调试会话,无法重标");
  1147. return;
  1148. }
  1149. if (IsCalibrating)
  1150. {
  1151. AddMessageInfo("[重标]批量标定进行中,请先中止或等待结束");
  1152. return;
  1153. }
  1154. if (wellSn < 1 || wellSn > 16)
  1155. {
  1156. AddMessageInfo("[重标]well 只能为 1-16");
  1157. return;
  1158. }
  1159. try
  1160. {
  1161. IsCalibrating = true;
  1162. IsStopCalibrate = false;
  1163. UpdateCalibResult(wellSn, item => { item.State = WellCalibState.Running; item.Note = "重标中..."; });
  1164. var r = await _calibClient.RecalibrateAsync(wellSn);
  1165. if (!r.Ok)
  1166. {
  1167. IsCalibrating = false;
  1168. AddMessageInfo($"[重标]well{wellSn} 发起失败:{r.Code}/{r.Error}");
  1169. return;
  1170. }
  1171. AddMessageInfo($"[重标]well{wellSn} 已发起,轮询进度...");
  1172. StartCalibPolling();
  1173. }
  1174. catch (Exception ex)
  1175. {
  1176. IsCalibrating = false;
  1177. ExLog(ex, "RecalibrateWell");
  1178. AddMessageInfo($"[重标]well{wellSn} 异常:{ex.Message}");
  1179. }
  1180. }
  1181. /// <summary>工程师中止一键标定:通知 control 停标,停本地轮询。</summary>
  1182. public void StopCalibrate()
  1183. {
  1184. IsStopCalibrate = true;
  1185. AddMessageInfo("[一键标定]收到中止请求,通知 control 停止...");
  1186. var calib = _calibClient;
  1187. if (calib != null)
  1188. {
  1189. Task.Run(async () =>
  1190. {
  1191. try { await calib.StopAsync(); } catch (Exception ex) { ExLog(ex, "StopCalibrate.StopAsync"); }
  1192. });
  1193. }
  1194. // 轮询任务读到 IsRunning=false 后会自停;此处也主动停一次兜底。
  1195. StopCalibPolling();
  1196. }
  1197. /// <summary>
  1198. /// 起标定进度轮询(~800ms 一次):调 control /debug/calibrate/progress,
  1199. /// 把每孔 WellCalibProgressDto(State 数字枚举)映射到 16 格 WellCalibUiItem。
  1200. /// IsRunning 转 false(或会话失效返回 null)即停轮询并复位 IsCalibrating。
  1201. /// 同一时刻只跑一个轮询任务(先停旧的)。
  1202. /// </summary>
  1203. private void StartCalibPolling()
  1204. {
  1205. StopCalibPolling();
  1206. var cts = new System.Threading.CancellationTokenSource();
  1207. _calibPollCts = cts;
  1208. var token = cts.Token;
  1209. var calib = _calibClient;
  1210. Task.Run(async () =>
  1211. {
  1212. try
  1213. {
  1214. while (!token.IsCancellationRequested)
  1215. {
  1216. var dto = await calib.PollProgressAsync();
  1217. if (token.IsCancellationRequested) break;
  1218. if (dto == null)
  1219. {
  1220. // 会话失效/无进度:停轮询(会话失效另由 DebugSessionClient.OnSessionExpired 提示)。
  1221. AddMessageInfo("[一键标定]进度查询无结果(会话可能已失效),停止轮询");
  1222. break;
  1223. }
  1224. MapProgressToUi(dto);
  1225. if (!dto.IsRunning)
  1226. {
  1227. int okCount = CalibResults.Count(x => x.State == WellCalibState.Qualified);
  1228. AddMessageInfo($"[一键标定]结束:合格 {okCount}/{dto.Total}(scene=0 基准由 control 协作端落库)");
  1229. break;
  1230. }
  1231. await Task.Delay(800, token);
  1232. }
  1233. }
  1234. catch (TaskCanceledException) { /* 主动停 */ }
  1235. catch (Exception ex)
  1236. {
  1237. ExLog(ex, "CalibPolling");
  1238. AddMessageInfo($"[一键标定]轮询异常:{ex.Message}");
  1239. }
  1240. finally
  1241. {
  1242. IsCalibrating = false;
  1243. }
  1244. }, token);
  1245. }
  1246. /// <summary>停标定进度轮询(取消轮询任务)。幂等。</summary>
  1247. private void StopCalibPolling()
  1248. {
  1249. var cts = _calibPollCts;
  1250. _calibPollCts = null;
  1251. if (cts != null) { try { cts.Cancel(); } catch { } try { cts.Dispose(); } catch { } }
  1252. }
  1253. /// <summary>把 control 进度 DTO 的每孔状态映射到 16 格 UI(State 为数字枚举:0待标/1标定中/2合格/3伪峰/4失败)。</summary>
  1254. private void MapProgressToUi(CalibProgressDto dto)
  1255. {
  1256. if (dto?.Wells == null) return;
  1257. foreach (var w in dto.Wells)
  1258. {
  1259. var well = w; // 闭包捕获
  1260. UpdateCalibResult(well.WellSn, item =>
  1261. {
  1262. item.State = (WellCalibState)well.State; // 0..4 与 operate 端枚举顺序一致
  1263. item.FocusZ = well.FocusZ;
  1264. item.Exposure = well.Exposure;
  1265. item.PeakRatio = well.PeakRatio;
  1266. item.CenterOffsetPct = well.CenterOffsetPct;
  1267. item.CircleFound = well.CircleFound;
  1268. item.Note = string.IsNullOrEmpty(well.Note)
  1269. ? StateNote((WellCalibState)well.State, well.FocusZ, well.PeakRatio)
  1270. : well.Note;
  1271. });
  1272. }
  1273. }
  1274. private static string StateNote(WellCalibState st, int focusZ, double peakRatio) => st switch
  1275. {
  1276. WellCalibState.Pending => "待标定",
  1277. WellCalibState.Running => "标定中...",
  1278. WellCalibState.Qualified => $"合格 Z={focusZ} 峰比={peakRatio:F2}",
  1279. WellCalibState.FakePeak => $"伪峰 Z={focusZ} 峰比={peakRatio:F2}",
  1280. WellCalibState.Failed => "失败",
  1281. _ => ""
  1282. };
  1283. private void ResetCalibResults(List<int> wells)
  1284. {
  1285. void build()
  1286. {
  1287. CalibResults.Clear();
  1288. foreach (var w in wells)
  1289. CalibResults.Add(new WellCalibUiItem { Well = w, State = WellCalibState.Pending, Note = "待标定" });
  1290. }
  1291. // 集合改动需在 UI 线程(ObservableCollection 绑定)。
  1292. var disp = System.Windows.Application.Current?.Dispatcher;
  1293. if (disp != null && !disp.CheckAccess()) disp.Invoke(build); else build();
  1294. }
  1295. private void UpdateCalibResult(int well, Action<WellCalibUiItem> mutate)
  1296. {
  1297. void apply()
  1298. {
  1299. var item = CalibResults.FirstOrDefault(x => x.Well == well);
  1300. if (item == null)
  1301. {
  1302. item = new WellCalibUiItem { Well = well };
  1303. CalibResults.Add(item);
  1304. }
  1305. mutate(item);
  1306. }
  1307. var disp = System.Windows.Application.Current?.Dispatcher;
  1308. if (disp != null && !disp.CheckAccess()) disp.Invoke(apply); else apply();
  1309. }
  1310. #endregion
  1311. #region M2-07 对焦后手动微调拍摄层(层数/层间距/下移)持久化 well 级
  1312. /// <summary>
  1313. /// M2-07 手调"实际拍摄层数"(well 级覆盖)。空字符串=留空继承设备级(保存写 null)。
  1314. /// View TextBox 双向绑定;校验在保存/预览时做(层数≥1)。
  1315. /// </summary>
  1316. [ObservableProperty] private string manualLayerCount = "";
  1317. /// <summary>
  1318. /// M2-07 手调"实际拍摄层间距脉冲"(well 级覆盖)。空=继承设备级(写 null)。校验:>0。
  1319. /// </summary>
  1320. [ObservableProperty] private string manualLayerSpacing = "";
  1321. /// <summary>
  1322. /// M2-07 手调"对焦起点下移层数"(复用 move_down_layer)。空=继承设备级。
  1323. /// 校验:≥0 且 &lt;层数(下移层须落在拍摄范围内,§2.4 清晰层=第 down 层)。
  1324. /// </summary>
  1325. [ObservableProperty] private string manualMoveDown = "";
  1326. /// <summary>
  1327. /// M2-07 实时预览各层绝对 Z 位置(调 M2-02 ComputeLayerPositions 生成,关联 V-045)。
  1328. /// View 绑定此集合显示 N 层位置列表,让工程师看到手调效果。
  1329. /// </summary>
  1330. public ObservableCollection<LayerPreviewItem> LayerPreview { get; } = new ObservableCollection<LayerPreviewItem>();
  1331. /// <summary>
  1332. /// M2-07 预览/手调锚点 well(默认随水平电机当前 well / 一键标定取 CurrentWell)。
  1333. /// </summary>
  1334. [ObservableProperty] private int manualTuneWell = 1;
  1335. /// <summary>
  1336. /// 取该 well 当前生效的"实际拍摄层"配置(well 级覆盖优先,空则回退设备级),
  1337. /// 回填三个手调输入框 + 触发一次预览。供"载入当前值"按钮调用。
  1338. /// </summary>
  1339. public void LoadManualLayerSetting(int well)
  1340. {
  1341. ManualTuneWell = well;
  1342. var ws = houseWellSettingList.FirstOrDefault(x => x.houseSn == CurrentHouseId && x.wellSn == well);
  1343. // well 级覆盖非空显示 well 值,否则显示继承的设备级值作占位(§2.5 就近优先)。
  1344. int? wellCount = ws?.focusLayerCount;
  1345. int? wellSpacing = ws?.focusLayerSpacingPulse;
  1346. // 下移复用 moveDownLayer(well 级为非空 int 列;0 视为有效覆盖值)。
  1347. int? wellDown = ws != null ? (int?)ws.moveDownLayer : null;
  1348. ManualLayerCount = (wellCount ?? tLSetting?.focusLayerCount)?.ToString() ?? "";
  1349. ManualLayerSpacing = (wellSpacing ?? tLSetting?.focusLayerSpacingPulse)?.ToString() ?? "";
  1350. ManualMoveDown = (wellDown ?? tLSetting?.focusLayerDown)?.ToString() ?? "";
  1351. PreviewManualLayers();
  1352. }
  1353. /// <summary>
  1354. /// 取该 well 最近标定的 FocusZ 作预览锚点(M2-05 一键标定结果 CalibResults 优先;
  1355. /// 回退 ccdPhoto 的 clearestPosition 即 scene0/1 库下发的清晰位置)。
  1356. /// 返回 null 表示无标定可用(须提示先标定)。
  1357. /// </summary>
  1358. private int? GetPreviewFocusZ(int well)
  1359. {
  1360. var calib = CalibResults.FirstOrDefault(x => x.Well == well
  1361. && (x.State == WellCalibState.Qualified || x.State == WellCalibState.FakePeak));
  1362. if (calib != null && calib.FocusZ > 0) return calib.FocusZ;
  1363. // 回退:调试页加载的清晰位置(scene0/1 库值 clearestPosition)。
  1364. var cc = ccdPhoto.FirstOrDefault(x => x.houseSn == CurrentHouseId && x.wellSn == well);
  1365. if (cc != null && cc.clearestPosition > 0) return cc.clearestPosition;
  1366. return null;
  1367. }
  1368. /// <summary>
  1369. /// 解析三个手调输入框(空=继承设备级取回退值),返回有效 (count,spacing,down) 或 null(非法/缺失)。
  1370. /// validateMsg 携带校验失败原因。
  1371. /// </summary>
  1372. private (int count, int spacing, int down)? ResolveEffectiveTune(out string validateMsg)
  1373. {
  1374. validateMsg = null;
  1375. // 解析层数:空→设备级回退;非空→必须 int。
  1376. int? count;
  1377. if (string.IsNullOrWhiteSpace(ManualLayerCount)) count = tLSetting?.focusLayerCount;
  1378. else if (int.TryParse(ManualLayerCount.Trim(), out int c)) count = c;
  1379. else { validateMsg = "层数只能输入整数"; return null; }
  1380. int? spacing;
  1381. if (string.IsNullOrWhiteSpace(ManualLayerSpacing)) spacing = tLSetting?.focusLayerSpacingPulse;
  1382. else if (int.TryParse(ManualLayerSpacing.Trim(), out int s)) spacing = s;
  1383. else { validateMsg = "层间距只能输入整数"; return null; }
  1384. int? down;
  1385. if (string.IsNullOrWhiteSpace(ManualMoveDown)) down = tLSetting?.focusLayerDown;
  1386. else if (int.TryParse(ManualMoveDown.Trim(), out int d)) down = d;
  1387. else { validateMsg = "下移层数只能输入整数"; return null; }
  1388. if (!count.HasValue) { validateMsg = "层数未配置(设备级也为空),请填层数或先初始化设备级"; return null; }
  1389. if (!spacing.HasValue) { validateMsg = "层间距未配置(设备级也为空),请填层间距或先初始化设备级(§2.5 不兜底)"; return null; }
  1390. if (!down.HasValue) { validateMsg = "下移层数未配置(设备级也为空),请填下移层数"; return null; }
  1391. // 校验:层数≥1、间距>0、下移≥0 且 <层数(下移层须落在拍摄范围内)。
  1392. if (count.Value < 1) { validateMsg = "层数必须 ≥ 1"; return null; }
  1393. if (spacing.Value <= 0) { validateMsg = "层间距必须 > 0"; return null; }
  1394. if (down.Value < 0) { validateMsg = "下移层数必须 ≥ 0"; return null; }
  1395. if (down.Value >= count.Value) { validateMsg = $"下移层数必须 < 层数({count.Value}),否则清晰层落在拍摄范围外"; return null; }
  1396. return (count.Value, spacing.Value, down.Value);
  1397. }
  1398. /// <summary>
  1399. /// M2-07 实时预览:用该 well 标定 FocusZ + 当前手调值,调 M2-02
  1400. /// ComputeLayerPositions(focusZ, cfg, pulseMax) 生成各层绝对 Z,刷新 LayerPreview(关联 V-045)。
  1401. /// 无标定锚点 → 清空预览并提示先标定;校验非法 → 清空预览并提示。
  1402. /// </summary>
  1403. public void PreviewManualLayers()
  1404. {
  1405. try
  1406. {
  1407. var focusZ = GetPreviewFocusZ(ManualTuneWell);
  1408. if (!focusZ.HasValue)
  1409. {
  1410. SetLayerPreview(null);
  1411. AddMessageInfo($"[手调拍摄层]well{ManualTuneWell} 无标定结果,请先对该 well 标定(或确认已下发清晰位置)再预览");
  1412. return;
  1413. }
  1414. var eff = ResolveEffectiveTune(out string msg);
  1415. if (eff == null)
  1416. {
  1417. SetLayerPreview(null);
  1418. AddMessageInfo($"[手调拍摄层]预览失败:{msg}");
  1419. return;
  1420. }
  1421. var cfg = new FocusLayerConfig
  1422. {
  1423. LayerCount = eff.Value.count,
  1424. LayerSpacingPulse = eff.Value.spacing,
  1425. LayerDown = eff.Value.down,
  1426. };
  1427. int pulseMax = tLSetting != null ? tLSetting.verticalMotorPulseMax : 0;
  1428. int[] positions = PhotoLayerCalculator.ComputeLayerPositions(focusZ.Value, cfg, pulseMax);
  1429. var items = new List<LayerPreviewItem>();
  1430. for (int i = 0; i < positions.Length; i++)
  1431. {
  1432. items.Add(new LayerPreviewItem
  1433. {
  1434. LayerIndex = i,
  1435. ZPulse = positions[i],
  1436. IsFocusLayer = (i == eff.Value.down), // 第 down 层 = 清晰层(FocusZ 锚点)
  1437. });
  1438. }
  1439. SetLayerPreview(items);
  1440. AddMessageInfo($"[手调拍摄层]well{ManualTuneWell} 预览:锚点FocusZ={focusZ.Value} 层数={eff.Value.count} " +
  1441. $"间距={eff.Value.spacing} 下移={eff.Value.down} → 第0层Z={positions[0]} 第{positions.Length - 1}层Z={positions[positions.Length - 1]}");
  1442. }
  1443. catch (Exception ex)
  1444. {
  1445. SetLayerPreview(null);
  1446. ExLog(ex, "PreviewManualLayers");
  1447. AddMessageInfo($"[手调拍摄层]预览异常:{ex.Message}");
  1448. }
  1449. }
  1450. /// <summary>
  1451. /// M2-07 保存为该 well 默认:校验通过后,把手调值写 house_well_setting well 级覆盖
  1452. /// (focus_layer_spacing_pulse/focus_layer_count + 复用 move_down_layer)。
  1453. /// 复用现有 operate 端 well 设置保存通道 HttpHelper.WellUpdateApi(同 SetWellMotorPosition/SetWellAutoFocus),
  1454. /// 走 /api/tl/control/setting/house/well/update。留空字段=继承设备级(写 null)。
  1455. /// 下次该 well 经 §2.5 就近优先(PhotoLayerCalculator.Resolve)沿用 well 覆盖值。
  1456. /// 返回 true=保存成功。
  1457. /// </summary>
  1458. public bool SaveManualLayerTune()
  1459. {
  1460. try
  1461. {
  1462. if (CurrentHouse == null)
  1463. {
  1464. AddMessageInfo("[手调拍摄层]未获取到舱室信息");
  1465. return false;
  1466. }
  1467. // M8-G3-1:保存手调拍摄层为"本地校验/计算 + HTTP 持久化 + 内存同步"打包的关键业务操作,
  1468. // 用 Begin scope 给一个父操作名(统一 traceId 串联其内的 WellUpdateApi HTTP 埋点;module=对焦调试)。
  1469. using var _op = Aivfo.OperationLog.OperationLogger.Begin("对焦调试", "保存手调拍摄层设置",
  1470. houseSn: CurrentHouseId);
  1471. // 校验:层数≥1、间距>0、下移≥0 且 <层数;非法不保存。
  1472. var eff = ResolveEffectiveTune(out string msg);
  1473. if (eff == null)
  1474. {
  1475. AddMessageInfo($"[手调拍摄层]保存被拦截(非法值):{msg}");
  1476. try { _op.Output(new { rejected = msg }).Fail("校验未通过:" + msg); } catch { }
  1477. return false;
  1478. }
  1479. // 留空字段=继承设备级 → 写 null(well 级覆盖留空,§2.5)。非空字段写实际值。
  1480. int? wellCount = string.IsNullOrWhiteSpace(ManualLayerCount) ? (int?)null : int.Parse(ManualLayerCount.Trim());
  1481. int? wellSpacing = string.IsNullOrWhiteSpace(ManualLayerSpacing) ? (int?)null : int.Parse(ManualLayerSpacing.Trim());
  1482. // 下移复用 move_down_layer(库列非空);留空时回退取生效值(eff.down)写回,不破坏旧列语义。
  1483. int wellMoveDown = string.IsNullOrWhiteSpace(ManualMoveDown) ? eff.Value.down : int.Parse(ManualMoveDown.Trim());
  1484. try { _op.Input(new { houseSn = CurrentHouseId, well = ManualTuneWell, wellCount, wellSpacing, wellMoveDown }); } catch { }
  1485. // 复用现有 well 设置保存通道:与 SetWellMotorPosition/SetWellAutoFocus 同一 WellUpdateApi。
  1486. // 后端按 tlSn/houseSn/wellSn 定位 house_well_setting 行做部分更新(仅本次携带的字段)。
  1487. string body = JsonConvert.SerializeObject(new
  1488. {
  1489. tlSn = CurrentHouse.tlSn,
  1490. houseSn = CurrentHouse.houseSn,
  1491. wellSn = ManualTuneWell,
  1492. focusLayerSpacingPulse = wellSpacing, // null=继承设备级
  1493. focusLayerCount = wellCount, // null=继承设备级
  1494. moveDownLayer = wellMoveDown, // 复用既有列(下移)
  1495. });
  1496. bool ok = AppData.Instance.HttpHelper.WellUpdateApi(body);
  1497. if (!ok)
  1498. {
  1499. AddMessageInfo("[手调拍摄层]保存失败(接口返回失败)");
  1500. try { _op.Fail("WellUpdateApi 返回失败"); } catch { }
  1501. return false;
  1502. }
  1503. // 本地内存同步,使"下次该 well 沿用"在不重载设置时也即时生效(预览/取数一致)。
  1504. var ws = houseWellSettingList.FirstOrDefault(x => x.houseSn == CurrentHouseId && x.wellSn == ManualTuneWell);
  1505. if (ws != null)
  1506. {
  1507. ws.focusLayerCount = wellCount;
  1508. ws.focusLayerSpacingPulse = wellSpacing;
  1509. ws.moveDownLayer = wellMoveDown;
  1510. }
  1511. AddMessageInfo($"[手调拍摄层]well{ManualTuneWell} 已存为默认:层数={(wellCount?.ToString() ?? "继承")} " +
  1512. $"间距={(wellSpacing?.ToString() ?? "继承")} 下移={wellMoveDown}(写 house_well_setting well 级覆盖,留空继承设备级)");
  1513. try { _op.Output(new { ok = true }).Success(); } catch { }
  1514. return true;
  1515. }
  1516. catch (Exception ex)
  1517. {
  1518. ExLog(ex, "SaveManualLayerTune");
  1519. AddMessageInfo($"[手调拍摄层]保存异常:{ex.Message}");
  1520. return false;
  1521. }
  1522. }
  1523. private void SetLayerPreview(List<LayerPreviewItem> items)
  1524. {
  1525. void build()
  1526. {
  1527. LayerPreview.Clear();
  1528. if (items != null)
  1529. foreach (var it in items) LayerPreview.Add(it);
  1530. }
  1531. var disp = System.Windows.Application.Current?.Dispatcher;
  1532. if (disp != null && !disp.CheckAccess()) disp.Invoke(build); else build();
  1533. }
  1534. #endregion
  1535. #region D2-02-T3.5 保存 per-well 对焦搜索范围(半幅)
  1536. /// <summary>
  1537. /// 当前编辑的 well 级"水平搜索半幅"(围绕 horizontalMotorPosition)。空字符串=留空继承设备级(保存写 null)。
  1538. /// View TextBox 双向绑定;校验在保存时做(非空须为 ≥0 整数)。
  1539. /// </summary>
  1540. [ObservableProperty] private string currentHFocusRange = "";
  1541. /// <summary>
  1542. /// 当前编辑的 well 级"垂直搜索半幅"(围绕 eepromClearPosition/清晰位)。空=继承设备级(写 null)。校验:≥0。
  1543. /// </summary>
  1544. [ObservableProperty] private string currentVFocusRange = "";
  1545. /// <summary>
  1546. /// 取该 well 当前 well 级半幅覆盖值回填两个输入框(空=继承设备级,显示空占位)。供"载入半幅"按钮调用。
  1547. /// 复用 ManualTuneWell 作为锚点 well(与手调拍摄层同一选定 well)。
  1548. /// </summary>
  1549. public void LoadWellFocusRange(int well)
  1550. {
  1551. ManualTuneWell = well;
  1552. var ws = houseWellSettingList.FirstOrDefault(x => x.houseSn == CurrentHouseId && x.wellSn == well);
  1553. CurrentHFocusRange = ws?.horizontalFocusRange?.ToString() ?? "";
  1554. CurrentVFocusRange = ws?.verticalFocusRange?.ToString() ?? "";
  1555. AddMessageInfo($"[对焦半幅]已载入 well{well} 当前覆盖:水平={(ws?.horizontalFocusRange?.ToString() ?? "继承")} 垂直={(ws?.verticalFocusRange?.ToString() ?? "继承")}");
  1556. }
  1557. /// <summary>
  1558. /// D2-02-T3.5 保存该 well 对焦搜索半幅:校验通过后写 house_well_setting well 级覆盖
  1559. /// (horizontal_focus_range/vertical_focus_range)。留空字段=继承设备级(写 null)。
  1560. /// 复用现有 well 设置保存通道 HttpHelper.WellUpdateApi(同 SetWellMotorPosition/SaveManualLayerTune),
  1561. /// 走 /well/update;后端 well/update 已支持这两列(Java HouseWellSettingUpdate.horizontalFocusRange/verticalFocusRange)。
  1562. /// 字段名与 Java DTO 完全一致:horizontalFocusRange / verticalFocusRange。
  1563. /// 返回 true=保存成功。
  1564. /// </summary>
  1565. public bool SaveWellFocusRange()
  1566. {
  1567. try
  1568. {
  1569. if (CurrentHouse == null)
  1570. {
  1571. AddMessageInfo("[对焦半幅]未获取到舱室信息");
  1572. return false;
  1573. }
  1574. if (ManualTuneWell < 1 || ManualTuneWell > 16)
  1575. {
  1576. AddMessageInfo("[对焦半幅]well 只能为 1-16");
  1577. return false;
  1578. }
  1579. // 校验:非空须为 ≥0 整数;留空=继承设备级(写 null)。
  1580. int? hRange;
  1581. if (string.IsNullOrWhiteSpace(CurrentHFocusRange)) hRange = null;
  1582. else if (int.TryParse(CurrentHFocusRange.Trim(), out int hv) && hv >= 0) hRange = hv;
  1583. else { AddMessageInfo("[对焦半幅]水平半幅只能输入 ≥0 整数(留空=继承设备级)"); return false; }
  1584. int? vRange;
  1585. if (string.IsNullOrWhiteSpace(CurrentVFocusRange)) vRange = null;
  1586. else if (int.TryParse(CurrentVFocusRange.Trim(), out int vv) && vv >= 0) vRange = vv;
  1587. else { AddMessageInfo("[对焦半幅]垂直半幅只能输入 ≥0 整数(留空=继承设备级)"); return false; }
  1588. // M8 埋点:保存对焦半幅为关键业务操作(统一 traceId 串其内 WellUpdateApi HTTP 埋点)。
  1589. using var _op = Aivfo.OperationLog.OperationLogger.Begin("对焦调试", "保存对焦搜索半幅",
  1590. houseSn: CurrentHouseId);
  1591. try { _op.Input(new { houseSn = CurrentHouseId, well = ManualTuneWell, horizontalFocusRange = hRange, verticalFocusRange = vRange }); } catch { }
  1592. // body 字段名与 Java HouseWellSettingUpdate 完全一致;留空=null 清空继承设备级(与 SaveManualLayerTune 一致)。
  1593. string body = JsonConvert.SerializeObject(new
  1594. {
  1595. tlSn = CurrentHouse.tlSn,
  1596. houseSn = CurrentHouse.houseSn,
  1597. wellSn = ManualTuneWell,
  1598. horizontalFocusRange = hRange, // null=继承设备级 focus_h_range_default
  1599. verticalFocusRange = vRange, // null=继承设备级 focus_v_range_default
  1600. });
  1601. bool ok = AppData.Instance.HttpHelper.WellUpdateApi(body);
  1602. if (!ok)
  1603. {
  1604. AddMessageInfo("[对焦半幅]保存失败(接口返回失败)");
  1605. try { _op.Fail("WellUpdateApi 返回失败"); } catch { }
  1606. return false;
  1607. }
  1608. // 本地内存同步,使取数一致(不重载设置即生效)。
  1609. var ws = houseWellSettingList.FirstOrDefault(x => x.houseSn == CurrentHouseId && x.wellSn == ManualTuneWell);
  1610. if (ws != null)
  1611. {
  1612. ws.horizontalFocusRange = hRange;
  1613. ws.verticalFocusRange = vRange;
  1614. }
  1615. AddMessageInfo($"[对焦半幅]well{ManualTuneWell} 已保存:水平={(hRange?.ToString() ?? "继承")} 垂直={(vRange?.ToString() ?? "继承")}(写 house_well_setting well 级覆盖,留空继承设备级)");
  1616. try { _op.Output(new { ok = true }).Success(); } catch { }
  1617. return true;
  1618. }
  1619. catch (Exception ex)
  1620. {
  1621. ExLog(ex, "SaveWellFocusRange");
  1622. AddMessageInfo($"[对焦半幅]保存异常:{ex.Message}");
  1623. return false;
  1624. }
  1625. }
  1626. #endregion
  1627. }
  1628. }