AutoDFRDiagnosisService.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424
  1. using AI.Common;
  2. using AI.Common.Log;
  3. using AIDiagnosis.Common.Enums;
  4. using AIDiagnosis.Common.Models;
  5. using AutoDFRCalculationLib;
  6. using System;
  7. using System.Collections.Concurrent;
  8. using System.Collections.Generic;
  9. using System.IO;
  10. using System.Threading;
  11. using Vinno.AI.AutoDFRDiagnosisSDK.Interfaces;
  12. using Vinno.AI.AutoDFRDiagnosisSDK.Models;
  13. using Vinno.AI.AutoDFRDiagnosisService.Tools;
  14. using Vinno.AI.CommonSDK.Enums;
  15. using Vinno.AI.CommonSDK.Models;
  16. using Vinno.AI.CommonSDK.Tools;
  17. using Vinno.AI.Service.Common.Interfaces;
  18. using Vinno.AI.Service.Common.Models;
  19. using Vinno.AI.Service.Common.Tools;
  20. using AutoDFRDiagnosis = AutoDFRDiagnosisSDK.AutoDFRDiagnosis;
  21. namespace Vinno.AI.AutoDFRDiagnosisService
  22. {
  23. public class AutoDFRDiagnosisService : IAutoDFRDiagnosisService, IDisposable, IEngine
  24. {
  25. private readonly string _modelFolder = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Networks");
  26. private readonly ConcurrentStack<byte[]> _singleImageCache;
  27. private PipeServer _singleImagePipeServer;
  28. private ImageProvider _imageProvider;
  29. private AutoDFRDiagnosis _autoDFRDiagnosis;
  30. private bool _disposed;
  31. public static List<FunctionInfo> AllFunctions { get; }
  32. static AutoDFRDiagnosisService()
  33. {
  34. AllFunctions = AutoDFRDiagnosis.AllFunctions;
  35. }
  36. public static void Init(FunctionInfo enableFunction, FunctionInfo currentUsedFunction)
  37. {
  38. AutoDFRDiagnosis.Init(enableFunction, currentUsedFunction);
  39. }
  40. public AutoDFRDiagnosisService()
  41. {
  42. try
  43. {
  44. _singleImageCache = new ConcurrentStack<byte[]>();
  45. _singleImagePipeServer = new PipeServer(AIDiagnosisSystemConsts.PipeForAutoDFRDiagnosisSingleImage);
  46. _singleImagePipeServer.LogMsgThrow += OnLogMsgThrow;
  47. _singleImagePipeServer.DataReceived += OnDataReceived;
  48. _singleImagePipeServer.StartAndReceive();
  49. _imageProvider = new ImageProvider(AIEnumType.AutoDFRDiagnosis);
  50. }
  51. catch (Exception ex)
  52. {
  53. Logger.Error($"AutoDFRDiagnosisService-Constructor error:{ex}");
  54. }
  55. }
  56. public void Initialize(AutoDFRDiagnosisParameter autoDFRParameter, bool hasImageProvider)
  57. {
  58. try
  59. {
  60. CloseDiagnosis();
  61. var cpuNumber = autoDFRParameter.CPUNumber;
  62. var detectMode = (EnumDetectMode)autoDFRParameter.DetectMode;
  63. var detectTps = autoDFRParameter.DetectTps;
  64. var intervalTime = autoDFRParameter.IntervalTime;
  65. var cmPerPixel = autoDFRParameter.CmPerPixel;
  66. var isIncludeContour = autoDFRParameter.IsIncludeContour;
  67. _autoDFRDiagnosis = new AutoDFRDiagnosis(Setting.Instance.IsSaveDetectImage, Setting.Instance.IsSaveAllImage, Logger.LogDir, hasImageProvider ? _imageProvider : null, cpuNumber, _modelFolder, cmPerPixel, detectMode, detectTps, intervalTime, isIncludeContour);
  68. _autoDFRDiagnosis.StartEvaluation += OnStartEvaluation;
  69. _autoDFRDiagnosis.FinishEvaluation += OnFinishEvaluation;
  70. _autoDFRDiagnosis.NotifyError += OnNotifyError;
  71. _autoDFRDiagnosis.NotifyLog += OnNotifyLog;
  72. }
  73. catch (Exception ex)
  74. {
  75. Logger.Error($"AutoDFRDiagnosisService-Initialize error:{ex}");
  76. }
  77. }
  78. /// <summary>
  79. /// 切换引擎
  80. /// </summary>
  81. /// <param name="functionInfo"></param>
  82. public void SwitchEngines(FunctionInfo functionInfo)
  83. {
  84. try
  85. {
  86. AutoDFRDiagnosis.SwitchAIEngines(functionInfo);
  87. if (_autoDFRDiagnosis != null)
  88. {
  89. _autoDFRDiagnosis.SwitchAIEngines2(functionInfo);
  90. }
  91. }
  92. catch (Exception ex)
  93. {
  94. Logger.Error($"AutoDFRDiagnosisService-SwitchEngines error:{ex}");
  95. }
  96. }
  97. public void Start()
  98. {
  99. try
  100. {
  101. if (_autoDFRDiagnosis != null)
  102. {
  103. _autoDFRDiagnosis.Start();
  104. }
  105. }
  106. catch (Exception ex)
  107. {
  108. Logger.Error($"AutoDFRDiagnosisService-Start error:{ex}");
  109. }
  110. }
  111. public void Stop()
  112. {
  113. try
  114. {
  115. if (_autoDFRDiagnosis != null)
  116. {
  117. _autoDFRDiagnosis.Stop();
  118. }
  119. }
  120. catch (Exception ex)
  121. {
  122. Logger.Error($"AutoDFRDiagnosisService-Stop error:{ex}");
  123. }
  124. }
  125. public void SetDetectTps(int detectTps)
  126. {
  127. try
  128. {
  129. if (_autoDFRDiagnosis != null)
  130. {
  131. _autoDFRDiagnosis.DetectTps = detectTps;
  132. }
  133. }
  134. catch (Exception ex)
  135. {
  136. Logger.Error($"AutoDFRDiagnosisService-SetDetectTps error:{ex}");
  137. }
  138. }
  139. public void SetIntervalTime(int intervalTime)
  140. {
  141. try
  142. {
  143. if (_autoDFRDiagnosis != null)
  144. {
  145. _autoDFRDiagnosis.IntervalTime = intervalTime;
  146. }
  147. }
  148. catch (Exception ex)
  149. {
  150. Logger.Error($"AutoDFRDiagnosisService-SetIntervalTime error:{ex}");
  151. }
  152. }
  153. public void SetDetectMode(AIEnumDetectMode detectMode)
  154. {
  155. try
  156. {
  157. if (_autoDFRDiagnosis != null)
  158. {
  159. _autoDFRDiagnosis.DetectMode = (EnumDetectMode)detectMode;
  160. }
  161. }
  162. catch (Exception ex)
  163. {
  164. Logger.Error($"AutoDFRDiagnosisService-SetDetectMode error:{ex}");
  165. }
  166. }
  167. /// <summary>
  168. /// 设置一个像素代表的实际物理距离是多少cm
  169. /// </summary>
  170. /// <param name="cmPerPixel"></param>
  171. public void SetCmPerPixel(float cmPerPixel)
  172. {
  173. try
  174. {
  175. if (_autoDFRDiagnosis != null)
  176. {
  177. _autoDFRDiagnosis.CmPerPixel = cmPerPixel;
  178. }
  179. }
  180. catch (Exception ex)
  181. {
  182. Logger.Error($"AutoDFRDiagnosisService-SetCmPerPixel error:{ex}");
  183. }
  184. }
  185. /// <summary>
  186. /// 检测单张Byte Image
  187. /// </summary>
  188. /// <param name="cmPerPixel">图像上一个像素实际代表的物理距离是多少cm</param>
  189. /// <returns></returns>
  190. public AIAutoDFRCalcResult DetectOneByteImage(float cmPerPixel)
  191. {
  192. try
  193. {
  194. byte[] byteImage = null;
  195. int retryCount = 0;
  196. while (!_singleImageCache.TryPop(out byteImage) && retryCount < 50)
  197. {
  198. Thread.Sleep(10);
  199. retryCount++;
  200. }
  201. if (byteImage == null)
  202. {
  203. Logger.Error($"AutoDFRDiagnosisService-DetectOneByteImage Get Image Cache Fail");
  204. return null;
  205. }
  206. var autoDFRCalcResult = _autoDFRDiagnosis.DetectOneImage(byteImage, cmPerPixel);
  207. return AIConvertHelper.ConvertAutoDFRCalcResultToAIAutoDFRCalcResult(autoDFRCalcResult);
  208. }
  209. catch (Exception ex)
  210. {
  211. Logger.Error($"AutoDFRDiagnosisService-DetectOneByteImage error:{ex}");
  212. return null;
  213. }
  214. }
  215. public AIAutoDFRCalcResult DetectOneRawImage(int height, int width, AIEnumColorType colorType, float cmPerPixel)
  216. {
  217. try
  218. {
  219. byte[] byteImage = null;
  220. int retryCount = 0;
  221. while (!_singleImageCache.TryPop(out byteImage) && retryCount < 50)
  222. {
  223. Thread.Sleep(10);
  224. retryCount++;
  225. }
  226. if (byteImage == null)
  227. {
  228. Logger.Error($"AutoDFRDiagnosisService-DetectOneRawImage Get Image Cache Fail");
  229. return null;
  230. }
  231. var rawImage = new RawImage(byteImage, width, height, (EnumColorType)colorType);
  232. var autoDFRCalcResult = _autoDFRDiagnosis.DetectOneImage(rawImage, cmPerPixel);
  233. return AIConvertHelper.ConvertAutoDFRCalcResultToAIAutoDFRCalcResult(autoDFRCalcResult);
  234. }
  235. catch (Exception ex)
  236. {
  237. Logger.Error($"AutoDFRDiagnosisService-DetectOneRawImage error:{ex}");
  238. return null;
  239. }
  240. }
  241. /// <summary>
  242. /// Send Raw Image Data For Pipe
  243. /// </summary>
  244. /// <param name="height"></param>
  245. /// <param name="width"></param>
  246. /// <param name="colorType"></param>
  247. public void SendRawImageData(int height, int width, AIEnumColorType colorType)
  248. {
  249. try
  250. {
  251. _imageProvider?.ReceiveRawImageData(height, width, (EnumColorType)colorType);
  252. }
  253. catch (Exception ex)
  254. {
  255. Logger.Error($"AutoDFRDiagnosisService-SendRawImageData error:{ex}");
  256. }
  257. }
  258. /// <summary>
  259. /// Send Byte Image Data For Pipe
  260. /// </summary>
  261. public void SendByteImageData()
  262. {
  263. try
  264. {
  265. _imageProvider?.ReceiveByteImageData();
  266. }
  267. catch (Exception ex)
  268. {
  269. Logger.Error($"AutoDFRDiagnosisService-SendByteImageData error:{ex}");
  270. }
  271. }
  272. public void Close()
  273. {
  274. try
  275. {
  276. Logger.Info($"AutoDFRDiagnosisService-Close Invoke");
  277. CloseDiagnosis();
  278. }
  279. catch (Exception ex)
  280. {
  281. Logger.Error($"AutoDFRDiagnosisService-Close error:{ex}");
  282. }
  283. }
  284. private void CloseDiagnosis()
  285. {
  286. if (_autoDFRDiagnosis != null)
  287. {
  288. _autoDFRDiagnosis.StartEvaluation -= OnStartEvaluation;
  289. _autoDFRDiagnosis.FinishEvaluation -= OnFinishEvaluation;
  290. _autoDFRDiagnosis.NotifyError -= OnNotifyError;
  291. _autoDFRDiagnosis.NotifyLog -= OnNotifyLog;
  292. _autoDFRDiagnosis.Close();
  293. _autoDFRDiagnosis = null;
  294. }
  295. }
  296. public void Dispose()
  297. {
  298. try
  299. {
  300. if (!_disposed)
  301. {
  302. Logger.Info($"AutoDFRDiagnosisService-Start Dispose");
  303. CloseDiagnosis();
  304. if (_singleImagePipeServer != null)
  305. {
  306. _singleImagePipeServer.DataReceived -= OnDataReceived;
  307. _singleImagePipeServer.Dispose();
  308. _singleImagePipeServer.LogMsgThrow -= OnLogMsgThrow;
  309. _singleImagePipeServer = null;
  310. }
  311. _imageProvider.Dispose();
  312. _imageProvider = null;
  313. _disposed = true;
  314. Logger.Info($"AutoDFRDiagnosisService Dispose End");
  315. }
  316. }
  317. catch (Exception ex)
  318. {
  319. Logger.Error($"AutoDFRDiagnosisService-Dispose error:{ex}");
  320. }
  321. }
  322. private void OnStartEvaluation(object sender, EventArgs e)
  323. {
  324. NotificationSender.SendNotification(new AINotificationArgs() { NotificationType = AIEnumNotificationType.AutoDFRDiagnosisStartEvaluationRaised, Params = e });
  325. }
  326. private void OnFinishEvaluation(object sender, AutoDFRCalcResult e)
  327. {
  328. var aiAutoDFRCalcResult = AIConvertHelper.ConvertAutoDFRCalcResultToAIAutoDFRCalcResult(e);
  329. NotificationSender.SendNotification(new AINotificationArgs() { NotificationType = AIEnumNotificationType.AutoDFRDiagnosisFinishEvaluationRaised, Params = aiAutoDFRCalcResult });
  330. }
  331. private void OnNotifyLog(object sender, LogEventArgs e)
  332. {
  333. if (e == null)
  334. {
  335. return;
  336. }
  337. switch (e.LogType)
  338. {
  339. case EnumLogType.InfoLog:
  340. Logger.Info($"AutoDFRDiagnosisService OnNotifyLog:{e.Msg}");
  341. break;
  342. case EnumLogType.WarnLog:
  343. Logger.Warning($"AutoDFRDiagnosisService OnNotifyLog:{e.Msg}");
  344. break;
  345. case EnumLogType.ErrorLog:
  346. case EnumLogType.FatalLog:
  347. default:
  348. Logger.Error($"AutoDFRDiagnosisService OnNotifyLog:{e.Msg}");
  349. break;
  350. }
  351. var logEventArgs = AICommonServiceConvertHelper.ConvertLogEventArgsToAILogEventArgs(e);
  352. NotificationSender.SendNotification(new AINotificationArgs() { NotificationType = AIEnumNotificationType.AutoDFRDiagnosisNotifyLogRaised, Params = logEventArgs });
  353. }
  354. private void OnNotifyError(object sender, ErrorEventArgs e)
  355. {
  356. Logger.Error($"AutoDFRDiagnosisService OnNotifyError:{e.GetException()}");
  357. var logEventArgs = AICommonServiceConvertHelper.ConvertErrorEventArgsToAILogEventArgs(e);
  358. NotificationSender.SendNotification(new AINotificationArgs() { NotificationType = AIEnumNotificationType.AutoDFRDiagnosisNotifyLogRaised, Params = logEventArgs });
  359. }
  360. private void OnLogMsgThrow(object sender, AILogEventArgs e)
  361. {
  362. if (e == null)
  363. {
  364. return;
  365. }
  366. switch (e.LogType)
  367. {
  368. case AIEnumLogType.ErrorLog:
  369. case AIEnumLogType.FatalLog:
  370. Logger.Error(e.Msg);
  371. break;
  372. case AIEnumLogType.WarnLog:
  373. Logger.Warning(e.Msg);
  374. break;
  375. case AIEnumLogType.InfoLog:
  376. default:
  377. Logger.Info(e.Msg);
  378. break;
  379. }
  380. }
  381. private void OnDataReceived(object sender, byte[] e)
  382. {
  383. try
  384. {
  385. _singleImageCache.Push(e);
  386. }
  387. catch (Exception ex)
  388. {
  389. Logger.Error($"AutoDFRDiagnosisService-OnDataReceived error:{ex}");
  390. }
  391. }
  392. }
  393. }