RemoteCommandService.cs 119 KB

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