RemoteCommandService.cs 184 KB

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