AppData.cs 80 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864
  1. using DBEntity;
  2. using Google.Protobuf;
  3. using ivf_tl_Com;
  4. using ivf_tl_Controller;
  5. using IvfTl.Control.Entity.DBEntitys;
  6. using IvfTl.Control.Entity.DTO;
  7. using IvfTl.Control.Entity.DTO.ApiRequestDTO;
  8. using IvfTl.Control.Entity.DTO.ApiResultDTO;
  9. using IvfTl.Control.Entity.GlobalEntitys;
  10. using IvfTl.Control.Entity.GlobalEnums;
  11. using IvfTl.Control.Entity.InitEntitys;
  12. using IvfTl.Control.Services;
  13. using IvfTl.Control.Services.HttpServices;
  14. using ivf_tl_ServicesImpl.DBServices;
  15. using ivf_tl_ServicesImpl.HttpServices;
  16. using ivf_tl_ServicesImpl.KafkaServices;
  17. using ivf_tl_ServicesImpl.LogServices;
  18. using ivf_tl_ServicesImpl.MqttServices;
  19. using ivf_tl_UtilHelper;
  20. using IvfTl.AutoFocus.Storage;
  21. using NetTaste;
  22. using Newtonsoft.Json;
  23. using Newtonsoft.Json.Linq;
  24. using Npgsql.TypeHandlers.GeometricHandlers;
  25. using System;
  26. using System.Collections.Generic;
  27. using System.Configuration;
  28. using System.Linq;
  29. using System.Diagnostics;
  30. using System.IO;
  31. using System.Text.Json.Nodes;
  32. using System.Windows;
  33. using System.Windows.Markup;
  34. namespace ivf_tl_Control
  35. {
  36. public class AppData
  37. {
  38. public static AppData Instance = new Lazy<AppData>(() => new AppData(), LazyThreadSafetyMode.ExecutionAndPublication).Value;
  39. public int guanbiTime = 0, csTime = 120, houseVentNum = 10, houseVentPre = 20, houseVentWaitTimeB = 1500, houseVentWaitTimeD = 5000, houseAutoWaitTime = 10, houseCCDAutoWaitTime = 5, houseCCDError = 0, houseCCDFailedNumber = 3, houseCCDFailedWaitTime = 15, queuAir = 0;
  40. public event Action StopProEvent;
  41. public bool MvcTest { get; set; } = false;
  42. public string TakePhotoString = string.Empty;
  43. private AppData()
  44. {
  45. _urlIp = $"{ConfigurationManager.AppSettings["urlIp"]}:{ConfigurationManager.AppSettings["urlPort"]}/";
  46. kfkaIP = $"{ConfigurationManager.AppSettings["kfkaIP"]}:{ConfigurationManager.AppSettings["kfkaPort"]}";
  47. // M5-01-2 / R8:mqttIp/mqttPort 启动期容错读取,缺键不崩在构造里(mqttIp 缺键回退空串,mqttPort 缺键/非数回退 1883)。
  48. MqttIp = ConfigurationManager.AppSettings["mqttIp"] ?? string.Empty;
  49. MqttPort = int.TryParse(ConfigurationManager.AppSettings["mqttPort"], out int mqttPortVal) ? mqttPortVal : 1883;
  50. if (int.TryParse(ConfigurationManager.AppSettings["gbTime"].ToString(), out int newTime1)) guanbiTime = newTime1;
  51. if (int.TryParse(ConfigurationManager.AppSettings["csTime"].ToString(), out int newTime2)) csTime = newTime2;
  52. if (int.TryParse(ConfigurationManager.AppSettings["VentNum"].ToString(), out int newTime3)) houseVentNum = newTime3;
  53. if (int.TryParse(ConfigurationManager.AppSettings["VentPre"].ToString(), out int newTime4)) houseVentPre = newTime4;
  54. if (int.TryParse(ConfigurationManager.AppSettings["VentWaitTimeB"].ToString(), out int newTime5)) houseVentWaitTimeB = newTime5;
  55. if (int.TryParse(ConfigurationManager.AppSettings["VentWaitTimeD"].ToString(), out int newTime6)) houseVentWaitTimeD = newTime6;
  56. if (int.TryParse(ConfigurationManager.AppSettings["AutoWaitTime"].ToString(), out int newTime7)) houseAutoWaitTime = newTime7;
  57. if (int.TryParse(ConfigurationManager.AppSettings["CCDAutoWaitTime"].ToString(), out int newTime8)) houseCCDAutoWaitTime = newTime8;
  58. if (int.TryParse(ConfigurationManager.AppSettings["CCDError"].ToString(), out int newTime9)) houseCCDError = newTime9;
  59. if (int.TryParse(ConfigurationManager.AppSettings["CCDFailedNumber"].ToString(), out int newTime10)) houseCCDFailedNumber = newTime10;
  60. if (int.TryParse(ConfigurationManager.AppSettings["CCDFailedWaitTime"].ToString(), out int newTime11)) houseCCDFailedWaitTime = newTime11;
  61. if (int.TryParse(ConfigurationManager.AppSettings["QueuAir"].ToString(), out int newTime12)) queuAir = newTime12;
  62. TakePhotoString = GetLanguageStringByKey("D0010");
  63. //_urlIp = "http://gateway.aivfo.com:36000/";
  64. //MqttIp = "211.149.139.131";
  65. //MqttPort = 61883;
  66. //_urlIp = "http://test-gateway.aivfo.com:36000/";
  67. //MqttIp = "211.149.139.131";
  68. //MqttPort = 62883;
  69. ImageDTODic = new Dictionary<string, ImageDTO>();
  70. sqlitePath = $"{Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, @"DependFile\DB\aivfoTL.db")}";
  71. LogService = new LogServiceImpl() { Pan = "C" };
  72. HttpService = new HttpService(_urlIp);
  73. HttpService.ErrorLogEvent += LogService.TLLog;
  74. HttpService.ExceptionLogEvent += LogService.ExceptionLog;
  75. DBService = new DBService();
  76. DBService.ErrorLogEvent += LogService.TLLog;
  77. DBService.ExceptionLogEvent += LogService.ExceptionLog;
  78. DBService.StartDbService(sqlitePath);
  79. // M2-04 标定结果存储:calibration.json 真相源 + 镜像 house_autofocus_calibration。
  80. // JSON 路径走部署工作目录(DependFile\AutoFocus),不写死 autofocustool 测试外壳常量路径。
  81. // DbMirror 绑定到 DBService.SaveAutofocusCalibration(scene 0 upsert / 1 append);
  82. // 任一步骤异常 CalibrationStore 内部已吞掉并经 Log 记录,不崩对焦/采集线程。
  83. string calibJsonPath = Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, @"DependFile\AutoFocus\calibration.json");
  84. AutofocusStore = new CalibrationStore
  85. {
  86. JsonPath = calibJsonPath,
  87. Source = "LOCAL_JSON",
  88. Log = msg => LogService.TLLog(msg, LogEnum.RunError),
  89. DbMirror = (tlSn, houseSn, wellSn, scene, focusZ, exposure, horizontalPulse, peakRatio, circleFound, centerOffsetPct, note, source) =>
  90. DBService.SaveAutofocusCalibration(tlSn, houseSn, wellSn, scene, focusZ, exposure, horizontalPulse, peakRatio, circleFound, centerOffsetPct, note, source),
  91. // M2-06 安全门降级:关闭本地对焦时按 scene=0 基准位置拍照,由此回调读基准 FocusZ。
  92. BaselineReader = (tlSn, houseSn, wellSn) => DBService.GetBaselineFocusZ(tlSn, houseSn, wellSn),
  93. };
  94. KafkaService = new KafkaService(kafkaTopic, kfkaIP);
  95. KafkaService.ErrorLogEvent += LogService.TLLog;
  96. KafkaService.ExceptionLogEvent += LogService.ExceptionLog;
  97. MqttService = new MqttService(MqttIp, MqttPort, MqttUserName, MqttPassword);
  98. MqttService.ErrorLogEvent += LogService.TLLog;
  99. MqttService.ExceptionLogEvent += LogService.ExceptionLog;
  100. MqttService.MessEvent += MqttMessage;
  101. MqttService.MqttAlarm += MqttAlarm;
  102. SerialBinController = new SerialBinController(HttpService, DBService);
  103. SerialBinController.LogEvent += LogService.TLLog;
  104. SerialBinController.ExceptionLogEvent += LogService.ExceptionLog;
  105. HouseBinController = new HouseBinController(HttpService, DBService);
  106. HouseBinController.LogEvent += LogService.TLLog;
  107. HouseBinController.ExceptionLogEvent += LogService.ExceptionLog;
  108. }
  109. public void TestEvent()
  110. {
  111. //string messageinfo = $"{GetLanguageStringByKey("D0007")}1{GetLanguageStringByKey("D0008")}";
  112. //MessageBox.Show(messageinfo);
  113. //string ss = GetLanguageStringByKey("D0001");
  114. //return;
  115. StopProEvent?.Invoke();
  116. }
  117. public string _urlIp = "http://192.168.31.89:10010/";
  118. //public string _urlIp = "http://gateway.aivfo.com:36000/";
  119. private string kafkaTopic = "jiangxuebingPicTestTopic";
  120. private string kfkaIP = "192.168.31.89:9092";
  121. private string MqttIp = "211.149.139.131";
  122. private int MqttPort = 1883;
  123. private string MqttUserName = "aivfo";
  124. private string MqttPassword = "aivfo";
  125. private string MqttClientId = "TL/DATA/tlSn";
  126. private string MqttTopicName = "TL/DATA/tlSn";
  127. private string sqlitePath = "";
  128. private bool isSetZiDong = false;
  129. public Dictionary<string, ImageDTO> ImageDTODic { get; set; }
  130. // ── M5-04-3:图片补传补强 ──
  131. // (a) 去重防重传:StartUpLoadImage 每 5s 重扫落盘目录,单文件一次上传可能跨多个 5s 周期(慢链/超时),
  132. // 用 in-flight 集合标记「正在上传」,重扫时跳过,避免同名文件被两轮并发重传(现 ImageDTODic lock 只护缓存)。
  133. private readonly HashSet<string> _uploadingFiles = new HashSet<string>();
  134. // (b) 断网累积兜底告警阈值:落盘待传数超过此值视为断网堆积,置位告警(只读暴露给监控/提示),不静默堆积。
  135. // [D10] 具体阈值留 M7 校准;此处为占位默认值。
  136. public int PendingImageAlarmThreshold { get; set; } = 500;
  137. // 断网累积告警状态(只读):true=待传堆积超阈值。供 GetMonitorSnapshot/断线提示呈现,不触发删图。
  138. public bool ImageBacklogAlarm { get; private set; }
  139. public int LastPendingImageCount { get; private set; }
  140. public SerialBinController SerialBinController { get; set; }
  141. public HouseBinController HouseBinController { get; set; }
  142. public ILogService LogService { get; set; }
  143. public HttpService HttpService { get; set; }
  144. public DBService DBService { get; set; }
  145. /// <summary>M2-04 标定结果存储入口(calibration.json 真相源 + house_autofocus_calibration 镜像)。</summary>
  146. public CalibrationStore AutofocusStore { get; set; }
  147. public KafkaService KafkaService { get; set; }
  148. public MqttService MqttService { get; set; }
  149. public UserInfo CurrentUser { get; set; }
  150. /// <summary>启动期坏舱清单(InitTL 写入;GetMonitorSnapshot 透出 /status;ReportStartupFaults 经 reportAlarm 闭环上报)。</summary>
  151. public List<HouseFault> StartupFaults { get; set; } = new List<HouseFault>();
  152. public TLSetting TLSetting;
  153. public HouseBin HouseBin1;
  154. public HouseBin HouseBin2;
  155. public HouseBin HouseBin3;
  156. public HouseBin HouseBin4;
  157. public HouseBin HouseBin5;
  158. public HouseBin HouseBin6;
  159. public HouseBin HouseBin7;
  160. public HouseBin HouseBin8;
  161. public HouseBin HouseBin9;
  162. public HouseBin HouseBin10;
  163. public BufferBottleBin BufferBottleBin;
  164. /// <summary>D2-02 第三阶段:按 houseSn 读该舱培养态(Dish!=null=在培养),供调试 acquire 给 operate 弹确认框。只读,不改采集。</summary>
  165. public (bool cultivating, int embryoCount) GetCultivation(int houseSn)
  166. {
  167. try
  168. {
  169. // 复用本类既有「按 houseSn 取 HouseBin」入口(舱11/越界无 case → 返回 null,下面兜底 false,0)。
  170. var bin = HouseSnToHouseBin(houseSn);
  171. var dish = bin?.Dish; // 缓冲瓶舱11无养胚胎 → 视为不培养
  172. if (dish == null) return (false, 0);
  173. // 优先数"仍在培养(state==0)"的胚胎(总数 embryoCount 含已移植/冷冻/作废的,不代表此刻在养);取不到明细则退回 embryoCount。
  174. int count = dish.Embryo != null && dish.Embryo.Count > 0
  175. ? dish.Embryo.Count(e => e.state == 0)
  176. : dish.embryoCount;
  177. return (true, count > 0 ? count : 0);
  178. }
  179. catch (Exception ex)
  180. {
  181. // 敏感场景(误停胚胎确认框该弹没弹)须可排查:吞异常但补日志;日志本身 try 包住,绝不二次抛影响借用。
  182. try { ExLog(ex, "GetCultivation"); } catch { }
  183. return (false, 0);
  184. }
  185. }
  186. // ── M5-03-2:各链路「最后成功通讯时间」只读时间戳 ──
  187. // 仅在已有的成功分支里赋值(不改上报逻辑/不改报文),供 GetMonitorSnapshot 只读呈现「不假装实时」。
  188. // LastHttpOkAt 由 operate 侧 HTTP 轮询(M5-04-4)写入,control 这里只持有/透传。
  189. public DateTime? LastMqttOkAt { get; private set; }
  190. public DateTime? LastKafkaOkAt { get; private set; }
  191. public DateTime? LastHttpOkAt { get; set; }
  192. /// <summary>
  193. /// M5-03-1:聚合 control 内存/事件的当前状态为只读快照(需求 7/10)。
  194. /// 纯读取 + 拷贝到值类型 DTO,不修改任何 control 状态、不暴露可写引用,监控页据此只读呈现。
  195. /// 任一字段取值异常被吞掉(监控页不应因取数失败而崩),缺失项以默认值呈现。
  196. /// </summary>
  197. public MonitorSnapshot GetMonitorSnapshot()
  198. {
  199. var snap = new MonitorSnapshot { SnapshotAt = DateTime.Now, ControlHosted = true };
  200. try
  201. {
  202. // MQTT 连接态(来源 MqttService.MqttIsConnected())
  203. try { snap.MqttConnected = MqttService != null && MqttService.MqttIsConnected(); } catch { snap.MqttConnected = false; }
  204. snap.LastMqttOkAt = LastMqttOkAt;
  205. try { snap.MqttLastConnectedAt = MqttService?.LastConnectedAt; } catch { }
  206. try { snap.MqttLastDisconnectedAt = MqttService?.LastDisconnectedAt; } catch { }
  207. snap.LastKafkaOkAt = LastKafkaOkAt;
  208. snap.LastHttpOkAt = LastHttpOkAt;
  209. // 服务器接口基址(脱敏展示,仅地址不含凭据)
  210. snap.ServerUrl = _urlIp;
  211. // 上传队列:内存缓存数 + 落盘目录待传数
  212. try { lock (ImageDTODic) snap.ImageCacheCount = ImageDTODic == null ? 0 : ImageDTODic.Count; } catch { }
  213. try { snap.PendingDiskImageCount = CountPendingDiskImages(); } catch { }
  214. snap.ImageBacklogAlarm = ImageBacklogAlarm;
  215. snap.PendingImageAlarmThreshold = PendingImageAlarmThreshold;
  216. // 磁盘(来源 GetDiskInfo(缓存盘))
  217. try
  218. {
  219. string pan = TLSetting != null && !string.IsNullOrEmpty(TLSetting.tmpDir) ? TLSetting.tmpDir : PathHelper.pan;
  220. if (!string.IsNullOrEmpty(pan))
  221. {
  222. var disk = GetDiskInfo(pan);
  223. snap.DiskPath = disk.diskPath;
  224. snap.DiskExist = disk.diskExist == 0;
  225. snap.DiskFreeGb = disk.diskSpace;
  226. }
  227. }
  228. catch { }
  229. // 各舱室只读态
  230. var bins = new HouseBin[] { HouseBin1, HouseBin2, HouseBin3, HouseBin4, HouseBin5, HouseBin6, HouseBin7, HouseBin8, HouseBin9, HouseBin10 };
  231. int sn = 0;
  232. foreach (var bin in bins)
  233. {
  234. sn++;
  235. if (bin == null) continue;
  236. try
  237. {
  238. snap.Houses.Add(new HouseMonitorRow
  239. {
  240. HouseSn = sn,
  241. PortName = bin.PortName,
  242. RunState = bin.RunState,
  243. Temperature = bin.Temperature,
  244. Pressure = bin.Pressure,
  245. HouseState = bin.IsDoorOpen.ToString(),
  246. ComState = bin.ComBin != null ? "已连接" : "未连接",
  247. CcdState = bin.CCDError ? "异常" : "正常",
  248. CcdError = bin.CCDError,
  249. // 阶段2 §6 三块补充(只读)
  250. WorkingType = bin.WorkingType.ToString(),
  251. ValveState = bin.ValveState.ToString(),
  252. CapturePausedByGate = bin.CapturePausedByGate,
  253. });
  254. }
  255. catch { }
  256. }
  257. }
  258. catch (Exception ex)
  259. {
  260. ExLog(ex, "GetMonitorSnapshot");
  261. }
  262. // 舱故障透出(StartupFaults → HouseFaultRow,字符串化枚举跨端);独立 try,不影响其余快照。
  263. try
  264. {
  265. snap.Faults = (StartupFaults ?? new List<HouseFault>())
  266. .Select(f => new HouseFaultRow
  267. {
  268. HouseSn = f.HouseSn,
  269. FaultType = f.Type.ToString(),
  270. Reason = f.Reason,
  271. Stage = f.Stage,
  272. At = f.At,
  273. Isolated = f.Isolated
  274. }).ToList();
  275. }
  276. catch { }
  277. return snap;
  278. }
  279. /// <summary>落盘目录(自动对焦 + CCD)待传 *.jpg 计数(只读,不删不改)。</summary>
  280. private int CountPendingDiskImages()
  281. {
  282. int count = 0;
  283. try
  284. {
  285. string autoPath = PathHelper.GetAutoFocusSaveDirectory();
  286. if (Directory.Exists(autoPath)) count += Directory.GetFiles(autoPath, "*.jpg").Length;
  287. }
  288. catch { }
  289. try
  290. {
  291. string ccdPath = PathHelper.GetEmbryoPicSaveDirectory();
  292. if (Directory.Exists(ccdPath)) count += Directory.GetFiles(ccdPath, "*.jpg").Length;
  293. }
  294. catch { }
  295. return count;
  296. }
  297. private void ExLog(Exception ex, string name)
  298. {
  299. LogService.ExceptionLog(ex, $"AppData.{name}", null, LogEnum.RunException);
  300. }
  301. public bool Login(string _account, string _password)
  302. {
  303. try
  304. {
  305. CurrentUser = HttpService.Login(_account, _password);
  306. return CurrentUser != null;
  307. }
  308. catch (Exception ex)
  309. {
  310. ExLog(ex, "Login");
  311. return false;
  312. }
  313. }
  314. /// <summary>
  315. /// 开启kafka、mqtt、历史记录上报
  316. /// </summary>
  317. /// <returns></returns>
  318. public async Task StartAsync()
  319. {
  320. KafkaService.KafkaSetNameAndIp(TLSetting.kafkaTopic, kfkaIP);
  321. var kafkaSuccess = await KafkaService.CreateTopicAsync(3);
  322. if (kafkaSuccess)
  323. {
  324. if (!MvcTest) StartUpLoadImage();
  325. }
  326. else
  327. {
  328. LogService.TLLog($"kafka创建分区失败", LogEnum.RunError);
  329. }
  330. MqttClientId = $"TL/DATA/{TLSetting.tlSn}";
  331. MqttService.StartMqtt(TLSetting.mqttQueue, MqttClientId);
  332. StartSendMqttMsg();
  333. StartSendHistoryMsg();
  334. StartPushMessageThread();
  335. Task.Run(() => DeleteLog());
  336. }
  337. /// <summary>
  338. /// 重启kafka、mqtt
  339. /// </summary>
  340. private void UpdataKafkaAndMqtt()
  341. {
  342. if (KafkaService.KafkaSetNameAndIp(TLSetting.kafkaTopic, kfkaIP))
  343. {
  344. var kafkaSuccess = KafkaService.CreateTopicAsync(3).Result;
  345. if (!kafkaSuccess)
  346. {
  347. LogService.TLLog($"kafka创建分区失败", LogEnum.RunError);
  348. }
  349. }
  350. if (!MqttService.IsXiangTong(TLSetting.mqttQueue, $"TL/DATA/{TLSetting.tlSn}"))
  351. {
  352. MqttService.IsDispose = true;
  353. MqttService = new MqttService(MqttIp, MqttPort, MqttUserName, MqttPassword);
  354. MqttService.ErrorLogEvent += LogService.TLLog;
  355. MqttService.ExceptionLogEvent += LogService.ExceptionLog;
  356. MqttService.MessEvent += MqttMessage;
  357. MqttClientId = $"TL/DATA/{TLSetting.tlSn}";
  358. MqttService.StartMqtt(TLSetting.mqttQueue, MqttClientId);
  359. }
  360. }
  361. /// <summary>
  362. /// 开启图片上传线程
  363. /// </summary>
  364. public void StartUpLoadImage()
  365. {
  366. LogService.TLLog($"开始运行kafka线程", LogEnum.KafkaRecord);
  367. Task.Factory.StartNew(async () =>
  368. {
  369. while (true)
  370. {
  371. try
  372. {
  373. string autoPath = PathHelper.GetAutoFocusSaveDirectory();
  374. if (Directory.Exists(autoPath))
  375. {
  376. var autoFileList = Directory.GetFiles(autoPath, "*.jpg");
  377. foreach (var item in autoFileList)
  378. {
  379. await KafkaUploadImageAsync(item);
  380. }
  381. }
  382. string ccdPath = PathHelper.GetEmbryoPicSaveDirectory();
  383. if (Directory.Exists(ccdPath))
  384. {
  385. var ccdFileList = Directory.GetFiles(ccdPath, "*.jpg");
  386. foreach (var item in ccdFileList)
  387. {
  388. await KafkaUploadImageAsync(item);
  389. }
  390. }
  391. // M5-04-3(b):断网累积兜底——每轮重扫后统计落盘待传数,超阈值置位告警(只读,供监控/断线提示)。
  392. // 不删图、不丢图,只把「堆积」显性暴露,避免静默撑爆磁盘(配合 M5-03 磁盘水位)。
  393. try
  394. {
  395. int pending = CountPendingDiskImages();
  396. LastPendingImageCount = pending;
  397. bool backlog = pending > PendingImageAlarmThreshold;
  398. if (backlog && !ImageBacklogAlarm)
  399. LogService.TLLog($"图片待传堆积告警:落盘待传 {pending} 张已超阈值 {PendingImageAlarmThreshold},疑似上传链路断开", LogEnum.RunError);
  400. ImageBacklogAlarm = backlog;
  401. }
  402. catch { }
  403. await Task.Delay(1000 * 5);
  404. }
  405. catch (Exception ex)
  406. {
  407. LogService.ExceptionLog(ex, "上传图片", null, LogEnum.RunException);
  408. }
  409. }
  410. }, TaskCreationOptions.LongRunning);
  411. }
  412. /// <summary>
  413. /// 开启mqtt消息上报线程
  414. /// </summary>
  415. public void StartSendMqttMsg()
  416. {
  417. LogService.TLLog($"Mqtt开始上报", LogEnum.MqttClient);
  418. Task.Factory.StartNew(async () =>
  419. {
  420. while (true)
  421. {
  422. try
  423. {
  424. if (!MqttService.MqttIsConnected())
  425. {
  426. await Task.Delay(3000);
  427. continue;
  428. }
  429. List<HouseMqttData> houseMqttDataList = new List<HouseMqttData>();
  430. var a = GetHouseMqttData(HouseBin1);
  431. if (a != null) houseMqttDataList.Add(a);
  432. a = GetHouseMqttData(HouseBin2);
  433. if (a != null) houseMqttDataList.Add(a);
  434. a = GetHouseMqttData(HouseBin3);
  435. if (a != null) houseMqttDataList.Add(a);
  436. a = GetHouseMqttData(HouseBin4);
  437. if (a != null) houseMqttDataList.Add(a);
  438. a = GetHouseMqttData(HouseBin5);
  439. if (a != null) houseMqttDataList.Add(a);
  440. a = GetHouseMqttData(HouseBin6);
  441. if (a != null) houseMqttDataList.Add(a);
  442. a = GetHouseMqttData(HouseBin7);
  443. if (a != null) houseMqttDataList.Add(a);
  444. a = GetHouseMqttData(HouseBin8);
  445. if (a != null) houseMqttDataList.Add(a);
  446. a = GetHouseMqttData(HouseBin9);
  447. if (a != null) houseMqttDataList.Add(a);
  448. a = GetHouseMqttData(HouseBin10);
  449. if (a != null) houseMqttDataList.Add(a);
  450. a = GetHouseMqttData(BufferBottleBin);
  451. if (a != null) houseMqttDataList.Add(a);
  452. if (houseMqttDataList.Any() && MqttService.MqttIsConnected())
  453. {
  454. string mqttMsg = JsonConvert.SerializeObject(houseMqttDataList);
  455. await MqttService.PublishAsync(mqttMsg);
  456. LastMqttOkAt = DateTime.Now; // M5-03-2:MQTT 上报成功时间戳(只读监控用,不改上报逻辑)
  457. }
  458. await Task.Delay(1000);
  459. }
  460. catch (Exception ex)
  461. {
  462. LogService.ExceptionLog(ex, "实时数据上报", null, LogEnum.RunException);
  463. }
  464. }
  465. }, TaskCreationOptions.LongRunning);
  466. }
  467. /// <summary>
  468. /// 开启仓时历史记录上报线程
  469. /// </summary>
  470. public void StartSendHistoryMsg()
  471. {
  472. LogService.TLLog($"开启仓时历史记录上报线程", LogEnum.KafkaRecord);
  473. Task.Factory.StartNew(async () =>
  474. {
  475. await Task.Delay(1000 * 60);
  476. List<HouseHistoryData> houseMqttDataList = new List<HouseHistoryData>();
  477. HouseHistoryData a = null;
  478. while (true)
  479. {
  480. try
  481. {
  482. //只上报缓冲瓶的历史记录
  483. houseMqttDataList.Clear();
  484. a = GetHouseHistoryData(BufferBottleBin);
  485. if (a != null) houseMqttDataList.Add(a);
  486. if (houseMqttDataList.Any()) SerialBinController.ReportDataController(JsonConvert.SerializeObject(houseMqttDataList));
  487. //List<HouseHistoryData> houseMqttDataList = new List<HouseHistoryData>();
  488. //var a = GetHouseHistoryData(HouseBin1);
  489. //if (a != null) houseMqttDataList.Add(a);
  490. //a = GetHouseHistoryData(HouseBin2);
  491. //if (a != null) houseMqttDataList.Add(a);
  492. //a = GetHouseHistoryData(HouseBin3);
  493. //if (a != null) houseMqttDataList.Add(a);
  494. //a = GetHouseHistoryData(HouseBin4);
  495. //if (a != null) houseMqttDataList.Add(a);
  496. //a = GetHouseHistoryData(HouseBin5);
  497. //if (a != null) houseMqttDataList.Add(a);
  498. //a = GetHouseHistoryData(HouseBin6);
  499. //if (a != null) houseMqttDataList.Add(a);
  500. //a = GetHouseHistoryData(HouseBin7);
  501. //if (a != null) houseMqttDataList.Add(a);
  502. //a = GetHouseHistoryData(HouseBin8);
  503. //if (a != null) houseMqttDataList.Add(a);
  504. //a = GetHouseHistoryData(HouseBin9);
  505. //if (a != null) houseMqttDataList.Add(a);
  506. //a = GetHouseHistoryData(HouseBin10);
  507. //if (a != null) houseMqttDataList.Add(a);
  508. //a = GetHouseHistoryData(BufferBottleBin);
  509. //if (a != null) houseMqttDataList.Add(a);
  510. //if (houseMqttDataList.Any())
  511. //{
  512. // string mqttMsg = JsonConvert.SerializeObject(houseMqttDataList);
  513. // SerialBinController.ReportDataController(mqttMsg);
  514. //}
  515. //await Task.Delay(1000 * TLSetting.historyCurveInterval);
  516. }
  517. catch (Exception ex)
  518. {
  519. LogService.ExceptionLog(ex, "仓时历史记录上报", null, LogEnum.RunException);
  520. }
  521. finally
  522. {
  523. await Task.Delay(1000 * TLSetting.historyCurveInterval);
  524. }
  525. }
  526. }, TaskCreationOptions.LongRunning);
  527. }
  528. /// <summary>
  529. /// 开启心跳线程
  530. /// </summary>
  531. public void StartPushMessageThread()
  532. {
  533. int time = 1000 * 60 * 10;
  534. Task.Factory.StartNew(() =>
  535. {
  536. while (true)
  537. {
  538. try
  539. {
  540. SerialBinController.PushMessageController(TLSetting.tlSn, 1, GetDiskInfo(TLSetting.tmpDir));
  541. if (DateTime.Now.Hour != TLSetting.autoFocusTime)
  542. {
  543. if (isSetZiDong) isSetZiDong = false;
  544. continue;
  545. }
  546. if (isSetZiDong) continue;
  547. Task.Run(() => DeleteLog());
  548. Task.Run(() => CleanAutofocusCalibration()); // G4-1:每日维护窗口同步清理对焦标定 scene=1 过期记录
  549. isSetZiDong = true;
  550. if (HouseBin1 != null)
  551. {
  552. HouseBin1.FirstClearest = true;
  553. HouseBin1.ReCa = true;
  554. }
  555. if (HouseBin2 != null)
  556. {
  557. HouseBin2.FirstClearest = true;
  558. HouseBin2.ReCa = true;
  559. }
  560. if (HouseBin3 != null)
  561. {
  562. HouseBin3.FirstClearest = true;
  563. HouseBin3.ReCa = true;
  564. }
  565. if (HouseBin4 != null)
  566. {
  567. HouseBin4.FirstClearest = true;
  568. HouseBin4.ReCa = true;
  569. }
  570. if (HouseBin5 != null)
  571. {
  572. HouseBin5.FirstClearest = true;
  573. HouseBin5.ReCa = true;
  574. }
  575. if (HouseBin6 != null)
  576. {
  577. HouseBin6.FirstClearest = true;
  578. HouseBin6.ReCa = true;
  579. }
  580. if (HouseBin7 != null)
  581. {
  582. HouseBin7.FirstClearest = true;
  583. HouseBin7.ReCa = true;
  584. }
  585. if (HouseBin8 != null)
  586. {
  587. HouseBin8.FirstClearest = true;
  588. HouseBin8.ReCa = true;
  589. }
  590. if (HouseBin9 != null)
  591. {
  592. HouseBin9.FirstClearest = true;
  593. HouseBin9.ReCa = true;
  594. }
  595. if (HouseBin10 != null)
  596. {
  597. HouseBin10.FirstClearest = true;
  598. HouseBin10.ReCa = true;
  599. }
  600. }
  601. catch (Exception ex)
  602. {
  603. LogService.ExceptionLog(ex, "心跳线程", null, LogEnum.RunException);
  604. }
  605. finally
  606. {
  607. Thread.Sleep(time);
  608. }
  609. }
  610. }, TaskCreationOptions.LongRunning);
  611. }
  612. #region 仓室事件设置
  613. /// <summary>
  614. /// 仓室事件初始化
  615. /// </summary>
  616. /// <param name="BufferBottleBin"></param>
  617. public void InitHouseBinEvent(HouseBin houseBin)
  618. {
  619. houseBin.TLLogEvent += LogService.TLLog;
  620. houseBin.HouseLogEvent += LogService.HouseLog;
  621. houseBin.ExceptionLogEvent += LogService.ExceptionLog;
  622. houseBin.GetAutoFocusServiceEvent += HouseBin_GetAutoFocusServiceEvent;
  623. houseBin.GetAutoFocusDBEvent += HouseBin_GetAutoFocusDBEvent;
  624. // M2-04:注入标定结果存储入口(写 JSON 真相源 + 镜像库),对焦逐 well 标定后调用。
  625. houseBin.AutofocusStore = AutofocusStore;
  626. houseBin.GetCCDServiceEvent += HouseBin_GetCCDServiceEvent;
  627. houseBin.GetCCDDBEvent += HouseBin_GetCCDDBEvent;
  628. houseBin.UploadImageEvent += HouseBin_UploadImageEvent;
  629. houseBin.UpdateAutofocusStateEvent += HouseBin_UpdateAutofocusStateEvent;
  630. houseBin.SavePicDbEvent += HouseBin_SavePicDbEvent;
  631. houseBin.HouseStateEvent += HouseBin_HouseStateEvent;
  632. houseBin.CCDStateEvent += HouseBinPhotoStateEvent;
  633. houseBin.OnHistoryEvent += HouseBin_OnHistoryEvent;
  634. houseBin.ChangeBufferBottleBinEvent += HouseBin_ChangeBufferBottleBinEvent;
  635. houseBin.HouseBinChangeBufferBottleBinEvent += HouseBin_HouseBinChangeBufferBottleBinEvent;
  636. //houseBin.CCDStateEvent += HouseBin_CCDStateEvent;
  637. houseBin.TongQi = csTime * 1000;
  638. houseBin.VentPre = houseVentPre;
  639. houseBin.VentNum = houseVentNum;
  640. houseBin.VentWaitTimeB = houseVentWaitTimeB;
  641. houseBin.VentWaitTimeD = houseVentWaitTimeD;
  642. houseBin.AutoWaitTime = houseAutoWaitTime * 60000;
  643. houseBin.CCDAutoWaitTime = houseCCDAutoWaitTime * 60000;
  644. houseBin.CCDFailedNumber = houseCCDFailedNumber;
  645. houseBin.CCDFailedWaitTime = houseCCDFailedWaitTime * 1000;
  646. if (houseCCDError == 1)
  647. {
  648. houseBin.CCDError = true;
  649. }
  650. else
  651. {
  652. houseBin.CCDError = false;
  653. }
  654. if (queuAir == 0)
  655. {
  656. houseBin.IsPai = false;
  657. }
  658. else
  659. {
  660. houseBin.IsPai = true;
  661. }
  662. houseBin.TakePhotoFailed = TakePhotoString;
  663. }
  664. private void HouseBin_CCDStateEvent(int houseSn, int ccdState)
  665. {
  666. if (ccdState == 1)
  667. {
  668. LogService.TLLog($"{houseSn}号舱室拍照异常,停止拍照", LogEnum.RunRecord);
  669. }
  670. else
  671. {
  672. LogService.TLLog($"{houseSn}号舱室拍照恢复正常", LogEnum.RunRecord);
  673. }
  674. }
  675. private bool HouseBin_HouseBinChangeBufferBottleBinEvent(HouseBin arg1, int arg2)
  676. {
  677. if (BufferBottleBin == null)
  678. {
  679. LogService.TLLog($"缓冲瓶为空,无法操作进气阀:{arg1}、{arg2}", LogEnum.RunError);
  680. return false;
  681. }
  682. if (arg2 == 0)
  683. {
  684. BufferBottleBin.HuanQiEnd(arg1);
  685. return true;
  686. }
  687. else if (arg2 == 1)
  688. {
  689. BufferBottleBin.HuanQiStart(arg1);
  690. return true;
  691. }
  692. else
  693. {
  694. LogService.TLLog($"状态码错误,无法操作进气阀:{arg1}、{arg2}", LogEnum.RunError);
  695. return false;
  696. }
  697. }
  698. private bool HouseBin_ChangeBufferBottleBinEvent(int arg1, int arg2)
  699. {
  700. if (BufferBottleBin == null)
  701. {
  702. LogService.TLLog($"缓冲瓶为空,无法操作进气阀:{arg1}、{arg2}", LogEnum.RunError);
  703. return false;
  704. }
  705. if (arg2 == 0)
  706. {
  707. BufferBottleBin.CloseIntakeValve(arg1);
  708. return true;
  709. }
  710. else if (arg2 == 1)
  711. {
  712. BufferBottleBin.OpenIntakeValve(arg1);
  713. return true;
  714. }
  715. else
  716. {
  717. LogService.TLLog($"状态码错误,无法操作进气阀:{arg1}、{arg2}", LogEnum.RunError);
  718. return false;
  719. }
  720. }
  721. private void HouseBin_OnHistoryEvent(HouseHistoryData obj)
  722. {
  723. SerialBinController.ReportDataController(JsonConvert.SerializeObject(new List<HouseHistoryData> { obj }));
  724. }
  725. private void HouseBin_HouseStateEvent(int housesn, int houseState, int comState, int photoState, int wellSN, int airSwapState)
  726. {
  727. SerialBinController.ReportAlarmController(TLSetting.tlSn, housesn, houseState, comState, photoState, wellSN, airSwapState);
  728. //if (photoState != 0)
  729. //{
  730. // SerialBinController.ReportAlarmController(TLSetting.tlSn, housesn, houseState, comState, photoState, wellSN, airSwapState);
  731. // return;
  732. //}
  733. //for (int i = 1; i <= 16; i++)
  734. //{
  735. // SerialBinController.ReportAlarmController(TLSetting.tlSn, housesn, houseState, comState, photoState, i, airSwapState);
  736. //}
  737. }
  738. private void HouseBinPhotoStateEvent(int housesn, int photoState, int wellSN)
  739. {
  740. if (photoState != 0)
  741. {
  742. SerialBinController.ReportAlarmController(TLSetting.tlSn, housesn, -1, -1, photoState, wellSN, -1);
  743. StopProEvent?.Invoke();
  744. return;
  745. }
  746. for (int i = 1; i <= 16; i++)
  747. {
  748. SerialBinController.ReportAlarmController(TLSetting.tlSn, housesn, -1, -1, photoState, i, -1);
  749. }
  750. }
  751. /// <summary>
  752. /// 仓室图片保存到数据库
  753. /// </summary>
  754. /// <param name="obj"></param>
  755. /// <exception cref="NotImplementedException"></exception>
  756. private void HouseBin_SavePicDbEvent(ImageDTO obj)
  757. {
  758. if (obj == null) return;
  759. SerialBinController.SavePictreController(obj);
  760. }
  761. /// <summary>
  762. /// 仓室上传图片
  763. /// </summary>
  764. /// <param name="obj"></param>
  765. private void HouseBin_UploadImageEvent(ImageDTO obj)
  766. {
  767. if (obj == null) return;
  768. lock (ImageDTODic)
  769. {
  770. if (ImageDTODic.Count > 50)
  771. {
  772. LogService.TLLog($"内存当中保存的图片已经超过50张了{obj.HouseSn}、{obj.WellSn}、{obj.SourceImageName}", LogEnum.RunError);
  773. return;
  774. }
  775. if (!ImageDTODic.ContainsKey(obj.SourceImageName))
  776. {
  777. ImageDTODic.Add(obj.SourceImageName, obj);
  778. }
  779. }
  780. }
  781. /// <summary>
  782. /// 从服务器获取自动对焦位置
  783. /// </summary>
  784. /// <param name="arg1"></param>
  785. /// <param name="arg2"></param>
  786. /// <param name="arg3"></param>
  787. /// <returns></returns>
  788. private List<HouseWellPhoto> HouseBin_GetAutoFocusServiceEvent(int arg1, Dictionary<int, DateTime?> arg3)
  789. {
  790. List<WellSnAndAutoTime> wellSnAndAutoTimes = new List<WellSnAndAutoTime>();
  791. foreach (var item in arg3)
  792. {
  793. wellSnAndAutoTimes.Add(new WellSnAndAutoTime
  794. {
  795. well = item.Key,
  796. autofocusTime = item.Value.HasValue ? item.Value.Value.ToString("yyyy-MM-dd HH:mm:ss") : null,
  797. });
  798. }
  799. PositionRequestDTO positionRequestDTO = new PositionRequestDTO()
  800. {
  801. houseSn = arg1,
  802. tlSn = TLSetting.tlSn,
  803. wellSnList = wellSnAndAutoTimes,
  804. };
  805. return HouseBinController.GetAutoFocusController(positionRequestDTO);
  806. }
  807. /// <summary>
  808. /// 从数据库获取自动对焦位置
  809. /// </summary>
  810. /// <param name="arg1"></param>
  811. /// <param name="arg2"></param>
  812. /// <param name="arg3"></param>
  813. /// <returns></returns>
  814. private List<HouseWellPhoto> HouseBin_GetAutoFocusDBEvent(int arg1, Dictionary<int, DateTime?> arg3)
  815. {
  816. List<WellSnAndAutoTime> wellSnAndAutoTimes = new List<WellSnAndAutoTime>();
  817. foreach (var item in arg3)
  818. {
  819. wellSnAndAutoTimes.Add(new WellSnAndAutoTime
  820. {
  821. well = item.Key,
  822. autofocusTime = item.Value.HasValue ? item.Value.Value.ToString("yyyy-MM-dd HH:mm:ss") : null,
  823. });
  824. }
  825. PositionRequestDTO positionRequestDTO = new PositionRequestDTO()
  826. {
  827. houseSn = arg1,
  828. tlSn = TLSetting.tlSn,
  829. wellSnList = wellSnAndAutoTimes,
  830. };
  831. return HouseBinController.DbGetPositionData(positionRequestDTO.wellSnList.Select(x => x.well).ToList(), positionRequestDTO.houseSn, positionRequestDTO.tlSn, 0);
  832. }
  833. /// <summary>
  834. /// 服务器获取仓室拍照位置
  835. /// </summary>
  836. /// <param name="arg1"></param>
  837. /// <param name="arg2"></param>
  838. /// <param name="arg3"></param>
  839. /// <returns></returns>
  840. private PositionInfoResultDTO HouseBin_GetCCDServiceEvent(int arg1, Dictionary<int, DateTime?> arg3)
  841. {
  842. List<WellSnAndAutoTime> wellSnAndAutoTimes = new List<WellSnAndAutoTime>();
  843. foreach (var item in arg3)
  844. {
  845. wellSnAndAutoTimes.Add(new WellSnAndAutoTime
  846. {
  847. well = item.Key,
  848. autofocusTime = item.Value.HasValue ? item.Value.Value.ToString("yyyy-MM-dd HH:mm:ss") : null,
  849. });
  850. }
  851. PositionRequestDTO positionRequestDTO = new PositionRequestDTO()
  852. {
  853. houseSn = arg1,
  854. wellSnList = wellSnAndAutoTimes,
  855. tlSn = TLSetting.tlSn,
  856. };
  857. var result = HouseBinController.GetCCDPositionController(positionRequestDTO);
  858. if (result != null && result.complete == 0)//完成
  859. {
  860. List<HouseWellPhoto> CCDPositionList = new List<HouseWellPhoto>();
  861. foreach (var item in result.positionVOList)
  862. {
  863. CCDPositionList.Add(ConvertHelper.ConvertToHouseWellPhoto(item));
  864. }
  865. HouseBinController.DbUpdatePositionData(CCDPositionList, positionRequestDTO.houseSn, positionRequestDTO.tlSn, 1);
  866. }
  867. return result;
  868. }
  869. /// <summary>
  870. /// 数据库获取仓室拍照位置
  871. /// </summary>
  872. /// <param name="arg1"></param>
  873. /// <param name="arg2"></param>
  874. /// <param name="arg3"></param>
  875. /// <returns></returns>
  876. private List<HouseWellPhoto> HouseBin_GetCCDDBEvent(int arg1, Dictionary<int, DateTime?> arg3)
  877. {
  878. List<WellSnAndAutoTime> wellSnAndAutoTimes = new List<WellSnAndAutoTime>();
  879. foreach (var item in arg3)
  880. {
  881. wellSnAndAutoTimes.Add(new WellSnAndAutoTime
  882. {
  883. well = item.Key,
  884. autofocusTime = item.Value.HasValue ? item.Value.Value.ToString("yyyy-MM-dd HH:mm:ss") : null,
  885. });
  886. }
  887. PositionRequestDTO positionRequestDTO = new PositionRequestDTO()
  888. {
  889. houseSn = arg1,
  890. wellSnList = wellSnAndAutoTimes,
  891. tlSn = TLSetting.tlSn,
  892. };
  893. return HouseBinController.DbGetPositionData(positionRequestDTO.wellSnList.Select(x => x.well).ToList(), positionRequestDTO.houseSn, positionRequestDTO.tlSn, 1);
  894. }
  895. private void HouseBin_UpdateAutofocusStateEvent(bool newValue, int housesn)
  896. {
  897. int autoFocus = 0;
  898. if (newValue)
  899. {
  900. autoFocus = 1;
  901. }
  902. SerialBinController.UpdateAutofocusStateController(TLSetting.tlSn, housesn, autoFocus);
  903. }
  904. /// <summary>
  905. /// 缓冲瓶事件初始化
  906. /// </summary>
  907. /// <param name="BufferBottleBin"></param>
  908. public void InitBufferBottleBinEvent(BufferBottleBin BufferBottleBin)
  909. {
  910. BufferBottleBin.TLLogEvent += LogService.TLLog;
  911. BufferBottleBin.HouseLogEvent += LogService.HouseLog;
  912. BufferBottleBin.ExceptionLogEvent += LogService.ExceptionLog;
  913. BufferBottleBin.HouseStateEvent += HouseBin_HouseStateEvent;
  914. }
  915. #endregion
  916. #region mqtt消息处理
  917. /// <summary>
  918. /// mqtt接受消息
  919. /// </summary>
  920. /// <param name="message"></param>
  921. public void MqttMessage(string message)
  922. {
  923. if (string.IsNullOrEmpty(message)) return;
  924. MqttResult mqttResult = null;
  925. bool isSuccess = true;
  926. string uuid = null;
  927. try
  928. {
  929. mqttResult = JsonConvert.DeserializeObject<MqttResult>(message);
  930. if (mqttResult == null)
  931. {
  932. LogService.TLLog($"AppData.MqttMessage,mqtt消息反序列化失败,消息:{message}", LogEnum.MqttClient);
  933. return;
  934. }
  935. switch (mqttResult.type)
  936. {
  937. case (int)MqttEnum.StartBalance:
  938. isSuccess = StartBalance(mqttResult.data);
  939. break;
  940. case (int)MqttEnum.EndBalance:
  941. isSuccess = EndBalance(mqttResult.data);
  942. break;
  943. case (int)MqttEnum.StartDish:
  944. isSuccess = StartDish(mqttResult.data);
  945. break;
  946. case (int)MqttEnum.EndDish:
  947. isSuccess = EndDish(mqttResult.data);
  948. break;
  949. case (int)MqttEnum.EmbryoState:
  950. isSuccess = EmbryoState(mqttResult.data);
  951. break;
  952. case (int)MqttEnum.Update:
  953. isSuccess = UpDataSettingMqtt(mqttResult.data);
  954. break;
  955. case (int)MqttEnum.DebugStart:
  956. isSuccess = DebugStart(mqttResult.data, ref uuid);
  957. break;
  958. case (int)MqttEnum.HouseAutoFocus:
  959. isSuccess = HouseAutoFocus(mqttResult.data);
  960. break;
  961. case (int)MqttEnum.WellAutoFocus:
  962. isSuccess = WellAutoFocus(mqttResult.data);
  963. break;
  964. }
  965. }
  966. catch (Exception ex)
  967. {
  968. LogService.ExceptionLog(ex, "mqtt消息处理", null, LogEnum.RunException);
  969. isSuccess = false;
  970. }
  971. finally
  972. {
  973. if (mqttResult != null)
  974. {
  975. if (string.IsNullOrEmpty(uuid))
  976. {
  977. SerialBinController.MqttResultController(isSuccess ? 200 : 400, isSuccess, mqttResult.messageId);
  978. }
  979. else
  980. {
  981. SerialBinController.MqttResultController(isSuccess ? 200 : 400, isSuccess, mqttResult.messageId, uuid);
  982. }
  983. }
  984. }
  985. }
  986. /// <summary>
  987. /// 开始平衡
  988. /// </summary>
  989. /// <param name="data"></param>
  990. /// <returns></returns>
  991. private bool StartBalance(object data)
  992. {
  993. try
  994. {
  995. Balance balance = JsonConvert.DeserializeObject<Balance>(data.ToString());
  996. DBService.AddBalance(balance);
  997. HouseBin currentHouseBin = HouseSnToHouseBin(balance.houseSn);
  998. if (currentHouseBin == null) return false;
  999. currentHouseBin.StartBlance(balance);
  1000. return true;
  1001. }
  1002. catch (Exception ex)
  1003. {
  1004. ExLog(ex, "StartBalance");
  1005. return false;
  1006. }
  1007. }
  1008. private bool EndBalance(object data)
  1009. {
  1010. try
  1011. {
  1012. Balance balance = JsonConvert.DeserializeObject<Balance>(data.ToString());
  1013. HouseBin currentHouseBin = HouseSnToHouseBin(balance.houseSn);
  1014. if (currentHouseBin == null) return false;
  1015. DBService.EndBalance(balance.id, balance.endTime);
  1016. currentHouseBin.StopBlance();
  1017. return true;
  1018. }
  1019. catch (Exception ex)
  1020. {
  1021. ExLog(ex, "EndBalance");
  1022. return false;
  1023. }
  1024. }
  1025. private bool StartDish(object data)
  1026. {
  1027. try
  1028. {
  1029. Dish dish = JsonConvert.DeserializeObject<Dish>(data.ToString());
  1030. DBService.AddDish(dish, dish.tlSn);
  1031. HouseBin currentHouseBin = HouseSnToHouseBin(dish.houseSn);
  1032. if (currentHouseBin == null) return false;
  1033. currentHouseBin.StartDish(dish);
  1034. return true;
  1035. }
  1036. catch (Exception ex)
  1037. {
  1038. ExLog(ex, "StartDish");
  1039. return false;
  1040. }
  1041. }
  1042. private bool EndDish(object data)
  1043. {
  1044. try
  1045. {
  1046. Dish dish = JsonConvert.DeserializeObject<Dish>(data.ToString());
  1047. DBService.EndDish(dish.id, dish.endTime.Value, dish.tlSn);
  1048. HouseBin currentHouseBin = HouseSnToHouseBin(dish.houseSn);
  1049. if (currentHouseBin == null) return false;
  1050. currentHouseBin.StopDish();
  1051. return true;
  1052. }
  1053. catch (Exception ex)
  1054. {
  1055. ExLog(ex, "EndDish");
  1056. return false;
  1057. }
  1058. }
  1059. private bool DebugStart(object data, ref string uuid)
  1060. {
  1061. try
  1062. {
  1063. //System.Collections.IList list = param["list"] as System.Collections.IList;
  1064. //JArray itemObject = (JArray)keyValuePair.Value;
  1065. //foreach (KeyValuePair<string, JToken> keyValuePair in jobject)
  1066. if (data == null) return false;
  1067. if (string.IsNullOrEmpty(data.ToString())) return false;
  1068. JObject jObject = JObject.Parse(data.ToString());
  1069. string tlsn = jObject["tlSn"].ToString();
  1070. uuid = jObject["uuid"].ToString();
  1071. int housesn = int.Parse(jObject["houseSn"].ToString());
  1072. switch (housesn)
  1073. {
  1074. case 1:
  1075. HouseBin1.IsDebug = true;
  1076. break;
  1077. case 2:
  1078. HouseBin2.IsDebug = true;
  1079. break;
  1080. case 3:
  1081. HouseBin3.IsDebug = true;
  1082. break;
  1083. case 4:
  1084. HouseBin4.IsDebug = true;
  1085. break;
  1086. case 5:
  1087. HouseBin5.IsDebug = true;
  1088. break;
  1089. case 6:
  1090. HouseBin6.IsDebug = true;
  1091. break;
  1092. case 7:
  1093. HouseBin7.IsDebug = true;
  1094. break;
  1095. case 8:
  1096. HouseBin8.IsDebug = true;
  1097. break;
  1098. case 9:
  1099. HouseBin9.IsDebug = true;
  1100. break;
  1101. case 10:
  1102. HouseBin10.IsDebug = true;
  1103. break;
  1104. }
  1105. bool IsDebugOk = false;
  1106. do
  1107. {
  1108. switch (housesn)
  1109. {
  1110. case 1:
  1111. IsDebugOk = HouseBin1.isDebugOk;
  1112. break;
  1113. case 2:
  1114. IsDebugOk = HouseBin2.isDebugOk;
  1115. break;
  1116. case 3:
  1117. IsDebugOk = HouseBin3.isDebugOk;
  1118. break;
  1119. case 4:
  1120. IsDebugOk = HouseBin4.isDebugOk;
  1121. break;
  1122. case 5:
  1123. IsDebugOk = HouseBin5.isDebugOk;
  1124. break;
  1125. case 6:
  1126. IsDebugOk = HouseBin6.isDebugOk;
  1127. break;
  1128. case 7:
  1129. IsDebugOk = HouseBin7.isDebugOk;
  1130. break;
  1131. case 8:
  1132. IsDebugOk = HouseBin8.isDebugOk;
  1133. break;
  1134. case 9:
  1135. IsDebugOk = HouseBin9.isDebugOk;
  1136. break;
  1137. case 10:
  1138. IsDebugOk = HouseBin10.isDebugOk;
  1139. break;
  1140. }
  1141. if (IsDebugOk)
  1142. {
  1143. break;
  1144. }
  1145. Thread.Sleep(1000);
  1146. } while (true);
  1147. return true;
  1148. }
  1149. catch (Exception ex)
  1150. {
  1151. LogService.ExceptionLog(ex, "mqtt.DebugStart", null, LogEnum.RunException);
  1152. return false;
  1153. }
  1154. }
  1155. private bool EmbryoState(object data)
  1156. {
  1157. try
  1158. {
  1159. Embryo embryo = JsonConvert.DeserializeObject<Embryo>(data.ToString());
  1160. DBService.ChangeEmbryoState(embryo);
  1161. HouseBin currentHouseBin = HouseSnToHouseBin(embryo.houseSn);
  1162. if (currentHouseBin == null) return false;
  1163. currentHouseBin.ChangeEmbryoState(embryo);
  1164. return true;
  1165. }
  1166. catch (Exception ex)
  1167. {
  1168. ExLog(ex, "EmbryoState");
  1169. return false;
  1170. }
  1171. }
  1172. private bool UpDataSettingMqtt(object data)
  1173. {
  1174. try
  1175. {
  1176. if (data == null) return false;
  1177. string dataString = data.ToString();
  1178. if (string.IsNullOrEmpty(dataString)) return false;
  1179. JObject jObject = JObject.Parse(dataString);
  1180. string tlsn = jObject["tlSn"].ToString();
  1181. string dateTime = jObject["updateTime"].ToString();
  1182. return UpdateSetting(tlsn);
  1183. }
  1184. catch (Exception ex)
  1185. {
  1186. ExLog(ex, "UpDataSettingMqtt");
  1187. return false;
  1188. }
  1189. }
  1190. public bool HouseAutoFocus(object data)
  1191. {
  1192. try
  1193. {
  1194. HouseAutoFocusMqtt houseAutoFocus = JsonConvert.DeserializeObject<HouseAutoFocusMqtt>(data.ToString());
  1195. if (houseAutoFocus == null || !houseAutoFocus.houseSnList.Any())
  1196. {
  1197. LogService.TLLog($"json转换失败,不更新配置信息{data.ToString()}", LogEnum.RunError);
  1198. return false;
  1199. }
  1200. if (!UpdateSetting(houseAutoFocus.tlSn))
  1201. {
  1202. LogService.TLLog($"更新配置信息失败,不开启自动对焦", LogEnum.RunError);
  1203. return false;
  1204. }
  1205. foreach (var houseSn in houseAutoFocus.houseSnList)
  1206. {
  1207. HouseBin currentHouseBin = HouseSnToHouseBin(houseSn);
  1208. if (currentHouseBin == null)
  1209. {
  1210. LogService.TLLog($"开启自动对焦时,获取舱室为空,{houseSn}、{data.ToString()}", LogEnum.RunError);
  1211. continue;
  1212. }
  1213. currentHouseBin.HouseAutoFocus();
  1214. }
  1215. return true;
  1216. }
  1217. catch (Exception ex)
  1218. {
  1219. ExLog(ex, "HouseAutoFocus");
  1220. return false;
  1221. }
  1222. }
  1223. public bool WellAutoFocus(object data)
  1224. {
  1225. try
  1226. {
  1227. WellAutoFocusMqtt wellAutoFocusMqtt = JsonConvert.DeserializeObject<WellAutoFocusMqtt>(data.ToString());
  1228. if (wellAutoFocusMqtt == null || !wellAutoFocusMqtt.houseSnList.Any()) return false;
  1229. if (!UpdateSetting(wellAutoFocusMqtt.tlSn))
  1230. {
  1231. LogService.TLLog($"更新配置信息失败,不开启自动对焦", LogEnum.RunError);
  1232. return false;
  1233. }
  1234. foreach (var houseSn in wellAutoFocusMqtt.houseSnList)
  1235. {
  1236. HouseBin currentHouseBin = HouseSnToHouseBin(houseSn.house);
  1237. if (currentHouseBin == null) continue;
  1238. currentHouseBin.WellAutoFocus(houseSn.well);
  1239. }
  1240. return true;
  1241. }
  1242. catch (Exception ex)
  1243. {
  1244. ExLog(ex, "WellAutoFocus");
  1245. return false;
  1246. }
  1247. }
  1248. public bool UpdateSetting(string tlsn)
  1249. {
  1250. try
  1251. {
  1252. var initTLResult = SerialBinController.UpdataSettingController(tlsn);
  1253. if (initTLResult == null)
  1254. {
  1255. LogService.TLLog($"更新设置时返回为空", LogEnum.RunError);
  1256. return false;
  1257. }
  1258. TLSetting = initTLResult.TLSetting;
  1259. PathHelper.pan = initTLResult.TLSetting.tmpDir;
  1260. LogService.Pan = initTLResult.TLSetting.tmpDir;
  1261. for (int i = 1; i <= 10; i++)
  1262. {
  1263. HouseBin currentHouseBin = HouseSnToHouseBin(i);
  1264. if (currentHouseBin == null) continue;
  1265. currentHouseBin.UpdataHouseSetting(initTLResult);
  1266. }
  1267. //UpdataKafkaAndMqtt();
  1268. return true;
  1269. }
  1270. catch (Exception ex)
  1271. {
  1272. ExLog(ex, "UpdateSetting");
  1273. return false;
  1274. }
  1275. }
  1276. #endregion
  1277. /// <summary>
  1278. /// mqtt报警
  1279. /// </summary>
  1280. /// <param name="message"></param>
  1281. public void MqttAlarm(string message)
  1282. {
  1283. try
  1284. {
  1285. HttpService.AlarmApi1(TLSetting.tlSn, "CLOUD_SLAVE_MQTT_ALARM", new List<string> { message });
  1286. }
  1287. catch (Exception ex)
  1288. {
  1289. ExLog(ex, "mqtt报警");
  1290. return;
  1291. }
  1292. }
  1293. /// <summary>
  1294. /// 上报启动期坏舱告警(每坏舱一条),复用现有 reportAlarm 报警闭环:
  1295. /// SerialBinController.ReportAlarmController → /reportAlarm → 报警责任链 → alarm 表
  1296. /// → front/operate 报警列表 + 短信/电话通知 + 可静音/恢复自动消警(与运行期 HouseStateEvent 同一入口)。
  1297. /// 维度码 0正常/1异常/-1跳过:相机类故障 → photoState=1;串口/编号/Init 类 → comState=1;其余维度 -1(不误清别的告警)。
  1298. /// 全 try 兜底,失败不影响启动。不走 reportCloudAlarm(群消息),无新增 alarmTypeKey、无 Java 改动。
  1299. /// </summary>
  1300. public void ReportStartupFaults()
  1301. {
  1302. if (StartupFaults == null || StartupFaults.Count == 0) return;
  1303. string tlSn = "";
  1304. try { tlSn = TLSetting?.tlSn ?? ""; } catch { }
  1305. foreach (var f in StartupFaults)
  1306. {
  1307. // 舱号未知(相机/串口级)定位不到具体舱,不进 reportAlarm(仍在 /status Faults 里可见)。
  1308. if (f.HouseSn <= 0) continue;
  1309. try
  1310. {
  1311. bool cameraFault = f.Type == HouseFaultType.CcdSnMissing
  1312. || f.Type == HouseFaultType.CcdSnDuplicate
  1313. || f.Type == HouseFaultType.CameraDuplicateSn
  1314. || f.Type == HouseFaultType.CameraReadFailed;
  1315. int comState = cameraFault ? -1 : 1; // 串口/编号/Init 异常
  1316. int photoState = cameraFault ? 1 : -1; // 相机异常
  1317. SerialBinController.ReportAlarmController(tlSn, f.HouseSn, -1, comState, photoState, -1, -1);
  1318. }
  1319. catch (Exception ex) { ExLog(ex, "ReportStartupFaults"); }
  1320. }
  1321. }
  1322. public void KafkaAlarm(string tlsn, int housesn, ulong dishId, ulong embryoId, string imageName, int wellSn)
  1323. {
  1324. try
  1325. {
  1326. HttpService.AlarmApi(tlsn, housesn, wellSn, "CLOUD_SLAVE_KAFKA_ALARM", new List<string> { dishId.ToString(), embryoId.ToString(), imageName });
  1327. }
  1328. catch (Exception ex)
  1329. {
  1330. ExLog(ex, "图片传输失败报警");
  1331. return;
  1332. }
  1333. }
  1334. public void KafkaAlarmChaoShi(string tlsn, int housesn, ulong dishId, ulong embryoId, string imageName, int wellSn)
  1335. {
  1336. try
  1337. {
  1338. HttpService.AlarmApi(tlsn, housesn, wellSn, "CLOUD_SLAVE_PICTURE_TRANSFER_ALARM", new List<string> { dishId.ToString(), embryoId.ToString(), imageName });
  1339. }
  1340. catch (Exception ex)
  1341. {
  1342. ExLog(ex, "图片传输超时报警");
  1343. return;
  1344. }
  1345. }
  1346. private async Task KafkaUploadImageAsync(string fileFullPath)
  1347. {
  1348. // M5-04-3(a):去重防并发重传。同名文件在上一轮上传未结束(慢链/超时)时,5s 重扫会再次进入本方法,
  1349. // 此处用 in-flight 集合保证同一文件同一时刻只有一条上传在跑;释放放在 finally,不影响「成功才删」语义。
  1350. string fileName = Path.GetFileName(fileFullPath);
  1351. lock (_uploadingFiles)
  1352. {
  1353. if (_uploadingFiles.Contains(fileName)) return; // 正在上传,跳过本轮重扫的重复触发
  1354. _uploadingFiles.Add(fileName);
  1355. }
  1356. try
  1357. {
  1358. Stopwatch stopwatch = Stopwatch.StartNew();
  1359. //LogService.TLLog($"准备上传{fileFullPath}", LogEnum.KafkaRecord);
  1360. ImageDTO imageDTO = null;
  1361. lock (ImageDTODic) if (ImageDTODic.ContainsKey(fileName)) imageDTO = ImageDTODic[fileName];
  1362. if (imageDTO == null)
  1363. {
  1364. imageDTO = SerialBinController.SearchPictureController(fileName, TLSetting.tlSn);
  1365. if (imageDTO == null)
  1366. {
  1367. LogService.TLLog($"数据库获取文件失败:{fileName}、{TLSetting.tlSn}:{fileFullPath}", LogEnum.RunError);
  1368. }
  1369. else
  1370. {
  1371. var imageBytes = AivfoHelper.GetImageData1(fileFullPath);
  1372. if (imageBytes == null)
  1373. {
  1374. LogService.TLLog($"上传中止,图片不存在:{fileFullPath}", LogEnum.RunError);
  1375. }
  1376. else
  1377. {
  1378. imageDTO.ImageData = ByteString.CopyFrom(imageBytes);
  1379. }
  1380. }
  1381. }
  1382. if (imageDTO == null)
  1383. {
  1384. LogService.TLLog($"上传中止,imageDTO为空:{fileFullPath}", LogEnum.KafkaRecord);
  1385. string newDir = PathHelper.GetErrorSaveDirectory();
  1386. if (!Directory.Exists(newDir)) Directory.CreateDirectory(newDir);
  1387. File.Move(fileFullPath, Path.Combine(newDir, fileName));
  1388. return;
  1389. }
  1390. //LogService.TLLog($"fileName文件大小:{imageDTO.ImageData.Count()}", LogEnum.KafkaRecord);
  1391. var time1 = stopwatch.Elapsed;
  1392. //LogService.TLLog($"开始上传{fileFullPath},准备耗时:{time1}毫秒", LogEnum.KafkaRecord);
  1393. var uploadResult = await KafkaService.kafkaProducerAsync(imageDTO);
  1394. var time2 = stopwatch.Elapsed;
  1395. //LogService.TLLog($"上传结束{fileFullPath},耗时:{time2 - time1}毫秒", LogEnum.KafkaRecord);
  1396. if (!uploadResult)
  1397. {
  1398. KafkaAlarm(imageDTO.TlSn, imageDTO.HouseSn, imageDTO.EmbryoCultureRecordId, imageDTO.EmbryoId, imageDTO.SourceImageName, imageDTO.WellSn);
  1399. LogService.TLLog($"上传失败:{fileFullPath}", LogEnum.RunError);
  1400. return;
  1401. }
  1402. if ((time2 - time1).TotalMilliseconds > 1000)
  1403. {
  1404. KafkaAlarmChaoShi(imageDTO.TlSn, imageDTO.HouseSn, imageDTO.EmbryoCultureRecordId, imageDTO.EmbryoId, imageDTO.SourceImageName, imageDTO.WellSn);
  1405. LogService.TLLog($"kafka上传超时:{fileFullPath}", LogEnum.RunError);
  1406. }
  1407. LastKafkaOkAt = DateTime.Now; // M5-03-2:Kafka 图片上传成功时间戳(只读监控用,不改上传逻辑)
  1408. lock (ImageDTODic) if (ImageDTODic.ContainsKey(fileName)) ImageDTODic.Remove(fileName);
  1409. if (File.Exists(fileFullPath))
  1410. {
  1411. try
  1412. {
  1413. File.Delete(fileFullPath);
  1414. }
  1415. catch (Exception ex)
  1416. {
  1417. LogService.ExceptionLog(ex, "kafka上传完成删除图片", null, LogEnum.RunException);
  1418. }
  1419. //if (imageDTO.PhotographType == 1)
  1420. //{
  1421. // string newpath = @"C:\TLData\AutofocusControlBreak";
  1422. // if (!Directory.Exists(newpath)) Directory.CreateDirectory(newpath);
  1423. // File.Move(fileFullPath, Path.Combine(newpath, fileName));
  1424. //}
  1425. //else
  1426. //{
  1427. // string newpath = @"C:\TLData\EmbryosControlBreak";
  1428. // if (!Directory.Exists(newpath)) Directory.CreateDirectory(newpath);
  1429. // File.Move(fileFullPath, Path.Combine(newpath, fileName));
  1430. //}
  1431. }
  1432. SerialBinController.DeletePictrueController(fileName, TLSetting.tlSn);
  1433. //LogService.TLLog($"上传完成:{fileFullPath},总耗时:{stopwatch.ElapsedMilliseconds}毫秒", LogEnum.KafkaRecord);
  1434. }
  1435. catch (Exception ex)
  1436. {
  1437. LogService.ExceptionLog(ex, "kafka上传图片", null, LogEnum.RunException);
  1438. return;
  1439. }
  1440. finally
  1441. {
  1442. // M5-04-3(a):无论成功/失败/中止,都释放 in-flight 标记,使下一轮重扫可重试(失败文件仍在落盘 → 不丢)。
  1443. lock (_uploadingFiles) _uploadingFiles.Remove(fileName);
  1444. }
  1445. }
  1446. private HouseMqttData GetHouseMqttData(HouseBin currentHouseBin)
  1447. {
  1448. if (currentHouseBin == null) return null;
  1449. if (currentHouseBin.House == null) return null;
  1450. int cultureState = 0;
  1451. if (currentHouseBin.Balance != null && currentHouseBin.Balance.id > 0) cultureState = 2;
  1452. if (currentHouseBin.Dish != null && currentHouseBin.Dish.id > 0) cultureState = 1;
  1453. return new HouseMqttData()
  1454. {
  1455. tlSn = TLSetting.tlSn,
  1456. houseSn = currentHouseBin.House.houseSn,
  1457. pressure = currentHouseBin.Pressure,
  1458. temperature = currentHouseBin.Temperature,
  1459. houseDoorState = currentHouseBin.IsDoorOpen == State.打开 ? 1 : 0,
  1460. pressureDesc = currentHouseBin.ValveState.ToString(),
  1461. houseDesc = currentHouseBin.RunState,
  1462. cultureState = cultureState,
  1463. houseState = (int)currentHouseBin.WorkingType,
  1464. };
  1465. }
  1466. private HouseMqttData GetHouseMqttData(BufferBottleBin currentBufferBottleBin)
  1467. {
  1468. if (currentBufferBottleBin == null) return null;
  1469. if (currentBufferBottleBin.House == null) return null;
  1470. return new HouseMqttData()
  1471. {
  1472. tlSn = TLSetting.tlSn,
  1473. houseSn = 11,
  1474. pressure = currentBufferBottleBin.BufferBottlePressure,
  1475. temperature = 0,
  1476. houseDoorState = 0,
  1477. pressureDesc = currentBufferBottleBin.ValveState.ToString(),
  1478. houseDesc = currentBufferBottleBin.RunState,
  1479. };
  1480. }
  1481. private HouseHistoryData GetHouseHistoryData(HouseBin currentHouseBin)
  1482. {
  1483. if (currentHouseBin == null) return null;
  1484. if (currentHouseBin.House == null) return null;
  1485. return new HouseHistoryData()
  1486. {
  1487. tlSn = TLSetting.tlSn,
  1488. houseSn = currentHouseBin.House.houseSn,
  1489. pressure = currentHouseBin.Pressure,
  1490. temperature = currentHouseBin.Temperature,
  1491. houseDoor = currentHouseBin.IsDoorOpen == State.打开 ? 1 : 0,
  1492. airSwap = currentHouseBin.WorkingType == WorkingType.AirSwapWorking ? 1 : 0,
  1493. temperatureLowerCover = currentHouseBin.Temperature2,
  1494. temperatureUpperCover = currentHouseBin.Temperature1,
  1495. temperatureLowerGlass = currentHouseBin.Temperature3,
  1496. };
  1497. }
  1498. private HouseHistoryData GetHouseHistoryData(BufferBottleBin currentBufferBottleBin)
  1499. {
  1500. if (currentBufferBottleBin == null) return null;
  1501. if (currentBufferBottleBin.House == null) return null;
  1502. return new HouseHistoryData()
  1503. {
  1504. tlSn = TLSetting.tlSn,
  1505. houseSn = 11,
  1506. pressure = currentBufferBottleBin.BufferBottlePressure,
  1507. temperature = 0,
  1508. houseDoor = 0,
  1509. airSwap = 0,
  1510. temperatureLowerCover = currentBufferBottleBin.Temperature1,
  1511. temperatureUpperCover = currentBufferBottleBin.Temperature2,
  1512. temperatureLowerGlass = 0,
  1513. cultureState = 0,
  1514. };
  1515. }
  1516. /// <summary>
  1517. /// Phase3(D2-02 Task3.2a):按 houseSn 取该舱 HouseBin 的公开访问器,供 ControlHost.CalibrationManager
  1518. /// 标定协作注入(取 per-well 范围 ReadWellFocusRange + 峰比阈值 + tlSn + AutofocusStore)。复用既有私有映射,无对应舱返回 null。
  1519. /// </summary>
  1520. public HouseBin GetHouseBin(int houseSn) => HouseSnToHouseBin(houseSn);
  1521. private HouseBin HouseSnToHouseBin(int housesn)
  1522. {
  1523. HouseBin result = null;
  1524. switch (housesn)
  1525. {
  1526. case 1:
  1527. result = HouseBin1;
  1528. break;
  1529. case 2:
  1530. result = HouseBin2;
  1531. break;
  1532. case 3:
  1533. result = HouseBin3;
  1534. break;
  1535. case 4:
  1536. result = HouseBin4;
  1537. break;
  1538. case 5:
  1539. result = HouseBin5;
  1540. break;
  1541. case 6:
  1542. result = HouseBin6;
  1543. break;
  1544. case 7:
  1545. result = HouseBin7;
  1546. break;
  1547. case 8:
  1548. result = HouseBin8;
  1549. break;
  1550. case 9:
  1551. result = HouseBin9;
  1552. break;
  1553. case 10:
  1554. result = HouseBin10;
  1555. break;
  1556. }
  1557. return result;
  1558. }
  1559. public DiskInfo GetDiskInfo(string pan)
  1560. {
  1561. DiskInfo diskInfo = new DiskInfo() { diskPath = pan };
  1562. try
  1563. {
  1564. string panNew = pan.ToUpper();
  1565. diskInfo.diskExist = Directory.Exists($"{panNew}:\\") ? 0 : 1;
  1566. if (diskInfo.diskExist == 1) return diskInfo;
  1567. bool IsFind = false;
  1568. DriveInfo[] allDirves = DriveInfo.GetDrives();
  1569. foreach (DriveInfo item in allDirves)
  1570. {
  1571. if (item.IsReady)
  1572. {
  1573. if (item.Name == $"{panNew}:\\")
  1574. {
  1575. IsFind = true;
  1576. diskInfo.diskSpace = (decimal)(item.TotalFreeSpace / (1024.00 * 1024.00 * 1024.00));
  1577. break;
  1578. }
  1579. }
  1580. }
  1581. if (!IsFind) diskInfo.diskExist = 1;
  1582. return diskInfo;
  1583. }
  1584. catch (Exception ex)
  1585. {
  1586. LogService.ExceptionLog(ex, "GetDiskInfo", null, LogEnum.RunException);
  1587. diskInfo.diskExist = 1;
  1588. return diskInfo;
  1589. }
  1590. }
  1591. public void DeleteLog()
  1592. {
  1593. try
  1594. {
  1595. string newPath = $"{TLSetting.tmpDir}:\\TLData\\ivf_tl_Control_logs";
  1596. var newDir = Directory.GetDirectories(newPath, "*", SearchOption.TopDirectoryOnly);
  1597. foreach (var item in newDir)
  1598. {
  1599. var dieName = System.IO.Path.GetFileName(item);
  1600. if (DateTime.TryParse(dieName, out DateTime newTime))
  1601. {
  1602. if (DateTime.Now.Subtract(newTime).Days >= 5)
  1603. {
  1604. Directory.Delete(item, true);
  1605. }
  1606. }
  1607. }
  1608. DeleteLogFile($"C:\\TLData\\ivf_tl_Control_logs\\LogError");
  1609. DeleteLogFile($"C:\\TLData\\ivf_tl_Control_logs\\Log");
  1610. }
  1611. catch (Exception ex)
  1612. {
  1613. LogService.ExceptionLog(ex, "DeleteLog", null, LogEnum.RunException);
  1614. }
  1615. }
  1616. /// <summary>
  1617. /// G4-1 / 需求文档12 §2.7:对焦标定数据清理(每日维护窗口触发,与 DeleteLog 同源)。
  1618. /// 保留天数取服务器下发的 TLSetting.cleanAutofocusData(缺省/非正回退 30);
  1619. /// 只删 scene=1 日常对焦记录、scene=0 出厂基准永久保留(由 DBService.CleanAutofocusData 保证)。
  1620. /// 全 try 兜底,异常吞掉记日志,绝不向上抛(不影响采集/对焦)。
  1621. /// </summary>
  1622. public void CleanAutofocusCalibration()
  1623. {
  1624. try
  1625. {
  1626. int keepDays = TLSetting?.cleanAutofocusData ?? 30;
  1627. if (keepDays <= 0) keepDays = 30;
  1628. int n = DBService.CleanAutofocusData(keepDays);
  1629. LogService.TLLog($"对焦标定清理(G4-1):保留 {keepDays} 天,删除 scene=1 共 {n} 条", LogEnum.RunRecord);
  1630. }
  1631. catch (Exception ex)
  1632. {
  1633. LogService.ExceptionLog(ex, "CleanAutofocusCalibration", null, LogEnum.RunException);
  1634. }
  1635. }
  1636. private void DeleteLogFile(string newPath)
  1637. {
  1638. var newDir = Directory.GetFiles(newPath, "*.htm", SearchOption.TopDirectoryOnly);
  1639. string fileName = "";
  1640. DateTime fileTime = DateTime.Now;
  1641. DateTime nowTime = fileTime;
  1642. foreach (var item in newDir)
  1643. {
  1644. fileName = System.IO.Path.GetFileNameWithoutExtension(item);
  1645. if (fileName.Length == 8)
  1646. {
  1647. fileName = fileName.Insert(6, "-");
  1648. fileName = fileName.Insert(4, "-");
  1649. if (DateTime.TryParse(fileName, out fileTime))
  1650. {
  1651. if (nowTime.Subtract(fileTime).Days >= 5)
  1652. {
  1653. try
  1654. {
  1655. File.Delete(item);
  1656. }
  1657. catch (Exception)
  1658. {
  1659. continue;
  1660. }
  1661. }
  1662. }
  1663. }
  1664. }
  1665. }
  1666. public string ReadText(string fileName)
  1667. {
  1668. return File.ReadAllText(fileName);
  1669. }
  1670. public PositionInfoResultDTO HouseBin_GetCCDServiceEventTest(int arg1, Dictionary<int, DateTime?> arg3)
  1671. {
  1672. List<WellSnAndAutoTime> wellSnAndAutoTimes = new List<WellSnAndAutoTime>();
  1673. foreach (var item in arg3)
  1674. {
  1675. wellSnAndAutoTimes.Add(new WellSnAndAutoTime
  1676. {
  1677. well = item.Key,
  1678. autofocusTime = item.Value.HasValue ? item.Value.Value.ToString("yyyy-MM-dd HH:mm:ss") : null,
  1679. });
  1680. }
  1681. PositionRequestDTO positionRequestDTO = new PositionRequestDTO()
  1682. {
  1683. houseSn = arg1,
  1684. wellSnList = wellSnAndAutoTimes,
  1685. tlSn = "NEO-1-20230410",
  1686. };
  1687. var result = HouseBinController.GetCCDPositionController(positionRequestDTO);
  1688. if (result != null && result.complete == 0)//完成
  1689. {
  1690. List<HouseWellPhoto> CCDPositionList = new List<HouseWellPhoto>();
  1691. foreach (var item in result.positionVOList)
  1692. {
  1693. CCDPositionList.Add(ConvertHelper.ConvertToHouseWellPhoto(item));
  1694. }
  1695. HouseBinController.DbUpdatePositionData(CCDPositionList, positionRequestDTO.houseSn, positionRequestDTO.tlSn, 1);
  1696. }
  1697. return result;
  1698. }
  1699. public List<HouseWellPhoto> HouseBin_GetAutoFocusServiceEventTest(int arg1, Dictionary<int, DateTime?> arg3)
  1700. {
  1701. List<WellSnAndAutoTime> wellSnAndAutoTimes = new List<WellSnAndAutoTime>();
  1702. foreach (var item in arg3)
  1703. {
  1704. wellSnAndAutoTimes.Add(new WellSnAndAutoTime
  1705. {
  1706. well = item.Key,
  1707. autofocusTime = item.Value.HasValue ? item.Value.Value.ToString("yyyy-MM-dd HH:mm:ss") : null,
  1708. });
  1709. }
  1710. PositionRequestDTO positionRequestDTO = new PositionRequestDTO()
  1711. {
  1712. houseSn = arg1,
  1713. tlSn = "NEO-1-20230410",
  1714. wellSnList = wellSnAndAutoTimes,
  1715. };
  1716. return HouseBinController.GetAutoFocusController(positionRequestDTO);
  1717. }
  1718. public string GetLanguageStringByKey(string key)
  1719. {
  1720. try
  1721. {
  1722. if (System.Windows.Application.Current == null) return "";
  1723. object value = System.Windows.Application.Current.TryFindResource(key);
  1724. return value == null ? "" : value.ToString();
  1725. }
  1726. catch (Exception)
  1727. {
  1728. return "";
  1729. }
  1730. }
  1731. }
  1732. }