AppData.cs 74 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760
  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. isSetZiDong = true;
  504. if (HouseBin1 != null)
  505. {
  506. HouseBin1.FirstClearest = true;
  507. HouseBin1.ReCa = true;
  508. }
  509. if (HouseBin2 != null)
  510. {
  511. HouseBin2.FirstClearest = true;
  512. HouseBin2.ReCa = true;
  513. }
  514. if (HouseBin3 != null)
  515. {
  516. HouseBin3.FirstClearest = true;
  517. HouseBin3.ReCa = true;
  518. }
  519. if (HouseBin4 != null)
  520. {
  521. HouseBin4.FirstClearest = true;
  522. HouseBin4.ReCa = true;
  523. }
  524. if (HouseBin5 != null)
  525. {
  526. HouseBin5.FirstClearest = true;
  527. HouseBin5.ReCa = true;
  528. }
  529. if (HouseBin6 != null)
  530. {
  531. HouseBin6.FirstClearest = true;
  532. HouseBin6.ReCa = true;
  533. }
  534. if (HouseBin7 != null)
  535. {
  536. HouseBin7.FirstClearest = true;
  537. HouseBin7.ReCa = true;
  538. }
  539. if (HouseBin8 != null)
  540. {
  541. HouseBin8.FirstClearest = true;
  542. HouseBin8.ReCa = true;
  543. }
  544. if (HouseBin9 != null)
  545. {
  546. HouseBin9.FirstClearest = true;
  547. HouseBin9.ReCa = true;
  548. }
  549. if (HouseBin10 != null)
  550. {
  551. HouseBin10.FirstClearest = true;
  552. HouseBin10.ReCa = true;
  553. }
  554. }
  555. catch (Exception ex)
  556. {
  557. LogService.ExceptionLog(ex, "心跳线程", null, LogEnum.RunException);
  558. }
  559. finally
  560. {
  561. Thread.Sleep(time);
  562. }
  563. }
  564. }, TaskCreationOptions.LongRunning);
  565. }
  566. #region 仓室事件设置
  567. /// <summary>
  568. /// 仓室事件初始化
  569. /// </summary>
  570. /// <param name="BufferBottleBin"></param>
  571. public void InitHouseBinEvent(HouseBin houseBin)
  572. {
  573. houseBin.TLLogEvent += LogService.TLLog;
  574. houseBin.HouseLogEvent += LogService.HouseLog;
  575. houseBin.ExceptionLogEvent += LogService.ExceptionLog;
  576. houseBin.GetAutoFocusServiceEvent += HouseBin_GetAutoFocusServiceEvent;
  577. houseBin.GetAutoFocusDBEvent += HouseBin_GetAutoFocusDBEvent;
  578. // M2-04:注入标定结果存储入口(写 JSON 真相源 + 镜像库),对焦逐 well 标定后调用。
  579. houseBin.AutofocusStore = AutofocusStore;
  580. houseBin.GetCCDServiceEvent += HouseBin_GetCCDServiceEvent;
  581. houseBin.GetCCDDBEvent += HouseBin_GetCCDDBEvent;
  582. houseBin.UploadImageEvent += HouseBin_UploadImageEvent;
  583. houseBin.UpdateAutofocusStateEvent += HouseBin_UpdateAutofocusStateEvent;
  584. houseBin.SavePicDbEvent += HouseBin_SavePicDbEvent;
  585. houseBin.HouseStateEvent += HouseBin_HouseStateEvent;
  586. houseBin.CCDStateEvent += HouseBinPhotoStateEvent;
  587. houseBin.OnHistoryEvent += HouseBin_OnHistoryEvent;
  588. houseBin.ChangeBufferBottleBinEvent += HouseBin_ChangeBufferBottleBinEvent;
  589. houseBin.HouseBinChangeBufferBottleBinEvent += HouseBin_HouseBinChangeBufferBottleBinEvent;
  590. //houseBin.CCDStateEvent += HouseBin_CCDStateEvent;
  591. houseBin.TongQi = csTime * 1000;
  592. houseBin.VentPre = houseVentPre;
  593. houseBin.VentNum = houseVentNum;
  594. houseBin.VentWaitTimeB = houseVentWaitTimeB;
  595. houseBin.VentWaitTimeD = houseVentWaitTimeD;
  596. houseBin.AutoWaitTime = houseAutoWaitTime * 60000;
  597. houseBin.CCDAutoWaitTime = houseCCDAutoWaitTime * 60000;
  598. houseBin.CCDFailedNumber = houseCCDFailedNumber;
  599. houseBin.CCDFailedWaitTime = houseCCDFailedWaitTime * 1000;
  600. if (houseCCDError == 1)
  601. {
  602. houseBin.CCDError = true;
  603. }
  604. else
  605. {
  606. houseBin.CCDError = false;
  607. }
  608. if (queuAir == 0)
  609. {
  610. houseBin.IsPai = false;
  611. }
  612. else
  613. {
  614. houseBin.IsPai = true;
  615. }
  616. houseBin.TakePhotoFailed = TakePhotoString;
  617. }
  618. private void HouseBin_CCDStateEvent(int houseSn, int ccdState)
  619. {
  620. if (ccdState == 1)
  621. {
  622. LogService.TLLog($"{houseSn}号舱室拍照异常,停止拍照", LogEnum.RunRecord);
  623. }
  624. else
  625. {
  626. LogService.TLLog($"{houseSn}号舱室拍照恢复正常", LogEnum.RunRecord);
  627. }
  628. }
  629. private bool HouseBin_HouseBinChangeBufferBottleBinEvent(HouseBin arg1, int arg2)
  630. {
  631. if (BufferBottleBin == null)
  632. {
  633. LogService.TLLog($"缓冲瓶为空,无法操作进气阀:{arg1}、{arg2}", LogEnum.RunError);
  634. return false;
  635. }
  636. if (arg2 == 0)
  637. {
  638. BufferBottleBin.HuanQiEnd(arg1);
  639. return true;
  640. }
  641. else if (arg2 == 1)
  642. {
  643. BufferBottleBin.HuanQiStart(arg1);
  644. return true;
  645. }
  646. else
  647. {
  648. LogService.TLLog($"状态码错误,无法操作进气阀:{arg1}、{arg2}", LogEnum.RunError);
  649. return false;
  650. }
  651. }
  652. private bool HouseBin_ChangeBufferBottleBinEvent(int arg1, int arg2)
  653. {
  654. if (BufferBottleBin == null)
  655. {
  656. LogService.TLLog($"缓冲瓶为空,无法操作进气阀:{arg1}、{arg2}", LogEnum.RunError);
  657. return false;
  658. }
  659. if (arg2 == 0)
  660. {
  661. BufferBottleBin.CloseIntakeValve(arg1);
  662. return true;
  663. }
  664. else if (arg2 == 1)
  665. {
  666. BufferBottleBin.OpenIntakeValve(arg1);
  667. return true;
  668. }
  669. else
  670. {
  671. LogService.TLLog($"状态码错误,无法操作进气阀:{arg1}、{arg2}", LogEnum.RunError);
  672. return false;
  673. }
  674. }
  675. private void HouseBin_OnHistoryEvent(HouseHistoryData obj)
  676. {
  677. SerialBinController.ReportDataController(JsonConvert.SerializeObject(new List<HouseHistoryData> { obj }));
  678. }
  679. private void HouseBin_HouseStateEvent(int housesn, int houseState, int comState, int photoState, int wellSN, int airSwapState)
  680. {
  681. SerialBinController.ReportAlarmController(TLSetting.tlSn, housesn, houseState, comState, photoState, wellSN, airSwapState);
  682. //if (photoState != 0)
  683. //{
  684. // SerialBinController.ReportAlarmController(TLSetting.tlSn, housesn, houseState, comState, photoState, wellSN, airSwapState);
  685. // return;
  686. //}
  687. //for (int i = 1; i <= 16; i++)
  688. //{
  689. // SerialBinController.ReportAlarmController(TLSetting.tlSn, housesn, houseState, comState, photoState, i, airSwapState);
  690. //}
  691. }
  692. private void HouseBinPhotoStateEvent(int housesn, int photoState, int wellSN)
  693. {
  694. if (photoState != 0)
  695. {
  696. SerialBinController.ReportAlarmController(TLSetting.tlSn, housesn, -1, -1, photoState, wellSN, -1);
  697. StopProEvent?.Invoke();
  698. return;
  699. }
  700. for (int i = 1; i <= 16; i++)
  701. {
  702. SerialBinController.ReportAlarmController(TLSetting.tlSn, housesn, -1, -1, photoState, i, -1);
  703. }
  704. }
  705. /// <summary>
  706. /// 仓室图片保存到数据库
  707. /// </summary>
  708. /// <param name="obj"></param>
  709. /// <exception cref="NotImplementedException"></exception>
  710. private void HouseBin_SavePicDbEvent(ImageDTO obj)
  711. {
  712. if (obj == null) return;
  713. SerialBinController.SavePictreController(obj);
  714. }
  715. /// <summary>
  716. /// 仓室上传图片
  717. /// </summary>
  718. /// <param name="obj"></param>
  719. private void HouseBin_UploadImageEvent(ImageDTO obj)
  720. {
  721. if (obj == null) return;
  722. lock (ImageDTODic)
  723. {
  724. if (ImageDTODic.Count > 50)
  725. {
  726. LogService.TLLog($"内存当中保存的图片已经超过50张了{obj.HouseSn}、{obj.WellSn}、{obj.SourceImageName}", LogEnum.RunError);
  727. return;
  728. }
  729. if (!ImageDTODic.ContainsKey(obj.SourceImageName))
  730. {
  731. ImageDTODic.Add(obj.SourceImageName, obj);
  732. }
  733. }
  734. }
  735. /// <summary>
  736. /// 从服务器获取自动对焦位置
  737. /// </summary>
  738. /// <param name="arg1"></param>
  739. /// <param name="arg2"></param>
  740. /// <param name="arg3"></param>
  741. /// <returns></returns>
  742. private List<HouseWellPhoto> HouseBin_GetAutoFocusServiceEvent(int arg1, Dictionary<int, DateTime?> arg3)
  743. {
  744. List<WellSnAndAutoTime> wellSnAndAutoTimes = new List<WellSnAndAutoTime>();
  745. foreach (var item in arg3)
  746. {
  747. wellSnAndAutoTimes.Add(new WellSnAndAutoTime
  748. {
  749. well = item.Key,
  750. autofocusTime = item.Value.HasValue ? item.Value.Value.ToString("yyyy-MM-dd HH:mm:ss") : null,
  751. });
  752. }
  753. PositionRequestDTO positionRequestDTO = new PositionRequestDTO()
  754. {
  755. houseSn = arg1,
  756. tlSn = TLSetting.tlSn,
  757. wellSnList = wellSnAndAutoTimes,
  758. };
  759. return HouseBinController.GetAutoFocusController(positionRequestDTO);
  760. }
  761. /// <summary>
  762. /// 从数据库获取自动对焦位置
  763. /// </summary>
  764. /// <param name="arg1"></param>
  765. /// <param name="arg2"></param>
  766. /// <param name="arg3"></param>
  767. /// <returns></returns>
  768. private List<HouseWellPhoto> HouseBin_GetAutoFocusDBEvent(int arg1, Dictionary<int, DateTime?> arg3)
  769. {
  770. List<WellSnAndAutoTime> wellSnAndAutoTimes = new List<WellSnAndAutoTime>();
  771. foreach (var item in arg3)
  772. {
  773. wellSnAndAutoTimes.Add(new WellSnAndAutoTime
  774. {
  775. well = item.Key,
  776. autofocusTime = item.Value.HasValue ? item.Value.Value.ToString("yyyy-MM-dd HH:mm:ss") : null,
  777. });
  778. }
  779. PositionRequestDTO positionRequestDTO = new PositionRequestDTO()
  780. {
  781. houseSn = arg1,
  782. tlSn = TLSetting.tlSn,
  783. wellSnList = wellSnAndAutoTimes,
  784. };
  785. return HouseBinController.DbGetPositionData(positionRequestDTO.wellSnList.Select(x => x.well).ToList(), positionRequestDTO.houseSn, positionRequestDTO.tlSn, 0);
  786. }
  787. /// <summary>
  788. /// 服务器获取仓室拍照位置
  789. /// </summary>
  790. /// <param name="arg1"></param>
  791. /// <param name="arg2"></param>
  792. /// <param name="arg3"></param>
  793. /// <returns></returns>
  794. private PositionInfoResultDTO HouseBin_GetCCDServiceEvent(int arg1, Dictionary<int, DateTime?> arg3)
  795. {
  796. List<WellSnAndAutoTime> wellSnAndAutoTimes = new List<WellSnAndAutoTime>();
  797. foreach (var item in arg3)
  798. {
  799. wellSnAndAutoTimes.Add(new WellSnAndAutoTime
  800. {
  801. well = item.Key,
  802. autofocusTime = item.Value.HasValue ? item.Value.Value.ToString("yyyy-MM-dd HH:mm:ss") : null,
  803. });
  804. }
  805. PositionRequestDTO positionRequestDTO = new PositionRequestDTO()
  806. {
  807. houseSn = arg1,
  808. wellSnList = wellSnAndAutoTimes,
  809. tlSn = TLSetting.tlSn,
  810. };
  811. var result = HouseBinController.GetCCDPositionController(positionRequestDTO);
  812. if (result != null && result.complete == 0)//完成
  813. {
  814. List<HouseWellPhoto> CCDPositionList = new List<HouseWellPhoto>();
  815. foreach (var item in result.positionVOList)
  816. {
  817. CCDPositionList.Add(ConvertHelper.ConvertToHouseWellPhoto(item));
  818. }
  819. HouseBinController.DbUpdatePositionData(CCDPositionList, positionRequestDTO.houseSn, positionRequestDTO.tlSn, 1);
  820. }
  821. return result;
  822. }
  823. /// <summary>
  824. /// 数据库获取仓室拍照位置
  825. /// </summary>
  826. /// <param name="arg1"></param>
  827. /// <param name="arg2"></param>
  828. /// <param name="arg3"></param>
  829. /// <returns></returns>
  830. private List<HouseWellPhoto> HouseBin_GetCCDDBEvent(int arg1, Dictionary<int, DateTime?> arg3)
  831. {
  832. List<WellSnAndAutoTime> wellSnAndAutoTimes = new List<WellSnAndAutoTime>();
  833. foreach (var item in arg3)
  834. {
  835. wellSnAndAutoTimes.Add(new WellSnAndAutoTime
  836. {
  837. well = item.Key,
  838. autofocusTime = item.Value.HasValue ? item.Value.Value.ToString("yyyy-MM-dd HH:mm:ss") : null,
  839. });
  840. }
  841. PositionRequestDTO positionRequestDTO = new PositionRequestDTO()
  842. {
  843. houseSn = arg1,
  844. wellSnList = wellSnAndAutoTimes,
  845. tlSn = TLSetting.tlSn,
  846. };
  847. return HouseBinController.DbGetPositionData(positionRequestDTO.wellSnList.Select(x => x.well).ToList(), positionRequestDTO.houseSn, positionRequestDTO.tlSn, 1);
  848. }
  849. private void HouseBin_UpdateAutofocusStateEvent(bool newValue, int housesn)
  850. {
  851. int autoFocus = 0;
  852. if (newValue)
  853. {
  854. autoFocus = 1;
  855. }
  856. SerialBinController.UpdateAutofocusStateController(TLSetting.tlSn, housesn, autoFocus);
  857. }
  858. /// <summary>
  859. /// 缓冲瓶事件初始化
  860. /// </summary>
  861. /// <param name="BufferBottleBin"></param>
  862. public void InitBufferBottleBinEvent(BufferBottleBin BufferBottleBin)
  863. {
  864. BufferBottleBin.TLLogEvent += LogService.TLLog;
  865. BufferBottleBin.HouseLogEvent += LogService.HouseLog;
  866. BufferBottleBin.ExceptionLogEvent += LogService.ExceptionLog;
  867. BufferBottleBin.HouseStateEvent += HouseBin_HouseStateEvent;
  868. }
  869. #endregion
  870. #region mqtt消息处理
  871. /// <summary>
  872. /// mqtt接受消息
  873. /// </summary>
  874. /// <param name="message"></param>
  875. public void MqttMessage(string message)
  876. {
  877. if (string.IsNullOrEmpty(message)) return;
  878. MqttResult mqttResult = null;
  879. bool isSuccess = true;
  880. string uuid = null;
  881. try
  882. {
  883. mqttResult = JsonConvert.DeserializeObject<MqttResult>(message);
  884. if (mqttResult == null)
  885. {
  886. LogService.TLLog($"AppData.MqttMessage,mqtt消息反序列化失败,消息:{message}", LogEnum.MqttClient);
  887. return;
  888. }
  889. switch (mqttResult.type)
  890. {
  891. case (int)MqttEnum.StartBalance:
  892. isSuccess = StartBalance(mqttResult.data);
  893. break;
  894. case (int)MqttEnum.EndBalance:
  895. isSuccess = EndBalance(mqttResult.data);
  896. break;
  897. case (int)MqttEnum.StartDish:
  898. isSuccess = StartDish(mqttResult.data);
  899. break;
  900. case (int)MqttEnum.EndDish:
  901. isSuccess = EndDish(mqttResult.data);
  902. break;
  903. case (int)MqttEnum.EmbryoState:
  904. isSuccess = EmbryoState(mqttResult.data);
  905. break;
  906. case (int)MqttEnum.Update:
  907. isSuccess = UpDataSettingMqtt(mqttResult.data);
  908. break;
  909. case (int)MqttEnum.DebugStart:
  910. isSuccess = DebugStart(mqttResult.data, ref uuid);
  911. break;
  912. case (int)MqttEnum.HouseAutoFocus:
  913. isSuccess = HouseAutoFocus(mqttResult.data);
  914. break;
  915. case (int)MqttEnum.WellAutoFocus:
  916. isSuccess = WellAutoFocus(mqttResult.data);
  917. break;
  918. }
  919. }
  920. catch (Exception ex)
  921. {
  922. LogService.ExceptionLog(ex, "mqtt消息处理", null, LogEnum.RunException);
  923. isSuccess = false;
  924. }
  925. finally
  926. {
  927. if (mqttResult != null)
  928. {
  929. if (string.IsNullOrEmpty(uuid))
  930. {
  931. SerialBinController.MqttResultController(isSuccess ? 200 : 400, isSuccess, mqttResult.messageId);
  932. }
  933. else
  934. {
  935. SerialBinController.MqttResultController(isSuccess ? 200 : 400, isSuccess, mqttResult.messageId, uuid);
  936. }
  937. }
  938. }
  939. }
  940. /// <summary>
  941. /// 开始平衡
  942. /// </summary>
  943. /// <param name="data"></param>
  944. /// <returns></returns>
  945. private bool StartBalance(object data)
  946. {
  947. try
  948. {
  949. Balance balance = JsonConvert.DeserializeObject<Balance>(data.ToString());
  950. DBService.AddBalance(balance);
  951. HouseBin currentHouseBin = HouseSnToHouseBin(balance.houseSn);
  952. if (currentHouseBin == null) return false;
  953. currentHouseBin.StartBlance(balance);
  954. return true;
  955. }
  956. catch (Exception ex)
  957. {
  958. ExLog(ex, "StartBalance");
  959. return false;
  960. }
  961. }
  962. private bool EndBalance(object data)
  963. {
  964. try
  965. {
  966. Balance balance = JsonConvert.DeserializeObject<Balance>(data.ToString());
  967. HouseBin currentHouseBin = HouseSnToHouseBin(balance.houseSn);
  968. if (currentHouseBin == null) return false;
  969. DBService.EndBalance(balance.id, balance.endTime);
  970. currentHouseBin.StopBlance();
  971. return true;
  972. }
  973. catch (Exception ex)
  974. {
  975. ExLog(ex, "EndBalance");
  976. return false;
  977. }
  978. }
  979. private bool StartDish(object data)
  980. {
  981. try
  982. {
  983. Dish dish = JsonConvert.DeserializeObject<Dish>(data.ToString());
  984. DBService.AddDish(dish, dish.tlSn);
  985. HouseBin currentHouseBin = HouseSnToHouseBin(dish.houseSn);
  986. if (currentHouseBin == null) return false;
  987. currentHouseBin.StartDish(dish);
  988. return true;
  989. }
  990. catch (Exception ex)
  991. {
  992. ExLog(ex, "StartDish");
  993. return false;
  994. }
  995. }
  996. private bool EndDish(object data)
  997. {
  998. try
  999. {
  1000. Dish dish = JsonConvert.DeserializeObject<Dish>(data.ToString());
  1001. DBService.EndDish(dish.id, dish.endTime.Value, dish.tlSn);
  1002. HouseBin currentHouseBin = HouseSnToHouseBin(dish.houseSn);
  1003. if (currentHouseBin == null) return false;
  1004. currentHouseBin.StopDish();
  1005. return true;
  1006. }
  1007. catch (Exception ex)
  1008. {
  1009. ExLog(ex, "EndDish");
  1010. return false;
  1011. }
  1012. }
  1013. private bool DebugStart(object data, ref string uuid)
  1014. {
  1015. try
  1016. {
  1017. //System.Collections.IList list = param["list"] as System.Collections.IList;
  1018. //JArray itemObject = (JArray)keyValuePair.Value;
  1019. //foreach (KeyValuePair<string, JToken> keyValuePair in jobject)
  1020. if (data == null) return false;
  1021. if (string.IsNullOrEmpty(data.ToString())) return false;
  1022. JObject jObject = JObject.Parse(data.ToString());
  1023. string tlsn = jObject["tlSn"].ToString();
  1024. uuid = jObject["uuid"].ToString();
  1025. int housesn = int.Parse(jObject["houseSn"].ToString());
  1026. switch (housesn)
  1027. {
  1028. case 1:
  1029. HouseBin1.IsDebug = true;
  1030. break;
  1031. case 2:
  1032. HouseBin2.IsDebug = true;
  1033. break;
  1034. case 3:
  1035. HouseBin3.IsDebug = true;
  1036. break;
  1037. case 4:
  1038. HouseBin4.IsDebug = true;
  1039. break;
  1040. case 5:
  1041. HouseBin5.IsDebug = true;
  1042. break;
  1043. case 6:
  1044. HouseBin6.IsDebug = true;
  1045. break;
  1046. case 7:
  1047. HouseBin7.IsDebug = true;
  1048. break;
  1049. case 8:
  1050. HouseBin8.IsDebug = true;
  1051. break;
  1052. case 9:
  1053. HouseBin9.IsDebug = true;
  1054. break;
  1055. case 10:
  1056. HouseBin10.IsDebug = true;
  1057. break;
  1058. }
  1059. bool IsDebugOk = false;
  1060. do
  1061. {
  1062. switch (housesn)
  1063. {
  1064. case 1:
  1065. IsDebugOk = HouseBin1.isDebugOk;
  1066. break;
  1067. case 2:
  1068. IsDebugOk = HouseBin2.isDebugOk;
  1069. break;
  1070. case 3:
  1071. IsDebugOk = HouseBin3.isDebugOk;
  1072. break;
  1073. case 4:
  1074. IsDebugOk = HouseBin4.isDebugOk;
  1075. break;
  1076. case 5:
  1077. IsDebugOk = HouseBin5.isDebugOk;
  1078. break;
  1079. case 6:
  1080. IsDebugOk = HouseBin6.isDebugOk;
  1081. break;
  1082. case 7:
  1083. IsDebugOk = HouseBin7.isDebugOk;
  1084. break;
  1085. case 8:
  1086. IsDebugOk = HouseBin8.isDebugOk;
  1087. break;
  1088. case 9:
  1089. IsDebugOk = HouseBin9.isDebugOk;
  1090. break;
  1091. case 10:
  1092. IsDebugOk = HouseBin10.isDebugOk;
  1093. break;
  1094. }
  1095. if (IsDebugOk)
  1096. {
  1097. break;
  1098. }
  1099. Thread.Sleep(1000);
  1100. } while (true);
  1101. return true;
  1102. }
  1103. catch (Exception ex)
  1104. {
  1105. LogService.ExceptionLog(ex, "mqtt.DebugStart", null, LogEnum.RunException);
  1106. return false;
  1107. }
  1108. }
  1109. private bool EmbryoState(object data)
  1110. {
  1111. try
  1112. {
  1113. Embryo embryo = JsonConvert.DeserializeObject<Embryo>(data.ToString());
  1114. DBService.ChangeEmbryoState(embryo);
  1115. HouseBin currentHouseBin = HouseSnToHouseBin(embryo.houseSn);
  1116. if (currentHouseBin == null) return false;
  1117. currentHouseBin.ChangeEmbryoState(embryo);
  1118. return true;
  1119. }
  1120. catch (Exception ex)
  1121. {
  1122. ExLog(ex, "EmbryoState");
  1123. return false;
  1124. }
  1125. }
  1126. private bool UpDataSettingMqtt(object data)
  1127. {
  1128. try
  1129. {
  1130. if (data == null) return false;
  1131. string dataString = data.ToString();
  1132. if (string.IsNullOrEmpty(dataString)) return false;
  1133. JObject jObject = JObject.Parse(dataString);
  1134. string tlsn = jObject["tlSn"].ToString();
  1135. string dateTime = jObject["updateTime"].ToString();
  1136. return UpdateSetting(tlsn);
  1137. }
  1138. catch (Exception ex)
  1139. {
  1140. ExLog(ex, "UpDataSettingMqtt");
  1141. return false;
  1142. }
  1143. }
  1144. public bool HouseAutoFocus(object data)
  1145. {
  1146. try
  1147. {
  1148. HouseAutoFocusMqtt houseAutoFocus = JsonConvert.DeserializeObject<HouseAutoFocusMqtt>(data.ToString());
  1149. if (houseAutoFocus == null || !houseAutoFocus.houseSnList.Any())
  1150. {
  1151. LogService.TLLog($"json转换失败,不更新配置信息{data.ToString()}", LogEnum.RunError);
  1152. return false;
  1153. }
  1154. if (!UpdateSetting(houseAutoFocus.tlSn))
  1155. {
  1156. LogService.TLLog($"更新配置信息失败,不开启自动对焦", LogEnum.RunError);
  1157. return false;
  1158. }
  1159. foreach (var houseSn in houseAutoFocus.houseSnList)
  1160. {
  1161. HouseBin currentHouseBin = HouseSnToHouseBin(houseSn);
  1162. if (currentHouseBin == null)
  1163. {
  1164. LogService.TLLog($"开启自动对焦时,获取舱室为空,{houseSn}、{data.ToString()}", LogEnum.RunError);
  1165. continue;
  1166. }
  1167. currentHouseBin.HouseAutoFocus();
  1168. }
  1169. return true;
  1170. }
  1171. catch (Exception ex)
  1172. {
  1173. ExLog(ex, "HouseAutoFocus");
  1174. return false;
  1175. }
  1176. }
  1177. public bool WellAutoFocus(object data)
  1178. {
  1179. try
  1180. {
  1181. WellAutoFocusMqtt wellAutoFocusMqtt = JsonConvert.DeserializeObject<WellAutoFocusMqtt>(data.ToString());
  1182. if (wellAutoFocusMqtt == null || !wellAutoFocusMqtt.houseSnList.Any()) return false;
  1183. if (!UpdateSetting(wellAutoFocusMqtt.tlSn))
  1184. {
  1185. LogService.TLLog($"更新配置信息失败,不开启自动对焦", LogEnum.RunError);
  1186. return false;
  1187. }
  1188. foreach (var houseSn in wellAutoFocusMqtt.houseSnList)
  1189. {
  1190. HouseBin currentHouseBin = HouseSnToHouseBin(houseSn.house);
  1191. if (currentHouseBin == null) continue;
  1192. currentHouseBin.WellAutoFocus(houseSn.well);
  1193. }
  1194. return true;
  1195. }
  1196. catch (Exception ex)
  1197. {
  1198. ExLog(ex, "WellAutoFocus");
  1199. return false;
  1200. }
  1201. }
  1202. public bool UpdateSetting(string tlsn)
  1203. {
  1204. try
  1205. {
  1206. var initTLResult = SerialBinController.UpdataSettingController(tlsn);
  1207. if (initTLResult == null)
  1208. {
  1209. LogService.TLLog($"更新设置时返回为空", LogEnum.RunError);
  1210. return false;
  1211. }
  1212. TLSetting = initTLResult.TLSetting;
  1213. PathHelper.pan = initTLResult.TLSetting.tmpDir;
  1214. LogService.Pan = initTLResult.TLSetting.tmpDir;
  1215. for (int i = 1; i <= 10; i++)
  1216. {
  1217. HouseBin currentHouseBin = HouseSnToHouseBin(i);
  1218. if (currentHouseBin == null) continue;
  1219. currentHouseBin.UpdataHouseSetting(initTLResult);
  1220. }
  1221. //UpdataKafkaAndMqtt();
  1222. return true;
  1223. }
  1224. catch (Exception ex)
  1225. {
  1226. ExLog(ex, "UpdateSetting");
  1227. return false;
  1228. }
  1229. }
  1230. #endregion
  1231. /// <summary>
  1232. /// mqtt报警
  1233. /// </summary>
  1234. /// <param name="message"></param>
  1235. public void MqttAlarm(string message)
  1236. {
  1237. try
  1238. {
  1239. HttpService.AlarmApi1(TLSetting.tlSn, "CLOUD_SLAVE_MQTT_ALARM", new List<string> { message });
  1240. }
  1241. catch (Exception ex)
  1242. {
  1243. ExLog(ex, "mqtt报警");
  1244. return;
  1245. }
  1246. }
  1247. public void KafkaAlarm(string tlsn, int housesn, ulong dishId, ulong embryoId, string imageName, int wellSn)
  1248. {
  1249. try
  1250. {
  1251. HttpService.AlarmApi(tlsn, housesn, wellSn, "CLOUD_SLAVE_KAFKA_ALARM", new List<string> { dishId.ToString(), embryoId.ToString(), imageName });
  1252. }
  1253. catch (Exception ex)
  1254. {
  1255. ExLog(ex, "图片传输失败报警");
  1256. return;
  1257. }
  1258. }
  1259. public void KafkaAlarmChaoShi(string tlsn, int housesn, ulong dishId, ulong embryoId, string imageName, int wellSn)
  1260. {
  1261. try
  1262. {
  1263. HttpService.AlarmApi(tlsn, housesn, wellSn, "CLOUD_SLAVE_PICTURE_TRANSFER_ALARM", new List<string> { dishId.ToString(), embryoId.ToString(), imageName });
  1264. }
  1265. catch (Exception ex)
  1266. {
  1267. ExLog(ex, "图片传输超时报警");
  1268. return;
  1269. }
  1270. }
  1271. private async Task KafkaUploadImageAsync(string fileFullPath)
  1272. {
  1273. // M5-04-3(a):去重防并发重传。同名文件在上一轮上传未结束(慢链/超时)时,5s 重扫会再次进入本方法,
  1274. // 此处用 in-flight 集合保证同一文件同一时刻只有一条上传在跑;释放放在 finally,不影响「成功才删」语义。
  1275. string fileName = Path.GetFileName(fileFullPath);
  1276. lock (_uploadingFiles)
  1277. {
  1278. if (_uploadingFiles.Contains(fileName)) return; // 正在上传,跳过本轮重扫的重复触发
  1279. _uploadingFiles.Add(fileName);
  1280. }
  1281. try
  1282. {
  1283. Stopwatch stopwatch = Stopwatch.StartNew();
  1284. //LogService.TLLog($"准备上传{fileFullPath}", LogEnum.KafkaRecord);
  1285. ImageDTO imageDTO = null;
  1286. lock (ImageDTODic) if (ImageDTODic.ContainsKey(fileName)) imageDTO = ImageDTODic[fileName];
  1287. if (imageDTO == null)
  1288. {
  1289. imageDTO = SerialBinController.SearchPictureController(fileName, TLSetting.tlSn);
  1290. if (imageDTO == null)
  1291. {
  1292. LogService.TLLog($"数据库获取文件失败:{fileName}、{TLSetting.tlSn}:{fileFullPath}", LogEnum.RunError);
  1293. }
  1294. else
  1295. {
  1296. var imageBytes = AivfoHelper.GetImageData1(fileFullPath);
  1297. if (imageBytes == null)
  1298. {
  1299. LogService.TLLog($"上传中止,图片不存在:{fileFullPath}", LogEnum.RunError);
  1300. }
  1301. else
  1302. {
  1303. imageDTO.ImageData = ByteString.CopyFrom(imageBytes);
  1304. }
  1305. }
  1306. }
  1307. if (imageDTO == null)
  1308. {
  1309. LogService.TLLog($"上传中止,imageDTO为空:{fileFullPath}", LogEnum.KafkaRecord);
  1310. string newDir = PathHelper.GetErrorSaveDirectory();
  1311. if (!Directory.Exists(newDir)) Directory.CreateDirectory(newDir);
  1312. File.Move(fileFullPath, Path.Combine(newDir, fileName));
  1313. return;
  1314. }
  1315. //LogService.TLLog($"fileName文件大小:{imageDTO.ImageData.Count()}", LogEnum.KafkaRecord);
  1316. var time1 = stopwatch.Elapsed;
  1317. //LogService.TLLog($"开始上传{fileFullPath},准备耗时:{time1}毫秒", LogEnum.KafkaRecord);
  1318. var uploadResult = await KafkaService.kafkaProducerAsync(imageDTO);
  1319. var time2 = stopwatch.Elapsed;
  1320. //LogService.TLLog($"上传结束{fileFullPath},耗时:{time2 - time1}毫秒", LogEnum.KafkaRecord);
  1321. if (!uploadResult)
  1322. {
  1323. KafkaAlarm(imageDTO.TlSn, imageDTO.HouseSn, imageDTO.EmbryoCultureRecordId, imageDTO.EmbryoId, imageDTO.SourceImageName, imageDTO.WellSn);
  1324. LogService.TLLog($"上传失败:{fileFullPath}", LogEnum.RunError);
  1325. return;
  1326. }
  1327. if ((time2 - time1).TotalMilliseconds > 1000)
  1328. {
  1329. KafkaAlarmChaoShi(imageDTO.TlSn, imageDTO.HouseSn, imageDTO.EmbryoCultureRecordId, imageDTO.EmbryoId, imageDTO.SourceImageName, imageDTO.WellSn);
  1330. LogService.TLLog($"kafka上传超时:{fileFullPath}", LogEnum.RunError);
  1331. }
  1332. LastKafkaOkAt = DateTime.Now; // M5-03-2:Kafka 图片上传成功时间戳(只读监控用,不改上传逻辑)
  1333. lock (ImageDTODic) if (ImageDTODic.ContainsKey(fileName)) ImageDTODic.Remove(fileName);
  1334. if (File.Exists(fileFullPath))
  1335. {
  1336. try
  1337. {
  1338. File.Delete(fileFullPath);
  1339. }
  1340. catch (Exception ex)
  1341. {
  1342. LogService.ExceptionLog(ex, "kafka上传完成删除图片", null, LogEnum.RunException);
  1343. }
  1344. //if (imageDTO.PhotographType == 1)
  1345. //{
  1346. // string newpath = @"C:\TLData\AutofocusControlBreak";
  1347. // if (!Directory.Exists(newpath)) Directory.CreateDirectory(newpath);
  1348. // File.Move(fileFullPath, Path.Combine(newpath, fileName));
  1349. //}
  1350. //else
  1351. //{
  1352. // string newpath = @"C:\TLData\EmbryosControlBreak";
  1353. // if (!Directory.Exists(newpath)) Directory.CreateDirectory(newpath);
  1354. // File.Move(fileFullPath, Path.Combine(newpath, fileName));
  1355. //}
  1356. }
  1357. SerialBinController.DeletePictrueController(fileName, TLSetting.tlSn);
  1358. //LogService.TLLog($"上传完成:{fileFullPath},总耗时:{stopwatch.ElapsedMilliseconds}毫秒", LogEnum.KafkaRecord);
  1359. }
  1360. catch (Exception ex)
  1361. {
  1362. LogService.ExceptionLog(ex, "kafka上传图片", null, LogEnum.RunException);
  1363. return;
  1364. }
  1365. finally
  1366. {
  1367. // M5-04-3(a):无论成功/失败/中止,都释放 in-flight 标记,使下一轮重扫可重试(失败文件仍在落盘 → 不丢)。
  1368. lock (_uploadingFiles) _uploadingFiles.Remove(fileName);
  1369. }
  1370. }
  1371. private HouseMqttData GetHouseMqttData(HouseBin currentHouseBin)
  1372. {
  1373. if (currentHouseBin == null) return null;
  1374. if (currentHouseBin.House == null) return null;
  1375. int cultureState = 0;
  1376. if (currentHouseBin.Balance != null && currentHouseBin.Balance.id > 0) cultureState = 2;
  1377. if (currentHouseBin.Dish != null && currentHouseBin.Dish.id > 0) cultureState = 1;
  1378. return new HouseMqttData()
  1379. {
  1380. tlSn = TLSetting.tlSn,
  1381. houseSn = currentHouseBin.House.houseSn,
  1382. pressure = currentHouseBin.Pressure,
  1383. temperature = currentHouseBin.Temperature,
  1384. houseDoorState = currentHouseBin.IsDoorOpen == State.打开 ? 1 : 0,
  1385. pressureDesc = currentHouseBin.ValveState.ToString(),
  1386. houseDesc = currentHouseBin.RunState,
  1387. cultureState = cultureState,
  1388. houseState = (int)currentHouseBin.WorkingType,
  1389. };
  1390. }
  1391. private HouseMqttData GetHouseMqttData(BufferBottleBin currentBufferBottleBin)
  1392. {
  1393. if (currentBufferBottleBin == null) return null;
  1394. if (currentBufferBottleBin.House == null) return null;
  1395. return new HouseMqttData()
  1396. {
  1397. tlSn = TLSetting.tlSn,
  1398. houseSn = 11,
  1399. pressure = currentBufferBottleBin.BufferBottlePressure,
  1400. temperature = 0,
  1401. houseDoorState = 0,
  1402. pressureDesc = currentBufferBottleBin.ValveState.ToString(),
  1403. houseDesc = currentBufferBottleBin.RunState,
  1404. };
  1405. }
  1406. private HouseHistoryData GetHouseHistoryData(HouseBin currentHouseBin)
  1407. {
  1408. if (currentHouseBin == null) return null;
  1409. if (currentHouseBin.House == null) return null;
  1410. return new HouseHistoryData()
  1411. {
  1412. tlSn = TLSetting.tlSn,
  1413. houseSn = currentHouseBin.House.houseSn,
  1414. pressure = currentHouseBin.Pressure,
  1415. temperature = currentHouseBin.Temperature,
  1416. houseDoor = currentHouseBin.IsDoorOpen == State.打开 ? 1 : 0,
  1417. airSwap = currentHouseBin.WorkingType == WorkingType.AirSwapWorking ? 1 : 0,
  1418. temperatureLowerCover = currentHouseBin.Temperature2,
  1419. temperatureUpperCover = currentHouseBin.Temperature1,
  1420. temperatureLowerGlass = currentHouseBin.Temperature3,
  1421. };
  1422. }
  1423. private HouseHistoryData GetHouseHistoryData(BufferBottleBin currentBufferBottleBin)
  1424. {
  1425. if (currentBufferBottleBin == null) return null;
  1426. if (currentBufferBottleBin.House == null) return null;
  1427. return new HouseHistoryData()
  1428. {
  1429. tlSn = TLSetting.tlSn,
  1430. houseSn = 11,
  1431. pressure = currentBufferBottleBin.BufferBottlePressure,
  1432. temperature = 0,
  1433. houseDoor = 0,
  1434. airSwap = 0,
  1435. temperatureLowerCover = currentBufferBottleBin.Temperature1,
  1436. temperatureUpperCover = currentBufferBottleBin.Temperature2,
  1437. temperatureLowerGlass = 0,
  1438. cultureState = 0,
  1439. };
  1440. }
  1441. private HouseBin HouseSnToHouseBin(int housesn)
  1442. {
  1443. HouseBin result = null;
  1444. switch (housesn)
  1445. {
  1446. case 1:
  1447. result = HouseBin1;
  1448. break;
  1449. case 2:
  1450. result = HouseBin2;
  1451. break;
  1452. case 3:
  1453. result = HouseBin3;
  1454. break;
  1455. case 4:
  1456. result = HouseBin4;
  1457. break;
  1458. case 5:
  1459. result = HouseBin5;
  1460. break;
  1461. case 6:
  1462. result = HouseBin6;
  1463. break;
  1464. case 7:
  1465. result = HouseBin7;
  1466. break;
  1467. case 8:
  1468. result = HouseBin8;
  1469. break;
  1470. case 9:
  1471. result = HouseBin9;
  1472. break;
  1473. case 10:
  1474. result = HouseBin10;
  1475. break;
  1476. }
  1477. return result;
  1478. }
  1479. public DiskInfo GetDiskInfo(string pan)
  1480. {
  1481. DiskInfo diskInfo = new DiskInfo() { diskPath = pan };
  1482. try
  1483. {
  1484. string panNew = pan.ToUpper();
  1485. diskInfo.diskExist = Directory.Exists($"{panNew}:\\") ? 0 : 1;
  1486. if (diskInfo.diskExist == 1) return diskInfo;
  1487. bool IsFind = false;
  1488. DriveInfo[] allDirves = DriveInfo.GetDrives();
  1489. foreach (DriveInfo item in allDirves)
  1490. {
  1491. if (item.IsReady)
  1492. {
  1493. if (item.Name == $"{panNew}:\\")
  1494. {
  1495. IsFind = true;
  1496. diskInfo.diskSpace = (decimal)(item.TotalFreeSpace / (1024.00 * 1024.00 * 1024.00));
  1497. break;
  1498. }
  1499. }
  1500. }
  1501. if (!IsFind) diskInfo.diskExist = 1;
  1502. return diskInfo;
  1503. }
  1504. catch (Exception ex)
  1505. {
  1506. LogService.ExceptionLog(ex, "GetDiskInfo", null, LogEnum.RunException);
  1507. diskInfo.diskExist = 1;
  1508. return diskInfo;
  1509. }
  1510. }
  1511. public void DeleteLog()
  1512. {
  1513. try
  1514. {
  1515. string newPath = $"{TLSetting.tmpDir}:\\TLData\\ivf_tl_Control_logs";
  1516. var newDir = Directory.GetDirectories(newPath, "*", SearchOption.TopDirectoryOnly);
  1517. foreach (var item in newDir)
  1518. {
  1519. var dieName = System.IO.Path.GetFileName(item);
  1520. if (DateTime.TryParse(dieName, out DateTime newTime))
  1521. {
  1522. if (DateTime.Now.Subtract(newTime).Days >= 5)
  1523. {
  1524. Directory.Delete(item, true);
  1525. }
  1526. }
  1527. }
  1528. DeleteLogFile($"C:\\TLData\\ivf_tl_Control_logs\\LogError");
  1529. DeleteLogFile($"C:\\TLData\\ivf_tl_Control_logs\\Log");
  1530. }
  1531. catch (Exception ex)
  1532. {
  1533. LogService.ExceptionLog(ex, "DeleteLog", null, LogEnum.RunException);
  1534. }
  1535. }
  1536. private void DeleteLogFile(string newPath)
  1537. {
  1538. var newDir = Directory.GetFiles(newPath, "*.htm", SearchOption.TopDirectoryOnly);
  1539. string fileName = "";
  1540. DateTime fileTime = DateTime.Now;
  1541. DateTime nowTime = fileTime;
  1542. foreach (var item in newDir)
  1543. {
  1544. fileName = System.IO.Path.GetFileNameWithoutExtension(item);
  1545. if (fileName.Length == 8)
  1546. {
  1547. fileName = fileName.Insert(6, "-");
  1548. fileName = fileName.Insert(4, "-");
  1549. if (DateTime.TryParse(fileName, out fileTime))
  1550. {
  1551. if (nowTime.Subtract(fileTime).Days >= 5)
  1552. {
  1553. try
  1554. {
  1555. File.Delete(item);
  1556. }
  1557. catch (Exception)
  1558. {
  1559. continue;
  1560. }
  1561. }
  1562. }
  1563. }
  1564. }
  1565. }
  1566. public string ReadText(string fileName)
  1567. {
  1568. return File.ReadAllText(fileName);
  1569. }
  1570. public PositionInfoResultDTO HouseBin_GetCCDServiceEventTest(int arg1, Dictionary<int, DateTime?> arg3)
  1571. {
  1572. List<WellSnAndAutoTime> wellSnAndAutoTimes = new List<WellSnAndAutoTime>();
  1573. foreach (var item in arg3)
  1574. {
  1575. wellSnAndAutoTimes.Add(new WellSnAndAutoTime
  1576. {
  1577. well = item.Key,
  1578. autofocusTime = item.Value.HasValue ? item.Value.Value.ToString("yyyy-MM-dd HH:mm:ss") : null,
  1579. });
  1580. }
  1581. PositionRequestDTO positionRequestDTO = new PositionRequestDTO()
  1582. {
  1583. houseSn = arg1,
  1584. wellSnList = wellSnAndAutoTimes,
  1585. tlSn = "NEO-1-20230410",
  1586. };
  1587. var result = HouseBinController.GetCCDPositionController(positionRequestDTO);
  1588. if (result != null && result.complete == 0)//完成
  1589. {
  1590. List<HouseWellPhoto> CCDPositionList = new List<HouseWellPhoto>();
  1591. foreach (var item in result.positionVOList)
  1592. {
  1593. CCDPositionList.Add(ConvertHelper.ConvertToHouseWellPhoto(item));
  1594. }
  1595. HouseBinController.DbUpdatePositionData(CCDPositionList, positionRequestDTO.houseSn, positionRequestDTO.tlSn, 1);
  1596. }
  1597. return result;
  1598. }
  1599. public List<HouseWellPhoto> HouseBin_GetAutoFocusServiceEventTest(int arg1, Dictionary<int, DateTime?> arg3)
  1600. {
  1601. List<WellSnAndAutoTime> wellSnAndAutoTimes = new List<WellSnAndAutoTime>();
  1602. foreach (var item in arg3)
  1603. {
  1604. wellSnAndAutoTimes.Add(new WellSnAndAutoTime
  1605. {
  1606. well = item.Key,
  1607. autofocusTime = item.Value.HasValue ? item.Value.Value.ToString("yyyy-MM-dd HH:mm:ss") : null,
  1608. });
  1609. }
  1610. PositionRequestDTO positionRequestDTO = new PositionRequestDTO()
  1611. {
  1612. houseSn = arg1,
  1613. tlSn = "NEO-1-20230410",
  1614. wellSnList = wellSnAndAutoTimes,
  1615. };
  1616. return HouseBinController.GetAutoFocusController(positionRequestDTO);
  1617. }
  1618. public string GetLanguageStringByKey(string key)
  1619. {
  1620. try
  1621. {
  1622. if (System.Windows.Application.Current == null) return "";
  1623. object value = System.Windows.Application.Current.TryFindResource(key);
  1624. return value == null ? "" : value.ToString();
  1625. }
  1626. catch (Exception)
  1627. {
  1628. return "";
  1629. }
  1630. }
  1631. }
  1632. }