RemoteCommandService.cs 119 KB

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