RemoteCommandService.cs 114 KB

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