AppData.cs 76 KB

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