RemoteCommandService.cs 136 KB

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