RemoteCommandService.cs 125 KB

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