RemoteCommandService.cs 161 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406
  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)
  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))
  1720. {
  1721. using (var bitmap = imges[0].ToBitmap())
  1722. {
  1723. var results = yolo.Infer(bitmap);
  1724. procedure.ToolBlock.Inputs["PhotoData"].Value = "";
  1725. // 输出结果
  1726. //Console.WriteLine($"检测到 {results.Count} 个目标:");
  1727. SendTaskMessage($"识别的个数:{results.Count()}", MessageLevel.Alarm);
  1728. foreach (var det in results)
  1729. {
  1730. //Console.WriteLine($" - {det.ClassName}: 置信度={det.Confidence:F4}, " +
  1731. // $"边界框=[{det.Box[0]:F0}, {det.Box[1]:F0}, {det.Box[2]:F0}, {det.Box[3]:F0}]");
  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. procedure.ToolBlock.Inputs["PhotoData"].Value = $"{det.ClassName}" + ",";
  1735. }
  1736. // 绘制结果 - 使用 OpenCvSharp
  1737. using (var image2 = ImageHelper.ICogImageConvertMat(imges[0]))
  1738. {
  1739. // 定义颜色映射
  1740. var colors = new[]
  1741. {
  1742. Scalar.Red, // NG1 - 红色
  1743. Scalar.Green, // NG2 - 绿色
  1744. Scalar.Blue, // NG3 - 蓝色
  1745. Scalar.Yellow // NG4 - 黄色
  1746. };
  1747. foreach (var det in results)
  1748. {
  1749. // 获取边界框坐标
  1750. int x1 = (int)det.Box[0];
  1751. int y1 = (int)det.Box[1];
  1752. int x2 = (int)det.Box[2];
  1753. int y2 = (int)det.Box[3];
  1754. // 添加边界检查:确保坐标有效
  1755. if (x1 >= x2 || y1 >= y2)
  1756. {
  1757. SendTaskMessage($"警告: 无效的边界框 [{x1}, {y1}, {x2}, {y2}]", MessageLevel.Error);
  1758. continue;
  1759. }
  1760. // 确保坐标在图像范围内
  1761. x1 = Math.Max(0, Math.Min(image2.Width, x1));
  1762. y1 = Math.Max(0, Math.Min(image2.Height, y1));
  1763. x2 = Math.Max(0, Math.Min(image2.Width, x2));
  1764. y2 = Math.Max(0, Math.Min(image2.Height, y2));
  1765. // 选择颜色(根据类别ID)
  1766. Scalar color = colors[det.ClassId % colors.Length];
  1767. // 绘制矩形框
  1768. Cv2.Rectangle(image2, new Point(x1, y1), new Point(x2, y2), color, 2);
  1769. // 准备标签文本
  1770. string label = $"{det.ClassName} {det.Confidence:P0}";
  1771. // 计算文本大小
  1772. var textSize = Cv2.GetTextSize(label, HersheyFonts.HersheySimplex, 0.6, 1, out int baseline);
  1773. // 确保文本位置不超出图像边界
  1774. int textX = x1;
  1775. int textY = y1 - 5;
  1776. // 如果文本超出图像顶部,显示在框内底部
  1777. if (textY - textSize.Height < 0)
  1778. {
  1779. textY = y2 + baseline + 5;
  1780. }
  1781. //绘制文本背景
  1782. Cv2.Rectangle(image2,
  1783. new OpenCvSharp.Rect(textX, textY - textSize.Height - baseline - 10,
  1784. textSize.Width + 10, textSize.Height + baseline + 10),
  1785. color, -1);
  1786. // 绘制文本
  1787. Cv2.PutText(image2, label,
  1788. new Point(textX + 5, textY - baseline - 5),
  1789. HersheyFonts.HersheySimplex, 0.6, Scalar.White, 2);
  1790. }
  1791. // 保存结果图像
  1792. //string outputPath = @"G:\TEST\文件\左上插线\result.jpg";
  1793. //Cv2.ImWrite(outputPath, image2);
  1794. //Console.WriteLine($"结果已保存到: {outputPath}");
  1795. var cogImage = ImageHelper.MatConvertICogImage(image2);
  1796. procedure.ToolBlock.Inputs["InputImage"].Value = cogImage;
  1797. outputCollection = procedure.ToolBlock.Outputs; //获取输出终端集合
  1798. ICogRecord record = null;
  1799. foreach (CogToolBlockTerminal item in outputCollection)
  1800. {
  1801. if (item.Value is ICogRecord)
  1802. record = item.Value as ICogRecord;
  1803. }
  1804. bool Found = (bool)(outputCollection["Found"].Value);
  1805. //获取图片存储的图片文件名
  1806. string imgName = string.Empty;
  1807. if (procedure.IsSaveImage && !string.IsNullOrEmpty(procedure.ImageFileNameFormat))
  1808. {
  1809. // 创建模板,使用 {变量名:格式} 语法
  1810. var template = new FileNameTemplate(procedure.ImageFileNameFormat);
  1811. // 注册变量
  1812. template.RegisterVariable("ProductSN", () => _productService.CurrentProductCode);
  1813. template.RegisterVariable("CameraName", () => procedure.CameraName);
  1814. template.RegisterVariable("ShotCount", () => 1);
  1815. template.RegisterVariable("Result", () => Found ? "OK" : "NG");
  1816. template.RegisterVariable("DateTime", () => DateTime.Now);
  1817. // 生成文件名
  1818. imgName = template.Generate();
  1819. }
  1820. procedure.ToolBlock.Run();
  1821. _eventAggregator.GetEvent<RenderUpdateNotification>().Publish(new ShowRender()
  1822. {
  1823. Id = procedure.DisplayId,
  1824. DisplayName = procedure.DisplayName,
  1825. //Image = (ICogImage)procedure.ToolBlock.Outputs["OriImage"].Value,
  1826. Image = cogImage,
  1827. Graphic = outputCollection["Graphic"].Value as CogGraphicCollection,
  1828. Record = record,
  1829. Result = Found,
  1830. IsShow = true,
  1831. IsSaveImage = procedure.IsSaveImage,
  1832. SaveImageModel = procedure.SaveImageModel,
  1833. SaveImagePathModel = procedure.SaveImagePathModel,
  1834. SavePath = procedure.SavePath,
  1835. IsCompress = procedure.IsCompress,
  1836. ProceductName = procedure.Name,
  1837. ImageFileName = imgName,
  1838. Is3DModel = is3dmodel,
  1839. //RangeImage = (CogImage16Range)procedure.ToolBlock.Outputs["RangeImage"].Value,
  1840. //GreyImage = (CogImage16Grey)procedure.ToolBlock.Outputs["GreyImage"].Value
  1841. });
  1842. // 可选:显示图像
  1843. //Cv2.ImShow("Detection Result", image2);
  1844. //Cv2.WaitKey(0);
  1845. }
  1846. }
  1847. }
  1848. return true;
  1849. }
  1850. else
  1851. {
  1852. // 3. 运行视觉工具
  1853. LogHelper.WriteLogInfo("开始运行视觉工具");
  1854. procedure.ToolBlock.Run(); //运行ToolBlock
  1855. if (procedure.ToolBlock.RunStatus.Result == CogToolResultConstants.Accept)
  1856. {
  1857. SendTaskMessage(Lang.视觉流程执行耗时.Replace("{0}", procedure.Name).Replace("{1}", $"{procedure.ToolBlock.RunStatus.ProcessingTime:F1}"), MessageLevel.Info);
  1858. outputCollection = procedure.ToolBlock.Outputs; //获取输出终端集合
  1859. DatabaseHelper.AddCameraRecords(_productService.GetCurrentProduct().Name, procedure.Name, outputCollection);
  1860. ICogRecord record = null;
  1861. foreach (CogToolBlockTerminal item in outputCollection)
  1862. {
  1863. if (item.Value is ICogRecord)
  1864. record = item.Value as ICogRecord;
  1865. }
  1866. bool Found = (bool)(outputCollection["Found"].Value);
  1867. //获取图片存储的图片文件名
  1868. string imgName = string.Empty;
  1869. if (procedure.IsSaveImage && !string.IsNullOrEmpty(procedure.ImageFileNameFormat))
  1870. {
  1871. // 创建模板,使用 {变量名:格式} 语法
  1872. var template = new FileNameTemplate(procedure.ImageFileNameFormat);
  1873. // 注册变量
  1874. template.RegisterVariable("ProductSN", () => _productService.CurrentProductCode);
  1875. template.RegisterVariable("CameraName", () => procedure.CameraName);
  1876. template.RegisterVariable("ShotCount", () => 1);
  1877. template.RegisterVariable("Result", () => Found ? "OK" : "NG");
  1878. template.RegisterVariable("DateTime", () => DateTime.Now);
  1879. // 生成文件名
  1880. imgName = template.Generate();
  1881. }
  1882. if (is3dmodel == true)
  1883. {
  1884. if (_configService.GetSystemConfiguration().PickPointNum == 0)
  1885. {
  1886. _eventAggregator.GetEvent<RenderUpdateNotification>().Publish(new ShowRender()
  1887. {
  1888. Id = procedure.DisplayId,
  1889. DisplayName = procedure.DisplayName,
  1890. //Image = (ICogImage)procedure.ToolBlock.Outputs["OriImage"].Value,
  1891. Image = (ICogImage)procedure.ToolBlock.Inputs["InputImage"].Value,
  1892. Graphic = outputCollection["Graphic"].Value as CogGraphicCollection,
  1893. Record = record,
  1894. Result = Found,
  1895. IsShow = true,
  1896. IsSaveImage = procedure.IsSaveImage,
  1897. SaveImageModel = procedure.SaveImageModel,
  1898. SaveImagePathModel = procedure.SaveImagePathModel,
  1899. SavePath = procedure.SavePath,
  1900. IsCompress = procedure.IsCompress,
  1901. ProceductName = procedure.Name,
  1902. ImageFileName = imgName,
  1903. Is3DModel = is3dmodel,
  1904. //RangeImage = (CogImage16Range)procedure.ToolBlock.Outputs["RangeImage"].Value,
  1905. //GreyImage = (CogImage16Grey)procedure.ToolBlock.Outputs["GreyImage"].Value
  1906. });
  1907. }
  1908. else
  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. }
  1933. else
  1934. {
  1935. _eventAggregator.GetEvent<RenderUpdateNotification>().Publish(new ShowRender()
  1936. {
  1937. Id = procedure.DisplayId,
  1938. DisplayName = procedure.DisplayName,
  1939. //Image = (ICogImage)procedure.ToolBlock.Outputs["OriImage"].Value,
  1940. Image = (ICogImage)procedure.ToolBlock.Inputs["InputImage"].Value,
  1941. Graphic = outputCollection["Graphic"].Value as CogGraphicCollection,
  1942. Record = record,
  1943. Result = Found,
  1944. IsShow = true,
  1945. IsSaveImage = procedure.IsSaveImage,
  1946. SaveImageModel = procedure.SaveImageModel,
  1947. SaveImagePathModel = procedure.SaveImagePathModel,
  1948. SavePath = procedure.SavePath,
  1949. IsCompress = procedure.IsCompress,
  1950. ProceductName = procedure.Name,
  1951. ImageFileName = imgName,
  1952. Is3DModel = is3dmodel
  1953. });
  1954. }
  1955. return true;
  1956. }
  1957. else
  1958. {
  1959. SendTaskMessage(Lang.视觉流程执行出错耗时.Replace("{0}", procedure.Name).Replace("{1}", $"{procedure.ToolBlock.RunStatus.ProcessingTime:F1}"), MessageLevel.Error);
  1960. SendTaskMessage(procedure.ToolBlock.RunStatus.Message, MessageLevel.Error);
  1961. outputCollection = null;
  1962. //获取图片存储的图片文件名
  1963. string imgName = string.Empty;
  1964. if (procedure.IsSaveImage && !string.IsNullOrEmpty(procedure.ImageFileNameFormat))
  1965. {
  1966. // 创建模板,使用 {变量名:格式} 语法
  1967. var template = new FileNameTemplate(procedure.ImageFileNameFormat);
  1968. // 注册变量
  1969. template.RegisterVariable("ProductSN", () => _productService.CurrentProductCode);
  1970. template.RegisterVariable("CameraName", () => procedure.CameraName);
  1971. template.RegisterVariable("ShotCount", () => 1);
  1972. template.RegisterVariable("Result", () => "NG");
  1973. template.RegisterVariable("DateTime", () => DateTime.Now);
  1974. // 生成文件名
  1975. imgName = template.Generate();
  1976. }
  1977. if (is3dmodel == true)
  1978. {
  1979. _eventAggregator.GetEvent<RenderUpdateNotification>().Publish(new ShowRender()
  1980. {
  1981. Id = procedure.DisplayId,
  1982. DisplayName = procedure.DisplayName,
  1983. //Image = (ICogImage)procedure.ToolBlock.Outputs["OriImage"].Value,
  1984. Image = (ICogImage)procedure.ToolBlock.Inputs["InputImage"].Value,
  1985. Graphic = new CogGraphicCollection(),
  1986. Result = false,
  1987. IsShow = true,
  1988. IsSaveImage = procedure.IsSaveImage,
  1989. SaveImageModel = procedure.SaveImageModel,
  1990. SaveImagePathModel = procedure.SaveImagePathModel,
  1991. SavePath = procedure.SavePath,
  1992. ProceductName = procedure.Name,
  1993. ImageFileName = imgName,
  1994. Is3DModel = is3dmodel,
  1995. RangeImage = (CogImage16Range)procedure.ToolBlock.Outputs["RangeImage"].Value,
  1996. GreyImage = (CogImage16Grey)procedure.ToolBlock.Outputs["GreyImage"].Value
  1997. });
  1998. }
  1999. else
  2000. {
  2001. _eventAggregator.GetEvent<RenderUpdateNotification>().Publish(new ShowRender()
  2002. {
  2003. Id = procedure.DisplayId,
  2004. DisplayName = procedure.DisplayName,
  2005. //Image = (ICogImage)procedure.ToolBlock.Outputs["OriImage"].Value,
  2006. Image = (ICogImage)procedure.ToolBlock.Inputs["InputImage"].Value,
  2007. Graphic = new CogGraphicCollection(),
  2008. Result = false,
  2009. IsShow = true,
  2010. IsSaveImage = procedure.IsSaveImage,
  2011. SaveImageModel = procedure.SaveImageModel,
  2012. SaveImagePathModel = procedure.SaveImagePathModel,
  2013. SavePath = procedure.SavePath,
  2014. ProceductName = procedure.Name,
  2015. ImageFileName = imgName,
  2016. Is3DModel = is3dmodel
  2017. });
  2018. }
  2019. return false;
  2020. }
  2021. }
  2022. }
  2023. catch (Exception ex)
  2024. {
  2025. SendTaskMessage(ex.Message, MessageLevel.Error);
  2026. LogHelper.WriteLogError("执行相机取图并执行视觉工具组时出错!", ex);
  2027. outputCollection = null;
  2028. return false;
  2029. }
  2030. }
  2031. /// <summary>
  2032. /// 采集图像
  2033. /// </summary>
  2034. /// <param name="procedure"></param>
  2035. /// <returns></returns>
  2036. public async Task <(bool IsSucceed, ICogImage[] Image, string Msg)> ExecuteGrabImageAsync(ProcedureModel procedure,bool Is3dPhoto)
  2037. {
  2038. try
  2039. {
  2040. var sysConfig = _configService.GetSystemConfiguration();
  2041. if (sysConfig.PhotosUse == true)
  2042. {
  2043. // 1. 采集图像
  2044. var camera = _cameraService.GetCamera(procedure.CameraId);
  2045. ICogImage image = null;
  2046. ICogImage image2 = null;
  2047. for (int i = 1; i <= procedure.PhotoCount; i++)
  2048. {
  2049. if (i == 1)
  2050. {
  2051. //bool isSucceed = false;
  2052. //isSucceed = await _lightManagerService.SetGlobalChannelBrightnessAsync(0, procedure.Photo1Light1);
  2053. //if (!isSucceed)
  2054. //{
  2055. // LogHelper.WriteLogInfo($"设置光源通道1亮度{procedure.Photo1Light1}失败!");
  2056. //}
  2057. //isSucceed = await _lightManagerService.SetGlobalChannelBrightnessAsync(1, procedure.Photo1Light2);
  2058. //if (!isSucceed)
  2059. //{
  2060. // LogHelper.WriteLogInfo($"设置光源通道2亮度{procedure.Photo1Light2}失败!");
  2061. //}
  2062. //isSucceed = await _lightManagerService.SetGlobalChannelBrightnessAsync(2, procedure.Photo1Light3);
  2063. //if (!isSucceed)
  2064. //{
  2065. // LogHelper.WriteLogInfo($"设置光源通道3亮度{procedure.Photo1Light3}失败!");
  2066. //}
  2067. bool succed = camera.SetExposureTime(procedure.ExposureTime);
  2068. if (!succed)
  2069. {
  2070. SendTaskMessage($"相机曝光设置失败!", MessageLevel.Error);
  2071. }
  2072. succed = camera.SetGain(procedure.Gain);
  2073. if (!succed)
  2074. {
  2075. SendTaskMessage($"相机增益设置失败!", MessageLevel.Error);
  2076. }
  2077. image = camera.Grab();
  2078. //isSucceed = await _lightManagerService.TurnOffGlobalChannelAsync(0);
  2079. //if (!isSucceed)
  2080. //{
  2081. // LogHelper.WriteLogInfo($"设置光源通道0关闭失败!");
  2082. //}
  2083. //isSucceed = await _lightManagerService.TurnOffGlobalChannelAsync(1);
  2084. //if (!isSucceed)
  2085. //{
  2086. // LogHelper.WriteLogInfo($"设置光源通道1关闭失败!");
  2087. //}
  2088. //isSucceed = await _lightManagerService.TurnOffGlobalChannelAsync(2);
  2089. //if (!isSucceed)
  2090. //{
  2091. // LogHelper.WriteLogInfo($"设置光源通道2关闭失败!");
  2092. //}
  2093. }
  2094. else if (i == 2)
  2095. {
  2096. //bool isSucceed = false;
  2097. //isSucceed = await _lightManagerService.SetGlobalChannelBrightnessAsync(0, procedure.Photo2Light1);
  2098. //if (!isSucceed)
  2099. //{
  2100. // LogHelper.WriteLogInfo($"设置光源通道1亮度{procedure.Photo2Light1}失败!");
  2101. //}
  2102. //isSucceed = await _lightManagerService.SetGlobalChannelBrightnessAsync(1, procedure.Photo2Light2);
  2103. //if (!isSucceed)
  2104. //{
  2105. // LogHelper.WriteLogInfo($"设置光源通道2亮度{procedure.Photo2Light2}失败!");
  2106. //}
  2107. //isSucceed = await _lightManagerService.SetGlobalChannelBrightnessAsync(2, procedure.Photo2Light3);
  2108. //if (!isSucceed)
  2109. //{
  2110. // LogHelper.WriteLogInfo($"设置光源通道3亮度{procedure.Photo2Light3}失败!");
  2111. //}
  2112. SendTaskMessage($"开始设置相机曝光!", MessageLevel.Info);
  2113. bool succed = camera.SetExposureTime(procedure.ExposureTime2);
  2114. if (!succed)
  2115. {
  2116. SendTaskMessage($"相机曝光设置失败!", MessageLevel.Error);
  2117. }
  2118. SendTaskMessage($"开始设置相机增益!", MessageLevel.Info);
  2119. succed = camera.SetGain(procedure.Gain2);
  2120. if (!succed)
  2121. {
  2122. SendTaskMessage($"相机增益设置失败!", MessageLevel.Error);
  2123. }
  2124. image2 = camera.Grab();
  2125. //isSucceed = await _lightManagerService.TurnOffGlobalChannelAsync(0);
  2126. //if (!isSucceed)
  2127. //{
  2128. // LogHelper.WriteLogInfo($"设置光源通道0关闭失败!");
  2129. //}
  2130. //isSucceed = await _lightManagerService.TurnOffGlobalChannelAsync(1);
  2131. //if (!isSucceed)
  2132. //{
  2133. // LogHelper.WriteLogInfo($"设置光源通道1关闭失败!");
  2134. //}
  2135. //isSucceed = await _lightManagerService.TurnOffGlobalChannelAsync(2);
  2136. //if (!isSucceed)
  2137. //{
  2138. // LogHelper.WriteLogInfo($"设置光源通道2关闭失败!");
  2139. //}
  2140. }
  2141. }
  2142. DateTime nowtime = DateTime.Now;
  2143. LogHelper.WriteLogInfo("开始采集图像");
  2144. //var image = camera.Grab();
  2145. if (Is3dPhoto == true)
  2146. {
  2147. image = camera.Grab();
  2148. image2 = camera.Grab2();
  2149. LogHelper.WriteLogInfo($"采集图像完成;用时:{(DateTime.Now - nowtime).Milliseconds}ms");
  2150. if (image == null || image2 == null)
  2151. {
  2152. SendTaskMessage(Lang.图像采集失败, MessageLevel.Error);
  2153. return (false, null, "图像采集失败");
  2154. }
  2155. return (true, new ICogImage[] { image, image2 }, "成功");
  2156. }
  2157. else
  2158. {
  2159. LogHelper.WriteLogInfo($"采集图像完成;用时:{(DateTime.Now - nowtime).Milliseconds}ms");
  2160. if (image == null )
  2161. {
  2162. SendTaskMessage(Lang.图像采集失败, MessageLevel.Error);
  2163. return (false, null, "图像采集失败");
  2164. }
  2165. if(procedure.PhotoCount>1)
  2166. {
  2167. if (image2 == null)
  2168. {
  2169. SendTaskMessage(Lang.图像采集失败, MessageLevel.Error);
  2170. return (false, null, "图像采集失败");
  2171. }
  2172. return (true, new ICogImage[] { image, image2 }, "成功");
  2173. }
  2174. return (true, new ICogImage[] { image}, "成功");
  2175. }
  2176. }
  2177. else
  2178. {
  2179. // 1. 采集图像
  2180. var camera = _cameraService.GetCamera(procedure.CameraId);
  2181. bool succed = camera.SetExposureTime(procedure.ExposureTime);
  2182. if (!succed)
  2183. {
  2184. SendTaskMessage($"相机曝光设置失败!", MessageLevel.Error);
  2185. }
  2186. succed = camera.SetGain(procedure.Gain);
  2187. if (!succed)
  2188. {
  2189. SendTaskMessage($"相机增益设置失败!", MessageLevel.Error);
  2190. }
  2191. DateTime nowtime = DateTime.Now;
  2192. LogHelper.WriteLogInfo("开始采集图像");
  2193. //var image = camera.Grab();
  2194. if (Is3dPhoto == true)
  2195. {
  2196. var image = camera.Grab();
  2197. var image2 = camera.Grab2();
  2198. LogHelper.WriteLogInfo($"采集图像完成;用时:{(DateTime.Now - nowtime).Milliseconds}ms");
  2199. if (image == null || image2 == null)
  2200. {
  2201. SendTaskMessage(Lang.图像采集失败, MessageLevel.Error);
  2202. return (false, null, "图像采集失败");
  2203. }
  2204. return (true, new ICogImage[] { image, image2 }, "成功");
  2205. }
  2206. else
  2207. {
  2208. var image = camera.Grab();
  2209. LogHelper.WriteLogInfo($"采集图像完成;用时:{(DateTime.Now - nowtime).Milliseconds}ms");
  2210. if (image == null)
  2211. {
  2212. SendTaskMessage(Lang.图像采集失败, MessageLevel.Error);
  2213. return (false, null, "图像采集失败");
  2214. }
  2215. return (true, new ICogImage[] { image }, "成功");
  2216. }
  2217. }
  2218. }
  2219. catch (Exception ex)
  2220. {
  2221. LogHelper.WriteLogError("采集图像失败!",ex);
  2222. return (false, null, "图像采集失败");
  2223. }
  2224. }
  2225. /// <summary>
  2226. /// 执行相机拍照获取单个点位结果
  2227. /// </summary>
  2228. /// <param name="procedure"></param>
  2229. /// <param name="InputTerminal"></param>
  2230. /// <param name="robotCoord"></param>
  2231. /// <param name="cancellationToken"></param>
  2232. /// <returns></returns>
  2233. public async Task<(bool IsSucceed, string[] Items, double Count)> ExecutePhotoGetSinglePoint1(ProcedureModel procedure, ICogImage[] imges, Dictionary<string, string> InputTerminal, double[] robotCoord, CancellationToken cancellationToken,bool is3dmodel)
  2234. {
  2235. DateTime nowtime = DateTime.Now;
  2236. try
  2237. {
  2238. //拍照失败时,需要多次拍照
  2239. //for (int i = 0; i < procedure.FeederFailLimit; i++)
  2240. for (int i = 0; i < 1; i++)
  2241. {
  2242. SendTaskMessage(Lang.开始执行视觉流程.Replace("{0}", $"{i + 1}").Replace("{1}", procedure.Name), MessageLevel.Info);
  2243. // 1. 执行相机拍照并运行视觉工具
  2244. bool visionSucceed = ExecutePhoto(procedure, imges, InputTerminal, out CogToolBlockTerminalCollection outputCollection, is3dmodel);
  2245. if (!visionSucceed)
  2246. {
  2247. SendTaskMessage(Lang.视觉任务执行失败, MessageLevel.Error);
  2248. continue;
  2249. }
  2250. if (!outputCollection.Contains("Found"))
  2251. {
  2252. SendTaskMessage(Lang.未找到视觉输出结果, MessageLevel.Error);
  2253. return (false, null, 0);
  2254. }
  2255. // 2. 获取视觉输出结果
  2256. //bool Found = (bool)(outputCollection["Found"].Value);
  2257. //if (!Found)
  2258. //{
  2259. // SendTaskMessage(Lang.拍照NG, MessageLevel.Debug);
  2260. // continue;
  2261. //}
  2262. SendTaskMessage(Lang.拍照OK, MessageLevel.Debug);
  2263. int Count = (int)(outputCollection["Count"].Value);
  2264. string[] PhotoRes = new string[100];
  2265. for (int k = 1; k <= Count; k++)
  2266. {
  2267. PhotoRes[k] = (string)(outputCollection[$"dis{k}"].Value);
  2268. //PhotoRes[k] = "222";
  2269. }
  2270. // 3. 获取视觉输出结果
  2271. LogHelper.WriteLogInfo("开始获取视觉输出结果");
  2272. /*
  2273. //获取相机校准
  2274. var calib = _calibrationService.GetCalibration(procedure.CalibrationId);
  2275. string points = (string)(outputCollection["Point"].Value);
  2276. string[] strpoints = points.Split(';');
  2277. //先将pos按照逗号进行分隔,拿到数组
  2278. var posParts = strpoints[0].Split(',');
  2279. double _pixel_x = double.Parse(posParts[0]);
  2280. double _pixel_y = double.Parse(posParts[1]);
  2281. double _pixel_u = double.Parse(posParts[2]);
  2282. //转换点位-像素转换成机器人绝对坐标
  2283. var calibResult = _calibrationService.ConvertPixelToPosition((_pixel_x, _pixel_y, _pixel_u), robotCoord, calib, RobotBrand.XYZ_Platform);
  2284. if (!calibResult.IsSucceed)
  2285. {
  2286. return (false, 0, 0, 0);
  2287. }
  2288. return (true, calibResult.X, calibResult.Y, calibResult.U);
  2289. */
  2290. return (true, PhotoRes, Count);
  2291. }
  2292. SendTaskMessage(Lang.多次拍照失败, MessageLevel.Alarm);
  2293. return (false, null, 0);
  2294. }
  2295. catch (Exception ex)
  2296. {
  2297. LogHelper.WriteLogError("执行相机取图并获取单点位时出错!", ex);
  2298. return (false, null, 0);
  2299. }
  2300. finally
  2301. {
  2302. var sysConfig = _configService.GetSystemConfiguration();
  2303. if (sysConfig.TurnOffAllLightUse == false)
  2304. {
  2305. await TurnOffLightAfterPhoto(procedure);
  2306. }
  2307. }
  2308. }
  2309. /// <summary>
  2310. /// 执行相机拍照获取单个点位结果
  2311. /// </summary>
  2312. /// <param name="procedure"></param>
  2313. /// <param name="InputTerminal"></param>
  2314. /// <param name="robotCoord"></param>
  2315. /// <param name="cancellationToken"></param>
  2316. /// <returns></returns>
  2317. public async Task<(bool IsSucceed, string X, double Y, double U)> ExecutePhotoGetSinglePoint2(ProcedureModel procedure, Dictionary<string, string> InputTerminal, double[] robotCoord, CancellationToken cancellationToken)
  2318. {
  2319. DateTime nowtime = DateTime.Now;
  2320. var sysConfig = _configService.GetSystemConfiguration();
  2321. if (sysConfig.TurnOnAllLightUse == false)
  2322. {
  2323. await SetLightBeforePhoto(procedure);
  2324. }
  2325. try
  2326. {
  2327. //拍照失败时,需要多次拍照
  2328. for (int i = 0; i < procedure.FeederFailLimit; i++)
  2329. {
  2330. SendTaskMessage(Lang.开始执行视觉流程.Replace("{0}", $"{i + 1}").Replace("{1}", procedure.Name), MessageLevel.Info);
  2331. // 1. 执行相机拍照并运行视觉工具
  2332. bool visionSucceed = ExecutePhoto2(procedure, InputTerminal, out CogToolBlockTerminalCollection outputCollection);
  2333. if (!visionSucceed)
  2334. {
  2335. SendTaskMessage(Lang.视觉任务执行失败, MessageLevel.Error);
  2336. continue;
  2337. }
  2338. if (!outputCollection.Contains("Found"))
  2339. {
  2340. SendTaskMessage(Lang.未找到视觉输出结果, MessageLevel.Error);
  2341. return (false, null, 0, 0);
  2342. }
  2343. // 2. 获取视觉输出结果
  2344. bool Found = (bool)(outputCollection["Found"].Value);
  2345. if (!Found)
  2346. {
  2347. SendTaskMessage(Lang.拍照NG, MessageLevel.Debug);
  2348. continue;
  2349. }
  2350. string SnCode = (string)(outputCollection["SnCode"].Value);
  2351. SendTaskMessage(Lang.拍照OK, MessageLevel.Debug);
  2352. // 3. 获取视觉输出结果
  2353. LogHelper.WriteLogInfo("开始获取视觉输出结果");
  2354. /*
  2355. //获取相机校准
  2356. var calib = _calibrationService.GetCalibration(procedure.CalibrationId);
  2357. string points = (string)(outputCollection["Point"].Value);
  2358. string[] strpoints = points.Split(';');
  2359. //先将pos按照逗号进行分隔,拿到数组
  2360. var posParts = strpoints[0].Split(',');
  2361. double _pixel_x = double.Parse(posParts[0]);
  2362. double _pixel_y = double.Parse(posParts[1]);
  2363. double _pixel_u = double.Parse(posParts[2]);
  2364. //转换点位-像素转换成机器人绝对坐标
  2365. var calibResult = _calibrationService.ConvertPixelToPosition((_pixel_x, _pixel_y, _pixel_u), robotCoord, calib, RobotBrand.XYZ_Platform);
  2366. if (!calibResult.IsSucceed)
  2367. {
  2368. return (false, 0, 0, 0);
  2369. }
  2370. return (true, calibResult.X, calibResult.Y, calibResult.U);
  2371. */
  2372. return (true, SnCode, 0, 0);
  2373. }
  2374. SendTaskMessage(Lang.多次拍照失败, MessageLevel.Alarm);
  2375. return (false, null, 0, 0);
  2376. }
  2377. catch (Exception ex)
  2378. {
  2379. LogHelper.WriteLogError("执行相机取图并获取单点位时出错!", ex);
  2380. return (false, null, 0, 0);
  2381. }
  2382. finally
  2383. {
  2384. if (sysConfig.TurnOffAllLightUse == false)
  2385. {
  2386. await TurnOffLightAfterPhoto(procedure);
  2387. }
  2388. }
  2389. }
  2390. /// <summary>
  2391. /// 执行相机拍照并运行 ToolBlock,返回是否成功并通过 out 参数返回 Outputs、图像和图形集合。
  2392. /// </summary>
  2393. /// <param name="procedure"></param>
  2394. /// <param name="InputTerminal"></param>
  2395. /// <param name="outputCollection"></param>
  2396. /// <param name="outImage"></param>
  2397. /// <param name="outGraphicCollection"></param>
  2398. /// <returns></returns>
  2399. public bool ExecutePhotoEx(ProcedureModel procedure, Dictionary<string, string> InputTerminal, out CogToolBlockTerminalCollection outputCollection,out ICogImage outImage,out CogGraphicCollection outGraphicCollection)
  2400. {
  2401. outImage = null;
  2402. outGraphicCollection = null;
  2403. try
  2404. {
  2405. // 1. 采集图像
  2406. var camera = _cameraService.GetCamera(procedure.CameraId);
  2407. bool succed = camera.SetExposureTime(procedure.ExposureTime);
  2408. if (!succed)
  2409. {
  2410. SendTaskMessage($"相机曝光设置失败!", MessageLevel.Error);
  2411. }
  2412. succed = camera.SetGain(procedure.Gain);
  2413. if (!succed)
  2414. {
  2415. SendTaskMessage($"相机增益设置失败!", MessageLevel.Error);
  2416. }
  2417. DateTime nowtime = DateTime.Now;
  2418. LogHelper.WriteLogInfo("开始采集图像");
  2419. var image = camera.Grab();
  2420. if (image == null)
  2421. {
  2422. SendTaskMessage(Lang.图像采集失败, MessageLevel.Error);
  2423. outputCollection = null;
  2424. return false;
  2425. }
  2426. outImage= image;
  2427. procedure.ToolBlock.Inputs["InputImage"].Value = image;
  2428. LogHelper.WriteLogInfo($"采集图像完成;用时:{(DateTime.Now - nowtime).Milliseconds}ms");
  2429. // 2. 为ToolBlock传入其他输入终端
  2430. if (InputTerminal != null)
  2431. {
  2432. LogHelper.WriteLogInfo($"为ToolBlock传入输入终端");
  2433. foreach (var item in InputTerminal)
  2434. {
  2435. if (procedure.ToolBlock.Inputs.Contains(item.Key))
  2436. {
  2437. LogHelper.WriteLogInfo($"传入[{item.Key}]={item.Value}");
  2438. procedure.ToolBlock.Inputs[item.Key].Value = item.Value;
  2439. }
  2440. else
  2441. {
  2442. LogHelper.WriteLogInfo($"创建并传入[{item.Key}]={item.Value}");
  2443. procedure.ToolBlock.Inputs.Add(new CogToolBlockTerminal(item.Key, item.Value));
  2444. }
  2445. }
  2446. }
  2447. // 3. 运行视觉工具
  2448. LogHelper.WriteLogInfo("开始运行视觉工具");
  2449. procedure.ToolBlock.Run(); //运行ToolBlock
  2450. if (procedure.ToolBlock.RunStatus.Result == CogToolResultConstants.Accept)
  2451. {
  2452. SendTaskMessage(Lang.视觉流程执行耗时.Replace("{0}", procedure.Name).Replace("{1}", $"{procedure.ToolBlock.RunStatus.ProcessingTime:F1}"), MessageLevel.Info);
  2453. outputCollection = procedure.ToolBlock.Outputs; //获取输出终端集合
  2454. DatabaseHelper.AddCameraRecords(_productService.GetCurrentProduct().Name, procedure.Name, outputCollection);
  2455. ICogRecord record = null;
  2456. foreach (CogToolBlockTerminal item in outputCollection)
  2457. {
  2458. if (item.Value is ICogRecord)
  2459. record = item.Value as ICogRecord;
  2460. }
  2461. outGraphicCollection= outputCollection["Graphic"].Value as CogGraphicCollection;
  2462. return true;
  2463. }
  2464. else
  2465. {
  2466. SendTaskMessage(Lang.视觉流程执行出错耗时.Replace("{0}", procedure.Name).Replace("{1}", $"{procedure.ToolBlock.RunStatus.ProcessingTime:F1}"), MessageLevel.Error);
  2467. SendTaskMessage(procedure.ToolBlock.RunStatus.Message, MessageLevel.Error);
  2468. outputCollection = null;
  2469. outGraphicCollection = outputCollection["Graphic"].Value as CogGraphicCollection;
  2470. return false;
  2471. }
  2472. }
  2473. catch (Exception ex)
  2474. {
  2475. SendTaskMessage(ex.Message, MessageLevel.Error);
  2476. LogHelper.WriteLogError("执行相机取图并执行视觉工具组时出错!", ex);
  2477. outputCollection = null;
  2478. return false;
  2479. }
  2480. }
  2481. /// <summary>
  2482. /// 执行相机拍照获取单个点位结果
  2483. /// </summary>
  2484. /// <param name="procedure"></param>
  2485. /// <param name="InputTerminal"></param>
  2486. /// <param name="robotCoord"></param>
  2487. /// <param name="cancellationToken"></param>
  2488. /// <returns></returns>
  2489. public async Task<(bool IsSucceed, double X, double Y, double U)> ExecutePhotoGetSinglePoint(ProcedureModel procedure, Dictionary<string, string> InputTerminal, double[] robotCoord, CancellationToken cancellationToken)
  2490. {
  2491. DateTime nowtime = DateTime.Now;
  2492. await SetLightBeforePhoto(procedure);
  2493. try
  2494. {
  2495. //拍照失败时,需要多次拍照
  2496. //for (int i = 0; i < procedure.FeederFailLimit; i++)
  2497. for (int i = 0; i < 1; i++)
  2498. {
  2499. SendTaskMessage(Lang.开始执行视觉流程.Replace("{0}", $"{i + 1}").Replace("{1}", procedure.Name), MessageLevel.Info);
  2500. //1.执行相机拍照并运行视觉工具
  2501. bool visionSucceed = ExecutePhoto(procedure, InputTerminal, out CogToolBlockTerminalCollection outputCollection);
  2502. if (!visionSucceed)
  2503. {
  2504. SendTaskMessage(Lang.视觉任务执行失败, MessageLevel.Error);
  2505. continue;
  2506. }
  2507. if (!outputCollection.Contains("Found"))
  2508. {
  2509. SendTaskMessage(Lang.未找到视觉输出结果, MessageLevel.Error);
  2510. return (false, 0, 0, 0);
  2511. }
  2512. // 2. 获取视觉输出结果
  2513. bool Found = (bool)(outputCollection["Found"].Value);
  2514. if (!Found)
  2515. {
  2516. SendTaskMessage(Lang.拍照NG, MessageLevel.Debug);
  2517. continue;
  2518. }
  2519. SendTaskMessage(Lang.拍照OK, MessageLevel.Debug);
  2520. //// 3. 获取视觉输出结果
  2521. //LogHelper.WriteLogInfo("开始获取视觉输出结果");
  2522. ////获取相机校准
  2523. //var calib = _calibrationService.GetCalibration(procedure.CalibrationId);
  2524. //string points = (string)(outputCollection["Point"].Value);
  2525. //string[] strpoints = points.Split(';');
  2526. ////先将pos按照逗号进行分隔,拿到数组
  2527. //var posParts = strpoints[0].Split(',');
  2528. //double _pixel_x = double.Parse(posParts[0]);
  2529. //double _pixel_y = double.Parse(posParts[1]);
  2530. //double _pixel_u = double.Parse(posParts[2]);
  2531. ////转换点位-像素转换成机器人绝对坐标
  2532. //var calibResult = _calibrationService.ConvertPixelToPosition((_pixel_x, _pixel_y, _pixel_u), robotCoord, calib, RobotBrand.XYZ_Platform);
  2533. //if (!calibResult.IsSucceed)
  2534. //{
  2535. // return (false, 0, 0, 0);
  2536. //}
  2537. return (true, 0,0, 0);
  2538. }
  2539. SendTaskMessage(Lang.多次拍照失败, MessageLevel.Alarm);
  2540. return (false, 0, 0, 0);
  2541. }
  2542. catch (Exception ex)
  2543. {
  2544. LogHelper.WriteLogError("执行相机取图并获取单点位时出错!", ex);
  2545. return (false, 0, 0, 0);
  2546. }
  2547. finally
  2548. {
  2549. await TurnOffLightAfterPhoto(procedure);
  2550. }
  2551. }
  2552. /// <summary>
  2553. /// 执行相机拍照获取单个点位结果
  2554. /// </summary>
  2555. /// <param name="procedure"></param>
  2556. /// <param name="InputTerminal"></param>
  2557. /// <param name="robotCoord"></param>
  2558. /// <param name="cancellationToken"></param>
  2559. /// <returns></returns>
  2560. public async Task<(bool IsSucceed, string[] Items, double Count)> ExecutePhotoGetSinglePoint1(ProcedureModel procedure, Dictionary<string, string> InputTerminal, double[] robotCoord, CancellationToken cancellationToken)
  2561. {
  2562. DateTime nowtime = DateTime.Now;
  2563. var sysConfig = _configService.GetSystemConfiguration();
  2564. if (sysConfig.TurnOnAllLightUse == false)
  2565. {
  2566. await SetLightBeforePhoto(procedure);
  2567. }
  2568. try
  2569. {
  2570. //拍照失败时,需要多次拍照
  2571. //for (int i = 0; i < procedure.FeederFailLimit; i++)
  2572. for (int i = 0; i < 1; i++)
  2573. {
  2574. SendTaskMessage(Lang.开始执行视觉流程.Replace("{0}", $"{i + 1}").Replace("{1}", procedure.Name), MessageLevel.Info);
  2575. // 1. 执行相机拍照并运行视觉工具
  2576. bool visionSucceed = ExecutePhoto(procedure, InputTerminal, out CogToolBlockTerminalCollection outputCollection);
  2577. if (!visionSucceed)
  2578. {
  2579. SendTaskMessage(Lang.视觉任务执行失败, MessageLevel.Error);
  2580. continue;
  2581. }
  2582. //if (!outputCollection.Contains("Found"))
  2583. //{
  2584. // SendTaskMessage(Lang.未找到视觉输出结果, MessageLevel.Error);
  2585. // return (false, null, 0);
  2586. //}
  2587. // 2. 获取视觉输出结果
  2588. //bool Found = (bool)(outputCollection["Found"].Value);
  2589. //if (!Found)
  2590. //{
  2591. // SendTaskMessage(Lang.拍照NG, MessageLevel.Debug);
  2592. // continue;
  2593. //}
  2594. SendTaskMessage(Lang.拍照OK, MessageLevel.Debug);
  2595. int Count = (int)(outputCollection["Count"].Value);
  2596. string[] PhotoRes = new string[100];
  2597. for (int k = 1; k <= Count; k++)
  2598. {
  2599. PhotoRes[k] = (string)(outputCollection[$"dis{k}"].Value);
  2600. //PhotoRes[k] = "222";
  2601. }
  2602. // 3. 获取视觉输出结果
  2603. LogHelper.WriteLogInfo("开始获取视觉输出结果");
  2604. /*
  2605. //获取相机校准
  2606. var calib = _calibrationService.GetCalibration(procedure.CalibrationId);
  2607. string points = (string)(outputCollection["Point"].Value);
  2608. string[] strpoints = points.Split(';');
  2609. //先将pos按照逗号进行分隔,拿到数组
  2610. var posParts = strpoints[0].Split(',');
  2611. double _pixel_x = double.Parse(posParts[0]);
  2612. double _pixel_y = double.Parse(posParts[1]);
  2613. double _pixel_u = double.Parse(posParts[2]);
  2614. //转换点位-像素转换成机器人绝对坐标
  2615. var calibResult = _calibrationService.ConvertPixelToPosition((_pixel_x, _pixel_y, _pixel_u), robotCoord, calib, RobotBrand.XYZ_Platform);
  2616. if (!calibResult.IsSucceed)
  2617. {
  2618. return (false, 0, 0, 0);
  2619. }
  2620. return (true, calibResult.X, calibResult.Y, calibResult.U);
  2621. */
  2622. return (true, PhotoRes, Count);
  2623. }
  2624. SendTaskMessage(Lang.多次拍照失败, MessageLevel.Alarm);
  2625. return (false, null, 0);
  2626. }
  2627. catch (Exception ex)
  2628. {
  2629. LogHelper.WriteLogError("执行相机取图并获取单点位时出错!", ex);
  2630. return (false, null, 0);
  2631. }
  2632. finally
  2633. {
  2634. //await TurnOffLightAfterPhoto(procedure);
  2635. }
  2636. }
  2637. /// <summary>
  2638. /// 执行相机拍照获取单个点位结果,并且返回图像和图形
  2639. /// </summary>
  2640. /// <param name="procedure"></param>
  2641. /// <param name="InputTerminal"></param>
  2642. /// <param name="robotCoord"></param>
  2643. /// <param name="cancellationToken"></param>
  2644. /// <returns></returns>
  2645. 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)
  2646. {
  2647. DateTime nowtime = DateTime.Now;
  2648. await SetLightBeforePhoto(procedure);
  2649. ICogImage outImage=null;
  2650. CogGraphicCollection outGraphicCollection=null;
  2651. try
  2652. {
  2653. //拍照失败时,需要多次拍照
  2654. for (int i = 0; i < procedure.FeederFailLimit; i++)
  2655. {
  2656. SendTaskMessage(Lang.开始执行视觉流程.Replace("{0}", $"{i + 1}").Replace("{1}", procedure.Name), MessageLevel.Info);
  2657. // 1. 执行相机拍照并运行视觉工具
  2658. bool visionSucceed = ExecutePhotoEx(procedure, InputTerminal, out CogToolBlockTerminalCollection outputCollection, out outImage, out outGraphicCollection);
  2659. if (!visionSucceed)
  2660. {
  2661. SendTaskMessage(Lang.视觉任务执行失败, MessageLevel.Error);
  2662. continue;
  2663. }
  2664. if (!outputCollection.Contains("Found"))
  2665. {
  2666. SendTaskMessage(Lang.未找到视觉输出结果, MessageLevel.Error);
  2667. return (false, 0, 0, 0, outImage, outGraphicCollection);
  2668. }
  2669. // 2. 获取视觉输出结果
  2670. bool Found = (bool)(outputCollection["Found"].Value);
  2671. if (!Found)
  2672. {
  2673. SendTaskMessage(Lang.拍照NG, MessageLevel.Debug);
  2674. continue;
  2675. }
  2676. SendTaskMessage(Lang.拍照OK, MessageLevel.Debug);
  2677. // 3. 获取视觉输出结果
  2678. LogHelper.WriteLogInfo("开始获取视觉输出结果");
  2679. //获取相机校准
  2680. var calib = _calibrationService.GetCalibration(procedure.CalibrationId);
  2681. string points = (string)(outputCollection["Point"].Value);
  2682. string[] strpoints = points.Split(';');
  2683. //先将pos按照逗号进行分隔,拿到数组
  2684. var posParts = strpoints[0].Split(',');
  2685. double _pixel_x = double.Parse(posParts[0]);
  2686. double _pixel_y = double.Parse(posParts[1]);
  2687. double _pixel_u = double.Parse(posParts[2]);
  2688. //转换点位-像素转换成机器人绝对坐标
  2689. var calibResult = _calibrationService.ConvertPixelToPosition((_pixel_x, _pixel_y, _pixel_u), robotCoord, calib, RobotBrand.XYZ_Platform);
  2690. if (!calibResult.IsSucceed)
  2691. {
  2692. return (false, 0, 0, 0, outImage, outGraphicCollection);
  2693. }
  2694. return (true, calibResult.X, calibResult.Y, calibResult.U, outImage, outGraphicCollection);
  2695. }
  2696. SendTaskMessage(Lang.多次拍照失败, MessageLevel.Alarm);
  2697. return (false, 0, 0, 0, outImage, outGraphicCollection);
  2698. }
  2699. catch (Exception ex)
  2700. {
  2701. LogHelper.WriteLogError("执行相机取图并获取单点位时出错!", ex);
  2702. return (false, 0, 0, 0, outImage, outGraphicCollection);
  2703. }
  2704. finally
  2705. {
  2706. await TurnOffLightAfterPhoto(procedure);
  2707. }
  2708. }
  2709. /// <summary>
  2710. /// 从 ToolBlock 的输出集合中根据 Procedure 配置提取需要发送的输出项并做必要的坐标转换。
  2711. /// 返回元组:是否成功、错误信息(失败时)和名称->(是否点位, 值) 的字典。
  2712. /// </summary>
  2713. public (bool IsSucceed, string ErrMsg, Dictionary<string, (bool IsPoint, object Value)> Output) GetVisionOutput(ProcedureModel procedure, CogToolBlockTerminalCollection outputCollection, double[] robotPos)
  2714. {
  2715. RobotBrand robotBrand = RobotBrand.Default;
  2716. var robot = _configService.GetRobot(procedure.RobotId);
  2717. if (robot != null)
  2718. {
  2719. robotBrand = robot.RobotBrand;
  2720. }
  2721. List<string> SendResults = new List<string>();
  2722. Dictionary<string, (bool IsPoint, object Value)> ResultCollection = new Dictionary<string, (bool IsPoint, object Value)>();
  2723. foreach (var output in procedure.ProcedureOutputs)
  2724. {
  2725. //根据输出类型进行区分输出
  2726. if (output.ValueType == typeof(string))
  2727. {
  2728. //需要点位转换时,进行点位提取
  2729. if (output.IsPointTran)
  2730. {
  2731. if (outputCollection[output.Name].Value == null || string.IsNullOrEmpty(outputCollection[output.Name].Value.ToString()))
  2732. {
  2733. //如果需要输出的项的值为空,即点位数据为空,则输出点位的个数为0
  2734. ResultCollection.Add(output.Name, (true, null));
  2735. continue;
  2736. }
  2737. string[] strpoints = outputCollection[output.Name].Value.ToString().Split(';');
  2738. //存储当前输出点位集合
  2739. List<string[]> currentPointsForFeeder = new List<string[]>();
  2740. //获取相机校准
  2741. var calib = _calibrationService.GetCalibration(procedure.CalibrationId);
  2742. if (calib == null)
  2743. {
  2744. SendTaskMessage(Lang.没有相机校准信息, MessageLevel.Alarm);
  2745. return (false, "NotCalibrations", null);
  2746. }
  2747. // 判断相机安装方式,如果是J4移动相机或者XYZ平台时,则需要判断robotPos不能为null
  2748. if ((calib.CameraMount == CameraMount.MobileJ4 || calib.CameraMount == CameraMount.MobileDown_XYPlatform) && robotPos == null)
  2749. {
  2750. SendTaskMessage(Lang.机器人当前位置不能为空, MessageLevel.Alarm);
  2751. return (false, "RobotPositionNull", null);
  2752. }
  2753. List<string> SendDtat = new List<string>();
  2754. List<string> points = new List<string>();
  2755. //遍历所有的输出点位
  2756. foreach (var pos in strpoints)
  2757. {
  2758. //先将pos按照逗号进行分隔,拿到数组,判断是否至少包含3个元素,并且前三个元素可以转换为double,确保是有效的点位数据
  2759. if (string.IsNullOrEmpty(pos))
  2760. {
  2761. continue;
  2762. }
  2763. //先将pos按照逗号进行分隔,拿到数组
  2764. var posParts = pos.Split(',');
  2765. if (posParts.Length < 3 ||
  2766. !double.TryParse(posParts[0], out double _pixel_x) ||
  2767. !double.TryParse(posParts[1], out double _pixel_y) ||
  2768. !double.TryParse(posParts[2], out double _pixel_u))
  2769. {
  2770. SendTaskMessage(string.Format(Lang.点位数据格式错误, pos), MessageLevel.Alarm);
  2771. return (false, "PointDataFormatError", null);
  2772. }
  2773. //转换点位-像素转换成机器人绝对坐标
  2774. var calibResult = _calibrationService.ConvertPixelToPosition((_pixel_x, _pixel_y, _pixel_u), robotPos, calib, robotBrand);
  2775. if (!calibResult.IsSucceed)
  2776. {
  2777. return (false, "CalibrationFailed", null);
  2778. }
  2779. //截取posParts数组从索引3开始到结尾的所有元素,得到新新的数组extraInfoArray
  2780. string[] extraInfoArray = posParts.Skip(3).ToArray();
  2781. //将rpos转换为字符串数组,保留3位小数
  2782. string[] strings = new string[] { $"{calibResult.X:F3}", $"{calibResult.Y:F3}", $"{calibResult.U:F3}" };
  2783. List<string> rposString = new List<string>(strings);
  2784. if (extraInfoArray.Length > 0)
  2785. {
  2786. rposString.AddRange(extraInfoArray);
  2787. }
  2788. currentPointsForFeeder.Add(rposString.ToArray());
  2789. }
  2790. ResultCollection[output.Name] = (true, currentPointsForFeeder);
  2791. }
  2792. //直接输出字符串
  2793. else
  2794. {
  2795. if (outputCollection[output.Name].Value == null || string.IsNullOrEmpty(outputCollection[output.Name].Value.ToString()))
  2796. {
  2797. ResultCollection.Add(output.Name, (false, null));
  2798. continue;
  2799. }
  2800. ResultCollection[output.Name] = (false, outputCollection[output.Name].Value.ToString());
  2801. }
  2802. }
  2803. else
  2804. {
  2805. if (outputCollection[output.Name].Value == null)
  2806. {
  2807. ResultCollection.Add(output.Name, (false, null));
  2808. }
  2809. else
  2810. {
  2811. ResultCollection[output.Name] = (false, outputCollection[output.Name].Value.ToString());
  2812. }
  2813. }
  2814. }
  2815. return (true, string.Empty, ResultCollection);
  2816. }
  2817. /// <summary>
  2818. /// 拍照前针对 Feeder 的准备动作:设置灯、必要时供料或振动等。
  2819. /// </summary>
  2820. public async Task ExecuteFeederForPhotoBefore(IVoiceCoilMotorFeeder Feeder, ProcedureModel procedure, bool doVibrateFirst, bool doCaptureFirst, CancellationToken cancellationToken)
  2821. {
  2822. // 1. 设置Feeder光源亮度、打开光源
  2823. if (Feeder.FeederBrand == FeederBrand.AFAG)
  2824. {
  2825. await Feeder.SetLightValueAsync((ushort)procedure.LightValue);
  2826. }
  2827. else
  2828. {
  2829. //Feeder光源亮度设置
  2830. if (procedure.LightValue > 3)
  2831. {
  2832. var light = await Feeder.GetLightBrightnessAsync();
  2833. if (procedure.LightValue != light)
  2834. {
  2835. await Feeder.SetLightValueAsync((ushort)procedure.LightValue);
  2836. }
  2837. //获取光源的超时时间
  2838. int lightTimeout = await Feeder.GetLightTimeoutAsync();
  2839. if (lightTimeout < 10000)
  2840. {
  2841. await Feeder.SetLightTimeOutAsync(10000);
  2842. }
  2843. //打开光源
  2844. await Feeder.OpenLightAsync();
  2845. }
  2846. }
  2847. if (doCaptureFirst)//如果不振动,等待光源稳定时间
  2848. {
  2849. if (procedure.WaitPhoto > 0) await Task.Delay(procedure.WaitPhoto);
  2850. return;
  2851. }
  2852. //先振后拍时
  2853. if (procedure.VibrationModel == VibrationModel.VibrationPhoto || doVibrateFirst)
  2854. {
  2855. if (procedure.FeederWorks != null && procedure.FeederWorks.FeederWorkList != null)
  2856. {
  2857. bool flog = false;
  2858. //如果上次的Blob面积小于设定的最小值,则触发供料
  2859. if (procedure.LastBlobArea <= procedure.MinArea)
  2860. {
  2861. flog = true;
  2862. SendTaskMessage(Lang.执行料仓供料, MessageLevel.Info);
  2863. await ExecuteFeederStockWorks(Feeder, procedure.FeederStockWorks, cancellationToken);
  2864. if (procedure.WaitFeederStop > 0) await Task.Delay(procedure.WaitFeederStop);
  2865. SendTaskMessage(Lang.料仓供料结束, MessageLevel.Info);
  2866. }
  2867. if (!flog)
  2868. {
  2869. //执行配置的Feeder振动任务
  2870. await ExecuteFeederWorks(Feeder, procedure.FeederWorks, cancellationToken, false);
  2871. if (procedure.WaitFeederStop > 0) await Task.Delay(procedure.WaitFeederStop);
  2872. }
  2873. }
  2874. }
  2875. else
  2876. {
  2877. if (procedure.LightValue > 3)
  2878. {
  2879. if (procedure.WaitPhoto > 0) await Task.Delay(procedure.WaitPhoto);
  2880. }
  2881. //如果上次的Blob面积小于设定的最小值,则触发供料
  2882. if (procedure.LastBlobArea <= procedure.MinArea)
  2883. {
  2884. SendTaskMessage(Lang.执行料仓供料, MessageLevel.Info);
  2885. await ExecuteFeederStockWorks(Feeder, procedure.FeederStockWorks, cancellationToken);
  2886. if (procedure.WaitFeederStop > 0) await Task.Delay(procedure.WaitFeederStop);
  2887. SendTaskMessage(Lang.料仓供料结束, MessageLevel.Info);
  2888. }
  2889. }
  2890. }
  2891. /// <summary>
  2892. /// 拍照后在 NG 情况下的 Feeder 后处理,例如供料或振动。
  2893. /// </summary>
  2894. public async Task ExecuteFeederForPhotoLater(IVoiceCoilMotorFeeder Feeder, ProcedureModel procedure, CancellationToken cancellationToken)
  2895. {
  2896. //根据斑点面积决定是否料仓供料
  2897. if (procedure.LastBlobArea <= procedure.MinArea)
  2898. {
  2899. SendTaskMessage(Lang.执行料仓供料, MessageLevel.Info);
  2900. await ExecuteFeederStockWorks(Feeder, procedure.FeederStockWorks, cancellationToken);
  2901. if (cancellationToken != null && cancellationToken.IsCancellationRequested) return;
  2902. if (procedure.WaitFeederStop > 0) await Task.Delay(procedure.WaitFeederStop, cancellationToken);
  2903. SendTaskMessage(Lang.料仓供料结束, MessageLevel.Info);
  2904. }
  2905. else
  2906. {
  2907. if (procedure.FeederWorks != null && procedure.FeederWorks.FeederWorkList != null)
  2908. {
  2909. SendTaskMessage(Lang.执行Feeder振动, MessageLevel.Info);
  2910. //执行配置的Feeder振动任务
  2911. await ExecuteFeederWorks(Feeder, procedure.FeederWorks, cancellationToken);
  2912. if (cancellationToken != null && cancellationToken.IsCancellationRequested) return;
  2913. if (procedure.WaitFeederStop > 0) await Task.Delay(procedure.WaitFeederStop, cancellationToken);
  2914. SendTaskMessage(Lang.Feeder振动结束, MessageLevel.Info);
  2915. }
  2916. }
  2917. }
  2918. /// <summary>
  2919. /// 并行执行料仓供料和振动任务。
  2920. /// </summary>
  2921. public async Task ExecuteFeederStockWorks(IVoiceCoilMotorFeeder feeder, FeederStockWorks works, CancellationToken cancellationToken, bool isUpdateParame = true)
  2922. {
  2923. //同时执行料仓供料和Feeder振动任务
  2924. var stockTask = ExecuteFeederStockWorksOnly(feeder, works.FeederStockWorkList.ToArray(), cancellationToken);
  2925. var vibrationTask = ExecuteFeederWorkOnly(feeder, works.FeederWorkList.ToArray(), cancellationToken);
  2926. await Task.WhenAll(stockTask, vibrationTask);
  2927. }
  2928. /// <summary>
  2929. /// 执行料仓振动任务序列(仅料仓相关动作)。
  2930. /// </summary>
  2931. public async Task ExecuteFeederStockWorksOnly(IVoiceCoilMotorFeeder feeder, FeederStockWork[] works, CancellationToken cancellationToken)
  2932. {
  2933. //执行配置的料仓振动任务
  2934. if (feeder.FeederBrand == FeederBrand.AFAG)
  2935. {
  2936. foreach (var stockwork in works)
  2937. {
  2938. if (stockwork.RegisterIndex == 0)
  2939. {
  2940. if (stockwork.Duration > 0) await Task.Delay(stockwork.Duration, cancellationToken);
  2941. }
  2942. else if (stockwork.RegisterIndex == 1)
  2943. {
  2944. // 保留原注释的位置给 Modbus 操作
  2945. }
  2946. if (cancellationToken != null && cancellationToken.IsCancellationRequested)
  2947. {
  2948. return;
  2949. }
  2950. }
  2951. }
  2952. else
  2953. {
  2954. foreach (var stockwork in works)
  2955. {
  2956. if (stockwork.Function == VibrationFunction.Delay)
  2957. {
  2958. if (stockwork.Duration > 0) await Task.Delay(stockwork.Duration, cancellationToken);
  2959. }
  2960. else
  2961. {
  2962. await feeder.OutputAsync(((int)stockwork.Function) + 1, stockwork.Duration);
  2963. if (stockwork.Duration > 0) await Task.Delay(stockwork.Duration, cancellationToken);
  2964. }
  2965. if (cancellationToken != null && cancellationToken.IsCancellationRequested)
  2966. {
  2967. return;
  2968. }
  2969. }
  2970. }
  2971. }
  2972. /// <summary>
  2973. /// 执行单独的 Feeder 振动动作序列(仅振动相关)。
  2974. /// </summary>
  2975. public async Task ExecuteFeederWorkOnly(IVoiceCoilMotorFeeder feeder, FeederWork[] works, CancellationToken cancellationToken, bool isUpdateParame = true)
  2976. {
  2977. if (works == null)
  2978. {
  2979. return;
  2980. }
  2981. if (feeder.FeederBrand == FeederBrand.AFAG)
  2982. {
  2983. //执行配置的Feeder振动任务
  2984. foreach (var feederwork in works)
  2985. {
  2986. if (feederwork.ConfigIndex < 0)
  2987. {
  2988. continue;
  2989. }
  2990. if (feederwork.ConfigIndex == 0)
  2991. {
  2992. if (feederwork.Duration > 0) await Task.Delay(feederwork.Duration, cancellationToken);
  2993. }
  2994. else
  2995. {
  2996. ((AfagFeeder)feeder).LoadConfiguration(feederwork.ConfigIndex);
  2997. ((AfagFeeder)feeder).SetIntensity(feederwork.Intensity);
  2998. ((AfagFeeder)feeder).SetDirection(feederwork.Direction);
  2999. if (feederwork.Duration > 0) await Task.Delay(feederwork.Duration, cancellationToken);
  3000. if (cancellationToken != null && cancellationToken.IsCancellationRequested)
  3001. {
  3002. return;
  3003. }
  3004. ((AfagFeeder)feeder).SetIntensity(0);
  3005. }
  3006. if (cancellationToken != null && cancellationToken.IsCancellationRequested)
  3007. {
  3008. return;
  3009. }
  3010. }
  3011. }
  3012. else
  3013. {
  3014. //执行配置的Feeder振动任务
  3015. foreach (var feederwork in works)
  3016. {
  3017. if (feederwork.Function == VibrationFunction.Delay)
  3018. {
  3019. if (feederwork.Duration > 0) await Task.Delay(feederwork.Duration, cancellationToken);
  3020. }
  3021. else
  3022. {
  3023. if (feederwork.SingleAction != null && isUpdateParame)
  3024. {
  3025. await feeder.SetShakeParametersAsync((int)feederwork.Function, feederwork.SingleAction);
  3026. }
  3027. await feeder.StartAction((int)feederwork.Function, feederwork.Duration);
  3028. if (feederwork.Duration > 0) await Task.Delay(feederwork.Duration, cancellationToken);
  3029. }
  3030. if (cancellationToken != null && cancellationToken.IsCancellationRequested)
  3031. {
  3032. return;
  3033. }
  3034. }
  3035. }
  3036. }
  3037. /// <summary>
  3038. /// 执行 Feeder 振动集合(逐个执行 FeederWorkList 中的动作)。
  3039. /// </summary>
  3040. public async Task ExecuteFeederWorks(IVoiceCoilMotorFeeder feeder, FeederWorks works, CancellationToken cancellationToken, bool isUpdateParame = true)
  3041. {
  3042. if (feeder.FeederBrand == FeederBrand.AFAG)
  3043. {
  3044. foreach (var feederwork in works.FeederWorkList)
  3045. {
  3046. if (feederwork.ConfigIndex < 0)
  3047. {
  3048. continue;
  3049. }
  3050. if (feederwork.ConfigIndex == 0)
  3051. {
  3052. await Task.Delay(feederwork.Duration, cancellationToken);
  3053. }
  3054. else
  3055. {
  3056. ((AfagFeeder)feeder).LoadConfiguration(feederwork.ConfigIndex);
  3057. ((AfagFeeder)feeder).SetIntensity(feederwork.Intensity);
  3058. ((AfagFeeder)feeder).SetDirection(feederwork.Direction);
  3059. await Task.Delay(feederwork.Duration, cancellationToken);
  3060. if (cancellationToken != null && cancellationToken.IsCancellationRequested)
  3061. {
  3062. return;
  3063. }
  3064. ((AfagFeeder)feeder).SetIntensity(0);
  3065. }
  3066. if (cancellationToken != null && cancellationToken.IsCancellationRequested)
  3067. {
  3068. return;
  3069. }
  3070. }
  3071. }
  3072. else
  3073. {
  3074. foreach (var feederwork in works.FeederWorkList)
  3075. {
  3076. if (feederwork.Function == VibrationFunction.Delay)
  3077. {
  3078. if (feederwork.Duration > 0) await Task.Delay(feederwork.Duration, cancellationToken);
  3079. }
  3080. else
  3081. {
  3082. if (feederwork.SingleAction != null && isUpdateParame)
  3083. {
  3084. await feeder.SetShakeParametersAsync((int)feederwork.Function, feederwork.SingleAction);
  3085. }
  3086. await feeder.StartAction((int)feederwork.Function, feederwork.Duration);
  3087. if (feederwork.Duration > 0) await Task.Delay(feederwork.Duration, cancellationToken);
  3088. }
  3089. if (cancellationToken != null && cancellationToken.IsCancellationRequested)
  3090. {
  3091. return;
  3092. }
  3093. }
  3094. }
  3095. }
  3096. /// <summary>
  3097. /// 在拍照前设置光源亮度和打开光源
  3098. /// </summary>
  3099. /// <param name="procedure">流程模型</param>
  3100. /// <returns></returns>
  3101. public async Task SetLightBeforePhoto(ProcedureModel procedure)
  3102. {
  3103. var sysConfig = _configService.GetSystemConfiguration();
  3104. if (sysConfig.LightUse == true)
  3105. {
  3106. return;
  3107. }
  3108. //判断当前流程是否启用光源控制
  3109. if (procedure.IsControlLightChannels)
  3110. {
  3111. //打开所有需要控制的光源通道
  3112. foreach (var lightChannel in procedure.LightChannels)
  3113. {
  3114. bool isSucceed = false;
  3115. isSucceed = await _lightManagerService.TurnOnGlobalChannelAsync(lightChannel.GlobalIndex);
  3116. if (!isSucceed)
  3117. {
  3118. LogHelper.WriteLogInfo($"设置光源通道{lightChannel.GlobalIndex}打开失败!");
  3119. }
  3120. isSucceed = await _lightManagerService.SetGlobalChannelBrightnessAsync(lightChannel.GlobalIndex, lightChannel.DefaultBrightness);
  3121. if (!isSucceed)
  3122. {
  3123. LogHelper.WriteLogInfo($"设置光源通道{lightChannel.GlobalIndex}亮度{lightChannel.DefaultBrightness}失败!");
  3124. }
  3125. }
  3126. }
  3127. }
  3128. /// <summary>
  3129. /// 在拍照后关闭光源
  3130. /// </summary>
  3131. /// <param name="procedure">流程模型</param>
  3132. /// <returns></returns>
  3133. public async Task TurnOffLightAfterPhoto(ProcedureModel procedure)
  3134. {
  3135. var sysConfig = _configService.GetSystemConfiguration();
  3136. if (sysConfig.LightUse == true)
  3137. {
  3138. return;
  3139. }
  3140. //判断当前流程是否启用光源控制
  3141. if (procedure.IsControlLightChannels)
  3142. {
  3143. //关闭所有需要控制的光源通道
  3144. foreach (var lightChannel in procedure.LightChannels)
  3145. {
  3146. bool isSucceed = false;
  3147. isSucceed = await _lightManagerService.TurnOffGlobalChannelAsync(lightChannel.GlobalIndex);
  3148. if (!isSucceed)
  3149. {
  3150. LogHelper.WriteLogInfo($"设置光源通道{lightChannel.GlobalIndex}关闭失败!");
  3151. }
  3152. }
  3153. }
  3154. }
  3155. #endregion
  3156. }
  3157. }