AppData.cs 75 KB

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