RemoteCommandService.cs 160 KB

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