HouseDebugPageViewModel.cs 77 KB

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