RemoteCommandService.cs 168 KB

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