HouseDebugPageViewModel.cs 83 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839
  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. Serial.ShakeHandsWait();
  300. OpenLed();
  301. Serial.HorizontalResetWait(tLSetting.motorDelay);
  302. CurrentHor = 0;
  303. CurrentWell = 0;
  304. Serial.HorizontalMoveToWait(currentHorSetting.horizontalMotorPosition, tLSetting.motorDelay);
  305. CurrentHor = currentHorSetting.horizontalMotorPosition;
  306. CurrentWell = 1;
  307. Serial.VerticalResetWait(tLSetting.motorDelay);
  308. CurrentVer = 0;
  309. CurrentFocal = 0;
  310. Serial.VerticalMoveToWait(verNewValue, tLSetting.motorDelay);
  311. CurrentVer = verNewValue;
  312. CurrentFocal = 1;
  313. RedTem();
  314. RedPre();
  315. RedDoor();
  316. RedVentTime();
  317. return;
  318. }
  319. catch (Exception ex)
  320. {
  321. AppData.Instance.LogHelper.ExceptionLog(ex, "调试模式初始化", LogEnum.RunException);
  322. AddMessageInfo($"初始化异常:{ex.Message}");
  323. return;
  324. }
  325. });
  326. }
  327. public bool ComHouseUnit()
  328. {
  329. try
  330. {
  331. // D2-02-T3.4:先停标定轮询、归还 control 协作会话(停心跳),再归还本地 HAL 借用。
  332. StopCalibPolling();
  333. ReleaseDebugSession();
  334. // M1-B2:物理串口/相机由采集端(control)持有,调试只归还借用,绝不 ClosePort/UnInit 关物理口——
  335. // 否则会把采集端的口/相机一并关掉。归还后 HAL 触发 ResumeCapture 恢复本舱采集(T1.3)。
  336. if (_halLease != null)
  337. {
  338. try { _halLease.Dispose(); } catch { }
  339. _halLease = null;
  340. AddMessageInfo($"[{CurrentHouseId}]已归还借用,恢复后台采集");
  341. }
  342. return true;
  343. }
  344. catch (Exception ex)
  345. {
  346. AppData.Instance.LogHelper.ExceptionLog(ex, "调试模式卸载", LogEnum.RunException);
  347. AddMessageInfo($"卸载异常:{ex.Message}");
  348. return false;
  349. }
  350. }
  351. #region D2-02-T3.4 调试会话协作(借硬件拿 sessionId / 归还)
  352. /// <summary>
  353. /// 向 control 借该舱调试会话:POST /debug/acquire {houseSn} → 拿 sessionId 存 CurrentSessionId,
  354. /// 并构造 16 孔标定协作客户端 CalibrationClient(复用同一 sessionId)。
  355. /// control 借用成功会起心跳;会话失效(SESSION_EXPIRED)回调提示工程师重进调试。
  356. /// 借不到(BUSY/会话异常)只提示不抛——预览/标定将因 CurrentSessionId 为空而拒绝执行。
  357. /// </summary>
  358. private async Task AcquireDebugSessionAsync(int houseSn)
  359. {
  360. try
  361. {
  362. // 关旧会话(重复初始化时)。
  363. ReleaseDebugSession();
  364. var client = new DebugSessionClient(ControlClient.BaseUrl);
  365. client.OnSessionExpired = () =>
  366. {
  367. CurrentSessionId = null;
  368. AddMessageInfo("⚠ 调试会话已失效(control 端超时回收),请退出后重新进入调试");
  369. };
  370. var r = await client.AcquireAsync(houseSn);
  371. if (!r.Ok || string.IsNullOrEmpty(r.SessionId))
  372. {
  373. try { client.Dispose(); } catch { }
  374. AddMessageInfo($"[{houseSn}]借调试会话失败:{r.Code}/{r.Error}(预览与标定不可用,请确认 control 已托管该舱)");
  375. return;
  376. }
  377. _sessionClient = client;
  378. CurrentSessionId = r.SessionId;
  379. // 标定协作客户端复用同一 baseUrl + sessionId。
  380. _calibClient = new CalibrationClient(ControlClient.BaseUrl, r.SessionId);
  381. string cultMsg = r.Cultivating ? $"(注意:该舱培养中,胚胎 {r.EmbryoCount} 枚)" : "";
  382. AddMessageInfo($"[{houseSn}]调试会话已建立 sessionId={r.SessionId}{cultMsg}");
  383. }
  384. catch (Exception ex)
  385. {
  386. ExLog(ex, "AcquireDebugSessionAsync");
  387. AddMessageInfo($"[{houseSn}]借调试会话异常:{ex.Message}");
  388. }
  389. }
  390. /// <summary>归还调试会话(停心跳、通知 control)并释放协作客户端。幂等。
  391. /// release 的 HTTP POST 放后台跑(避免 control 失联时 HttpClient 默认 100s 超时卡死 UI 线程);
  392. /// DebugSessionClient.ReleaseAsync 在 await POST 前已同步置闸+停心跳,故心跳即时停止、不必等 POST。</summary>
  393. private void ReleaseDebugSession()
  394. {
  395. var calib = _calibClient; _calibClient = null;
  396. if (calib != null) { try { calib.Dispose(); } catch { } }
  397. var sc = _sessionClient; _sessionClient = null;
  398. if (sc != null)
  399. {
  400. // 后台 best-effort 归还+释放;失败也无妨(control 端 TTL 看门狗会超时回收会话)。
  401. Task.Run(async () =>
  402. {
  403. try { await sc.ReleaseAsync(); } catch { }
  404. try { sc.Dispose(); } catch { }
  405. });
  406. }
  407. CurrentSessionId = null;
  408. }
  409. #endregion
  410. /// <summary>
  411. /// 读温度
  412. /// </summary>
  413. public void RedTem()
  414. {
  415. if (Serial == null) return;
  416. Temperature = Serial.TemperatureWait();
  417. }
  418. /// <summary>
  419. /// 读压力
  420. /// </summary>
  421. public void RedPre()
  422. {
  423. if (Serial == null) return;
  424. Pressure = Serial.PressureWait();
  425. }
  426. /// <summary>
  427. /// 读舱门
  428. /// </summary>
  429. public void RedDoor()
  430. {
  431. if (Serial == null) return;
  432. string DoorStateString = Serial.DoorStatusWait().ToString();
  433. if(DoorStateString == "关闭")
  434. {
  435. DoorState = KeyToStringConvert.GetLanguageStringByKey("C0305");
  436. }
  437. if (DoorStateString == "打开")
  438. {
  439. DoorState = KeyToStringConvert.GetLanguageStringByKey("C0306");
  440. }
  441. }
  442. /// <summary>
  443. /// 打开Led灯
  444. /// </summary>
  445. public void OpenLed()
  446. {
  447. if (Serial == null) return;
  448. // M8-G3-1:LED 开关为串口设备命令入口,补操作日志埋点(module=对焦调试)。
  449. Aivfo.OperationLog.OperationLogger.Run("对焦调试", "打开LED灯",
  450. () => Serial.OpenLedWait(),
  451. input: new { houseSn = CurrentHouseId });
  452. LedState = KeyToStringConvert.GetLanguageStringByKey("C0306");
  453. //LedState = "开启";
  454. }
  455. /// <summary>
  456. /// 关闭Led灯
  457. /// </summary>
  458. public void CloseLed()
  459. {
  460. if (Serial == null) return;
  461. // M8-G3-1:LED 开关为串口设备命令入口,补操作日志埋点(module=对焦调试)。
  462. Aivfo.OperationLog.OperationLogger.Run("对焦调试", "关闭LED灯",
  463. () => Serial.CloseLedWait(),
  464. input: new { houseSn = CurrentHouseId });
  465. //LedState = "关闭";
  466. LedState = KeyToStringConvert.GetLanguageStringByKey("C0305");
  467. }
  468. /// <summary>
  469. /// 打开进气阀
  470. /// </summary>
  471. public void OpenIntake()
  472. {
  473. if (Serial == null) return;
  474. // M8-G3-1:进气阀开关为串口设备命令入口,补操作日志埋点(module=对焦调试)。
  475. Aivfo.OperationLog.OperationLogger.Run("对焦调试", "打开进气阀",
  476. () => Serial.OpenIntakeValveWait(),
  477. input: new { houseSn = CurrentHouseId });
  478. }
  479. /// <summary>
  480. /// 关闭进气阀
  481. /// </summary>
  482. public void CloseIntake()
  483. {
  484. if (Serial == null) return;
  485. // M8-G3-1:进气阀开关为串口设备命令入口,补操作日志埋点(module=对焦调试)。
  486. Aivfo.OperationLog.OperationLogger.Run("对焦调试", "关闭进气阀",
  487. () => Serial.CloseIntakeValveWait(),
  488. input: new { houseSn = CurrentHouseId });
  489. }
  490. /// <summary>
  491. /// 打开排气阀
  492. /// </summary>
  493. public void OpenExhaust()
  494. {
  495. if (Serial == null) return;
  496. // M8-G3-1:排气阀开关为串口设备命令入口,补操作日志埋点(module=对焦调试)。
  497. Aivfo.OperationLog.OperationLogger.Run("对焦调试", "打开排气阀",
  498. () => Serial.OpenExhaustValveWait(),
  499. input: new { houseSn = CurrentHouseId });
  500. }
  501. /// <summary>
  502. /// 关闭排气阀
  503. /// </summary>
  504. public void CloseExhaust()
  505. {
  506. if (Serial == null) return;
  507. // M8-G3-1:排气阀开关为串口设备命令入口,补操作日志埋点(module=对焦调试)。
  508. Aivfo.OperationLog.OperationLogger.Run("对焦调试", "关闭排气阀",
  509. () => Serial.CloseExhaustValveWait(),
  510. input: new { houseSn = CurrentHouseId });
  511. }
  512. /// <summary>
  513. /// 舱室补气
  514. /// </summary>
  515. public void HouseAeration()
  516. {
  517. if (Serial == null) return;
  518. // M8-G3-1:舱室补气为串口设备命令入口,补操作日志埋点(module=对焦调试)。
  519. Aivfo.OperationLog.OperationLogger.Run("对焦调试", "舱室补气",
  520. () => Serial.HouseAerationWait(),
  521. input: new { houseSn = CurrentHouseId });
  522. }
  523. /// <summary>
  524. /// 舱室排气
  525. /// </summary>
  526. public void HouseVent()
  527. {
  528. if (Serial == null) return;
  529. // M8-G3-1:舱室排气为串口设备命令入口,补操作日志埋点(module=对焦调试)。
  530. Aivfo.OperationLog.OperationLogger.Run("对焦调试", "舱室排气",
  531. () => Serial.HouseVentWait(),
  532. input: new { houseSn = CurrentHouseId });
  533. }
  534. /// <summary>
  535. /// 写舱室进气阀时间
  536. /// </summary>
  537. /// <param name="newValue"></param>
  538. public void WriteOpenIntakeTime(int newValue)
  539. {
  540. if (Serial == null) return;
  541. // M1-B2:走 lease.Serial→control ComBin(builder 与 operate 逐字节一致)。⚠ 待真机 V-010(写E方回包判定)。
  542. // M8-G3-1:写舱室进气阀时间为写 EEPROM 设备命令入口,补操作日志埋点(module=对焦调试)。
  543. Aivfo.OperationLog.OperationLogger.Run("对焦调试", "写舱室进气阀时间",
  544. () => Serial.WriteOpenIntakeTimeWait(newValue, isBuffer: false),
  545. input: new { houseSn = CurrentHouseId, newValue });
  546. }
  547. /// <summary>
  548. /// 写舱室排气阀时间
  549. /// </summary>
  550. /// <param name="newValue"></param>
  551. public void WriteOpenVentTime(int newValue)
  552. {
  553. if (Serial == null) return;
  554. // M-01 已补:control 端补齐写排气阀时间 E方命令(builder 地址 00 03 08,与合并前 operate 逐字节一致),
  555. // 经 lease.Serial→control ComBin 真正下发下位机。
  556. // M8-G3-1:写舱室排气阀时间为写 EEPROM 设备命令入口,补操作日志埋点(module=对焦调试)。
  557. var written = Aivfo.OperationLog.OperationLogger.Run("对焦调试", "写舱室排气阀时间",
  558. () => Serial.WriteOpenVentTimeWait(newValue),
  559. input: new { houseSn = CurrentHouseId, newValue });
  560. if (!written)
  561. {
  562. AddMessageInfo($"[排气阀时间]下发失败,仅本地暂存{newValue}");
  563. }
  564. HouseVentTimeE = newValue;
  565. }
  566. /// <summary>
  567. /// 读舱室排气阀打开时间
  568. /// </summary>
  569. public void RedVentTime()
  570. {
  571. if (Serial == null) return;
  572. // M-02 已补:control 端补齐读排气阀时间 E方命令(地址 00 03 08);读不到(-1)则保持原值不覆盖。
  573. int v = Serial.ReadOpenVentTimeWait();
  574. if (v >= 0) HouseVentTimeE = v;
  575. }
  576. /// <summary>
  577. /// 写垂直电机间隔脉冲
  578. /// </summary>
  579. /// <param name="newValue"></param>
  580. public void WriteOVerSpace(int newValue)
  581. {
  582. if (Serial == null) return;
  583. // M1-B2:走 lease.Serial→control ComBin(builder 与 operate 逐字节一致)。⚠ 待真机 V-010。
  584. // M8-G3-1:写垂直电机间隔脉冲为写 EEPROM 设备命令入口,补操作日志埋点(module=对焦调试)。
  585. Aivfo.OperationLog.OperationLogger.Run("对焦调试", "写垂直电机间隔脉冲",
  586. () => Serial.WriteScanStepWait(newValue),
  587. input: new { houseSn = CurrentHouseId, newValue });
  588. }
  589. /// <summary>
  590. /// 保存水平电机位置
  591. /// </summary>
  592. /// <param name="newValue"></param>
  593. public void SaveWellHor()
  594. {
  595. if (Serial == null) return;
  596. // M8-P3b:手调保存水平电机位置(关键命令入口,module=对焦调试)。
  597. // M1-B2:走 lease.Serial.WriteWellHorizontalPosWait→control ComBin(builder 逐字节一致)。⚠ 待真机 V-010。
  598. Aivfo.OperationLog.OperationLogger.Run("对焦调试", "手调保存水平电机位置",
  599. () => Serial.WriteWellHorizontalPosWait(CurrentWell, CurrentHor),
  600. input: new { houseSn = CurrentHouseId, well = CurrentWell, hor = CurrentHor });
  601. }
  602. #region 电机运动
  603. /// <summary>
  604. /// 水平电机复位
  605. /// </summary>
  606. public void HorizontalMotorReset()
  607. {
  608. if (Serial == null) return;
  609. // M8-P3b:电机控制命令埋点(module=对焦调试)。
  610. Aivfo.OperationLog.OperationLogger.Run("对焦调试", "水平电机复位",
  611. () => Serial.HorizontalResetWait(tLSetting.motorDelay),
  612. input: new { houseSn = CurrentHouseId });
  613. CurrentHor = 0;
  614. CurrentWell = 0;
  615. }
  616. /// <summary>
  617. /// 水平电机正向
  618. /// </summary>
  619. public void HorizontalMotorForward(int value)
  620. {
  621. if (Serial == null) return;
  622. // M8-G3-1:电机控制命令入口,补操作日志埋点(module=对焦调试)。
  623. Aivfo.OperationLog.OperationLogger.Run("对焦调试", "水平电机正向",
  624. () => Serial.HorizontalForwardWait(value, tLSetting.motorDelay),
  625. input: new { houseSn = CurrentHouseId, value });
  626. CurrentHor += value;
  627. }
  628. /// <summary>
  629. /// 水平电机反向
  630. /// </summary>
  631. public void HorizontalMotorBackward(int value)
  632. {
  633. if (Serial == null) return;
  634. // M8-G3-1:电机控制命令入口,补操作日志埋点(module=对焦调试)。
  635. Aivfo.OperationLog.OperationLogger.Run("对焦调试", "水平电机反向",
  636. () => Serial.HorizontalBackwardWait(value, tLSetting.motorDelay),
  637. input: new { houseSn = CurrentHouseId, value });
  638. CurrentHor -= value;
  639. }
  640. /// <summary>
  641. /// 水平电机到目标well
  642. /// </summary>
  643. /// <param name="newWell"></param>
  644. public void HorizontalMotorToWell(int newWell)
  645. {
  646. if (Serial == null) return;
  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. Aivfo.OperationLog.OperationLogger.Run("对焦调试", "水平电机到well",
  655. () => Serial.HorizontalMoveToWait(currentHorSetting.horizontalMotorPosition, tLSetting.motorDelay),
  656. input: new { houseSn = CurrentHouseId, well = newWell, hor = currentHorSetting.horizontalMotorPosition });
  657. CurrentHor = currentHorSetting.horizontalMotorPosition;
  658. CurrentWell = newWell;
  659. }
  660. /// <summary>
  661. /// 垂直电机复位
  662. /// </summary>
  663. public void VerticalMotorReset()
  664. {
  665. if (Serial == null) return;
  666. // M8-P3b:电机控制命令埋点(module=对焦调试)。
  667. Aivfo.OperationLog.OperationLogger.Run("对焦调试", "垂直电机复位",
  668. () => Serial.VerticalResetWait(tLSetting.motorDelay),
  669. input: new { houseSn = CurrentHouseId });
  670. CurrentVer = 0;
  671. }
  672. /// <summary>
  673. /// 垂直电机正向运动
  674. /// </summary>
  675. public void VerticalMotorForward(int newValue)
  676. {
  677. if (Serial == null) return;
  678. // M8-G3-1:电机控制命令入口,补操作日志埋点(module=对焦调试)。
  679. Aivfo.OperationLog.OperationLogger.Run("对焦调试", "垂直电机正向",
  680. () => Serial.VerticalForwardWait(newValue, tLSetting.motorDelay),
  681. input: new { houseSn = CurrentHouseId, newValue });
  682. CurrentVer += newValue;
  683. }
  684. /// <summary>
  685. /// 垂直电机反向运动
  686. /// </summary>
  687. public void VerticalMotorBackward(int newValue)
  688. {
  689. if (Serial == null) return;
  690. // M8-G3-1:电机控制命令入口,补操作日志埋点(module=对焦调试)。
  691. Aivfo.OperationLog.OperationLogger.Run("对焦调试", "垂直电机反向",
  692. () => Serial.VerticalBackwardWait(newValue, tLSetting.motorDelay),
  693. input: new { houseSn = CurrentHouseId, newValue });
  694. CurrentVer -= newValue;
  695. }
  696. /// <summary>
  697. /// 垂直电机绝对运动
  698. /// </summary>
  699. public void VerticalMotorAbsolute(int newValue)
  700. {
  701. if (Serial == null) return;
  702. // M8-G3-1:电机控制命令入口,补操作日志埋点(module=对焦调试)。
  703. Aivfo.OperationLog.OperationLogger.Run("对焦调试", "垂直电机绝对运动",
  704. () => Serial.VerticalMoveToWait(newValue, tLSetting.motorDelay),
  705. input: new { houseSn = CurrentHouseId, newValue });
  706. CurrentVer = newValue;
  707. }
  708. /// <summary>
  709. /// 一键电机准备
  710. /// </summary>
  711. public void MototReady()
  712. {
  713. if (Serial == null) return;
  714. var currentHorSetting = houseWellSettingList.FirstOrDefault(x => x.houseSn == CurrentHouseId && x.wellSn == 1);
  715. if (currentHorSetting == null)
  716. {
  717. AddMessageInfo($"[未获取到1号well的水平电机位置]");
  718. return;
  719. }
  720. var verNewValue = currentHorSetting.eepromClearPosition;
  721. var cc = ccdPhoto.FirstOrDefault(x => x.houseSn == CurrentHouseId && x.wellSn == 1);
  722. if (cc != null)
  723. {
  724. verNewValue = cc.clearestPosition;
  725. }
  726. // M8-G3-1:一键电机准备为多步串口动作流程,用 Begin scope 串联各子动作(module=对焦调试)。
  727. using var _op = Aivfo.OperationLog.OperationLogger.Begin("对焦调试", "一键电机准备",
  728. houseSn: CurrentHouseId);
  729. try { _op.Input(new { houseSn = CurrentHouseId, targetHor = currentHorSetting.horizontalMotorPosition, targetVer = verNewValue }); } catch { }
  730. Serial.HorizontalResetWait(tLSetting.motorDelay);
  731. CurrentHor = 0;
  732. CurrentWell = 0;
  733. Serial.HorizontalMoveToWait(currentHorSetting.horizontalMotorPosition, tLSetting.motorDelay);
  734. CurrentHor = currentHorSetting.horizontalMotorPosition;
  735. CurrentWell = 1;
  736. Serial.VerticalResetWait(tLSetting.motorDelay);
  737. CurrentVer = 0;
  738. CurrentFocal = 0;
  739. Serial.VerticalMoveToWait(verNewValue, tLSetting.motorDelay);
  740. CurrentVer = verNewValue;
  741. CurrentFocal = 1;
  742. }
  743. /// <summary>
  744. /// 单张抓拍
  745. /// </summary>
  746. public bool SavePic(string fullName)
  747. {
  748. try
  749. {
  750. if (GetPicData() == 0)
  751. {
  752. if (Cam == null) return false;
  753. // M8-G3-1:单张抓拍落盘为相机采图+保存命令入口,补操作日志埋点(module=对焦调试)。
  754. // 批量抓图(水平抓图/清晰图层抓图)经 Begin scope 调用时,本埋点自动成为其子埋点(父子链)。
  755. return Aivfo.OperationLog.OperationLogger.Run("对焦调试", "单张抓拍",
  756. () => Cam.SavePic(fullName, CurrentHouse.ccdWidth, CurrentHouse.ccdHeight),
  757. input: new { houseSn = CurrentHouseId, well = CurrentWell, focal = CurrentFocal, hor = CurrentHor, ver = CurrentVer });
  758. }
  759. return false;
  760. }
  761. catch (Exception ex)
  762. {
  763. AppData.Instance.LogHelper.ExceptionLog(ex, $"单张抓拍", LogEnum.RunException);
  764. AddMessageInfo($"单张抓拍异常:{ex.Message}");
  765. return false;
  766. }
  767. }
  768. /// <summary>
  769. /// 水平抓图
  770. /// </summary>
  771. public void ShuiPingZhuaPai()
  772. {
  773. try
  774. {
  775. IsStop = false;
  776. if (Serial == null) return;
  777. if (IsStop) return;
  778. // M8-G3-1:水平抓图为多步循环采图流程,用 Begin scope 串联各 well 抓拍子埋点(module=对焦调试)。
  779. using var _op = Aivfo.OperationLog.OperationLogger.Begin("对焦调试", "水平抓图",
  780. houseSn: CurrentHouseId);
  781. try { _op.Input(new { houseSn = CurrentHouseId }); } catch { }
  782. Serial.HorizontalResetWait(tLSetting.motorDelay);
  783. CurrentHor = 0;
  784. CurrentWell = 0;
  785. HouseWellSetting currentHorSetting = null;
  786. string dtnow = string.Format("{0:yyyy-MM-dd-HH-mm-ss}", DateTime.Now); //24小时制
  787. string path = AppData.Instance.LogHelper.GetDeBugShuiPingDirectory(CurrentHouse.houseSn, dtnow);
  788. if (!Directory.Exists(path))
  789. {
  790. Directory.CreateDirectory(path);
  791. }
  792. for (int i = 1; i <= 16; i++)
  793. {
  794. currentHorSetting = houseWellSettingList.FirstOrDefault(x => x.houseSn == CurrentHouseId && x.wellSn == i);
  795. if (currentHorSetting == null)
  796. {
  797. AddMessageInfo($"[未获取到1号well的水平电机位置]");
  798. continue;
  799. }
  800. if (IsStop) return;
  801. if (Serial == null) return;
  802. Serial.HorizontalMoveToWait(currentHorSetting.horizontalMotorPosition, tLSetting.motorDelay);
  803. if (IsStop) return;
  804. CurrentHor = currentHorSetting.horizontalMotorPosition;
  805. CurrentWell = i;
  806. string filename = $"{dtnow}-house{CurrentHouse.houseSn}-well{CurrentWell}-{CurrentFocal}-{CurrentHor}-{CurrentVer}.jpg";
  807. string fullName = $"{path}{filename}";
  808. if (Cam == null) return;
  809. if (SavePic(fullName))
  810. {
  811. AddPic(fullName);
  812. }
  813. }
  814. }
  815. catch (Exception ex)
  816. {
  817. AppData.Instance.LogHelper.ExceptionLog(ex, $"水平抓拍", LogEnum.RunException);
  818. AddMessageInfo($"水平抓拍异常:{ex.Message}");
  819. }
  820. }
  821. /// <summary>
  822. /// 清晰图层抓图
  823. /// </summary>
  824. public async Task AutoFocusPic(int focalCount, int xun)
  825. {
  826. await Task.Run(async () =>
  827. {
  828. try
  829. {
  830. IsStop = false;
  831. var startAutoFocus = -1;
  832. var cc = ccdPhoto.FirstOrDefault(x => x.houseSn == CurrentHouseId && x.wellSn == CurrentWell);
  833. if (cc == null)
  834. {
  835. AddMessageInfo($"[未获取到{CurrentWell}号well的自动对焦起点]");
  836. return;
  837. }
  838. // M8-G3-1:清晰图层抓图为多步循环采图流程,用 Begin scope 串联各层抓拍子埋点(module=对焦调试)。
  839. using var _op = Aivfo.OperationLog.OperationLogger.Begin("对焦调试", "清晰图层抓图",
  840. houseSn: CurrentHouseId);
  841. try { _op.Input(new { houseSn = CurrentHouseId, well = CurrentWell, focalCount, xun }); } catch { }
  842. startAutoFocus = cc.autoFocusPosition;
  843. string dtnow = string.Format("{0:yyyy-MM-dd-HH-mm-ss}", DateTime.Now); //24小时制
  844. string path = null;
  845. string fullName = null;
  846. for (int k = 0; k < xun; k++)
  847. {
  848. if (IsStop) return;
  849. if (Serial == null) return;
  850. Serial.VerticalResetWait(tLSetting.motorDelay);
  851. CurrentVer = 0;
  852. CurrentFocal = 0;
  853. var verSpacePulse = 128;
  854. if (CurrentHouse.verticalMotorSpacePulse.HasValue) verSpacePulse = CurrentHouse.verticalMotorSpacePulse.Value;
  855. path = $"{AppData.Instance.LogHelper.GetDeBugQingXiDirectory(CurrentHouse.houseSn, CurrentWell, dtnow)}{(k + 1)}_{CurrentHor}";
  856. if (!Directory.Exists(path)) Directory.CreateDirectory(path);
  857. for (int i = 0; i < focalCount; i++)
  858. {
  859. CurrentFocal = i + 1;
  860. var currentVerValue = startAutoFocus + (i * verSpacePulse);
  861. if (IsStop) return;
  862. if (Serial == null) return;
  863. if(currentVerValue > tLSetting.verticalMotorPulseMax)
  864. {
  865. AddMessageInfo($"清晰图层抓图超出垂直电机上限:{tLSetting.verticalMotorPulseMax}");
  866. return;
  867. }
  868. Serial.VerticalMoveToWait(currentVerValue, tLSetting.motorDelay);
  869. CurrentVer = currentVerValue;
  870. fullName = $"{path}\\{currentVerValue}.jpg";
  871. if (IsStop) return;
  872. if (Cam == null) return;
  873. if (SavePic(fullName)) AddPic(fullName);
  874. }
  875. }
  876. }
  877. catch (Exception ex)
  878. {
  879. AppData.Instance.LogHelper.ExceptionLog(ex, $"清晰图层抓图", LogEnum.RunException);
  880. AddMessageInfo($"清晰图层抓图异常:{ex.Message}");
  881. }
  882. });
  883. }
  884. /// <summary>
  885. /// 抓图
  886. /// </summary>
  887. public int GetPicData()
  888. {
  889. try
  890. {
  891. if (Cam == null) return -1;
  892. int GetRgbData = -1;
  893. bool isWuTu = false;
  894. if (isWuTu)
  895. {
  896. GetRgbData = Cam.GrabRaw();//获取字节流
  897. AddMessageInfo($"[抓拍结果:{GetRgbData}][注:0表示成功]");
  898. if (GetRgbData == 0)
  899. {
  900. GetRgbData = Cam.RawToRgb();
  901. AddMessageInfo($"[rawToRgb结果:{GetRgbData}][注:0表示成功]");
  902. }
  903. }
  904. else
  905. {
  906. GetRgbData = Cam.GrabRgb();//获取字节流
  907. AddMessageInfo($"[抓拍结果:{GetRgbData}][注:0表示成功]");
  908. }
  909. return GetRgbData;
  910. }
  911. catch (Exception ex)
  912. {
  913. AppData.Instance.LogHelper.ExceptionLog(ex, $"调试模式抓拍", LogEnum.RunException);
  914. AddMessageInfo($"相机抓拍异常:{ex.Message}");
  915. return -1;
  916. }
  917. }
  918. #endregion
  919. #region 相机操作
  920. /// <summary>
  921. /// 设置曝光值
  922. /// </summary>
  923. /// <param name="newExporuse"></param>
  924. public void SetExposure(int newExporuse)
  925. {
  926. if (Cam == null) { AddMessageInfo("设置曝光失败:相机句柄为空"); return; }
  927. // M8-G3-1:设置相机曝光为相机设备命令入口,补操作日志埋点(module=对焦调试)。
  928. var ret = Aivfo.OperationLog.OperationLogger.Run("对焦调试", "设置相机曝光值",
  929. () => Cam.SetExposure(newExporuse),
  930. input: new { houseSn = CurrentHouseId, ccdId = CurrentCCDId, newExporuse });
  931. AddMessageInfo($"设置曝光结果:{ret}");
  932. }
  933. /// <summary>
  934. /// 打开实时预览(贴宿主窗口句柄)。M1-B2:走借用到的 lease.Camera(StartPreview),不再触碰具体 Camera。
  935. /// 返回 0 成功;相机句柄为空返回 -1。
  936. /// </summary>
  937. public int StartPreview(IntPtr hostControl, int left, int top, int width, int height)
  938. {
  939. if (Cam == null) return -1;
  940. return Cam.StartPreview(hostControl, left, top, width, height);
  941. }
  942. /// <summary>关闭实时预览。返回 0 成功;相机句柄为空返回 -1。</summary>
  943. public int StopPreview()
  944. {
  945. if (Cam == null) return -1;
  946. return Cam.StopPreview();
  947. }
  948. //public bool OpenVideo(IntPtr mControlPtr, int left, int top, int width, int height)
  949. //{
  950. // try
  951. // {
  952. // var a = camera.Usb2Start(mControlPtr, left, top, width, height);
  953. // AddMessageInfo($"图像打开结果[0表示成功]:{a}");
  954. // return a == 0;
  955. // }
  956. // catch (Exception ex)
  957. // {
  958. // ExLog(ex, "OpenVideo");
  959. // AddMessageInfo($"图像打开异常:{ex.Message}");
  960. // return false;
  961. // }
  962. //}
  963. //public bool CloseVideo()
  964. //{
  965. // try
  966. // {
  967. // var a = camera.Usb2Stop();
  968. // AddMessageInfo($"图像关闭结果[0表示成功]:{a}");
  969. // return a == 0;
  970. // }
  971. // catch (Exception ex)
  972. // {
  973. // ExLog(ex, "CloseVideo");
  974. // AddMessageInfo($"图像关闭异常:{ex.Message}");
  975. // return false;
  976. // }
  977. //}
  978. #endregion
  979. #region 参数保存
  980. /// <summary>
  981. /// 保存舱室参数
  982. /// </summary>
  983. /// <returns></returns>
  984. public bool SetHouseInfo()
  985. {
  986. try
  987. {
  988. if (CurrentHouse == null) return true;
  989. string body = JsonConvert.SerializeObject(new
  990. {
  991. tlSn = CurrentHouse.tlSn,
  992. houseSn = CurrentHouse.houseSn,
  993. ccdExposure = CurrentHouse.ccdExposure,
  994. inletValveOpeningTime = CurrentHouse.inletValveOpeningTime,
  995. verticalMotorSpacePulse = CurrentHouse.verticalMotorSpacePulse,
  996. });
  997. return AppData.Instance.HttpHelper.HouseDebuggingApi(body);
  998. }
  999. catch (Exception ex)
  1000. {
  1001. ExLog(ex, "SetHouseExposure");
  1002. return false;
  1003. }
  1004. }
  1005. /// <summary>
  1006. /// 保存当前well位置
  1007. /// </summary>
  1008. /// <returns></returns>
  1009. public bool SetWellMotorPosition()
  1010. {
  1011. try
  1012. {
  1013. if (CurrentHouse == null)
  1014. {
  1015. AddMessageInfo("获取舱室信息失败");
  1016. }
  1017. string body = JsonConvert.SerializeObject(new
  1018. {
  1019. horizontalMotorPosition = CurrentHor,
  1020. houseSn = CurrentHouse.houseSn,
  1021. tlSn = CurrentHouse.tlSn,
  1022. wellSn = CurrentWell,
  1023. });
  1024. return AppData.Instance.HttpHelper.WellUpdateApi(body);
  1025. }
  1026. catch (Exception ex)
  1027. {
  1028. ExLog(ex, "SetWellMotorPosition");
  1029. return false;
  1030. }
  1031. }
  1032. /// <summary>
  1033. /// 保存自动对焦起点
  1034. /// </summary>
  1035. /// <returns></returns>
  1036. public bool SetWellAutoFocus()
  1037. {
  1038. try
  1039. {
  1040. if (CurrentHouse == null)
  1041. {
  1042. AddMessageInfo("获取舱室信息失败");
  1043. }
  1044. string body = JsonConvert.SerializeObject(new
  1045. {
  1046. verticalMotorPosition = CurrentVer,
  1047. houseSn = CurrentHouse.houseSn,
  1048. tlSn = CurrentHouse.tlSn,
  1049. wellSn = CurrentWell,
  1050. });
  1051. return AppData.Instance.HttpHelper.WellUpdateApi(body);
  1052. }
  1053. catch (Exception ex)
  1054. {
  1055. ExLog(ex, "SetWellAutoFocus");
  1056. return false;
  1057. }
  1058. }
  1059. #endregion
  1060. private void ComBin_ExceptionLogEvent(Exception exception, string arg2, string arg3, LogEnum @enum)
  1061. {
  1062. AppData.Instance.LogHelper.ExceptionLog(exception, $"{arg2}{arg3}", @enum);
  1063. }
  1064. private void ComBin_ErrorLogEvent(string arg1, LogEnum @enum)
  1065. {
  1066. AppData.Instance.LogHelper.TLLog(arg1, @enum);
  1067. }
  1068. private void ComBin_CommandLogEvent(int arg1, DateTime time, string arg3, LogEnum @enum)
  1069. {
  1070. AppData.Instance.LogHelper.HouseLog(arg1, time, arg3, @enum);
  1071. }
  1072. public void AddMessageInfo(string mess)
  1073. {
  1074. MessageEvent?.Invoke(mess);
  1075. }
  1076. public void AddPic(string picFullName)
  1077. {
  1078. AddPicEvent?.Invoke(picFullName, CurrentWell, CurrentFocal);
  1079. }
  1080. #region 场景A 一键全自动标定(经 control 协作,D2-02-T3.4 重构)
  1081. /// <summary>
  1082. /// 一键全自动标定(D2-02-T3.4 重构为"经 control 协作")。
  1083. /// 旧实现:operate 本地 new CalibrationEngine 逐 well 跑 + CalibrationStore 写 JSON/scene0(已停用)。
  1084. /// 新实现:operate 仅发 /debug/calibrate/start(经 CalibrationClient,复用 acquire 的 sessionId) →
  1085. /// 起轮询 /debug/calibrate/progress(~800ms) 把每孔状态映射到 16 格 UI(合格绿/伪峰橙/失败红 + FocusZ/峰比/偏移)。
  1086. /// 标定由 control 协作端真正执行(持真硬件)、scene=0 基准由 control 端落库。
  1087. /// 前提:ComHouseInit 已成功 acquire(CurrentSessionId 非空、_calibClient 已构造)。
  1088. /// 中止:StopCalibrate → /debug/calibrate/stop + 停轮询。
  1089. ///
  1090. /// ⚠ 待验证(compile-pending,operate.exe 卡死未编译):start/progress/stop 协作往返、16 格映射、合格判定一致。
  1091. /// </summary>
  1092. /// <param name="wells">勾选的 well 列表(空/null 视为全 16 well)。</param>
  1093. public async Task OneClickCalibrate(IEnumerable<int> wells = null)
  1094. {
  1095. if (IsCalibrating)
  1096. {
  1097. AddMessageInfo("[一键标定]已在标定中,请勿重复触发");
  1098. return;
  1099. }
  1100. if (_calibClient == null || string.IsNullOrEmpty(CurrentSessionId))
  1101. {
  1102. AddMessageInfo("[一键标定]未建立调试会话(请先初始化舱室借硬件),无法发起协作标定");
  1103. return;
  1104. }
  1105. if (CurrentHouse == null)
  1106. {
  1107. AddMessageInfo("[一键标定]未获取到舱室信息");
  1108. return;
  1109. }
  1110. // 勾选 well:未传则默认 16 well;去重、按序、限定 1-16。
  1111. var wellList = (wells ?? Enumerable.Range(1, 16))
  1112. .Where(w => w >= 1 && w <= 16).Distinct().OrderBy(w => w).ToList();
  1113. if (wellList.Count == 0) wellList = Enumerable.Range(1, 16).ToList();
  1114. IsCalibrating = true;
  1115. IsStopCalibrate = false;
  1116. try
  1117. {
  1118. // M8-P3b:一键标定发起为关键命令入口,记一条操作日志(start 同步发起;异步轮询单独不再串 scope,
  1119. // 避免 using scope 在方法返回即 Dispose 后被后台轮询误用)。
  1120. using (var _opScope = Aivfo.OperationLog.OperationLogger.Begin("对焦调试", "一键标定发起(协作)", houseSn: CurrentHouseId))
  1121. {
  1122. try { _opScope.Input(new { houseSn = CurrentHouseId, wells = wellList.ToArray() }); } catch { }
  1123. ResetCalibResults(wellList);
  1124. // D2-02-T3.4:标定由 control 协作端执行(scene=0 落库由 control 端处理)。
  1125. // operate 仅发 start + 轮询进度刷新 16 格 UI,不再 operate 本地 new CalibrationEngine/CalibrationStore。
  1126. var r = await _calibClient.StartAsync(wellList);
  1127. if (!r.Ok)
  1128. {
  1129. IsCalibrating = false;
  1130. AddMessageInfo($"[一键标定]发起失败:{r.Code}/{r.Error}");
  1131. try { _opScope.Fail($"start 失败:{r.Code}/{r.Error}"); } catch { }
  1132. return;
  1133. }
  1134. try { _opScope.Output(new { started = true }).Success(); } catch { }
  1135. }
  1136. AddMessageInfo($"[一键标定]已发起(control 协作):舱{CurrentHouse.houseSn} 共 {wellList.Count} well,开始轮询进度...");
  1137. // 起轮询任务,把 control 端进度映射到 16 格 UI;IsRunning 转 false 即停。
  1138. StartCalibPolling();
  1139. }
  1140. catch (Exception ex)
  1141. {
  1142. IsCalibrating = false;
  1143. ExLog(ex, "OneClickCalibrate");
  1144. AddMessageInfo($"[一键标定]整体异常:{ex.Message}");
  1145. }
  1146. }
  1147. /// <summary>
  1148. /// D2-02-T3.4 单孔重标:经 control 协作端对该 well 重新标定一次,并起轮询刷新该格。
  1149. /// </summary>
  1150. public async Task RecalibrateWell(int wellSn)
  1151. {
  1152. if (_calibClient == null || string.IsNullOrEmpty(CurrentSessionId))
  1153. {
  1154. AddMessageInfo("[重标]未建立调试会话,无法重标");
  1155. return;
  1156. }
  1157. if (IsCalibrating)
  1158. {
  1159. AddMessageInfo("[重标]批量标定进行中,请先中止或等待结束");
  1160. return;
  1161. }
  1162. if (wellSn < 1 || wellSn > 16)
  1163. {
  1164. AddMessageInfo("[重标]well 只能为 1-16");
  1165. return;
  1166. }
  1167. try
  1168. {
  1169. IsCalibrating = true;
  1170. IsStopCalibrate = false;
  1171. UpdateCalibResult(wellSn, item => { item.State = WellCalibState.Running; item.Note = "重标中..."; });
  1172. var r = await _calibClient.RecalibrateAsync(wellSn);
  1173. if (!r.Ok)
  1174. {
  1175. IsCalibrating = false;
  1176. AddMessageInfo($"[重标]well{wellSn} 发起失败:{r.Code}/{r.Error}");
  1177. return;
  1178. }
  1179. AddMessageInfo($"[重标]well{wellSn} 已发起,轮询进度...");
  1180. StartCalibPolling();
  1181. }
  1182. catch (Exception ex)
  1183. {
  1184. IsCalibrating = false;
  1185. ExLog(ex, "RecalibrateWell");
  1186. AddMessageInfo($"[重标]well{wellSn} 异常:{ex.Message}");
  1187. }
  1188. }
  1189. /// <summary>工程师中止一键标定:通知 control 停标,停本地轮询。</summary>
  1190. public void StopCalibrate()
  1191. {
  1192. IsStopCalibrate = true;
  1193. AddMessageInfo("[一键标定]收到中止请求,通知 control 停止...");
  1194. var calib = _calibClient;
  1195. if (calib != null)
  1196. {
  1197. Task.Run(async () =>
  1198. {
  1199. try { await calib.StopAsync(); } catch (Exception ex) { ExLog(ex, "StopCalibrate.StopAsync"); }
  1200. });
  1201. }
  1202. // 轮询任务读到 IsRunning=false 后会自停;此处也主动停一次兜底。
  1203. StopCalibPolling();
  1204. }
  1205. /// <summary>
  1206. /// 起标定进度轮询(~800ms 一次):调 control /debug/calibrate/progress,
  1207. /// 把每孔 WellCalibProgressDto(State 数字枚举)映射到 16 格 WellCalibUiItem。
  1208. /// IsRunning 转 false(或会话失效返回 null)即停轮询并复位 IsCalibrating。
  1209. /// 同一时刻只跑一个轮询任务(先停旧的)。
  1210. /// </summary>
  1211. private void StartCalibPolling()
  1212. {
  1213. StopCalibPolling();
  1214. var cts = new System.Threading.CancellationTokenSource();
  1215. _calibPollCts = cts;
  1216. var token = cts.Token;
  1217. var calib = _calibClient;
  1218. Task.Run(async () =>
  1219. {
  1220. try
  1221. {
  1222. while (!token.IsCancellationRequested)
  1223. {
  1224. var dto = await calib.PollProgressAsync();
  1225. if (token.IsCancellationRequested) break;
  1226. if (dto == null)
  1227. {
  1228. // 会话失效/无进度:停轮询(会话失效另由 DebugSessionClient.OnSessionExpired 提示)。
  1229. AddMessageInfo("[一键标定]进度查询无结果(会话可能已失效),停止轮询");
  1230. break;
  1231. }
  1232. MapProgressToUi(dto);
  1233. if (!dto.IsRunning)
  1234. {
  1235. int okCount = CalibResults.Count(x => x.State == WellCalibState.Qualified);
  1236. AddMessageInfo($"[一键标定]结束:合格 {okCount}/{dto.Total}(scene=0 基准由 control 协作端落库)");
  1237. break;
  1238. }
  1239. await Task.Delay(800, token);
  1240. }
  1241. }
  1242. catch (TaskCanceledException) { /* 主动停 */ }
  1243. catch (Exception ex)
  1244. {
  1245. ExLog(ex, "CalibPolling");
  1246. AddMessageInfo($"[一键标定]轮询异常:{ex.Message}");
  1247. }
  1248. finally
  1249. {
  1250. IsCalibrating = false;
  1251. }
  1252. }, token);
  1253. }
  1254. /// <summary>停标定进度轮询(取消轮询任务)。幂等。</summary>
  1255. private void StopCalibPolling()
  1256. {
  1257. var cts = _calibPollCts;
  1258. _calibPollCts = null;
  1259. if (cts != null) { try { cts.Cancel(); } catch { } try { cts.Dispose(); } catch { } }
  1260. }
  1261. /// <summary>把 control 进度 DTO 的每孔状态映射到 16 格 UI(State 为数字枚举:0待标/1标定中/2合格/3伪峰/4失败)。</summary>
  1262. private void MapProgressToUi(CalibProgressDto dto)
  1263. {
  1264. if (dto?.Wells == null) return;
  1265. foreach (var w in dto.Wells)
  1266. {
  1267. var well = w; // 闭包捕获
  1268. UpdateCalibResult(well.WellSn, item =>
  1269. {
  1270. item.State = (WellCalibState)well.State; // 0..4 与 operate 端枚举顺序一致
  1271. item.FocusZ = well.FocusZ;
  1272. item.Exposure = well.Exposure;
  1273. item.PeakRatio = well.PeakRatio;
  1274. item.CenterOffsetPct = well.CenterOffsetPct;
  1275. item.CircleFound = well.CircleFound;
  1276. item.Note = string.IsNullOrEmpty(well.Note)
  1277. ? StateNote((WellCalibState)well.State, well.FocusZ, well.PeakRatio)
  1278. : well.Note;
  1279. });
  1280. }
  1281. }
  1282. private static string StateNote(WellCalibState st, int focusZ, double peakRatio) => st switch
  1283. {
  1284. WellCalibState.Pending => "待标定",
  1285. WellCalibState.Running => "标定中...",
  1286. WellCalibState.Qualified => $"合格 Z={focusZ} 峰比={peakRatio:F2}",
  1287. WellCalibState.FakePeak => $"伪峰 Z={focusZ} 峰比={peakRatio:F2}",
  1288. WellCalibState.Failed => "失败",
  1289. _ => ""
  1290. };
  1291. private void ResetCalibResults(List<int> wells)
  1292. {
  1293. void build()
  1294. {
  1295. CalibResults.Clear();
  1296. foreach (var w in wells)
  1297. CalibResults.Add(new WellCalibUiItem { Well = w, State = WellCalibState.Pending, Note = "待标定" });
  1298. }
  1299. // 集合改动需在 UI 线程(ObservableCollection 绑定)。
  1300. var disp = System.Windows.Application.Current?.Dispatcher;
  1301. if (disp != null && !disp.CheckAccess()) disp.Invoke(build); else build();
  1302. }
  1303. private void UpdateCalibResult(int well, Action<WellCalibUiItem> mutate)
  1304. {
  1305. void apply()
  1306. {
  1307. var item = CalibResults.FirstOrDefault(x => x.Well == well);
  1308. if (item == null)
  1309. {
  1310. item = new WellCalibUiItem { Well = well };
  1311. CalibResults.Add(item);
  1312. }
  1313. mutate(item);
  1314. }
  1315. var disp = System.Windows.Application.Current?.Dispatcher;
  1316. if (disp != null && !disp.CheckAccess()) disp.Invoke(apply); else apply();
  1317. }
  1318. #endregion
  1319. #region M2-07 对焦后手动微调拍摄层(层数/层间距/下移)持久化 well 级
  1320. /// <summary>
  1321. /// M2-07 手调"实际拍摄层数"(well 级覆盖)。空字符串=留空继承设备级(保存写 null)。
  1322. /// View TextBox 双向绑定;校验在保存/预览时做(层数≥1)。
  1323. /// </summary>
  1324. [ObservableProperty] private string manualLayerCount = "";
  1325. /// <summary>
  1326. /// M2-07 手调"实际拍摄层间距脉冲"(well 级覆盖)。空=继承设备级(写 null)。校验:>0。
  1327. /// </summary>
  1328. [ObservableProperty] private string manualLayerSpacing = "";
  1329. /// <summary>
  1330. /// M2-07 手调"对焦起点下移层数"(复用 move_down_layer)。空=继承设备级。
  1331. /// 校验:≥0 且 &lt;层数(下移层须落在拍摄范围内,§2.4 清晰层=第 down 层)。
  1332. /// </summary>
  1333. [ObservableProperty] private string manualMoveDown = "";
  1334. /// <summary>
  1335. /// M2-07 实时预览各层绝对 Z 位置(调 M2-02 ComputeLayerPositions 生成,关联 V-045)。
  1336. /// View 绑定此集合显示 N 层位置列表,让工程师看到手调效果。
  1337. /// </summary>
  1338. public ObservableCollection<LayerPreviewItem> LayerPreview { get; } = new ObservableCollection<LayerPreviewItem>();
  1339. /// <summary>
  1340. /// M2-07 预览/手调锚点 well(默认随水平电机当前 well / 一键标定取 CurrentWell)。
  1341. /// </summary>
  1342. [ObservableProperty] private int manualTuneWell = 1;
  1343. /// <summary>
  1344. /// 取该 well 当前生效的"实际拍摄层"配置(well 级覆盖优先,空则回退设备级),
  1345. /// 回填三个手调输入框 + 触发一次预览。供"载入当前值"按钮调用。
  1346. /// </summary>
  1347. public void LoadManualLayerSetting(int well)
  1348. {
  1349. ManualTuneWell = well;
  1350. var ws = houseWellSettingList.FirstOrDefault(x => x.houseSn == CurrentHouseId && x.wellSn == well);
  1351. // well 级覆盖非空显示 well 值,否则显示继承的设备级值作占位(§2.5 就近优先)。
  1352. int? wellCount = ws?.focusLayerCount;
  1353. int? wellSpacing = ws?.focusLayerSpacingPulse;
  1354. // 下移复用 moveDownLayer(well 级为非空 int 列;0 视为有效覆盖值)。
  1355. int? wellDown = ws != null ? (int?)ws.moveDownLayer : null;
  1356. ManualLayerCount = (wellCount ?? tLSetting?.focusLayerCount)?.ToString() ?? "";
  1357. ManualLayerSpacing = (wellSpacing ?? tLSetting?.focusLayerSpacingPulse)?.ToString() ?? "";
  1358. ManualMoveDown = (wellDown ?? tLSetting?.focusLayerDown)?.ToString() ?? "";
  1359. PreviewManualLayers();
  1360. }
  1361. /// <summary>
  1362. /// 取该 well 最近标定的 FocusZ 作预览锚点(M2-05 一键标定结果 CalibResults 优先;
  1363. /// 回退 ccdPhoto 的 clearestPosition 即 scene0/1 库下发的清晰位置)。
  1364. /// 返回 null 表示无标定可用(须提示先标定)。
  1365. /// </summary>
  1366. private int? GetPreviewFocusZ(int well)
  1367. {
  1368. var calib = CalibResults.FirstOrDefault(x => x.Well == well
  1369. && (x.State == WellCalibState.Qualified || x.State == WellCalibState.FakePeak));
  1370. if (calib != null && calib.FocusZ > 0) return calib.FocusZ;
  1371. // 回退:调试页加载的清晰位置(scene0/1 库值 clearestPosition)。
  1372. var cc = ccdPhoto.FirstOrDefault(x => x.houseSn == CurrentHouseId && x.wellSn == well);
  1373. if (cc != null && cc.clearestPosition > 0) return cc.clearestPosition;
  1374. return null;
  1375. }
  1376. /// <summary>
  1377. /// 解析三个手调输入框(空=继承设备级取回退值),返回有效 (count,spacing,down) 或 null(非法/缺失)。
  1378. /// validateMsg 携带校验失败原因。
  1379. /// </summary>
  1380. private (int count, int spacing, int down)? ResolveEffectiveTune(out string validateMsg)
  1381. {
  1382. validateMsg = null;
  1383. // 解析层数:空→设备级回退;非空→必须 int。
  1384. int? count;
  1385. if (string.IsNullOrWhiteSpace(ManualLayerCount)) count = tLSetting?.focusLayerCount;
  1386. else if (int.TryParse(ManualLayerCount.Trim(), out int c)) count = c;
  1387. else { validateMsg = "层数只能输入整数"; return null; }
  1388. int? spacing;
  1389. if (string.IsNullOrWhiteSpace(ManualLayerSpacing)) spacing = tLSetting?.focusLayerSpacingPulse;
  1390. else if (int.TryParse(ManualLayerSpacing.Trim(), out int s)) spacing = s;
  1391. else { validateMsg = "层间距只能输入整数"; return null; }
  1392. int? down;
  1393. if (string.IsNullOrWhiteSpace(ManualMoveDown)) down = tLSetting?.focusLayerDown;
  1394. else if (int.TryParse(ManualMoveDown.Trim(), out int d)) down = d;
  1395. else { validateMsg = "下移层数只能输入整数"; return null; }
  1396. if (!count.HasValue) { validateMsg = "层数未配置(设备级也为空),请填层数或先初始化设备级"; return null; }
  1397. if (!spacing.HasValue) { validateMsg = "层间距未配置(设备级也为空),请填层间距或先初始化设备级(§2.5 不兜底)"; return null; }
  1398. if (!down.HasValue) { validateMsg = "下移层数未配置(设备级也为空),请填下移层数"; return null; }
  1399. // 校验:层数≥1、间距>0、下移≥0 且 <层数(下移层须落在拍摄范围内)。
  1400. if (count.Value < 1) { validateMsg = "层数必须 ≥ 1"; return null; }
  1401. if (spacing.Value <= 0) { validateMsg = "层间距必须 > 0"; return null; }
  1402. if (down.Value < 0) { validateMsg = "下移层数必须 ≥ 0"; return null; }
  1403. if (down.Value >= count.Value) { validateMsg = $"下移层数必须 < 层数({count.Value}),否则清晰层落在拍摄范围外"; return null; }
  1404. return (count.Value, spacing.Value, down.Value);
  1405. }
  1406. /// <summary>
  1407. /// M2-07 实时预览:用该 well 标定 FocusZ + 当前手调值,调 M2-02
  1408. /// ComputeLayerPositions(focusZ, cfg, pulseMax) 生成各层绝对 Z,刷新 LayerPreview(关联 V-045)。
  1409. /// 无标定锚点 → 清空预览并提示先标定;校验非法 → 清空预览并提示。
  1410. /// </summary>
  1411. public void PreviewManualLayers()
  1412. {
  1413. try
  1414. {
  1415. var focusZ = GetPreviewFocusZ(ManualTuneWell);
  1416. if (!focusZ.HasValue)
  1417. {
  1418. SetLayerPreview(null);
  1419. AddMessageInfo($"[手调拍摄层]well{ManualTuneWell} 无标定结果,请先对该 well 标定(或确认已下发清晰位置)再预览");
  1420. return;
  1421. }
  1422. var eff = ResolveEffectiveTune(out string msg);
  1423. if (eff == null)
  1424. {
  1425. SetLayerPreview(null);
  1426. AddMessageInfo($"[手调拍摄层]预览失败:{msg}");
  1427. return;
  1428. }
  1429. var cfg = new FocusLayerConfig
  1430. {
  1431. LayerCount = eff.Value.count,
  1432. LayerSpacingPulse = eff.Value.spacing,
  1433. LayerDown = eff.Value.down,
  1434. };
  1435. int pulseMax = tLSetting != null ? tLSetting.verticalMotorPulseMax : 0;
  1436. int[] positions = PhotoLayerCalculator.ComputeLayerPositions(focusZ.Value, cfg, pulseMax);
  1437. var items = new List<LayerPreviewItem>();
  1438. for (int i = 0; i < positions.Length; i++)
  1439. {
  1440. items.Add(new LayerPreviewItem
  1441. {
  1442. LayerIndex = i,
  1443. ZPulse = positions[i],
  1444. IsFocusLayer = (i == eff.Value.down), // 第 down 层 = 清晰层(FocusZ 锚点)
  1445. });
  1446. }
  1447. SetLayerPreview(items);
  1448. AddMessageInfo($"[手调拍摄层]well{ManualTuneWell} 预览:锚点FocusZ={focusZ.Value} 层数={eff.Value.count} " +
  1449. $"间距={eff.Value.spacing} 下移={eff.Value.down} → 第0层Z={positions[0]} 第{positions.Length - 1}层Z={positions[positions.Length - 1]}");
  1450. }
  1451. catch (Exception ex)
  1452. {
  1453. SetLayerPreview(null);
  1454. ExLog(ex, "PreviewManualLayers");
  1455. AddMessageInfo($"[手调拍摄层]预览异常:{ex.Message}");
  1456. }
  1457. }
  1458. /// <summary>
  1459. /// M2-07 保存为该 well 默认:校验通过后,把手调值写 house_well_setting well 级覆盖
  1460. /// (focus_layer_spacing_pulse/focus_layer_count + 复用 move_down_layer)。
  1461. /// 复用现有 operate 端 well 设置保存通道 HttpHelper.WellUpdateApi(同 SetWellMotorPosition/SetWellAutoFocus),
  1462. /// 走 /api/tl/control/setting/house/well/update。留空字段=继承设备级(写 null)。
  1463. /// 下次该 well 经 §2.5 就近优先(PhotoLayerCalculator.Resolve)沿用 well 覆盖值。
  1464. /// 返回 true=保存成功。
  1465. /// </summary>
  1466. public bool SaveManualLayerTune()
  1467. {
  1468. try
  1469. {
  1470. if (CurrentHouse == null)
  1471. {
  1472. AddMessageInfo("[手调拍摄层]未获取到舱室信息");
  1473. return false;
  1474. }
  1475. // M8-G3-1:保存手调拍摄层为"本地校验/计算 + HTTP 持久化 + 内存同步"打包的关键业务操作,
  1476. // 用 Begin scope 给一个父操作名(统一 traceId 串联其内的 WellUpdateApi HTTP 埋点;module=对焦调试)。
  1477. using var _op = Aivfo.OperationLog.OperationLogger.Begin("对焦调试", "保存手调拍摄层设置",
  1478. houseSn: CurrentHouseId);
  1479. // 校验:层数≥1、间距>0、下移≥0 且 <层数;非法不保存。
  1480. var eff = ResolveEffectiveTune(out string msg);
  1481. if (eff == null)
  1482. {
  1483. AddMessageInfo($"[手调拍摄层]保存被拦截(非法值):{msg}");
  1484. try { _op.Output(new { rejected = msg }).Fail("校验未通过:" + msg); } catch { }
  1485. return false;
  1486. }
  1487. // 留空字段=继承设备级 → 写 null(well 级覆盖留空,§2.5)。非空字段写实际值。
  1488. int? wellCount = string.IsNullOrWhiteSpace(ManualLayerCount) ? (int?)null : int.Parse(ManualLayerCount.Trim());
  1489. int? wellSpacing = string.IsNullOrWhiteSpace(ManualLayerSpacing) ? (int?)null : int.Parse(ManualLayerSpacing.Trim());
  1490. // 下移复用 move_down_layer(库列非空);留空时回退取生效值(eff.down)写回,不破坏旧列语义。
  1491. int wellMoveDown = string.IsNullOrWhiteSpace(ManualMoveDown) ? eff.Value.down : int.Parse(ManualMoveDown.Trim());
  1492. try { _op.Input(new { houseSn = CurrentHouseId, well = ManualTuneWell, wellCount, wellSpacing, wellMoveDown }); } catch { }
  1493. // 复用现有 well 设置保存通道:与 SetWellMotorPosition/SetWellAutoFocus 同一 WellUpdateApi。
  1494. // 后端按 tlSn/houseSn/wellSn 定位 house_well_setting 行做部分更新(仅本次携带的字段)。
  1495. string body = JsonConvert.SerializeObject(new
  1496. {
  1497. tlSn = CurrentHouse.tlSn,
  1498. houseSn = CurrentHouse.houseSn,
  1499. wellSn = ManualTuneWell,
  1500. focusLayerSpacingPulse = wellSpacing, // null=继承设备级
  1501. focusLayerCount = wellCount, // null=继承设备级
  1502. moveDownLayer = wellMoveDown, // 复用既有列(下移)
  1503. });
  1504. bool ok = AppData.Instance.HttpHelper.WellUpdateApi(body);
  1505. if (!ok)
  1506. {
  1507. AddMessageInfo("[手调拍摄层]保存失败(接口返回失败)");
  1508. try { _op.Fail("WellUpdateApi 返回失败"); } catch { }
  1509. return false;
  1510. }
  1511. // 本地内存同步,使"下次该 well 沿用"在不重载设置时也即时生效(预览/取数一致)。
  1512. var ws = houseWellSettingList.FirstOrDefault(x => x.houseSn == CurrentHouseId && x.wellSn == ManualTuneWell);
  1513. if (ws != null)
  1514. {
  1515. ws.focusLayerCount = wellCount;
  1516. ws.focusLayerSpacingPulse = wellSpacing;
  1517. ws.moveDownLayer = wellMoveDown;
  1518. }
  1519. AddMessageInfo($"[手调拍摄层]well{ManualTuneWell} 已存为默认:层数={(wellCount?.ToString() ?? "继承")} " +
  1520. $"间距={(wellSpacing?.ToString() ?? "继承")} 下移={wellMoveDown}(写 house_well_setting well 级覆盖,留空继承设备级)");
  1521. try { _op.Output(new { ok = true }).Success(); } catch { }
  1522. return true;
  1523. }
  1524. catch (Exception ex)
  1525. {
  1526. ExLog(ex, "SaveManualLayerTune");
  1527. AddMessageInfo($"[手调拍摄层]保存异常:{ex.Message}");
  1528. return false;
  1529. }
  1530. }
  1531. private void SetLayerPreview(List<LayerPreviewItem> items)
  1532. {
  1533. void build()
  1534. {
  1535. LayerPreview.Clear();
  1536. if (items != null)
  1537. foreach (var it in items) LayerPreview.Add(it);
  1538. }
  1539. var disp = System.Windows.Application.Current?.Dispatcher;
  1540. if (disp != null && !disp.CheckAccess()) disp.Invoke(build); else build();
  1541. }
  1542. #endregion
  1543. #region D2-02-T3.5 保存 per-well 对焦搜索范围(半幅)
  1544. /// <summary>
  1545. /// 当前编辑的 well 级"水平搜索半幅"(围绕 horizontalMotorPosition)。空字符串=留空继承设备级(保存写 null)。
  1546. /// View TextBox 双向绑定;校验在保存时做(非空须为 ≥0 整数)。
  1547. /// </summary>
  1548. [ObservableProperty] private string currentHFocusRange = "";
  1549. /// <summary>
  1550. /// 当前编辑的 well 级"垂直搜索半幅"(围绕 eepromClearPosition/清晰位)。空=继承设备级(写 null)。校验:≥0。
  1551. /// </summary>
  1552. [ObservableProperty] private string currentVFocusRange = "";
  1553. /// <summary>
  1554. /// 取该 well 当前 well 级半幅覆盖值回填两个输入框(空=继承设备级,显示空占位)。供"载入半幅"按钮调用。
  1555. /// 复用 ManualTuneWell 作为锚点 well(与手调拍摄层同一选定 well)。
  1556. /// </summary>
  1557. public void LoadWellFocusRange(int well)
  1558. {
  1559. ManualTuneWell = well;
  1560. var ws = houseWellSettingList.FirstOrDefault(x => x.houseSn == CurrentHouseId && x.wellSn == well);
  1561. CurrentHFocusRange = ws?.horizontalFocusRange?.ToString() ?? "";
  1562. CurrentVFocusRange = ws?.verticalFocusRange?.ToString() ?? "";
  1563. AddMessageInfo($"[对焦半幅]已载入 well{well} 当前覆盖:水平={(ws?.horizontalFocusRange?.ToString() ?? "继承")} 垂直={(ws?.verticalFocusRange?.ToString() ?? "继承")}");
  1564. }
  1565. /// <summary>
  1566. /// D2-02-T3.5 保存该 well 对焦搜索半幅:校验通过后写 house_well_setting well 级覆盖
  1567. /// (horizontal_focus_range/vertical_focus_range)。留空字段=继承设备级(写 null)。
  1568. /// 复用现有 well 设置保存通道 HttpHelper.WellUpdateApi(同 SetWellMotorPosition/SaveManualLayerTune),
  1569. /// 走 /well/update;后端 well/update 已支持这两列(Java HouseWellSettingUpdate.horizontalFocusRange/verticalFocusRange)。
  1570. /// 字段名与 Java DTO 完全一致:horizontalFocusRange / verticalFocusRange。
  1571. /// 返回 true=保存成功。
  1572. /// </summary>
  1573. public bool SaveWellFocusRange()
  1574. {
  1575. try
  1576. {
  1577. if (CurrentHouse == null)
  1578. {
  1579. AddMessageInfo("[对焦半幅]未获取到舱室信息");
  1580. return false;
  1581. }
  1582. if (ManualTuneWell < 1 || ManualTuneWell > 16)
  1583. {
  1584. AddMessageInfo("[对焦半幅]well 只能为 1-16");
  1585. return false;
  1586. }
  1587. // 校验:非空须为 ≥0 整数;留空=继承设备级(写 null)。
  1588. int? hRange;
  1589. if (string.IsNullOrWhiteSpace(CurrentHFocusRange)) hRange = null;
  1590. else if (int.TryParse(CurrentHFocusRange.Trim(), out int hv) && hv >= 0) hRange = hv;
  1591. else { AddMessageInfo("[对焦半幅]水平半幅只能输入 ≥0 整数(留空=继承设备级)"); return false; }
  1592. int? vRange;
  1593. if (string.IsNullOrWhiteSpace(CurrentVFocusRange)) vRange = null;
  1594. else if (int.TryParse(CurrentVFocusRange.Trim(), out int vv) && vv >= 0) vRange = vv;
  1595. else { AddMessageInfo("[对焦半幅]垂直半幅只能输入 ≥0 整数(留空=继承设备级)"); return false; }
  1596. // M8 埋点:保存对焦半幅为关键业务操作(统一 traceId 串其内 WellUpdateApi HTTP 埋点)。
  1597. using var _op = Aivfo.OperationLog.OperationLogger.Begin("对焦调试", "保存对焦搜索半幅",
  1598. houseSn: CurrentHouseId);
  1599. try { _op.Input(new { houseSn = CurrentHouseId, well = ManualTuneWell, horizontalFocusRange = hRange, verticalFocusRange = vRange }); } catch { }
  1600. // body 字段名与 Java HouseWellSettingUpdate 完全一致;留空=null 清空继承设备级(与 SaveManualLayerTune 一致)。
  1601. string body = JsonConvert.SerializeObject(new
  1602. {
  1603. tlSn = CurrentHouse.tlSn,
  1604. houseSn = CurrentHouse.houseSn,
  1605. wellSn = ManualTuneWell,
  1606. horizontalFocusRange = hRange, // null=继承设备级 focus_h_range_default
  1607. verticalFocusRange = vRange, // null=继承设备级 focus_v_range_default
  1608. });
  1609. bool ok = AppData.Instance.HttpHelper.WellUpdateApi(body);
  1610. if (!ok)
  1611. {
  1612. AddMessageInfo("[对焦半幅]保存失败(接口返回失败)");
  1613. try { _op.Fail("WellUpdateApi 返回失败"); } catch { }
  1614. return false;
  1615. }
  1616. // 本地内存同步,使取数一致(不重载设置即生效)。
  1617. var ws = houseWellSettingList.FirstOrDefault(x => x.houseSn == CurrentHouseId && x.wellSn == ManualTuneWell);
  1618. if (ws != null)
  1619. {
  1620. ws.horizontalFocusRange = hRange;
  1621. ws.verticalFocusRange = vRange;
  1622. }
  1623. AddMessageInfo($"[对焦半幅]well{ManualTuneWell} 已保存:水平={(hRange?.ToString() ?? "继承")} 垂直={(vRange?.ToString() ?? "继承")}(写 house_well_setting well 级覆盖,留空继承设备级)");
  1624. try { _op.Output(new { ok = true }).Success(); } catch { }
  1625. return true;
  1626. }
  1627. catch (Exception ex)
  1628. {
  1629. ExLog(ex, "SaveWellFocusRange");
  1630. AddMessageInfo($"[对焦半幅]保存异常:{ex.Message}");
  1631. return false;
  1632. }
  1633. }
  1634. #endregion
  1635. }
  1636. }