AppData.cs 81 KB

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