RemoteCommandService.cs 141 KB

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