HouseDebugPageViewModel.cs 73 KB

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