HouseDebugPageViewModel.cs 65 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510
  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_Services;
  9. using IvfTl.Hardware;
  10. using IvfTl.Hardware.Impl;
  11. using IvfTl.AutoFocus.Calib;
  12. using IvfTl.AutoFocus.Layout;
  13. using IvfTl.AutoFocus.Storage;
  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. /// <summary>
  54. /// 当前housesn
  55. /// </summary>
  56. public int CurrentHouseId { get; set; } = 1;
  57. /// <summary>
  58. /// 当前ccdID
  59. /// </summary>
  60. public int CurrentCCDId { get; set; } = 0;
  61. /// <summary>
  62. /// 所有舱室
  63. /// </summary>
  64. public List<HouseInfo> HouseList { get; set; } = new List<HouseInfo>();
  65. /// <summary>
  66. /// 仪器设置
  67. /// </summary>
  68. public TLSetting tLSetting { get; set; } = new TLSetting();
  69. /// <summary>
  70. /// 自动对焦和拍照位置
  71. /// </summary>
  72. public List<HousePhotographLocation> ccdPhoto = new List<HousePhotographLocation>();
  73. /// <summary>
  74. /// 水平电机位置
  75. /// </summary>
  76. public List<HouseWellSetting> houseWellSettingList = new List<HouseWellSetting>();
  77. [ObservableProperty]
  78. private ObservableCollection<string> messageInfoList = new ObservableCollection<string>();
  79. [ObservableProperty]
  80. private decimal temperature = 0m;
  81. [ObservableProperty]
  82. private decimal pressure = 0m;
  83. [ObservableProperty]
  84. private string doorState = null;
  85. [ObservableProperty]
  86. private string ledState = null;
  87. [ObservableProperty]
  88. private int currentWell = 0;
  89. [ObservableProperty]
  90. private int currentFocal = 0;
  91. /// <summary>
  92. /// 结束抓图
  93. /// </summary>
  94. public bool IsStop { get; set; } = false;
  95. /// <summary>
  96. /// M2-05 一键标定中止标志(工程师可中止;每 well 间检查)。
  97. /// </summary>
  98. public bool IsStopCalibrate { get; set; } = false;
  99. /// <summary>
  100. /// M2-05 一键标定是否进行中(UI 据此禁用重复触发)。
  101. /// </summary>
  102. [ObservableProperty]
  103. private bool isCalibrating = false;
  104. /// <summary>
  105. /// M2-05 场景A 一键标定 16 well 实时结果(合格绿/伪峰红,含 FocusZ/峰比/偏移)。
  106. /// View 绑定此集合做 4x4 实时呈现(沿用调试页内呈现,不另开 CalibWindow)。
  107. /// </summary>
  108. public ObservableCollection<WellCalibUiItem> CalibResults { get; } = new ObservableCollection<WellCalibUiItem>();
  109. /// <summary>
  110. /// 垂直电机当前位置
  111. /// </summary>
  112. [ObservableProperty]
  113. private int currentVer = 0;
  114. /// <summary>
  115. /// 水平电机当前位置
  116. /// </summary>
  117. [ObservableProperty]
  118. private int currentHor = 0;
  119. [ObservableProperty]
  120. private HouseInfo currentHouse = null;
  121. [ObservableProperty]
  122. private int houseVentTimeE = 0;
  123. public HouseDebugPageViewModel()
  124. {
  125. //HouseList = AppData.Instance.HttpHelper.GetSettingHouseApi(AppData.Instance.TlSn);
  126. //CurrentHouse = HouseList.FirstOrDefault(x => x.houseSn == 1);
  127. }
  128. private void ExLog(Exception ex, string name)
  129. {
  130. AppData.Instance.LogHelper.ExceptionLog(ex, $"HouseDebugPageViewModel.{name}", LogEnum.RunException);
  131. }
  132. private void ErrorLog(string message, LogEnum logType)
  133. {
  134. AppData.Instance.LogHelper.TLLog($"HouseDebugPageViewModel.{message}", logType);
  135. }
  136. public void Start(ref string errora)
  137. {
  138. try
  139. {
  140. SerialBin serialBin = new SerialBin();
  141. serialBin.TLLogEvent += AppData.Instance.LogHelper.TLLog;
  142. serialBin.ExceptionLogEvent += AppData.Instance.LogHelper.ExceptionLog;
  143. serialBin.HouseLogEvent += AppData.Instance.LogHelper.HouseLog;
  144. var errorList = serialBin.UpdataCamera();
  145. AppData.Instance.LogHelper.TLLog($"ccdidsn:{JsonConvert.SerializeObject(serialBin.CCDidSn)}", LogEnum.RunRecord);
  146. if (errorList.Any())
  147. {
  148. errora = $"获取相机Id和CCDSN错误{JsonConvert.SerializeObject(errorList)}";
  149. AppData.Instance.LogHelper.TLLog(errora, LogEnum.RunRecord);
  150. return;
  151. }
  152. errorList = serialBin.Start(ConfigurationManager.AppSettings["autoFocus"].ToString());
  153. AppData.Instance.LogHelper.TLLog($"舱室信息:{JsonConvert.SerializeObject(serialBin.SerialModels)}", LogEnum.RunRecord);
  154. AppData.Instance.LogHelper.TLLog($"E方数据:{JsonConvert.SerializeObject(serialBin.HouseEEPROInfos)}", LogEnum.RunRecord);
  155. if (errorList.Any())
  156. {
  157. errora = $"获取串口信息错误{JsonConvert.SerializeObject(errorList)}";
  158. AppData.Instance.LogHelper.TLLog(errora, LogEnum.RunRecord);
  159. return;
  160. }
  161. var modelCount = serialBin.SerialModels.Count;
  162. if (modelCount != 11)
  163. {
  164. //string messageinfo = $"检测到{modelCount}个模块,是否继续运行?";
  165. string messageinfo = $" Detected {modelCount} cabin, are you sure to run?";
  166. MessageBoxResult aaa = MessageBox.Show(messageinfo, KeyToStringConvert.GetLanguageStringByKey("C0171"), MessageBoxButton.YesNo, MessageBoxImage.Question, MessageBoxResult.No, MessageBoxOptions.DefaultDesktopOnly);
  167. if (aaa != MessageBoxResult.Yes)
  168. {
  169. errora = "结束";
  170. return;
  171. }
  172. }
  173. List<int> listIntRunHoues = serialBin.SerialModels.Select(x => x.houseSn).ToList();
  174. TLInitData tLInitData = new TLInitData();
  175. tLInitData.tlSn = $"NEO-1-{serialBin.TLNum}";
  176. tLInitData.softwareVersion = "V2.0.0";
  177. tLInitData.verticalMotorPulseMax = 125000;
  178. tLInitData.houseLinkDataList = serialBin.SerialModels.OrderBy(x => x.houseSn).ToList();
  179. foreach (var item in serialBin.HouseEEPROInfos)
  180. {
  181. item.tlSn = tLInitData.tlSn;
  182. }
  183. tLInitData.houseEEPROInitDTOList = serialBin.HouseEEPROInfos.OrderBy(x => x.houseSn).ToList();
  184. AppData.Instance.LogHelper.TLLog($"舱室信息:{JsonConvert.SerializeObject(tLInitData)}", LogEnum.RunRecord);
  185. SettingDataApiData settingDataApiData = AppData.Instance.HttpHelper.GetSettingDataApi(tLInitData);
  186. if (settingDataApiData == null)
  187. {
  188. errora = $"{tLInitData.tlSn}获取仪器设置失败";
  189. return;
  190. }
  191. AppData.Instance.LogHelper.TLLog(JsonConvert.SerializeObject(settingDataApiData), LogEnum.RunRecord);
  192. tLSetting = AppData.Instance.ConvertHelper.ConvertToTLSetting(settingDataApiData.tlInfo, settingDataApiData.tlSetting);
  193. ccdPhoto = settingDataApiData.housePhotographLocation;
  194. houseWellSettingList = settingDataApiData.houseWellSettingList;
  195. HouseList = settingDataApiData.houseList;
  196. CurrentHouse = HouseList.FirstOrDefault(x => x.houseSn == 1);
  197. }
  198. catch (Exception ex)
  199. {
  200. AppData.Instance.LogHelper.ExceptionLog(ex, $"调试模式初始化", LogEnum.RunException);
  201. errora = $"调试模式初始化异常:{ex.Message}";
  202. }
  203. }
  204. public async Task ComHouseInit()
  205. {
  206. await Task.Run(async () =>
  207. {
  208. try
  209. {
  210. var currentHouse = HouseList.FirstOrDefault(x => x.houseSn == CurrentHouseId);
  211. // M1-03/B2 HAL: 向 HAL 申请该舱前台借用——HAL 暂停 control 对本舱采集(T1.3)并让采集端让出串口/相机,
  212. // 调试页随后复用借用到的同一物理句柄(lease.Serial/lease.Camera),不再 new 第二个 ComBin/Camera 开同口/同相机。
  213. try
  214. {
  215. var gate = HardwareAccessLayer.Instance.GetHouseGate(currentHouse.houseSn);
  216. _halLease = gate.Acquire(HardwareUser.OperateDebug);
  217. if (_halLease == null)
  218. {
  219. AddMessageInfo($"[{currentHouse.houseSn}]该舱正被占用(采集/对焦),借用超时,稍后重试");
  220. return;
  221. }
  222. }
  223. catch (Exception le)
  224. {
  225. AddMessageInfo($"[{currentHouse.houseSn}]HAL 借用异常:{le.Message}");
  226. return;
  227. }
  228. if (Serial == null)
  229. {
  230. AddMessageInfo($"[{currentHouse.houseSn}]借用到的串口句柄为空(HAL 未 ScanDevices 到本舱?),无法进入调试");
  231. return;
  232. }
  233. if (!Serial.IsOpen)
  234. {
  235. // 物理口由采集端持有并保持打开;T1.3 暂停只停发不关口。此处兜底再开一次(幂等)。
  236. if (!Serial.Open())
  237. {
  238. AddMessageInfo($"[{currentHouse.houseSn}][{currentHouse.housePort}]借用串口未打开且兜底打开失败");
  239. return;
  240. }
  241. }
  242. AddMessageInfo($"[{currentHouse.houseSn}][{currentHouse.housePort}]调试已复用采集端串口句柄(同一物理口)");
  243. // 相机:复用借用到的同一相机句柄。采集端通常已 Init+SetOpMode;仅在未 Init 时兜底 Init,
  244. // 然后统一设单帧采集模式(mode=0)供调试抓图,避免重复 Init 扰动采集端相机。
  245. if (Cam == null)
  246. {
  247. AddMessageInfo($"[{currentHouse.houseSn}]本舱无相机句柄(buffer/无相机舱?),跳过相机初始化");
  248. }
  249. else
  250. {
  251. if (!Cam.IsInit)
  252. {
  253. int cameraInit = Cam.Init();
  254. AddMessageInfo($"[CCD模块初始化]CCDID={CurrentCCDId},SN={currentHouse.ccdSn} 初始化结果:{cameraInit}[0=成功]");
  255. if (cameraInit != 0) return;
  256. }
  257. int cameraSetMode = Cam.SetOpMode();
  258. AddMessageInfo($"[CCD模块初始化]开启图像捕捉结果:{cameraSetMode}[0=成功]");
  259. if (cameraSetMode != 0) return;
  260. }
  261. var currentHorSetting = houseWellSettingList.FirstOrDefault(x => x.houseSn == currentHouse.houseSn && x.wellSn == 1);
  262. if (currentHorSetting == null)
  263. {
  264. AddMessageInfo($"[{currentHouse.houseSn}][{currentHouse.housePort}][未获取到1号well的水平电机位置]");
  265. return;
  266. }
  267. //OpenVideoEvent?.Invoke();
  268. var verNewValue = currentHorSetting.eepromClearPosition;
  269. var cc = ccdPhoto.FirstOrDefault(x => x.houseSn == currentHouse.houseSn && x.wellSn == 1);
  270. if (cc != null)
  271. {
  272. verNewValue = cc.clearestPosition;
  273. }
  274. Serial.ShakeHandsWait();
  275. OpenLed();
  276. Serial.HorizontalResetWait(tLSetting.motorDelay);
  277. CurrentHor = 0;
  278. CurrentWell = 0;
  279. Serial.HorizontalMoveToWait(currentHorSetting.horizontalMotorPosition, tLSetting.motorDelay);
  280. CurrentHor = currentHorSetting.horizontalMotorPosition;
  281. CurrentWell = 1;
  282. Serial.VerticalResetWait(tLSetting.motorDelay);
  283. CurrentVer = 0;
  284. CurrentFocal = 0;
  285. Serial.VerticalMoveToWait(verNewValue, tLSetting.motorDelay);
  286. CurrentVer = verNewValue;
  287. CurrentFocal = 1;
  288. RedTem();
  289. RedPre();
  290. RedDoor();
  291. RedVentTime();
  292. return;
  293. }
  294. catch (Exception ex)
  295. {
  296. AppData.Instance.LogHelper.ExceptionLog(ex, "调试模式初始化", LogEnum.RunException);
  297. AddMessageInfo($"初始化异常:{ex.Message}");
  298. return;
  299. }
  300. });
  301. }
  302. public bool ComHouseUnit()
  303. {
  304. try
  305. {
  306. // M1-B2:物理串口/相机由采集端(control)持有,调试只归还借用,绝不 ClosePort/UnInit 关物理口——
  307. // 否则会把采集端的口/相机一并关掉。归还后 HAL 触发 ResumeCapture 恢复本舱采集(T1.3)。
  308. if (_halLease != null)
  309. {
  310. try { _halLease.Dispose(); } catch { }
  311. _halLease = null;
  312. AddMessageInfo($"[{CurrentHouseId}]已归还借用,恢复后台采集");
  313. }
  314. return true;
  315. }
  316. catch (Exception ex)
  317. {
  318. AppData.Instance.LogHelper.ExceptionLog(ex, "调试模式卸载", LogEnum.RunException);
  319. AddMessageInfo($"卸载异常:{ex.Message}");
  320. return false;
  321. }
  322. }
  323. /// <summary>
  324. /// 读温度
  325. /// </summary>
  326. public void RedTem()
  327. {
  328. if (Serial == null) return;
  329. Temperature = Serial.TemperatureWait();
  330. }
  331. /// <summary>
  332. /// 读压力
  333. /// </summary>
  334. public void RedPre()
  335. {
  336. if (Serial == null) return;
  337. Pressure = Serial.PressureWait();
  338. }
  339. /// <summary>
  340. /// 读舱门
  341. /// </summary>
  342. public void RedDoor()
  343. {
  344. if (Serial == null) return;
  345. string DoorStateString = Serial.DoorStatusWait().ToString();
  346. if(DoorStateString == "关闭")
  347. {
  348. DoorState = KeyToStringConvert.GetLanguageStringByKey("C0305");
  349. }
  350. if (DoorStateString == "打开")
  351. {
  352. DoorState = KeyToStringConvert.GetLanguageStringByKey("C0306");
  353. }
  354. }
  355. /// <summary>
  356. /// 打开Led灯
  357. /// </summary>
  358. public void OpenLed()
  359. {
  360. if (Serial == null) return;
  361. Serial.OpenLedWait();
  362. LedState = KeyToStringConvert.GetLanguageStringByKey("C0306");
  363. //LedState = "开启";
  364. }
  365. /// <summary>
  366. /// 关闭Led灯
  367. /// </summary>
  368. public void CloseLed()
  369. {
  370. if (Serial == null) return;
  371. Serial.CloseLedWait();
  372. //LedState = "关闭";
  373. LedState = KeyToStringConvert.GetLanguageStringByKey("C0305");
  374. }
  375. /// <summary>
  376. /// 打开进气阀
  377. /// </summary>
  378. public void OpenIntake()
  379. {
  380. if (Serial == null) return;
  381. Serial.OpenIntakeValveWait();
  382. }
  383. /// <summary>
  384. /// 关闭进气阀
  385. /// </summary>
  386. public void CloseIntake()
  387. {
  388. if (Serial == null) return;
  389. Serial.CloseIntakeValveWait();
  390. }
  391. /// <summary>
  392. /// 打开排气阀
  393. /// </summary>
  394. public void OpenExhaust()
  395. {
  396. if (Serial == null) return;
  397. Serial.OpenExhaustValveWait();
  398. }
  399. /// <summary>
  400. /// 关闭排气阀
  401. /// </summary>
  402. public void CloseExhaust()
  403. {
  404. if (Serial == null) return;
  405. Serial.CloseExhaustValveWait();
  406. }
  407. /// <summary>
  408. /// 舱室补气
  409. /// </summary>
  410. public void HouseAeration()
  411. {
  412. if (Serial == null) return;
  413. Serial.HouseAerationWait();
  414. }
  415. /// <summary>
  416. /// 舱室排气
  417. /// </summary>
  418. public void HouseVent()
  419. {
  420. if (Serial == null) return;
  421. Serial.HouseVentWait();
  422. }
  423. /// <summary>
  424. /// 写舱室进气阀时间
  425. /// </summary>
  426. /// <param name="newValue"></param>
  427. public void WriteOpenIntakeTime(int newValue)
  428. {
  429. if (Serial == null) return;
  430. // M1-B2:走 lease.Serial→control ComBin(builder 与 operate 逐字节一致)。⚠ 待真机 V-010(写E方回包判定)。
  431. Serial.WriteOpenIntakeTimeWait(newValue, isBuffer: false);
  432. }
  433. /// <summary>
  434. /// 写舱室排气阀时间
  435. /// </summary>
  436. /// <param name="newValue"></param>
  437. public void WriteOpenVentTime(int newValue)
  438. {
  439. if (Serial == null) return;
  440. // ⚠ M1-B2:control Commander 缺 CreateWriteEEPROOpenVentTimeCommand(T1.1 核实),不臆造字节 → 暂不下发。
  441. // 待真机核对字节后在 control Commander 补 builder 再接入。当前仅本地回显,未真正写入下位机。
  442. if (!Serial.WriteOpenVentTimeWait(newValue))
  443. {
  444. AddMessageInfo($"[排气阀时间]control 端暂缺写E方命令(待真机补字节),本次未下发到下位机,仅本地暂存{newValue}");
  445. }
  446. HouseVentTimeE = newValue;
  447. }
  448. /// <summary>
  449. /// 读舱室排气阀打开时间
  450. /// </summary>
  451. public void RedVentTime()
  452. {
  453. if (Serial == null) return;
  454. // ⚠ M1-B2:control 缺读排气阀时间命令(待真机);读不到则保持原值不覆盖。
  455. int v = Serial.ReadOpenVentTimeWait();
  456. if (v >= 0) HouseVentTimeE = v;
  457. }
  458. /// <summary>
  459. /// 写垂直电机间隔脉冲
  460. /// </summary>
  461. /// <param name="newValue"></param>
  462. public void WriteOVerSpace(int newValue)
  463. {
  464. if (Serial == null) return;
  465. // M1-B2:走 lease.Serial→control ComBin(builder 与 operate 逐字节一致)。⚠ 待真机 V-010。
  466. Serial.WriteScanStepWait(newValue);
  467. }
  468. /// <summary>
  469. /// 保存水平电机位置
  470. /// </summary>
  471. /// <param name="newValue"></param>
  472. public void SaveWellHor()
  473. {
  474. if (Serial == null) return;
  475. // M8-P3b:手调保存水平电机位置(关键命令入口,module=对焦调试)。
  476. // M1-B2:走 lease.Serial.WriteWellHorizontalPosWait→control ComBin(builder 逐字节一致)。⚠ 待真机 V-010。
  477. Aivfo.OperationLog.OperationLogger.Run("对焦调试", "手调保存水平电机位置",
  478. () => Serial.WriteWellHorizontalPosWait(CurrentWell, CurrentHor),
  479. input: new { houseSn = CurrentHouseId, well = CurrentWell, hor = CurrentHor });
  480. }
  481. #region 电机运动
  482. /// <summary>
  483. /// 水平电机复位
  484. /// </summary>
  485. public void HorizontalMotorReset()
  486. {
  487. if (Serial == null) return;
  488. // M8-P3b:电机控制命令埋点(module=对焦调试)。
  489. Aivfo.OperationLog.OperationLogger.Run("对焦调试", "水平电机复位",
  490. () => Serial.HorizontalResetWait(tLSetting.motorDelay),
  491. input: new { houseSn = CurrentHouseId });
  492. CurrentHor = 0;
  493. CurrentWell = 0;
  494. }
  495. /// <summary>
  496. /// 水平电机正向
  497. /// </summary>
  498. public void HorizontalMotorForward(int value)
  499. {
  500. if (Serial == null) return;
  501. Serial.HorizontalForwardWait(value, tLSetting.motorDelay);
  502. CurrentHor += value;
  503. }
  504. /// <summary>
  505. /// 水平电机反向
  506. /// </summary>
  507. public void HorizontalMotorBackward(int value)
  508. {
  509. if (Serial == null) return;
  510. Serial.HorizontalBackwardWait(value, tLSetting.motorDelay);
  511. CurrentHor -= value;
  512. }
  513. /// <summary>
  514. /// 水平电机到目标well
  515. /// </summary>
  516. /// <param name="newWell"></param>
  517. public void HorizontalMotorToWell(int newWell)
  518. {
  519. if (Serial == null) return;
  520. var currentHorSetting = houseWellSettingList.FirstOrDefault(x => x.houseSn == CurrentHouseId && x.wellSn == newWell);
  521. if (currentHorSetting == null)
  522. {
  523. AddMessageInfo($"[未获取到{newWell}号well的水平电机位置]");
  524. return;
  525. }
  526. Serial.HorizontalMoveToWait(currentHorSetting.horizontalMotorPosition, tLSetting.motorDelay);
  527. CurrentHor = currentHorSetting.horizontalMotorPosition;
  528. CurrentWell = newWell;
  529. }
  530. /// <summary>
  531. /// 垂直电机复位
  532. /// </summary>
  533. public void VerticalMotorReset()
  534. {
  535. if (Serial == null) return;
  536. // M8-P3b:电机控制命令埋点(module=对焦调试)。
  537. Aivfo.OperationLog.OperationLogger.Run("对焦调试", "垂直电机复位",
  538. () => Serial.VerticalResetWait(tLSetting.motorDelay),
  539. input: new { houseSn = CurrentHouseId });
  540. CurrentVer = 0;
  541. }
  542. /// <summary>
  543. /// 垂直电机正向运动
  544. /// </summary>
  545. public void VerticalMotorForward(int newValue)
  546. {
  547. if (Serial == null) return;
  548. Serial.VerticalForwardWait(newValue, tLSetting.motorDelay);
  549. CurrentVer += newValue;
  550. }
  551. /// <summary>
  552. /// 垂直电机反向运动
  553. /// </summary>
  554. public void VerticalMotorBackward(int newValue)
  555. {
  556. if (Serial == null) return;
  557. Serial.VerticalBackwardWait(newValue, tLSetting.motorDelay);
  558. CurrentVer -= newValue;
  559. }
  560. /// <summary>
  561. /// 垂直电机绝对运动
  562. /// </summary>
  563. public void VerticalMotorAbsolute(int newValue)
  564. {
  565. if (Serial == null) return;
  566. Serial.VerticalMoveToWait(newValue, tLSetting.motorDelay);
  567. CurrentVer = newValue;
  568. }
  569. /// <summary>
  570. /// 一键电机准备
  571. /// </summary>
  572. public void MototReady()
  573. {
  574. if (Serial == null) return;
  575. var currentHorSetting = houseWellSettingList.FirstOrDefault(x => x.houseSn == CurrentHouseId && x.wellSn == 1);
  576. if (currentHorSetting == null)
  577. {
  578. AddMessageInfo($"[未获取到1号well的水平电机位置]");
  579. return;
  580. }
  581. var verNewValue = currentHorSetting.eepromClearPosition;
  582. var cc = ccdPhoto.FirstOrDefault(x => x.houseSn == CurrentHouseId && x.wellSn == 1);
  583. if (cc != null)
  584. {
  585. verNewValue = cc.clearestPosition;
  586. }
  587. Serial.HorizontalResetWait(tLSetting.motorDelay);
  588. CurrentHor = 0;
  589. CurrentWell = 0;
  590. Serial.HorizontalMoveToWait(currentHorSetting.horizontalMotorPosition, tLSetting.motorDelay);
  591. CurrentHor = currentHorSetting.horizontalMotorPosition;
  592. CurrentWell = 1;
  593. Serial.VerticalResetWait(tLSetting.motorDelay);
  594. CurrentVer = 0;
  595. CurrentFocal = 0;
  596. Serial.VerticalMoveToWait(verNewValue, tLSetting.motorDelay);
  597. CurrentVer = verNewValue;
  598. CurrentFocal = 1;
  599. }
  600. /// <summary>
  601. /// 单张抓拍
  602. /// </summary>
  603. public bool SavePic(string fullName)
  604. {
  605. try
  606. {
  607. if (GetPicData() == 0)
  608. {
  609. if (Cam == null) return false;
  610. return Cam.SavePic(fullName, CurrentHouse.ccdWidth, CurrentHouse.ccdHeight);
  611. }
  612. return false;
  613. }
  614. catch (Exception ex)
  615. {
  616. AppData.Instance.LogHelper.ExceptionLog(ex, $"单张抓拍", LogEnum.RunException);
  617. AddMessageInfo($"单张抓拍异常:{ex.Message}");
  618. return false;
  619. }
  620. }
  621. /// <summary>
  622. /// 水平抓图
  623. /// </summary>
  624. public void ShuiPingZhuaPai()
  625. {
  626. try
  627. {
  628. IsStop = false;
  629. if (Serial == null) return;
  630. if (IsStop) return;
  631. Serial.HorizontalResetWait(tLSetting.motorDelay);
  632. CurrentHor = 0;
  633. CurrentWell = 0;
  634. HouseWellSetting currentHorSetting = null;
  635. string dtnow = string.Format("{0:yyyy-MM-dd-HH-mm-ss}", DateTime.Now); //24小时制
  636. string path = AppData.Instance.LogHelper.GetDeBugShuiPingDirectory(CurrentHouse.houseSn, dtnow);
  637. if (!Directory.Exists(path))
  638. {
  639. Directory.CreateDirectory(path);
  640. }
  641. for (int i = 1; i <= 16; i++)
  642. {
  643. currentHorSetting = houseWellSettingList.FirstOrDefault(x => x.houseSn == CurrentHouseId && x.wellSn == i);
  644. if (currentHorSetting == null)
  645. {
  646. AddMessageInfo($"[未获取到1号well的水平电机位置]");
  647. continue;
  648. }
  649. if (IsStop) return;
  650. if (Serial == null) return;
  651. Serial.HorizontalMoveToWait(currentHorSetting.horizontalMotorPosition, tLSetting.motorDelay);
  652. if (IsStop) return;
  653. CurrentHor = currentHorSetting.horizontalMotorPosition;
  654. CurrentWell = i;
  655. string filename = $"{dtnow}-house{CurrentHouse.houseSn}-well{CurrentWell}-{CurrentFocal}-{CurrentHor}-{CurrentVer}.jpg";
  656. string fullName = $"{path}{filename}";
  657. if (Cam == null) return;
  658. if (SavePic(fullName))
  659. {
  660. AddPic(fullName);
  661. }
  662. }
  663. }
  664. catch (Exception ex)
  665. {
  666. AppData.Instance.LogHelper.ExceptionLog(ex, $"水平抓拍", LogEnum.RunException);
  667. AddMessageInfo($"水平抓拍异常:{ex.Message}");
  668. }
  669. }
  670. /// <summary>
  671. /// 清晰图层抓图
  672. /// </summary>
  673. public async Task AutoFocusPic(int focalCount, int xun)
  674. {
  675. await Task.Run(async () =>
  676. {
  677. try
  678. {
  679. IsStop = false;
  680. var startAutoFocus = -1;
  681. var cc = ccdPhoto.FirstOrDefault(x => x.houseSn == CurrentHouseId && x.wellSn == CurrentWell);
  682. if (cc == null)
  683. {
  684. AddMessageInfo($"[未获取到{CurrentWell}号well的自动对焦起点]");
  685. return;
  686. }
  687. startAutoFocus = cc.autoFocusPosition;
  688. string dtnow = string.Format("{0:yyyy-MM-dd-HH-mm-ss}", DateTime.Now); //24小时制
  689. string path = null;
  690. string fullName = null;
  691. for (int k = 0; k < xun; k++)
  692. {
  693. if (IsStop) return;
  694. if (Serial == null) return;
  695. Serial.VerticalResetWait(tLSetting.motorDelay);
  696. CurrentVer = 0;
  697. CurrentFocal = 0;
  698. var verSpacePulse = 128;
  699. if (CurrentHouse.verticalMotorSpacePulse.HasValue) verSpacePulse = CurrentHouse.verticalMotorSpacePulse.Value;
  700. path = $"{AppData.Instance.LogHelper.GetDeBugQingXiDirectory(CurrentHouse.houseSn, CurrentWell, dtnow)}{(k + 1)}_{CurrentHor}";
  701. if (!Directory.Exists(path)) Directory.CreateDirectory(path);
  702. for (int i = 0; i < focalCount; i++)
  703. {
  704. CurrentFocal = i + 1;
  705. var currentVerValue = startAutoFocus + (i * verSpacePulse);
  706. if (IsStop) return;
  707. if (Serial == null) return;
  708. if(currentVerValue > tLSetting.verticalMotorPulseMax)
  709. {
  710. AddMessageInfo($"清晰图层抓图超出垂直电机上限:{tLSetting.verticalMotorPulseMax}");
  711. return;
  712. }
  713. Serial.VerticalMoveToWait(currentVerValue, tLSetting.motorDelay);
  714. CurrentVer = currentVerValue;
  715. fullName = $"{path}\\{currentVerValue}.jpg";
  716. if (IsStop) return;
  717. if (Cam == null) return;
  718. if (SavePic(fullName)) AddPic(fullName);
  719. }
  720. }
  721. }
  722. catch (Exception ex)
  723. {
  724. AppData.Instance.LogHelper.ExceptionLog(ex, $"清晰图层抓图", LogEnum.RunException);
  725. AddMessageInfo($"清晰图层抓图异常:{ex.Message}");
  726. }
  727. });
  728. }
  729. /// <summary>
  730. /// 抓图
  731. /// </summary>
  732. public int GetPicData()
  733. {
  734. try
  735. {
  736. if (Cam == null) return -1;
  737. int GetRgbData = -1;
  738. bool isWuTu = false;
  739. if (isWuTu)
  740. {
  741. GetRgbData = Cam.GrabRaw();//获取字节流
  742. AddMessageInfo($"[抓拍结果:{GetRgbData}][注:0表示成功]");
  743. if (GetRgbData == 0)
  744. {
  745. GetRgbData = Cam.RawToRgb();
  746. AddMessageInfo($"[rawToRgb结果:{GetRgbData}][注:0表示成功]");
  747. }
  748. }
  749. else
  750. {
  751. GetRgbData = Cam.GrabRgb();//获取字节流
  752. AddMessageInfo($"[抓拍结果:{GetRgbData}][注:0表示成功]");
  753. }
  754. return GetRgbData;
  755. }
  756. catch (Exception ex)
  757. {
  758. AppData.Instance.LogHelper.ExceptionLog(ex, $"调试模式抓拍", LogEnum.RunException);
  759. AddMessageInfo($"相机抓拍异常:{ex.Message}");
  760. return -1;
  761. }
  762. }
  763. #endregion
  764. #region 相机操作
  765. /// <summary>
  766. /// 设置曝光值
  767. /// </summary>
  768. /// <param name="newExporuse"></param>
  769. public void SetExposure(int newExporuse)
  770. {
  771. if (Cam == null) { AddMessageInfo("设置曝光失败:相机句柄为空"); return; }
  772. AddMessageInfo($"设置曝光结果:{Cam.SetExposure(newExporuse)}");
  773. }
  774. /// <summary>
  775. /// 打开实时预览(贴宿主窗口句柄)。M1-B2:走借用到的 lease.Camera(StartPreview),不再触碰具体 Camera。
  776. /// 返回 0 成功;相机句柄为空返回 -1。
  777. /// </summary>
  778. public int StartPreview(IntPtr hostControl, int left, int top, int width, int height)
  779. {
  780. if (Cam == null) return -1;
  781. return Cam.StartPreview(hostControl, left, top, width, height);
  782. }
  783. /// <summary>关闭实时预览。返回 0 成功;相机句柄为空返回 -1。</summary>
  784. public int StopPreview()
  785. {
  786. if (Cam == null) return -1;
  787. return Cam.StopPreview();
  788. }
  789. //public bool OpenVideo(IntPtr mControlPtr, int left, int top, int width, int height)
  790. //{
  791. // try
  792. // {
  793. // var a = camera.Usb2Start(mControlPtr, left, top, width, height);
  794. // AddMessageInfo($"图像打开结果[0表示成功]:{a}");
  795. // return a == 0;
  796. // }
  797. // catch (Exception ex)
  798. // {
  799. // ExLog(ex, "OpenVideo");
  800. // AddMessageInfo($"图像打开异常:{ex.Message}");
  801. // return false;
  802. // }
  803. //}
  804. //public bool CloseVideo()
  805. //{
  806. // try
  807. // {
  808. // var a = camera.Usb2Stop();
  809. // AddMessageInfo($"图像关闭结果[0表示成功]:{a}");
  810. // return a == 0;
  811. // }
  812. // catch (Exception ex)
  813. // {
  814. // ExLog(ex, "CloseVideo");
  815. // AddMessageInfo($"图像关闭异常:{ex.Message}");
  816. // return false;
  817. // }
  818. //}
  819. #endregion
  820. #region 参数保存
  821. /// <summary>
  822. /// 保存舱室参数
  823. /// </summary>
  824. /// <returns></returns>
  825. public bool SetHouseInfo()
  826. {
  827. try
  828. {
  829. if (CurrentHouse == null) return true;
  830. string body = JsonConvert.SerializeObject(new
  831. {
  832. tlSn = CurrentHouse.tlSn,
  833. houseSn = CurrentHouse.houseSn,
  834. ccdExposure = CurrentHouse.ccdExposure,
  835. inletValveOpeningTime = CurrentHouse.inletValveOpeningTime,
  836. verticalMotorSpacePulse = CurrentHouse.verticalMotorSpacePulse,
  837. });
  838. return AppData.Instance.HttpHelper.HouseDebuggingApi(body);
  839. }
  840. catch (Exception ex)
  841. {
  842. ExLog(ex, "SetHouseExposure");
  843. return false;
  844. }
  845. }
  846. /// <summary>
  847. /// 保存当前well位置
  848. /// </summary>
  849. /// <returns></returns>
  850. public bool SetWellMotorPosition()
  851. {
  852. try
  853. {
  854. if (CurrentHouse == null)
  855. {
  856. AddMessageInfo("获取舱室信息失败");
  857. }
  858. string body = JsonConvert.SerializeObject(new
  859. {
  860. horizontalMotorPosition = CurrentHor,
  861. houseSn = CurrentHouse.houseSn,
  862. tlSn = CurrentHouse.tlSn,
  863. wellSn = CurrentWell,
  864. });
  865. return AppData.Instance.HttpHelper.WellUpdateApi(body);
  866. }
  867. catch (Exception ex)
  868. {
  869. ExLog(ex, "SetWellMotorPosition");
  870. return false;
  871. }
  872. }
  873. /// <summary>
  874. /// 保存自动对焦起点
  875. /// </summary>
  876. /// <returns></returns>
  877. public bool SetWellAutoFocus()
  878. {
  879. try
  880. {
  881. if (CurrentHouse == null)
  882. {
  883. AddMessageInfo("获取舱室信息失败");
  884. }
  885. string body = JsonConvert.SerializeObject(new
  886. {
  887. verticalMotorPosition = CurrentVer,
  888. houseSn = CurrentHouse.houseSn,
  889. tlSn = CurrentHouse.tlSn,
  890. wellSn = CurrentWell,
  891. });
  892. return AppData.Instance.HttpHelper.WellUpdateApi(body);
  893. }
  894. catch (Exception ex)
  895. {
  896. ExLog(ex, "SetWellAutoFocus");
  897. return false;
  898. }
  899. }
  900. #endregion
  901. private void ComBin_ExceptionLogEvent(Exception exception, string arg2, string arg3, LogEnum @enum)
  902. {
  903. AppData.Instance.LogHelper.ExceptionLog(exception, $"{arg2}{arg3}", @enum);
  904. }
  905. private void ComBin_ErrorLogEvent(string arg1, LogEnum @enum)
  906. {
  907. AppData.Instance.LogHelper.TLLog(arg1, @enum);
  908. }
  909. private void ComBin_CommandLogEvent(int arg1, DateTime time, string arg3, LogEnum @enum)
  910. {
  911. AppData.Instance.LogHelper.HouseLog(arg1, time, arg3, @enum);
  912. }
  913. public void AddMessageInfo(string mess)
  914. {
  915. MessageEvent?.Invoke(mess);
  916. }
  917. public void AddPic(string picFullName)
  918. {
  919. AddPicEvent?.Invoke(picFullName, CurrentWell, CurrentFocal);
  920. }
  921. #region M2-05 场景A 一键全自动标定(沙盒)
  922. /// <summary>
  923. /// M2-05 场景A 工程师调试页一键全自动标定(人盯安全沙盒,03 §2/§7.1)。
  924. /// 流程:对选中 well 列表逐 well 跑 M2-01 四步标定引擎(CalibrationEngine) →
  925. /// 收集 WellCalib → 实时 UI 合格绿/伪峰红 → 结果作出厂基准 scene=0 落库 + 写 calibration.json。
  926. ///
  927. /// 硬件复用:调试页 ComHouseInit 已经 Acquire(OperateDebug) 前台借用(HAL 暂停 control 采集),
  928. /// 借用到的 lease.Serial/lease.Camera 即与采集端同一物理句柄(M1-B2)。标定引擎直接用这两个 HAL 接口,
  929. /// 不再 new ComBin/Camera、不二次 Open/Init 同 COM 口/相机。互斥由调试页持有的前台借用保证。
  930. /// 中止:IsStopCalibrate 标志,每 well 间检查,工程师可随时中止,已完成 well 结果保留。
  931. /// 异常:单 well 失败/存储失败不崩 UI,记日志继续;整体异常兜底,IsCalibrating 复位。
  932. ///
  933. /// ⚠ 待验证 V-055..V-059:16well 跑通(关联 V-004 算法严谨性)/合格绿伪峰红/基准scene0落库+JSON/
  934. /// 借用期间采集暂停/中止响应。
  935. /// </summary>
  936. /// <param name="wells">勾选的 well 列表(空/null 视为全 16 well)。</param>
  937. public async Task OneClickCalibrate(IEnumerable<int> wells = null)
  938. {
  939. await Task.Run(() =>
  940. {
  941. if (IsCalibrating)
  942. {
  943. AddMessageInfo("[一键标定]已在标定中,请勿重复触发");
  944. return;
  945. }
  946. if (Serial == null || Cam == null)
  947. {
  948. AddMessageInfo("[一键标定]请先初始化舱室(串口/相机未就绪)");
  949. return;
  950. }
  951. if (CurrentHouse == null)
  952. {
  953. AddMessageInfo("[一键标定]未获取到舱室信息");
  954. return;
  955. }
  956. IsCalibrating = true;
  957. IsStopCalibrate = false;
  958. // M8-P3b:一键标定为关键命令入口,建立操作日志 scope(统一 traceId 串联本次标定内的 HTTP/串口/相机埋点)。
  959. using var _opScope = Aivfo.OperationLog.OperationLogger.Begin("对焦调试", "一键标定",
  960. houseSn: CurrentHouseId);
  961. try { _opScope.Input(new { houseSn = CurrentHouseId }); } catch { }
  962. // 勾选 well:未传则默认 16 well;去重、按序、限定 1-16。
  963. var wellList = (wells != null ? wells : Enumerable.Range(1, 16))
  964. .Where(w => w >= 1 && w <= 16).Distinct().OrderBy(w => w).ToList();
  965. if (wellList.Count == 0) wellList = Enumerable.Range(1, 16).ToList();
  966. // 合格判据阈值:tl_setting.focus_peak_ratio_threshold,缺省 1.2(03 §7.1)。
  967. double peakThreshold = (tLSetting != null && tLSetting.focusPeakRatioThreshold.HasValue)
  968. ? (double)tLSetting.focusPeakRatioThreshold.Value : 1.2;
  969. ResetCalibResults(wellList);
  970. // 标定结果存储:calibration.json 真相源(12 §2.7/03 §4,IncludeFields=true 由 CalibrationFile.Load 保证)。
  971. // operate 端无 SqlSugar 直连(走 HttpHelper),故 DbMirror=null:仅写 JSON 真相源;
  972. // house_autofocus_calibration 的 scene=0 基准 upsert 由 control 端 AppData.AutofocusStore 镜像(M2-04)。
  973. var store = new CalibrationStore
  974. {
  975. JsonPath = System.IO.Path.Combine(
  976. System.AppDomain.CurrentDomain.BaseDirectory, @"DependFile\AutoFocus\calibration.json"),
  977. Source = "OPERATE_DEBUG_SCENE0",
  978. Log = msg => AddMessageInfo($"[一键标定]{msg}"),
  979. // DbMirror 为空 → 只写 JSON 不镜像库(operate 无 DB 直连)。
  980. };
  981. try
  982. {
  983. var jsonDir = System.IO.Path.GetDirectoryName(store.JsonPath);
  984. if (!string.IsNullOrEmpty(jsonDir) && !System.IO.Directory.Exists(jsonDir))
  985. System.IO.Directory.CreateDirectory(jsonDir);
  986. }
  987. catch (Exception exDir)
  988. {
  989. AddMessageInfo($"[一键标定]创建 calibration.json 目录失败(将仅 UI 显示):{exDir.Message}");
  990. }
  991. string tlSn = (tLSetting != null && !string.IsNullOrEmpty(tLSetting.tlSn))
  992. ? tLSetting.tlSn : (CurrentHouse.tlSn ?? AppData.Instance.TlSn);
  993. try
  994. {
  995. // M1-B2:借用到的 lease.Serial/lease.Camera 本就是 HAL 接口(ISerialChannel/ICamera),
  996. // 直接喂给 M2-01 引擎,无需再经 DebugSerial/CameraAdapter 包 operate 具体类型(已退役)。
  997. var serial = Serial;
  998. var cam = Cam;
  999. var engine = new CalibrationEngine(serial, cam)
  1000. {
  1001. Log = msg => AddMessageInfo(msg)
  1002. };
  1003. AddMessageInfo($"[一键标定]开始:舱{CurrentHouse.houseSn} 共 {wellList.Count} well,合格峰比阈值={peakThreshold:F2}");
  1004. foreach (var well in wellList)
  1005. {
  1006. if (IsStopCalibrate)
  1007. {
  1008. AddMessageInfo("[一键标定]已被中止,停止后续 well");
  1009. break;
  1010. }
  1011. UpdateCalibResult(well, item => { item.State = WellCalibState.Running; item.Note = "标定中..."; });
  1012. CurrentWell = well;
  1013. try
  1014. {
  1015. // EEPROM 仅作扫描中心(参考),不进配置解析链、不回写(§2.5)。
  1016. int hpos = serial.ReadWellHorizontalPosWait(well);
  1017. int zZero = serial.ReadWellFocusZeroWait(well);
  1018. var wc = engine.CalibrateWell(well, Math.Max(0, hpos), Math.Max(0, zZero));
  1019. if (wc == null)
  1020. {
  1021. UpdateCalibResult(well, item =>
  1022. {
  1023. item.State = WellCalibState.Failed;
  1024. item.Note = "无结果";
  1025. });
  1026. AddMessageInfo($"[一键标定]{well}号 well 无标定结果");
  1027. continue;
  1028. }
  1029. // 合格判据:circleFound && peakRatio>阈值 → 绿;否则(未检圆/伪峰/弱峰) → 红。
  1030. bool qualified = wc.CircleFound && wc.PeakRatio > peakThreshold;
  1031. UpdateCalibResult(well, item =>
  1032. {
  1033. item.State = qualified ? WellCalibState.Qualified : WellCalibState.FakePeak;
  1034. item.FocusZ = wc.FocusZ;
  1035. item.PeakRatio = wc.PeakRatio;
  1036. item.CenterOffsetPct = wc.CenterOffsetPct;
  1037. item.CircleFound = wc.CircleFound;
  1038. item.Exposure = wc.Exposure;
  1039. item.Note = qualified
  1040. ? $"合格 Z={wc.FocusZ} 峰比={wc.PeakRatio:F2}"
  1041. : $"伪峰 Z={wc.FocusZ} 峰比={wc.PeakRatio:F2} {(wc.CircleFound ? "" : "未检圆")}{wc.Note}";
  1042. });
  1043. AddMessageInfo($"[一键标定]{well}号 well {(qualified ? "✓合格(绿)" : "✗伪峰(红)")} " +
  1044. $"FocusZ={wc.FocusZ} 峰比={wc.PeakRatio:F2} 偏移={wc.CenterOffsetPct:F1}%");
  1045. // 出厂基准 scene=0 落库 + 写 calibration.json(存储失败不崩 UI,CalibrationStore 内部已吞异常)。
  1046. try
  1047. {
  1048. store.SaveCalibration(wc, tlSn, CurrentHouse.houseSn, well, scene: 0,
  1049. port: CurrentHouse.housePort, ccdSn: CurrentHouse.ccdSn);
  1050. }
  1051. catch (Exception exStore)
  1052. {
  1053. AddMessageInfo($"[一键标定]{well}号 well 结果存档失败:{exStore.Message}");
  1054. }
  1055. }
  1056. catch (Exception exWell)
  1057. {
  1058. // 单 well 异常不崩 UI:记日志/标红,继续下一 well。
  1059. UpdateCalibResult(well, item =>
  1060. {
  1061. item.State = WellCalibState.Failed;
  1062. item.Note = $"异常:{exWell.Message}";
  1063. });
  1064. ExLog(exWell, $"OneClickCalibrate.well{well}");
  1065. AddMessageInfo($"[一键标定]{well}号 well 标定异常:{exWell.Message}");
  1066. }
  1067. }
  1068. int okCount = CalibResults.Count(x => x.State == WellCalibState.Qualified);
  1069. AddMessageInfo($"[一键标定]结束:合格 {okCount}/{wellList.Count}(结果已存档为出厂基准 scene=0 + calibration.json)");
  1070. // M8-P3b:记录标定结果到操作日志 scope。
  1071. try { _opScope.Output(new { okCount, total = wellList.Count }).Success(); } catch { }
  1072. }
  1073. catch (Exception ex)
  1074. {
  1075. ExLog(ex, "OneClickCalibrate");
  1076. AddMessageInfo($"[一键标定]整体异常:{ex.Message}");
  1077. // M8-P3b:标定整体异常标记失败。
  1078. try { _opScope.Fail(ex.GetType().Name + ": " + ex.Message); } catch { }
  1079. }
  1080. finally
  1081. {
  1082. IsCalibrating = false;
  1083. }
  1084. });
  1085. }
  1086. /// <summary>工程师中止一键标定。</summary>
  1087. public void StopCalibrate()
  1088. {
  1089. IsStopCalibrate = true;
  1090. AddMessageInfo("[一键标定]收到中止请求,将在当前 well 结束后停止");
  1091. }
  1092. private void ResetCalibResults(List<int> wells)
  1093. {
  1094. void build()
  1095. {
  1096. CalibResults.Clear();
  1097. foreach (var w in wells)
  1098. CalibResults.Add(new WellCalibUiItem { Well = w, State = WellCalibState.Pending, Note = "待标定" });
  1099. }
  1100. // 集合改动需在 UI 线程(ObservableCollection 绑定)。
  1101. var disp = System.Windows.Application.Current?.Dispatcher;
  1102. if (disp != null && !disp.CheckAccess()) disp.Invoke(build); else build();
  1103. }
  1104. private void UpdateCalibResult(int well, Action<WellCalibUiItem> mutate)
  1105. {
  1106. void apply()
  1107. {
  1108. var item = CalibResults.FirstOrDefault(x => x.Well == well);
  1109. if (item == null)
  1110. {
  1111. item = new WellCalibUiItem { Well = well };
  1112. CalibResults.Add(item);
  1113. }
  1114. mutate(item);
  1115. }
  1116. var disp = System.Windows.Application.Current?.Dispatcher;
  1117. if (disp != null && !disp.CheckAccess()) disp.Invoke(apply); else apply();
  1118. }
  1119. #endregion
  1120. #region M2-07 对焦后手动微调拍摄层(层数/层间距/下移)持久化 well 级
  1121. /// <summary>
  1122. /// M2-07 手调"实际拍摄层数"(well 级覆盖)。空字符串=留空继承设备级(保存写 null)。
  1123. /// View TextBox 双向绑定;校验在保存/预览时做(层数≥1)。
  1124. /// </summary>
  1125. [ObservableProperty] private string manualLayerCount = "";
  1126. /// <summary>
  1127. /// M2-07 手调"实际拍摄层间距脉冲"(well 级覆盖)。空=继承设备级(写 null)。校验:>0。
  1128. /// </summary>
  1129. [ObservableProperty] private string manualLayerSpacing = "";
  1130. /// <summary>
  1131. /// M2-07 手调"对焦起点下移层数"(复用 move_down_layer)。空=继承设备级。
  1132. /// 校验:≥0 且 &lt;层数(下移层须落在拍摄范围内,§2.4 清晰层=第 down 层)。
  1133. /// </summary>
  1134. [ObservableProperty] private string manualMoveDown = "";
  1135. /// <summary>
  1136. /// M2-07 实时预览各层绝对 Z 位置(调 M2-02 ComputeLayerPositions 生成,关联 V-045)。
  1137. /// View 绑定此集合显示 N 层位置列表,让工程师看到手调效果。
  1138. /// </summary>
  1139. public ObservableCollection<LayerPreviewItem> LayerPreview { get; } = new ObservableCollection<LayerPreviewItem>();
  1140. /// <summary>
  1141. /// M2-07 预览/手调锚点 well(默认随水平电机当前 well / 一键标定取 CurrentWell)。
  1142. /// </summary>
  1143. [ObservableProperty] private int manualTuneWell = 1;
  1144. /// <summary>
  1145. /// 取该 well 当前生效的"实际拍摄层"配置(well 级覆盖优先,空则回退设备级),
  1146. /// 回填三个手调输入框 + 触发一次预览。供"载入当前值"按钮调用。
  1147. /// </summary>
  1148. public void LoadManualLayerSetting(int well)
  1149. {
  1150. ManualTuneWell = well;
  1151. var ws = houseWellSettingList.FirstOrDefault(x => x.houseSn == CurrentHouseId && x.wellSn == well);
  1152. // well 级覆盖非空显示 well 值,否则显示继承的设备级值作占位(§2.5 就近优先)。
  1153. int? wellCount = ws?.focusLayerCount;
  1154. int? wellSpacing = ws?.focusLayerSpacingPulse;
  1155. // 下移复用 moveDownLayer(well 级为非空 int 列;0 视为有效覆盖值)。
  1156. int? wellDown = ws != null ? (int?)ws.moveDownLayer : null;
  1157. ManualLayerCount = (wellCount ?? tLSetting?.focusLayerCount)?.ToString() ?? "";
  1158. ManualLayerSpacing = (wellSpacing ?? tLSetting?.focusLayerSpacingPulse)?.ToString() ?? "";
  1159. ManualMoveDown = (wellDown ?? tLSetting?.focusLayerDown)?.ToString() ?? "";
  1160. PreviewManualLayers();
  1161. }
  1162. /// <summary>
  1163. /// 取该 well 最近标定的 FocusZ 作预览锚点(M2-05 一键标定结果 CalibResults 优先;
  1164. /// 回退 ccdPhoto 的 clearestPosition 即 scene0/1 库下发的清晰位置)。
  1165. /// 返回 null 表示无标定可用(须提示先标定)。
  1166. /// </summary>
  1167. private int? GetPreviewFocusZ(int well)
  1168. {
  1169. var calib = CalibResults.FirstOrDefault(x => x.Well == well
  1170. && (x.State == WellCalibState.Qualified || x.State == WellCalibState.FakePeak));
  1171. if (calib != null && calib.FocusZ > 0) return calib.FocusZ;
  1172. // 回退:调试页加载的清晰位置(scene0/1 库值 clearestPosition)。
  1173. var cc = ccdPhoto.FirstOrDefault(x => x.houseSn == CurrentHouseId && x.wellSn == well);
  1174. if (cc != null && cc.clearestPosition > 0) return cc.clearestPosition;
  1175. return null;
  1176. }
  1177. /// <summary>
  1178. /// 解析三个手调输入框(空=继承设备级取回退值),返回有效 (count,spacing,down) 或 null(非法/缺失)。
  1179. /// validateMsg 携带校验失败原因。
  1180. /// </summary>
  1181. private (int count, int spacing, int down)? ResolveEffectiveTune(out string validateMsg)
  1182. {
  1183. validateMsg = null;
  1184. // 解析层数:空→设备级回退;非空→必须 int。
  1185. int? count;
  1186. if (string.IsNullOrWhiteSpace(ManualLayerCount)) count = tLSetting?.focusLayerCount;
  1187. else if (int.TryParse(ManualLayerCount.Trim(), out int c)) count = c;
  1188. else { validateMsg = "层数只能输入整数"; return null; }
  1189. int? spacing;
  1190. if (string.IsNullOrWhiteSpace(ManualLayerSpacing)) spacing = tLSetting?.focusLayerSpacingPulse;
  1191. else if (int.TryParse(ManualLayerSpacing.Trim(), out int s)) spacing = s;
  1192. else { validateMsg = "层间距只能输入整数"; return null; }
  1193. int? down;
  1194. if (string.IsNullOrWhiteSpace(ManualMoveDown)) down = tLSetting?.focusLayerDown;
  1195. else if (int.TryParse(ManualMoveDown.Trim(), out int d)) down = d;
  1196. else { validateMsg = "下移层数只能输入整数"; return null; }
  1197. if (!count.HasValue) { validateMsg = "层数未配置(设备级也为空),请填层数或先初始化设备级"; return null; }
  1198. if (!spacing.HasValue) { validateMsg = "层间距未配置(设备级也为空),请填层间距或先初始化设备级(§2.5 不兜底)"; return null; }
  1199. if (!down.HasValue) { validateMsg = "下移层数未配置(设备级也为空),请填下移层数"; return null; }
  1200. // 校验:层数≥1、间距>0、下移≥0 且 <层数(下移层须落在拍摄范围内)。
  1201. if (count.Value < 1) { validateMsg = "层数必须 ≥ 1"; return null; }
  1202. if (spacing.Value <= 0) { validateMsg = "层间距必须 > 0"; return null; }
  1203. if (down.Value < 0) { validateMsg = "下移层数必须 ≥ 0"; return null; }
  1204. if (down.Value >= count.Value) { validateMsg = $"下移层数必须 < 层数({count.Value}),否则清晰层落在拍摄范围外"; return null; }
  1205. return (count.Value, spacing.Value, down.Value);
  1206. }
  1207. /// <summary>
  1208. /// M2-07 实时预览:用该 well 标定 FocusZ + 当前手调值,调 M2-02
  1209. /// ComputeLayerPositions(focusZ, cfg, pulseMax) 生成各层绝对 Z,刷新 LayerPreview(关联 V-045)。
  1210. /// 无标定锚点 → 清空预览并提示先标定;校验非法 → 清空预览并提示。
  1211. /// </summary>
  1212. public void PreviewManualLayers()
  1213. {
  1214. try
  1215. {
  1216. var focusZ = GetPreviewFocusZ(ManualTuneWell);
  1217. if (!focusZ.HasValue)
  1218. {
  1219. SetLayerPreview(null);
  1220. AddMessageInfo($"[手调拍摄层]well{ManualTuneWell} 无标定结果,请先对该 well 标定(或确认已下发清晰位置)再预览");
  1221. return;
  1222. }
  1223. var eff = ResolveEffectiveTune(out string msg);
  1224. if (eff == null)
  1225. {
  1226. SetLayerPreview(null);
  1227. AddMessageInfo($"[手调拍摄层]预览失败:{msg}");
  1228. return;
  1229. }
  1230. var cfg = new FocusLayerConfig
  1231. {
  1232. LayerCount = eff.Value.count,
  1233. LayerSpacingPulse = eff.Value.spacing,
  1234. LayerDown = eff.Value.down,
  1235. };
  1236. int pulseMax = tLSetting != null ? tLSetting.verticalMotorPulseMax : 0;
  1237. int[] positions = PhotoLayerCalculator.ComputeLayerPositions(focusZ.Value, cfg, pulseMax);
  1238. var items = new List<LayerPreviewItem>();
  1239. for (int i = 0; i < positions.Length; i++)
  1240. {
  1241. items.Add(new LayerPreviewItem
  1242. {
  1243. LayerIndex = i,
  1244. ZPulse = positions[i],
  1245. IsFocusLayer = (i == eff.Value.down), // 第 down 层 = 清晰层(FocusZ 锚点)
  1246. });
  1247. }
  1248. SetLayerPreview(items);
  1249. AddMessageInfo($"[手调拍摄层]well{ManualTuneWell} 预览:锚点FocusZ={focusZ.Value} 层数={eff.Value.count} " +
  1250. $"间距={eff.Value.spacing} 下移={eff.Value.down} → 第0层Z={positions[0]} 第{positions.Length - 1}层Z={positions[positions.Length - 1]}");
  1251. }
  1252. catch (Exception ex)
  1253. {
  1254. SetLayerPreview(null);
  1255. ExLog(ex, "PreviewManualLayers");
  1256. AddMessageInfo($"[手调拍摄层]预览异常:{ex.Message}");
  1257. }
  1258. }
  1259. /// <summary>
  1260. /// M2-07 保存为该 well 默认:校验通过后,把手调值写 house_well_setting well 级覆盖
  1261. /// (focus_layer_spacing_pulse/focus_layer_count + 复用 move_down_layer)。
  1262. /// 复用现有 operate 端 well 设置保存通道 HttpHelper.WellUpdateApi(同 SetWellMotorPosition/SetWellAutoFocus),
  1263. /// 走 /api/tl/control/setting/house/well/update。留空字段=继承设备级(写 null)。
  1264. /// 下次该 well 经 §2.5 就近优先(PhotoLayerCalculator.Resolve)沿用 well 覆盖值。
  1265. /// 返回 true=保存成功。
  1266. /// </summary>
  1267. public bool SaveManualLayerTune()
  1268. {
  1269. try
  1270. {
  1271. if (CurrentHouse == null)
  1272. {
  1273. AddMessageInfo("[手调拍摄层]未获取到舱室信息");
  1274. return false;
  1275. }
  1276. // 校验:层数≥1、间距>0、下移≥0 且 <层数;非法不保存。
  1277. var eff = ResolveEffectiveTune(out string msg);
  1278. if (eff == null)
  1279. {
  1280. AddMessageInfo($"[手调拍摄层]保存被拦截(非法值):{msg}");
  1281. return false;
  1282. }
  1283. // 留空字段=继承设备级 → 写 null(well 级覆盖留空,§2.5)。非空字段写实际值。
  1284. int? wellCount = string.IsNullOrWhiteSpace(ManualLayerCount) ? (int?)null : int.Parse(ManualLayerCount.Trim());
  1285. int? wellSpacing = string.IsNullOrWhiteSpace(ManualLayerSpacing) ? (int?)null : int.Parse(ManualLayerSpacing.Trim());
  1286. // 下移复用 move_down_layer(库列非空);留空时回退取生效值(eff.down)写回,不破坏旧列语义。
  1287. int wellMoveDown = string.IsNullOrWhiteSpace(ManualMoveDown) ? eff.Value.down : int.Parse(ManualMoveDown.Trim());
  1288. // 复用现有 well 设置保存通道:与 SetWellMotorPosition/SetWellAutoFocus 同一 WellUpdateApi。
  1289. // 后端按 tlSn/houseSn/wellSn 定位 house_well_setting 行做部分更新(仅本次携带的字段)。
  1290. string body = JsonConvert.SerializeObject(new
  1291. {
  1292. tlSn = CurrentHouse.tlSn,
  1293. houseSn = CurrentHouse.houseSn,
  1294. wellSn = ManualTuneWell,
  1295. focusLayerSpacingPulse = wellSpacing, // null=继承设备级
  1296. focusLayerCount = wellCount, // null=继承设备级
  1297. moveDownLayer = wellMoveDown, // 复用既有列(下移)
  1298. });
  1299. bool ok = AppData.Instance.HttpHelper.WellUpdateApi(body);
  1300. if (!ok)
  1301. {
  1302. AddMessageInfo("[手调拍摄层]保存失败(接口返回失败)");
  1303. return false;
  1304. }
  1305. // 本地内存同步,使"下次该 well 沿用"在不重载设置时也即时生效(预览/取数一致)。
  1306. var ws = houseWellSettingList.FirstOrDefault(x => x.houseSn == CurrentHouseId && x.wellSn == ManualTuneWell);
  1307. if (ws != null)
  1308. {
  1309. ws.focusLayerCount = wellCount;
  1310. ws.focusLayerSpacingPulse = wellSpacing;
  1311. ws.moveDownLayer = wellMoveDown;
  1312. }
  1313. AddMessageInfo($"[手调拍摄层]well{ManualTuneWell} 已存为默认:层数={(wellCount?.ToString() ?? "继承")} " +
  1314. $"间距={(wellSpacing?.ToString() ?? "继承")} 下移={wellMoveDown}(写 house_well_setting well 级覆盖,留空继承设备级)");
  1315. return true;
  1316. }
  1317. catch (Exception ex)
  1318. {
  1319. ExLog(ex, "SaveManualLayerTune");
  1320. AddMessageInfo($"[手调拍摄层]保存异常:{ex.Message}");
  1321. return false;
  1322. }
  1323. }
  1324. private void SetLayerPreview(List<LayerPreviewItem> items)
  1325. {
  1326. void build()
  1327. {
  1328. LayerPreview.Clear();
  1329. if (items != null)
  1330. foreach (var it in items) LayerPreview.Add(it);
  1331. }
  1332. var disp = System.Windows.Application.Current?.Dispatcher;
  1333. if (disp != null && !disp.CheckAccess()) disp.Invoke(build); else build();
  1334. }
  1335. #endregion
  1336. }
  1337. }