RemoteCommandService.cs 119 KB

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