RemoteCommandService.cs 185 KB

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