RemoteCommandService.cs 90 KB

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