123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568 |
- using AI.Common.Interface;
- using AIDiagnosis.Common.Enums;
- using AIDiagnosis.Common.Models;
- using System;
- using System.Collections.Concurrent;
- using System.Collections.Generic;
- using System.IO;
- using System.Linq;
- using System.Threading;
- using Vinno.AI.CommonSDK.Enums;
- using Vinno.AI.CommonSDK.Models;
- using Vinno.AI.CommonSDK.Models.Data;
- using Vinno.AI.CommonSDK.Tools;
- using Vinno.AI.CustomizeDiagnosisSDK.Interfaces;
- using Vinno.AI.CustomizeDiagnosisSDK.Models;
- using Vinno.AI.CustomizeDiagnosisService.Tools;
- using Vinno.AI.Service.Common.Models;
- using Vinno.AI.Service.Common.Tools;
- using CustomizeDiagnosis = CustomizeDiagnosisSDK.CustomizeDiagnosis;
- namespace Vinno.AI.CustomizeDiagnosisService
- {
- public class CustomizeDiagnosisService : ICustomizeDiagnosisService, IDisposable
- {
- private readonly ConcurrentDictionary<string, ConcurrentStack<byte[]>> _singleImageCacheList;
- private readonly ConcurrentDictionary<string, PipeServer> _singleImagePipeServerList;
- private readonly ConcurrentDictionary<string, CustomizeImageProviderV2> _imageProviderList;
- private static readonly string _customizeFolder = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "CustomizeFolder");
- private bool _disposed;
- private static List<CustomizeDiagnosis> _customizeDiagnoses;
- public static List<FunctionInfo> AllFunctions { get; private set; }
- static CustomizeDiagnosisService()
- {
- try
- {
- _customizeDiagnoses = new List<CustomizeDiagnosis>();
- LoadCustomizeEngines();
- }
- catch (Exception ex)
- {
- Logger.Error($"CustomizeDiagnosisService-Constructor error:{ex}");
- }
- }
- private static void LoadCustomizeEngines()
- {
- if (!Directory.Exists(_customizeFolder))
- {
- return;
- }
- var folders = Directory.GetDirectories(_customizeFolder);
- if (folders == null || folders.Length == 0)
- {
- return;
- }
- foreach (var item in folders)
- {
- var directoryName = Path.GetFileName(item);
- var engineArray = directoryName.Split('_');
- if (engineArray.Length == 2)
- {
- if (!engineArray[1].ToLower().EndsWith(".dll"))
- {
- continue;
- }
- var engineType = engineArray[0];
- var engineDllName = engineArray[1];
- var engineDll = Directory.GetFiles(item).FirstOrDefault(x => x.EndsWith(engineDllName));
- if (engineDll == null)
- {
- continue;
- }
- try
- {
- var customizeDiagnosis = new CustomizeDiagnosis(engineDll, engineType);
- _customizeDiagnoses.Add(customizeDiagnosis);
- if (AllFunctions == null)
- {
- AllFunctions = new List<FunctionInfo>
- {
- new FunctionInfo(AIEnumType.CustomizeDiagnosis, true, customizeDiagnosis.FunctionVersion, null, new List<EngineInfo>())
- };
- }
- AllFunctions[0].Engines.Add(customizeDiagnosis.EngineInfo);
- }
- catch (Exception ex)
- {
- Logger.Warning($"LoadCustomizeEngines Error:{ex}");
- continue;
- }
- }
- else
- {
- continue;
- }
- }
- }
- public CustomizeDiagnosisService()
- {
- try
- {
- _singleImageCacheList = new ConcurrentDictionary<string, ConcurrentStack<byte[]>>();
- _singleImagePipeServerList = new ConcurrentDictionary<string, PipeServer>();
- _imageProviderList = new ConcurrentDictionary<string, CustomizeImageProviderV2>();
- if (AllFunctions?.FirstOrDefault()?.Engines == null || AllFunctions.FirstOrDefault()?.Engines.Count == 0)
- {
- throw new ArgumentNullException("CustomizeDiagnosisService has no enable Function or Engines");
- }
- foreach (var engine in AllFunctions.FirstOrDefault()?.Engines)
- {
- var uniqueString = engine.GetUniqueString();
- var singleImagePipeServer = new PipeServer(AIDiagnosisSystemConsts.PipeForCustomizeDiagnosisSingleImage + uniqueString);
- singleImagePipeServer.LogMsgThrow += OnLogMsgThrow;
- singleImagePipeServer.DataReceived += OnDataReceived;
- singleImagePipeServer.StartAndReceive();
- if (!_singleImagePipeServerList.TryAdd(uniqueString, singleImagePipeServer))
- {
- Logger.Error($"CustomizeDiagnosisService Try Add _singleImagePipeServerList Failed, UniqueString:{uniqueString}");
- continue;
- }
- if (!_singleImageCacheList.TryAdd(AIDiagnosisSystemConsts.PipeForCustomizeDiagnosisSingleImage + uniqueString, new ConcurrentStack<byte[]>()))
- {
- Logger.Error($"CustomizeDiagnosisService Try Add _singleImageCacheList Failed, UniqueString:{uniqueString}");
- continue;
- }
- if (!_imageProviderList.TryAdd(uniqueString, new CustomizeImageProviderV2(uniqueString)))
- {
- Logger.Error($"CustomizeDiagnosisService Try Add _imageProviderList Failed, UniqueString:{uniqueString}");
- continue;
- }
- }
- }
- catch (Exception ex)
- {
- Logger.Error($"CustomizeDiagnosis-Constructor error:{ex}");
- }
- }
- public void Initialize(AIEngineInfo aiEngineInfo, CustomizeDiagnosisParameter customizeDiagnosisParameter, bool hasImageProvider)
- {
- try
- {
- if (aiEngineInfo == null)
- {
- Logger.Error($"CustomizeDiagnosisService Initialize Error: engineInfo is null");
- return;
- }
- var uniqueString = aiEngineInfo.GetUniqueString();
- var existDiagnosis = _customizeDiagnoses.FirstOrDefault(x => x.EngineInfo.GetUniqueString() == uniqueString);
- if (existDiagnosis == null)
- {
- Logger.Error($"CustomizeDiagnosisService Initialize Error: {uniqueString} not found ");
- return;
- }
- CloseDiagnosis(existDiagnosis);
- var detectMode = (EnumDetectMode)customizeDiagnosisParameter.DetectMode;
- var detectTps = customizeDiagnosisParameter.DetectTps;
- var intervalTime = customizeDiagnosisParameter.IntervalTime;
- CustomizeImageProviderV2 imageProvider;
- if (hasImageProvider)
- {
- if (_imageProviderList.ContainsKey(uniqueString))
- {
- imageProvider = _imageProviderList[aiEngineInfo.GetUniqueString()];
- }
- else
- {
- imageProvider = null;
- }
- }
- else
- {
- imageProvider = null;
- }
- existDiagnosis.Initialize(Setting.Instance.IsSaveDetectImage, Setting.Instance.IsSaveAllImage, Logger.LogDir, imageProvider, detectMode, detectTps, intervalTime);
- existDiagnosis.StartEvaluation += OnStartEvaluation;
- existDiagnosis.FinishEvaluation += OnFinishEvaluation;
- existDiagnosis.NotifyLog += OnNotifyLog;
- }
- catch (Exception ex)
- {
- Logger.Error($"CustomizeDiagnosis-Initialize error:{ex}");
- }
- }
- public AICustomizeDetectedObjectInfo[] DetectOneImage(AIEngineInfo aiEngineInfo, int height, int width, AIEnumColorType colorType, AIImageDataId aiImageDataId, AIImageExtraInfo imageExtraInfo, AICustomizeUltrasoundImageRegionInfo ultrasoundImageRegionInfo)
- {
- try
- {
- if (aiEngineInfo == null)
- {
- Logger.Error($"CustomizeDiagnosisService DetectOneRawImage Error: engineInfo is null");
- return null;
- }
- var uniqueString = aiEngineInfo.GetUniqueString();
- var existDiagnosis = _customizeDiagnoses.FirstOrDefault(x => x.EngineInfo.GetUniqueString() == uniqueString);
- if (existDiagnosis == null)
- {
- Logger.Error($"CustomizeDiagnosisService DetectOneRawImage Error: {uniqueString} not found ");
- return null;
- }
- if (!_singleImageCacheList.ContainsKey(AIDiagnosisSystemConsts.PipeForCustomizeDiagnosisSingleImage + uniqueString))
- {
- Logger.Error($"CustomizeDiagnosisService DetectOneRawImage Error: _singleImageCacheList not found {uniqueString}");
- return null;
- }
- byte[] byteImage = null;
- int retryCount = 0;
- while (!_singleImageCacheList[AIDiagnosisSystemConsts.PipeForCustomizeDiagnosisSingleImage + uniqueString].TryPop(out byteImage) && retryCount < 50)
- {
- Thread.Sleep(10);
- retryCount++;
- }
- if (byteImage == null)
- {
- Logger.Error($"CustomizeDiagnosis-DetectOneRawImage Get Image Cache Fail");
- return null;
- }
- var rawImage = new RawImage(byteImage, width, height, (EnumColorType)colorType);
- var imageDataId = AICommonServiceConvertHelperV2.ConvertAIImageDataIdToImageDataId(aiImageDataId);
- Dictionary<string, object> extraInfoList = new Dictionary<string, object>();
- if (imageExtraInfo != null)
- {
- extraInfoList.Add(nameof(imageExtraInfo.CmPerPixel), imageExtraInfo.CmPerPixel);
- }
- if (ultrasoundImageRegionInfo != null)
- {
- var ultrasoundImageRegion = AIConvertHelper.ConvertAICustomizeUltrasoundImageRegionInfoToIUltrasoundImageRegion(ultrasoundImageRegionInfo);
- if (ultrasoundImageRegion != null)
- {
- extraInfoList.Add("UltrasoundImageRegion", ultrasoundImageRegion);
- }
- }
- var imageInputData = new ImageInputData(rawImage, imageDataId, extraInfoList);
- var detectedObjects = existDiagnosis.DetectOneImage(imageInputData);
- return AIConvertHelper.ConvertIDetectedObjectArrayToAICustomizeDetectedObjectInfoArray(detectedObjects);
- }
- catch (Exception ex)
- {
- Logger.Error($"CustomizeDiagnosis-DetectOneRawImage error:{ex}");
- return null;
- }
- }
- public void Start(AIEngineInfo aiEngineInfo)
- {
- try
- {
- if (aiEngineInfo == null)
- {
- Logger.Error($"CustomizeDiagnosisService Start Error: engineInfo is null");
- return;
- }
- var uniqueString = aiEngineInfo.GetUniqueString();
- var existDiagnosis = _customizeDiagnoses.FirstOrDefault(x => x.EngineInfo.GetUniqueString() == uniqueString);
- if (existDiagnosis == null)
- {
- Logger.Error($"CustomizeDiagnosisService Start Error: {uniqueString} not found ");
- return;
- }
- if (existDiagnosis.IsInitialized)
- {
- existDiagnosis.Start();
- }
- }
- catch (Exception ex)
- {
- Logger.Error($"CustomizeDiagnosisService-Start error:{ex}");
- }
- }
- public void Stop(AIEngineInfo aiEngineInfo)
- {
- try
- {
- if (aiEngineInfo == null)
- {
- Logger.Error($"CustomizeDiagnosisService Stop Error: engineInfo is null");
- return;
- }
- var uniqueString = aiEngineInfo.GetUniqueString();
- var existDiagnosis = _customizeDiagnoses.FirstOrDefault(x => x.EngineInfo.GetUniqueString() == uniqueString);
- if (existDiagnosis == null)
- {
- Logger.Error($"CustomizeDiagnosisService Stop Error: {uniqueString} not found ");
- return;
- }
- if (existDiagnosis.IsInitialized)
- {
- existDiagnosis.Stop();
- }
- }
- catch (Exception ex)
- {
- Logger.Error($"CustomizeDiagnosisService-Stop error:{ex}");
- }
- }
- public void SetDetectTps(AIEngineInfo aiEngineInfo, int detectTps)
- {
- try
- {
- if (aiEngineInfo == null)
- {
- Logger.Error($"CustomizeDiagnosisService SetDetectTps Error: engineInfo is null");
- return;
- }
- var uniqueString = aiEngineInfo.GetUniqueString();
- var existDiagnosis = _customizeDiagnoses.FirstOrDefault(x => x.EngineInfo.GetUniqueString() == uniqueString);
- if (existDiagnosis == null)
- {
- Logger.Error($"CustomizeDiagnosisService SetDetectTps Error: {uniqueString} not found ");
- return;
- }
- if (existDiagnosis.IsInitialized)
- {
- existDiagnosis.DetectTps = detectTps;
- }
- }
- catch (Exception ex)
- {
- Logger.Error($"CustomizeDiagnosisService-SetDetectTps error:{ex}");
- }
- }
- public void SetIntervalTime(AIEngineInfo aiEngineInfo, int intervalTime)
- {
- try
- {
- if (aiEngineInfo == null)
- {
- Logger.Error($"CustomizeDiagnosisService SetIntervalTime Error: engineInfo is null");
- return;
- }
- var uniqueString = aiEngineInfo.GetUniqueString();
- var existDiagnosis = _customizeDiagnoses.FirstOrDefault(x => x.EngineInfo.GetUniqueString() == uniqueString);
- if (existDiagnosis == null)
- {
- Logger.Error($"CustomizeDiagnosisService SetIntervalTime Error: {uniqueString} not found ");
- return;
- }
- if (existDiagnosis.IsInitialized)
- {
- existDiagnosis.IntervalTime = intervalTime;
- }
- }
- catch (Exception ex)
- {
- Logger.Error($"CustomizeDiagnosisService-SetIntervalTime error:{ex}");
- }
- }
- public void SetDetectMode(AIEngineInfo aiEngineInfo, AIEnumDetectMode detectMode)
- {
- try
- {
- if (aiEngineInfo == null)
- {
- Logger.Error($"CustomizeDiagnosisService SetDetectMode Error: engineInfo is null");
- return;
- }
- var uniqueString = aiEngineInfo.GetUniqueString();
- var existDiagnosis = _customizeDiagnoses.FirstOrDefault(x => x.EngineInfo.GetUniqueString() == uniqueString);
- if (existDiagnosis == null)
- {
- Logger.Error($"CustomizeDiagnosisService SetDetectMode Error: {uniqueString} not found ");
- return;
- }
- if (existDiagnosis.IsInitialized)
- {
- existDiagnosis.DetectMode = (EnumDetectMode)detectMode; ;
- }
- }
- catch (Exception ex)
- {
- Logger.Error($"CustomizeDiagnosisService-SetDetectMode error:{ex}");
- }
- }
- public void Close(AIEngineInfo aiEngineInfo)
- {
- try
- {
- if (aiEngineInfo == null)
- {
- Logger.Error($"CustomizeDiagnosisService Close Error: engineInfo is null");
- return;
- }
- Logger.Info($"CustomizeDiagnosis-Close Invoke {aiEngineInfo.GetUniqueString()}");
- var uniqueString = aiEngineInfo.GetUniqueString();
- var existDiagnosis = _customizeDiagnoses.FirstOrDefault(x => x.EngineInfo.GetUniqueString() == uniqueString);
- if (existDiagnosis == null)
- {
- Logger.Error($"CustomizeDiagnosisService Close Error: {uniqueString} not found ");
- return;
- }
- existDiagnosis.NotifyLog -= OnNotifyLog;
- existDiagnosis.Close();
- }
- catch (Exception ex)
- {
- Logger.Error($"CustomizeDiagnosis-Close error:{ex}");
- }
- }
- public void CloseAllEngines()
- {
- try
- {
- Logger.Info($"CustomizeDiagnosis-CloseAllEngines Invoke");
- foreach (var customizeDiagnosis in _customizeDiagnoses)
- {
- CloseDiagnosis(customizeDiagnosis);
- }
- }
- catch (Exception ex)
- {
- Logger.Error($"CustomizeDiagnosis-Close error:{ex}");
- }
- }
- private void CloseDiagnosis(CustomizeDiagnosis customizeDiagnosis)
- {
- customizeDiagnosis.StartEvaluation -= OnStartEvaluation;
- customizeDiagnosis.FinishEvaluation -= OnFinishEvaluation;
- customizeDiagnosis.NotifyLog -= OnNotifyLog;
- customizeDiagnosis.Close();
- }
- public void Dispose()
- {
- try
- {
- if (!_disposed)
- {
- Logger.Info($"CustomizeDiagnosis-Start Dispose");
- CloseAllEngines();
- foreach (var pipeKey in _singleImagePipeServerList.Keys.ToArray())
- {
- if (_singleImagePipeServerList.TryRemove(pipeKey, out var pipeServer))
- {
- pipeServer.DataReceived -= OnDataReceived;
- pipeServer.Dispose();
- pipeServer.LogMsgThrow -= OnLogMsgThrow;
- pipeServer = null;
- }
- }
- _singleImagePipeServerList.Clear();
- foreach (var key in _imageProviderList.Keys.ToArray())
- {
- if (_imageProviderList.TryRemove(key, out var imageProvider))
- {
- imageProvider.Dispose();
- imageProvider = null;
- }
- }
- _imageProviderList.Clear();
- _disposed = true;
- Logger.Info($"CustomizeDiagnosis Dispose End");
- }
- }
- catch (Exception ex)
- {
- Logger.Error($"CustomizeDiagnosis-Dispose error:{ex}");
- }
- }
- private void OnNotifyLog(object sender, LogEventArgs e)
- {
- if (e == null)
- {
- return;
- }
- switch (e.LogType)
- {
- case EnumLogType.InfoLog:
- Logger.Info($"CustomizeDiagnosis OnNotifyLog:{e.Msg}");
- break;
- case EnumLogType.WarnLog:
- Logger.Warning($"CustomizeDiagnosis OnNotifyLog:{e.Msg}");
- break;
- case EnumLogType.ErrorLog:
- case EnumLogType.FatalLog:
- default:
- Logger.Error($"CustomizeDiagnosis OnNotifyLog:{e.Msg}");
- break;
- }
- var logEventArgs = AICommonServiceConvertHelperV2.ConvertLogEventArgsToAILogEventArgs(e);
- NotificationSender.SendNotification(new AINotificationArgs() { NotificationType = AIEnumNotificationType.CustomizeDiagnosisNotifyLogRaised, Params = logEventArgs });
- }
- private void OnLogMsgThrow(object sender, AILogEventArgs e)
- {
- if (e == null)
- {
- return;
- }
- switch (e.LogType)
- {
- case AIEnumLogType.ErrorLog:
- case AIEnumLogType.FatalLog:
- Logger.Error(e.Msg);
- break;
- case AIEnumLogType.WarnLog:
- Logger.Warning(e.Msg);
- break;
- case AIEnumLogType.InfoLog:
- default:
- Logger.Info(e.Msg);
- break;
- }
- }
- private void OnDataReceived(object sender, byte[] e)
- {
- try
- {
- var pipeServer = (PipeServer)sender;
- if (_singleImageCacheList.ContainsKey(pipeServer.PipeName))
- {
- _singleImageCacheList[pipeServer.PipeName].Push(e);
- }
- }
- catch (Exception ex)
- {
- Logger.Error($"CustomizeDiagnosis-OnDataReceived error:{ex}");
- }
- }
- public void SendImageData(AIEngineInfo aiEngineInfo, int height, int width, AIEnumColorType colorType, AIImageDataId continuityExtraInfo, AIImageExtraInfo measuringScaleExtraInfo, AICustomizeUltrasoundImageRegionInfo ultrasoundImageRegion)
- {
- if (aiEngineInfo == null)
- {
- Logger.Error($"CustomizeDiagnosisService SendImageData Error: engineInfo is null");
- return;
- }
- var uniqueString = aiEngineInfo.GetUniqueString();
- if (_imageProviderList.ContainsKey(uniqueString))
- {
- _imageProviderList[aiEngineInfo.GetUniqueString()].ReceiveImageData(height, width, colorType, continuityExtraInfo, measuringScaleExtraInfo, ultrasoundImageRegion);
- }
- }
- private void OnStartEvaluation(object sender, EventArgs e)
- {
- var diagnosis = (CustomizeDiagnosis)sender;
- var aiEngineInfo = AIConvertHelper.ConvertEngineInfoToAIEngineInfo(diagnosis.EngineInfo, true);
- NotificationSender.SendNotification(new AINotificationArgs() { NotificationType = AIEnumNotificationType.CustomizeDiagnosisStartEvaluationRaised, Params = aiEngineInfo });
- }
- private void OnFinishEvaluation(object sender, IDetectedObject[] e)
- {
- var result = AIConvertHelper.ConvertIDetectedObjectArrayToAICustomizeDetectedObjectInfoArray(e);
- var diagnosis = (CustomizeDiagnosis)sender;
- var aiEngineInfo = AIConvertHelper.ConvertEngineInfoToAIEngineInfo(diagnosis.EngineInfo, true);
- NotificationSender.SendNotification(new AINotificationArgs() { NotificationType = AIEnumNotificationType.CustomizeDiagnosisFinishEvaluationRaised, Params = new TransAICustomizeDetectedObjectInfo(aiEngineInfo, result) });
- }
- }
- }
|