HouseDebugPageViewModel.cs 73 KB

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