RemoteCommandService.cs 92 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026
  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 Org.BouncyCastle.Tls;
  7. using Prism.Events;
  8. using Prism.Ioc;
  9. using Prism.Regions;
  10. using System;
  11. using System.Collections.Concurrent;
  12. using System.Collections.Generic;
  13. using System.ComponentModel;
  14. using System.IO;
  15. using System.Linq;
  16. using System.Reflection;
  17. using System.Text;
  18. using System.Threading;
  19. using System.Threading.Tasks;
  20. using System.Windows.Shapes;
  21. using Team.FFFeederService;
  22. using Team.FFFeederService.Interfaces;
  23. using TeamAAS_VP.Core;
  24. using TeamAAS_VP.Data;
  25. using TeamAAS_VP.Enums;
  26. using TeamAAS_VP.Events;
  27. using TeamAAS_VP.Interfaces;
  28. using TeamAAS_VP.Models;
  29. using TeamAAS_VP.Models.Calibration;
  30. using TeamAAS_VP.Models.Feeder;
  31. using TeamAAS_VP.Models.Product;
  32. using TeamAAS_VP.Resources.Languages;
  33. namespace TeamAAS_VP.Services
  34. {
  35. /// <summary>
  36. /// 远程命令服务:
  37. /// 负责解析并执行外部传入的命令字符串(例如 LoadProduct、视觉流程触发、清料任务等)。
  38. /// 该类封装了原 Management.ExecuteRemoteCommand 的精简迁移实现,依赖于领域服务(产品、配置、校准、Feeder、相机、机器人、系统数据库等)。
  39. /// 线程安全:通过内部计数器和 ConcurrentDictionary 跟踪正在运行的任务。
  40. /// </summary>
  41. public class RemoteCommandService : IRemoteCommandService, INotifyPropertyChanged
  42. {
  43. // 依赖服务,由构造函数注入
  44. private readonly IEventAggregator _eventAggregator;
  45. private readonly IProductService _productService;
  46. private readonly IConfigService _configService;
  47. private readonly ICalibrationService _calibrationService;
  48. private readonly IFeederService _feederService;
  49. private readonly ICameraService _cameraService;
  50. private readonly IRobotService _robotService;
  51. private readonly IContainerProvider _container;
  52. private readonly IRegionManager _regionManager;
  53. private readonly ISystemDatabaseService _systemDatabaseService;
  54. /// <summary>
  55. /// 节拍计时任务的取消令牌,用于 StartCycleTiming/StopCycleTiming。
  56. /// </summary>
  57. private CancellationTokenSource _cycleTimingCts;
  58. /// <summary>
  59. /// 清料任务的取消令牌字典,Key 为任务编号(TaskCode)。
  60. /// 当需要取消特定清料任务时,通过该字典查找并调用 Cancel。
  61. /// </summary>
  62. private readonly ConcurrentDictionary<int, CancellationTokenSource> _clearMaterialCtsDict = new ConcurrentDictionary<int, CancellationTokenSource>();
  63. // 内部执行状态计数器和任务跟踪集合
  64. private int _activeCount;
  65. private int _visionActiveCount;
  66. private readonly ConcurrentDictionary<Guid, Task> _runningTasks = new ConcurrentDictionary<Guid, Task>();
  67. // INotifyPropertyChanged 实现
  68. public event PropertyChangedEventHandler PropertyChanged;
  69. private void OnPropertyChanged(string name) => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
  70. /// <summary>
  71. /// 标识是否存在任意正在执行的命令(非视觉与视觉命令)。
  72. /// 由 TrackExecutionAsync 自动维护。
  73. /// </summary>
  74. public bool IsExecuting => Volatile.Read(ref _activeCount) > 0;
  75. /// <summary>
  76. /// 标识是否存在正在执行的视觉指令。
  77. /// 由 TrackExecutionAsync 在 isVision 参数为 true 时自动维护。
  78. /// </summary>
  79. public bool IsExecutingVisionCommand => Volatile.Read(ref _visionActiveCount) > 0;
  80. /// <summary>
  81. /// 当执行状态发生变化(开始/结束)时触发(便于传统事件订阅)。
  82. /// </summary>
  83. public event EventHandler ExecutionStateChanged;
  84. /// <summary>
  85. /// 节拍计时的定时回调事件,通知订阅者当前已用时。
  86. /// </summary>
  87. public event EventHandler<TimeSpan> CycleTimingTicked;
  88. /// <summary>
  89. /// 构造函数,注入必要的系统服务。
  90. /// </summary>
  91. /// <param name="eventAggregator">事件聚合器,用于发布 UI 渲染/消息等事件。</param>
  92. /// <param name="regionManager">区域管理器,用于 UI 区域导航(在脚本中可能使用)。</param>
  93. /// <param name="productService">产品服务,用于加载/查询产品信息。</param>
  94. /// <param name="configService">配置服务,用于读取机器人/任务/Feeder 等配置。</param>
  95. /// <param name="calibrationService">校准服务,用于像素到机器人坐标的转换。</param>
  96. /// <param name="feederService">Feeder 服务,控制料仓/振动等。</param>
  97. /// <param name="cameraService">相机服务,用于图像采集。</param>
  98. /// <param name="robotService">机器人服务,提供机器人状态码/调试模式等信息。</param>
  99. /// <param name="container">IOC 容器提供者,用于脚本执行时解析依赖。</param>
  100. /// <param name="systemDatabaseService">系统数据库服务,用于记录产量/报警等。</param>
  101. public RemoteCommandService(IEventAggregator eventAggregator, IRegionManager regionManager, IProductService productService, IConfigService configService, ICalibrationService calibrationService,
  102. IFeederService feederService, ICameraService cameraService, IRobotService robotService, IContainerProvider container, ISystemDatabaseService systemDatabaseService)
  103. {
  104. _eventAggregator = eventAggregator;
  105. _regionManager = regionManager;
  106. _productService = productService;
  107. _configService = configService;
  108. _calibrationService = calibrationService;
  109. _feederService = feederService;
  110. _cameraService = cameraService;
  111. _robotService = robotService;
  112. _container = container;
  113. _systemDatabaseService = systemDatabaseService;
  114. }
  115. /// <summary>
  116. /// 占位 Dispose 方法(当前无资源释放逻辑)。
  117. /// </summary>
  118. public void Dispose() { }
  119. /// <summary>
  120. /// 通用的异步执行包装器。该方法:
  121. /// - 为每次执行生成唯一 id 并加入运行任务集合以便跟踪
  122. /// - 维护 _activeCount 和 _visionActiveCount
  123. /// - 在任务开始/结束时触发属性变化和 ExecutionStateChanged 事件
  124. /// - 返回工作 delegate 的结果
  125. /// </summary>
  126. /// <typeparam name="T">工作返回类型</typeparam>
  127. /// <param name="work">以 CancellationToken 为参数的异步工作委托</param>
  128. /// <param name="isVision">指示该工作是否为视觉命令(影响视觉计数器)</param>
  129. /// <param name="ct">外部取消令牌,传递给工作委托</param>
  130. /// <returns>工作委托的返回值</returns>
  131. private async Task<T> TrackExecutionAsync<T>(Func<CancellationToken, Task<T>> work, bool isVision, CancellationToken ct)
  132. {
  133. var id = Guid.NewGuid();
  134. Interlocked.Increment(ref _activeCount);
  135. if (isVision) Interlocked.Increment(ref _visionActiveCount);
  136. OnPropertyChanged(nameof(IsExecuting));
  137. OnPropertyChanged(nameof(IsExecutingVisionCommand));
  138. ExecutionStateChanged?.Invoke(this, EventArgs.Empty);
  139. try
  140. {
  141. var task = work(ct);
  142. _runningTasks.TryAdd(id, task);
  143. var result = await task.ConfigureAwait(false);
  144. return result;
  145. }
  146. finally
  147. {
  148. Interlocked.Decrement(ref _activeCount);
  149. if (isVision) Interlocked.Decrement(ref _visionActiveCount);
  150. _runningTasks.TryRemove(id, out _);
  151. OnPropertyChanged(nameof(IsExecuting));
  152. OnPropertyChanged(nameof(IsExecutingVisionCommand));
  153. ExecutionStateChanged?.Invoke(this, EventArgs.Empty);
  154. }
  155. }
  156. /// <summary>
  157. /// 解析并执行传入的命令字符串。命令以逗号分隔,第一个字段为命令名称,后续为参数。
  158. /// 支持多种内建命令(示例:LoadProduct、GetProductName、CycleTime、Record、StartClearMaterial 等),以及映射到产品 CameraProcedures 的自定义视觉触发命令。
  159. /// </summary>
  160. /// <param name="command">原始命令字符串</param>
  161. /// <param name="cancellationToken">外部取消令牌</param>
  162. /// <param name="callback">用于将执行结果回传(比如发送到调用方)的回调,参数为单行响应字符串</param>
  163. /// <returns>完成任务</returns>
  164. public async Task ExecuteAsync(string command, CancellationToken cancellationToken, Action<string> callback)
  165. {
  166. var items = (command ?? string.Empty).Split(new[] { ',' }, StringSplitOptions.None).Select(s => s.Trim()).ToArray();
  167. if (items.Length == 0) return;
  168. string triggerCommand = items[0];
  169. string[] commandParams = items.Skip(1).ToArray();
  170. string response = string.Empty;
  171. switch (triggerCommand)
  172. {
  173. case "LoadProduct":
  174. if (commandParams.Length < 1)
  175. {
  176. callback?.Invoke("InvalidParameters");
  177. return;
  178. }
  179. response = await TrackExecutionAsync(async ct =>
  180. {
  181. var ok = await LoadProductAsync(commandParams[0], ct);
  182. return ok ? "OK" : "NG";
  183. }, isVision: false, cancellationToken);
  184. callback?.Invoke($"LoadProduct,{response}");
  185. break;
  186. case "GetProductName":
  187. if (commandParams.Length < 1)
  188. {
  189. response = await TrackExecutionAsync(async ct =>
  190. {
  191. return await GetCurrentProductNameAsync(ct);
  192. }, isVision: false, cancellationToken);
  193. if (string.IsNullOrEmpty(response))
  194. {
  195. callback?.Invoke("GetProductName,NG");
  196. }
  197. else
  198. {
  199. callback?.Invoke($"GetProductName,{response}");
  200. }
  201. break;
  202. }
  203. else if (commandParams.Length == 1)
  204. {
  205. if (!int.TryParse(commandParams[0], out int productNumber))
  206. {
  207. callback?.Invoke("InvalidParameters");
  208. return;
  209. }
  210. response = await TrackExecutionAsync(async ct =>
  211. {
  212. return await GetProductNameByNumberAsync(productNumber, ct);
  213. }, isVision: false, cancellationToken);
  214. if (string.IsNullOrEmpty(response))
  215. {
  216. callback?.Invoke($"GetProductName,NG");
  217. }
  218. else
  219. {
  220. callback?.Invoke($"GetProductName,{response}");
  221. }
  222. break;
  223. }
  224. else
  225. {
  226. callback?.Invoke("InvalidParameters");
  227. return;
  228. }
  229. case "GetProductID":
  230. if (commandParams.Length < 1)
  231. {
  232. response = await TrackExecutionAsync(async ct =>
  233. {
  234. int productNum = await GetCurrentProductNumberAsync(ct);
  235. return productNum.ToString();
  236. }, isVision: false, cancellationToken);
  237. if (response == "-1")
  238. {
  239. callback?.Invoke("GetProductID,NG");
  240. }
  241. else
  242. {
  243. callback?.Invoke($"GetProductID,{response}");
  244. }
  245. break;
  246. }
  247. else if (commandParams.Length == 1)
  248. {
  249. response = await TrackExecutionAsync(async ct =>
  250. {
  251. int productNum = await GetProductNumberByNameAsync(commandParams[0], ct);
  252. return productNum.ToString();
  253. }, isVision: false, cancellationToken);
  254. if (response == "-1")
  255. {
  256. callback?.Invoke($"GetProductID,NG");
  257. }
  258. else
  259. {
  260. callback?.Invoke($"GetProductID,{response}");
  261. }
  262. break;
  263. }
  264. else
  265. {
  266. callback?.Invoke("InvalidParameters");
  267. return;
  268. }
  269. case "GetRobotPointsCountById":
  270. if (commandParams.Length < 2 || !int.TryParse(commandParams[0], out int robotNumber) || !int.TryParse(commandParams[1], out int pointNumber))
  271. {
  272. callback?.Invoke("InvalidParameters");
  273. return;
  274. }
  275. response = await TrackExecutionAsync(async ct =>
  276. {
  277. return await GetRobotPointInfoAsync(robotNumber, pointNumber, ct);
  278. }, isVision: false, cancellationToken);
  279. if (string.IsNullOrEmpty(response))
  280. {
  281. callback?.Invoke($"GetRobotPointsCountById,NG");
  282. }
  283. else
  284. {
  285. callback?.Invoke($"GetRobotPointsCountById,{response}");
  286. }
  287. break;
  288. case "GetPalletPoint":
  289. 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))
  290. {
  291. callback?.Invoke("InvalidParameters");
  292. return;
  293. }
  294. response = await TrackExecutionAsync(async ct =>
  295. {
  296. return await GetRobotPalletPointInfoAsync(robotNumber1, palletNumber1, pointNumber1, ct);
  297. }, isVision: false, cancellationToken);
  298. if (string.IsNullOrEmpty(response))
  299. {
  300. callback?.Invoke($"GetPalletPoint,NG");
  301. }
  302. else
  303. callback?.Invoke($"GetPalletPoint,{response}");
  304. break;
  305. case "CycleTime":
  306. if (commandParams.Length < 1)
  307. {
  308. callback?.Invoke("InvalidParameters");
  309. return;
  310. }
  311. if (int.Parse(commandParams[0]) == 1)
  312. {
  313. response = await TrackExecutionAsync(async ct =>
  314. {
  315. bool cycleResult = await StartCycleTimingAsync(ct);
  316. return cycleResult ? "OK" : "NG";
  317. }, isVision: false, cancellationToken);
  318. callback?.Invoke($"CycleTime,{response}");
  319. break;
  320. }
  321. else
  322. {
  323. response = await TrackExecutionAsync(async ct =>
  324. {
  325. bool cycleResult = await StopCycleTimingAsync(ct);
  326. return cycleResult ? "OK" : "NG";
  327. }, isVision: false, cancellationToken);
  328. callback?.Invoke($"CycleTime,{response}");
  329. break;
  330. }
  331. case "Record":
  332. if (commandParams.Length < 1)
  333. {
  334. callback?.Invoke("InvalidParameters");
  335. return;
  336. }
  337. response = await TrackExecutionAsync(async ct =>
  338. {
  339. bool recordResult = await CreateProductionCountAsync(commandParams[0].Trim(), ct);
  340. return recordResult ? "OK" : "NG";
  341. }, isVision: false, cancellationToken);
  342. callback?.Invoke($"Record,{response}");
  343. break;
  344. case "RecordQuery":
  345. if (commandParams.Length < 1)
  346. {
  347. callback?.Invoke("InvalidParameters");
  348. return;
  349. }
  350. response = await TrackExecutionAsync(async ct =>
  351. {
  352. int recordCount = await GetCurrentProductionCountAsync(commandParams[0].Trim(), ct);
  353. return recordCount.ToString();
  354. }, isVision: false, cancellationToken);
  355. callback?.Invoke($"RecordQuery,{response}");
  356. break;
  357. case "RecordReset":
  358. if (commandParams.Length < 1)
  359. {
  360. callback?.Invoke("InvalidParameters");
  361. return;
  362. }
  363. response = await TrackExecutionAsync(async ct =>
  364. {
  365. bool recordResetResult = await ResetProductionCountAsync(commandParams[0].Trim(), ct);
  366. return recordResetResult ? "OK" : "NG";
  367. }, isVision: false, cancellationToken);
  368. callback?.Invoke($"RecordReset,{response}");
  369. break;
  370. case "Err":
  371. if (commandParams.Length < 2)
  372. {
  373. callback?.Invoke("InvalidParameters");
  374. return;
  375. }
  376. response = await TrackExecutionAsync(async ct =>
  377. {
  378. bool errResult = await CreateAlarmRecordAsync(commandParams[0].Trim(), commandParams[1].Trim(), ct);
  379. return errResult ? "OK" : "NG";
  380. }, isVision: false, cancellationToken);
  381. callback?.Invoke($"Err,{response}");
  382. break;
  383. case "Info":
  384. if (commandParams.Length < 1)
  385. {
  386. callback?.Invoke("InvalidParameters");
  387. return;
  388. }
  389. response = await TrackExecutionAsync(async ct =>
  390. {
  391. bool infoResult = await CreateOperationLogAsync(commandParams[0].Trim(), ct);
  392. return infoResult ? "OK" : "NG";
  393. }, isVision: false, cancellationToken);
  394. callback?.Invoke($"Info,{response}");
  395. break;
  396. case "GetGlobalParam":
  397. if (commandParams.Length == 1)
  398. {
  399. response = await TrackExecutionAsync(async ct =>
  400. {
  401. return await GetGlobalParameterAsync(int.Parse(commandParams[0]), -1, ct);
  402. }, isVision: false, cancellationToken);
  403. if (string.IsNullOrEmpty(response))
  404. {
  405. callback?.Invoke("GetGlobalParam,NG");
  406. }
  407. else
  408. {
  409. callback?.Invoke($"GetGlobalParam,{response}");
  410. }
  411. break;
  412. }
  413. else if (commandParams.Length == 2)
  414. {
  415. response = await TrackExecutionAsync(async ct =>
  416. {
  417. return await GetGlobalParameterAsync(int.Parse(commandParams[0]), int.Parse(commandParams[1]), ct);
  418. }, isVision: false, cancellationToken);
  419. if (string.IsNullOrEmpty(response))
  420. {
  421. callback?.Invoke("GetGlobalParam,NG");
  422. }
  423. else
  424. {
  425. callback?.Invoke($"GetGlobalParam,{response}");
  426. }
  427. break;
  428. }
  429. else
  430. {
  431. callback?.Invoke("InvalidParameters");
  432. return;
  433. }
  434. case "GetSpeed":
  435. response = await TrackExecutionAsync(async ct =>
  436. {
  437. return await GetOperationSpeedAsync(ct);
  438. }, isVision: false, cancellationToken);
  439. if (string.IsNullOrEmpty(response))
  440. {
  441. callback?.Invoke("GetSpeed,NG");
  442. return;
  443. }
  444. else
  445. callback?.Invoke($"GetSpeed,{response}");
  446. break;
  447. case "GetToolParam":
  448. if (commandParams.Length < 2)
  449. {
  450. callback?.Invoke("InvalidParameters");
  451. return;
  452. }
  453. response = await TrackExecutionAsync(async ct =>
  454. {
  455. return await GetToolParamAsync(commandParams[0], int.Parse(commandParams[1]), ct);
  456. }, isVision: false, cancellationToken);
  457. if (string.IsNullOrEmpty(response))
  458. {
  459. callback?.Invoke("GetToolParam,NG");
  460. return;
  461. }
  462. else
  463. callback?.Invoke($"GetToolParam,{response}");
  464. break;
  465. case "GetProcedureParam":
  466. if (commandParams.Length < 1)
  467. {
  468. callback?.Invoke("InvalidParameters");
  469. return;
  470. }
  471. response = await TrackExecutionAsync(async ct =>
  472. {
  473. return await GetProcessParamAsync(commandParams[0], ct);
  474. }, isVision: false, cancellationToken);
  475. if (string.IsNullOrEmpty(response))
  476. {
  477. callback?.Invoke("GetProcedureParam,NG");
  478. return;
  479. }
  480. else
  481. callback?.Invoke($"GetProcedureParam,{response}");
  482. break;
  483. case "StartClearMaterial":
  484. if (commandParams.Length < 1)
  485. {
  486. callback?.Invoke("InvalidParameters");
  487. return;
  488. }
  489. response = await TrackExecutionAsync(async ct =>
  490. {
  491. bool startClearResult = await ExecuteClearMaterialTaskAsync(int.Parse(commandParams[0]), ct);
  492. return startClearResult ? "OK" : "NG";
  493. }, isVision: false, cancellationToken);
  494. callback?.Invoke($"StartClearMaterial,{response}");
  495. break;
  496. case "StopClearMaterial":
  497. if (commandParams.Length < 1)
  498. {
  499. callback?.Invoke("InvalidParameters");
  500. return;
  501. }
  502. response = await TrackExecutionAsync(async ct =>
  503. {
  504. bool stopClearResult = await StopClearMaterialTaskAsync(int.Parse(commandParams[0]), ct);
  505. return stopClearResult ? "OK" : "NG";
  506. }, isVision: false, cancellationToken);
  507. callback?.Invoke($"StopClearMaterial,{response}");
  508. break;
  509. case "RobotIsDebugMode":
  510. if (commandParams.Length < 1)
  511. {
  512. callback?.Invoke("InvalidParameters");
  513. return;
  514. }
  515. response = await TrackExecutionAsync(async ct =>
  516. {
  517. bool isDebugMode = await IsRobotInDebugModeAsync(int.Parse(commandParams[0]), ct);
  518. return isDebugMode ? "1" : "0";
  519. }, isVision: false, cancellationToken);
  520. callback?.Invoke($"RobotIsDebugMode,{response}");
  521. break;
  522. default:
  523. var currentProduct = _productService.GetCurrentProduct();
  524. if (currentProduct == null) return;
  525. var procedure = currentProduct.CameraProcedures
  526. .SelectMany(cp => cp.ProcedureModels)
  527. .FirstOrDefault(p => p.TriggerCommand == triggerCommand);
  528. if (procedure == null) return;
  529. var visionResult = await TrackExecutionAsync(async ct =>
  530. {
  531. var r = await ExecuteVisionTaskAsync(procedure, commandParams, ct);
  532. return Tuple.Create(r.IsSucceed, r.Response);
  533. }, isVision: true, cancellationToken);
  534. if (visionResult.Item1)
  535. {
  536. foreach (var item in visionResult.Item2)
  537. {
  538. callback?.Invoke($"{triggerCommand},OK,{item}");
  539. }
  540. }
  541. else
  542. {
  543. string msg = string.Empty;
  544. if (visionResult.Item2 != null && visionResult.Item2.Length > 0)
  545. {
  546. msg = visionResult.Item2[0];
  547. }
  548. callback?.Invoke($"{triggerCommand},NG,{msg}");
  549. }
  550. break;
  551. }
  552. }
  553. /// <summary>
  554. /// 根据产品名称或编号加载并设置当前产品。
  555. /// 若传入字符串可解析为 int,则先按编号查找产品,否则按名称查找。
  556. /// </summary>
  557. /// <param name="productName">产品名称或编号字符串</param>
  558. /// <param name="cancellationToken">取消令牌</param>
  559. /// <returns>加载成功返回 true,否则 false</returns>
  560. public async Task<bool> LoadProductAsync(string productName, CancellationToken cancellationToken)
  561. {
  562. bool exists = _productService.ContainsProductByName(productName);
  563. if (exists)
  564. {
  565. var product = _productService.GetAllProducts().FirstOrDefault(p => p.Name == productName);
  566. await _productService.LoadProductAsync(product.ID);
  567. _productService.SetCurrentProduct(product.ID);
  568. return true;
  569. }
  570. if (int.TryParse(productName, out int productNumber))
  571. {
  572. var product = _productService.GetAllProducts().FirstOrDefault(p => p.NumberCode == productNumber);
  573. if (product != null)
  574. {
  575. await _productService.LoadProductAsync(product.ID);
  576. _productService.SetCurrentProduct(product.ID);
  577. return true;
  578. }
  579. }
  580. return false;
  581. }
  582. /// <summary>
  583. /// 通过产品编号获取产品名称。
  584. /// </summary>
  585. public Task<string> GetProductNameByNumberAsync(int productNumber, CancellationToken cancellationToken)
  586. {
  587. var product = _productService.GetAllProducts().FirstOrDefault(p => p.NumberCode == productNumber);
  588. if (product != null)
  589. {
  590. return Task.FromResult(product.Name);
  591. }
  592. return Task.FromResult(string.Empty);
  593. }
  594. /// <summary>
  595. /// 获取当前被设置为活动的产品名称。如果没有则返回空字符串。
  596. /// </summary>
  597. public Task<string> GetCurrentProductNameAsync(CancellationToken cancellationToken)
  598. {
  599. var currentProduct = _productService.GetCurrentProduct();
  600. if (currentProduct != null)
  601. {
  602. return Task.FromResult(currentProduct.Name);
  603. }
  604. return Task.FromResult(string.Empty);
  605. }
  606. /// <summary>
  607. /// 通过产品名称获取其编号(NumberCode)。找不到则返回 -1。
  608. /// </summary>
  609. public Task<int> GetProductNumberByNameAsync(string productName, CancellationToken cancellationToken)
  610. {
  611. bool exists = _productService.ContainsProductByName(productName);
  612. if (exists)
  613. {
  614. var product = _productService.GetAllProducts().FirstOrDefault(p => p.Name == productName);
  615. return Task.FromResult(product.NumberCode);
  616. }
  617. return Task.FromResult(-1);
  618. }
  619. /// <summary>
  620. /// 获取当前产品编号(NumberCode)。找不到则返回 -1。
  621. /// </summary>
  622. public Task<int> GetCurrentProductNumberAsync(CancellationToken cancellationToken)
  623. {
  624. var currentProduct = _productService.GetCurrentProduct();
  625. if (currentProduct != null)
  626. {
  627. return Task.FromResult(currentProduct.NumberCode);
  628. }
  629. return Task.FromResult(-1);
  630. }
  631. /// <summary>
  632. /// 根据机器人编号和点位编号获取点位信息(字符串表示),查找逻辑基于当前产品的 RobotPoint 配置。
  633. /// </summary>
  634. public Task<string> GetRobotPointInfoAsync(int robotNumber, int pointNumber, CancellationToken cancellationToken)
  635. {
  636. var currentProduct = _productService.GetCurrentProduct();
  637. if (currentProduct == null) return Task.FromResult(string.Empty);
  638. var robot = _configService.GetAllRobots().FirstOrDefault(r => r.RobotNo == robotNumber);
  639. if (robot == null) return Task.FromResult(string.Empty);
  640. var robotPoint = currentProduct.RobotPoint.Robots.FirstOrDefault(rp => rp.Id == robot.Id);
  641. if (robotPoint == null) return Task.FromResult(string.Empty);
  642. var point = robotPoint.Points.FirstOrDefault(p => p.Number == pointNumber);
  643. if (point == null) return Task.FromResult(string.Empty);
  644. return Task.FromResult(point.ToString());
  645. }
  646. /// <summary>
  647. /// 通过机器人编号、托盘编号和点编号获取托盘点位信息,返回格式化字符串。
  648. /// </summary>
  649. public Task<string> GetRobotPalletPointInfoAsync(int robotNumber, int palletNumber, int pointNumber, CancellationToken cancellationToken)
  650. {
  651. var currentProduct = _productService.GetCurrentProduct();
  652. if (currentProduct == null) return Task.FromResult(string.Empty);
  653. var robot = _configService.GetAllRobots().FirstOrDefault(r => r.RobotNo == robotNumber);
  654. if (robot == null) return Task.FromResult(string.Empty);
  655. var robotPoint = currentProduct.RobotPoint.Robots.FirstOrDefault(rp => rp.Id == robot.Id);
  656. if (robotPoint == null) return Task.FromResult(string.Empty);
  657. var pallet = robotPoint.Pallets.FirstOrDefault(p => p.PalletNo == palletNumber);
  658. if (pallet == null) return Task.FromResult(string.Empty);
  659. PalletTool palletTool = new PalletTool(pallet);
  660. if (pointNumber > palletTool.Points.Length || pointNumber < 1) return Task.FromResult(string.Empty);
  661. var pos = palletTool.Points[pointNumber - 1];
  662. 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}";
  663. return Task.FromResult(response);
  664. }
  665. /// <summary>
  666. /// 开始节拍计时。返回是否成功(始终 true)。
  667. /// 会启动后台定时任务并周期性触发 CycleTimingTicked 事件。
  668. /// </summary>
  669. public Task<bool> StartCycleTimingAsync(CancellationToken cancellationToken)
  670. {
  671. if (_cycleTimingCts != null)
  672. {
  673. _cycleTimingCts.Cancel();
  674. _cycleTimingCts.Dispose();
  675. }
  676. _cycleTimingCts = new CancellationTokenSource();
  677. var token = _cycleTimingCts.Token;
  678. Task.Run(async () =>
  679. {
  680. var startTime = DateTime.UtcNow;
  681. while (!token.IsCancellationRequested)
  682. {
  683. var elapsed = DateTime.UtcNow - startTime;
  684. OnCycleTimingTicked(elapsed);
  685. await Task.Delay(100, token);
  686. }
  687. }, token);
  688. return Task.FromResult(true);
  689. }
  690. /// <summary>
  691. /// 停止节拍计时并清理取消令牌。
  692. /// </summary>
  693. public Task<bool> StopCycleTimingAsync(CancellationToken cancellationToken)
  694. {
  695. if (_cycleTimingCts != null)
  696. {
  697. _cycleTimingCts.Cancel();
  698. _cycleTimingCts.Dispose();
  699. _cycleTimingCts = null;
  700. }
  701. return Task.FromResult(true);
  702. }
  703. /// <summary>
  704. /// 新增一条生产计数记录,数量固定为 1。
  705. /// </summary>
  706. public Task<bool> CreateProductionCountAsync(string countItem, CancellationToken cancellationToken)
  707. {
  708. _systemDatabaseService.RecordProductionAsync(new ProductionRecord
  709. {
  710. Category = countItem,
  711. ProductName = _productService.GetCurrentProduct()?.Name ?? "Unknown",
  712. Quantity = 1,
  713. Timestamp = DateTime.UtcNow
  714. });
  715. return Task.FromResult(true);
  716. }
  717. /// <summary>
  718. /// 查询当前产品在指定分类下的累计产量。
  719. /// </summary>
  720. public async Task<int> GetCurrentProductionCountAsync(string countItem, CancellationToken cancellationToken)
  721. {
  722. var currentProduct = _productService.GetCurrentProduct();
  723. if (currentProduct == null) return 0;
  724. var records = _systemDatabaseService.GetProductCategoriesAsync(currentProduct.Name);
  725. int totalCount = await _systemDatabaseService.GetTotalProductionAsync(currentProduct.Name, new List<string> { countItem });
  726. return totalCount;
  727. }
  728. /// <summary>
  729. /// 重置当前产品的生产统计(通过系统 DB 服务)。
  730. /// </summary>
  731. public async Task<bool> ResetProductionCountAsync(string countItem, CancellationToken cancellationToken)
  732. {
  733. var currentProduct = _productService.GetCurrentProduct();
  734. if (currentProduct == null) return false;
  735. await _systemDatabaseService.ResetProductionAsync(currentProduct.Name);
  736. return true;
  737. }
  738. /// <summary>
  739. /// 记录一条报警信息到系统数据库,并通过事件发布错误级别的任务消息。
  740. /// </summary>
  741. public Task<bool> CreateAlarmRecordAsync(string alarmCode, string alarmDescription, CancellationToken cancellationToken)
  742. {
  743. SendTaskMessage(alarmDescription, MessageLevel.Error);
  744. _systemDatabaseService.RecordAlarmAsync(new AlarmRecord
  745. {
  746. Code = alarmCode,
  747. Message = alarmDescription,
  748. Source = "Unknown",
  749. Time = DateTime.UtcNow
  750. });
  751. return Task.FromResult(true);
  752. }
  753. /// <summary>
  754. /// 发布运行信息日志(仅消息推送,不持久化)。
  755. /// </summary>
  756. public Task<bool> CreateOperationLogAsync(string logMessage, CancellationToken cancellationToken)
  757. {
  758. SendTaskMessage(logMessage, MessageLevel.Info);
  759. return Task.FromResult(true);
  760. }
  761. /// <summary>
  762. /// 获取当前产品的全局参数,支持按索引(1-4)返回指定子项,或返回完整 ToString。
  763. /// </summary>
  764. public Task<string> GetGlobalParameterAsync(int parameterNumber, int itemIndex, CancellationToken cancellationToken)
  765. {
  766. var currentProduct = _productService.GetCurrentProduct();
  767. if (currentProduct == null) return Task.FromResult(string.Empty);
  768. if (currentProduct.GlobalParamListCollection == null) return Task.FromResult(string.Empty);
  769. var globalParam = currentProduct.GlobalParamListCollection.FirstOrDefault(p => p.Number == parameterNumber);
  770. if (globalParam == null) return Task.FromResult(string.Empty);
  771. string response = string.Empty;
  772. if (itemIndex == 1)
  773. {
  774. response = $"{globalParam.Number},{globalParam.Name},{globalParam.Param1}";
  775. }
  776. else if (itemIndex == 2)
  777. {
  778. response = $"{globalParam.Number},{globalParam.Name},{globalParam.Param2}";
  779. }
  780. else if (itemIndex == 3)
  781. {
  782. response = $"{globalParam.Number},{globalParam.Name},{globalParam.Param3}";
  783. }
  784. else if (itemIndex == 4)
  785. {
  786. response = $"{globalParam.Number},{globalParam.Name},{globalParam.Param4}";
  787. }
  788. else
  789. {
  790. response = globalParam.ToString();
  791. }
  792. return Task.FromResult(response);
  793. }
  794. /// <summary>
  795. /// 返回当前产品的速度/加速度等运行参数的格式化字符串。
  796. /// </summary>
  797. public Task<string> GetOperationSpeedAsync(CancellationToken cancellationToken)
  798. {
  799. var currentProduct = _productService.GetCurrentProduct();
  800. if (currentProduct == null) return Task.FromResult(string.Empty);
  801. string response = $"{currentProduct.Speed},{currentProduct.Accel},{currentProduct.Speeds},{currentProduct.Accels},{Convert.ToInt16(currentProduct.Power)},{Convert.ToInt16(currentProduct.IsUserUpCamera)}";
  802. return Task.FromResult(response);
  803. }
  804. /// <summary>
  805. /// 获取某流程指定工具编号的工具参数(格式化字符串),找不到返回空字符串。
  806. /// </summary>
  807. public Task<string> GetToolParamAsync(string triggerCommand, int toolNumber, CancellationToken cancellationToken)
  808. {
  809. var currentProduct = _productService.GetCurrentProduct();
  810. if (currentProduct == null) return Task.FromResult(string.Empty);
  811. ProcedureModel procedure = currentProduct.CameraProcedures
  812. .SelectMany(cp => cp.ProcedureModels)
  813. .FirstOrDefault(p => p.TriggerCommand == triggerCommand);
  814. if (procedure == null || procedure.ToolInfo == null) return Task.FromResult(string.Empty);
  815. var tool = procedure.ToolInfo.FirstOrDefault(t => t.Number == toolNumber);
  816. if (tool == null) return Task.FromResult(string.Empty);
  817. if (tool.Tool == null) return Task.FromResult(string.Empty);
  818. 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}";
  819. return Task.FromResult(response);
  820. }
  821. /// <summary>
  822. /// 获取流程参数(例如 WaitPhoto 与用户自定义参数等),以逗号分隔的字符串返回。
  823. /// </summary>
  824. public Task<string> GetProcessParamAsync(string triggerCommand, CancellationToken cancellationToken)
  825. {
  826. var currentProduct = _productService.GetCurrentProduct();
  827. if (currentProduct == null) return Task.FromResult(string.Empty);
  828. ProcedureModel procedure = currentProduct.CameraProcedures
  829. .SelectMany(cp => cp.ProcedureModels)
  830. .FirstOrDefault(p => p.TriggerCommand == triggerCommand);
  831. if (procedure == null || procedure.ToolInfo == null) return Task.FromResult(string.Empty);
  832. StringBuilder response = new StringBuilder();
  833. response.Append($"{procedure.WaitPhoto}");
  834. if (procedure.UserDefineParameters != null)
  835. {
  836. foreach (var param in procedure.UserDefineParameters)
  837. {
  838. response.Append("," + param.ToString());
  839. }
  840. }
  841. return Task.FromResult(response.ToString());
  842. }
  843. /// <summary>
  844. /// 执行指定编号的清料任务(异步)。流程:
  845. /// - 根据配置获取任务
  846. /// - 检查 Feeder 连接性
  847. /// - 使用专用 CancellationTokenSource 跟踪任务并支持停止
  848. /// - 循环执行开挡板、振动、关闭挡板等步骤,检查取消状态
  849. /// </summary>
  850. public async Task<bool> ExecuteClearMaterialTaskAsync(int taskNumber, CancellationToken cancellationToken)
  851. {
  852. var feederClearWork = _configService.GetClearanceTaskByNumber(taskNumber);
  853. if (feederClearWork == null)
  854. {
  855. return false;
  856. }
  857. IVoiceCoilMotorFeeder Feeder = _feederService.GetFeeder(feederClearWork.FeederId);
  858. if (!Feeder.IsConnected)
  859. {
  860. return false;
  861. }
  862. if (_clearMaterialCtsDict.ContainsKey(feederClearWork.TaskCode))
  863. {
  864. return false;
  865. }
  866. _clearMaterialCtsDict[feederClearWork.TaskCode] = new CancellationTokenSource();
  867. if (cancellationToken != null)
  868. {
  869. cancellationToken.Register(() =>
  870. {
  871. if (_clearMaterialCtsDict.ContainsKey(feederClearWork.TaskCode))
  872. {
  873. _clearMaterialCtsDict[feederClearWork.TaskCode].Cancel();
  874. }
  875. });
  876. }
  877. var token = _clearMaterialCtsDict[feederClearWork.TaskCode].Token;
  878. for (int i = 0; i < feederClearWork.ClearCount; i++)
  879. {
  880. await Feeder.OutputAsync((int)feederClearWork.BeforeOutput + 1, 0);
  881. await Task.Delay(200, token);
  882. if ((cancellationToken != null && cancellationToken.IsCancellationRequested) || (token != null && token.IsCancellationRequested))
  883. {
  884. await Feeder.StopOutputAsync();
  885. if (_clearMaterialCtsDict.ContainsKey(feederClearWork.TaskCode))
  886. {
  887. _clearMaterialCtsDict[feederClearWork.TaskCode].Cancel();
  888. _clearMaterialCtsDict.TryRemove(feederClearWork.TaskCode, out _);
  889. }
  890. return false;
  891. }
  892. for (int j = 0; j < feederClearWork.VibrationCount; j++)
  893. {
  894. await ExecuteFeederWorks(Feeder, feederClearWork.FeederWorks, token, true);
  895. if ((cancellationToken != null && cancellationToken.IsCancellationRequested) || (token != null && token.IsCancellationRequested))
  896. {
  897. await Feeder.StopOutputAsync();
  898. if (_clearMaterialCtsDict.ContainsKey(feederClearWork.TaskCode))
  899. {
  900. _clearMaterialCtsDict[feederClearWork.TaskCode].Cancel();
  901. _clearMaterialCtsDict.TryRemove(feederClearWork.TaskCode, out _);
  902. }
  903. return false;
  904. }
  905. if (!await Feeder.GetOutputStatusAsync())
  906. {
  907. await Feeder.OutputAsync((int)feederClearWork.BeforeOutput + 1, 0);
  908. }
  909. if ((cancellationToken != null && cancellationToken.IsCancellationRequested) || (token != null && token.IsCancellationRequested))
  910. {
  911. await Feeder.StopOutputAsync();
  912. if (_clearMaterialCtsDict.ContainsKey(feederClearWork.TaskCode))
  913. {
  914. _clearMaterialCtsDict[feederClearWork.TaskCode].Cancel();
  915. _clearMaterialCtsDict.TryRemove(feederClearWork.TaskCode, out _);
  916. }
  917. return false;
  918. }
  919. }
  920. if ((cancellationToken != null && cancellationToken.IsCancellationRequested) || (token != null && token.IsCancellationRequested))
  921. {
  922. await Feeder.StopOutputAsync();
  923. if (_clearMaterialCtsDict.ContainsKey(feederClearWork.TaskCode))
  924. {
  925. _clearMaterialCtsDict[feederClearWork.TaskCode].Cancel();
  926. _clearMaterialCtsDict.TryRemove(feederClearWork.TaskCode, out _);
  927. }
  928. return false;
  929. }
  930. await Feeder.StopOutputAsync();
  931. await Task.Delay(300, token);
  932. if ((cancellationToken != null && cancellationToken.IsCancellationRequested) || (token != null && token.IsCancellationRequested))
  933. {
  934. await Feeder.StopOutputAsync();
  935. if (_clearMaterialCtsDict.ContainsKey(feederClearWork.TaskCode))
  936. {
  937. _clearMaterialCtsDict[feederClearWork.TaskCode].Cancel();
  938. _clearMaterialCtsDict.TryRemove(feederClearWork.TaskCode, out _);
  939. }
  940. return false;
  941. }
  942. }
  943. await Feeder.StopOutputAsync();
  944. await Task.Delay(300, token);
  945. if ((cancellationToken != null && cancellationToken.IsCancellationRequested) || (token != null && token.IsCancellationRequested))
  946. {
  947. await Feeder.StopOutputAsync();
  948. if (_clearMaterialCtsDict.ContainsKey(feederClearWork.TaskCode))
  949. {
  950. _clearMaterialCtsDict[feederClearWork.TaskCode].Cancel();
  951. _clearMaterialCtsDict.TryRemove(feederClearWork.TaskCode, out _);
  952. }
  953. return false;
  954. }
  955. if (_clearMaterialCtsDict.ContainsKey(feederClearWork.TaskCode))
  956. {
  957. _clearMaterialCtsDict[feederClearWork.TaskCode].Cancel();
  958. _clearMaterialCtsDict.TryRemove(feederClearWork.TaskCode, out _);
  959. }
  960. return true;
  961. }
  962. /// <summary>
  963. /// 停止指定编号的清料任务(如果正在运行)。
  964. /// </summary>
  965. public Task<bool> StopClearMaterialTaskAsync(int taskNumber, CancellationToken cancellationToken)
  966. {
  967. var feederClearWork = _configService.GetClearanceTaskByNumber(taskNumber);
  968. if (feederClearWork == null)
  969. {
  970. return Task.FromResult(false);
  971. }
  972. if (_clearMaterialCtsDict.ContainsKey(feederClearWork.TaskCode))
  973. {
  974. _clearMaterialCtsDict[feederClearWork.TaskCode].Cancel();
  975. _clearMaterialCtsDict.TryRemove(feederClearWork.TaskCode, out _);
  976. }
  977. return Task.FromResult(true);
  978. }
  979. /// <summary>
  980. /// 判断指定编号的机器人是否处于调试模式。
  981. /// </summary>
  982. public Task<bool> IsRobotInDebugModeAsync(int robotNumber, CancellationToken cancellationToken)
  983. {
  984. var robotInfo = _configService.GetAllRobots().FirstOrDefault(r => r.RobotNo == robotNumber);
  985. if (robotInfo == null)
  986. {
  987. return Task.FromResult(false);
  988. }
  989. var robot = _robotService.GetRobot(robotInfo.Id);
  990. if (robot != null) return Task.FromResult(robot.EnterDebugMode);
  991. return Task.FromResult(false);
  992. }
  993. /// <summary>
  994. /// 执行视觉任务的统一入口:
  995. /// - 如果为产品局部脚本存在,则调用脚本
  996. /// - 否则根据 procedure.FeederId 调用 Feeder 引导的视觉任务或普通视觉任务
  997. /// 返回是否成功以及字符串数组形式的响应(用于发送多条结果)。
  998. /// </summary>
  999. public async Task<(bool IsSucceed, string[] Response)> ExecuteVisionTaskAsync(ProcedureModel procedure, string[] items, CancellationToken cancellationToken)
  1000. {
  1001. var currentProduct = _productService.GetCurrentProduct();
  1002. string scriptFilePath = FilePath.ProductsPath + "//" + currentProduct.Name + "//" + procedure.CameraName + "//" + procedure.Name + ".cs";
  1003. if (File.Exists(scriptFilePath))
  1004. {
  1005. try
  1006. {
  1007. string script = FileHelper.ReadFile(scriptFilePath);
  1008. SendTaskMessage(Lang.执行视觉处理脚本, MessageLevel.Debug);
  1009. Tuple<bool, string[]> rstn = null;
  1010. var rst1 = await ScriptHelper.ExecuteVisionScriptingAsync(script, _regionManager, _eventAggregator, _container, procedure, items, rst =>
  1011. {
  1012. rstn = rst;
  1013. });
  1014. if (!rst1.Item1)
  1015. {
  1016. SendTaskMessage(Lang.视觉处理脚本出错, MessageLevel.Error);
  1017. foreach (var item in rst1.Item2)
  1018. {
  1019. SendTaskMessage(item, MessageLevel.Error);
  1020. }
  1021. return (false, new string[] { "ScriptError" });
  1022. }
  1023. return (rstn.Item1, rstn.Item2);
  1024. }
  1025. catch (Exception ex)
  1026. {
  1027. SendTaskMessage(ex.Message, MessageLevel.Error);
  1028. LogHelper.WriteLogError("执行视觉处理脚本时出错!", ex);
  1029. return (false, new string[] { "ScriptException" });
  1030. }
  1031. }
  1032. else
  1033. {
  1034. IVoiceCoilMotorFeeder Feeder = null;
  1035. if (procedure.FeederId != Guid.Empty)
  1036. {
  1037. Feeder = _feederService.GetFeeder(procedure.FeederId);
  1038. return await ExecuteFeederVisionTaskAsync(Feeder, procedure, items, cancellationToken);
  1039. }
  1040. else
  1041. {
  1042. var result = await ExecuteNormalVisionTaskAsync(procedure, items, cancellationToken);
  1043. return (result.IsSucceed, new string[] { result.Response });
  1044. }
  1045. }
  1046. }
  1047. /// <summary>
  1048. /// 内部:触发节拍计时回调。
  1049. /// </summary>
  1050. private void OnCycleTimingTicked(TimeSpan elapsed)
  1051. {
  1052. CycleTimingTicked?.Invoke(this, elapsed);
  1053. }
  1054. /// <summary>
  1055. /// 发布任务消息到事件聚合器(通过 UI Dispatcher 保证线程安全)。
  1056. /// </summary>
  1057. private void SendTaskMessage(string msg, MessageLevel level)
  1058. {
  1059. App.Current.Dispatcher.Invoke(() =>
  1060. {
  1061. _eventAggregator.GetEvent<TaskMessageNotification>().Publish(new Models.MessageStruct() { Message = msg, level = level });
  1062. });
  1063. }
  1064. #region 执行视觉任务辅助方法
  1065. /// <summary>
  1066. /// 执行 Feeder 引导的视觉任务。负责:
  1067. /// - 解析输入命令(是否先振动/先拍照、SetInputs)
  1068. /// - 在拍照前后执行对应的 Feeder 操作(开灯、振动、供料等)
  1069. /// - 多次尝试拍照并运行视觉工具,直到成功或达到失败次数上限
  1070. /// - 返回布尔成功标记及字符串数组形式的响应项
  1071. /// </summary>
  1072. public async Task<(bool IsSucceed, string[] Response)> ExecuteFeederVisionTaskAsync(IVoiceCoilMotorFeeder feeder, ProcedureModel procedure, string[] items, CancellationToken cancellationToken)
  1073. {
  1074. // 如果输入的items中是否包含Vibration和NoVibration,这两个分别对应是否先振动和是否先拍照
  1075. bool doVibrateFirst = items != null && items.Contains("VibrateFirst");
  1076. bool doCaptureFirst = items != null && items.Contains("CaptureFirst");
  1077. if (doVibrateFirst && doCaptureFirst) doCaptureFirst = false; // 如果两个都包含,则以振动优先为准
  1078. // 触发命令传入的输入终端
  1079. Dictionary<string, string> InputTerminal = null;
  1080. // 解析触发命令传入的输入终端参数
  1081. //判断传入参数中是否存在“SetInputs”
  1082. if (items != null && items.Length > 1 && items[0] == "SetInputs")
  1083. {
  1084. //依次从索引1开始解析参数,格式为 key=value,直到遇到非key=value格式的参数为止
  1085. InputTerminal = new Dictionary<string, string>();
  1086. for (int i = 1; i < items.Length; i++)
  1087. {
  1088. var pair = items[i].Split('=');
  1089. if (pair.Length == 2)
  1090. {
  1091. InputTerminal[pair[0]] = pair[1];
  1092. }
  1093. else
  1094. {
  1095. break; // 遇到非key=value格式的参数,停止解析
  1096. }
  1097. }
  1098. }
  1099. //执行Feeder相机拍照前的任务
  1100. await ExecuteFeederForPhotoBefore(feeder, procedure, doVibrateFirst, doCaptureFirst, cancellationToken);
  1101. // 如果遇到取消令牌,则直接返回失败
  1102. if (cancellationToken != null && cancellationToken.IsCancellationRequested)
  1103. {
  1104. await feeder.CloseLightAsync();
  1105. return (false, new string[] { "FeederTaskCancelled" });
  1106. }
  1107. DateTime nowtime = DateTime.Now;
  1108. //拍照失败时,需要多次拍照
  1109. for (int i = 0; i < procedure.FeederFailLimit; i++)
  1110. {
  1111. if (cancellationToken != null && cancellationToken.IsCancellationRequested)
  1112. {
  1113. await feeder.CloseLightAsync();
  1114. return (false, new string[] { "VisionTaskCancelled" });
  1115. }
  1116. SendTaskMessage(Lang.开始执行视觉流程.Replace("{0}", $"{i + 1}").Replace("{1}", procedure.Name), MessageLevel.Info);
  1117. // 1. 执行相机拍照并运行视觉工具
  1118. bool visionSucceed = ExecutePhoto(procedure, InputTerminal, out CogToolBlockTerminalCollection outputCollection);
  1119. if (!visionSucceed)
  1120. {
  1121. SendTaskMessage(Lang.视觉任务执行失败, MessageLevel.Error);
  1122. continue;
  1123. }
  1124. if (!outputCollection.Contains("Found"))
  1125. {
  1126. SendTaskMessage(Lang.未找到视觉输出结果, MessageLevel.Error);
  1127. return (false, new string[] { "NoFoundOutput" });
  1128. }
  1129. procedure.LastBlobArea = Convert.ToDouble(outputCollection["BlobTotalArea"].Value);
  1130. // 2. 获取视觉输出结果
  1131. bool Found = (bool)(outputCollection["Found"].Value);
  1132. if (!Found)
  1133. {
  1134. SendTaskMessage(Lang.拍照NG, MessageLevel.Debug);
  1135. await ExecuteFeederForPhotoLater(feeder, procedure, cancellationToken);
  1136. continue;
  1137. }
  1138. SendTaskMessage(Lang.拍照OK, MessageLevel.Debug);
  1139. if (procedure.ProcedureOutputs == null)
  1140. {
  1141. SendTaskMessage(Lang.视觉流程未配置输出项, MessageLevel.Alarm);
  1142. return (false, new string[] { "NoOutputConfigured" });
  1143. }
  1144. // 3. 获取视觉输出结果
  1145. LogHelper.WriteLogInfo("开始获取视觉输出结果");
  1146. var (IsSucceed, ErrMsg, Output) = GetVisionOutput(procedure, outputCollection, null);
  1147. if (!IsSucceed)
  1148. {
  1149. SendTaskMessage(Lang.获取视觉输出结果失败, MessageLevel.Error);
  1150. return (false, new string[] { ErrMsg });
  1151. }
  1152. // 4. 组织返回结果
  1153. int outputPointCount = 0;//输出点的数量
  1154. List<double[]> currentPoints = new List<double[]>(); //点位数据
  1155. List<string> outputItems = new List<string>(); //多项输出结果集合
  1156. foreach (var output in procedure.ProcedureOutputs)
  1157. {
  1158. if (Output.ContainsKey(output.Name))
  1159. {
  1160. var (IsPoint, Value) = Output[output.Name];
  1161. if (IsPoint)
  1162. {
  1163. //Value是点位数据,类型:List<string[]>,string[]是一个点位,里面是X、Y,U等数据
  1164. //将所有点位数据和单个点位数据中的坐标之间都用逗号分隔,多个点位之间用逗号分隔
  1165. List<string[]> points = Value as List<string[]>;
  1166. List<string> allpoints = new List<string>();
  1167. for (int j = 0; j < points.Count; j++)
  1168. {
  1169. //如果当前流程开启了剔除重复点功能,则进行剔除
  1170. if (procedure.IsExcludeNearPoint && procedure.LastRunPoints != null && procedure.LastRunPoints.Count > 0)
  1171. {
  1172. //当前点的坐标数据
  1173. double px = double.Parse(points[j][0]);
  1174. double py = double.Parse(points[j][1]);
  1175. double pu = double.Parse(points[j][2]);
  1176. //检查当前点是否与上次运行的点过于接近
  1177. //使用linq来检测上一次的点位集合中,是否存在某个点与当前点的x,y,u的差值小于设定的阈值
  1178. bool isNear = procedure.LastRunPoints.Any(lp =>
  1179. Math.Abs(lp[0] - px) < procedure.ExcludeNearPointThreshol &&
  1180. Math.Abs(lp[1] - py) < procedure.ExcludeNearPointThreshol &&
  1181. Math.Abs(lp[2] - pu) < procedure.ExcludeNearPointThreshol);
  1182. if (isNear) continue; //如果存在接近的点,则跳过当前点,不进行添加
  1183. }
  1184. //单个点位内坐标之间逗号分隔
  1185. allpoints.Add(string.Join(",", points[j]));
  1186. //如果输出模式是AllAtOnce或者BatchedUntilTerminator,则需要检查是否达到最大点位数量限制
  1187. if (procedure.OutputPointMode == OutputPointMode.AllAtOnce || procedure.OutputPointMode == OutputPointMode.BatchedUntilTerminator)
  1188. {
  1189. //如果当前总点位数量已经达到最大限制,则停止添加更多点位
  1190. if (allpoints.Count >= procedure.OutputPointCountMax)
  1191. {
  1192. break;
  1193. }
  1194. }
  1195. currentPoints.Add(new double[] { double.Parse(points[j][0]), double.Parse(points[j][1]), double.Parse(points[j][2]) });
  1196. }
  1197. //多个点位之间逗号分隔
  1198. string pointstr = allpoints.Count + "," + string.Join(",", allpoints);
  1199. if (procedure.OutputPointMode == OutputPointMode.UntilTerminator || procedure.OutputPointMode == OutputPointMode.BatchedUntilTerminator)
  1200. {
  1201. outputItems.AddRange(allpoints);
  1202. }
  1203. else
  1204. {
  1205. outputItems.Add(pointstr);
  1206. }
  1207. outputPointCount += allpoints.Count;
  1208. }
  1209. else
  1210. {
  1211. string itemstr = Value != null ? Value.ToString() : string.Empty;
  1212. outputItems.Add(itemstr);
  1213. }
  1214. }
  1215. }
  1216. procedure.LastRunPoints = currentPoints;
  1217. //关闭Feeder灯光
  1218. if (feeder.IsConnected)
  1219. {
  1220. await feeder.CloseLightAsync();
  1221. }
  1222. //如果输出模式是AllAtOnce或者BatchedUntilTerminator,则分次发送数据
  1223. if (procedure.OutputPointMode == OutputPointMode.UntilTerminator || procedure.OutputPointMode == OutputPointMode.BatchedUntilTerminator)
  1224. {
  1225. //将outputItems按照procedure.OutputSeparator进行拼接,得到最终返回结果
  1226. string finalResponse = string.Join(procedure.OutputSeparator, outputItems);
  1227. return (true, outputItems.ToArray());
  1228. }
  1229. else
  1230. {
  1231. //否则,一次发送所有数据
  1232. //将outputItems按照procedure.OutputSeparator进行拼接,得到最终返回结果
  1233. string finalResponse = string.Join(procedure.OutputSeparator, outputItems);
  1234. return (true, new string[] { finalResponse });
  1235. }
  1236. }
  1237. //关闭Feeder灯光
  1238. if (feeder.IsConnected)
  1239. {
  1240. await feeder.CloseLightAsync();
  1241. }
  1242. SendTaskMessage(Lang.多次拍照失败, MessageLevel.Alarm);
  1243. return (false, new string[] { "VisionFailed" });
  1244. }
  1245. /// <summary>
  1246. /// 执行非 Feeder 引导的普通视觉任务,返回单字符串响应。
  1247. /// </summary>
  1248. public async Task<(bool IsSucceed, string Response)> ExecuteNormalVisionTaskAsync(ProcedureModel procedure, string[] items, CancellationToken cancellationToken)
  1249. {
  1250. // 开始执行前的时间点
  1251. DateTime startTime = DateTime.Now;
  1252. try
  1253. {
  1254. // 触发命令传入的输入终端
  1255. Dictionary<string, string> InputTerminal = null;
  1256. // 解析触发命令传入的输入终端参数
  1257. //判断传入参数中是否存在“SetInputs”
  1258. if (items != null && items.Length > 1 && items[0] == "SetInputs")
  1259. {
  1260. InputTerminal = items.Skip(1)
  1261. .Select(x => x.Split('='))
  1262. .Where(y => y.Length == 2)
  1263. .ToDictionary(z => z[0], z => z[1]);
  1264. }
  1265. // 机器人当前坐标
  1266. double[] currentpos = null;
  1267. // 判断传入参数长度是否3,并且是否都是double
  1268. 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))
  1269. {
  1270. currentpos = new double[] { _x, _y, _u };
  1271. }
  1272. //拍照失败时,需要多次拍照
  1273. for (int i = 0; i < procedure.FeederFailLimit; i++)
  1274. {
  1275. if (cancellationToken != null && cancellationToken.IsCancellationRequested)
  1276. {
  1277. return (false, "VisionTaskCancelled");
  1278. }
  1279. // 1. 执行相机拍照并运行视觉工具
  1280. LogHelper.WriteLogInfo("开始执行相机拍照并运行视觉工具");
  1281. bool visionSucceed = ExecutePhoto(procedure, InputTerminal, out CogToolBlockTerminalCollection outputCollection);
  1282. if (!visionSucceed)
  1283. {
  1284. SendTaskMessage(Lang.视觉任务执行失败, MessageLevel.Error);
  1285. continue;
  1286. }
  1287. if (!outputCollection.Contains("Found"))
  1288. {
  1289. SendTaskMessage(Lang.未找到视觉输出结果, MessageLevel.Error);
  1290. return (false, "NoFoundOutput");
  1291. }
  1292. bool Found = (bool)(outputCollection["Found"].Value);
  1293. if (!Found)
  1294. {
  1295. SendTaskMessage(Lang.拍照NG, MessageLevel.Debug);
  1296. continue;
  1297. }
  1298. SendTaskMessage(Lang.拍照OK, MessageLevel.Debug);
  1299. // 2. 获取视觉输出结果
  1300. LogHelper.WriteLogInfo("开始获取视觉输出结果");
  1301. var (IsSucceed, ErrMsg, Output) = GetVisionOutput(procedure, outputCollection, currentpos);
  1302. if (!IsSucceed)
  1303. {
  1304. SendTaskMessage(Lang.获取视觉输出结果失败, MessageLevel.Error);
  1305. return (false, ErrMsg);
  1306. }
  1307. // 3. 组织返回结果
  1308. List<string> outputItems = new List<string>(); //多项输出结果集合
  1309. foreach (var output in procedure.ProcedureOutputs)
  1310. {
  1311. if (Output.ContainsKey(output.Name))
  1312. {
  1313. var (IsPoint, Value) = Output[output.Name];
  1314. if (IsPoint)
  1315. {
  1316. List<string[]> points = Value as List<string[]>;
  1317. List<string> allpoints = new List<string>();
  1318. for (int j = 0; j < points.Count; j++)
  1319. {
  1320. allpoints.Add(string.Join(",", points[j]));
  1321. }
  1322. //多个点位之间逗号分隔
  1323. string pointstr = allpoints.Count + "," + string.Join(",", allpoints);
  1324. outputItems.Add(pointstr);
  1325. }
  1326. else
  1327. {
  1328. string itemstr = Value != null ? Value.ToString() : string.Empty;
  1329. outputItems.Add(itemstr);
  1330. }
  1331. }
  1332. }
  1333. //将outputItems按照procedure.OutputSeparator进行拼接,得到最终返回结果
  1334. string finalResponse = string.Join(procedure.OutputSeparator, outputItems);
  1335. return (true, finalResponse);
  1336. }
  1337. return (false, "VisionFailed");
  1338. }
  1339. catch (Exception ex)
  1340. {
  1341. SendTaskMessage(ex.Message, MessageLevel.Error);
  1342. LogHelper.WriteLogError("执行普通视觉任务时出错!", ex);
  1343. return (false, "Exception");
  1344. }
  1345. }
  1346. /// <summary>
  1347. /// 执行相机拍照并运行 ToolBlock,返回是否成功并通过 out 参数返回 Outputs。
  1348. /// 该方法会发布 RenderUpdateNotification 以更新 UI。
  1349. /// </summary>
  1350. public bool ExecutePhoto(ProcedureModel procedure, Dictionary<string, string> InputTerminal, out CogToolBlockTerminalCollection outputCollection)
  1351. {
  1352. try
  1353. {
  1354. // 1. 采集图像
  1355. var camera = _cameraService.GetCamera(procedure.CameraId);
  1356. bool succed = camera.SetExposureTime(procedure.ExposureTime);
  1357. if (!succed)
  1358. {
  1359. SendTaskMessage($"相机曝光设置失败!", MessageLevel.Error);
  1360. }
  1361. succed = camera.SetGain(procedure.Gain);
  1362. if (!succed)
  1363. {
  1364. SendTaskMessage($"相机增益设置失败!", MessageLevel.Error);
  1365. }
  1366. DateTime nowtime = DateTime.Now;
  1367. LogHelper.WriteLogInfo("开始采集图像");
  1368. var image = camera.Grab();
  1369. if (image == null)
  1370. {
  1371. SendTaskMessage(Lang.图像采集失败, MessageLevel.Error);
  1372. outputCollection = null;
  1373. return false;
  1374. }
  1375. procedure.ToolBlock.Inputs["InputImage"].Value = image;
  1376. LogHelper.WriteLogInfo($"采集图像完成;用时:{(DateTime.Now - nowtime).Milliseconds}ms");
  1377. // 2. 为ToolBlock传入其他输入终端
  1378. if (InputTerminal != null)
  1379. {
  1380. LogHelper.WriteLogInfo($"为ToolBlock传入输入终端");
  1381. foreach (var item in InputTerminal)
  1382. {
  1383. if (procedure.ToolBlock.Inputs.Contains(item.Key))
  1384. {
  1385. LogHelper.WriteLogInfo($"传入[{item.Key}]={item.Value}");
  1386. procedure.ToolBlock.Inputs[item.Key].Value = item.Value;
  1387. }
  1388. else
  1389. {
  1390. LogHelper.WriteLogInfo($"创建并传入[{item.Key}]={item.Value}");
  1391. procedure.ToolBlock.Inputs.Add(new CogToolBlockTerminal(item.Key, item.Value));
  1392. }
  1393. }
  1394. }
  1395. // 3. 运行视觉工具
  1396. LogHelper.WriteLogInfo("开始运行视觉工具");
  1397. procedure.ToolBlock.Run(); //运行ToolBlock
  1398. if (procedure.ToolBlock.RunStatus.Result == CogToolResultConstants.Accept)
  1399. {
  1400. SendTaskMessage(Lang.视觉流程执行耗时.Replace("{0}", procedure.Name).Replace("{1}", $"{procedure.ToolBlock.RunStatus.ProcessingTime:F1}"), MessageLevel.Info);
  1401. outputCollection = procedure.ToolBlock.Outputs; //获取输出终端集合
  1402. DatabaseHelper.AddCameraRecords(_productService.GetCurrentProduct().Name, procedure.Name, outputCollection);
  1403. ICogRecord record = null;
  1404. foreach (CogToolBlockTerminal item in outputCollection)
  1405. {
  1406. if (item.Value is ICogRecord)
  1407. record = item.Value as ICogRecord;
  1408. }
  1409. _eventAggregator.GetEvent<RenderUpdateNotification>().Publish(new ShowRender()
  1410. {
  1411. CameraName = procedure.CameraName,
  1412. Id = procedure.CameraId,
  1413. Image = (ICogImage)procedure.ToolBlock.Inputs["InputImage"].Value,
  1414. Graphic = outputCollection["Graphic"].Value as CogGraphicCollection,
  1415. Record = record,
  1416. Result = (bool)(outputCollection["Found"].Value),
  1417. IsShow = true,
  1418. IsSaveImage = procedure.IsSaveImage,
  1419. SaveImageModel = procedure.SaveImageModel,
  1420. SaveImagePathModel = procedure.SaveImagePathModel,
  1421. SavePath = procedure.SavePath,
  1422. IsCompress = procedure.IsCompress,
  1423. });
  1424. return true;
  1425. }
  1426. else
  1427. {
  1428. SendTaskMessage(Lang.视觉流程执行出错耗时.Replace("{0}", procedure.Name).Replace("{1}", $"{procedure.ToolBlock.RunStatus.ProcessingTime:F1}"), MessageLevel.Error);
  1429. SendTaskMessage(procedure.ToolBlock.RunStatus.Message, MessageLevel.Error);
  1430. outputCollection = null;
  1431. _eventAggregator.GetEvent<RenderUpdateNotification>().Publish(new ShowRender()
  1432. {
  1433. CameraName = procedure.CameraName,
  1434. Id = procedure.CameraId,
  1435. Image = (ICogImage)procedure.ToolBlock.Inputs["InputImage"].Value,
  1436. Graphic = new CogGraphicCollection(),
  1437. Result = false,
  1438. IsShow = true,
  1439. IsSaveImage = procedure.IsSaveImage,
  1440. SaveImageModel = procedure.SaveImageModel,
  1441. SaveImagePathModel = procedure.SaveImagePathModel,
  1442. SavePath = procedure.SavePath
  1443. });
  1444. return false;
  1445. }
  1446. }
  1447. catch (Exception ex)
  1448. {
  1449. SendTaskMessage(ex.Message, MessageLevel.Error);
  1450. LogHelper.WriteLogError("执行相机取图并执行视觉工具组时出错!", ex);
  1451. outputCollection = null;
  1452. return false;
  1453. }
  1454. }
  1455. /// <summary>
  1456. /// 执行相机拍照获取单个点位结果
  1457. /// </summary>
  1458. /// <param name="procedure"></param>
  1459. /// <param name="InputTerminal"></param>
  1460. /// <param name="robotCoord"></param>
  1461. /// <param name="cancellationToken"></param>
  1462. /// <returns></returns>
  1463. public (bool IsSucceed ,double X,double Y,double U) ExecutePhotoGetSinglePoint(ProcedureModel procedure, Dictionary<string, string> InputTerminal, double[] robotCoord, CancellationToken cancellationToken)
  1464. {
  1465. DateTime nowtime = DateTime.Now;
  1466. //拍照失败时,需要多次拍照
  1467. for (int i = 0; i < procedure.FeederFailLimit; i++)
  1468. {
  1469. SendTaskMessage(Lang.开始执行视觉流程.Replace("{0}", $"{i + 1}").Replace("{1}", procedure.Name), MessageLevel.Info);
  1470. // 1. 执行相机拍照并运行视觉工具
  1471. bool visionSucceed = ExecutePhoto(procedure, InputTerminal, out CogToolBlockTerminalCollection outputCollection);
  1472. if (!visionSucceed)
  1473. {
  1474. SendTaskMessage(Lang.视觉任务执行失败, MessageLevel.Error);
  1475. continue;
  1476. }
  1477. if (!outputCollection.Contains("Found"))
  1478. {
  1479. SendTaskMessage(Lang.未找到视觉输出结果, MessageLevel.Error);
  1480. return (false,0,0,0);
  1481. }
  1482. // 2. 获取视觉输出结果
  1483. bool Found = (bool)(outputCollection["Found"].Value);
  1484. if (!Found)
  1485. {
  1486. SendTaskMessage(Lang.拍照NG, MessageLevel.Debug);
  1487. continue;
  1488. }
  1489. SendTaskMessage(Lang.拍照OK, MessageLevel.Debug);
  1490. // 3. 获取视觉输出结果
  1491. LogHelper.WriteLogInfo("开始获取视觉输出结果");
  1492. //获取相机校准
  1493. var calib = _calibrationService.GetCalibration(procedure.CalibrationId);
  1494. string points = (string)(outputCollection["Point"].Value);
  1495. string[] strpoints = points.Split(';');
  1496. //先将pos按照逗号进行分隔,拿到数组
  1497. var posParts = strpoints[0].Split(',');
  1498. double _pixel_x = double.Parse(posParts[0]);
  1499. double _pixel_y = double.Parse(posParts[1]);
  1500. double _pixel_u = double.Parse(posParts[2]);
  1501. //转换点位-像素转换成机器人绝对坐标
  1502. var calibResult = _calibrationService.ConvertPixelToPosition((_pixel_x, _pixel_y, _pixel_u), robotCoord, calib, RobotBrand.XYZ_Platform);
  1503. if (!calibResult.IsSucceed)
  1504. {
  1505. return (false, 0, 0, 0);
  1506. }
  1507. return (true, calibResult.X, calibResult.Y, calibResult.U);
  1508. }
  1509. SendTaskMessage(Lang.多次拍照失败, MessageLevel.Alarm);
  1510. return (false, 0, 0, 0);
  1511. }
  1512. /// <summary>
  1513. /// 从 ToolBlock 的输出集合中根据 Procedure 配置提取需要发送的输出项并做必要的坐标转换。
  1514. /// 返回元组:是否成功、错误信息(失败时)和名称->(是否点位, 值) 的字典。
  1515. /// </summary>
  1516. public (bool IsSucceed, string ErrMsg, Dictionary<string, (bool IsPoint, object Value)> Output) GetVisionOutput(ProcedureModel procedure, CogToolBlockTerminalCollection outputCollection, double[] robotPos)
  1517. {
  1518. RobotBrand robotBrand = RobotBrand.Default;
  1519. var robot = _configService.GetRobot(procedure.RobotId);
  1520. if (robot != null)
  1521. {
  1522. robotBrand = robot.RobotBrand;
  1523. }
  1524. List<string> SendResults = new List<string>();
  1525. Dictionary<string, (bool IsPoint, object Value)> ResultCollection = new Dictionary<string, (bool IsPoint, object Value)>();
  1526. foreach (var output in procedure.ProcedureOutputs)
  1527. {
  1528. //根据输出类型进行区分输出
  1529. if (output.ValueType == typeof(string))
  1530. {
  1531. //需要点位转换时,进行点位提取
  1532. if (output.IsPointTran)
  1533. {
  1534. if (outputCollection[output.Name].Value == null || string.IsNullOrEmpty(outputCollection[output.Name].Value.ToString()))
  1535. {
  1536. //如果需要输出的项的值为空,即点位数据为空,则输出点位的个数为0
  1537. ResultCollection.Add(output.Name, (true, null));
  1538. continue;
  1539. }
  1540. string[] strpoints = outputCollection[output.Name].Value.ToString().Split(';');
  1541. //存储当前输出点位集合
  1542. List<string[]> currentPointsForFeeder = new List<string[]>();
  1543. //获取相机校准
  1544. var calib = _calibrationService.GetCalibration(procedure.CalibrationId);
  1545. if (calib == null)
  1546. {
  1547. SendTaskMessage(Lang.没有相机校准信息, MessageLevel.Alarm);
  1548. return (false, "NotCalibrations", null);
  1549. }
  1550. // 判断相机安装方式,如果是J4移动相机或者XYZ平台时,则需要判断robotPos不能为null
  1551. if ((calib.CameraMount == CameraMount.MobileJ4 || calib.CameraMount == CameraMount.MobileDown_XYPlatform) && robotPos == null)
  1552. {
  1553. SendTaskMessage(Lang.机器人当前位置不能为空, MessageLevel.Alarm);
  1554. return (false, "RobotPositionNull", null);
  1555. }
  1556. List<string> SendDtat = new List<string>();
  1557. List<string> points = new List<string>();
  1558. //遍历所有的输出点位
  1559. foreach (var pos in strpoints)
  1560. {
  1561. //先将pos按照逗号进行分隔,拿到数组,判断是否至少包含3个元素,并且前三个元素可以转换为double,确保是有效的点位数据
  1562. if (string.IsNullOrEmpty(pos))
  1563. {
  1564. continue;
  1565. }
  1566. //先将pos按照逗号进行分隔,拿到数组
  1567. var posParts = pos.Split(',');
  1568. if (posParts.Length < 3 ||
  1569. !double.TryParse(posParts[0], out double _pixel_x) ||
  1570. !double.TryParse(posParts[1], out double _pixel_y) ||
  1571. !double.TryParse(posParts[2], out double _pixel_u))
  1572. {
  1573. SendTaskMessage(string.Format(Lang.点位数据格式错误, pos), MessageLevel.Alarm);
  1574. return (false, "PointDataFormatError", null);
  1575. }
  1576. //转换点位-像素转换成机器人绝对坐标
  1577. var calibResult = _calibrationService.ConvertPixelToPosition((_pixel_x, _pixel_y, _pixel_u), robotPos, calib, robotBrand);
  1578. if (!calibResult.IsSucceed)
  1579. {
  1580. return (false, "CalibrationFailed", null);
  1581. }
  1582. //截取posParts数组从索引3开始到结尾的所有元素,得到新新的数组extraInfoArray
  1583. string[] extraInfoArray = posParts.Skip(3).ToArray();
  1584. //将rpos转换为字符串数组,保留3位小数
  1585. string[] strings = new string[] { $"{calibResult.X:F3}", $"{calibResult.Y:F3}", $"{calibResult.U:F3}" };
  1586. List<string> rposString = new List<string>(strings);
  1587. if (extraInfoArray.Length > 0)
  1588. {
  1589. rposString.AddRange(extraInfoArray);
  1590. }
  1591. currentPointsForFeeder.Add(rposString.ToArray());
  1592. }
  1593. ResultCollection[output.Name] = (true, currentPointsForFeeder);
  1594. }
  1595. //直接输出字符串
  1596. else
  1597. {
  1598. if (outputCollection[output.Name].Value == null || string.IsNullOrEmpty(outputCollection[output.Name].Value.ToString()))
  1599. {
  1600. ResultCollection.Add(output.Name, (false, null));
  1601. continue;
  1602. }
  1603. ResultCollection[output.Name] = (false, outputCollection[output.Name].Value.ToString());
  1604. }
  1605. }
  1606. else
  1607. {
  1608. if (outputCollection[output.Name].Value == null)
  1609. {
  1610. ResultCollection.Add(output.Name, (false, null));
  1611. }
  1612. else
  1613. {
  1614. ResultCollection[output.Name] = (false, outputCollection[output.Name].Value.ToString());
  1615. }
  1616. }
  1617. }
  1618. return (true, string.Empty, ResultCollection);
  1619. }
  1620. /// <summary>
  1621. /// 拍照前针对 Feeder 的准备动作:设置灯、必要时供料或振动等。
  1622. /// </summary>
  1623. public async Task ExecuteFeederForPhotoBefore(IVoiceCoilMotorFeeder Feeder, ProcedureModel procedure, bool doVibrateFirst, bool doCaptureFirst, CancellationToken cancellationToken)
  1624. {
  1625. // 1. 设置Feeder光源亮度、打开光源
  1626. if (Feeder.FeederBrand == FeederBrand.AFAG)
  1627. {
  1628. await Feeder.SetLightValueAsync((ushort)procedure.LightValue);
  1629. }
  1630. else
  1631. {
  1632. //Feeder光源亮度设置
  1633. if (procedure.LightValue > 3)
  1634. {
  1635. var light = await Feeder.GetLightBrightnessAsync();
  1636. if (procedure.LightValue != light)
  1637. {
  1638. await Feeder.SetLightValueAsync((ushort)procedure.LightValue);
  1639. }
  1640. //获取光源的超时时间
  1641. int lightTimeout = await Feeder.GetLightTimeoutAsync();
  1642. if (lightTimeout < 10000)
  1643. {
  1644. await Feeder.SetLightTimeOutAsync(10000);
  1645. }
  1646. //打开光源
  1647. await Feeder.OpenLightAsync();
  1648. }
  1649. }
  1650. if (doCaptureFirst)//如果不振动,等待光源稳定时间
  1651. {
  1652. if (procedure.WaitPhoto > 0) await Task.Delay(procedure.WaitPhoto);
  1653. return;
  1654. }
  1655. //先振后拍时
  1656. if (procedure.VibrationModel == VibrationModel.VibrationPhoto || doVibrateFirst)
  1657. {
  1658. if (procedure.FeederWorks != null && procedure.FeederWorks.FeederWorkList != null)
  1659. {
  1660. bool flog = false;
  1661. //如果上次的Blob面积小于设定的最小值,则触发供料
  1662. if (procedure.LastBlobArea <= procedure.MinArea)
  1663. {
  1664. flog = true;
  1665. SendTaskMessage(Lang.执行料仓供料, MessageLevel.Info);
  1666. await ExecuteFeederStockWorks(Feeder, procedure.FeederStockWorks, cancellationToken);
  1667. if (procedure.WaitFeederStop > 0) await Task.Delay(procedure.WaitFeederStop);
  1668. SendTaskMessage(Lang.料仓供料结束, MessageLevel.Info);
  1669. }
  1670. if (!flog)
  1671. {
  1672. //执行配置的Feeder振动任务
  1673. await ExecuteFeederWorks(Feeder, procedure.FeederWorks, cancellationToken, false);
  1674. if (procedure.WaitFeederStop > 0) await Task.Delay(procedure.WaitFeederStop);
  1675. }
  1676. }
  1677. }
  1678. else
  1679. {
  1680. if (procedure.LightValue > 3)
  1681. {
  1682. if (procedure.WaitPhoto > 0) await Task.Delay(procedure.WaitPhoto);
  1683. }
  1684. //如果上次的Blob面积小于设定的最小值,则触发供料
  1685. if (procedure.LastBlobArea <= procedure.MinArea)
  1686. {
  1687. SendTaskMessage(Lang.执行料仓供料, MessageLevel.Info);
  1688. await ExecuteFeederStockWorks(Feeder, procedure.FeederStockWorks, cancellationToken);
  1689. if (procedure.WaitFeederStop > 0) await Task.Delay(procedure.WaitFeederStop);
  1690. SendTaskMessage(Lang.料仓供料结束, MessageLevel.Info);
  1691. }
  1692. }
  1693. }
  1694. /// <summary>
  1695. /// 拍照后在 NG 情况下的 Feeder 后处理,例如供料或振动。
  1696. /// </summary>
  1697. public async Task ExecuteFeederForPhotoLater(IVoiceCoilMotorFeeder Feeder, ProcedureModel procedure, CancellationToken cancellationToken)
  1698. {
  1699. //根据斑点面积决定是否料仓供料
  1700. if (procedure.LastBlobArea <= procedure.MinArea)
  1701. {
  1702. SendTaskMessage(Lang.执行料仓供料, MessageLevel.Info);
  1703. await ExecuteFeederStockWorks(Feeder, procedure.FeederStockWorks, cancellationToken);
  1704. if (cancellationToken != null && cancellationToken.IsCancellationRequested) return;
  1705. if (procedure.WaitFeederStop > 0) await Task.Delay(procedure.WaitFeederStop, cancellationToken);
  1706. SendTaskMessage(Lang.料仓供料结束, MessageLevel.Info);
  1707. }
  1708. else
  1709. {
  1710. if (procedure.FeederWorks != null && procedure.FeederWorks.FeederWorkList != null)
  1711. {
  1712. SendTaskMessage(Lang.执行Feeder振动, MessageLevel.Info);
  1713. //执行配置的Feeder振动任务
  1714. await ExecuteFeederWorks(Feeder, procedure.FeederWorks, cancellationToken);
  1715. if (cancellationToken != null && cancellationToken.IsCancellationRequested) return;
  1716. if (procedure.WaitFeederStop > 0) await Task.Delay(procedure.WaitFeederStop, cancellationToken);
  1717. SendTaskMessage(Lang.Feeder振动结束, MessageLevel.Info);
  1718. }
  1719. }
  1720. }
  1721. /// <summary>
  1722. /// 并行执行料仓供料和振动任务。
  1723. /// </summary>
  1724. public async Task ExecuteFeederStockWorks(IVoiceCoilMotorFeeder feeder, FeederStockWorks works, CancellationToken cancellationToken, bool isUpdateParame = true)
  1725. {
  1726. //同时执行料仓供料和Feeder振动任务
  1727. var stockTask = ExecuteFeederStockWorksOnly(feeder, works.FeederStockWorkList.ToArray(), cancellationToken);
  1728. var vibrationTask = ExecuteFeederWorkOnly(feeder, works.FeederWorkList.ToArray(), cancellationToken);
  1729. await Task.WhenAll(stockTask, vibrationTask);
  1730. }
  1731. /// <summary>
  1732. /// 执行料仓振动任务序列(仅料仓相关动作)。
  1733. /// </summary>
  1734. public async Task ExecuteFeederStockWorksOnly(IVoiceCoilMotorFeeder feeder, FeederStockWork[] works, CancellationToken cancellationToken)
  1735. {
  1736. //执行配置的料仓振动任务
  1737. if (feeder.FeederBrand == FeederBrand.AFAG)
  1738. {
  1739. foreach (var stockwork in works)
  1740. {
  1741. if (stockwork.RegisterIndex == 0)
  1742. {
  1743. if (stockwork.Duration > 0) await Task.Delay(stockwork.Duration, cancellationToken);
  1744. }
  1745. else if (stockwork.RegisterIndex == 1)
  1746. {
  1747. // 保留原注释的位置给 Modbus 操作
  1748. }
  1749. if (cancellationToken != null && cancellationToken.IsCancellationRequested)
  1750. {
  1751. return;
  1752. }
  1753. }
  1754. }
  1755. else
  1756. {
  1757. foreach (var stockwork in works)
  1758. {
  1759. if (stockwork.Function == VibrationFunction.Delay)
  1760. {
  1761. if (stockwork.Duration > 0) await Task.Delay(stockwork.Duration, cancellationToken);
  1762. }
  1763. else
  1764. {
  1765. await feeder.OutputAsync(((int)stockwork.Function) + 1, stockwork.Duration);
  1766. if (stockwork.Duration > 0) await Task.Delay(stockwork.Duration, cancellationToken);
  1767. }
  1768. if (cancellationToken != null && cancellationToken.IsCancellationRequested)
  1769. {
  1770. return;
  1771. }
  1772. }
  1773. }
  1774. }
  1775. /// <summary>
  1776. /// 执行单独的 Feeder 振动动作序列(仅振动相关)。
  1777. /// </summary>
  1778. public async Task ExecuteFeederWorkOnly(IVoiceCoilMotorFeeder feeder, FeederWork[] works, CancellationToken cancellationToken, bool isUpdateParame = true)
  1779. {
  1780. if (works == null)
  1781. {
  1782. return;
  1783. }
  1784. if (feeder.FeederBrand == FeederBrand.AFAG)
  1785. {
  1786. //执行配置的Feeder振动任务
  1787. foreach (var feederwork in works)
  1788. {
  1789. if (feederwork.ConfigIndex < 0)
  1790. {
  1791. continue;
  1792. }
  1793. if (feederwork.ConfigIndex == 0)
  1794. {
  1795. if (feederwork.Duration > 0) await Task.Delay(feederwork.Duration, cancellationToken);
  1796. }
  1797. else
  1798. {
  1799. ((AfagFeeder)feeder).LoadConfiguration(feederwork.ConfigIndex);
  1800. ((AfagFeeder)feeder).SetIntensity(feederwork.Intensity);
  1801. ((AfagFeeder)feeder).SetDirection(feederwork.Direction);
  1802. if (feederwork.Duration > 0) await Task.Delay(feederwork.Duration, cancellationToken);
  1803. if (cancellationToken != null && cancellationToken.IsCancellationRequested)
  1804. {
  1805. return;
  1806. }
  1807. ((AfagFeeder)feeder).SetIntensity(0);
  1808. }
  1809. if (cancellationToken != null && cancellationToken.IsCancellationRequested)
  1810. {
  1811. return;
  1812. }
  1813. }
  1814. }
  1815. else
  1816. {
  1817. //执行配置的Feeder振动任务
  1818. foreach (var feederwork in works)
  1819. {
  1820. if (feederwork.Function == VibrationFunction.Delay)
  1821. {
  1822. if (feederwork.Duration > 0) await Task.Delay(feederwork.Duration, cancellationToken);
  1823. }
  1824. else
  1825. {
  1826. if (feederwork.SingleAction != null && isUpdateParame)
  1827. {
  1828. await feeder.SetShakeParametersAsync((int)feederwork.Function, feederwork.SingleAction);
  1829. }
  1830. await feeder.StartAction((int)feederwork.Function, feederwork.Duration);
  1831. if (feederwork.Duration > 0) await Task.Delay(feederwork.Duration, cancellationToken);
  1832. }
  1833. if (cancellationToken != null && cancellationToken.IsCancellationRequested)
  1834. {
  1835. return;
  1836. }
  1837. }
  1838. }
  1839. }
  1840. /// <summary>
  1841. /// 执行 Feeder 振动集合(逐个执行 FeederWorkList 中的动作)。
  1842. /// </summary>
  1843. public async Task ExecuteFeederWorks(IVoiceCoilMotorFeeder feeder, FeederWorks works, CancellationToken cancellationToken, bool isUpdateParame = true)
  1844. {
  1845. if (feeder.FeederBrand == FeederBrand.AFAG)
  1846. {
  1847. foreach (var feederwork in works.FeederWorkList)
  1848. {
  1849. if (feederwork.ConfigIndex < 0)
  1850. {
  1851. continue;
  1852. }
  1853. if (feederwork.ConfigIndex == 0)
  1854. {
  1855. await Task.Delay(feederwork.Duration, cancellationToken);
  1856. }
  1857. else
  1858. {
  1859. ((AfagFeeder)feeder).LoadConfiguration(feederwork.ConfigIndex);
  1860. ((AfagFeeder)feeder).SetIntensity(feederwork.Intensity);
  1861. ((AfagFeeder)feeder).SetDirection(feederwork.Direction);
  1862. await Task.Delay(feederwork.Duration, cancellationToken);
  1863. if (cancellationToken != null && cancellationToken.IsCancellationRequested)
  1864. {
  1865. return;
  1866. }
  1867. ((AfagFeeder)feeder).SetIntensity(0);
  1868. }
  1869. if (cancellationToken != null && cancellationToken.IsCancellationRequested)
  1870. {
  1871. return;
  1872. }
  1873. }
  1874. }
  1875. else
  1876. {
  1877. foreach (var feederwork in works.FeederWorkList)
  1878. {
  1879. if (feederwork.Function == VibrationFunction.Delay)
  1880. {
  1881. if (feederwork.Duration > 0) await Task.Delay(feederwork.Duration, cancellationToken);
  1882. }
  1883. else
  1884. {
  1885. if (feederwork.SingleAction != null && isUpdateParame)
  1886. {
  1887. await feeder.SetShakeParametersAsync((int)feederwork.Function, feederwork.SingleAction);
  1888. }
  1889. await feeder.StartAction((int)feederwork.Function, feederwork.Duration);
  1890. if (feederwork.Duration > 0) await Task.Delay(feederwork.Duration, cancellationToken);
  1891. }
  1892. if (cancellationToken != null && cancellationToken.IsCancellationRequested)
  1893. {
  1894. return;
  1895. }
  1896. }
  1897. }
  1898. }
  1899. #endregion
  1900. }
  1901. }