AppData.cs 80 KB

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