RemoteCommandService.cs 139 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032
  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. _eventAggregator.GetEvent<RenderUpdateNotification>().Publish(new ShowRender()
  1728. {
  1729. Id = procedure.DisplayId,
  1730. DisplayName = procedure.DisplayName,
  1731. //Image = (ICogImage)procedure.ToolBlock.Outputs["OriImage"].Value,
  1732. Image = (ICogImage)procedure.ToolBlock.Inputs["InputImage"].Value,
  1733. Graphic = outputCollection["Graphic"].Value as CogGraphicCollection,
  1734. Record = record,
  1735. Result = Found,
  1736. IsShow = true,
  1737. IsSaveImage = procedure.IsSaveImage,
  1738. SaveImageModel = procedure.SaveImageModel,
  1739. SaveImagePathModel = procedure.SaveImagePathModel,
  1740. SavePath = procedure.SavePath,
  1741. IsCompress = procedure.IsCompress,
  1742. ProceductName = procedure.Name,
  1743. ImageFileName = imgName,
  1744. Is3DModel = is3dmodel,
  1745. RangeImage = (CogImage16Range)procedure.ToolBlock.Outputs["RangeImage"].Value,
  1746. GreyImage = (CogImage16Grey)procedure.ToolBlock.Outputs["GreyImage"].Value
  1747. });
  1748. }
  1749. else
  1750. {
  1751. _eventAggregator.GetEvent<RenderUpdateNotification>().Publish(new ShowRender()
  1752. {
  1753. Id = procedure.DisplayId,
  1754. DisplayName = procedure.DisplayName,
  1755. //Image = (ICogImage)procedure.ToolBlock.Outputs["OriImage"].Value,
  1756. Image = (ICogImage)procedure.ToolBlock.Inputs["InputImage"].Value,
  1757. Graphic = outputCollection["Graphic"].Value as CogGraphicCollection,
  1758. Record = record,
  1759. Result = Found,
  1760. IsShow = true,
  1761. IsSaveImage = procedure.IsSaveImage,
  1762. SaveImageModel = procedure.SaveImageModel,
  1763. SaveImagePathModel = procedure.SaveImagePathModel,
  1764. SavePath = procedure.SavePath,
  1765. IsCompress = procedure.IsCompress,
  1766. ProceductName = procedure.Name,
  1767. ImageFileName = imgName,
  1768. Is3DModel = is3dmodel
  1769. });
  1770. }
  1771. return true;
  1772. }
  1773. else
  1774. {
  1775. SendTaskMessage(Lang.视觉流程执行出错耗时.Replace("{0}", procedure.Name).Replace("{1}", $"{procedure.ToolBlock.RunStatus.ProcessingTime:F1}"), MessageLevel.Error);
  1776. SendTaskMessage(procedure.ToolBlock.RunStatus.Message, MessageLevel.Error);
  1777. outputCollection = null;
  1778. //获取图片存储的图片文件名
  1779. string imgName = string.Empty;
  1780. if (procedure.IsSaveImage && !string.IsNullOrEmpty(procedure.ImageFileNameFormat))
  1781. {
  1782. // 创建模板,使用 {变量名:格式} 语法
  1783. var template = new FileNameTemplate(procedure.ImageFileNameFormat);
  1784. // 注册变量
  1785. template.RegisterVariable("ProductSN", () => _productService.CurrentProductCode);
  1786. template.RegisterVariable("CameraName", () => procedure.CameraName);
  1787. template.RegisterVariable("ShotCount", () => 1);
  1788. template.RegisterVariable("Result", () => "NG");
  1789. template.RegisterVariable("DateTime", () => DateTime.Now);
  1790. // 生成文件名
  1791. imgName = template.Generate();
  1792. }
  1793. if(is3dmodel==true)
  1794. {
  1795. _eventAggregator.GetEvent<RenderUpdateNotification>().Publish(new ShowRender()
  1796. {
  1797. Id = procedure.Id,
  1798. DisplayName = procedure.DisplayName,
  1799. //Image = (ICogImage)procedure.ToolBlock.Outputs["OriImage"].Value,
  1800. Image = (ICogImage)procedure.ToolBlock.Inputs["InputImage"].Value,
  1801. Graphic = new CogGraphicCollection(),
  1802. Result = false,
  1803. IsShow = true,
  1804. IsSaveImage = procedure.IsSaveImage,
  1805. SaveImageModel = procedure.SaveImageModel,
  1806. SaveImagePathModel = procedure.SaveImagePathModel,
  1807. SavePath = procedure.SavePath,
  1808. ProceductName = procedure.Name,
  1809. ImageFileName = imgName,
  1810. Is3DModel = is3dmodel,
  1811. RangeImage = (CogImage16Range)procedure.ToolBlock.Outputs["RangeImage"].Value,
  1812. GreyImage = (CogImage16Grey)procedure.ToolBlock.Outputs["GreyImage"].Value
  1813. });
  1814. }
  1815. else
  1816. {
  1817. _eventAggregator.GetEvent<RenderUpdateNotification>().Publish(new ShowRender()
  1818. {
  1819. Id = procedure.Id,
  1820. DisplayName = procedure.DisplayName,
  1821. //Image = (ICogImage)procedure.ToolBlock.Outputs["OriImage"].Value,
  1822. Image = (ICogImage)procedure.ToolBlock.Inputs["InputImage"].Value,
  1823. Graphic = new CogGraphicCollection(),
  1824. Result = false,
  1825. IsShow = true,
  1826. IsSaveImage = procedure.IsSaveImage,
  1827. SaveImageModel = procedure.SaveImageModel,
  1828. SaveImagePathModel = procedure.SaveImagePathModel,
  1829. SavePath = procedure.SavePath,
  1830. ProceductName = procedure.Name,
  1831. ImageFileName = imgName,
  1832. Is3DModel = is3dmodel
  1833. });
  1834. }
  1835. return false;
  1836. }
  1837. }
  1838. catch (Exception ex)
  1839. {
  1840. SendTaskMessage(ex.Message, MessageLevel.Error);
  1841. LogHelper.WriteLogError("执行相机取图并执行视觉工具组时出错!", ex);
  1842. outputCollection = null;
  1843. return false;
  1844. }
  1845. }
  1846. /// <summary>
  1847. /// 采集图像
  1848. /// </summary>
  1849. /// <param name="procedure"></param>
  1850. /// <returns></returns>
  1851. public async Task <(bool IsSucceed, ICogImage[] Image, string Msg)> ExecuteGrabImageAsync(ProcedureModel procedure)
  1852. {
  1853. try
  1854. {
  1855. var sysConfig = _configService.GetSystemConfiguration();
  1856. if(sysConfig.TurnOnAllLightUse==false)
  1857. {
  1858. await SetLightBeforePhoto(procedure);
  1859. }
  1860. // 1. 采集图像
  1861. var camera = _cameraService.GetCamera(procedure.CameraId);
  1862. bool succed = camera.SetExposureTime(procedure.ExposureTime);
  1863. if (!succed)
  1864. {
  1865. SendTaskMessage($"相机曝光设置失败!", MessageLevel.Error);
  1866. }
  1867. succed = camera.SetGain(procedure.Gain);
  1868. if (!succed)
  1869. {
  1870. SendTaskMessage($"相机增益设置失败!", MessageLevel.Error);
  1871. }
  1872. DateTime nowtime = DateTime.Now;
  1873. LogHelper.WriteLogInfo("开始采集图像");
  1874. //var image = camera.Grab();
  1875. var image = camera.Grab();
  1876. LogHelper.WriteLogInfo($"采集图像完成;用时:{(DateTime.Now - nowtime).Milliseconds}ms");
  1877. if (image == null)
  1878. {
  1879. SendTaskMessage(Lang.图像采集失败, MessageLevel.Error);
  1880. return (false,null,"图像采集失败");
  1881. }
  1882. return (true, new ICogImage[] { image }, "成功");
  1883. }
  1884. catch (Exception ex)
  1885. {
  1886. LogHelper.WriteLogError("采集图像失败!",ex);
  1887. return (false, null, "图像采集失败");
  1888. }
  1889. }
  1890. /// <summary>
  1891. /// 执行相机拍照获取单个点位结果
  1892. /// </summary>
  1893. /// <param name="procedure"></param>
  1894. /// <param name="InputTerminal"></param>
  1895. /// <param name="robotCoord"></param>
  1896. /// <param name="cancellationToken"></param>
  1897. /// <returns></returns>
  1898. public async Task<(bool IsSucceed, string[] Items, double Count)> ExecutePhotoGetSinglePoint1(ProcedureModel procedure, ICogImage[] imges, Dictionary<string, string> InputTerminal, double[] robotCoord, CancellationToken cancellationToken,bool is3dmodel)
  1899. {
  1900. DateTime nowtime = DateTime.Now;
  1901. try
  1902. {
  1903. //拍照失败时,需要多次拍照
  1904. //for (int i = 0; i < procedure.FeederFailLimit; i++)
  1905. for (int i = 0; i < 1; i++)
  1906. {
  1907. SendTaskMessage(Lang.开始执行视觉流程.Replace("{0}", $"{i + 1}").Replace("{1}", procedure.Name), MessageLevel.Info);
  1908. // 1. 执行相机拍照并运行视觉工具
  1909. bool visionSucceed = ExecutePhoto(procedure, imges, InputTerminal, out CogToolBlockTerminalCollection outputCollection, is3dmodel);
  1910. if (!visionSucceed)
  1911. {
  1912. SendTaskMessage(Lang.视觉任务执行失败, MessageLevel.Error);
  1913. continue;
  1914. }
  1915. if (!outputCollection.Contains("Found"))
  1916. {
  1917. SendTaskMessage(Lang.未找到视觉输出结果, MessageLevel.Error);
  1918. return (false, null, 0);
  1919. }
  1920. // 2. 获取视觉输出结果
  1921. //bool Found = (bool)(outputCollection["Found"].Value);
  1922. //if (!Found)
  1923. //{
  1924. // SendTaskMessage(Lang.拍照NG, MessageLevel.Debug);
  1925. // continue;
  1926. //}
  1927. SendTaskMessage(Lang.拍照OK, MessageLevel.Debug);
  1928. int Count = (int)(outputCollection["Count"].Value);
  1929. string[] PhotoRes = new string[100];
  1930. for (int k = 1; k <= Count; k++)
  1931. {
  1932. PhotoRes[k] = (string)(outputCollection[$"dis{k}"].Value);
  1933. //PhotoRes[k] = "222";
  1934. }
  1935. // 3. 获取视觉输出结果
  1936. LogHelper.WriteLogInfo("开始获取视觉输出结果");
  1937. /*
  1938. //获取相机校准
  1939. var calib = _calibrationService.GetCalibration(procedure.CalibrationId);
  1940. string points = (string)(outputCollection["Point"].Value);
  1941. string[] strpoints = points.Split(';');
  1942. //先将pos按照逗号进行分隔,拿到数组
  1943. var posParts = strpoints[0].Split(',');
  1944. double _pixel_x = double.Parse(posParts[0]);
  1945. double _pixel_y = double.Parse(posParts[1]);
  1946. double _pixel_u = double.Parse(posParts[2]);
  1947. //转换点位-像素转换成机器人绝对坐标
  1948. var calibResult = _calibrationService.ConvertPixelToPosition((_pixel_x, _pixel_y, _pixel_u), robotCoord, calib, RobotBrand.XYZ_Platform);
  1949. if (!calibResult.IsSucceed)
  1950. {
  1951. return (false, 0, 0, 0);
  1952. }
  1953. return (true, calibResult.X, calibResult.Y, calibResult.U);
  1954. */
  1955. return (true, PhotoRes, Count);
  1956. }
  1957. SendTaskMessage(Lang.多次拍照失败, MessageLevel.Alarm);
  1958. return (false, null, 0);
  1959. }
  1960. catch (Exception ex)
  1961. {
  1962. LogHelper.WriteLogError("执行相机取图并获取单点位时出错!", ex);
  1963. return (false, null, 0);
  1964. }
  1965. finally
  1966. {
  1967. var sysConfig = _configService.GetSystemConfiguration();
  1968. if (sysConfig.TurnOffAllLightUse == false)
  1969. {
  1970. await TurnOffLightAfterPhoto(procedure);
  1971. }
  1972. }
  1973. }
  1974. /// <summary>
  1975. /// 执行相机拍照获取单个点位结果
  1976. /// </summary>
  1977. /// <param name="procedure"></param>
  1978. /// <param name="InputTerminal"></param>
  1979. /// <param name="robotCoord"></param>
  1980. /// <param name="cancellationToken"></param>
  1981. /// <returns></returns>
  1982. public async Task<(bool IsSucceed, string X, double Y, double U)> ExecutePhotoGetSinglePoint2(ProcedureModel procedure, Dictionary<string, string> InputTerminal, double[] robotCoord, CancellationToken cancellationToken)
  1983. {
  1984. DateTime nowtime = DateTime.Now;
  1985. var sysConfig = _configService.GetSystemConfiguration();
  1986. if (sysConfig.TurnOnAllLightUse == false)
  1987. {
  1988. await SetLightBeforePhoto(procedure);
  1989. }
  1990. try
  1991. {
  1992. //拍照失败时,需要多次拍照
  1993. for (int i = 0; i < procedure.FeederFailLimit; i++)
  1994. {
  1995. SendTaskMessage(Lang.开始执行视觉流程.Replace("{0}", $"{i + 1}").Replace("{1}", procedure.Name), MessageLevel.Info);
  1996. // 1. 执行相机拍照并运行视觉工具
  1997. bool visionSucceed = ExecutePhoto2(procedure, InputTerminal, out CogToolBlockTerminalCollection outputCollection);
  1998. if (!visionSucceed)
  1999. {
  2000. SendTaskMessage(Lang.视觉任务执行失败, MessageLevel.Error);
  2001. continue;
  2002. }
  2003. if (!outputCollection.Contains("Found"))
  2004. {
  2005. SendTaskMessage(Lang.未找到视觉输出结果, MessageLevel.Error);
  2006. return (false, null, 0, 0);
  2007. }
  2008. // 2. 获取视觉输出结果
  2009. bool Found = (bool)(outputCollection["Found"].Value);
  2010. if (!Found)
  2011. {
  2012. SendTaskMessage(Lang.拍照NG, MessageLevel.Debug);
  2013. continue;
  2014. }
  2015. string SnCode = (string)(outputCollection["SnCode"].Value);
  2016. SendTaskMessage(Lang.拍照OK, MessageLevel.Debug);
  2017. // 3. 获取视觉输出结果
  2018. LogHelper.WriteLogInfo("开始获取视觉输出结果");
  2019. /*
  2020. //获取相机校准
  2021. var calib = _calibrationService.GetCalibration(procedure.CalibrationId);
  2022. string points = (string)(outputCollection["Point"].Value);
  2023. string[] strpoints = points.Split(';');
  2024. //先将pos按照逗号进行分隔,拿到数组
  2025. var posParts = strpoints[0].Split(',');
  2026. double _pixel_x = double.Parse(posParts[0]);
  2027. double _pixel_y = double.Parse(posParts[1]);
  2028. double _pixel_u = double.Parse(posParts[2]);
  2029. //转换点位-像素转换成机器人绝对坐标
  2030. var calibResult = _calibrationService.ConvertPixelToPosition((_pixel_x, _pixel_y, _pixel_u), robotCoord, calib, RobotBrand.XYZ_Platform);
  2031. if (!calibResult.IsSucceed)
  2032. {
  2033. return (false, 0, 0, 0);
  2034. }
  2035. return (true, calibResult.X, calibResult.Y, calibResult.U);
  2036. */
  2037. return (true, SnCode, 0, 0);
  2038. }
  2039. SendTaskMessage(Lang.多次拍照失败, MessageLevel.Alarm);
  2040. return (false, null, 0, 0);
  2041. }
  2042. catch (Exception ex)
  2043. {
  2044. LogHelper.WriteLogError("执行相机取图并获取单点位时出错!", ex);
  2045. return (false, null, 0, 0);
  2046. }
  2047. finally
  2048. {
  2049. if (sysConfig.TurnOffAllLightUse == false)
  2050. {
  2051. await TurnOffLightAfterPhoto(procedure);
  2052. }
  2053. }
  2054. }
  2055. /// <summary>
  2056. /// 执行相机拍照并运行 ToolBlock,返回是否成功并通过 out 参数返回 Outputs、图像和图形集合。
  2057. /// </summary>
  2058. /// <param name="procedure"></param>
  2059. /// <param name="InputTerminal"></param>
  2060. /// <param name="outputCollection"></param>
  2061. /// <param name="outImage"></param>
  2062. /// <param name="outGraphicCollection"></param>
  2063. /// <returns></returns>
  2064. public bool ExecutePhotoEx(ProcedureModel procedure, Dictionary<string, string> InputTerminal, out CogToolBlockTerminalCollection outputCollection,out ICogImage outImage,out CogGraphicCollection outGraphicCollection)
  2065. {
  2066. outImage = null;
  2067. outGraphicCollection = null;
  2068. try
  2069. {
  2070. // 1. 采集图像
  2071. var camera = _cameraService.GetCamera(procedure.CameraId);
  2072. bool succed = camera.SetExposureTime(procedure.ExposureTime);
  2073. if (!succed)
  2074. {
  2075. SendTaskMessage($"相机曝光设置失败!", MessageLevel.Error);
  2076. }
  2077. succed = camera.SetGain(procedure.Gain);
  2078. if (!succed)
  2079. {
  2080. SendTaskMessage($"相机增益设置失败!", MessageLevel.Error);
  2081. }
  2082. DateTime nowtime = DateTime.Now;
  2083. LogHelper.WriteLogInfo("开始采集图像");
  2084. var image = camera.Grab();
  2085. if (image == null)
  2086. {
  2087. SendTaskMessage(Lang.图像采集失败, MessageLevel.Error);
  2088. outputCollection = null;
  2089. return false;
  2090. }
  2091. outImage= image;
  2092. procedure.ToolBlock.Inputs["InputImage"].Value = image;
  2093. LogHelper.WriteLogInfo($"采集图像完成;用时:{(DateTime.Now - nowtime).Milliseconds}ms");
  2094. // 2. 为ToolBlock传入其他输入终端
  2095. if (InputTerminal != null)
  2096. {
  2097. LogHelper.WriteLogInfo($"为ToolBlock传入输入终端");
  2098. foreach (var item in InputTerminal)
  2099. {
  2100. if (procedure.ToolBlock.Inputs.Contains(item.Key))
  2101. {
  2102. LogHelper.WriteLogInfo($"传入[{item.Key}]={item.Value}");
  2103. procedure.ToolBlock.Inputs[item.Key].Value = item.Value;
  2104. }
  2105. else
  2106. {
  2107. LogHelper.WriteLogInfo($"创建并传入[{item.Key}]={item.Value}");
  2108. procedure.ToolBlock.Inputs.Add(new CogToolBlockTerminal(item.Key, item.Value));
  2109. }
  2110. }
  2111. }
  2112. // 3. 运行视觉工具
  2113. LogHelper.WriteLogInfo("开始运行视觉工具");
  2114. procedure.ToolBlock.Run(); //运行ToolBlock
  2115. if (procedure.ToolBlock.RunStatus.Result == CogToolResultConstants.Accept)
  2116. {
  2117. SendTaskMessage(Lang.视觉流程执行耗时.Replace("{0}", procedure.Name).Replace("{1}", $"{procedure.ToolBlock.RunStatus.ProcessingTime:F1}"), MessageLevel.Info);
  2118. outputCollection = procedure.ToolBlock.Outputs; //获取输出终端集合
  2119. DatabaseHelper.AddCameraRecords(_productService.GetCurrentProduct().Name, procedure.Name, outputCollection);
  2120. ICogRecord record = null;
  2121. foreach (CogToolBlockTerminal item in outputCollection)
  2122. {
  2123. if (item.Value is ICogRecord)
  2124. record = item.Value as ICogRecord;
  2125. }
  2126. outGraphicCollection= outputCollection["Graphic"].Value as CogGraphicCollection;
  2127. return true;
  2128. }
  2129. else
  2130. {
  2131. SendTaskMessage(Lang.视觉流程执行出错耗时.Replace("{0}", procedure.Name).Replace("{1}", $"{procedure.ToolBlock.RunStatus.ProcessingTime:F1}"), MessageLevel.Error);
  2132. SendTaskMessage(procedure.ToolBlock.RunStatus.Message, MessageLevel.Error);
  2133. outputCollection = null;
  2134. outGraphicCollection = outputCollection["Graphic"].Value as CogGraphicCollection;
  2135. return false;
  2136. }
  2137. }
  2138. catch (Exception ex)
  2139. {
  2140. SendTaskMessage(ex.Message, MessageLevel.Error);
  2141. LogHelper.WriteLogError("执行相机取图并执行视觉工具组时出错!", ex);
  2142. outputCollection = null;
  2143. return false;
  2144. }
  2145. }
  2146. /// <summary>
  2147. /// 执行相机拍照获取单个点位结果
  2148. /// </summary>
  2149. /// <param name="procedure"></param>
  2150. /// <param name="InputTerminal"></param>
  2151. /// <param name="robotCoord"></param>
  2152. /// <param name="cancellationToken"></param>
  2153. /// <returns></returns>
  2154. public async Task<(bool IsSucceed, double X, double Y, double U)> ExecutePhotoGetSinglePoint(ProcedureModel procedure, Dictionary<string, string> InputTerminal, double[] robotCoord, CancellationToken cancellationToken)
  2155. {
  2156. DateTime nowtime = DateTime.Now;
  2157. await SetLightBeforePhoto(procedure);
  2158. try
  2159. {
  2160. //拍照失败时,需要多次拍照
  2161. //for (int i = 0; i < procedure.FeederFailLimit; i++)
  2162. for (int i = 0; i < 1; i++)
  2163. {
  2164. SendTaskMessage(Lang.开始执行视觉流程.Replace("{0}", $"{i + 1}").Replace("{1}", procedure.Name), MessageLevel.Info);
  2165. //1.执行相机拍照并运行视觉工具
  2166. bool visionSucceed = ExecutePhoto(procedure, InputTerminal, out CogToolBlockTerminalCollection outputCollection);
  2167. if (!visionSucceed)
  2168. {
  2169. SendTaskMessage(Lang.视觉任务执行失败, MessageLevel.Error);
  2170. continue;
  2171. }
  2172. if (!outputCollection.Contains("Found"))
  2173. {
  2174. SendTaskMessage(Lang.未找到视觉输出结果, MessageLevel.Error);
  2175. return (false, 0, 0, 0);
  2176. }
  2177. // 2. 获取视觉输出结果
  2178. bool Found = (bool)(outputCollection["Found"].Value);
  2179. if (!Found)
  2180. {
  2181. SendTaskMessage(Lang.拍照NG, MessageLevel.Debug);
  2182. continue;
  2183. }
  2184. SendTaskMessage(Lang.拍照OK, MessageLevel.Debug);
  2185. //// 3. 获取视觉输出结果
  2186. //LogHelper.WriteLogInfo("开始获取视觉输出结果");
  2187. ////获取相机校准
  2188. //var calib = _calibrationService.GetCalibration(procedure.CalibrationId);
  2189. //string points = (string)(outputCollection["Point"].Value);
  2190. //string[] strpoints = points.Split(';');
  2191. ////先将pos按照逗号进行分隔,拿到数组
  2192. //var posParts = strpoints[0].Split(',');
  2193. //double _pixel_x = double.Parse(posParts[0]);
  2194. //double _pixel_y = double.Parse(posParts[1]);
  2195. //double _pixel_u = double.Parse(posParts[2]);
  2196. ////转换点位-像素转换成机器人绝对坐标
  2197. //var calibResult = _calibrationService.ConvertPixelToPosition((_pixel_x, _pixel_y, _pixel_u), robotCoord, calib, RobotBrand.XYZ_Platform);
  2198. //if (!calibResult.IsSucceed)
  2199. //{
  2200. // return (false, 0, 0, 0);
  2201. //}
  2202. return (true, 0,0, 0);
  2203. }
  2204. SendTaskMessage(Lang.多次拍照失败, MessageLevel.Alarm);
  2205. return (false, 0, 0, 0);
  2206. }
  2207. catch (Exception ex)
  2208. {
  2209. LogHelper.WriteLogError("执行相机取图并获取单点位时出错!", ex);
  2210. return (false, 0, 0, 0);
  2211. }
  2212. finally
  2213. {
  2214. await TurnOffLightAfterPhoto(procedure);
  2215. }
  2216. }
  2217. /// <summary>
  2218. /// 执行相机拍照获取单个点位结果
  2219. /// </summary>
  2220. /// <param name="procedure"></param>
  2221. /// <param name="InputTerminal"></param>
  2222. /// <param name="robotCoord"></param>
  2223. /// <param name="cancellationToken"></param>
  2224. /// <returns></returns>
  2225. public async Task<(bool IsSucceed, string[] Items, double Count)> ExecutePhotoGetSinglePoint1(ProcedureModel procedure, Dictionary<string, string> InputTerminal, double[] robotCoord, CancellationToken cancellationToken)
  2226. {
  2227. DateTime nowtime = DateTime.Now;
  2228. var sysConfig = _configService.GetSystemConfiguration();
  2229. if (sysConfig.TurnOnAllLightUse == false)
  2230. {
  2231. await SetLightBeforePhoto(procedure);
  2232. }
  2233. try
  2234. {
  2235. //拍照失败时,需要多次拍照
  2236. //for (int i = 0; i < procedure.FeederFailLimit; i++)
  2237. for (int i = 0; i < 1; i++)
  2238. {
  2239. SendTaskMessage(Lang.开始执行视觉流程.Replace("{0}", $"{i + 1}").Replace("{1}", procedure.Name), MessageLevel.Info);
  2240. // 1. 执行相机拍照并运行视觉工具
  2241. bool visionSucceed = ExecutePhoto(procedure, InputTerminal, out CogToolBlockTerminalCollection outputCollection);
  2242. if (!visionSucceed)
  2243. {
  2244. SendTaskMessage(Lang.视觉任务执行失败, MessageLevel.Error);
  2245. continue;
  2246. }
  2247. //if (!outputCollection.Contains("Found"))
  2248. //{
  2249. // SendTaskMessage(Lang.未找到视觉输出结果, MessageLevel.Error);
  2250. // return (false, null, 0);
  2251. //}
  2252. // 2. 获取视觉输出结果
  2253. //bool Found = (bool)(outputCollection["Found"].Value);
  2254. //if (!Found)
  2255. //{
  2256. // SendTaskMessage(Lang.拍照NG, MessageLevel.Debug);
  2257. // continue;
  2258. //}
  2259. SendTaskMessage(Lang.拍照OK, MessageLevel.Debug);
  2260. int Count = (int)(outputCollection["Count"].Value);
  2261. string[] PhotoRes = new string[100];
  2262. for (int k = 1; k <= Count; k++)
  2263. {
  2264. PhotoRes[k] = (string)(outputCollection[$"dis{k}"].Value);
  2265. //PhotoRes[k] = "222";
  2266. }
  2267. // 3. 获取视觉输出结果
  2268. LogHelper.WriteLogInfo("开始获取视觉输出结果");
  2269. /*
  2270. //获取相机校准
  2271. var calib = _calibrationService.GetCalibration(procedure.CalibrationId);
  2272. string points = (string)(outputCollection["Point"].Value);
  2273. string[] strpoints = points.Split(';');
  2274. //先将pos按照逗号进行分隔,拿到数组
  2275. var posParts = strpoints[0].Split(',');
  2276. double _pixel_x = double.Parse(posParts[0]);
  2277. double _pixel_y = double.Parse(posParts[1]);
  2278. double _pixel_u = double.Parse(posParts[2]);
  2279. //转换点位-像素转换成机器人绝对坐标
  2280. var calibResult = _calibrationService.ConvertPixelToPosition((_pixel_x, _pixel_y, _pixel_u), robotCoord, calib, RobotBrand.XYZ_Platform);
  2281. if (!calibResult.IsSucceed)
  2282. {
  2283. return (false, 0, 0, 0);
  2284. }
  2285. return (true, calibResult.X, calibResult.Y, calibResult.U);
  2286. */
  2287. return (true, PhotoRes, Count);
  2288. }
  2289. SendTaskMessage(Lang.多次拍照失败, MessageLevel.Alarm);
  2290. return (false, null, 0);
  2291. }
  2292. catch (Exception ex)
  2293. {
  2294. LogHelper.WriteLogError("执行相机取图并获取单点位时出错!", ex);
  2295. return (false, null, 0);
  2296. }
  2297. finally
  2298. {
  2299. //await TurnOffLightAfterPhoto(procedure);
  2300. }
  2301. }
  2302. /// <summary>
  2303. /// 执行相机拍照获取单个点位结果,并且返回图像和图形
  2304. /// </summary>
  2305. /// <param name="procedure"></param>
  2306. /// <param name="InputTerminal"></param>
  2307. /// <param name="robotCoord"></param>
  2308. /// <param name="cancellationToken"></param>
  2309. /// <returns></returns>
  2310. 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)
  2311. {
  2312. DateTime nowtime = DateTime.Now;
  2313. await SetLightBeforePhoto(procedure);
  2314. ICogImage outImage=null;
  2315. CogGraphicCollection outGraphicCollection=null;
  2316. try
  2317. {
  2318. //拍照失败时,需要多次拍照
  2319. for (int i = 0; i < procedure.FeederFailLimit; i++)
  2320. {
  2321. SendTaskMessage(Lang.开始执行视觉流程.Replace("{0}", $"{i + 1}").Replace("{1}", procedure.Name), MessageLevel.Info);
  2322. // 1. 执行相机拍照并运行视觉工具
  2323. bool visionSucceed = ExecutePhotoEx(procedure, InputTerminal, out CogToolBlockTerminalCollection outputCollection, out outImage, out outGraphicCollection);
  2324. if (!visionSucceed)
  2325. {
  2326. SendTaskMessage(Lang.视觉任务执行失败, MessageLevel.Error);
  2327. continue;
  2328. }
  2329. if (!outputCollection.Contains("Found"))
  2330. {
  2331. SendTaskMessage(Lang.未找到视觉输出结果, MessageLevel.Error);
  2332. return (false, 0, 0, 0, outImage, outGraphicCollection);
  2333. }
  2334. // 2. 获取视觉输出结果
  2335. bool Found = (bool)(outputCollection["Found"].Value);
  2336. if (!Found)
  2337. {
  2338. SendTaskMessage(Lang.拍照NG, MessageLevel.Debug);
  2339. continue;
  2340. }
  2341. SendTaskMessage(Lang.拍照OK, MessageLevel.Debug);
  2342. // 3. 获取视觉输出结果
  2343. LogHelper.WriteLogInfo("开始获取视觉输出结果");
  2344. //获取相机校准
  2345. var calib = _calibrationService.GetCalibration(procedure.CalibrationId);
  2346. string points = (string)(outputCollection["Point"].Value);
  2347. string[] strpoints = points.Split(';');
  2348. //先将pos按照逗号进行分隔,拿到数组
  2349. var posParts = strpoints[0].Split(',');
  2350. double _pixel_x = double.Parse(posParts[0]);
  2351. double _pixel_y = double.Parse(posParts[1]);
  2352. double _pixel_u = double.Parse(posParts[2]);
  2353. //转换点位-像素转换成机器人绝对坐标
  2354. var calibResult = _calibrationService.ConvertPixelToPosition((_pixel_x, _pixel_y, _pixel_u), robotCoord, calib, RobotBrand.XYZ_Platform);
  2355. if (!calibResult.IsSucceed)
  2356. {
  2357. return (false, 0, 0, 0, outImage, outGraphicCollection);
  2358. }
  2359. return (true, calibResult.X, calibResult.Y, calibResult.U, outImage, outGraphicCollection);
  2360. }
  2361. SendTaskMessage(Lang.多次拍照失败, MessageLevel.Alarm);
  2362. return (false, 0, 0, 0, outImage, outGraphicCollection);
  2363. }
  2364. catch (Exception ex)
  2365. {
  2366. LogHelper.WriteLogError("执行相机取图并获取单点位时出错!", ex);
  2367. return (false, 0, 0, 0, outImage, outGraphicCollection);
  2368. }
  2369. finally
  2370. {
  2371. await TurnOffLightAfterPhoto(procedure);
  2372. }
  2373. }
  2374. /// <summary>
  2375. /// 从 ToolBlock 的输出集合中根据 Procedure 配置提取需要发送的输出项并做必要的坐标转换。
  2376. /// 返回元组:是否成功、错误信息(失败时)和名称->(是否点位, 值) 的字典。
  2377. /// </summary>
  2378. public (bool IsSucceed, string ErrMsg, Dictionary<string, (bool IsPoint, object Value)> Output) GetVisionOutput(ProcedureModel procedure, CogToolBlockTerminalCollection outputCollection, double[] robotPos)
  2379. {
  2380. RobotBrand robotBrand = RobotBrand.Default;
  2381. var robot = _configService.GetRobot(procedure.RobotId);
  2382. if (robot != null)
  2383. {
  2384. robotBrand = robot.RobotBrand;
  2385. }
  2386. List<string> SendResults = new List<string>();
  2387. Dictionary<string, (bool IsPoint, object Value)> ResultCollection = new Dictionary<string, (bool IsPoint, object Value)>();
  2388. foreach (var output in procedure.ProcedureOutputs)
  2389. {
  2390. //根据输出类型进行区分输出
  2391. if (output.ValueType == typeof(string))
  2392. {
  2393. //需要点位转换时,进行点位提取
  2394. if (output.IsPointTran)
  2395. {
  2396. if (outputCollection[output.Name].Value == null || string.IsNullOrEmpty(outputCollection[output.Name].Value.ToString()))
  2397. {
  2398. //如果需要输出的项的值为空,即点位数据为空,则输出点位的个数为0
  2399. ResultCollection.Add(output.Name, (true, null));
  2400. continue;
  2401. }
  2402. string[] strpoints = outputCollection[output.Name].Value.ToString().Split(';');
  2403. //存储当前输出点位集合
  2404. List<string[]> currentPointsForFeeder = new List<string[]>();
  2405. //获取相机校准
  2406. var calib = _calibrationService.GetCalibration(procedure.CalibrationId);
  2407. if (calib == null)
  2408. {
  2409. SendTaskMessage(Lang.没有相机校准信息, MessageLevel.Alarm);
  2410. return (false, "NotCalibrations", null);
  2411. }
  2412. // 判断相机安装方式,如果是J4移动相机或者XYZ平台时,则需要判断robotPos不能为null
  2413. if ((calib.CameraMount == CameraMount.MobileJ4 || calib.CameraMount == CameraMount.MobileDown_XYPlatform) && robotPos == null)
  2414. {
  2415. SendTaskMessage(Lang.机器人当前位置不能为空, MessageLevel.Alarm);
  2416. return (false, "RobotPositionNull", null);
  2417. }
  2418. List<string> SendDtat = new List<string>();
  2419. List<string> points = new List<string>();
  2420. //遍历所有的输出点位
  2421. foreach (var pos in strpoints)
  2422. {
  2423. //先将pos按照逗号进行分隔,拿到数组,判断是否至少包含3个元素,并且前三个元素可以转换为double,确保是有效的点位数据
  2424. if (string.IsNullOrEmpty(pos))
  2425. {
  2426. continue;
  2427. }
  2428. //先将pos按照逗号进行分隔,拿到数组
  2429. var posParts = pos.Split(',');
  2430. if (posParts.Length < 3 ||
  2431. !double.TryParse(posParts[0], out double _pixel_x) ||
  2432. !double.TryParse(posParts[1], out double _pixel_y) ||
  2433. !double.TryParse(posParts[2], out double _pixel_u))
  2434. {
  2435. SendTaskMessage(string.Format(Lang.点位数据格式错误, pos), MessageLevel.Alarm);
  2436. return (false, "PointDataFormatError", null);
  2437. }
  2438. //转换点位-像素转换成机器人绝对坐标
  2439. var calibResult = _calibrationService.ConvertPixelToPosition((_pixel_x, _pixel_y, _pixel_u), robotPos, calib, robotBrand);
  2440. if (!calibResult.IsSucceed)
  2441. {
  2442. return (false, "CalibrationFailed", null);
  2443. }
  2444. //截取posParts数组从索引3开始到结尾的所有元素,得到新新的数组extraInfoArray
  2445. string[] extraInfoArray = posParts.Skip(3).ToArray();
  2446. //将rpos转换为字符串数组,保留3位小数
  2447. string[] strings = new string[] { $"{calibResult.X:F3}", $"{calibResult.Y:F3}", $"{calibResult.U:F3}" };
  2448. List<string> rposString = new List<string>(strings);
  2449. if (extraInfoArray.Length > 0)
  2450. {
  2451. rposString.AddRange(extraInfoArray);
  2452. }
  2453. currentPointsForFeeder.Add(rposString.ToArray());
  2454. }
  2455. ResultCollection[output.Name] = (true, currentPointsForFeeder);
  2456. }
  2457. //直接输出字符串
  2458. else
  2459. {
  2460. if (outputCollection[output.Name].Value == null || string.IsNullOrEmpty(outputCollection[output.Name].Value.ToString()))
  2461. {
  2462. ResultCollection.Add(output.Name, (false, null));
  2463. continue;
  2464. }
  2465. ResultCollection[output.Name] = (false, outputCollection[output.Name].Value.ToString());
  2466. }
  2467. }
  2468. else
  2469. {
  2470. if (outputCollection[output.Name].Value == null)
  2471. {
  2472. ResultCollection.Add(output.Name, (false, null));
  2473. }
  2474. else
  2475. {
  2476. ResultCollection[output.Name] = (false, outputCollection[output.Name].Value.ToString());
  2477. }
  2478. }
  2479. }
  2480. return (true, string.Empty, ResultCollection);
  2481. }
  2482. /// <summary>
  2483. /// 拍照前针对 Feeder 的准备动作:设置灯、必要时供料或振动等。
  2484. /// </summary>
  2485. public async Task ExecuteFeederForPhotoBefore(IVoiceCoilMotorFeeder Feeder, ProcedureModel procedure, bool doVibrateFirst, bool doCaptureFirst, CancellationToken cancellationToken)
  2486. {
  2487. // 1. 设置Feeder光源亮度、打开光源
  2488. if (Feeder.FeederBrand == FeederBrand.AFAG)
  2489. {
  2490. await Feeder.SetLightValueAsync((ushort)procedure.LightValue);
  2491. }
  2492. else
  2493. {
  2494. //Feeder光源亮度设置
  2495. if (procedure.LightValue > 3)
  2496. {
  2497. var light = await Feeder.GetLightBrightnessAsync();
  2498. if (procedure.LightValue != light)
  2499. {
  2500. await Feeder.SetLightValueAsync((ushort)procedure.LightValue);
  2501. }
  2502. //获取光源的超时时间
  2503. int lightTimeout = await Feeder.GetLightTimeoutAsync();
  2504. if (lightTimeout < 10000)
  2505. {
  2506. await Feeder.SetLightTimeOutAsync(10000);
  2507. }
  2508. //打开光源
  2509. await Feeder.OpenLightAsync();
  2510. }
  2511. }
  2512. if (doCaptureFirst)//如果不振动,等待光源稳定时间
  2513. {
  2514. if (procedure.WaitPhoto > 0) await Task.Delay(procedure.WaitPhoto);
  2515. return;
  2516. }
  2517. //先振后拍时
  2518. if (procedure.VibrationModel == VibrationModel.VibrationPhoto || doVibrateFirst)
  2519. {
  2520. if (procedure.FeederWorks != null && procedure.FeederWorks.FeederWorkList != null)
  2521. {
  2522. bool flog = false;
  2523. //如果上次的Blob面积小于设定的最小值,则触发供料
  2524. if (procedure.LastBlobArea <= procedure.MinArea)
  2525. {
  2526. flog = true;
  2527. SendTaskMessage(Lang.执行料仓供料, MessageLevel.Info);
  2528. await ExecuteFeederStockWorks(Feeder, procedure.FeederStockWorks, cancellationToken);
  2529. if (procedure.WaitFeederStop > 0) await Task.Delay(procedure.WaitFeederStop);
  2530. SendTaskMessage(Lang.料仓供料结束, MessageLevel.Info);
  2531. }
  2532. if (!flog)
  2533. {
  2534. //执行配置的Feeder振动任务
  2535. await ExecuteFeederWorks(Feeder, procedure.FeederWorks, cancellationToken, false);
  2536. if (procedure.WaitFeederStop > 0) await Task.Delay(procedure.WaitFeederStop);
  2537. }
  2538. }
  2539. }
  2540. else
  2541. {
  2542. if (procedure.LightValue > 3)
  2543. {
  2544. if (procedure.WaitPhoto > 0) await Task.Delay(procedure.WaitPhoto);
  2545. }
  2546. //如果上次的Blob面积小于设定的最小值,则触发供料
  2547. if (procedure.LastBlobArea <= procedure.MinArea)
  2548. {
  2549. SendTaskMessage(Lang.执行料仓供料, MessageLevel.Info);
  2550. await ExecuteFeederStockWorks(Feeder, procedure.FeederStockWorks, cancellationToken);
  2551. if (procedure.WaitFeederStop > 0) await Task.Delay(procedure.WaitFeederStop);
  2552. SendTaskMessage(Lang.料仓供料结束, MessageLevel.Info);
  2553. }
  2554. }
  2555. }
  2556. /// <summary>
  2557. /// 拍照后在 NG 情况下的 Feeder 后处理,例如供料或振动。
  2558. /// </summary>
  2559. public async Task ExecuteFeederForPhotoLater(IVoiceCoilMotorFeeder Feeder, ProcedureModel procedure, CancellationToken cancellationToken)
  2560. {
  2561. //根据斑点面积决定是否料仓供料
  2562. if (procedure.LastBlobArea <= procedure.MinArea)
  2563. {
  2564. SendTaskMessage(Lang.执行料仓供料, MessageLevel.Info);
  2565. await ExecuteFeederStockWorks(Feeder, procedure.FeederStockWorks, cancellationToken);
  2566. if (cancellationToken != null && cancellationToken.IsCancellationRequested) return;
  2567. if (procedure.WaitFeederStop > 0) await Task.Delay(procedure.WaitFeederStop, cancellationToken);
  2568. SendTaskMessage(Lang.料仓供料结束, MessageLevel.Info);
  2569. }
  2570. else
  2571. {
  2572. if (procedure.FeederWorks != null && procedure.FeederWorks.FeederWorkList != null)
  2573. {
  2574. SendTaskMessage(Lang.执行Feeder振动, MessageLevel.Info);
  2575. //执行配置的Feeder振动任务
  2576. await ExecuteFeederWorks(Feeder, procedure.FeederWorks, cancellationToken);
  2577. if (cancellationToken != null && cancellationToken.IsCancellationRequested) return;
  2578. if (procedure.WaitFeederStop > 0) await Task.Delay(procedure.WaitFeederStop, cancellationToken);
  2579. SendTaskMessage(Lang.Feeder振动结束, MessageLevel.Info);
  2580. }
  2581. }
  2582. }
  2583. /// <summary>
  2584. /// 并行执行料仓供料和振动任务。
  2585. /// </summary>
  2586. public async Task ExecuteFeederStockWorks(IVoiceCoilMotorFeeder feeder, FeederStockWorks works, CancellationToken cancellationToken, bool isUpdateParame = true)
  2587. {
  2588. //同时执行料仓供料和Feeder振动任务
  2589. var stockTask = ExecuteFeederStockWorksOnly(feeder, works.FeederStockWorkList.ToArray(), cancellationToken);
  2590. var vibrationTask = ExecuteFeederWorkOnly(feeder, works.FeederWorkList.ToArray(), cancellationToken);
  2591. await Task.WhenAll(stockTask, vibrationTask);
  2592. }
  2593. /// <summary>
  2594. /// 执行料仓振动任务序列(仅料仓相关动作)。
  2595. /// </summary>
  2596. public async Task ExecuteFeederStockWorksOnly(IVoiceCoilMotorFeeder feeder, FeederStockWork[] works, CancellationToken cancellationToken)
  2597. {
  2598. //执行配置的料仓振动任务
  2599. if (feeder.FeederBrand == FeederBrand.AFAG)
  2600. {
  2601. foreach (var stockwork in works)
  2602. {
  2603. if (stockwork.RegisterIndex == 0)
  2604. {
  2605. if (stockwork.Duration > 0) await Task.Delay(stockwork.Duration, cancellationToken);
  2606. }
  2607. else if (stockwork.RegisterIndex == 1)
  2608. {
  2609. // 保留原注释的位置给 Modbus 操作
  2610. }
  2611. if (cancellationToken != null && cancellationToken.IsCancellationRequested)
  2612. {
  2613. return;
  2614. }
  2615. }
  2616. }
  2617. else
  2618. {
  2619. foreach (var stockwork in works)
  2620. {
  2621. if (stockwork.Function == VibrationFunction.Delay)
  2622. {
  2623. if (stockwork.Duration > 0) await Task.Delay(stockwork.Duration, cancellationToken);
  2624. }
  2625. else
  2626. {
  2627. await feeder.OutputAsync(((int)stockwork.Function) + 1, stockwork.Duration);
  2628. if (stockwork.Duration > 0) await Task.Delay(stockwork.Duration, cancellationToken);
  2629. }
  2630. if (cancellationToken != null && cancellationToken.IsCancellationRequested)
  2631. {
  2632. return;
  2633. }
  2634. }
  2635. }
  2636. }
  2637. /// <summary>
  2638. /// 执行单独的 Feeder 振动动作序列(仅振动相关)。
  2639. /// </summary>
  2640. public async Task ExecuteFeederWorkOnly(IVoiceCoilMotorFeeder feeder, FeederWork[] works, CancellationToken cancellationToken, bool isUpdateParame = true)
  2641. {
  2642. if (works == null)
  2643. {
  2644. return;
  2645. }
  2646. if (feeder.FeederBrand == FeederBrand.AFAG)
  2647. {
  2648. //执行配置的Feeder振动任务
  2649. foreach (var feederwork in works)
  2650. {
  2651. if (feederwork.ConfigIndex < 0)
  2652. {
  2653. continue;
  2654. }
  2655. if (feederwork.ConfigIndex == 0)
  2656. {
  2657. if (feederwork.Duration > 0) await Task.Delay(feederwork.Duration, cancellationToken);
  2658. }
  2659. else
  2660. {
  2661. ((AfagFeeder)feeder).LoadConfiguration(feederwork.ConfigIndex);
  2662. ((AfagFeeder)feeder).SetIntensity(feederwork.Intensity);
  2663. ((AfagFeeder)feeder).SetDirection(feederwork.Direction);
  2664. if (feederwork.Duration > 0) await Task.Delay(feederwork.Duration, cancellationToken);
  2665. if (cancellationToken != null && cancellationToken.IsCancellationRequested)
  2666. {
  2667. return;
  2668. }
  2669. ((AfagFeeder)feeder).SetIntensity(0);
  2670. }
  2671. if (cancellationToken != null && cancellationToken.IsCancellationRequested)
  2672. {
  2673. return;
  2674. }
  2675. }
  2676. }
  2677. else
  2678. {
  2679. //执行配置的Feeder振动任务
  2680. foreach (var feederwork in works)
  2681. {
  2682. if (feederwork.Function == VibrationFunction.Delay)
  2683. {
  2684. if (feederwork.Duration > 0) await Task.Delay(feederwork.Duration, cancellationToken);
  2685. }
  2686. else
  2687. {
  2688. if (feederwork.SingleAction != null && isUpdateParame)
  2689. {
  2690. await feeder.SetShakeParametersAsync((int)feederwork.Function, feederwork.SingleAction);
  2691. }
  2692. await feeder.StartAction((int)feederwork.Function, feederwork.Duration);
  2693. if (feederwork.Duration > 0) await Task.Delay(feederwork.Duration, cancellationToken);
  2694. }
  2695. if (cancellationToken != null && cancellationToken.IsCancellationRequested)
  2696. {
  2697. return;
  2698. }
  2699. }
  2700. }
  2701. }
  2702. /// <summary>
  2703. /// 执行 Feeder 振动集合(逐个执行 FeederWorkList 中的动作)。
  2704. /// </summary>
  2705. public async Task ExecuteFeederWorks(IVoiceCoilMotorFeeder feeder, FeederWorks works, CancellationToken cancellationToken, bool isUpdateParame = true)
  2706. {
  2707. if (feeder.FeederBrand == FeederBrand.AFAG)
  2708. {
  2709. foreach (var feederwork in works.FeederWorkList)
  2710. {
  2711. if (feederwork.ConfigIndex < 0)
  2712. {
  2713. continue;
  2714. }
  2715. if (feederwork.ConfigIndex == 0)
  2716. {
  2717. await Task.Delay(feederwork.Duration, cancellationToken);
  2718. }
  2719. else
  2720. {
  2721. ((AfagFeeder)feeder).LoadConfiguration(feederwork.ConfigIndex);
  2722. ((AfagFeeder)feeder).SetIntensity(feederwork.Intensity);
  2723. ((AfagFeeder)feeder).SetDirection(feederwork.Direction);
  2724. await Task.Delay(feederwork.Duration, cancellationToken);
  2725. if (cancellationToken != null && cancellationToken.IsCancellationRequested)
  2726. {
  2727. return;
  2728. }
  2729. ((AfagFeeder)feeder).SetIntensity(0);
  2730. }
  2731. if (cancellationToken != null && cancellationToken.IsCancellationRequested)
  2732. {
  2733. return;
  2734. }
  2735. }
  2736. }
  2737. else
  2738. {
  2739. foreach (var feederwork in works.FeederWorkList)
  2740. {
  2741. if (feederwork.Function == VibrationFunction.Delay)
  2742. {
  2743. if (feederwork.Duration > 0) await Task.Delay(feederwork.Duration, cancellationToken);
  2744. }
  2745. else
  2746. {
  2747. if (feederwork.SingleAction != null && isUpdateParame)
  2748. {
  2749. await feeder.SetShakeParametersAsync((int)feederwork.Function, feederwork.SingleAction);
  2750. }
  2751. await feeder.StartAction((int)feederwork.Function, feederwork.Duration);
  2752. if (feederwork.Duration > 0) await Task.Delay(feederwork.Duration, cancellationToken);
  2753. }
  2754. if (cancellationToken != null && cancellationToken.IsCancellationRequested)
  2755. {
  2756. return;
  2757. }
  2758. }
  2759. }
  2760. }
  2761. /// <summary>
  2762. /// 在拍照前设置光源亮度和打开光源
  2763. /// </summary>
  2764. /// <param name="procedure">流程模型</param>
  2765. /// <returns></returns>
  2766. public async Task SetLightBeforePhoto(ProcedureModel procedure)
  2767. {
  2768. var sysConfig = _configService.GetSystemConfiguration();
  2769. if (sysConfig.LightUse == true)
  2770. {
  2771. return;
  2772. }
  2773. //判断当前流程是否启用光源控制
  2774. if (procedure.IsControlLightChannels)
  2775. {
  2776. //打开所有需要控制的光源通道
  2777. foreach (var lightChannel in procedure.LightChannels)
  2778. {
  2779. bool isSucceed = false;
  2780. isSucceed = await _lightManagerService.TurnOnGlobalChannelAsync(lightChannel.GlobalIndex);
  2781. if (!isSucceed)
  2782. {
  2783. LogHelper.WriteLogInfo($"设置光源通道{lightChannel.GlobalIndex}打开失败!");
  2784. }
  2785. isSucceed = await _lightManagerService.SetGlobalChannelBrightnessAsync(lightChannel.GlobalIndex, lightChannel.DefaultBrightness);
  2786. if (!isSucceed)
  2787. {
  2788. LogHelper.WriteLogInfo($"设置光源通道{lightChannel.GlobalIndex}亮度{lightChannel.DefaultBrightness}失败!");
  2789. }
  2790. }
  2791. }
  2792. }
  2793. /// <summary>
  2794. /// 在拍照后关闭光源
  2795. /// </summary>
  2796. /// <param name="procedure">流程模型</param>
  2797. /// <returns></returns>
  2798. public async Task TurnOffLightAfterPhoto(ProcedureModel procedure)
  2799. {
  2800. var sysConfig = _configService.GetSystemConfiguration();
  2801. if (sysConfig.LightUse == true)
  2802. {
  2803. return;
  2804. }
  2805. //判断当前流程是否启用光源控制
  2806. if (procedure.IsControlLightChannels)
  2807. {
  2808. //关闭所有需要控制的光源通道
  2809. foreach (var lightChannel in procedure.LightChannels)
  2810. {
  2811. bool isSucceed = false;
  2812. isSucceed = await _lightManagerService.TurnOffGlobalChannelAsync(lightChannel.GlobalIndex);
  2813. if (!isSucceed)
  2814. {
  2815. LogHelper.WriteLogInfo($"设置光源通道{lightChannel.GlobalIndex}关闭失败!");
  2816. }
  2817. }
  2818. }
  2819. }
  2820. #endregion
  2821. }
  2822. }