RemoteCommandService.cs 136 KB

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