RemoteCommandService.cs 177 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699
  1. using Basler.Pylon;
  2. using Cognex.VisionPro;
  3. using Cognex.VisionPro.ImageFile;
  4. using Cognex.VisionPro.ToolBlock;
  5. using MathNet.Numerics.LinearAlgebra;
  6. using Microsoft.CodeAnalysis.Scripting;
  7. using NPOI.SS.Formula.Functions;
  8. using OpenCvSharp;
  9. using OpenCvSharp.Flann;
  10. using Org.BouncyCastle.Asn1.Cms;
  11. using Org.BouncyCastle.Tls;
  12. using Prism.Events;
  13. using Prism.Ioc;
  14. using Prism.Regions;
  15. using System;
  16. using System.Collections.Concurrent;
  17. using System.Collections.Generic;
  18. using System.ComponentModel;
  19. using System.IO;
  20. using System.Linq;
  21. using System.Reflection;
  22. using System.Text;
  23. using System.Threading;
  24. using System.Threading.Tasks;
  25. using System.Web.UI.WebControls;
  26. using System.Windows.Forms;
  27. using System.Windows.Media.Media3D;
  28. using System.Windows.Shapes;
  29. using Team.FFFeederService;
  30. using Team.FFFeederService.Interfaces;
  31. using TeamAAS_VP.Core;
  32. using TeamAAS_VP.Core.Cameras;
  33. using TeamAAS_VP.Data;
  34. using TeamAAS_VP.Enums;
  35. using TeamAAS_VP.Events;
  36. using TeamAAS_VP.Interfaces;
  37. using TeamAAS_VP.Models;
  38. using TeamAAS_VP.Models.Calibration;
  39. using TeamAAS_VP.Models.Feeder;
  40. using TeamAAS_VP.Models.Product;
  41. using TeamAAS_VP.Resources.Languages;
  42. using WpfTest.core;
  43. namespace TeamAAS_VP.Services
  44. {
  45. /// <summary>
  46. /// 远程命令服务:
  47. /// 负责解析并执行外部传入的命令字符串(例如 LoadProduct、视觉流程触发、清料任务等)。
  48. /// 该类封装了原 Management.ExecuteRemoteCommand 的精简迁移实现,依赖于领域服务(产品、配置、校准、Feeder、相机、机器人、系统数据库等)。
  49. /// 线程安全:通过内部计数器和 ConcurrentDictionary 跟踪正在运行的任务。
  50. /// </summary>
  51. public class RemoteCommandService : IRemoteCommandService, INotifyPropertyChanged
  52. {
  53. // 依赖服务,由构造函数注入
  54. private readonly IEventAggregator _eventAggregator;
  55. private readonly IProductService _productService;
  56. private readonly IConfigService _configService;
  57. private readonly ICalibrationService _calibrationService;
  58. private readonly IFeederService _feederService;
  59. private readonly ICameraService _cameraService;
  60. private readonly IRobotService _robotService;
  61. private readonly IContainerProvider _container;
  62. private readonly IRegionManager _regionManager;
  63. private readonly ISystemDatabaseService _systemDatabaseService;
  64. private readonly ILightManagerService _lightManagerService;
  65. /// <summary>
  66. /// 节拍计时任务的取消令牌,用于 StartCycleTiming/StopCycleTiming。
  67. /// </summary>
  68. private CancellationTokenSource _cycleTimingCts;
  69. /// <summary>
  70. /// 清料任务的取消令牌字典,Key 为任务编号(TaskCode)。
  71. /// 当需要取消特定清料任务时,通过该字典查找并调用 Cancel。
  72. /// </summary>
  73. private readonly ConcurrentDictionary<int, CancellationTokenSource> _clearMaterialCtsDict = new ConcurrentDictionary<int, CancellationTokenSource>();
  74. // 内部执行状态计数器和任务跟踪集合
  75. private int _activeCount;
  76. private int _visionActiveCount;
  77. private readonly ConcurrentDictionary<Guid, Task> _runningTasks = new ConcurrentDictionary<Guid, Task>();
  78. // INotifyPropertyChanged 实现
  79. public event PropertyChangedEventHandler PropertyChanged;
  80. private void OnPropertyChanged(string name) => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
  81. /// <summary>
  82. /// 标识是否存在任意正在执行的命令(非视觉与视觉命令)。
  83. /// 由 TrackExecutionAsync 自动维护。
  84. /// </summary>
  85. public bool IsExecuting => Volatile.Read(ref _activeCount) > 0;
  86. /// <summary>
  87. /// 标识是否存在正在执行的视觉指令。
  88. /// 由 TrackExecutionAsync 在 isVision 参数为 true 时自动维护。
  89. /// </summary>
  90. public bool IsExecutingVisionCommand => Volatile.Read(ref _visionActiveCount) > 0;
  91. /// <summary>
  92. /// 当执行状态发生变化(开始/结束)时触发(便于传统事件订阅)。
  93. /// </summary>
  94. public event EventHandler ExecutionStateChanged;
  95. /// <summary>
  96. /// 节拍计时的定时回调事件,通知订阅者当前已用时。
  97. /// </summary>
  98. public event EventHandler<TimeSpan> CycleTimingTicked;
  99. public float TempExposureTime = 0;
  100. public float TempGain = 0;
  101. /// <summary>
  102. /// 构造函数,注入必要的系统服务。
  103. /// </summary>
  104. /// <param name="eventAggregator">事件聚合器,用于发布 UI 渲染/消息等事件。</param>
  105. /// <param name="regionManager">区域管理器,用于 UI 区域导航(在脚本中可能使用)。</param>
  106. /// <param name="productService">产品服务,用于加载/查询产品信息。</param>
  107. /// <param name="configService">配置服务,用于读取机器人/任务/Feeder 等配置。</param>
  108. /// <param name="calibrationService">校准服务,用于像素到机器人坐标的转换。</param>
  109. /// <param name="feederService">Feeder 服务,控制料仓/振动等。</param>
  110. /// <param name="cameraService">相机服务,用于图像采集。</param>
  111. /// <param name="robotService">机器人服务,提供机器人状态码/调试模式等信息。</param>
  112. /// <param name="container">IOC 容器提供者,用于脚本执行时解析依赖。</param>
  113. /// <param name="systemDatabaseService">系统数据库服务,用于记录产量/报警等。</param>
  114. public RemoteCommandService(IEventAggregator eventAggregator, IRegionManager regionManager, IProductService productService, IConfigService configService, ICalibrationService calibrationService,
  115. IFeederService feederService, ICameraService cameraService, IRobotService robotService, IContainerProvider container, ISystemDatabaseService systemDatabaseService, ILightManagerService lightManagerService)
  116. {
  117. _eventAggregator = eventAggregator;
  118. _regionManager = regionManager;
  119. _productService = productService;
  120. _configService = configService;
  121. _calibrationService = calibrationService;
  122. _feederService = feederService;
  123. _cameraService = cameraService;
  124. _robotService = robotService;
  125. _container = container;
  126. _systemDatabaseService = systemDatabaseService;
  127. _lightManagerService = lightManagerService;
  128. }
  129. /// <summary>
  130. /// 占位 Dispose 方法(当前无资源释放逻辑)。
  131. /// </summary>
  132. public void Dispose() { }
  133. /// <summary>
  134. /// 通用的异步执行包装器。该方法:
  135. /// - 为每次执行生成唯一 id 并加入运行任务集合以便跟踪
  136. /// - 维护 _activeCount 和 _visionActiveCount
  137. /// - 在任务开始/结束时触发属性变化和 ExecutionStateChanged 事件
  138. /// - 返回工作 delegate 的结果
  139. /// </summary>
  140. /// <typeparam name="T">工作返回类型</typeparam>
  141. /// <param name="work">以 CancellationToken 为参数的异步工作委托</param>
  142. /// <param name="isVision">指示该工作是否为视觉命令(影响视觉计数器)</param>
  143. /// <param name="ct">外部取消令牌,传递给工作委托</param>
  144. /// <returns>工作委托的返回值</returns>
  145. private async Task<T> TrackExecutionAsync<T>(Func<CancellationToken, Task<T>> work, bool isVision, CancellationToken ct)
  146. {
  147. var id = Guid.NewGuid();
  148. Interlocked.Increment(ref _activeCount);
  149. if (isVision) Interlocked.Increment(ref _visionActiveCount);
  150. OnPropertyChanged(nameof(IsExecuting));
  151. OnPropertyChanged(nameof(IsExecutingVisionCommand));
  152. ExecutionStateChanged?.Invoke(this, EventArgs.Empty);
  153. try
  154. {
  155. var task = work(ct);
  156. _runningTasks.TryAdd(id, task);
  157. var result = await task.ConfigureAwait(false);
  158. return result;
  159. }
  160. finally
  161. {
  162. Interlocked.Decrement(ref _activeCount);
  163. if (isVision) Interlocked.Decrement(ref _visionActiveCount);
  164. _runningTasks.TryRemove(id, out _);
  165. OnPropertyChanged(nameof(IsExecuting));
  166. OnPropertyChanged(nameof(IsExecutingVisionCommand));
  167. ExecutionStateChanged?.Invoke(this, EventArgs.Empty);
  168. }
  169. }
  170. /// <summary>
  171. /// 解析并执行传入的命令字符串。命令以逗号分隔,第一个字段为命令名称,后续为参数。
  172. /// 支持多种内建命令(示例:LoadProduct、GetProductName、CycleTime、Record、StartClearMaterial 等),以及映射到产品 CameraProcedures 的自定义视觉触发命令。
  173. /// </summary>
  174. /// <param name="command">原始命令字符串</param>
  175. /// <param name="cancellationToken">外部取消令牌</param>
  176. /// <param name="callback">用于将执行结果回传(比如发送到调用方)的回调,参数为单行响应字符串</param>
  177. /// <returns>完成任务</returns>
  178. public async Task ExecuteAsync(string command, CancellationToken cancellationToken, Action<string> callback)
  179. {
  180. var items = (command ?? string.Empty).Split(new[] { ',' }, StringSplitOptions.None).Select(s => s.Trim()).ToArray();
  181. if (items.Length == 0) return;
  182. string triggerCommand = items[0];
  183. string[] commandParams = items.Skip(1).ToArray();
  184. string response = string.Empty;
  185. switch (triggerCommand)
  186. {
  187. case "LoadProduct":
  188. if (commandParams.Length < 1)
  189. {
  190. callback?.Invoke("InvalidParameters");
  191. return;
  192. }
  193. response = await TrackExecutionAsync(async ct =>
  194. {
  195. var ok = await LoadProductAsync(commandParams[0], ct);
  196. return ok ? "OK" : "NG";
  197. }, isVision: false, cancellationToken);
  198. callback?.Invoke($"LoadProduct,{response}");
  199. break;
  200. case "GetProductName":
  201. if (commandParams.Length < 1)
  202. {
  203. response = await TrackExecutionAsync(async ct =>
  204. {
  205. return await GetCurrentProductNameAsync(ct);
  206. }, isVision: false, cancellationToken);
  207. if (string.IsNullOrEmpty(response))
  208. {
  209. callback?.Invoke("GetProductName,NG");
  210. }
  211. else
  212. {
  213. callback?.Invoke($"GetProductName,{response}");
  214. }
  215. break;
  216. }
  217. else if (commandParams.Length == 1)
  218. {
  219. if (!int.TryParse(commandParams[0], out int productNumber))
  220. {
  221. callback?.Invoke("InvalidParameters");
  222. return;
  223. }
  224. response = await TrackExecutionAsync(async ct =>
  225. {
  226. return await GetProductNameByNumberAsync(productNumber, ct);
  227. }, isVision: false, cancellationToken);
  228. if (string.IsNullOrEmpty(response))
  229. {
  230. callback?.Invoke($"GetProductName,NG");
  231. }
  232. else
  233. {
  234. callback?.Invoke($"GetProductName,{response}");
  235. }
  236. break;
  237. }
  238. else
  239. {
  240. callback?.Invoke("InvalidParameters");
  241. return;
  242. }
  243. case "GetProductID":
  244. if (commandParams.Length < 1)
  245. {
  246. response = await TrackExecutionAsync(async ct =>
  247. {
  248. int productNum = await GetCurrentProductNumberAsync(ct);
  249. return productNum.ToString();
  250. }, isVision: false, cancellationToken);
  251. if (response == "-1")
  252. {
  253. callback?.Invoke("GetProductID,NG");
  254. }
  255. else
  256. {
  257. callback?.Invoke($"GetProductID,{response}");
  258. }
  259. break;
  260. }
  261. else if (commandParams.Length == 1)
  262. {
  263. response = await TrackExecutionAsync(async ct =>
  264. {
  265. int productNum = await GetProductNumberByNameAsync(commandParams[0], ct);
  266. return productNum.ToString();
  267. }, isVision: false, cancellationToken);
  268. if (response == "-1")
  269. {
  270. callback?.Invoke($"GetProductID,NG");
  271. }
  272. else
  273. {
  274. callback?.Invoke($"GetProductID,{response}");
  275. }
  276. break;
  277. }
  278. else
  279. {
  280. callback?.Invoke("InvalidParameters");
  281. return;
  282. }
  283. case "GetRobotPointsCountById":
  284. if (commandParams.Length < 2 || !int.TryParse(commandParams[0], out int robotNumber) || !int.TryParse(commandParams[1], out int pointNumber))
  285. {
  286. callback?.Invoke("InvalidParameters");
  287. return;
  288. }
  289. response = await TrackExecutionAsync(async ct =>
  290. {
  291. return await GetRobotPointInfoAsync(robotNumber, pointNumber, ct);
  292. }, isVision: false, cancellationToken);
  293. if (string.IsNullOrEmpty(response))
  294. {
  295. callback?.Invoke($"GetRobotPointsCountById,NG");
  296. }
  297. else
  298. {
  299. callback?.Invoke($"GetRobotPointsCountById,{response}");
  300. }
  301. break;
  302. case "GetPalletPoint":
  303. if (commandParams.Length < 2 || !int.TryParse(commandParams[0], out int robotNumber1) || !int.TryParse(commandParams[1], out int palletNumber1) || !int.TryParse(commandParams[2], out int pointNumber1))
  304. {
  305. callback?.Invoke("InvalidParameters");
  306. return;
  307. }
  308. response = await TrackExecutionAsync(async ct =>
  309. {
  310. return await GetRobotPalletPointInfoAsync(robotNumber1, palletNumber1, pointNumber1, ct);
  311. }, isVision: false, cancellationToken);
  312. if (string.IsNullOrEmpty(response))
  313. {
  314. callback?.Invoke($"GetPalletPoint,NG");
  315. }
  316. else
  317. callback?.Invoke($"GetPalletPoint,{response}");
  318. break;
  319. case "CycleTime":
  320. if (commandParams.Length < 1)
  321. {
  322. callback?.Invoke("InvalidParameters");
  323. return;
  324. }
  325. if (int.Parse(commandParams[0]) == 1)
  326. {
  327. response = await TrackExecutionAsync(async ct =>
  328. {
  329. bool cycleResult = await StartCycleTimingAsync(ct);
  330. return cycleResult ? "OK" : "NG";
  331. }, isVision: false, cancellationToken);
  332. callback?.Invoke($"CycleTime,{response}");
  333. break;
  334. }
  335. else
  336. {
  337. response = await TrackExecutionAsync(async ct =>
  338. {
  339. bool cycleResult = await StopCycleTimingAsync(ct);
  340. return cycleResult ? "OK" : "NG";
  341. }, isVision: false, cancellationToken);
  342. callback?.Invoke($"CycleTime,{response}");
  343. break;
  344. }
  345. case "Record":
  346. if (commandParams.Length < 1)
  347. {
  348. callback?.Invoke("InvalidParameters");
  349. return;
  350. }
  351. response = await TrackExecutionAsync(async ct =>
  352. {
  353. bool recordResult = await CreateProductionCountAsync(commandParams[0].Trim(), ct);
  354. return recordResult ? "OK" : "NG";
  355. }, isVision: false, cancellationToken);
  356. callback?.Invoke($"Record,{response}");
  357. break;
  358. case "RecordQuery":
  359. if (commandParams.Length < 1)
  360. {
  361. callback?.Invoke("InvalidParameters");
  362. return;
  363. }
  364. response = await TrackExecutionAsync(async ct =>
  365. {
  366. int recordCount = await GetCurrentProductionCountAsync(commandParams[0].Trim(), ct);
  367. return recordCount.ToString();
  368. }, isVision: false, cancellationToken);
  369. callback?.Invoke($"RecordQuery,{response}");
  370. break;
  371. case "RecordReset":
  372. if (commandParams.Length < 1)
  373. {
  374. callback?.Invoke("InvalidParameters");
  375. return;
  376. }
  377. response = await TrackExecutionAsync(async ct =>
  378. {
  379. bool recordResetResult = await ResetProductionCountAsync(commandParams[0].Trim(), ct);
  380. return recordResetResult ? "OK" : "NG";
  381. }, isVision: false, cancellationToken);
  382. callback?.Invoke($"RecordReset,{response}");
  383. break;
  384. case "Err":
  385. if (commandParams.Length < 2)
  386. {
  387. callback?.Invoke("InvalidParameters");
  388. return;
  389. }
  390. response = await TrackExecutionAsync(async ct =>
  391. {
  392. bool errResult = await CreateAlarmRecordAsync(commandParams[0].Trim(), commandParams[1].Trim(), ct);
  393. return errResult ? "OK" : "NG";
  394. }, isVision: false, cancellationToken);
  395. callback?.Invoke($"Err,{response}");
  396. break;
  397. case "Info":
  398. if (commandParams.Length < 1)
  399. {
  400. callback?.Invoke("InvalidParameters");
  401. return;
  402. }
  403. response = await TrackExecutionAsync(async ct =>
  404. {
  405. bool infoResult = await CreateOperationLogAsync(commandParams[0].Trim(), ct);
  406. return infoResult ? "OK" : "NG";
  407. }, isVision: false, cancellationToken);
  408. callback?.Invoke($"Info,{response}");
  409. break;
  410. case "GetGlobalParam":
  411. if (commandParams.Length == 1)
  412. {
  413. response = await TrackExecutionAsync(async ct =>
  414. {
  415. return await GetGlobalParameterAsync(int.Parse(commandParams[0]), -1, ct);
  416. }, isVision: false, cancellationToken);
  417. if (string.IsNullOrEmpty(response))
  418. {
  419. callback?.Invoke("GetGlobalParam,NG");
  420. }
  421. else
  422. {
  423. callback?.Invoke($"GetGlobalParam,{response}");
  424. }
  425. break;
  426. }
  427. else if (commandParams.Length == 2)
  428. {
  429. response = await TrackExecutionAsync(async ct =>
  430. {
  431. return await GetGlobalParameterAsync(int.Parse(commandParams[0]), int.Parse(commandParams[1]), ct);
  432. }, isVision: false, cancellationToken);
  433. if (string.IsNullOrEmpty(response))
  434. {
  435. callback?.Invoke("GetGlobalParam,NG");
  436. }
  437. else
  438. {
  439. callback?.Invoke($"GetGlobalParam,{response}");
  440. }
  441. break;
  442. }
  443. else
  444. {
  445. callback?.Invoke("InvalidParameters");
  446. return;
  447. }
  448. case "GetSpeed":
  449. response = await TrackExecutionAsync(async ct =>
  450. {
  451. return await GetOperationSpeedAsync(ct);
  452. }, isVision: false, cancellationToken);
  453. if (string.IsNullOrEmpty(response))
  454. {
  455. callback?.Invoke("GetSpeed,NG");
  456. return;
  457. }
  458. else
  459. callback?.Invoke($"GetSpeed,{response}");
  460. break;
  461. case "GetToolParam":
  462. if (commandParams.Length < 2)
  463. {
  464. callback?.Invoke("InvalidParameters");
  465. return;
  466. }
  467. response = await TrackExecutionAsync(async ct =>
  468. {
  469. return await GetToolParamAsync(commandParams[0], int.Parse(commandParams[1]), ct);
  470. }, isVision: false, cancellationToken);
  471. if (string.IsNullOrEmpty(response))
  472. {
  473. callback?.Invoke("GetToolParam,NG");
  474. return;
  475. }
  476. else
  477. callback?.Invoke($"GetToolParam,{response}");
  478. break;
  479. case "GetProcedureParam":
  480. if (commandParams.Length < 1)
  481. {
  482. callback?.Invoke("InvalidParameters");
  483. return;
  484. }
  485. response = await TrackExecutionAsync(async ct =>
  486. {
  487. return await GetProcessParamAsync(commandParams[0], ct);
  488. }, isVision: false, cancellationToken);
  489. if (string.IsNullOrEmpty(response))
  490. {
  491. callback?.Invoke("GetProcedureParam,NG");
  492. return;
  493. }
  494. else
  495. callback?.Invoke($"GetProcedureParam,{response}");
  496. break;
  497. case "StartClearMaterial":
  498. if (commandParams.Length < 1)
  499. {
  500. callback?.Invoke("InvalidParameters");
  501. return;
  502. }
  503. response = await TrackExecutionAsync(async ct =>
  504. {
  505. bool startClearResult = await ExecuteClearMaterialTaskAsync(int.Parse(commandParams[0]), ct);
  506. return startClearResult ? "OK" : "NG";
  507. }, isVision: false, cancellationToken);
  508. callback?.Invoke($"StartClearMaterial,{response}");
  509. break;
  510. case "StopClearMaterial":
  511. if (commandParams.Length < 1)
  512. {
  513. callback?.Invoke("InvalidParameters");
  514. return;
  515. }
  516. response = await TrackExecutionAsync(async ct =>
  517. {
  518. bool stopClearResult = await StopClearMaterialTaskAsync(int.Parse(commandParams[0]), ct);
  519. return stopClearResult ? "OK" : "NG";
  520. }, isVision: false, cancellationToken);
  521. callback?.Invoke($"StopClearMaterial,{response}");
  522. break;
  523. case "RobotIsDebugMode":
  524. if (commandParams.Length < 1)
  525. {
  526. callback?.Invoke("InvalidParameters");
  527. return;
  528. }
  529. response = await TrackExecutionAsync(async ct =>
  530. {
  531. bool isDebugMode = await IsRobotInDebugModeAsync(int.Parse(commandParams[0]), ct);
  532. return isDebugMode ? "1" : "0";
  533. }, isVision: false, cancellationToken);
  534. callback?.Invoke($"RobotIsDebugMode,{response}");
  535. break;
  536. default:
  537. var currentProduct = _productService.GetCurrentProduct();
  538. if (currentProduct == null) return;
  539. var procedure = currentProduct.CameraProcedures
  540. .SelectMany(cp => cp.ProcedureModels)
  541. .FirstOrDefault(p => p.TriggerCommand == triggerCommand);
  542. if (procedure == null) return;
  543. var visionResult = await TrackExecutionAsync(async ct =>
  544. {
  545. var r = await ExecuteVisionTaskAsync(procedure, commandParams, ct);
  546. return Tuple.Create(r.IsSucceed, r.Response);
  547. }, isVision: true, cancellationToken);
  548. if (visionResult.Item1)
  549. {
  550. foreach (var item in visionResult.Item2)
  551. {
  552. callback?.Invoke($"{triggerCommand},OK,{item}");
  553. }
  554. }
  555. else
  556. {
  557. string msg = string.Empty;
  558. if (visionResult.Item2 != null && visionResult.Item2.Length > 0)
  559. {
  560. msg = visionResult.Item2[0];
  561. }
  562. callback?.Invoke($"{triggerCommand},NG,{msg}");
  563. }
  564. break;
  565. }
  566. }
  567. /// <summary>
  568. /// 根据产品名称或编号加载并设置当前产品。
  569. /// 若传入字符串可解析为 int,则先按编号查找产品,否则按名称查找。
  570. /// </summary>
  571. /// <param name="productName">产品名称或编号字符串</param>
  572. /// <param name="cancellationToken">取消令牌</param>
  573. /// <returns>加载成功返回 true,否则 false</returns>
  574. public async Task<bool> LoadProductAsync(string productName, CancellationToken cancellationToken)
  575. {
  576. bool exists = _productService.ContainsProductByName(productName);
  577. if (exists)
  578. {
  579. var product = _productService.GetAllProducts().FirstOrDefault(p => p.Name == productName);
  580. await _productService.LoadProductAsync(product.ID);
  581. _productService.SetCurrentProduct(product.ID);
  582. return true;
  583. }
  584. if (int.TryParse(productName, out int productNumber))
  585. {
  586. var product = _productService.GetAllProducts().FirstOrDefault(p => p.NumberCode == productNumber);
  587. if (product != null)
  588. {
  589. await _productService.LoadProductAsync(product.ID);
  590. _productService.SetCurrentProduct(product.ID);
  591. return true;
  592. }
  593. }
  594. return false;
  595. }
  596. /// <summary>
  597. /// 通过产品编号获取产品名称。
  598. /// </summary>
  599. public Task<string> GetProductNameByNumberAsync(int productNumber, CancellationToken cancellationToken)
  600. {
  601. var product = _productService.GetAllProducts().FirstOrDefault(p => p.NumberCode == productNumber);
  602. if (product != null)
  603. {
  604. return Task.FromResult(product.Name);
  605. }
  606. return Task.FromResult(string.Empty);
  607. }
  608. /// <summary>
  609. /// 获取当前被设置为活动的产品名称。如果没有则返回空字符串。
  610. /// </summary>
  611. public Task<string> GetCurrentProductNameAsync(CancellationToken cancellationToken)
  612. {
  613. var currentProduct = _productService.GetCurrentProduct();
  614. if (currentProduct != null)
  615. {
  616. return Task.FromResult(currentProduct.Name);
  617. }
  618. return Task.FromResult(string.Empty);
  619. }
  620. /// <summary>
  621. /// 通过产品名称获取其编号(NumberCode)。找不到则返回 -1。
  622. /// </summary>
  623. public Task<int> GetProductNumberByNameAsync(string productName, CancellationToken cancellationToken)
  624. {
  625. bool exists = _productService.ContainsProductByName(productName);
  626. if (exists)
  627. {
  628. var product = _productService.GetAllProducts().FirstOrDefault(p => p.Name == productName);
  629. return Task.FromResult(product.NumberCode);
  630. }
  631. return Task.FromResult(-1);
  632. }
  633. /// <summary>
  634. /// 获取当前产品编号(NumberCode)。找不到则返回 -1。
  635. /// </summary>
  636. public Task<int> GetCurrentProductNumberAsync(CancellationToken cancellationToken)
  637. {
  638. var currentProduct = _productService.GetCurrentProduct();
  639. if (currentProduct != null)
  640. {
  641. return Task.FromResult(currentProduct.NumberCode);
  642. }
  643. return Task.FromResult(-1);
  644. }
  645. /// <summary>
  646. /// 根据机器人编号和点位编号获取点位信息(字符串表示),查找逻辑基于当前产品的 RobotPoint 配置。
  647. /// </summary>
  648. public Task<string> GetRobotPointInfoAsync(int robotNumber, int pointNumber, CancellationToken cancellationToken)
  649. {
  650. var currentProduct = _productService.GetCurrentProduct();
  651. if (currentProduct == null) return Task.FromResult(string.Empty);
  652. var robot = _configService.GetAllRobots().FirstOrDefault(r => r.RobotNo == robotNumber);
  653. if (robot == null) return Task.FromResult(string.Empty);
  654. var robotPoint = currentProduct.RobotPoint.Robots.FirstOrDefault(rp => rp.Id == robot.Id);
  655. if (robotPoint == null) return Task.FromResult(string.Empty);
  656. var point = robotPoint.Points.FirstOrDefault(p => p.Number == pointNumber);
  657. if (point == null) return Task.FromResult(string.Empty);
  658. return Task.FromResult(point.ToString());
  659. }
  660. /// <summary>
  661. /// 通过机器人编号、托盘编号和点编号获取托盘点位信息,返回格式化字符串。
  662. /// </summary>
  663. public Task<string> GetRobotPalletPointInfoAsync(int robotNumber, int palletNumber, int pointNumber, CancellationToken cancellationToken)
  664. {
  665. var currentProduct = _productService.GetCurrentProduct();
  666. if (currentProduct == null) return Task.FromResult(string.Empty);
  667. var robot = _configService.GetAllRobots().FirstOrDefault(r => r.RobotNo == robotNumber);
  668. if (robot == null) return Task.FromResult(string.Empty);
  669. var robotPoint = currentProduct.RobotPoint.Robots.FirstOrDefault(rp => rp.Id == robot.Id);
  670. if (robotPoint == null) return Task.FromResult(string.Empty);
  671. var pallet = robotPoint.Pallets.FirstOrDefault(p => p.PalletNo == palletNumber);
  672. if (pallet == null) return Task.FromResult(string.Empty);
  673. PalletTool palletTool = new PalletTool(pallet);
  674. if (pointNumber > palletTool.Points.Length || pointNumber < 1) return Task.FromResult(string.Empty);
  675. var pos = palletTool.Points[pointNumber - 1];
  676. string response = $"{robotNumber},{palletNumber},{palletTool.Points.Length},{pos.Number},{pos.X:F3},{pos.Y:F3},{pos.Z:F3},{pos.U:F3},{pos.V:F3},{pos.W:F3},{pos.Local},{pos.Tool},{pos.Hand}";
  677. return Task.FromResult(response);
  678. }
  679. /// <summary>
  680. /// 开始节拍计时。返回是否成功(始终 true)。
  681. /// 会启动后台定时任务并周期性触发 CycleTimingTicked 事件。
  682. /// </summary>
  683. public Task<bool> StartCycleTimingAsync(CancellationToken cancellationToken)
  684. {
  685. if (_cycleTimingCts != null)
  686. {
  687. _cycleTimingCts.Cancel();
  688. _cycleTimingCts.Dispose();
  689. }
  690. _cycleTimingCts = new CancellationTokenSource();
  691. var token = _cycleTimingCts.Token;
  692. Task.Run(async () =>
  693. {
  694. var startTime = DateTime.UtcNow;
  695. while (!token.IsCancellationRequested)
  696. {
  697. var elapsed = DateTime.UtcNow - startTime;
  698. OnCycleTimingTicked(elapsed);
  699. await Task.Delay(100, token);
  700. }
  701. }, token);
  702. return Task.FromResult(true);
  703. }
  704. /// <summary>
  705. /// 停止节拍计时并清理取消令牌。
  706. /// </summary>
  707. public Task<bool> StopCycleTimingAsync(CancellationToken cancellationToken)
  708. {
  709. if (_cycleTimingCts != null)
  710. {
  711. _cycleTimingCts.Cancel();
  712. _cycleTimingCts.Dispose();
  713. _cycleTimingCts = null;
  714. }
  715. return Task.FromResult(true);
  716. }
  717. /// <summary>
  718. /// 新增一条生产计数记录,数量固定为 1。
  719. /// </summary>
  720. public Task<bool> CreateProductionCountAsync(string countItem, CancellationToken cancellationToken)
  721. {
  722. _systemDatabaseService.RecordProductionAsync(new ProductionRecord
  723. {
  724. Category = countItem,
  725. ProductName = _productService.GetCurrentProduct()?.Name ?? "Unknown",
  726. Quantity = 1,
  727. Timestamp = DateTime.UtcNow
  728. });
  729. return Task.FromResult(true);
  730. }
  731. /// <summary>
  732. /// 查询当前产品在指定分类下的累计产量。
  733. /// </summary>
  734. public async Task<int> GetCurrentProductionCountAsync(string countItem, CancellationToken cancellationToken)
  735. {
  736. var currentProduct = _productService.GetCurrentProduct();
  737. if (currentProduct == null) return 0;
  738. var records = _systemDatabaseService.GetProductCategoriesAsync(currentProduct.Name);
  739. int totalCount = await _systemDatabaseService.GetTotalProductionAsync(currentProduct.Name, new List<string> { countItem });
  740. return totalCount;
  741. }
  742. /// <summary>
  743. /// 重置当前产品的生产统计(通过系统 DB 服务)。
  744. /// </summary>
  745. public async Task<bool> ResetProductionCountAsync(string countItem, CancellationToken cancellationToken)
  746. {
  747. var currentProduct = _productService.GetCurrentProduct();
  748. if (currentProduct == null) return false;
  749. await _systemDatabaseService.ResetProductionAsync(currentProduct.Name);
  750. return true;
  751. }
  752. /// <summary>
  753. /// 记录一条报警信息到系统数据库,并通过事件发布错误级别的任务消息。
  754. /// </summary>
  755. public Task<bool> CreateAlarmRecordAsync(string alarmCode, string alarmDescription, CancellationToken cancellationToken)
  756. {
  757. SendTaskMessage(alarmDescription, MessageLevel.Error);
  758. _systemDatabaseService.RecordAlarmAsync(new AlarmRecord
  759. {
  760. Code = alarmCode,
  761. Message = alarmDescription,
  762. Source = "Unknown",
  763. Time = DateTime.UtcNow
  764. });
  765. return Task.FromResult(true);
  766. }
  767. /// <summary>
  768. /// 发布运行信息日志(仅消息推送,不持久化)。
  769. /// </summary>
  770. public Task<bool> CreateOperationLogAsync(string logMessage, CancellationToken cancellationToken)
  771. {
  772. SendTaskMessage(logMessage, MessageLevel.Info);
  773. return Task.FromResult(true);
  774. }
  775. /// <summary>
  776. /// 获取当前产品的全局参数,支持按索引(1-4)返回指定子项,或返回完整 ToString。
  777. /// </summary>
  778. public Task<string> GetGlobalParameterAsync(int parameterNumber, int itemIndex, CancellationToken cancellationToken)
  779. {
  780. var currentProduct = _productService.GetCurrentProduct();
  781. if (currentProduct == null) return Task.FromResult(string.Empty);
  782. if (currentProduct.GlobalParamListCollection == null) return Task.FromResult(string.Empty);
  783. var globalParam = currentProduct.GlobalParamListCollection.FirstOrDefault(p => p.Number == parameterNumber);
  784. if (globalParam == null) return Task.FromResult(string.Empty);
  785. string response = string.Empty;
  786. if (itemIndex == 1)
  787. {
  788. response = $"{globalParam.Number},{globalParam.Name},{globalParam.Param1}";
  789. }
  790. else if (itemIndex == 2)
  791. {
  792. response = $"{globalParam.Number},{globalParam.Name},{globalParam.Param2}";
  793. }
  794. else if (itemIndex == 3)
  795. {
  796. response = $"{globalParam.Number},{globalParam.Name},{globalParam.Param3}";
  797. }
  798. else if (itemIndex == 4)
  799. {
  800. response = $"{globalParam.Number},{globalParam.Name},{globalParam.Param4}";
  801. }
  802. else if (itemIndex == 5)
  803. {
  804. response = $"{globalParam.Number},{globalParam.Name},{globalParam.Param5}";
  805. }
  806. else
  807. {
  808. response = globalParam.ToString();
  809. }
  810. return Task.FromResult(response);
  811. }
  812. /// <summary>
  813. /// 返回当前产品的速度/加速度等运行参数的格式化字符串。
  814. /// </summary>
  815. public Task<string> GetOperationSpeedAsync(CancellationToken cancellationToken)
  816. {
  817. var currentProduct = _productService.GetCurrentProduct();
  818. if (currentProduct == null) return Task.FromResult(string.Empty);
  819. string response = $"{currentProduct.Speed},{currentProduct.Accel},{currentProduct.Speeds},{currentProduct.Accels},{Convert.ToInt16(currentProduct.Power)},{Convert.ToInt16(currentProduct.IsUserUpCamera)}";
  820. return Task.FromResult(response);
  821. }
  822. /// <summary>
  823. /// 获取某流程指定工具编号的工具参数(格式化字符串),找不到返回空字符串。
  824. /// </summary>
  825. public Task<string> GetToolParamAsync(string triggerCommand, int toolNumber, CancellationToken cancellationToken)
  826. {
  827. var currentProduct = _productService.GetCurrentProduct();
  828. if (currentProduct == null) return Task.FromResult(string.Empty);
  829. ProcedureModel procedure = currentProduct.CameraProcedures
  830. .SelectMany(cp => cp.ProcedureModels)
  831. .FirstOrDefault(p => p.TriggerCommand == triggerCommand);
  832. if (procedure == null || procedure.ToolInfo == null) return Task.FromResult(string.Empty);
  833. var tool = procedure.ToolInfo.FirstOrDefault(t => t.Number == toolNumber);
  834. if (tool == null) return Task.FromResult(string.Empty);
  835. if (tool.Tool == null) return Task.FromResult(string.Empty);
  836. string response = $"{tool.Tool.Number},{tool.Tool.X:F3},{tool.Tool.Y:F3},{tool.OffsetX:F3},{tool.OffsetY:F3},{tool.OffsetZ:F3},{tool.OffsetU:F3}";
  837. return Task.FromResult(response);
  838. }
  839. /// <summary>
  840. /// 获取流程参数(例如 WaitPhoto 与用户自定义参数等),以逗号分隔的字符串返回。
  841. /// </summary>
  842. public Task<string> GetProcessParamAsync(string triggerCommand, CancellationToken cancellationToken)
  843. {
  844. var currentProduct = _productService.GetCurrentProduct();
  845. if (currentProduct == null) return Task.FromResult(string.Empty);
  846. ProcedureModel procedure = currentProduct.CameraProcedures
  847. .SelectMany(cp => cp.ProcedureModels)
  848. .FirstOrDefault(p => p.TriggerCommand == triggerCommand);
  849. if (procedure == null || procedure.ToolInfo == null) return Task.FromResult(string.Empty);
  850. StringBuilder response = new StringBuilder();
  851. response.Append($"{procedure.WaitPhoto}");
  852. if (procedure.UserDefineParameters != null)
  853. {
  854. foreach (var param in procedure.UserDefineParameters)
  855. {
  856. response.Append("," + param.ToString());
  857. }
  858. }
  859. return Task.FromResult(response.ToString());
  860. }
  861. /// <summary>
  862. /// 执行指定编号的清料任务(异步)。流程:
  863. /// - 根据配置获取任务
  864. /// - 检查 Feeder 连接性
  865. /// - 使用专用 CancellationTokenSource 跟踪任务并支持停止
  866. /// - 循环执行开挡板、振动、关闭挡板等步骤,检查取消状态
  867. /// </summary>
  868. public async Task<bool> ExecuteClearMaterialTaskAsync(int taskNumber, CancellationToken cancellationToken)
  869. {
  870. var feederClearWork = _configService.GetClearanceTaskByNumber(taskNumber);
  871. if (feederClearWork == null)
  872. {
  873. return false;
  874. }
  875. IVoiceCoilMotorFeeder Feeder = _feederService.GetFeeder(feederClearWork.FeederId);
  876. if (!Feeder.IsConnected)
  877. {
  878. return false;
  879. }
  880. if (_clearMaterialCtsDict.ContainsKey(feederClearWork.TaskCode))
  881. {
  882. return false;
  883. }
  884. _clearMaterialCtsDict[feederClearWork.TaskCode] = new CancellationTokenSource();
  885. if (cancellationToken != null)
  886. {
  887. cancellationToken.Register(() =>
  888. {
  889. if (_clearMaterialCtsDict.ContainsKey(feederClearWork.TaskCode))
  890. {
  891. _clearMaterialCtsDict[feederClearWork.TaskCode].Cancel();
  892. }
  893. });
  894. }
  895. var token = _clearMaterialCtsDict[feederClearWork.TaskCode].Token;
  896. for (int i = 0; i < feederClearWork.ClearCount; i++)
  897. {
  898. await Feeder.OutputAsync((int)feederClearWork.BeforeOutput + 1, 0);
  899. await Task.Delay(200, token);
  900. if ((cancellationToken != null && cancellationToken.IsCancellationRequested) || (token != null && token.IsCancellationRequested))
  901. {
  902. await Feeder.StopOutputAsync();
  903. if (_clearMaterialCtsDict.ContainsKey(feederClearWork.TaskCode))
  904. {
  905. _clearMaterialCtsDict[feederClearWork.TaskCode].Cancel();
  906. _clearMaterialCtsDict.TryRemove(feederClearWork.TaskCode, out _);
  907. }
  908. return false;
  909. }
  910. for (int j = 0; j < feederClearWork.VibrationCount; j++)
  911. {
  912. await ExecuteFeederWorks(Feeder, feederClearWork.FeederWorks, token, true);
  913. if ((cancellationToken != null && cancellationToken.IsCancellationRequested) || (token != null && token.IsCancellationRequested))
  914. {
  915. await Feeder.StopOutputAsync();
  916. if (_clearMaterialCtsDict.ContainsKey(feederClearWork.TaskCode))
  917. {
  918. _clearMaterialCtsDict[feederClearWork.TaskCode].Cancel();
  919. _clearMaterialCtsDict.TryRemove(feederClearWork.TaskCode, out _);
  920. }
  921. return false;
  922. }
  923. if (!await Feeder.GetOutputStatusAsync())
  924. {
  925. await Feeder.OutputAsync((int)feederClearWork.BeforeOutput + 1, 0);
  926. }
  927. if ((cancellationToken != null && cancellationToken.IsCancellationRequested) || (token != null && token.IsCancellationRequested))
  928. {
  929. await Feeder.StopOutputAsync();
  930. if (_clearMaterialCtsDict.ContainsKey(feederClearWork.TaskCode))
  931. {
  932. _clearMaterialCtsDict[feederClearWork.TaskCode].Cancel();
  933. _clearMaterialCtsDict.TryRemove(feederClearWork.TaskCode, out _);
  934. }
  935. return false;
  936. }
  937. }
  938. if ((cancellationToken != null && cancellationToken.IsCancellationRequested) || (token != null && token.IsCancellationRequested))
  939. {
  940. await Feeder.StopOutputAsync();
  941. if (_clearMaterialCtsDict.ContainsKey(feederClearWork.TaskCode))
  942. {
  943. _clearMaterialCtsDict[feederClearWork.TaskCode].Cancel();
  944. _clearMaterialCtsDict.TryRemove(feederClearWork.TaskCode, out _);
  945. }
  946. return false;
  947. }
  948. await Feeder.StopOutputAsync();
  949. await Task.Delay(300, token);
  950. if ((cancellationToken != null && cancellationToken.IsCancellationRequested) || (token != null && token.IsCancellationRequested))
  951. {
  952. await Feeder.StopOutputAsync();
  953. if (_clearMaterialCtsDict.ContainsKey(feederClearWork.TaskCode))
  954. {
  955. _clearMaterialCtsDict[feederClearWork.TaskCode].Cancel();
  956. _clearMaterialCtsDict.TryRemove(feederClearWork.TaskCode, out _);
  957. }
  958. return false;
  959. }
  960. }
  961. await Feeder.StopOutputAsync();
  962. await Task.Delay(300, token);
  963. if ((cancellationToken != null && cancellationToken.IsCancellationRequested) || (token != null && token.IsCancellationRequested))
  964. {
  965. await Feeder.StopOutputAsync();
  966. if (_clearMaterialCtsDict.ContainsKey(feederClearWork.TaskCode))
  967. {
  968. _clearMaterialCtsDict[feederClearWork.TaskCode].Cancel();
  969. _clearMaterialCtsDict.TryRemove(feederClearWork.TaskCode, out _);
  970. }
  971. return false;
  972. }
  973. if (_clearMaterialCtsDict.ContainsKey(feederClearWork.TaskCode))
  974. {
  975. _clearMaterialCtsDict[feederClearWork.TaskCode].Cancel();
  976. _clearMaterialCtsDict.TryRemove(feederClearWork.TaskCode, out _);
  977. }
  978. return true;
  979. }
  980. /// <summary>
  981. /// 停止指定编号的清料任务(如果正在运行)。
  982. /// </summary>
  983. public Task<bool> StopClearMaterialTaskAsync(int taskNumber, CancellationToken cancellationToken)
  984. {
  985. var feederClearWork = _configService.GetClearanceTaskByNumber(taskNumber);
  986. if (feederClearWork == null)
  987. {
  988. return Task.FromResult(false);
  989. }
  990. if (_clearMaterialCtsDict.ContainsKey(feederClearWork.TaskCode))
  991. {
  992. _clearMaterialCtsDict[feederClearWork.TaskCode].Cancel();
  993. _clearMaterialCtsDict.TryRemove(feederClearWork.TaskCode, out _);
  994. }
  995. return Task.FromResult(true);
  996. }
  997. /// <summary>
  998. /// 判断指定编号的机器人是否处于调试模式。
  999. /// </summary>
  1000. public Task<bool> IsRobotInDebugModeAsync(int robotNumber, CancellationToken cancellationToken)
  1001. {
  1002. var robotInfo = _configService.GetAllRobots().FirstOrDefault(r => r.RobotNo == robotNumber);
  1003. if (robotInfo == null)
  1004. {
  1005. return Task.FromResult(false);
  1006. }
  1007. var robot = _robotService.GetRobot(robotInfo.Id);
  1008. if (robot != null) return Task.FromResult(robot.EnterDebugMode);
  1009. return Task.FromResult(false);
  1010. }
  1011. /// <summary>
  1012. /// 执行视觉任务的统一入口:
  1013. /// - 如果为产品局部脚本存在,则调用脚本
  1014. /// - 否则根据 procedure.FeederId 调用 Feeder 引导的视觉任务或普通视觉任务
  1015. /// 返回是否成功以及字符串数组形式的响应(用于发送多条结果)。
  1016. /// </summary>
  1017. public async Task<(bool IsSucceed, string[] Response)> ExecuteVisionTaskAsync(ProcedureModel procedure, string[] items, CancellationToken cancellationToken)
  1018. {
  1019. var currentProduct = _productService.GetCurrentProduct();
  1020. string scriptFilePath = FilePath.ProductsPath + "//" + currentProduct.Name + "//" + procedure.CameraName + "//" + procedure.Name + ".cs";
  1021. if (File.Exists(scriptFilePath))
  1022. {
  1023. try
  1024. {
  1025. string script = FileHelper.ReadFile(scriptFilePath);
  1026. SendTaskMessage(Lang.执行视觉处理脚本, MessageLevel.Debug);
  1027. Tuple<bool, string[]> rstn = null;
  1028. var rst1 = await ScriptHelper.ExecuteVisionScriptingAsync(script, _regionManager, _eventAggregator, _container, procedure, items, rst =>
  1029. {
  1030. rstn = rst;
  1031. });
  1032. if (!rst1.Item1)
  1033. {
  1034. SendTaskMessage(Lang.视觉处理脚本出错, MessageLevel.Error);
  1035. foreach (var item in rst1.Item2)
  1036. {
  1037. SendTaskMessage(item, MessageLevel.Error);
  1038. }
  1039. return (false, new string[] { "ScriptError" });
  1040. }
  1041. return (rstn.Item1, rstn.Item2);
  1042. }
  1043. catch (Exception ex)
  1044. {
  1045. SendTaskMessage(ex.Message, MessageLevel.Error);
  1046. LogHelper.WriteLogError("执行视觉处理脚本时出错!", ex);
  1047. return (false, new string[] { "ScriptException" });
  1048. }
  1049. }
  1050. else
  1051. {
  1052. IVoiceCoilMotorFeeder Feeder = null;
  1053. if (procedure.FeederId != Guid.Empty)
  1054. {
  1055. Feeder = _feederService.GetFeeder(procedure.FeederId);
  1056. return await ExecuteFeederVisionTaskAsync(Feeder, procedure, items, cancellationToken);
  1057. }
  1058. else
  1059. {
  1060. var result = await ExecuteNormalVisionTaskAsync(procedure, items, cancellationToken);
  1061. return (result.IsSucceed, new string[] { result.Response });
  1062. }
  1063. }
  1064. }
  1065. /// <summary>
  1066. /// 内部:触发节拍计时回调。
  1067. /// </summary>
  1068. private void OnCycleTimingTicked(TimeSpan elapsed)
  1069. {
  1070. CycleTimingTicked?.Invoke(this, elapsed);
  1071. }
  1072. /// <summary>
  1073. /// 发布任务消息到事件聚合器(通过 UI Dispatcher 保证线程安全)。
  1074. /// </summary>
  1075. private void SendTaskMessage(string msg, MessageLevel level)
  1076. {
  1077. App.Current.Dispatcher.Invoke(() =>
  1078. {
  1079. _eventAggregator.GetEvent<TaskMessageNotification>().Publish(new Models.MessageStruct() { Message = msg, level = level });
  1080. });
  1081. }
  1082. #region 执行视觉任务辅助方法
  1083. /// <summary>
  1084. /// 执行 Feeder 引导的视觉任务。负责:
  1085. /// - 解析输入命令(是否先振动/先拍照、SetInputs)
  1086. /// - 在拍照前后执行对应的 Feeder 操作(开灯、振动、供料等)
  1087. /// - 多次尝试拍照并运行视觉工具,直到成功或达到失败次数上限
  1088. /// - 返回布尔成功标记及字符串数组形式的响应项
  1089. /// </summary>
  1090. public async Task<(bool IsSucceed, string[] Response)> ExecuteFeederVisionTaskAsync(IVoiceCoilMotorFeeder feeder, ProcedureModel procedure, string[] items, CancellationToken cancellationToken)
  1091. {
  1092. // 如果输入的items中是否包含Vibration和NoVibration,这两个分别对应是否先振动和是否先拍照
  1093. bool doVibrateFirst = items != null && items.Contains("VibrateFirst");
  1094. bool doCaptureFirst = items != null && items.Contains("CaptureFirst");
  1095. if (doVibrateFirst && doCaptureFirst) doCaptureFirst = false; // 如果两个都包含,则以振动优先为准
  1096. // 触发命令传入的输入终端
  1097. Dictionary<string, string> InputTerminal = null;
  1098. // 解析触发命令传入的输入终端参数
  1099. //判断传入参数中是否存在“SetInputs”
  1100. if (items != null && items.Length > 1 && items[0] == "SetInputs")
  1101. {
  1102. //依次从索引1开始解析参数,格式为 key=value,直到遇到非key=value格式的参数为止
  1103. InputTerminal = new Dictionary<string, string>();
  1104. for (int i = 1; i < items.Length; i++)
  1105. {
  1106. var pair = items[i].Split('=');
  1107. if (pair.Length == 2)
  1108. {
  1109. InputTerminal[pair[0]] = pair[1];
  1110. }
  1111. else
  1112. {
  1113. break; // 遇到非key=value格式的参数,停止解析
  1114. }
  1115. }
  1116. }
  1117. await SetLightBeforePhoto(procedure);
  1118. //执行Feeder相机拍照前的任务
  1119. await ExecuteFeederForPhotoBefore(feeder, procedure, doVibrateFirst, doCaptureFirst, cancellationToken);
  1120. // 如果遇到取消令牌,则直接返回失败
  1121. if (cancellationToken != null && cancellationToken.IsCancellationRequested)
  1122. {
  1123. await feeder.CloseLightAsync();
  1124. return (false, new string[] { "FeederTaskCancelled" });
  1125. }
  1126. DateTime nowtime = DateTime.Now;
  1127. //拍照失败时,需要多次拍照
  1128. for (int i = 0; i < procedure.FeederFailLimit; i++)
  1129. {
  1130. if (cancellationToken != null && cancellationToken.IsCancellationRequested)
  1131. {
  1132. await feeder.CloseLightAsync();
  1133. await TurnOffLightAfterPhoto(procedure);
  1134. return (false, new string[] { "VisionTaskCancelled" });
  1135. }
  1136. SendTaskMessage(Lang.开始执行视觉流程.Replace("{0}", $"{i + 1}").Replace("{1}", procedure.Name), MessageLevel.Info);
  1137. // 1. 执行相机拍照并运行视觉工具
  1138. bool visionSucceed = ExecutePhoto(procedure, InputTerminal, out CogToolBlockTerminalCollection outputCollection);
  1139. if (!visionSucceed)
  1140. {
  1141. SendTaskMessage(Lang.视觉任务执行失败, MessageLevel.Error);
  1142. continue;
  1143. }
  1144. if (!outputCollection.Contains("Found"))
  1145. {
  1146. SendTaskMessage(Lang.未找到视觉输出结果, MessageLevel.Error);
  1147. return (false, new string[] { "NoFoundOutput" });
  1148. }
  1149. procedure.LastBlobArea = Convert.ToDouble(outputCollection["BlobTotalArea"].Value);
  1150. // 2. 获取视觉输出结果
  1151. bool Found = (bool)(outputCollection["Found"].Value);
  1152. if (!Found)
  1153. {
  1154. SendTaskMessage(Lang.拍照NG, MessageLevel.Debug);
  1155. await TurnOffLightAfterPhoto(procedure);
  1156. await ExecuteFeederForPhotoLater(feeder, procedure, cancellationToken);
  1157. continue;
  1158. }
  1159. SendTaskMessage(Lang.拍照OK, MessageLevel.Debug);
  1160. if (procedure.ProcedureOutputs == null)
  1161. {
  1162. SendTaskMessage(Lang.视觉流程未配置输出项, MessageLevel.Alarm);
  1163. return (false, new string[] { "NoOutputConfigured" });
  1164. }
  1165. // 3. 获取视觉输出结果
  1166. LogHelper.WriteLogInfo("开始获取视觉输出结果");
  1167. var (IsSucceed, ErrMsg, Output) = GetVisionOutput(procedure, outputCollection, null);
  1168. if (!IsSucceed)
  1169. {
  1170. SendTaskMessage(Lang.获取视觉输出结果失败, MessageLevel.Error);
  1171. return (false, new string[] { ErrMsg });
  1172. }
  1173. // 4. 组织返回结果
  1174. int outputPointCount = 0;//输出点的数量
  1175. List<double[]> currentPoints = new List<double[]>(); //点位数据
  1176. List<string> outputItems = new List<string>(); //多项输出结果集合
  1177. foreach (var output in procedure.ProcedureOutputs)
  1178. {
  1179. if (Output.ContainsKey(output.Name))
  1180. {
  1181. var (IsPoint, Value) = Output[output.Name];
  1182. if (IsPoint)
  1183. {
  1184. //Value是点位数据,类型:List<string[]>,string[]是一个点位,里面是X、Y,U等数据
  1185. //将所有点位数据和单个点位数据中的坐标之间都用逗号分隔,多个点位之间用逗号分隔
  1186. List<string[]> points = Value as List<string[]>;
  1187. List<string> allpoints = new List<string>();
  1188. for (int j = 0; j < points.Count; j++)
  1189. {
  1190. //如果当前流程开启了剔除重复点功能,则进行剔除
  1191. if (procedure.IsExcludeNearPoint && procedure.LastRunPoints != null && procedure.LastRunPoints.Count > 0)
  1192. {
  1193. //当前点的坐标数据
  1194. double px = double.Parse(points[j][0]);
  1195. double py = double.Parse(points[j][1]);
  1196. double pu = double.Parse(points[j][2]);
  1197. //检查当前点是否与上次运行的点过于接近
  1198. //使用linq来检测上一次的点位集合中,是否存在某个点与当前点的x,y,u的差值小于设定的阈值
  1199. bool isNear = procedure.LastRunPoints.Any(lp =>
  1200. Math.Abs(lp[0] - px) < procedure.ExcludeNearPointThreshol &&
  1201. Math.Abs(lp[1] - py) < procedure.ExcludeNearPointThreshol &&
  1202. Math.Abs(lp[2] - pu) < procedure.ExcludeNearPointThreshol);
  1203. if (isNear) continue; //如果存在接近的点,则跳过当前点,不进行添加
  1204. }
  1205. //单个点位内坐标之间逗号分隔
  1206. allpoints.Add(string.Join(",", points[j]));
  1207. //如果输出模式是AllAtOnce或者BatchedUntilTerminator,则需要检查是否达到最大点位数量限制
  1208. if (procedure.OutputPointMode == OutputPointMode.AllAtOnce || procedure.OutputPointMode == OutputPointMode.BatchedUntilTerminator)
  1209. {
  1210. //如果当前总点位数量已经达到最大限制,则停止添加更多点位
  1211. if (allpoints.Count >= procedure.OutputPointCountMax)
  1212. {
  1213. break;
  1214. }
  1215. }
  1216. currentPoints.Add(new double[] { double.Parse(points[j][0]), double.Parse(points[j][1]), double.Parse(points[j][2]) });
  1217. }
  1218. //多个点位之间逗号分隔
  1219. string pointstr = allpoints.Count + "," + string.Join(",", allpoints);
  1220. if (procedure.OutputPointMode == OutputPointMode.UntilTerminator || procedure.OutputPointMode == OutputPointMode.BatchedUntilTerminator)
  1221. {
  1222. outputItems.AddRange(allpoints);
  1223. }
  1224. else
  1225. {
  1226. outputItems.Add(pointstr);
  1227. }
  1228. outputPointCount += allpoints.Count;
  1229. }
  1230. else
  1231. {
  1232. string itemstr = Value != null ? Value.ToString() : string.Empty;
  1233. outputItems.Add(itemstr);
  1234. }
  1235. }
  1236. }
  1237. procedure.LastRunPoints = currentPoints;
  1238. //关闭Feeder灯光
  1239. if (feeder.IsConnected)
  1240. {
  1241. await feeder.CloseLightAsync();
  1242. }
  1243. await TurnOffLightAfterPhoto(procedure);
  1244. //如果输出模式是AllAtOnce或者BatchedUntilTerminator,则分次发送数据
  1245. if (procedure.OutputPointMode == OutputPointMode.UntilTerminator || procedure.OutputPointMode == OutputPointMode.BatchedUntilTerminator)
  1246. {
  1247. //将outputItems按照procedure.OutputSeparator进行拼接,得到最终返回结果
  1248. string finalResponse = string.Join(procedure.OutputSeparator, outputItems);
  1249. return (true, outputItems.ToArray());
  1250. }
  1251. else
  1252. {
  1253. //否则,一次发送所有数据
  1254. //将outputItems按照procedure.OutputSeparator进行拼接,得到最终返回结果
  1255. string finalResponse = string.Join(procedure.OutputSeparator, outputItems);
  1256. return (true, new string[] { finalResponse });
  1257. }
  1258. }
  1259. //关闭Feeder灯光
  1260. if (feeder.IsConnected)
  1261. {
  1262. await feeder.CloseLightAsync();
  1263. }
  1264. await TurnOffLightAfterPhoto(procedure);
  1265. SendTaskMessage(Lang.多次拍照失败, MessageLevel.Alarm);
  1266. return (false, new string[] { "VisionFailed" });
  1267. }
  1268. /// <summary>
  1269. /// 执行非 Feeder 引导的普通视觉任务,返回单字符串响应。
  1270. /// </summary>
  1271. public async Task<(bool IsSucceed, string Response)> ExecuteNormalVisionTaskAsync(ProcedureModel procedure, string[] items, CancellationToken cancellationToken)
  1272. {
  1273. // 开始执行前的时间点
  1274. DateTime startTime = DateTime.Now;
  1275. try
  1276. {
  1277. await SetLightBeforePhoto(procedure);
  1278. // 触发命令传入的输入终端
  1279. Dictionary<string, string> InputTerminal = null;
  1280. // 解析触发命令传入的输入终端参数
  1281. //判断传入参数中是否存在“SetInputs”
  1282. if (items != null && items.Length > 1 && items[0] == "SetInputs")
  1283. {
  1284. InputTerminal = items.Skip(1)
  1285. .Select(x => x.Split('='))
  1286. .Where(y => y.Length == 2)
  1287. .ToDictionary(z => z[0], z => z[1]);
  1288. }
  1289. // 机器人当前坐标
  1290. double[] currentpos = null;
  1291. // 判断传入参数长度是否3,并且是否都是double
  1292. if (items != null && items.Length >= 3 && double.TryParse(items[0], out double _x) && double.TryParse(items[1], out double _y) && double.TryParse(items[2], out double _u))
  1293. {
  1294. currentpos = new double[] { _x, _y, _u };
  1295. }
  1296. //拍照失败时,需要多次拍照
  1297. for (int i = 0; i < procedure.FeederFailLimit; i++)
  1298. {
  1299. if (cancellationToken != null && cancellationToken.IsCancellationRequested)
  1300. {
  1301. return (false, "VisionTaskCancelled");
  1302. }
  1303. // 1. 执行相机拍照并运行视觉工具
  1304. LogHelper.WriteLogInfo("开始执行相机拍照并运行视觉工具");
  1305. bool visionSucceed = ExecutePhoto(procedure, InputTerminal, out CogToolBlockTerminalCollection outputCollection);
  1306. if (!visionSucceed)
  1307. {
  1308. SendTaskMessage(Lang.视觉任务执行失败, MessageLevel.Error);
  1309. continue;
  1310. }
  1311. if (!outputCollection.Contains("Found"))
  1312. {
  1313. SendTaskMessage(Lang.未找到视觉输出结果, MessageLevel.Error);
  1314. return (false, "NoFoundOutput");
  1315. }
  1316. bool Found = (bool)(outputCollection["Found"].Value);
  1317. if (!Found)
  1318. {
  1319. SendTaskMessage(Lang.拍照NG, MessageLevel.Debug);
  1320. continue;
  1321. }
  1322. SendTaskMessage(Lang.拍照OK, MessageLevel.Debug);
  1323. // 2. 获取视觉输出结果
  1324. LogHelper.WriteLogInfo("开始获取视觉输出结果");
  1325. var (IsSucceed, ErrMsg, Output) = GetVisionOutput(procedure, outputCollection, currentpos);
  1326. if (!IsSucceed)
  1327. {
  1328. SendTaskMessage(Lang.获取视觉输出结果失败, MessageLevel.Error);
  1329. return (false, ErrMsg);
  1330. }
  1331. // 3. 组织返回结果
  1332. List<string> outputItems = new List<string>(); //多项输出结果集合
  1333. foreach (var output in procedure.ProcedureOutputs)
  1334. {
  1335. if (Output.ContainsKey(output.Name))
  1336. {
  1337. var (IsPoint, Value) = Output[output.Name];
  1338. if (IsPoint)
  1339. {
  1340. List<string[]> points = Value as List<string[]>;
  1341. List<string> allpoints = new List<string>();
  1342. for (int j = 0; j < points.Count; j++)
  1343. {
  1344. allpoints.Add(string.Join(",", points[j]));
  1345. }
  1346. //多个点位之间逗号分隔
  1347. string pointstr = allpoints.Count + "," + string.Join(",", allpoints);
  1348. outputItems.Add(pointstr);
  1349. }
  1350. else
  1351. {
  1352. string itemstr = Value != null ? Value.ToString() : string.Empty;
  1353. outputItems.Add(itemstr);
  1354. }
  1355. }
  1356. }
  1357. //将outputItems按照procedure.OutputSeparator进行拼接,得到最终返回结果
  1358. string finalResponse = string.Join(procedure.OutputSeparator, outputItems);
  1359. return (true, finalResponse);
  1360. }
  1361. return (false, "VisionFailed");
  1362. }
  1363. catch (Exception ex)
  1364. {
  1365. SendTaskMessage(ex.Message, MessageLevel.Error);
  1366. LogHelper.WriteLogError("执行普通视觉任务时出错!", ex);
  1367. return (false, "Exception");
  1368. }
  1369. finally
  1370. {
  1371. await TurnOffLightAfterPhoto(procedure);
  1372. }
  1373. }
  1374. /// <summary>
  1375. /// 执行翻转相机拍照流程运行
  1376. /// </summary>
  1377. /// <param name="procedure"></param>
  1378. /// <param name="outputCollection"></param>
  1379. /// <returns></returns>
  1380. public bool ExecutePhoto(ProcedureModel procedure, out CogToolBlockTerminalCollection outputCollection)
  1381. {
  1382. try
  1383. {
  1384. //SetLightBeforePhoto(procedure);
  1385. // 1. 采集图像
  1386. var camera = _cameraService.GetCamera(procedure.CameraId);
  1387. bool succed = camera.SetExposureTime(procedure.ExposureTime);
  1388. if (!succed)
  1389. {
  1390. SendTaskMessage("相机曝光设置失败", MessageLevel.Error);
  1391. }
  1392. succed = camera.SetGain(procedure.Gain);
  1393. if (!succed)
  1394. {
  1395. SendTaskMessage("相机增益设置失败", MessageLevel.Error);
  1396. }
  1397. DateTime nowtime = DateTime.Now;
  1398. LogHelper.WriteLogInfo("开始采集图像");
  1399. var image = camera.Grab();
  1400. if (image == null)
  1401. {
  1402. SendTaskMessage(Lang.图像采集失败, MessageLevel.Error);
  1403. outputCollection = null;
  1404. return false;
  1405. }
  1406. procedure.ToolBlock.Inputs["InputImage"].Value = image;
  1407. LogHelper.WriteLogInfo(string.Format("采集图像完成用时0ms", (DateTime.Now - nowtime).Milliseconds));
  1408. // 3. 运行视觉工具
  1409. LogHelper.WriteLogInfo("开始运行视觉工具");
  1410. procedure.ToolBlock.Run(); //运行ToolBlock
  1411. if (procedure.ToolBlock.RunStatus.Result == CogToolResultConstants.Accept)
  1412. {
  1413. SendTaskMessage(Lang.视觉流程执行耗时.Replace("{0}", procedure.Name).Replace("{1}", $"{procedure.ToolBlock.RunStatus.ProcessingTime:F1}"), MessageLevel.Info);
  1414. outputCollection = procedure.ToolBlock.Outputs; //获取输出终端集合
  1415. DatabaseHelper.AddCameraRecords(_productService.GetCurrentProduct().Name, procedure.Name, outputCollection);
  1416. ICogRecord record = null;
  1417. foreach (CogToolBlockTerminal item in outputCollection)
  1418. {
  1419. if (item.Value is ICogRecord)
  1420. record = item.Value as ICogRecord;
  1421. }
  1422. bool Found = (bool)(outputCollection["Found"].Value);
  1423. //获取图片存储的图片文件名
  1424. string imgName = string.Empty;
  1425. if (procedure.IsSaveImage && !string.IsNullOrEmpty(procedure.ImageFileNameFormat))
  1426. {
  1427. // 创建模板,使用 {变量名:格式} 语法
  1428. var template = new FileNameTemplate(procedure.ImageFileNameFormat);
  1429. // 注册变量
  1430. template.RegisterVariable("ProductSN", () => _productService.CurrentProductCode);
  1431. template.RegisterVariable("CameraName", () => procedure.CameraName);
  1432. template.RegisterVariable("ShotCount", () => 1);
  1433. template.RegisterVariable("Result", () => Found ? "OK" : "NG");
  1434. template.RegisterVariable("DateTime", () => DateTime.Now);
  1435. // 生成文件名
  1436. imgName = template.Generate();
  1437. }
  1438. _eventAggregator.GetEvent<RenderUpdateNotification>().Publish(new ShowRender()
  1439. {
  1440. Id = procedure.Id,
  1441. DisplayName = procedure.DisplayName,
  1442. //Image = (ICogImage)procedure.ToolBlock.Outputs["OriImage"].Value,
  1443. //Image = (ICogImage)procedure.ToolBlock.Inputs["InputImage"].Value,
  1444. Image = image,
  1445. Graphic = outputCollection["Graphic"].Value as CogGraphicCollection,
  1446. Record = record,
  1447. Result = Found,
  1448. IsShow = true,
  1449. IsSaveImage = procedure.IsSaveImage,
  1450. SaveImageModel = procedure.SaveImageModel,
  1451. SaveImagePathModel = procedure.SaveImagePathModel,
  1452. SavePath = procedure.SavePath,
  1453. IsCompress = procedure.IsCompress,
  1454. ProceductName = procedure.Name,
  1455. ImageFileName = imgName,
  1456. Is3DModel = true
  1457. });
  1458. return true;
  1459. }
  1460. else
  1461. {
  1462. SendTaskMessage(Lang.视觉流程执行出错耗时.Replace("{0}", procedure.Name).Replace("{1}", $"{procedure.ToolBlock.RunStatus.ProcessingTime:F1}"), MessageLevel.Error);
  1463. SendTaskMessage(procedure.ToolBlock.RunStatus.Message, MessageLevel.Error);
  1464. outputCollection = null;
  1465. //获取图片存储的图片文件名
  1466. string imgName = string.Empty;
  1467. if (procedure.IsSaveImage && !string.IsNullOrEmpty(procedure.ImageFileNameFormat))
  1468. {
  1469. // 创建模板,使用 {变量名:格式} 语法
  1470. var template = new FileNameTemplate(procedure.ImageFileNameFormat);
  1471. // 注册变量
  1472. template.RegisterVariable("ProductSN", () => _productService.CurrentProductCode);
  1473. template.RegisterVariable("CameraName", () => procedure.CameraName);
  1474. template.RegisterVariable("ShotCount", () => 1);
  1475. template.RegisterVariable("Result", () => "NG");
  1476. template.RegisterVariable("DateTime", () => DateTime.Now);
  1477. // 生成文件名
  1478. imgName = template.Generate();
  1479. }
  1480. _eventAggregator.GetEvent<RenderUpdateNotification>().Publish(new ShowRender()
  1481. {
  1482. Id = procedure.Id,
  1483. DisplayName = procedure.DisplayName,
  1484. //Image = (ICogImage)procedure.ToolBlock.Outputs["OriImage"].Value,
  1485. //Image = (ICogImage)procedure.ToolBlock.Inputs["InputImage"].Value,
  1486. Image = image,
  1487. Graphic = new CogGraphicCollection(),
  1488. Result = false,
  1489. IsShow = true,
  1490. IsSaveImage = procedure.IsSaveImage,
  1491. SaveImageModel = procedure.SaveImageModel,
  1492. SaveImagePathModel = procedure.SaveImagePathModel,
  1493. SavePath = procedure.SavePath,
  1494. ProceductName = procedure.Name,
  1495. ImageFileName = imgName,
  1496. Is3DModel = true
  1497. });
  1498. return false;
  1499. }
  1500. }
  1501. catch (Exception ex)
  1502. {
  1503. SendTaskMessage(ex.Message, MessageLevel.Error);
  1504. LogHelper.WriteLogError("执行相机取图并执行视觉工具组时出错", ex);
  1505. outputCollection = null;
  1506. return false;
  1507. }
  1508. }
  1509. /// <summary>
  1510. /// 执行相机拍照并运行 ToolBlock,返回是否成功并通过 out 参数返回 Outputs。
  1511. /// 该方法会发布 RenderUpdateNotification 以更新 UI。
  1512. /// </summary>
  1513. public bool ExecutePhoto(ProcedureModel procedure, Dictionary<string, string> InputTerminal, out CogToolBlockTerminalCollection outputCollection)
  1514. {
  1515. try
  1516. {
  1517. // 1. 采集图像
  1518. var camera = _cameraService.GetCamera(procedure.CameraId);
  1519. bool succed = camera.SetExposureTime(procedure.ExposureTime);
  1520. if (!succed)
  1521. {
  1522. SendTaskMessage($"相机曝光设置失败!", MessageLevel.Error);
  1523. }
  1524. succed = camera.SetGain(procedure.Gain);
  1525. if (!succed)
  1526. {
  1527. SendTaskMessage($"相机增益设置失败!", MessageLevel.Error);
  1528. }
  1529. DateTime nowtime = DateTime.Now;
  1530. LogHelper.WriteLogInfo("开始采集图像");
  1531. //var image = camera.Grab();
  1532. var image = camera.Grab();
  1533. if (image == null)
  1534. {
  1535. SendTaskMessage(Lang.图像采集失败, MessageLevel.Error);
  1536. outputCollection = null;
  1537. return false;
  1538. }
  1539. procedure.ToolBlock.Inputs["InputImage"].Value = image;
  1540. LogHelper.WriteLogInfo($"采集图像完成;用时:{(DateTime.Now - nowtime).Milliseconds}ms");
  1541. // 2. 为ToolBlock传入其他输入终端
  1542. if (InputTerminal != null)
  1543. {
  1544. LogHelper.WriteLogInfo($"为ToolBlock传入输入终端");
  1545. foreach (var item in InputTerminal)
  1546. {
  1547. if (procedure.ToolBlock.Inputs.Contains(item.Key))
  1548. {
  1549. LogHelper.WriteLogInfo($"传入[{item.Key}]={item.Value}");
  1550. procedure.ToolBlock.Inputs[item.Key].Value = item.Value;
  1551. }
  1552. else
  1553. {
  1554. LogHelper.WriteLogInfo($"创建并传入[{item.Key}]={item.Value}");
  1555. procedure.ToolBlock.Inputs.Add(new CogToolBlockTerminal(item.Key, item.Value));
  1556. }
  1557. }
  1558. }
  1559. // 3. 运行视觉工具
  1560. LogHelper.WriteLogInfo("开始运行视觉工具");
  1561. procedure.ToolBlock.Run(); //运行ToolBlock
  1562. if (procedure.ToolBlock.RunStatus.Result == CogToolResultConstants.Accept)
  1563. {
  1564. SendTaskMessage(Lang.视觉流程执行耗时.Replace("{0}", procedure.Name).Replace("{1}", $"{procedure.ToolBlock.RunStatus.ProcessingTime:F1}"), MessageLevel.Info);
  1565. outputCollection = procedure.ToolBlock.Outputs; //获取输出终端集合
  1566. DatabaseHelper.AddCameraRecords(_productService.GetCurrentProduct().Name, procedure.Name, outputCollection);
  1567. ICogRecord record = null;
  1568. foreach (CogToolBlockTerminal item in outputCollection)
  1569. {
  1570. if (item.Value is ICogRecord)
  1571. record = item.Value as ICogRecord;
  1572. }
  1573. bool Found = (bool)(outputCollection["Found"].Value);
  1574. //获取图片存储的图片文件名
  1575. string imgName = string.Empty;
  1576. if (procedure.IsSaveImage && !string.IsNullOrEmpty(procedure.ImageFileNameFormat))
  1577. {
  1578. // 创建模板,使用 {变量名:格式} 语法
  1579. var template = new FileNameTemplate(procedure.ImageFileNameFormat);
  1580. // 注册变量
  1581. template.RegisterVariable("ProductSN", () => _productService.CurrentProductCode);
  1582. template.RegisterVariable("CameraName", () => procedure.CameraName);
  1583. template.RegisterVariable("ShotCount", () => 1);
  1584. template.RegisterVariable("Result", () => Found ? "OK" : "NG");
  1585. template.RegisterVariable("DateTime", () => DateTime.Now);
  1586. // 生成文件名
  1587. imgName = template.Generate();
  1588. }
  1589. _eventAggregator.GetEvent<RenderUpdateNotification>().Publish(new ShowRender()
  1590. {
  1591. Id = procedure.Id,
  1592. DisplayName = procedure.DisplayName,
  1593. //Image = (ICogImage)procedure.ToolBlock.Outputs["OriImage"].Value,
  1594. //Image = (ICogImage)procedure.ToolBlock.Inputs["InputImage"].Value,
  1595. Image = image,
  1596. Graphic = outputCollection["Graphic"].Value as CogGraphicCollection,
  1597. Record = record,
  1598. Result = Found,
  1599. IsShow = true,
  1600. IsSaveImage = procedure.IsSaveImage,
  1601. SaveImageModel = procedure.SaveImageModel,
  1602. SaveImagePathModel = procedure.SaveImagePathModel,
  1603. SavePath = procedure.SavePath,
  1604. IsCompress = procedure.IsCompress,
  1605. ProceductName = procedure.Name,
  1606. ImageFileName = imgName,
  1607. Is3DModel = true
  1608. });
  1609. return true;
  1610. }
  1611. else
  1612. {
  1613. SendTaskMessage(Lang.视觉流程执行出错耗时.Replace("{0}", procedure.Name).Replace("{1}", $"{procedure.ToolBlock.RunStatus.ProcessingTime:F1}"), MessageLevel.Error);
  1614. SendTaskMessage(procedure.ToolBlock.RunStatus.Message, MessageLevel.Error);
  1615. outputCollection = null;
  1616. //获取图片存储的图片文件名
  1617. string imgName = string.Empty;
  1618. if (procedure.IsSaveImage && !string.IsNullOrEmpty(procedure.ImageFileNameFormat))
  1619. {
  1620. // 创建模板,使用 {变量名:格式} 语法
  1621. var template = new FileNameTemplate(procedure.ImageFileNameFormat);
  1622. // 注册变量
  1623. template.RegisterVariable("ProductSN", () => _productService.CurrentProductCode);
  1624. template.RegisterVariable("CameraName", () => procedure.CameraName);
  1625. template.RegisterVariable("ShotCount", () => 1);
  1626. template.RegisterVariable("Result", () => "NG");
  1627. template.RegisterVariable("DateTime", () => DateTime.Now);
  1628. // 生成文件名
  1629. imgName = template.Generate();
  1630. }
  1631. _eventAggregator.GetEvent<RenderUpdateNotification>().Publish(new ShowRender()
  1632. {
  1633. Id = procedure.Id,
  1634. DisplayName = procedure.DisplayName,
  1635. //Image = (ICogImage)procedure.ToolBlock.Outputs["OriImage"].Value,
  1636. //Image = (ICogImage)procedure.ToolBlock.Inputs["InputImage"].Value,
  1637. Image = image,
  1638. Graphic = new CogGraphicCollection(),
  1639. Result = false,
  1640. IsShow = true,
  1641. IsSaveImage = procedure.IsSaveImage,
  1642. SaveImageModel = procedure.SaveImageModel,
  1643. SaveImagePathModel = procedure.SaveImagePathModel,
  1644. SavePath = procedure.SavePath,
  1645. ProceductName = procedure.Name,
  1646. ImageFileName = imgName,
  1647. Is3DModel = true
  1648. });
  1649. return false;
  1650. }
  1651. }
  1652. catch (Exception ex)
  1653. {
  1654. SendTaskMessage(ex.Message, MessageLevel.Error);
  1655. LogHelper.WriteLogError("执行相机取图并执行视觉工具组时出错!", ex);
  1656. outputCollection = null;
  1657. return false;
  1658. }
  1659. }
  1660. /// <summary>
  1661. /// 执行相机拍照并运行 ToolBlock,返回是否成功并通过 out 参数返回 Outputs。
  1662. /// 该方法会发布 RenderUpdateNotification 以更新 UI。
  1663. /// </summary>
  1664. public bool ExecutePhoto2(ProcedureModel procedure, Dictionary<string, string> InputTerminal, out CogToolBlockTerminalCollection outputCollection)
  1665. {
  1666. try
  1667. {
  1668. // 1. 采集图像
  1669. var camera = _cameraService.GetCamera(procedure.CameraId);
  1670. bool succed = camera.SetExposureTime(procedure.ExposureTime);
  1671. if (!succed)
  1672. {
  1673. SendTaskMessage($"相机曝光设置失败!", MessageLevel.Error);
  1674. }
  1675. succed = camera.SetGain(procedure.Gain);
  1676. if (!succed)
  1677. {
  1678. SendTaskMessage($"相机增益设置失败!", MessageLevel.Error);
  1679. }
  1680. DateTime nowtime = DateTime.Now;
  1681. LogHelper.WriteLogInfo("开始采集图像");
  1682. //var image = camera.Grab();
  1683. var image = camera.Grab();
  1684. if (image == null)
  1685. {
  1686. SendTaskMessage(Lang.图像采集失败, MessageLevel.Error);
  1687. outputCollection = null;
  1688. return false;
  1689. }
  1690. procedure.ToolBlock.Inputs["InputImage"].Value = image;
  1691. LogHelper.WriteLogInfo($"采集图像完成;用时:{(DateTime.Now - nowtime).Milliseconds}ms");
  1692. // 2. 为ToolBlock传入其他输入终端
  1693. if (InputTerminal != null)
  1694. {
  1695. LogHelper.WriteLogInfo($"为ToolBlock传入输入终端");
  1696. foreach (var item in InputTerminal)
  1697. {
  1698. if (procedure.ToolBlock.Inputs.Contains(item.Key))
  1699. {
  1700. LogHelper.WriteLogInfo($"传入[{item.Key}]={item.Value}");
  1701. procedure.ToolBlock.Inputs[item.Key].Value = item.Value;
  1702. }
  1703. else
  1704. {
  1705. LogHelper.WriteLogInfo($"创建并传入[{item.Key}]={item.Value}");
  1706. procedure.ToolBlock.Inputs.Add(new CogToolBlockTerminal(item.Key, item.Value));
  1707. }
  1708. }
  1709. }
  1710. // 3. 运行视觉工具
  1711. LogHelper.WriteLogInfo("开始运行视觉工具");
  1712. procedure.ToolBlock.Run(); //运行ToolBlock
  1713. if (procedure.ToolBlock.RunStatus.Result == CogToolResultConstants.Accept)
  1714. {
  1715. SendTaskMessage(Lang.视觉流程执行耗时.Replace("{0}", procedure.Name).Replace("{1}", $"{procedure.ToolBlock.RunStatus.ProcessingTime:F1}"), MessageLevel.Info);
  1716. outputCollection = procedure.ToolBlock.Outputs; //获取输出终端集合
  1717. DatabaseHelper.AddCameraRecords(_productService.GetCurrentProduct().Name, procedure.Name, outputCollection);
  1718. ICogRecord record = null;
  1719. foreach (CogToolBlockTerminal item in outputCollection)
  1720. {
  1721. if (item.Value is ICogRecord)
  1722. record = item.Value as ICogRecord;
  1723. }
  1724. bool Found = (bool)(outputCollection["Found"].Value);
  1725. //获取图片存储的图片文件名
  1726. string imgName = string.Empty;
  1727. if (procedure.IsSaveImage && !string.IsNullOrEmpty(procedure.ImageFileNameFormat))
  1728. {
  1729. // 创建模板,使用 {变量名:格式} 语法
  1730. var template = new FileNameTemplate(procedure.ImageFileNameFormat);
  1731. // 注册变量
  1732. template.RegisterVariable("ProductSN", () => _productService.CurrentProductCode);
  1733. template.RegisterVariable("CameraName", () => procedure.CameraName);
  1734. template.RegisterVariable("ShotCount", () => 1);
  1735. template.RegisterVariable("Result", () => Found ? "OK" : "NG");
  1736. template.RegisterVariable("DateTime", () => DateTime.Now);
  1737. // 生成文件名
  1738. imgName = template.Generate();
  1739. }
  1740. _eventAggregator.GetEvent<RenderUpdateNotification>().Publish(new ShowRender()
  1741. {
  1742. Id = procedure.DisplayId,
  1743. DisplayName = procedure.DisplayName,
  1744. //Image = (ICogImage)procedure.ToolBlock.Outputs["OriImage"].Value,
  1745. Image = (ICogImage)procedure.ToolBlock.Inputs["InputImage"].Value,
  1746. Graphic = outputCollection["Graphic"].Value as CogGraphicCollection,
  1747. Record = record,
  1748. Result = Found,
  1749. IsShow = true,
  1750. IsSaveImage = procedure.IsSaveImage,
  1751. SaveImageModel = procedure.SaveImageModel,
  1752. SaveImagePathModel = procedure.SaveImagePathModel,
  1753. SavePath = procedure.SavePath,
  1754. IsCompress = procedure.IsCompress,
  1755. ProceductName = procedure.Name,
  1756. ImageFileName = imgName,
  1757. Is3DModel = false
  1758. });
  1759. return true;
  1760. }
  1761. else
  1762. {
  1763. SendTaskMessage(Lang.视觉流程执行出错耗时.Replace("{0}", procedure.Name).Replace("{1}", $"{procedure.ToolBlock.RunStatus.ProcessingTime:F1}"), MessageLevel.Error);
  1764. SendTaskMessage(procedure.ToolBlock.RunStatus.Message, MessageLevel.Error);
  1765. outputCollection = null;
  1766. //获取图片存储的图片文件名
  1767. string imgName = string.Empty;
  1768. if (procedure.IsSaveImage && !string.IsNullOrEmpty(procedure.ImageFileNameFormat))
  1769. {
  1770. // 创建模板,使用 {变量名:格式} 语法
  1771. var template = new FileNameTemplate(procedure.ImageFileNameFormat);
  1772. // 注册变量
  1773. template.RegisterVariable("ProductSN", () => _productService.CurrentProductCode);
  1774. template.RegisterVariable("CameraName", () => procedure.CameraName);
  1775. template.RegisterVariable("ShotCount", () => 1);
  1776. template.RegisterVariable("Result", () => "NG");
  1777. template.RegisterVariable("DateTime", () => DateTime.Now);
  1778. // 生成文件名
  1779. imgName = template.Generate();
  1780. }
  1781. _eventAggregator.GetEvent<RenderUpdateNotification>().Publish(new ShowRender()
  1782. {
  1783. Id = procedure.DisplayId,
  1784. DisplayName = procedure.DisplayName,
  1785. //Image = (ICogImage)procedure.ToolBlock.Outputs["OriImage"].Value,
  1786. Image = (ICogImage)procedure.ToolBlock.Inputs["InputImage"].Value,
  1787. Graphic = new CogGraphicCollection(),
  1788. Result = false,
  1789. IsShow = true,
  1790. IsSaveImage = procedure.IsSaveImage,
  1791. SaveImageModel = procedure.SaveImageModel,
  1792. SaveImagePathModel = procedure.SaveImagePathModel,
  1793. SavePath = procedure.SavePath,
  1794. ProceductName = procedure.Name,
  1795. ImageFileName = imgName,
  1796. Is3DModel = false
  1797. });
  1798. return false;
  1799. }
  1800. }
  1801. catch (Exception ex)
  1802. {
  1803. SendTaskMessage(ex.Message, MessageLevel.Error);
  1804. LogHelper.WriteLogError("执行相机取图并执行视觉工具组时出错!", ex);
  1805. outputCollection = null;
  1806. return false;
  1807. }
  1808. }
  1809. /// <summary>
  1810. /// 执行相机拍照并运行 ToolBlock,返回是否成功并通过 out 参数返回 Outputs。
  1811. /// 该方法会发布 RenderUpdateNotification 以更新 UI。
  1812. /// </summary>
  1813. public bool ExecutePhoto(ProcedureModel procedure, ICogImage[] imges, Dictionary<string, string> InputTerminal, out CogToolBlockTerminalCollection outputCollection, bool is3dmodel, float confThreshold = 0.25f, float iouThreshold = 0.45f)
  1814. {
  1815. try
  1816. {
  1817. procedure.ToolBlock.Inputs["InputImage"].Value = imges[0];
  1818. if (is3dmodel == true || imges.Length > 1)
  1819. {
  1820. procedure.ToolBlock.Inputs["InputImage2"].Value = imges[1];
  1821. }
  1822. // 2. 为ToolBlock传入其他输入终端
  1823. if (InputTerminal != null)
  1824. {
  1825. LogHelper.WriteLogInfo($"为ToolBlock传入输入终端");
  1826. foreach (var item in InputTerminal)
  1827. {
  1828. if (procedure.ToolBlock.Inputs.Contains(item.Key))
  1829. {
  1830. LogHelper.WriteLogInfo($"传入[{item.Key}]={item.Value}");
  1831. procedure.ToolBlock.Inputs[item.Key].Value = item.Value;
  1832. }
  1833. else
  1834. {
  1835. LogHelper.WriteLogInfo($"创建并传入[{item.Key}]={item.Value}");
  1836. procedure.ToolBlock.Inputs.Add(new CogToolBlockTerminal(item.Key, item.Value));
  1837. }
  1838. }
  1839. }
  1840. string photoAiValue = procedure.UserDefineParameters?.FirstOrDefault(p => string.Equals(p.ParamName, "Photo_AI", StringComparison.OrdinalIgnoreCase))?.ParamValue;
  1841. // photoAiValue 可能为 null/空,建议给个默认值
  1842. bool enablePhotoAi = photoAiValue == "1";
  1843. if (enablePhotoAi == true)
  1844. {
  1845. string exeDir = System.IO.Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
  1846. string trainFolderName = string.IsNullOrWhiteSpace(procedure.CameraTrainFolder) ? "TrainPhoto" : procedure.CameraTrainFolder;
  1847. string trainRoot = System.IO.Path.Combine(exeDir, "Train", trainFolderName);
  1848. string modelPath = System.IO.Path.Combine(exeDir, trainRoot, "weights", "best_openvino_model", "best.xml");
  1849. string metadataPath = System.IO.Path.Combine(exeDir, trainRoot, "weights", "best_openvino_model", "metadata.yaml");
  1850. // (可选)如果你希望缺文件时给出更明确提示:
  1851. if (!File.Exists(modelPath))
  1852. throw new FileNotFoundException("未找到模型文件 best.xml", modelPath);
  1853. if (!File.Exists(metadataPath))
  1854. throw new FileNotFoundException("未找到模型文件 metadata.yaml", metadataPath);
  1855. //string modelPath = @"G:\TEST\train17\weights\best_openvino_model\best.xml";
  1856. //string metadataPath = @"G:\TEST\train17\weights\best_openvino_model\metadata.yaml";
  1857. //string imagePath = "G:\\TEST\\文件\\左上插线\\1.bmp";
  1858. float confThreshold1 = float.Parse(procedure.UserDefineParameters?.FirstOrDefault(p => string.Equals(p.ParamName, "ConfThreshold", StringComparison.OrdinalIgnoreCase))?.ParamValue);
  1859. float iouThreshold1 = float.Parse(procedure.UserDefineParameters?.FirstOrDefault(p => string.Equals(p.ParamName, "IouThreshold", StringComparison.OrdinalIgnoreCase))?.ParamValue);
  1860. using (var yolo = new YoloOpenVINOInference(modelPath, metadataPath, confThreshold1, iouThreshold1))
  1861. {
  1862. using (var bitmap = imges[0].ToBitmap())
  1863. {
  1864. var results = yolo.Infer(bitmap);
  1865. procedure.ToolBlock.Inputs["PhotoData"].Value = "";
  1866. procedure.ToolBlock.Inputs["Confidence"].Value = "";
  1867. // 输出结果
  1868. SendTaskMessage($"识别的个数:{results.Count()}", MessageLevel.Alarm);
  1869. string ClassName = "";
  1870. string Confidence = "";
  1871. foreach (var det in results)
  1872. {
  1873. SendTaskMessage($" - {det.ClassName}: 置信度={det.Confidence:F4}, " +
  1874. $"边界框=[{det.Box[0]:F0}, {det.Box[1]:F0}, {det.Box[2]:F0}, {det.Box[3]:F0}]", MessageLevel.Alarm);
  1875. ClassName += $"{det.ClassName}" + ",";
  1876. Confidence += $"{det.Confidence}" + ",";
  1877. }
  1878. procedure.ToolBlock.Inputs["PhotoData"].Value = ClassName;
  1879. procedure.ToolBlock.Inputs["Confidence"].Value = Confidence;
  1880. // 绘制结果 - 使用 OpenCvSharp
  1881. using (var image2 = ImageHelper.ICogImageConvertMat(imges[0]))
  1882. {
  1883. var OriginyoloColorCogImage = ImageHelper.MatConvertICogImage(image2, true);
  1884. // 定义颜色映射
  1885. var colors = new[]
  1886. {
  1887. Scalar.Red, // NG1 - 红色
  1888. Scalar.Green, // NG2 - 绿色
  1889. Scalar.Blue, // NG3 - 蓝色
  1890. Scalar.Yellow // NG4 - 黄色
  1891. };
  1892. foreach (var det in results)
  1893. {
  1894. // 获取边界框坐标
  1895. int x1 = (int)det.Box[0];
  1896. int y1 = (int)det.Box[1];
  1897. int x2 = (int)det.Box[2];
  1898. int y2 = (int)det.Box[3];
  1899. // 添加边界检查:确保坐标有效
  1900. if (x1 >= x2 || y1 >= y2)
  1901. {
  1902. SendTaskMessage($"警告: 无效的边界框 [{x1}, {y1}, {x2}, {y2}]", MessageLevel.Error);
  1903. continue;
  1904. }
  1905. // 确保坐标在图像范围内
  1906. x1 = Math.Max(0, Math.Min(image2.Width, x1));
  1907. y1 = Math.Max(0, Math.Min(image2.Height, y1));
  1908. x2 = Math.Max(0, Math.Min(image2.Width, x2));
  1909. y2 = Math.Max(0, Math.Min(image2.Height, y2));
  1910. // 选择颜色(根据类别ID)
  1911. Scalar color = colors[det.ClassId % colors.Length];
  1912. // 绘制矩形框
  1913. Cv2.Rectangle(image2, new Point(x1, y1), new Point(x2, y2), color, 2);
  1914. // 准备标签文本
  1915. string label = $"{det.ClassName} {det.Confidence:P0}";
  1916. // 计算文本大小
  1917. var textSize = Cv2.GetTextSize(label, HersheyFonts.HersheySimplex, 0.6, 1, out int baseline);
  1918. // 确保文本位置不超出图像边界
  1919. int textX = x1;
  1920. int textY = y1 - 5;
  1921. // 如果文本超出图像顶部,显示在框内底部
  1922. if (textY - textSize.Height < 0)
  1923. {
  1924. textY = y2 + baseline + 5;
  1925. }
  1926. //绘制文本背景
  1927. Cv2.Rectangle(image2,
  1928. new OpenCvSharp.Rect(textX, textY - textSize.Height - baseline - 10,
  1929. textSize.Width + 10, textSize.Height + baseline + 10),
  1930. color, -1);
  1931. // 绘制文本
  1932. Cv2.PutText(image2, label,
  1933. new Point(textX + 5, textY - baseline - 5),
  1934. HersheyFonts.HersheySimplex, 0.6, Scalar.White, 2);
  1935. }
  1936. // 关键:这里转成彩色 ICogImage
  1937. var yoloColorCogImage = ImageHelper.MatConvertICogImage(image2,true);
  1938. // 模板检测如果需要原图,可以用 imges[0]
  1939. // 如果你希望模板也拿 YOLO 画框图,就用 yoloColorCogImage
  1940. procedure.ToolBlock.Inputs["InputImage"].Value = yoloColorCogImage;
  1941. procedure.ToolBlock.Run();
  1942. outputCollection = procedure.ToolBlock.Outputs;
  1943. ICogRecord record = null;
  1944. foreach (CogToolBlockTerminal item in outputCollection)
  1945. {
  1946. if (item.Value is ICogRecord)
  1947. record = item.Value as ICogRecord;
  1948. }
  1949. bool Found = (bool)(outputCollection["Found"].Value);
  1950. //获取图片存储的图片文件名
  1951. string imgName = string.Empty;
  1952. if (procedure.IsSaveImage && !string.IsNullOrEmpty(procedure.ImageFileNameFormat))
  1953. {
  1954. // 创建模板,使用 {变量名:格式} 语法
  1955. var template = new FileNameTemplate(procedure.ImageFileNameFormat);
  1956. // 注册变量
  1957. template.RegisterVariable("ProductSN", () => _productService.CurrentProductCode);
  1958. template.RegisterVariable("CameraName", () => procedure.CameraName);
  1959. template.RegisterVariable("ShotCount", () => 1);
  1960. template.RegisterVariable("Result", () => Found ? "OK" : "NG");
  1961. template.RegisterVariable("DateTime", () => DateTime.Now);
  1962. // 生成文件名
  1963. imgName = template.Generate();
  1964. }
  1965. _eventAggregator.GetEvent<RenderUpdateNotification>().Publish(new ShowRender()
  1966. {
  1967. Id = procedure.DisplayId,
  1968. DisplayName = procedure.DisplayName,
  1969. // 显示和保存用 YOLO 彩色图
  1970. Image = yoloColorCogImage,
  1971. Graphic = outputCollection["Graphic"].Value as CogGraphicCollection,
  1972. Record = record,
  1973. Result = Found,
  1974. IsShow = false,
  1975. IsSaveImage = procedure.IsSaveImage,
  1976. SaveImageModel = procedure.SaveImageModel,
  1977. SaveImagePathModel = procedure.SaveImagePathModel,
  1978. SavePath = procedure.SavePath,
  1979. IsCompress = procedure.IsCompress,
  1980. ProceductName = procedure.Name,
  1981. ImageFileName = imgName,
  1982. Is3DModel = is3dmodel,
  1983. });
  1984. _eventAggregator.GetEvent<RenderUpdateNotification>().Publish(new ShowRender()
  1985. {
  1986. Id = procedure.DisplayId,
  1987. DisplayName = procedure.DisplayName,
  1988. Image = OriginyoloColorCogImage,
  1989. Graphic = outputCollection["Graphic"].Value as CogGraphicCollection,
  1990. Record = record,
  1991. Result = Found,
  1992. IsShow = true,
  1993. IsSaveImage = procedure.IsSaveImage,
  1994. SaveImageModel = procedure.SaveImageModel,
  1995. SaveImagePathModel = procedure.SaveImagePathModel,
  1996. SavePath = procedure.SavePath,
  1997. IsCompress = procedure.IsCompress,
  1998. ProceductName = procedure.Name,
  1999. ImageFileName = imgName,
  2000. Is3DModel = is3dmodel,
  2001. });
  2002. }
  2003. }
  2004. }
  2005. return true;
  2006. }
  2007. else
  2008. {
  2009. // 3. 运行视觉工具
  2010. LogHelper.WriteLogInfo("开始运行视觉工具");
  2011. procedure.ToolBlock.Run(); //运行ToolBlock
  2012. if (procedure.ToolBlock.RunStatus.Result == CogToolResultConstants.Accept)
  2013. {
  2014. SendTaskMessage(Lang.视觉流程执行耗时.Replace("{0}", procedure.Name).Replace("{1}", $"{procedure.ToolBlock.RunStatus.ProcessingTime:F1}"), MessageLevel.Info);
  2015. outputCollection = procedure.ToolBlock.Outputs; //获取输出终端集合
  2016. DatabaseHelper.AddCameraRecords(_productService.GetCurrentProduct().Name, procedure.Name, outputCollection);
  2017. ICogRecord record = null;
  2018. foreach (CogToolBlockTerminal item in outputCollection)
  2019. {
  2020. if (item.Value is ICogRecord)
  2021. record = item.Value as ICogRecord;
  2022. }
  2023. bool Found = (bool)(outputCollection["Found"].Value);
  2024. //获取图片存储的图片文件名
  2025. string imgName = string.Empty;
  2026. if (procedure.IsSaveImage && !string.IsNullOrEmpty(procedure.ImageFileNameFormat))
  2027. {
  2028. // 创建模板,使用 {变量名:格式} 语法
  2029. var template = new FileNameTemplate(procedure.ImageFileNameFormat);
  2030. // 注册变量
  2031. template.RegisterVariable("ProductSN", () => _productService.CurrentProductCode);
  2032. template.RegisterVariable("CameraName", () => procedure.CameraName);
  2033. template.RegisterVariable("ShotCount", () => 1);
  2034. template.RegisterVariable("Result", () => Found ? "OK" : "NG");
  2035. template.RegisterVariable("DateTime", () => DateTime.Now);
  2036. // 生成文件名
  2037. imgName = template.Generate();
  2038. }
  2039. if (is3dmodel == true)
  2040. {
  2041. if (_configService.GetSystemConfiguration().PickPointNum == 0)
  2042. {
  2043. if (procedure.ToolBlock.Inputs.Contains("InputImage2"))
  2044. {
  2045. _eventAggregator.GetEvent<RenderUpdateNotification>().Publish(new ShowRender()
  2046. {
  2047. Id = procedure.DisplayId,
  2048. DisplayName = procedure.DisplayName,
  2049. //Image = (ICogImage)procedure.ToolBlock.Outputs["OriImage"].Value,
  2050. Image = (ICogImage)procedure.ToolBlock.Inputs["InputImage2"].Value,
  2051. Graphic = outputCollection["Graphic"].Value as CogGraphicCollection,
  2052. Record = record,
  2053. Result = Found,
  2054. IsShow = true,
  2055. IsSaveImage = procedure.IsSaveImage,
  2056. SaveImageModel = procedure.SaveImageModel,
  2057. SaveImagePathModel = procedure.SaveImagePathModel,
  2058. SavePath = procedure.SavePath,
  2059. IsCompress = procedure.IsCompress,
  2060. ProceductName = procedure.Name,
  2061. ImageFileName = imgName + "image2",
  2062. Is3DModel = false,
  2063. });
  2064. }
  2065. _eventAggregator.GetEvent<RenderUpdateNotification>().Publish(new ShowRender()
  2066. {
  2067. Id = procedure.DisplayId,
  2068. DisplayName = procedure.DisplayName,
  2069. //Image = (ICogImage)procedure.ToolBlock.Outputs["OriImage"].Value,
  2070. Image = (ICogImage)procedure.ToolBlock.Inputs["InputImage"].Value,
  2071. Graphic = outputCollection["Graphic"].Value as CogGraphicCollection,
  2072. Record = record,
  2073. Result = Found,
  2074. IsShow = true,
  2075. IsSaveImage = procedure.IsSaveImage,
  2076. SaveImageModel = procedure.SaveImageModel,
  2077. SaveImagePathModel = procedure.SaveImagePathModel,
  2078. SavePath = procedure.SavePath,
  2079. IsCompress = procedure.IsCompress,
  2080. ProceductName = procedure.Name,
  2081. ImageFileName = imgName,
  2082. Is3DModel = is3dmodel,
  2083. //RangeImage = (CogImage16Range)procedure.ToolBlock.Outputs["RangeImage"].Value,
  2084. //GreyImage = (CogImage16Grey)procedure.ToolBlock.Outputs["GreyImage"].Value
  2085. });
  2086. }
  2087. else
  2088. {
  2089. if (procedure.ToolBlock.Inputs.Contains("InputImage2"))
  2090. {
  2091. _eventAggregator.GetEvent<RenderUpdateNotification>().Publish(new ShowRender()
  2092. {
  2093. Id = procedure.DisplayId,
  2094. DisplayName = procedure.DisplayName,
  2095. //Image = (ICogImage)procedure.ToolBlock.Outputs["OriImage"].Value,
  2096. Image = (ICogImage)procedure.ToolBlock.Inputs["InputImage2"].Value,
  2097. Graphic = outputCollection["Graphic"].Value as CogGraphicCollection,
  2098. Record = record,
  2099. Result = Found,
  2100. IsShow = true,
  2101. IsSaveImage = procedure.IsSaveImage,
  2102. SaveImageModel = procedure.SaveImageModel,
  2103. SaveImagePathModel = procedure.SaveImagePathModel,
  2104. SavePath = procedure.SavePath,
  2105. IsCompress = procedure.IsCompress,
  2106. ProceductName = procedure.Name,
  2107. ImageFileName = imgName + "image2",
  2108. Is3DModel = false,
  2109. });
  2110. }
  2111. _eventAggregator.GetEvent<RenderUpdateNotification>().Publish(new ShowRender()
  2112. {
  2113. Id = procedure.DisplayId,
  2114. DisplayName = procedure.DisplayName,
  2115. //Image = (ICogImage)procedure.ToolBlock.Outputs["OriImage"].Value,
  2116. Image = (ICogImage)procedure.ToolBlock.Inputs["InputImage"].Value,
  2117. Graphic = outputCollection["Graphic"].Value as CogGraphicCollection,
  2118. Record = record,
  2119. Result = Found,
  2120. IsShow = true,
  2121. IsSaveImage = procedure.IsSaveImage,
  2122. SaveImageModel = procedure.SaveImageModel,
  2123. SaveImagePathModel = procedure.SaveImagePathModel,
  2124. SavePath = procedure.SavePath,
  2125. IsCompress = procedure.IsCompress,
  2126. ProceductName = procedure.Name,
  2127. ImageFileName = imgName,
  2128. Is3DModel = is3dmodel,
  2129. RangeImage = (CogImage16Range)procedure.ToolBlock.Outputs["RangeImage"].Value,
  2130. GreyImage = (CogImage16Grey)procedure.ToolBlock.Outputs["GreyImage"].Value
  2131. });
  2132. }
  2133. }
  2134. else
  2135. {
  2136. if (procedure.ToolBlock.Inputs.Contains("InputImage2"))
  2137. {
  2138. _eventAggregator.GetEvent<RenderUpdateNotification>().Publish(new ShowRender()
  2139. {
  2140. Id = procedure.DisplayId,
  2141. DisplayName = procedure.DisplayName,
  2142. //Image = (ICogImage)procedure.ToolBlock.Outputs["OriImage"].Value,
  2143. Image = (ICogImage)procedure.ToolBlock.Inputs["InputImage2"].Value,
  2144. Graphic = outputCollection["Graphic"].Value as CogGraphicCollection,
  2145. Record = record,
  2146. Result = Found,
  2147. IsShow = true,
  2148. IsSaveImage = procedure.IsSaveImage,
  2149. SaveImageModel = procedure.SaveImageModel,
  2150. SaveImagePathModel = procedure.SaveImagePathModel,
  2151. SavePath = procedure.SavePath,
  2152. IsCompress = procedure.IsCompress,
  2153. ProceductName = procedure.Name,
  2154. ImageFileName = imgName + "image2",
  2155. Is3DModel = false,
  2156. });
  2157. }
  2158. _eventAggregator.GetEvent<RenderUpdateNotification>().Publish(new ShowRender()
  2159. {
  2160. Id = procedure.DisplayId,
  2161. DisplayName = procedure.DisplayName,
  2162. //Image = (ICogImage)procedure.ToolBlock.Outputs["OriImage"].Value,
  2163. Image = (ICogImage)procedure.ToolBlock.Inputs["InputImage"].Value,
  2164. Graphic = outputCollection["Graphic"].Value as CogGraphicCollection,
  2165. Record = record,
  2166. Result = Found,
  2167. IsShow = true,
  2168. IsSaveImage = procedure.IsSaveImage,
  2169. SaveImageModel = procedure.SaveImageModel,
  2170. SaveImagePathModel = procedure.SaveImagePathModel,
  2171. SavePath = procedure.SavePath,
  2172. IsCompress = procedure.IsCompress,
  2173. ProceductName = procedure.Name,
  2174. ImageFileName = imgName,
  2175. Is3DModel = is3dmodel
  2176. });
  2177. }
  2178. return true;
  2179. }
  2180. else
  2181. {
  2182. SendTaskMessage(Lang.视觉流程执行出错耗时.Replace("{0}", procedure.Name).Replace("{1}", $"{procedure.ToolBlock.RunStatus.ProcessingTime:F1}"), MessageLevel.Error);
  2183. SendTaskMessage(procedure.ToolBlock.RunStatus.Message, MessageLevel.Error);
  2184. outputCollection = null;
  2185. //获取图片存储的图片文件名
  2186. string imgName = string.Empty;
  2187. if (procedure.IsSaveImage && !string.IsNullOrEmpty(procedure.ImageFileNameFormat))
  2188. {
  2189. // 创建模板,使用 {变量名:格式} 语法
  2190. var template = new FileNameTemplate(procedure.ImageFileNameFormat);
  2191. // 注册变量
  2192. template.RegisterVariable("ProductSN", () => _productService.CurrentProductCode);
  2193. template.RegisterVariable("CameraName", () => procedure.CameraName);
  2194. template.RegisterVariable("ShotCount", () => 1);
  2195. template.RegisterVariable("Result", () => "NG");
  2196. template.RegisterVariable("DateTime", () => DateTime.Now);
  2197. // 生成文件名
  2198. imgName = template.Generate();
  2199. }
  2200. if (is3dmodel == true)
  2201. {
  2202. if (procedure.ToolBlock.Inputs.Contains("InputImage2"))
  2203. {
  2204. _eventAggregator.GetEvent<RenderUpdateNotification>().Publish(new ShowRender()
  2205. {
  2206. Id = procedure.DisplayId,
  2207. DisplayName = procedure.DisplayName,
  2208. //Image = (ICogImage)procedure.ToolBlock.Outputs["OriImage"].Value,
  2209. Image = (ICogImage)procedure.ToolBlock.Inputs["InputImage2"].Value,
  2210. Graphic = outputCollection["Graphic"].Value as CogGraphicCollection,
  2211. Result = false,
  2212. IsShow = true,
  2213. IsSaveImage = procedure.IsSaveImage,
  2214. SaveImageModel = procedure.SaveImageModel,
  2215. SaveImagePathModel = procedure.SaveImagePathModel,
  2216. SavePath = procedure.SavePath,
  2217. IsCompress = procedure.IsCompress,
  2218. ProceductName = procedure.Name,
  2219. ImageFileName = imgName + "image2",
  2220. Is3DModel = is3dmodel,
  2221. });
  2222. }
  2223. _eventAggregator.GetEvent<RenderUpdateNotification>().Publish(new ShowRender()
  2224. {
  2225. Id = procedure.DisplayId,
  2226. DisplayName = procedure.DisplayName,
  2227. //Image = (ICogImage)procedure.ToolBlock.Outputs["OriImage"].Value,
  2228. Image = (ICogImage)procedure.ToolBlock.Inputs["InputImage"].Value,
  2229. Graphic = new CogGraphicCollection(),
  2230. Result = false,
  2231. IsShow = true,
  2232. IsSaveImage = procedure.IsSaveImage,
  2233. SaveImageModel = procedure.SaveImageModel,
  2234. SaveImagePathModel = procedure.SaveImagePathModel,
  2235. SavePath = procedure.SavePath,
  2236. ProceductName = procedure.Name,
  2237. ImageFileName = imgName,
  2238. Is3DModel = is3dmodel,
  2239. RangeImage = (CogImage16Range)procedure.ToolBlock.Outputs["RangeImage"].Value,
  2240. GreyImage = (CogImage16Grey)procedure.ToolBlock.Outputs["GreyImage"].Value
  2241. });
  2242. }
  2243. else
  2244. {
  2245. if (procedure.ToolBlock.Inputs.Contains("InputImage2"))
  2246. {
  2247. _eventAggregator.GetEvent<RenderUpdateNotification>().Publish(new ShowRender()
  2248. {
  2249. Id = procedure.DisplayId,
  2250. DisplayName = procedure.DisplayName,
  2251. //Image = (ICogImage)procedure.ToolBlock.Outputs["OriImage"].Value,
  2252. Image = (ICogImage)procedure.ToolBlock.Inputs["InputImage2"].Value,
  2253. Graphic = outputCollection["Graphic"].Value as CogGraphicCollection,
  2254. Result = false,
  2255. IsShow = true,
  2256. IsSaveImage = procedure.IsSaveImage,
  2257. SaveImageModel = procedure.SaveImageModel,
  2258. SaveImagePathModel = procedure.SaveImagePathModel,
  2259. SavePath = procedure.SavePath,
  2260. IsCompress = procedure.IsCompress,
  2261. ProceductName = procedure.Name,
  2262. ImageFileName = imgName + "image2",
  2263. Is3DModel = is3dmodel,
  2264. });
  2265. }
  2266. _eventAggregator.GetEvent<RenderUpdateNotification>().Publish(new ShowRender()
  2267. {
  2268. Id = procedure.DisplayId,
  2269. DisplayName = procedure.DisplayName,
  2270. //Image = (ICogImage)procedure.ToolBlock.Outputs["OriImage"].Value,
  2271. Image = (ICogImage)procedure.ToolBlock.Inputs["InputImage"].Value,
  2272. Graphic = new CogGraphicCollection(),
  2273. Result = false,
  2274. IsShow = true,
  2275. IsSaveImage = procedure.IsSaveImage,
  2276. SaveImageModel = procedure.SaveImageModel,
  2277. SaveImagePathModel = procedure.SaveImagePathModel,
  2278. SavePath = procedure.SavePath,
  2279. ProceductName = procedure.Name,
  2280. ImageFileName = imgName,
  2281. Is3DModel = is3dmodel
  2282. });
  2283. }
  2284. return false;
  2285. }
  2286. }
  2287. }
  2288. catch (Exception ex)
  2289. {
  2290. SendTaskMessage(ex.Message, MessageLevel.Error);
  2291. LogHelper.WriteLogError("执行相机取图并执行视觉工具组时出错!", ex);
  2292. outputCollection = null;
  2293. return false;
  2294. }
  2295. }
  2296. /// <summary>
  2297. /// 采集图像
  2298. /// </summary>
  2299. /// <param name="procedure"></param>
  2300. /// <returns></returns>
  2301. public async Task<(bool IsSucceed, ICogImage[] Image, string Msg)> ExecuteGrabImageAsync(ProcedureModel procedure, bool Is3dPhoto, SystemConfiguration sysConfig)
  2302. {
  2303. try
  2304. {
  2305. //var sysConfig = _configService.GetSystemConfiguration();
  2306. if (sysConfig.PhotosUse == true)
  2307. {
  2308. // 1. 采集图像
  2309. var camera = _cameraService.GetCamera(procedure.CameraId);
  2310. ICogImage image = null;
  2311. ICogImage image2 = null;
  2312. for (int i = 1; i <= procedure.PhotoCount; i++)
  2313. {
  2314. if (i == 1)
  2315. {
  2316. bool isSucceed = false;
  2317. //isSucceed = await _lightManagerService.SetGlobalChannelBrightnessAsync(0, procedure.Photo1Light1);
  2318. //if (!isSucceed)
  2319. //{
  2320. // LogHelper.WriteLogInfo($"设置光源通道1亮度{procedure.Photo1Light1}失败!");
  2321. //}
  2322. //isSucceed = await _lightManagerService.SetGlobalChannelBrightnessAsync(1, procedure.Photo1Light2);
  2323. //if (!isSucceed)
  2324. //{
  2325. // LogHelper.WriteLogInfo($"设置光源通道2亮度{procedure.Photo1Light2}失败!");
  2326. //}
  2327. //isSucceed = await _lightManagerService.SetGlobalChannelBrightnessAsync(2, procedure.Photo1Light3);
  2328. //if (!isSucceed)
  2329. //{
  2330. // LogHelper.WriteLogInfo($"设置光源通道3亮度{procedure.Photo1Light3}失败!");
  2331. //}
  2332. bool succed = camera.SetExposureTime(procedure.ExposureTime);
  2333. if (!succed)
  2334. {
  2335. SendTaskMessage($"相机曝光设置失败!", MessageLevel.Error);
  2336. }
  2337. succed = camera.SetGain(procedure.Gain);
  2338. if (!succed)
  2339. {
  2340. SendTaskMessage($"相机增益设置失败!", MessageLevel.Error);
  2341. }
  2342. image = camera.Grab();
  2343. //isSucceed = await _lightManagerService.TurnOffGlobalChannelAsync(0);
  2344. //if (!isSucceed)
  2345. //{
  2346. // LogHelper.WriteLogInfo($"设置光源通道0关闭失败!");
  2347. //}
  2348. //isSucceed = await _lightManagerService.TurnOffGlobalChannelAsync(1);
  2349. //if (!isSucceed)
  2350. //{
  2351. // LogHelper.WriteLogInfo($"设置光源通道1关闭失败!");
  2352. //}
  2353. //isSucceed = await _lightManagerService.TurnOffGlobalChannelAsync(2);
  2354. //if (!isSucceed)
  2355. //{
  2356. // LogHelper.WriteLogInfo($"设置光源通道2关闭失败!");
  2357. //}
  2358. }
  2359. else if (i == 2)
  2360. {
  2361. bool isSucceed = false;
  2362. //isSucceed = await _lightManagerService.SetGlobalChannelBrightnessAsync(0, procedure.Photo2Light1);
  2363. //if (!isSucceed)
  2364. //{
  2365. // LogHelper.WriteLogInfo($"设置光源通道1亮度{procedure.Photo2Light1}失败!");
  2366. //}
  2367. //isSucceed = await _lightManagerService.SetGlobalChannelBrightnessAsync(1, procedure.Photo2Light2);
  2368. //if (!isSucceed)
  2369. //{
  2370. // LogHelper.WriteLogInfo($"设置光源通道2亮度{procedure.Photo2Light2}失败!");
  2371. //}
  2372. //isSucceed = await _lightManagerService.SetGlobalChannelBrightnessAsync(2, procedure.Photo2Light3);
  2373. //if (!isSucceed)
  2374. //{
  2375. // LogHelper.WriteLogInfo($"设置光源通道3亮度{procedure.Photo2Light3}失败!");
  2376. //}
  2377. SendTaskMessage($"开始设置相机曝光!", MessageLevel.Info);
  2378. bool succed = camera.SetExposureTime(procedure.ExposureTime2);
  2379. if (!succed)
  2380. {
  2381. SendTaskMessage($"相机曝光设置失败!", MessageLevel.Error);
  2382. }
  2383. SendTaskMessage($"开始设置相机增益!", MessageLevel.Info);
  2384. succed = camera.SetGain(procedure.Gain2);
  2385. if (!succed)
  2386. {
  2387. SendTaskMessage($"相机增益设置失败!", MessageLevel.Error);
  2388. }
  2389. image2 = camera.Grab();
  2390. isSucceed = await _lightManagerService.TurnOffGlobalChannelAsync(0);
  2391. if (!isSucceed)
  2392. {
  2393. LogHelper.WriteLogInfo($"设置光源通道0关闭失败!");
  2394. }
  2395. isSucceed = await _lightManagerService.TurnOffGlobalChannelAsync(1);
  2396. if (!isSucceed)
  2397. {
  2398. LogHelper.WriteLogInfo($"设置光源通道1关闭失败!");
  2399. }
  2400. isSucceed = await _lightManagerService.TurnOffGlobalChannelAsync(2);
  2401. if (!isSucceed)
  2402. {
  2403. LogHelper.WriteLogInfo($"设置光源通道2关闭失败!");
  2404. }
  2405. }
  2406. }
  2407. DateTime nowtime = DateTime.Now;
  2408. LogHelper.WriteLogInfo("开始采集图像");
  2409. //var image = camera.Grab();
  2410. if (Is3dPhoto == true)
  2411. {
  2412. image = camera.Grab();
  2413. image2 = camera.Grab2();
  2414. LogHelper.WriteLogInfo($"采集图像完成;用时:{(DateTime.Now - nowtime).Milliseconds}ms");
  2415. if (image == null || image2 == null)
  2416. {
  2417. SendTaskMessage(Lang.图像采集失败, MessageLevel.Error);
  2418. return (false, null, "图像采集失败");
  2419. }
  2420. return (true, new ICogImage[] { image, image2 }, "成功");
  2421. }
  2422. else
  2423. {
  2424. LogHelper.WriteLogInfo($"采集图像完成;用时:{(DateTime.Now - nowtime).Milliseconds}ms");
  2425. if (image == null)
  2426. {
  2427. SendTaskMessage(Lang.图像采集失败, MessageLevel.Error);
  2428. return (false, null, "图像采集失败");
  2429. }
  2430. if (procedure.PhotoCount > 1)
  2431. {
  2432. if (image2 == null)
  2433. {
  2434. SendTaskMessage(Lang.图像采集失败, MessageLevel.Error);
  2435. return (false, null, "图像采集失败");
  2436. }
  2437. return (true, new ICogImage[] { image, image2 }, "成功");
  2438. }
  2439. return (true, new ICogImage[] { image }, "成功");
  2440. }
  2441. }
  2442. else
  2443. {
  2444. // 1. 采集图像
  2445. var camera = _cameraService.GetCamera(procedure.CameraId);
  2446. if (TempExposureTime != procedure.ExposureTime)
  2447. {
  2448. bool succed1 = camera.SetExposureTime(procedure.ExposureTime);
  2449. if (!succed1)
  2450. {
  2451. SendTaskMessage($"相机曝光设置失败!", MessageLevel.Error);
  2452. }
  2453. else
  2454. {
  2455. TempExposureTime = procedure.ExposureTime;
  2456. }
  2457. }
  2458. //else
  2459. //{
  2460. // SendTaskMessage($"相机曝光重复", MessageLevel.Error);
  2461. //}
  2462. if (TempGain != procedure.Gain)
  2463. {
  2464. bool succed2 = camera.SetGain(procedure.Gain);
  2465. if (!succed2)
  2466. {
  2467. SendTaskMessage($"相机增益设置失败!", MessageLevel.Error);
  2468. }
  2469. else
  2470. {
  2471. TempGain = procedure.Gain;
  2472. }
  2473. }
  2474. //else
  2475. //{
  2476. // SendTaskMessage($"相机增益重复", MessageLevel.Error);
  2477. //}
  2478. DateTime nowtime = DateTime.Now;
  2479. LogHelper.WriteLogInfo("开始采集图像");
  2480. //var image = camera.Grab();
  2481. if (Is3dPhoto == true)
  2482. {
  2483. var image = camera.Grab();
  2484. var image2 = camera.Grab2();
  2485. LogHelper.WriteLogInfo($"采集图像完成;用时:{(DateTime.Now - nowtime).Milliseconds}ms");
  2486. if (image == null || image2 == null)
  2487. {
  2488. SendTaskMessage(Lang.图像采集失败, MessageLevel.Error);
  2489. return (false, null, "图像采集失败");
  2490. }
  2491. return (true, new ICogImage[] { image, image2 }, "成功");
  2492. }
  2493. else
  2494. {
  2495. var image = camera.Grab();
  2496. LogHelper.WriteLogInfo($"采集图像完成;用时:{(DateTime.Now - nowtime).Milliseconds}ms");
  2497. if (image == null)
  2498. {
  2499. SendTaskMessage(Lang.图像采集失败, MessageLevel.Error);
  2500. return (false, null, "图像采集失败");
  2501. }
  2502. return (true, new ICogImage[] { image }, "成功");
  2503. }
  2504. }
  2505. }
  2506. catch (Exception ex)
  2507. {
  2508. LogHelper.WriteLogError("采集图像失败!", ex);
  2509. return (false, null, "图像采集失败");
  2510. }
  2511. }
  2512. /// <summary>
  2513. /// 执行相机拍照获取单个点位结果
  2514. /// </summary>
  2515. /// <param name="procedure"></param>
  2516. /// <param name="InputTerminal"></param>
  2517. /// <param name="robotCoord"></param>
  2518. /// <param name="cancellationToken"></param>
  2519. /// <returns></returns>
  2520. public async Task<(bool IsSucceed, string[] Items, double Count)> ExecutePhotoGetSinglePoint1(ProcedureModel procedure, ICogImage[] imges, Dictionary<string, string> InputTerminal, double[] robotCoord, CancellationToken cancellationToken, bool is3dmodel, float confThreshold = 0.25f, float iouThreshold = 0.45f)
  2521. {
  2522. DateTime nowtime = DateTime.Now;
  2523. try
  2524. {
  2525. //拍照失败时,需要多次拍照
  2526. //for (int i = 0; i < procedure.FeederFailLimit; i++)
  2527. for (int i = 0; i < 1; i++)
  2528. {
  2529. SendTaskMessage(Lang.开始执行视觉流程.Replace("{0}", $"{i + 1}").Replace("{1}", procedure.Name), MessageLevel.Info);
  2530. // 1. 执行相机拍照并运行视觉工具
  2531. bool visionSucceed = ExecutePhoto(procedure, imges, InputTerminal, out CogToolBlockTerminalCollection outputCollection, is3dmodel, confThreshold, iouThreshold);
  2532. if (!visionSucceed)
  2533. {
  2534. SendTaskMessage(Lang.视觉任务执行失败, MessageLevel.Error);
  2535. continue;
  2536. }
  2537. if (!outputCollection.Contains("Found"))
  2538. {
  2539. SendTaskMessage(Lang.未找到视觉输出结果, MessageLevel.Error);
  2540. return (false, null, 0);
  2541. }
  2542. // 2. 获取视觉输出结果
  2543. //bool Found = (bool)(outputCollection["Found"].Value);
  2544. //if (!Found)
  2545. //{
  2546. // SendTaskMessage(Lang.拍照NG, MessageLevel.Debug);
  2547. // continue;
  2548. //}
  2549. //SendTaskMessage(Lang.拍照OK, MessageLevel.Debug);
  2550. int Count = (int)(outputCollection["Count"].Value);
  2551. string[] PhotoRes = new string[100];
  2552. for (int k = 1; k <= Count; k++)
  2553. {
  2554. PhotoRes[k] = (string)(outputCollection[$"dis{k}"].Value);
  2555. //PhotoRes[k] = "222";
  2556. }
  2557. // 3. 获取视觉输出结果
  2558. LogHelper.WriteLogInfo("开始获取视觉输出结果");
  2559. return (true, PhotoRes, Count);
  2560. }
  2561. SendTaskMessage(Lang.多次拍照失败, MessageLevel.Alarm);
  2562. return (false, null, 0);
  2563. }
  2564. catch (Exception ex)
  2565. {
  2566. LogHelper.WriteLogError("执行相机取图并获取单点位时出错!", ex);
  2567. return (false, null, 0);
  2568. }
  2569. finally
  2570. {
  2571. var sysConfig = _configService.GetSystemConfiguration();
  2572. if (sysConfig.TurnOffAllLightUse == false)
  2573. {
  2574. await TurnOffLightAfterPhoto(procedure);
  2575. }
  2576. }
  2577. }
  2578. /// <summary>
  2579. /// 执行相机拍照获取单个点位结果
  2580. /// </summary>
  2581. /// <param name="procedure"></param>
  2582. /// <param name="InputTerminal"></param>
  2583. /// <param name="robotCoord"></param>
  2584. /// <param name="cancellationToken"></param>
  2585. /// <returns></returns>
  2586. public async Task<(bool IsSucceed, string X, double Y, double U)> ExecutePhotoGetSinglePoint2(ProcedureModel procedure, Dictionary<string, string> InputTerminal, double[] robotCoord, CancellationToken cancellationToken)
  2587. {
  2588. DateTime nowtime = DateTime.Now;
  2589. var sysConfig = _configService.GetSystemConfiguration();
  2590. if (sysConfig.TurnOnAllLightUse == false)
  2591. {
  2592. await SetLightBeforePhoto(procedure);
  2593. }
  2594. try
  2595. {
  2596. //拍照失败时,需要多次拍照
  2597. for (int i = 0; i < procedure.FeederFailLimit; i++)
  2598. {
  2599. SendTaskMessage(Lang.开始执行视觉流程.Replace("{0}", $"{i + 1}").Replace("{1}", procedure.Name), MessageLevel.Info);
  2600. // 1. 执行相机拍照并运行视觉工具
  2601. bool visionSucceed = ExecutePhoto2(procedure, InputTerminal, out CogToolBlockTerminalCollection outputCollection);
  2602. if (!visionSucceed)
  2603. {
  2604. SendTaskMessage(Lang.视觉任务执行失败, MessageLevel.Error);
  2605. continue;
  2606. }
  2607. if (!outputCollection.Contains("Found"))
  2608. {
  2609. SendTaskMessage(Lang.未找到视觉输出结果, MessageLevel.Error);
  2610. return (false, null, 0, 0);
  2611. }
  2612. // 2. 获取视觉输出结果
  2613. bool Found = (bool)(outputCollection["Found"].Value);
  2614. if (!Found)
  2615. {
  2616. SendTaskMessage(Lang.拍照NG, MessageLevel.Debug);
  2617. continue;
  2618. }
  2619. string SnCode = (string)(outputCollection["SnCode"].Value);
  2620. SendTaskMessage(Lang.拍照OK, MessageLevel.Debug);
  2621. // 3. 获取视觉输出结果
  2622. LogHelper.WriteLogInfo("开始获取视觉输出结果");
  2623. /*
  2624. //获取相机校准
  2625. var calib = _calibrationService.GetCalibration(procedure.CalibrationId);
  2626. string points = (string)(outputCollection["Point"].Value);
  2627. string[] strpoints = points.Split(';');
  2628. //先将pos按照逗号进行分隔,拿到数组
  2629. var posParts = strpoints[0].Split(',');
  2630. double _pixel_x = double.Parse(posParts[0]);
  2631. double _pixel_y = double.Parse(posParts[1]);
  2632. double _pixel_u = double.Parse(posParts[2]);
  2633. //转换点位-像素转换成机器人绝对坐标
  2634. var calibResult = _calibrationService.ConvertPixelToPosition((_pixel_x, _pixel_y, _pixel_u), robotCoord, calib, RobotBrand.XYZ_Platform);
  2635. if (!calibResult.IsSucceed)
  2636. {
  2637. return (false, 0, 0, 0);
  2638. }
  2639. return (true, calibResult.X, calibResult.Y, calibResult.U);
  2640. */
  2641. return (true, SnCode, 0, 0);
  2642. }
  2643. SendTaskMessage(Lang.多次拍照失败, MessageLevel.Alarm);
  2644. return (false, null, 0, 0);
  2645. }
  2646. catch (Exception ex)
  2647. {
  2648. LogHelper.WriteLogError("执行相机取图并获取单点位时出错!", ex);
  2649. return (false, null, 0, 0);
  2650. }
  2651. finally
  2652. {
  2653. if (sysConfig.TurnOffAllLightUse == false)
  2654. {
  2655. await TurnOffLightAfterPhoto(procedure);
  2656. }
  2657. }
  2658. }
  2659. /// <summary>
  2660. /// 执行相机拍照并运行 ToolBlock,返回是否成功并通过 out 参数返回 Outputs、图像和图形集合。
  2661. /// </summary>
  2662. /// <param name="procedure"></param>
  2663. /// <param name="InputTerminal"></param>
  2664. /// <param name="outputCollection"></param>
  2665. /// <param name="outImage"></param>
  2666. /// <param name="outGraphicCollection"></param>
  2667. /// <returns></returns>
  2668. public bool ExecutePhotoEx(ProcedureModel procedure, Dictionary<string, string> InputTerminal, out CogToolBlockTerminalCollection outputCollection, out ICogImage outImage, out CogGraphicCollection outGraphicCollection)
  2669. {
  2670. outImage = null;
  2671. outGraphicCollection = null;
  2672. try
  2673. {
  2674. // 1. 采集图像
  2675. var camera = _cameraService.GetCamera(procedure.CameraId);
  2676. bool succed = camera.SetExposureTime(procedure.ExposureTime);
  2677. if (!succed)
  2678. {
  2679. SendTaskMessage($"相机曝光设置失败!", MessageLevel.Error);
  2680. }
  2681. succed = camera.SetGain(procedure.Gain);
  2682. if (!succed)
  2683. {
  2684. SendTaskMessage($"相机增益设置失败!", MessageLevel.Error);
  2685. }
  2686. DateTime nowtime = DateTime.Now;
  2687. LogHelper.WriteLogInfo("开始采集图像");
  2688. var image = camera.Grab();
  2689. if (image == null)
  2690. {
  2691. SendTaskMessage(Lang.图像采集失败, MessageLevel.Error);
  2692. outputCollection = null;
  2693. return false;
  2694. }
  2695. outImage = image;
  2696. procedure.ToolBlock.Inputs["InputImage"].Value = image;
  2697. LogHelper.WriteLogInfo($"采集图像完成;用时:{(DateTime.Now - nowtime).Milliseconds}ms");
  2698. // 2. 为ToolBlock传入其他输入终端
  2699. if (InputTerminal != null)
  2700. {
  2701. LogHelper.WriteLogInfo($"为ToolBlock传入输入终端");
  2702. foreach (var item in InputTerminal)
  2703. {
  2704. if (procedure.ToolBlock.Inputs.Contains(item.Key))
  2705. {
  2706. LogHelper.WriteLogInfo($"传入[{item.Key}]={item.Value}");
  2707. procedure.ToolBlock.Inputs[item.Key].Value = item.Value;
  2708. }
  2709. else
  2710. {
  2711. LogHelper.WriteLogInfo($"创建并传入[{item.Key}]={item.Value}");
  2712. procedure.ToolBlock.Inputs.Add(new CogToolBlockTerminal(item.Key, item.Value));
  2713. }
  2714. }
  2715. }
  2716. // 3. 运行视觉工具
  2717. LogHelper.WriteLogInfo("开始运行视觉工具");
  2718. procedure.ToolBlock.Run(); //运行ToolBlock
  2719. if (procedure.ToolBlock.RunStatus.Result == CogToolResultConstants.Accept)
  2720. {
  2721. SendTaskMessage(Lang.视觉流程执行耗时.Replace("{0}", procedure.Name).Replace("{1}", $"{procedure.ToolBlock.RunStatus.ProcessingTime:F1}"), MessageLevel.Info);
  2722. outputCollection = procedure.ToolBlock.Outputs; //获取输出终端集合
  2723. DatabaseHelper.AddCameraRecords(_productService.GetCurrentProduct().Name, procedure.Name, outputCollection);
  2724. ICogRecord record = null;
  2725. foreach (CogToolBlockTerminal item in outputCollection)
  2726. {
  2727. if (item.Value is ICogRecord)
  2728. record = item.Value as ICogRecord;
  2729. }
  2730. outGraphicCollection = outputCollection["Graphic"].Value as CogGraphicCollection;
  2731. return true;
  2732. }
  2733. else
  2734. {
  2735. SendTaskMessage(Lang.视觉流程执行出错耗时.Replace("{0}", procedure.Name).Replace("{1}", $"{procedure.ToolBlock.RunStatus.ProcessingTime:F1}"), MessageLevel.Error);
  2736. SendTaskMessage(procedure.ToolBlock.RunStatus.Message, MessageLevel.Error);
  2737. outputCollection = null;
  2738. outGraphicCollection = outputCollection["Graphic"].Value as CogGraphicCollection;
  2739. return false;
  2740. }
  2741. }
  2742. catch (Exception ex)
  2743. {
  2744. SendTaskMessage(ex.Message, MessageLevel.Error);
  2745. LogHelper.WriteLogError("执行相机取图并执行视觉工具组时出错!", ex);
  2746. outputCollection = null;
  2747. return false;
  2748. }
  2749. }
  2750. /// <summary>
  2751. /// 执行相机拍照获取单个点位结果
  2752. /// </summary>
  2753. /// <param name="procedure"></param>
  2754. /// <param name="InputTerminal"></param>
  2755. /// <param name="robotCoord"></param>
  2756. /// <param name="cancellationToken"></param>
  2757. /// <returns></returns>
  2758. public async Task<(bool IsSucceed, double X, double Y, double U)> ExecutePhotoGetSinglePoint(ProcedureModel procedure, Dictionary<string, string> InputTerminal, double[] robotCoord, CancellationToken cancellationToken)
  2759. {
  2760. DateTime nowtime = DateTime.Now;
  2761. await SetLightBeforePhoto(procedure);
  2762. try
  2763. {
  2764. //拍照失败时,需要多次拍照
  2765. //for (int i = 0; i < procedure.FeederFailLimit; i++)
  2766. for (int i = 0; i < 1; i++)
  2767. {
  2768. SendTaskMessage(Lang.开始执行视觉流程.Replace("{0}", $"{i + 1}").Replace("{1}", procedure.Name), MessageLevel.Info);
  2769. //1.执行相机拍照并运行视觉工具
  2770. bool visionSucceed = ExecutePhoto(procedure, InputTerminal, out CogToolBlockTerminalCollection outputCollection);
  2771. if (!visionSucceed)
  2772. {
  2773. SendTaskMessage(Lang.视觉任务执行失败, MessageLevel.Error);
  2774. continue;
  2775. }
  2776. if (!outputCollection.Contains("Found"))
  2777. {
  2778. SendTaskMessage(Lang.未找到视觉输出结果, MessageLevel.Error);
  2779. return (false, 0, 0, 0);
  2780. }
  2781. // 2. 获取视觉输出结果
  2782. bool Found = (bool)(outputCollection["Found"].Value);
  2783. if (!Found)
  2784. {
  2785. SendTaskMessage(Lang.拍照NG, MessageLevel.Debug);
  2786. continue;
  2787. }
  2788. SendTaskMessage(Lang.拍照OK, MessageLevel.Debug);
  2789. //// 3. 获取视觉输出结果
  2790. //LogHelper.WriteLogInfo("开始获取视觉输出结果");
  2791. ////获取相机校准
  2792. //var calib = _calibrationService.GetCalibration(procedure.CalibrationId);
  2793. //string points = (string)(outputCollection["Point"].Value);
  2794. //string[] strpoints = points.Split(';');
  2795. ////先将pos按照逗号进行分隔,拿到数组
  2796. //var posParts = strpoints[0].Split(',');
  2797. //double _pixel_x = double.Parse(posParts[0]);
  2798. //double _pixel_y = double.Parse(posParts[1]);
  2799. //double _pixel_u = double.Parse(posParts[2]);
  2800. ////转换点位-像素转换成机器人绝对坐标
  2801. //var calibResult = _calibrationService.ConvertPixelToPosition((_pixel_x, _pixel_y, _pixel_u), robotCoord, calib, RobotBrand.XYZ_Platform);
  2802. //if (!calibResult.IsSucceed)
  2803. //{
  2804. // return (false, 0, 0, 0);
  2805. //}
  2806. return (true, 0, 0, 0);
  2807. }
  2808. SendTaskMessage(Lang.多次拍照失败, MessageLevel.Alarm);
  2809. return (false, 0, 0, 0);
  2810. }
  2811. catch (Exception ex)
  2812. {
  2813. LogHelper.WriteLogError("执行相机取图并获取单点位时出错!", ex);
  2814. return (false, 0, 0, 0);
  2815. }
  2816. finally
  2817. {
  2818. await TurnOffLightAfterPhoto(procedure);
  2819. }
  2820. }
  2821. /// <summary>
  2822. /// 执行相机拍照获取单个点位结果
  2823. /// </summary>
  2824. /// <param name="procedure"></param>
  2825. /// <param name="InputTerminal"></param>
  2826. /// <param name="robotCoord"></param>
  2827. /// <param name="cancellationToken"></param>
  2828. /// <returns></returns>
  2829. public async Task<(bool IsSucceed, string[] Items, double Count)> ExecutePhotoGetSinglePoint1(ProcedureModel procedure, Dictionary<string, string> InputTerminal, double[] robotCoord, CancellationToken cancellationToken)
  2830. {
  2831. DateTime nowtime = DateTime.Now;
  2832. var sysConfig = _configService.GetSystemConfiguration();
  2833. if (sysConfig.TurnOnAllLightUse == false)
  2834. {
  2835. await SetLightBeforePhoto(procedure);
  2836. }
  2837. try
  2838. {
  2839. //拍照失败时,需要多次拍照
  2840. //for (int i = 0; i < procedure.FeederFailLimit; i++)
  2841. for (int i = 0; i < 1; i++)
  2842. {
  2843. SendTaskMessage(Lang.开始执行视觉流程.Replace("{0}", $"{i + 1}").Replace("{1}", procedure.Name), MessageLevel.Info);
  2844. // 1. 执行相机拍照并运行视觉工具
  2845. bool visionSucceed = ExecutePhoto(procedure, InputTerminal, out CogToolBlockTerminalCollection outputCollection);
  2846. if (!visionSucceed)
  2847. {
  2848. SendTaskMessage(Lang.视觉任务执行失败, MessageLevel.Error);
  2849. continue;
  2850. }
  2851. //if (!outputCollection.Contains("Found"))
  2852. //{
  2853. // SendTaskMessage(Lang.未找到视觉输出结果, MessageLevel.Error);
  2854. // return (false, null, 0);
  2855. //}
  2856. // 2. 获取视觉输出结果
  2857. //bool Found = (bool)(outputCollection["Found"].Value);
  2858. //if (!Found)
  2859. //{
  2860. // SendTaskMessage(Lang.拍照NG, MessageLevel.Debug);
  2861. // continue;
  2862. //}
  2863. SendTaskMessage(Lang.拍照OK, MessageLevel.Debug);
  2864. int Count = (int)(outputCollection["Count"].Value);
  2865. string[] PhotoRes = new string[100];
  2866. for (int k = 1; k <= Count; k++)
  2867. {
  2868. PhotoRes[k] = (string)(outputCollection[$"dis{k}"].Value);
  2869. //PhotoRes[k] = "222";
  2870. }
  2871. // 3. 获取视觉输出结果
  2872. LogHelper.WriteLogInfo("开始获取视觉输出结果");
  2873. /*
  2874. //获取相机校准
  2875. var calib = _calibrationService.GetCalibration(procedure.CalibrationId);
  2876. string points = (string)(outputCollection["Point"].Value);
  2877. string[] strpoints = points.Split(';');
  2878. //先将pos按照逗号进行分隔,拿到数组
  2879. var posParts = strpoints[0].Split(',');
  2880. double _pixel_x = double.Parse(posParts[0]);
  2881. double _pixel_y = double.Parse(posParts[1]);
  2882. double _pixel_u = double.Parse(posParts[2]);
  2883. //转换点位-像素转换成机器人绝对坐标
  2884. var calibResult = _calibrationService.ConvertPixelToPosition((_pixel_x, _pixel_y, _pixel_u), robotCoord, calib, RobotBrand.XYZ_Platform);
  2885. if (!calibResult.IsSucceed)
  2886. {
  2887. return (false, 0, 0, 0);
  2888. }
  2889. return (true, calibResult.X, calibResult.Y, calibResult.U);
  2890. */
  2891. return (true, PhotoRes, Count);
  2892. }
  2893. SendTaskMessage(Lang.多次拍照失败, MessageLevel.Alarm);
  2894. return (false, null, 0);
  2895. }
  2896. catch (Exception ex)
  2897. {
  2898. LogHelper.WriteLogError("执行相机取图并获取单点位时出错!", ex);
  2899. return (false, null, 0);
  2900. }
  2901. finally
  2902. {
  2903. //await TurnOffLightAfterPhoto(procedure);
  2904. }
  2905. }
  2906. /// <summary>
  2907. /// 执行相机拍照获取单个点位结果,并且返回图像和图形
  2908. /// </summary>
  2909. /// <param name="procedure"></param>
  2910. /// <param name="InputTerminal"></param>
  2911. /// <param name="robotCoord"></param>
  2912. /// <param name="cancellationToken"></param>
  2913. /// <returns></returns>
  2914. public async Task<(bool IsSucceed, double X, double Y, double U, ICogImage Image, CogGraphicCollection Graphic)> ExecutePhotoGetSinglePointWithImage(ProcedureModel procedure, Dictionary<string, string> InputTerminal, double[] robotCoord, CancellationToken cancellationToken)
  2915. {
  2916. DateTime nowtime = DateTime.Now;
  2917. await SetLightBeforePhoto(procedure);
  2918. ICogImage outImage = null;
  2919. CogGraphicCollection outGraphicCollection = null;
  2920. try
  2921. {
  2922. //拍照失败时,需要多次拍照
  2923. for (int i = 0; i < procedure.FeederFailLimit; i++)
  2924. {
  2925. SendTaskMessage(Lang.开始执行视觉流程.Replace("{0}", $"{i + 1}").Replace("{1}", procedure.Name), MessageLevel.Info);
  2926. // 1. 执行相机拍照并运行视觉工具
  2927. bool visionSucceed = ExecutePhotoEx(procedure, InputTerminal, out CogToolBlockTerminalCollection outputCollection, out outImage, out outGraphicCollection);
  2928. if (!visionSucceed)
  2929. {
  2930. SendTaskMessage(Lang.视觉任务执行失败, MessageLevel.Error);
  2931. continue;
  2932. }
  2933. if (!outputCollection.Contains("Found"))
  2934. {
  2935. SendTaskMessage(Lang.未找到视觉输出结果, MessageLevel.Error);
  2936. return (false, 0, 0, 0, outImage, outGraphicCollection);
  2937. }
  2938. // 2. 获取视觉输出结果
  2939. bool Found = (bool)(outputCollection["Found"].Value);
  2940. if (!Found)
  2941. {
  2942. SendTaskMessage(Lang.拍照NG, MessageLevel.Debug);
  2943. continue;
  2944. }
  2945. SendTaskMessage(Lang.拍照OK, MessageLevel.Debug);
  2946. // 3. 获取视觉输出结果
  2947. LogHelper.WriteLogInfo("开始获取视觉输出结果");
  2948. //获取相机校准
  2949. var calib = _calibrationService.GetCalibration(procedure.CalibrationId);
  2950. string points = (string)(outputCollection["Point"].Value);
  2951. string[] strpoints = points.Split(';');
  2952. //先将pos按照逗号进行分隔,拿到数组
  2953. var posParts = strpoints[0].Split(',');
  2954. double _pixel_x = double.Parse(posParts[0]);
  2955. double _pixel_y = double.Parse(posParts[1]);
  2956. double _pixel_u = double.Parse(posParts[2]);
  2957. //转换点位-像素转换成机器人绝对坐标
  2958. var calibResult = _calibrationService.ConvertPixelToPosition((_pixel_x, _pixel_y, _pixel_u), robotCoord, calib, RobotBrand.XYZ_Platform);
  2959. if (!calibResult.IsSucceed)
  2960. {
  2961. return (false, 0, 0, 0, outImage, outGraphicCollection);
  2962. }
  2963. return (true, calibResult.X, calibResult.Y, calibResult.U, outImage, outGraphicCollection);
  2964. }
  2965. SendTaskMessage(Lang.多次拍照失败, MessageLevel.Alarm);
  2966. return (false, 0, 0, 0, outImage, outGraphicCollection);
  2967. }
  2968. catch (Exception ex)
  2969. {
  2970. LogHelper.WriteLogError("执行相机取图并获取单点位时出错!", ex);
  2971. return (false, 0, 0, 0, outImage, outGraphicCollection);
  2972. }
  2973. finally
  2974. {
  2975. await TurnOffLightAfterPhoto(procedure);
  2976. }
  2977. }
  2978. /// <summary>
  2979. /// 从 ToolBlock 的输出集合中根据 Procedure 配置提取需要发送的输出项并做必要的坐标转换。
  2980. /// 返回元组:是否成功、错误信息(失败时)和名称->(是否点位, 值) 的字典。
  2981. /// </summary>
  2982. public (bool IsSucceed, string ErrMsg, Dictionary<string, (bool IsPoint, object Value)> Output) GetVisionOutput(ProcedureModel procedure, CogToolBlockTerminalCollection outputCollection, double[] robotPos)
  2983. {
  2984. RobotBrand robotBrand = RobotBrand.Default;
  2985. var robot = _configService.GetRobot(procedure.RobotId);
  2986. if (robot != null)
  2987. {
  2988. robotBrand = robot.RobotBrand;
  2989. }
  2990. List<string> SendResults = new List<string>();
  2991. Dictionary<string, (bool IsPoint, object Value)> ResultCollection = new Dictionary<string, (bool IsPoint, object Value)>();
  2992. foreach (var output in procedure.ProcedureOutputs)
  2993. {
  2994. //根据输出类型进行区分输出
  2995. if (output.ValueType == typeof(string))
  2996. {
  2997. //需要点位转换时,进行点位提取
  2998. if (output.IsPointTran)
  2999. {
  3000. if (outputCollection[output.Name].Value == null || string.IsNullOrEmpty(outputCollection[output.Name].Value.ToString()))
  3001. {
  3002. //如果需要输出的项的值为空,即点位数据为空,则输出点位的个数为0
  3003. ResultCollection.Add(output.Name, (true, null));
  3004. continue;
  3005. }
  3006. string[] strpoints = outputCollection[output.Name].Value.ToString().Split(';');
  3007. //存储当前输出点位集合
  3008. List<string[]> currentPointsForFeeder = new List<string[]>();
  3009. //获取相机校准
  3010. var calib = _calibrationService.GetCalibration(procedure.CalibrationId);
  3011. if (calib == null)
  3012. {
  3013. SendTaskMessage(Lang.没有相机校准信息, MessageLevel.Alarm);
  3014. return (false, "NotCalibrations", null);
  3015. }
  3016. // 判断相机安装方式,如果是J4移动相机或者XYZ平台时,则需要判断robotPos不能为null
  3017. if ((calib.CameraMount == CameraMount.MobileJ4 || calib.CameraMount == CameraMount.MobileDown_XYPlatform) && robotPos == null)
  3018. {
  3019. SendTaskMessage(Lang.机器人当前位置不能为空, MessageLevel.Alarm);
  3020. return (false, "RobotPositionNull", null);
  3021. }
  3022. List<string> SendDtat = new List<string>();
  3023. List<string> points = new List<string>();
  3024. //遍历所有的输出点位
  3025. foreach (var pos in strpoints)
  3026. {
  3027. //先将pos按照逗号进行分隔,拿到数组,判断是否至少包含3个元素,并且前三个元素可以转换为double,确保是有效的点位数据
  3028. if (string.IsNullOrEmpty(pos))
  3029. {
  3030. continue;
  3031. }
  3032. //先将pos按照逗号进行分隔,拿到数组
  3033. var posParts = pos.Split(',');
  3034. if (posParts.Length < 3 ||
  3035. !double.TryParse(posParts[0], out double _pixel_x) ||
  3036. !double.TryParse(posParts[1], out double _pixel_y) ||
  3037. !double.TryParse(posParts[2], out double _pixel_u))
  3038. {
  3039. SendTaskMessage(string.Format(Lang.点位数据格式错误, pos), MessageLevel.Alarm);
  3040. return (false, "PointDataFormatError", null);
  3041. }
  3042. //转换点位-像素转换成机器人绝对坐标
  3043. var calibResult = _calibrationService.ConvertPixelToPosition((_pixel_x, _pixel_y, _pixel_u), robotPos, calib, robotBrand);
  3044. if (!calibResult.IsSucceed)
  3045. {
  3046. return (false, "CalibrationFailed", null);
  3047. }
  3048. //截取posParts数组从索引3开始到结尾的所有元素,得到新新的数组extraInfoArray
  3049. string[] extraInfoArray = posParts.Skip(3).ToArray();
  3050. //将rpos转换为字符串数组,保留3位小数
  3051. string[] strings = new string[] { $"{calibResult.X:F3}", $"{calibResult.Y:F3}", $"{calibResult.U:F3}" };
  3052. List<string> rposString = new List<string>(strings);
  3053. if (extraInfoArray.Length > 0)
  3054. {
  3055. rposString.AddRange(extraInfoArray);
  3056. }
  3057. currentPointsForFeeder.Add(rposString.ToArray());
  3058. }
  3059. ResultCollection[output.Name] = (true, currentPointsForFeeder);
  3060. }
  3061. //直接输出字符串
  3062. else
  3063. {
  3064. if (outputCollection[output.Name].Value == null || string.IsNullOrEmpty(outputCollection[output.Name].Value.ToString()))
  3065. {
  3066. ResultCollection.Add(output.Name, (false, null));
  3067. continue;
  3068. }
  3069. ResultCollection[output.Name] = (false, outputCollection[output.Name].Value.ToString());
  3070. }
  3071. }
  3072. else
  3073. {
  3074. if (outputCollection[output.Name].Value == null)
  3075. {
  3076. ResultCollection.Add(output.Name, (false, null));
  3077. }
  3078. else
  3079. {
  3080. ResultCollection[output.Name] = (false, outputCollection[output.Name].Value.ToString());
  3081. }
  3082. }
  3083. }
  3084. return (true, string.Empty, ResultCollection);
  3085. }
  3086. /// <summary>
  3087. /// 拍照前针对 Feeder 的准备动作:设置灯、必要时供料或振动等。
  3088. /// </summary>
  3089. public async Task ExecuteFeederForPhotoBefore(IVoiceCoilMotorFeeder Feeder, ProcedureModel procedure, bool doVibrateFirst, bool doCaptureFirst, CancellationToken cancellationToken)
  3090. {
  3091. // 1. 设置Feeder光源亮度、打开光源
  3092. if (Feeder.FeederBrand == FeederBrand.AFAG)
  3093. {
  3094. await Feeder.SetLightValueAsync((ushort)procedure.LightValue);
  3095. }
  3096. else
  3097. {
  3098. //Feeder光源亮度设置
  3099. if (procedure.LightValue > 3)
  3100. {
  3101. var light = await Feeder.GetLightBrightnessAsync();
  3102. if (procedure.LightValue != light)
  3103. {
  3104. await Feeder.SetLightValueAsync((ushort)procedure.LightValue);
  3105. }
  3106. //获取光源的超时时间
  3107. int lightTimeout = await Feeder.GetLightTimeoutAsync();
  3108. if (lightTimeout < 10000)
  3109. {
  3110. await Feeder.SetLightTimeOutAsync(10000);
  3111. }
  3112. //打开光源
  3113. await Feeder.OpenLightAsync();
  3114. }
  3115. }
  3116. if (doCaptureFirst)//如果不振动,等待光源稳定时间
  3117. {
  3118. if (procedure.WaitPhoto > 0) await Task.Delay(procedure.WaitPhoto);
  3119. return;
  3120. }
  3121. //先振后拍时
  3122. if (procedure.VibrationModel == VibrationModel.VibrationPhoto || doVibrateFirst)
  3123. {
  3124. if (procedure.FeederWorks != null && procedure.FeederWorks.FeederWorkList != null)
  3125. {
  3126. bool flog = false;
  3127. //如果上次的Blob面积小于设定的最小值,则触发供料
  3128. if (procedure.LastBlobArea <= procedure.MinArea)
  3129. {
  3130. flog = true;
  3131. SendTaskMessage(Lang.执行料仓供料, MessageLevel.Info);
  3132. await ExecuteFeederStockWorks(Feeder, procedure.FeederStockWorks, cancellationToken);
  3133. if (procedure.WaitFeederStop > 0) await Task.Delay(procedure.WaitFeederStop);
  3134. SendTaskMessage(Lang.料仓供料结束, MessageLevel.Info);
  3135. }
  3136. if (!flog)
  3137. {
  3138. //执行配置的Feeder振动任务
  3139. await ExecuteFeederWorks(Feeder, procedure.FeederWorks, cancellationToken, false);
  3140. if (procedure.WaitFeederStop > 0) await Task.Delay(procedure.WaitFeederStop);
  3141. }
  3142. }
  3143. }
  3144. else
  3145. {
  3146. if (procedure.LightValue > 3)
  3147. {
  3148. if (procedure.WaitPhoto > 0) await Task.Delay(procedure.WaitPhoto);
  3149. }
  3150. //如果上次的Blob面积小于设定的最小值,则触发供料
  3151. if (procedure.LastBlobArea <= procedure.MinArea)
  3152. {
  3153. SendTaskMessage(Lang.执行料仓供料, MessageLevel.Info);
  3154. await ExecuteFeederStockWorks(Feeder, procedure.FeederStockWorks, cancellationToken);
  3155. if (procedure.WaitFeederStop > 0) await Task.Delay(procedure.WaitFeederStop);
  3156. SendTaskMessage(Lang.料仓供料结束, MessageLevel.Info);
  3157. }
  3158. }
  3159. }
  3160. /// <summary>
  3161. /// 拍照后在 NG 情况下的 Feeder 后处理,例如供料或振动。
  3162. /// </summary>
  3163. public async Task ExecuteFeederForPhotoLater(IVoiceCoilMotorFeeder Feeder, ProcedureModel procedure, CancellationToken cancellationToken)
  3164. {
  3165. //根据斑点面积决定是否料仓供料
  3166. if (procedure.LastBlobArea <= procedure.MinArea)
  3167. {
  3168. SendTaskMessage(Lang.执行料仓供料, MessageLevel.Info);
  3169. await ExecuteFeederStockWorks(Feeder, procedure.FeederStockWorks, cancellationToken);
  3170. if (cancellationToken != null && cancellationToken.IsCancellationRequested) return;
  3171. if (procedure.WaitFeederStop > 0) await Task.Delay(procedure.WaitFeederStop, cancellationToken);
  3172. SendTaskMessage(Lang.料仓供料结束, MessageLevel.Info);
  3173. }
  3174. else
  3175. {
  3176. if (procedure.FeederWorks != null && procedure.FeederWorks.FeederWorkList != null)
  3177. {
  3178. SendTaskMessage(Lang.执行Feeder振动, MessageLevel.Info);
  3179. //执行配置的Feeder振动任务
  3180. await ExecuteFeederWorks(Feeder, procedure.FeederWorks, cancellationToken);
  3181. if (cancellationToken != null && cancellationToken.IsCancellationRequested) return;
  3182. if (procedure.WaitFeederStop > 0) await Task.Delay(procedure.WaitFeederStop, cancellationToken);
  3183. SendTaskMessage(Lang.Feeder振动结束, MessageLevel.Info);
  3184. }
  3185. }
  3186. }
  3187. /// <summary>
  3188. /// 并行执行料仓供料和振动任务。
  3189. /// </summary>
  3190. public async Task ExecuteFeederStockWorks(IVoiceCoilMotorFeeder feeder, FeederStockWorks works, CancellationToken cancellationToken, bool isUpdateParame = true)
  3191. {
  3192. //同时执行料仓供料和Feeder振动任务
  3193. var stockTask = ExecuteFeederStockWorksOnly(feeder, works.FeederStockWorkList.ToArray(), cancellationToken);
  3194. var vibrationTask = ExecuteFeederWorkOnly(feeder, works.FeederWorkList.ToArray(), cancellationToken);
  3195. await Task.WhenAll(stockTask, vibrationTask);
  3196. }
  3197. /// <summary>
  3198. /// 执行料仓振动任务序列(仅料仓相关动作)。
  3199. /// </summary>
  3200. public async Task ExecuteFeederStockWorksOnly(IVoiceCoilMotorFeeder feeder, FeederStockWork[] works, CancellationToken cancellationToken)
  3201. {
  3202. //执行配置的料仓振动任务
  3203. if (feeder.FeederBrand == FeederBrand.AFAG)
  3204. {
  3205. foreach (var stockwork in works)
  3206. {
  3207. if (stockwork.RegisterIndex == 0)
  3208. {
  3209. if (stockwork.Duration > 0) await Task.Delay(stockwork.Duration, cancellationToken);
  3210. }
  3211. else if (stockwork.RegisterIndex == 1)
  3212. {
  3213. // 保留原注释的位置给 Modbus 操作
  3214. }
  3215. if (cancellationToken != null && cancellationToken.IsCancellationRequested)
  3216. {
  3217. return;
  3218. }
  3219. }
  3220. }
  3221. else
  3222. {
  3223. foreach (var stockwork in works)
  3224. {
  3225. if (stockwork.Function == VibrationFunction.Delay)
  3226. {
  3227. if (stockwork.Duration > 0) await Task.Delay(stockwork.Duration, cancellationToken);
  3228. }
  3229. else
  3230. {
  3231. await feeder.OutputAsync(((int)stockwork.Function) + 1, stockwork.Duration);
  3232. if (stockwork.Duration > 0) await Task.Delay(stockwork.Duration, cancellationToken);
  3233. }
  3234. if (cancellationToken != null && cancellationToken.IsCancellationRequested)
  3235. {
  3236. return;
  3237. }
  3238. }
  3239. }
  3240. }
  3241. /// <summary>
  3242. /// 执行单独的 Feeder 振动动作序列(仅振动相关)。
  3243. /// </summary>
  3244. public async Task ExecuteFeederWorkOnly(IVoiceCoilMotorFeeder feeder, FeederWork[] works, CancellationToken cancellationToken, bool isUpdateParame = true)
  3245. {
  3246. if (works == null)
  3247. {
  3248. return;
  3249. }
  3250. if (feeder.FeederBrand == FeederBrand.AFAG)
  3251. {
  3252. //执行配置的Feeder振动任务
  3253. foreach (var feederwork in works)
  3254. {
  3255. if (feederwork.ConfigIndex < 0)
  3256. {
  3257. continue;
  3258. }
  3259. if (feederwork.ConfigIndex == 0)
  3260. {
  3261. if (feederwork.Duration > 0) await Task.Delay(feederwork.Duration, cancellationToken);
  3262. }
  3263. else
  3264. {
  3265. ((AfagFeeder)feeder).LoadConfiguration(feederwork.ConfigIndex);
  3266. ((AfagFeeder)feeder).SetIntensity(feederwork.Intensity);
  3267. ((AfagFeeder)feeder).SetDirection(feederwork.Direction);
  3268. if (feederwork.Duration > 0) await Task.Delay(feederwork.Duration, cancellationToken);
  3269. if (cancellationToken != null && cancellationToken.IsCancellationRequested)
  3270. {
  3271. return;
  3272. }
  3273. ((AfagFeeder)feeder).SetIntensity(0);
  3274. }
  3275. if (cancellationToken != null && cancellationToken.IsCancellationRequested)
  3276. {
  3277. return;
  3278. }
  3279. }
  3280. }
  3281. else
  3282. {
  3283. //执行配置的Feeder振动任务
  3284. foreach (var feederwork in works)
  3285. {
  3286. if (feederwork.Function == VibrationFunction.Delay)
  3287. {
  3288. if (feederwork.Duration > 0) await Task.Delay(feederwork.Duration, cancellationToken);
  3289. }
  3290. else
  3291. {
  3292. if (feederwork.SingleAction != null && isUpdateParame)
  3293. {
  3294. await feeder.SetShakeParametersAsync((int)feederwork.Function, feederwork.SingleAction);
  3295. }
  3296. await feeder.StartAction((int)feederwork.Function, feederwork.Duration);
  3297. if (feederwork.Duration > 0) await Task.Delay(feederwork.Duration, cancellationToken);
  3298. }
  3299. if (cancellationToken != null && cancellationToken.IsCancellationRequested)
  3300. {
  3301. return;
  3302. }
  3303. }
  3304. }
  3305. }
  3306. /// <summary>
  3307. /// 执行 Feeder 振动集合(逐个执行 FeederWorkList 中的动作)。
  3308. /// </summary>
  3309. public async Task ExecuteFeederWorks(IVoiceCoilMotorFeeder feeder, FeederWorks works, CancellationToken cancellationToken, bool isUpdateParame = true)
  3310. {
  3311. if (feeder.FeederBrand == FeederBrand.AFAG)
  3312. {
  3313. foreach (var feederwork in works.FeederWorkList)
  3314. {
  3315. if (feederwork.ConfigIndex < 0)
  3316. {
  3317. continue;
  3318. }
  3319. if (feederwork.ConfigIndex == 0)
  3320. {
  3321. await Task.Delay(feederwork.Duration, cancellationToken);
  3322. }
  3323. else
  3324. {
  3325. ((AfagFeeder)feeder).LoadConfiguration(feederwork.ConfigIndex);
  3326. ((AfagFeeder)feeder).SetIntensity(feederwork.Intensity);
  3327. ((AfagFeeder)feeder).SetDirection(feederwork.Direction);
  3328. await Task.Delay(feederwork.Duration, cancellationToken);
  3329. if (cancellationToken != null && cancellationToken.IsCancellationRequested)
  3330. {
  3331. return;
  3332. }
  3333. ((AfagFeeder)feeder).SetIntensity(0);
  3334. }
  3335. if (cancellationToken != null && cancellationToken.IsCancellationRequested)
  3336. {
  3337. return;
  3338. }
  3339. }
  3340. }
  3341. else
  3342. {
  3343. foreach (var feederwork in works.FeederWorkList)
  3344. {
  3345. if (feederwork.Function == VibrationFunction.Delay)
  3346. {
  3347. if (feederwork.Duration > 0) await Task.Delay(feederwork.Duration, cancellationToken);
  3348. }
  3349. else
  3350. {
  3351. if (feederwork.SingleAction != null && isUpdateParame)
  3352. {
  3353. await feeder.SetShakeParametersAsync((int)feederwork.Function, feederwork.SingleAction);
  3354. }
  3355. await feeder.StartAction((int)feederwork.Function, feederwork.Duration);
  3356. if (feederwork.Duration > 0) await Task.Delay(feederwork.Duration, cancellationToken);
  3357. }
  3358. if (cancellationToken != null && cancellationToken.IsCancellationRequested)
  3359. {
  3360. return;
  3361. }
  3362. }
  3363. }
  3364. }
  3365. /// <summary>
  3366. /// 在拍照前设置光源亮度和打开光源
  3367. /// </summary>
  3368. /// <param name="procedure">流程模型</param>
  3369. /// <returns></returns>
  3370. public async Task SetLightBeforePhoto(ProcedureModel procedure)
  3371. {
  3372. var sysConfig = _configService.GetSystemConfiguration();
  3373. if (sysConfig.LightUse == true)
  3374. {
  3375. return;
  3376. }
  3377. //判断当前流程是否启用光源控制
  3378. if (procedure.IsControlLightChannels)
  3379. {
  3380. //打开所有需要控制的光源通道
  3381. foreach (var lightChannel in procedure.LightChannels)
  3382. {
  3383. bool isSucceed = false;
  3384. isSucceed = await _lightManagerService.TurnOnGlobalChannelAsync(lightChannel.GlobalIndex);
  3385. if (!isSucceed)
  3386. {
  3387. LogHelper.WriteLogInfo($"设置光源通道{lightChannel.GlobalIndex}打开失败!");
  3388. }
  3389. isSucceed = await _lightManagerService.SetGlobalChannelBrightnessAsync(lightChannel.GlobalIndex, lightChannel.DefaultBrightness);
  3390. if (!isSucceed)
  3391. {
  3392. LogHelper.WriteLogInfo($"设置光源通道{lightChannel.GlobalIndex}亮度{lightChannel.DefaultBrightness}失败!");
  3393. }
  3394. }
  3395. }
  3396. }
  3397. /// <summary>
  3398. /// 在拍照后关闭光源
  3399. /// </summary>
  3400. /// <param name="procedure">流程模型</param>
  3401. /// <returns></returns>
  3402. public async Task TurnOffLightAfterPhoto(ProcedureModel procedure)
  3403. {
  3404. var sysConfig = _configService.GetSystemConfiguration();
  3405. if (sysConfig.LightUse == true)
  3406. {
  3407. return;
  3408. }
  3409. //判断当前流程是否启用光源控制
  3410. if (procedure.IsControlLightChannels)
  3411. {
  3412. //关闭所有需要控制的光源通道
  3413. foreach (var lightChannel in procedure.LightChannels)
  3414. {
  3415. bool isSucceed = false;
  3416. isSucceed = await _lightManagerService.TurnOffGlobalChannelAsync(lightChannel.GlobalIndex);
  3417. if (!isSucceed)
  3418. {
  3419. LogHelper.WriteLogInfo($"设置光源通道{lightChannel.GlobalIndex}关闭失败!");
  3420. }
  3421. }
  3422. }
  3423. }
  3424. #endregion
  3425. }
  3426. }