RemoteCommandService.cs 176 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695
  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 void SendTaskMessage(string msg, MessageLevel level)
  1076. {
  1077. App.Current.Dispatcher.Invoke(() =>
  1078. {
  1079. _eventAggregator.GetEvent<TaskMessageNotification>().Publish(new Models.MessageStruct() { Message = msg, level = level });
  1080. });
  1081. }
  1082. #region 执行视觉任务辅助方法
  1083. /// <summary>
  1084. /// 执行 Feeder 引导的视觉任务。负责:
  1085. /// - 解析输入命令(是否先振动/先拍照、SetInputs)
  1086. /// - 在拍照前后执行对应的 Feeder 操作(开灯、振动、供料等)
  1087. /// - 多次尝试拍照并运行视觉工具,直到成功或达到失败次数上限
  1088. /// - 返回布尔成功标记及字符串数组形式的响应项
  1089. /// </summary>
  1090. public async Task<(bool IsSucceed, string[] Response)> ExecuteFeederVisionTaskAsync(IVoiceCoilMotorFeeder feeder, ProcedureModel procedure, string[] items, CancellationToken cancellationToken)
  1091. {
  1092. // 如果输入的items中是否包含Vibration和NoVibration,这两个分别对应是否先振动和是否先拍照
  1093. bool doVibrateFirst = items != null && items.Contains("VibrateFirst");
  1094. bool doCaptureFirst = items != null && items.Contains("CaptureFirst");
  1095. if (doVibrateFirst && doCaptureFirst) doCaptureFirst = false; // 如果两个都包含,则以振动优先为准
  1096. // 触发命令传入的输入终端
  1097. Dictionary<string, string> InputTerminal = null;
  1098. // 解析触发命令传入的输入终端参数
  1099. //判断传入参数中是否存在“SetInputs”
  1100. if (items != null && items.Length > 1 && items[0] == "SetInputs")
  1101. {
  1102. //依次从索引1开始解析参数,格式为 key=value,直到遇到非key=value格式的参数为止
  1103. InputTerminal = new Dictionary<string, string>();
  1104. for (int i = 1; i < items.Length; i++)
  1105. {
  1106. var pair = items[i].Split('=');
  1107. if (pair.Length == 2)
  1108. {
  1109. InputTerminal[pair[0]] = pair[1];
  1110. }
  1111. else
  1112. {
  1113. break; // 遇到非key=value格式的参数,停止解析
  1114. }
  1115. }
  1116. }
  1117. await SetLightBeforePhoto(procedure);
  1118. //执行Feeder相机拍照前的任务
  1119. await ExecuteFeederForPhotoBefore(feeder, procedure, doVibrateFirst, doCaptureFirst, cancellationToken);
  1120. // 如果遇到取消令牌,则直接返回失败
  1121. if (cancellationToken != null && cancellationToken.IsCancellationRequested)
  1122. {
  1123. await feeder.CloseLightAsync();
  1124. return (false, new string[] { "FeederTaskCancelled" });
  1125. }
  1126. DateTime nowtime = DateTime.Now;
  1127. //拍照失败时,需要多次拍照
  1128. for (int i = 0; i < procedure.FeederFailLimit; i++)
  1129. {
  1130. if (cancellationToken != null && cancellationToken.IsCancellationRequested)
  1131. {
  1132. await feeder.CloseLightAsync();
  1133. await TurnOffLightAfterPhoto(procedure);
  1134. return (false, new string[] { "VisionTaskCancelled" });
  1135. }
  1136. SendTaskMessage(Lang.开始执行视觉流程.Replace("{0}", $"{i + 1}").Replace("{1}", procedure.Name), MessageLevel.Info);
  1137. // 1. 执行相机拍照并运行视觉工具
  1138. bool visionSucceed = ExecutePhoto(procedure, InputTerminal, out CogToolBlockTerminalCollection outputCollection);
  1139. if (!visionSucceed)
  1140. {
  1141. SendTaskMessage(Lang.视觉任务执行失败, MessageLevel.Error);
  1142. continue;
  1143. }
  1144. if (!outputCollection.Contains("Found"))
  1145. {
  1146. SendTaskMessage(Lang.未找到视觉输出结果, MessageLevel.Error);
  1147. return (false, new string[] { "NoFoundOutput" });
  1148. }
  1149. procedure.LastBlobArea = Convert.ToDouble(outputCollection["BlobTotalArea"].Value);
  1150. // 2. 获取视觉输出结果
  1151. bool Found = (bool)(outputCollection["Found"].Value);
  1152. if (!Found)
  1153. {
  1154. SendTaskMessage(Lang.拍照NG, MessageLevel.Debug);
  1155. await TurnOffLightAfterPhoto(procedure);
  1156. await ExecuteFeederForPhotoLater(feeder, procedure, cancellationToken);
  1157. continue;
  1158. }
  1159. SendTaskMessage(Lang.拍照OK, MessageLevel.Debug);
  1160. if (procedure.ProcedureOutputs == null)
  1161. {
  1162. SendTaskMessage(Lang.视觉流程未配置输出项, MessageLevel.Alarm);
  1163. return (false, new string[] { "NoOutputConfigured" });
  1164. }
  1165. // 3. 获取视觉输出结果
  1166. LogHelper.WriteLogInfo("开始获取视觉输出结果");
  1167. var (IsSucceed, ErrMsg, Output) = GetVisionOutput(procedure, outputCollection, null);
  1168. if (!IsSucceed)
  1169. {
  1170. SendTaskMessage(Lang.获取视觉输出结果失败, MessageLevel.Error);
  1171. return (false, new string[] { ErrMsg });
  1172. }
  1173. // 4. 组织返回结果
  1174. int outputPointCount = 0;//输出点的数量
  1175. List<double[]> currentPoints = new List<double[]>(); //点位数据
  1176. List<string> outputItems = new List<string>(); //多项输出结果集合
  1177. foreach (var output in procedure.ProcedureOutputs)
  1178. {
  1179. if (Output.ContainsKey(output.Name))
  1180. {
  1181. var (IsPoint, Value) = Output[output.Name];
  1182. if (IsPoint)
  1183. {
  1184. //Value是点位数据,类型:List<string[]>,string[]是一个点位,里面是X、Y,U等数据
  1185. //将所有点位数据和单个点位数据中的坐标之间都用逗号分隔,多个点位之间用逗号分隔
  1186. List<string[]> points = Value as List<string[]>;
  1187. List<string> allpoints = new List<string>();
  1188. for (int j = 0; j < points.Count; j++)
  1189. {
  1190. //如果当前流程开启了剔除重复点功能,则进行剔除
  1191. if (procedure.IsExcludeNearPoint && procedure.LastRunPoints != null && procedure.LastRunPoints.Count > 0)
  1192. {
  1193. //当前点的坐标数据
  1194. double px = double.Parse(points[j][0]);
  1195. double py = double.Parse(points[j][1]);
  1196. double pu = double.Parse(points[j][2]);
  1197. //检查当前点是否与上次运行的点过于接近
  1198. //使用linq来检测上一次的点位集合中,是否存在某个点与当前点的x,y,u的差值小于设定的阈值
  1199. bool isNear = procedure.LastRunPoints.Any(lp =>
  1200. Math.Abs(lp[0] - px) < procedure.ExcludeNearPointThreshol &&
  1201. Math.Abs(lp[1] - py) < procedure.ExcludeNearPointThreshol &&
  1202. Math.Abs(lp[2] - pu) < procedure.ExcludeNearPointThreshol);
  1203. if (isNear) continue; //如果存在接近的点,则跳过当前点,不进行添加
  1204. }
  1205. //单个点位内坐标之间逗号分隔
  1206. allpoints.Add(string.Join(",", points[j]));
  1207. //如果输出模式是AllAtOnce或者BatchedUntilTerminator,则需要检查是否达到最大点位数量限制
  1208. if (procedure.OutputPointMode == OutputPointMode.AllAtOnce || procedure.OutputPointMode == OutputPointMode.BatchedUntilTerminator)
  1209. {
  1210. //如果当前总点位数量已经达到最大限制,则停止添加更多点位
  1211. if (allpoints.Count >= procedure.OutputPointCountMax)
  1212. {
  1213. break;
  1214. }
  1215. }
  1216. currentPoints.Add(new double[] { double.Parse(points[j][0]), double.Parse(points[j][1]), double.Parse(points[j][2]) });
  1217. }
  1218. //多个点位之间逗号分隔
  1219. string pointstr = allpoints.Count + "," + string.Join(",", allpoints);
  1220. if (procedure.OutputPointMode == OutputPointMode.UntilTerminator || procedure.OutputPointMode == OutputPointMode.BatchedUntilTerminator)
  1221. {
  1222. outputItems.AddRange(allpoints);
  1223. }
  1224. else
  1225. {
  1226. outputItems.Add(pointstr);
  1227. }
  1228. outputPointCount += allpoints.Count;
  1229. }
  1230. else
  1231. {
  1232. string itemstr = Value != null ? Value.ToString() : string.Empty;
  1233. outputItems.Add(itemstr);
  1234. }
  1235. }
  1236. }
  1237. procedure.LastRunPoints = currentPoints;
  1238. //关闭Feeder灯光
  1239. if (feeder.IsConnected)
  1240. {
  1241. await feeder.CloseLightAsync();
  1242. }
  1243. await TurnOffLightAfterPhoto(procedure);
  1244. //如果输出模式是AllAtOnce或者BatchedUntilTerminator,则分次发送数据
  1245. if (procedure.OutputPointMode == OutputPointMode.UntilTerminator || procedure.OutputPointMode == OutputPointMode.BatchedUntilTerminator)
  1246. {
  1247. //将outputItems按照procedure.OutputSeparator进行拼接,得到最终返回结果
  1248. string finalResponse = string.Join(procedure.OutputSeparator, outputItems);
  1249. return (true, outputItems.ToArray());
  1250. }
  1251. else
  1252. {
  1253. //否则,一次发送所有数据
  1254. //将outputItems按照procedure.OutputSeparator进行拼接,得到最终返回结果
  1255. string finalResponse = string.Join(procedure.OutputSeparator, outputItems);
  1256. return (true, new string[] { finalResponse });
  1257. }
  1258. }
  1259. //关闭Feeder灯光
  1260. if (feeder.IsConnected)
  1261. {
  1262. await feeder.CloseLightAsync();
  1263. }
  1264. await TurnOffLightAfterPhoto(procedure);
  1265. SendTaskMessage(Lang.多次拍照失败, MessageLevel.Alarm);
  1266. return (false, new string[] { "VisionFailed" });
  1267. }
  1268. /// <summary>
  1269. /// 执行非 Feeder 引导的普通视觉任务,返回单字符串响应。
  1270. /// </summary>
  1271. public async Task<(bool IsSucceed, string Response)> ExecuteNormalVisionTaskAsync(ProcedureModel procedure, string[] items, CancellationToken cancellationToken)
  1272. {
  1273. // 开始执行前的时间点
  1274. DateTime startTime = DateTime.Now;
  1275. try
  1276. {
  1277. await SetLightBeforePhoto(procedure);
  1278. // 触发命令传入的输入终端
  1279. Dictionary<string, string> InputTerminal = null;
  1280. // 解析触发命令传入的输入终端参数
  1281. //判断传入参数中是否存在“SetInputs”
  1282. if (items != null && items.Length > 1 && items[0] == "SetInputs")
  1283. {
  1284. InputTerminal = items.Skip(1)
  1285. .Select(x => x.Split('='))
  1286. .Where(y => y.Length == 2)
  1287. .ToDictionary(z => z[0], z => z[1]);
  1288. }
  1289. // 机器人当前坐标
  1290. double[] currentpos = null;
  1291. // 判断传入参数长度是否3,并且是否都是double
  1292. 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))
  1293. {
  1294. currentpos = new double[] { _x, _y, _u };
  1295. }
  1296. //拍照失败时,需要多次拍照
  1297. for (int i = 0; i < procedure.FeederFailLimit; i++)
  1298. {
  1299. if (cancellationToken != null && cancellationToken.IsCancellationRequested)
  1300. {
  1301. return (false, "VisionTaskCancelled");
  1302. }
  1303. // 1. 执行相机拍照并运行视觉工具
  1304. LogHelper.WriteLogInfo("开始执行相机拍照并运行视觉工具");
  1305. bool visionSucceed = ExecutePhoto(procedure, InputTerminal, out CogToolBlockTerminalCollection outputCollection);
  1306. if (!visionSucceed)
  1307. {
  1308. SendTaskMessage(Lang.视觉任务执行失败, MessageLevel.Error);
  1309. continue;
  1310. }
  1311. if (!outputCollection.Contains("Found"))
  1312. {
  1313. SendTaskMessage(Lang.未找到视觉输出结果, MessageLevel.Error);
  1314. return (false, "NoFoundOutput");
  1315. }
  1316. bool Found = (bool)(outputCollection["Found"].Value);
  1317. if (!Found)
  1318. {
  1319. SendTaskMessage(Lang.拍照NG, MessageLevel.Debug);
  1320. continue;
  1321. }
  1322. SendTaskMessage(Lang.拍照OK, MessageLevel.Debug);
  1323. // 2. 获取视觉输出结果
  1324. LogHelper.WriteLogInfo("开始获取视觉输出结果");
  1325. var (IsSucceed, ErrMsg, Output) = GetVisionOutput(procedure, outputCollection, currentpos);
  1326. if (!IsSucceed)
  1327. {
  1328. SendTaskMessage(Lang.获取视觉输出结果失败, MessageLevel.Error);
  1329. return (false, ErrMsg);
  1330. }
  1331. // 3. 组织返回结果
  1332. List<string> outputItems = new List<string>(); //多项输出结果集合
  1333. foreach (var output in procedure.ProcedureOutputs)
  1334. {
  1335. if (Output.ContainsKey(output.Name))
  1336. {
  1337. var (IsPoint, Value) = Output[output.Name];
  1338. if (IsPoint)
  1339. {
  1340. List<string[]> points = Value as List<string[]>;
  1341. List<string> allpoints = new List<string>();
  1342. for (int j = 0; j < points.Count; j++)
  1343. {
  1344. allpoints.Add(string.Join(",", points[j]));
  1345. }
  1346. //多个点位之间逗号分隔
  1347. string pointstr = allpoints.Count + "," + string.Join(",", allpoints);
  1348. outputItems.Add(pointstr);
  1349. }
  1350. else
  1351. {
  1352. string itemstr = Value != null ? Value.ToString() : string.Empty;
  1353. outputItems.Add(itemstr);
  1354. }
  1355. }
  1356. }
  1357. //将outputItems按照procedure.OutputSeparator进行拼接,得到最终返回结果
  1358. string finalResponse = string.Join(procedure.OutputSeparator, outputItems);
  1359. return (true, finalResponse);
  1360. }
  1361. return (false, "VisionFailed");
  1362. }
  1363. catch (Exception ex)
  1364. {
  1365. SendTaskMessage(ex.Message, MessageLevel.Error);
  1366. LogHelper.WriteLogError("执行普通视觉任务时出错!", ex);
  1367. return (false, "Exception");
  1368. }
  1369. finally
  1370. {
  1371. await TurnOffLightAfterPhoto(procedure);
  1372. }
  1373. }
  1374. /// <summary>
  1375. /// 执行翻转相机拍照流程运行
  1376. /// </summary>
  1377. /// <param name="procedure"></param>
  1378. /// <param name="outputCollection"></param>
  1379. /// <returns></returns>
  1380. public bool ExecutePhoto(ProcedureModel procedure, out CogToolBlockTerminalCollection outputCollection)
  1381. {
  1382. try
  1383. {
  1384. //SetLightBeforePhoto(procedure);
  1385. // 1. 采集图像
  1386. var camera = _cameraService.GetCamera(procedure.CameraId);
  1387. bool succed = camera.SetExposureTime(procedure.ExposureTime);
  1388. if (!succed)
  1389. {
  1390. SendTaskMessage("相机曝光设置失败", MessageLevel.Error);
  1391. }
  1392. succed = camera.SetGain(procedure.Gain);
  1393. if (!succed)
  1394. {
  1395. SendTaskMessage("相机增益设置失败", MessageLevel.Error);
  1396. }
  1397. DateTime nowtime = DateTime.Now;
  1398. LogHelper.WriteLogInfo("开始采集图像");
  1399. var image = camera.Grab();
  1400. if (image == null)
  1401. {
  1402. SendTaskMessage(Lang.图像采集失败, MessageLevel.Error);
  1403. outputCollection = null;
  1404. return false;
  1405. }
  1406. procedure.ToolBlock.Inputs["InputImage"].Value = image;
  1407. LogHelper.WriteLogInfo(string.Format("采集图像完成用时0ms", (DateTime.Now - nowtime).Milliseconds));
  1408. // 3. 运行视觉工具
  1409. LogHelper.WriteLogInfo("开始运行视觉工具");
  1410. procedure.ToolBlock.Run(); //运行ToolBlock
  1411. if (procedure.ToolBlock.RunStatus.Result == CogToolResultConstants.Accept)
  1412. {
  1413. SendTaskMessage(Lang.视觉流程执行耗时.Replace("{0}", procedure.Name).Replace("{1}", $"{procedure.ToolBlock.RunStatus.ProcessingTime:F1}"), MessageLevel.Info);
  1414. outputCollection = procedure.ToolBlock.Outputs; //获取输出终端集合
  1415. DatabaseHelper.AddCameraRecords(_productService.GetCurrentProduct().Name, procedure.Name, outputCollection);
  1416. ICogRecord record = null;
  1417. foreach (CogToolBlockTerminal item in outputCollection)
  1418. {
  1419. if (item.Value is ICogRecord)
  1420. record = item.Value as ICogRecord;
  1421. }
  1422. bool Found = (bool)(outputCollection["Found"].Value);
  1423. //获取图片存储的图片文件名
  1424. string imgName = string.Empty;
  1425. if (procedure.IsSaveImage && !string.IsNullOrEmpty(procedure.ImageFileNameFormat))
  1426. {
  1427. // 创建模板,使用 {变量名:格式} 语法
  1428. var template = new FileNameTemplate(procedure.ImageFileNameFormat);
  1429. // 注册变量
  1430. template.RegisterVariable("ProductSN", () => _productService.CurrentProductCode);
  1431. template.RegisterVariable("CameraName", () => procedure.CameraName);
  1432. template.RegisterVariable("ShotCount", () => 1);
  1433. template.RegisterVariable("Result", () => Found ? "OK" : "NG");
  1434. template.RegisterVariable("DateTime", () => DateTime.Now);
  1435. // 生成文件名
  1436. imgName = template.Generate();
  1437. }
  1438. _eventAggregator.GetEvent<RenderUpdateNotification>().Publish(new ShowRender()
  1439. {
  1440. Id = procedure.Id,
  1441. DisplayName = procedure.DisplayName,
  1442. //Image = (ICogImage)procedure.ToolBlock.Outputs["OriImage"].Value,
  1443. //Image = (ICogImage)procedure.ToolBlock.Inputs["InputImage"].Value,
  1444. Image = image,
  1445. Graphic = outputCollection["Graphic"].Value as CogGraphicCollection,
  1446. Record = record,
  1447. Result = Found,
  1448. IsShow = true,
  1449. IsSaveImage = procedure.IsSaveImage,
  1450. SaveImageModel = procedure.SaveImageModel,
  1451. SaveImagePathModel = procedure.SaveImagePathModel,
  1452. SavePath = procedure.SavePath,
  1453. IsCompress = procedure.IsCompress,
  1454. ProceductName = procedure.Name,
  1455. ImageFileName = imgName,
  1456. Is3DModel = true
  1457. });
  1458. return true;
  1459. }
  1460. else
  1461. {
  1462. SendTaskMessage(Lang.视觉流程执行出错耗时.Replace("{0}", procedure.Name).Replace("{1}", $"{procedure.ToolBlock.RunStatus.ProcessingTime:F1}"), MessageLevel.Error);
  1463. SendTaskMessage(procedure.ToolBlock.RunStatus.Message, MessageLevel.Error);
  1464. outputCollection = null;
  1465. //获取图片存储的图片文件名
  1466. string imgName = string.Empty;
  1467. if (procedure.IsSaveImage && !string.IsNullOrEmpty(procedure.ImageFileNameFormat))
  1468. {
  1469. // 创建模板,使用 {变量名:格式} 语法
  1470. var template = new FileNameTemplate(procedure.ImageFileNameFormat);
  1471. // 注册变量
  1472. template.RegisterVariable("ProductSN", () => _productService.CurrentProductCode);
  1473. template.RegisterVariable("CameraName", () => procedure.CameraName);
  1474. template.RegisterVariable("ShotCount", () => 1);
  1475. template.RegisterVariable("Result", () => "NG");
  1476. template.RegisterVariable("DateTime", () => DateTime.Now);
  1477. // 生成文件名
  1478. imgName = template.Generate();
  1479. }
  1480. _eventAggregator.GetEvent<RenderUpdateNotification>().Publish(new ShowRender()
  1481. {
  1482. Id = procedure.Id,
  1483. DisplayName = procedure.DisplayName,
  1484. //Image = (ICogImage)procedure.ToolBlock.Outputs["OriImage"].Value,
  1485. //Image = (ICogImage)procedure.ToolBlock.Inputs["InputImage"].Value,
  1486. Image = image,
  1487. Graphic = new CogGraphicCollection(),
  1488. Result = false,
  1489. IsShow = true,
  1490. IsSaveImage = procedure.IsSaveImage,
  1491. SaveImageModel = procedure.SaveImageModel,
  1492. SaveImagePathModel = procedure.SaveImagePathModel,
  1493. SavePath = procedure.SavePath,
  1494. ProceductName = procedure.Name,
  1495. ImageFileName = imgName,
  1496. Is3DModel = true
  1497. });
  1498. return false;
  1499. }
  1500. }
  1501. catch (Exception ex)
  1502. {
  1503. SendTaskMessage(ex.Message, MessageLevel.Error);
  1504. LogHelper.WriteLogError("执行相机取图并执行视觉工具组时出错", ex);
  1505. outputCollection = null;
  1506. return false;
  1507. }
  1508. }
  1509. /// <summary>
  1510. /// 执行相机拍照并运行 ToolBlock,返回是否成功并通过 out 参数返回 Outputs。
  1511. /// 该方法会发布 RenderUpdateNotification 以更新 UI。
  1512. /// </summary>
  1513. public bool ExecutePhoto(ProcedureModel procedure, Dictionary<string, string> InputTerminal, out CogToolBlockTerminalCollection outputCollection)
  1514. {
  1515. try
  1516. {
  1517. // 1. 采集图像
  1518. var camera = _cameraService.GetCamera(procedure.CameraId);
  1519. bool succed = camera.SetExposureTime(procedure.ExposureTime);
  1520. if (!succed)
  1521. {
  1522. SendTaskMessage($"相机曝光设置失败!", MessageLevel.Error);
  1523. }
  1524. succed = camera.SetGain(procedure.Gain);
  1525. if (!succed)
  1526. {
  1527. SendTaskMessage($"相机增益设置失败!", MessageLevel.Error);
  1528. }
  1529. DateTime nowtime = DateTime.Now;
  1530. LogHelper.WriteLogInfo("开始采集图像");
  1531. //var image = camera.Grab();
  1532. var image = camera.Grab();
  1533. if (image == null)
  1534. {
  1535. SendTaskMessage(Lang.图像采集失败, MessageLevel.Error);
  1536. outputCollection = null;
  1537. return false;
  1538. }
  1539. procedure.ToolBlock.Inputs["InputImage"].Value = image;
  1540. LogHelper.WriteLogInfo($"采集图像完成;用时:{(DateTime.Now - nowtime).Milliseconds}ms");
  1541. // 2. 为ToolBlock传入其他输入终端
  1542. if (InputTerminal != null)
  1543. {
  1544. LogHelper.WriteLogInfo($"为ToolBlock传入输入终端");
  1545. foreach (var item in InputTerminal)
  1546. {
  1547. if (procedure.ToolBlock.Inputs.Contains(item.Key))
  1548. {
  1549. LogHelper.WriteLogInfo($"传入[{item.Key}]={item.Value}");
  1550. procedure.ToolBlock.Inputs[item.Key].Value = item.Value;
  1551. }
  1552. else
  1553. {
  1554. LogHelper.WriteLogInfo($"创建并传入[{item.Key}]={item.Value}");
  1555. procedure.ToolBlock.Inputs.Add(new CogToolBlockTerminal(item.Key, item.Value));
  1556. }
  1557. }
  1558. }
  1559. // 3. 运行视觉工具
  1560. LogHelper.WriteLogInfo("开始运行视觉工具");
  1561. procedure.ToolBlock.Run(); //运行ToolBlock
  1562. if (procedure.ToolBlock.RunStatus.Result == CogToolResultConstants.Accept)
  1563. {
  1564. SendTaskMessage(Lang.视觉流程执行耗时.Replace("{0}", procedure.Name).Replace("{1}", $"{procedure.ToolBlock.RunStatus.ProcessingTime:F1}"), MessageLevel.Info);
  1565. outputCollection = procedure.ToolBlock.Outputs; //获取输出终端集合
  1566. DatabaseHelper.AddCameraRecords(_productService.GetCurrentProduct().Name, procedure.Name, outputCollection);
  1567. ICogRecord record = null;
  1568. foreach (CogToolBlockTerminal item in outputCollection)
  1569. {
  1570. if (item.Value is ICogRecord)
  1571. record = item.Value as ICogRecord;
  1572. }
  1573. bool Found = (bool)(outputCollection["Found"].Value);
  1574. //获取图片存储的图片文件名
  1575. string imgName = string.Empty;
  1576. if (procedure.IsSaveImage && !string.IsNullOrEmpty(procedure.ImageFileNameFormat))
  1577. {
  1578. // 创建模板,使用 {变量名:格式} 语法
  1579. var template = new FileNameTemplate(procedure.ImageFileNameFormat);
  1580. // 注册变量
  1581. template.RegisterVariable("ProductSN", () => _productService.CurrentProductCode);
  1582. template.RegisterVariable("CameraName", () => procedure.CameraName);
  1583. template.RegisterVariable("ShotCount", () => 1);
  1584. template.RegisterVariable("Result", () => Found ? "OK" : "NG");
  1585. template.RegisterVariable("DateTime", () => DateTime.Now);
  1586. // 生成文件名
  1587. imgName = template.Generate();
  1588. }
  1589. _eventAggregator.GetEvent<RenderUpdateNotification>().Publish(new ShowRender()
  1590. {
  1591. Id = procedure.Id,
  1592. DisplayName = procedure.DisplayName,
  1593. //Image = (ICogImage)procedure.ToolBlock.Outputs["OriImage"].Value,
  1594. //Image = (ICogImage)procedure.ToolBlock.Inputs["InputImage"].Value,
  1595. Image = image,
  1596. Graphic = outputCollection["Graphic"].Value as CogGraphicCollection,
  1597. Record = record,
  1598. Result = Found,
  1599. IsShow = true,
  1600. IsSaveImage = procedure.IsSaveImage,
  1601. SaveImageModel = procedure.SaveImageModel,
  1602. SaveImagePathModel = procedure.SaveImagePathModel,
  1603. SavePath = procedure.SavePath,
  1604. IsCompress = procedure.IsCompress,
  1605. ProceductName = procedure.Name,
  1606. ImageFileName = imgName,
  1607. Is3DModel = true
  1608. });
  1609. return true;
  1610. }
  1611. else
  1612. {
  1613. SendTaskMessage(Lang.视觉流程执行出错耗时.Replace("{0}", procedure.Name).Replace("{1}", $"{procedure.ToolBlock.RunStatus.ProcessingTime:F1}"), MessageLevel.Error);
  1614. SendTaskMessage(procedure.ToolBlock.RunStatus.Message, MessageLevel.Error);
  1615. outputCollection = null;
  1616. //获取图片存储的图片文件名
  1617. string imgName = string.Empty;
  1618. if (procedure.IsSaveImage && !string.IsNullOrEmpty(procedure.ImageFileNameFormat))
  1619. {
  1620. // 创建模板,使用 {变量名:格式} 语法
  1621. var template = new FileNameTemplate(procedure.ImageFileNameFormat);
  1622. // 注册变量
  1623. template.RegisterVariable("ProductSN", () => _productService.CurrentProductCode);
  1624. template.RegisterVariable("CameraName", () => procedure.CameraName);
  1625. template.RegisterVariable("ShotCount", () => 1);
  1626. template.RegisterVariable("Result", () => "NG");
  1627. template.RegisterVariable("DateTime", () => DateTime.Now);
  1628. // 生成文件名
  1629. imgName = template.Generate();
  1630. }
  1631. _eventAggregator.GetEvent<RenderUpdateNotification>().Publish(new ShowRender()
  1632. {
  1633. Id = procedure.Id,
  1634. DisplayName = procedure.DisplayName,
  1635. //Image = (ICogImage)procedure.ToolBlock.Outputs["OriImage"].Value,
  1636. //Image = (ICogImage)procedure.ToolBlock.Inputs["InputImage"].Value,
  1637. Image = image,
  1638. Graphic = new CogGraphicCollection(),
  1639. Result = false,
  1640. IsShow = true,
  1641. IsSaveImage = procedure.IsSaveImage,
  1642. SaveImageModel = procedure.SaveImageModel,
  1643. SaveImagePathModel = procedure.SaveImagePathModel,
  1644. SavePath = procedure.SavePath,
  1645. ProceductName = procedure.Name,
  1646. ImageFileName = imgName,
  1647. Is3DModel = true
  1648. });
  1649. return false;
  1650. }
  1651. }
  1652. catch (Exception ex)
  1653. {
  1654. SendTaskMessage(ex.Message, MessageLevel.Error);
  1655. LogHelper.WriteLogError("执行相机取图并执行视觉工具组时出错!", ex);
  1656. outputCollection = null;
  1657. return false;
  1658. }
  1659. }
  1660. /// <summary>
  1661. /// 执行相机拍照并运行 ToolBlock,返回是否成功并通过 out 参数返回 Outputs。
  1662. /// 该方法会发布 RenderUpdateNotification 以更新 UI。
  1663. /// </summary>
  1664. public bool ExecutePhoto2(ProcedureModel procedure, Dictionary<string, string> InputTerminal, out CogToolBlockTerminalCollection outputCollection)
  1665. {
  1666. try
  1667. {
  1668. // 1. 采集图像
  1669. var camera = _cameraService.GetCamera(procedure.CameraId);
  1670. bool succed = camera.SetExposureTime(procedure.ExposureTime);
  1671. if (!succed)
  1672. {
  1673. SendTaskMessage($"相机曝光设置失败!", MessageLevel.Error);
  1674. }
  1675. succed = camera.SetGain(procedure.Gain);
  1676. if (!succed)
  1677. {
  1678. SendTaskMessage($"相机增益设置失败!", MessageLevel.Error);
  1679. }
  1680. DateTime nowtime = DateTime.Now;
  1681. LogHelper.WriteLogInfo("开始采集图像");
  1682. //var image = camera.Grab();
  1683. var image = camera.Grab();
  1684. if (image == null)
  1685. {
  1686. SendTaskMessage(Lang.图像采集失败, MessageLevel.Error);
  1687. outputCollection = null;
  1688. return false;
  1689. }
  1690. procedure.ToolBlock.Inputs["InputImage"].Value = image;
  1691. LogHelper.WriteLogInfo($"采集图像完成;用时:{(DateTime.Now - nowtime).Milliseconds}ms");
  1692. // 2. 为ToolBlock传入其他输入终端
  1693. if (InputTerminal != null)
  1694. {
  1695. LogHelper.WriteLogInfo($"为ToolBlock传入输入终端");
  1696. foreach (var item in InputTerminal)
  1697. {
  1698. if (procedure.ToolBlock.Inputs.Contains(item.Key))
  1699. {
  1700. LogHelper.WriteLogInfo($"传入[{item.Key}]={item.Value}");
  1701. procedure.ToolBlock.Inputs[item.Key].Value = item.Value;
  1702. }
  1703. else
  1704. {
  1705. LogHelper.WriteLogInfo($"创建并传入[{item.Key}]={item.Value}");
  1706. procedure.ToolBlock.Inputs.Add(new CogToolBlockTerminal(item.Key, item.Value));
  1707. }
  1708. }
  1709. }
  1710. // 3. 运行视觉工具
  1711. LogHelper.WriteLogInfo("开始运行视觉工具");
  1712. procedure.ToolBlock.Run(); //运行ToolBlock
  1713. if (procedure.ToolBlock.RunStatus.Result == CogToolResultConstants.Accept)
  1714. {
  1715. SendTaskMessage(Lang.视觉流程执行耗时.Replace("{0}", procedure.Name).Replace("{1}", $"{procedure.ToolBlock.RunStatus.ProcessingTime:F1}"), MessageLevel.Info);
  1716. outputCollection = procedure.ToolBlock.Outputs; //获取输出终端集合
  1717. DatabaseHelper.AddCameraRecords(_productService.GetCurrentProduct().Name, procedure.Name, outputCollection);
  1718. ICogRecord record = null;
  1719. foreach (CogToolBlockTerminal item in outputCollection)
  1720. {
  1721. if (item.Value is ICogRecord)
  1722. record = item.Value as ICogRecord;
  1723. }
  1724. bool Found = (bool)(outputCollection["Found"].Value);
  1725. //获取图片存储的图片文件名
  1726. string imgName = string.Empty;
  1727. if (procedure.IsSaveImage && !string.IsNullOrEmpty(procedure.ImageFileNameFormat))
  1728. {
  1729. // 创建模板,使用 {变量名:格式} 语法
  1730. var template = new FileNameTemplate(procedure.ImageFileNameFormat);
  1731. // 注册变量
  1732. template.RegisterVariable("ProductSN", () => _productService.CurrentProductCode);
  1733. template.RegisterVariable("CameraName", () => procedure.CameraName);
  1734. template.RegisterVariable("ShotCount", () => 1);
  1735. template.RegisterVariable("Result", () => Found ? "OK" : "NG");
  1736. template.RegisterVariable("DateTime", () => DateTime.Now);
  1737. // 生成文件名
  1738. imgName = template.Generate();
  1739. }
  1740. _eventAggregator.GetEvent<RenderUpdateNotification>().Publish(new ShowRender()
  1741. {
  1742. Id = procedure.DisplayId,
  1743. DisplayName = procedure.DisplayName,
  1744. //Image = (ICogImage)procedure.ToolBlock.Outputs["OriImage"].Value,
  1745. Image = (ICogImage)procedure.ToolBlock.Inputs["InputImage"].Value,
  1746. Graphic = outputCollection["Graphic"].Value as CogGraphicCollection,
  1747. Record = record,
  1748. Result = Found,
  1749. IsShow = true,
  1750. IsSaveImage = procedure.IsSaveImage,
  1751. SaveImageModel = procedure.SaveImageModel,
  1752. SaveImagePathModel = procedure.SaveImagePathModel,
  1753. SavePath = procedure.SavePath,
  1754. IsCompress = procedure.IsCompress,
  1755. ProceductName = procedure.Name,
  1756. ImageFileName = imgName,
  1757. Is3DModel = false
  1758. });
  1759. return true;
  1760. }
  1761. else
  1762. {
  1763. SendTaskMessage(Lang.视觉流程执行出错耗时.Replace("{0}", procedure.Name).Replace("{1}", $"{procedure.ToolBlock.RunStatus.ProcessingTime:F1}"), MessageLevel.Error);
  1764. SendTaskMessage(procedure.ToolBlock.RunStatus.Message, MessageLevel.Error);
  1765. outputCollection = null;
  1766. //获取图片存储的图片文件名
  1767. string imgName = string.Empty;
  1768. if (procedure.IsSaveImage && !string.IsNullOrEmpty(procedure.ImageFileNameFormat))
  1769. {
  1770. // 创建模板,使用 {变量名:格式} 语法
  1771. var template = new FileNameTemplate(procedure.ImageFileNameFormat);
  1772. // 注册变量
  1773. template.RegisterVariable("ProductSN", () => _productService.CurrentProductCode);
  1774. template.RegisterVariable("CameraName", () => procedure.CameraName);
  1775. template.RegisterVariable("ShotCount", () => 1);
  1776. template.RegisterVariable("Result", () => "NG");
  1777. template.RegisterVariable("DateTime", () => DateTime.Now);
  1778. // 生成文件名
  1779. imgName = template.Generate();
  1780. }
  1781. _eventAggregator.GetEvent<RenderUpdateNotification>().Publish(new ShowRender()
  1782. {
  1783. Id = procedure.DisplayId,
  1784. DisplayName = procedure.DisplayName,
  1785. //Image = (ICogImage)procedure.ToolBlock.Outputs["OriImage"].Value,
  1786. Image = (ICogImage)procedure.ToolBlock.Inputs["InputImage"].Value,
  1787. Graphic = new CogGraphicCollection(),
  1788. Result = false,
  1789. IsShow = true,
  1790. IsSaveImage = procedure.IsSaveImage,
  1791. SaveImageModel = procedure.SaveImageModel,
  1792. SaveImagePathModel = procedure.SaveImagePathModel,
  1793. SavePath = procedure.SavePath,
  1794. ProceductName = procedure.Name,
  1795. ImageFileName = imgName,
  1796. Is3DModel = false
  1797. });
  1798. return false;
  1799. }
  1800. }
  1801. catch (Exception ex)
  1802. {
  1803. SendTaskMessage(ex.Message, MessageLevel.Error);
  1804. LogHelper.WriteLogError("执行相机取图并执行视觉工具组时出错!", ex);
  1805. outputCollection = null;
  1806. return false;
  1807. }
  1808. }
  1809. /// <summary>
  1810. /// 执行相机拍照并运行 ToolBlock,返回是否成功并通过 out 参数返回 Outputs。
  1811. /// 该方法会发布 RenderUpdateNotification 以更新 UI。
  1812. /// </summary>
  1813. public bool ExecutePhoto(ProcedureModel procedure, ICogImage[] imges, Dictionary<string, string> InputTerminal, out CogToolBlockTerminalCollection outputCollection, bool is3dmodel, float confThreshold = 0.25f, float iouThreshold = 0.45f)
  1814. {
  1815. try
  1816. {
  1817. procedure.ToolBlock.Inputs["InputImage"].Value = imges[0];
  1818. if (is3dmodel == true || imges.Length > 1)
  1819. {
  1820. procedure.ToolBlock.Inputs["InputImage2"].Value = imges[1];
  1821. }
  1822. // 2. 为ToolBlock传入其他输入终端
  1823. if (InputTerminal != null)
  1824. {
  1825. LogHelper.WriteLogInfo($"为ToolBlock传入输入终端");
  1826. foreach (var item in InputTerminal)
  1827. {
  1828. if (procedure.ToolBlock.Inputs.Contains(item.Key))
  1829. {
  1830. LogHelper.WriteLogInfo($"传入[{item.Key}]={item.Value}");
  1831. procedure.ToolBlock.Inputs[item.Key].Value = item.Value;
  1832. }
  1833. else
  1834. {
  1835. LogHelper.WriteLogInfo($"创建并传入[{item.Key}]={item.Value}");
  1836. procedure.ToolBlock.Inputs.Add(new CogToolBlockTerminal(item.Key, item.Value));
  1837. }
  1838. }
  1839. }
  1840. string photoAiValue = procedure.UserDefineParameters?.FirstOrDefault(p => string.Equals(p.ParamName, "Photo_AI", StringComparison.OrdinalIgnoreCase))?.ParamValue;
  1841. // photoAiValue 可能为 null/空,建议给个默认值
  1842. bool enablePhotoAi = photoAiValue == "1";
  1843. if (enablePhotoAi == true)
  1844. {
  1845. string exeDir = System.IO.Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
  1846. string trainFolderName = string.IsNullOrWhiteSpace(procedure.CameraTrainFolder) ? "TrainPhoto" : procedure.CameraTrainFolder;
  1847. string trainRoot = System.IO.Path.Combine(exeDir, "Train", trainFolderName);
  1848. string modelPath = System.IO.Path.Combine(exeDir, trainRoot, "weights", "best_openvino_model", "best.xml");
  1849. string metadataPath = System.IO.Path.Combine(exeDir, trainRoot, "weights", "best_openvino_model", "metadata.yaml");
  1850. // (可选)如果你希望缺文件时给出更明确提示:
  1851. if (!File.Exists(modelPath))
  1852. throw new FileNotFoundException("未找到模型文件 best.xml", modelPath);
  1853. if (!File.Exists(metadataPath))
  1854. throw new FileNotFoundException("未找到模型文件 metadata.yaml", metadataPath);
  1855. //string modelPath = @"G:\TEST\train17\weights\best_openvino_model\best.xml";
  1856. //string metadataPath = @"G:\TEST\train17\weights\best_openvino_model\metadata.yaml";
  1857. //string imagePath = "G:\\TEST\\文件\\左上插线\\1.bmp";
  1858. using (var yolo = new YoloOpenVINOInference(modelPath, metadataPath, confThreshold, iouThreshold))
  1859. {
  1860. using (var bitmap = imges[0].ToBitmap())
  1861. {
  1862. var results = yolo.Infer(bitmap);
  1863. procedure.ToolBlock.Inputs["PhotoData"].Value = "";
  1864. procedure.ToolBlock.Inputs["Confidence"].Value = "";
  1865. // 输出结果
  1866. SendTaskMessage($"识别的个数:{results.Count()}", MessageLevel.Alarm);
  1867. string ClassName = "";
  1868. string Confidence = "";
  1869. foreach (var det in results)
  1870. {
  1871. SendTaskMessage($" - {det.ClassName}: 置信度={det.Confidence:F4}, " +
  1872. $"边界框=[{det.Box[0]:F0}, {det.Box[1]:F0}, {det.Box[2]:F0}, {det.Box[3]:F0}]", MessageLevel.Alarm);
  1873. ClassName += $"{det.ClassName}" + ",";
  1874. Confidence += $"{det.Confidence}" + ",";
  1875. }
  1876. procedure.ToolBlock.Inputs["PhotoData"].Value = ClassName;
  1877. procedure.ToolBlock.Inputs["Confidence"].Value = Confidence;
  1878. // 绘制结果 - 使用 OpenCvSharp
  1879. using (var image2 = ImageHelper.ICogImageConvertMat(imges[0]))
  1880. {
  1881. var OriginyoloColorCogImage = ImageHelper.MatConvertICogImage(image2, true);
  1882. // 定义颜色映射
  1883. var colors = new[]
  1884. {
  1885. Scalar.Red, // NG1 - 红色
  1886. Scalar.Green, // NG2 - 绿色
  1887. Scalar.Blue, // NG3 - 蓝色
  1888. Scalar.Yellow // NG4 - 黄色
  1889. };
  1890. foreach (var det in results)
  1891. {
  1892. // 获取边界框坐标
  1893. int x1 = (int)det.Box[0];
  1894. int y1 = (int)det.Box[1];
  1895. int x2 = (int)det.Box[2];
  1896. int y2 = (int)det.Box[3];
  1897. // 添加边界检查:确保坐标有效
  1898. if (x1 >= x2 || y1 >= y2)
  1899. {
  1900. SendTaskMessage($"警告: 无效的边界框 [{x1}, {y1}, {x2}, {y2}]", MessageLevel.Error);
  1901. continue;
  1902. }
  1903. // 确保坐标在图像范围内
  1904. x1 = Math.Max(0, Math.Min(image2.Width, x1));
  1905. y1 = Math.Max(0, Math.Min(image2.Height, y1));
  1906. x2 = Math.Max(0, Math.Min(image2.Width, x2));
  1907. y2 = Math.Max(0, Math.Min(image2.Height, y2));
  1908. // 选择颜色(根据类别ID)
  1909. Scalar color = colors[det.ClassId % colors.Length];
  1910. // 绘制矩形框
  1911. Cv2.Rectangle(image2, new Point(x1, y1), new Point(x2, y2), color, 2);
  1912. // 准备标签文本
  1913. string label = $"{det.ClassName} {det.Confidence:P0}";
  1914. // 计算文本大小
  1915. var textSize = Cv2.GetTextSize(label, HersheyFonts.HersheySimplex, 0.6, 1, out int baseline);
  1916. // 确保文本位置不超出图像边界
  1917. int textX = x1;
  1918. int textY = y1 - 5;
  1919. // 如果文本超出图像顶部,显示在框内底部
  1920. if (textY - textSize.Height < 0)
  1921. {
  1922. textY = y2 + baseline + 5;
  1923. }
  1924. //绘制文本背景
  1925. Cv2.Rectangle(image2,
  1926. new OpenCvSharp.Rect(textX, textY - textSize.Height - baseline - 10,
  1927. textSize.Width + 10, textSize.Height + baseline + 10),
  1928. color, -1);
  1929. // 绘制文本
  1930. Cv2.PutText(image2, label,
  1931. new Point(textX + 5, textY - baseline - 5),
  1932. HersheyFonts.HersheySimplex, 0.6, Scalar.White, 2);
  1933. }
  1934. // 关键:这里转成彩色 ICogImage
  1935. var yoloColorCogImage = ImageHelper.MatConvertICogImage(image2);
  1936. // 模板检测如果需要原图,可以用 imges[0]
  1937. // 如果你希望模板也拿 YOLO 画框图,就用 yoloColorCogImage
  1938. procedure.ToolBlock.Inputs["InputImage"].Value = yoloColorCogImage;
  1939. procedure.ToolBlock.Run();
  1940. outputCollection = procedure.ToolBlock.Outputs;
  1941. ICogRecord record = null;
  1942. foreach (CogToolBlockTerminal item in outputCollection)
  1943. {
  1944. if (item.Value is ICogRecord)
  1945. record = item.Value as ICogRecord;
  1946. }
  1947. bool Found = (bool)(outputCollection["Found"].Value);
  1948. //获取图片存储的图片文件名
  1949. string imgName = string.Empty;
  1950. if (procedure.IsSaveImage && !string.IsNullOrEmpty(procedure.ImageFileNameFormat))
  1951. {
  1952. // 创建模板,使用 {变量名:格式} 语法
  1953. var template = new FileNameTemplate(procedure.ImageFileNameFormat);
  1954. // 注册变量
  1955. template.RegisterVariable("ProductSN", () => _productService.CurrentProductCode);
  1956. template.RegisterVariable("CameraName", () => procedure.CameraName);
  1957. template.RegisterVariable("ShotCount", () => 1);
  1958. template.RegisterVariable("Result", () => Found ? "OK" : "NG");
  1959. template.RegisterVariable("DateTime", () => DateTime.Now);
  1960. // 生成文件名
  1961. imgName = template.Generate();
  1962. }
  1963. _eventAggregator.GetEvent<RenderUpdateNotification>().Publish(new ShowRender()
  1964. {
  1965. Id = procedure.DisplayId,
  1966. DisplayName = procedure.DisplayName,
  1967. Image = OriginyoloColorCogImage,
  1968. Graphic = outputCollection["Graphic"].Value as CogGraphicCollection,
  1969. Record = record,
  1970. Result = Found,
  1971. IsShow = false,
  1972. IsSaveImage = procedure.IsSaveImage,
  1973. SaveImageModel = procedure.SaveImageModel,
  1974. SaveImagePathModel = procedure.SaveImagePathModel,
  1975. SavePath = procedure.SavePath,
  1976. IsCompress = procedure.IsCompress,
  1977. ProceductName = procedure.Name,
  1978. ImageFileName = imgName,
  1979. Is3DModel = is3dmodel,
  1980. });
  1981. _eventAggregator.GetEvent<RenderUpdateNotification>().Publish(new ShowRender()
  1982. {
  1983. Id = procedure.DisplayId,
  1984. DisplayName = procedure.DisplayName,
  1985. // 显示和保存用 YOLO 彩色图
  1986. Image = yoloColorCogImage,
  1987. Graphic = outputCollection["Graphic"].Value as CogGraphicCollection,
  1988. Record = record,
  1989. Result = Found,
  1990. IsShow = true,
  1991. IsSaveImage = procedure.IsSaveImage,
  1992. SaveImageModel = procedure.SaveImageModel,
  1993. SaveImagePathModel = procedure.SaveImagePathModel,
  1994. SavePath = procedure.SavePath,
  1995. IsCompress = procedure.IsCompress,
  1996. ProceductName = procedure.Name,
  1997. ImageFileName = imgName,
  1998. Is3DModel = is3dmodel,
  1999. });
  2000. }
  2001. }
  2002. }
  2003. return true;
  2004. }
  2005. else
  2006. {
  2007. // 3. 运行视觉工具
  2008. LogHelper.WriteLogInfo("开始运行视觉工具");
  2009. procedure.ToolBlock.Run(); //运行ToolBlock
  2010. if (procedure.ToolBlock.RunStatus.Result == CogToolResultConstants.Accept)
  2011. {
  2012. SendTaskMessage(Lang.视觉流程执行耗时.Replace("{0}", procedure.Name).Replace("{1}", $"{procedure.ToolBlock.RunStatus.ProcessingTime:F1}"), MessageLevel.Info);
  2013. outputCollection = procedure.ToolBlock.Outputs; //获取输出终端集合
  2014. DatabaseHelper.AddCameraRecords(_productService.GetCurrentProduct().Name, procedure.Name, outputCollection);
  2015. ICogRecord record = null;
  2016. foreach (CogToolBlockTerminal item in outputCollection)
  2017. {
  2018. if (item.Value is ICogRecord)
  2019. record = item.Value as ICogRecord;
  2020. }
  2021. bool Found = (bool)(outputCollection["Found"].Value);
  2022. //获取图片存储的图片文件名
  2023. string imgName = string.Empty;
  2024. if (procedure.IsSaveImage && !string.IsNullOrEmpty(procedure.ImageFileNameFormat))
  2025. {
  2026. // 创建模板,使用 {变量名:格式} 语法
  2027. var template = new FileNameTemplate(procedure.ImageFileNameFormat);
  2028. // 注册变量
  2029. template.RegisterVariable("ProductSN", () => _productService.CurrentProductCode);
  2030. template.RegisterVariable("CameraName", () => procedure.CameraName);
  2031. template.RegisterVariable("ShotCount", () => 1);
  2032. template.RegisterVariable("Result", () => Found ? "OK" : "NG");
  2033. template.RegisterVariable("DateTime", () => DateTime.Now);
  2034. // 生成文件名
  2035. imgName = template.Generate();
  2036. }
  2037. if (is3dmodel == true)
  2038. {
  2039. if (_configService.GetSystemConfiguration().PickPointNum == 0)
  2040. {
  2041. if (procedure.ToolBlock.Inputs.Contains("InputImage2"))
  2042. {
  2043. _eventAggregator.GetEvent<RenderUpdateNotification>().Publish(new ShowRender()
  2044. {
  2045. Id = procedure.DisplayId,
  2046. DisplayName = procedure.DisplayName,
  2047. //Image = (ICogImage)procedure.ToolBlock.Outputs["OriImage"].Value,
  2048. Image = (ICogImage)procedure.ToolBlock.Inputs["InputImage2"].Value,
  2049. Graphic = outputCollection["Graphic"].Value as CogGraphicCollection,
  2050. Record = record,
  2051. Result = Found,
  2052. IsShow = true,
  2053. IsSaveImage = procedure.IsSaveImage,
  2054. SaveImageModel = procedure.SaveImageModel,
  2055. SaveImagePathModel = procedure.SaveImagePathModel,
  2056. SavePath = procedure.SavePath,
  2057. IsCompress = procedure.IsCompress,
  2058. ProceductName = procedure.Name,
  2059. ImageFileName = imgName + "image2",
  2060. Is3DModel = false,
  2061. });
  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["InputImage"].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,
  2080. Is3DModel = is3dmodel,
  2081. //RangeImage = (CogImage16Range)procedure.ToolBlock.Outputs["RangeImage"].Value,
  2082. //GreyImage = (CogImage16Grey)procedure.ToolBlock.Outputs["GreyImage"].Value
  2083. });
  2084. }
  2085. else
  2086. {
  2087. if (procedure.ToolBlock.Inputs.Contains("InputImage2"))
  2088. {
  2089. _eventAggregator.GetEvent<RenderUpdateNotification>().Publish(new ShowRender()
  2090. {
  2091. Id = procedure.DisplayId,
  2092. DisplayName = procedure.DisplayName,
  2093. //Image = (ICogImage)procedure.ToolBlock.Outputs["OriImage"].Value,
  2094. Image = (ICogImage)procedure.ToolBlock.Inputs["InputImage2"].Value,
  2095. Graphic = outputCollection["Graphic"].Value as CogGraphicCollection,
  2096. Record = record,
  2097. Result = Found,
  2098. IsShow = true,
  2099. IsSaveImage = procedure.IsSaveImage,
  2100. SaveImageModel = procedure.SaveImageModel,
  2101. SaveImagePathModel = procedure.SaveImagePathModel,
  2102. SavePath = procedure.SavePath,
  2103. IsCompress = procedure.IsCompress,
  2104. ProceductName = procedure.Name,
  2105. ImageFileName = imgName + "image2",
  2106. Is3DModel = false,
  2107. });
  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["InputImage"].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,
  2126. Is3DModel = is3dmodel,
  2127. RangeImage = (CogImage16Range)procedure.ToolBlock.Outputs["RangeImage"].Value,
  2128. GreyImage = (CogImage16Grey)procedure.ToolBlock.Outputs["GreyImage"].Value
  2129. });
  2130. }
  2131. }
  2132. else
  2133. {
  2134. if (procedure.ToolBlock.Inputs.Contains("InputImage2"))
  2135. {
  2136. _eventAggregator.GetEvent<RenderUpdateNotification>().Publish(new ShowRender()
  2137. {
  2138. Id = procedure.DisplayId,
  2139. DisplayName = procedure.DisplayName,
  2140. //Image = (ICogImage)procedure.ToolBlock.Outputs["OriImage"].Value,
  2141. Image = (ICogImage)procedure.ToolBlock.Inputs["InputImage2"].Value,
  2142. Graphic = outputCollection["Graphic"].Value as CogGraphicCollection,
  2143. Record = record,
  2144. Result = Found,
  2145. IsShow = true,
  2146. IsSaveImage = procedure.IsSaveImage,
  2147. SaveImageModel = procedure.SaveImageModel,
  2148. SaveImagePathModel = procedure.SaveImagePathModel,
  2149. SavePath = procedure.SavePath,
  2150. IsCompress = procedure.IsCompress,
  2151. ProceductName = procedure.Name,
  2152. ImageFileName = imgName + "image2",
  2153. Is3DModel = false,
  2154. });
  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["InputImage"].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,
  2173. Is3DModel = is3dmodel
  2174. });
  2175. }
  2176. return true;
  2177. }
  2178. else
  2179. {
  2180. SendTaskMessage(Lang.视觉流程执行出错耗时.Replace("{0}", procedure.Name).Replace("{1}", $"{procedure.ToolBlock.RunStatus.ProcessingTime:F1}"), MessageLevel.Error);
  2181. SendTaskMessage(procedure.ToolBlock.RunStatus.Message, MessageLevel.Error);
  2182. outputCollection = null;
  2183. //获取图片存储的图片文件名
  2184. string imgName = string.Empty;
  2185. if (procedure.IsSaveImage && !string.IsNullOrEmpty(procedure.ImageFileNameFormat))
  2186. {
  2187. // 创建模板,使用 {变量名:格式} 语法
  2188. var template = new FileNameTemplate(procedure.ImageFileNameFormat);
  2189. // 注册变量
  2190. template.RegisterVariable("ProductSN", () => _productService.CurrentProductCode);
  2191. template.RegisterVariable("CameraName", () => procedure.CameraName);
  2192. template.RegisterVariable("ShotCount", () => 1);
  2193. template.RegisterVariable("Result", () => "NG");
  2194. template.RegisterVariable("DateTime", () => DateTime.Now);
  2195. // 生成文件名
  2196. imgName = template.Generate();
  2197. }
  2198. if (is3dmodel == true)
  2199. {
  2200. if (procedure.ToolBlock.Inputs.Contains("InputImage2"))
  2201. {
  2202. _eventAggregator.GetEvent<RenderUpdateNotification>().Publish(new ShowRender()
  2203. {
  2204. Id = procedure.DisplayId,
  2205. DisplayName = procedure.DisplayName,
  2206. //Image = (ICogImage)procedure.ToolBlock.Outputs["OriImage"].Value,
  2207. Image = (ICogImage)procedure.ToolBlock.Inputs["InputImage2"].Value,
  2208. Graphic = outputCollection["Graphic"].Value as CogGraphicCollection,
  2209. Result = false,
  2210. IsShow = true,
  2211. IsSaveImage = procedure.IsSaveImage,
  2212. SaveImageModel = procedure.SaveImageModel,
  2213. SaveImagePathModel = procedure.SaveImagePathModel,
  2214. SavePath = procedure.SavePath,
  2215. IsCompress = procedure.IsCompress,
  2216. ProceductName = procedure.Name,
  2217. ImageFileName = imgName + "image2",
  2218. Is3DModel = is3dmodel,
  2219. });
  2220. }
  2221. _eventAggregator.GetEvent<RenderUpdateNotification>().Publish(new ShowRender()
  2222. {
  2223. Id = procedure.DisplayId,
  2224. DisplayName = procedure.DisplayName,
  2225. //Image = (ICogImage)procedure.ToolBlock.Outputs["OriImage"].Value,
  2226. Image = (ICogImage)procedure.ToolBlock.Inputs["InputImage"].Value,
  2227. Graphic = new CogGraphicCollection(),
  2228. Result = false,
  2229. IsShow = true,
  2230. IsSaveImage = procedure.IsSaveImage,
  2231. SaveImageModel = procedure.SaveImageModel,
  2232. SaveImagePathModel = procedure.SaveImagePathModel,
  2233. SavePath = procedure.SavePath,
  2234. ProceductName = procedure.Name,
  2235. ImageFileName = imgName,
  2236. Is3DModel = is3dmodel,
  2237. RangeImage = (CogImage16Range)procedure.ToolBlock.Outputs["RangeImage"].Value,
  2238. GreyImage = (CogImage16Grey)procedure.ToolBlock.Outputs["GreyImage"].Value
  2239. });
  2240. }
  2241. else
  2242. {
  2243. if (procedure.ToolBlock.Inputs.Contains("InputImage2"))
  2244. {
  2245. _eventAggregator.GetEvent<RenderUpdateNotification>().Publish(new ShowRender()
  2246. {
  2247. Id = procedure.DisplayId,
  2248. DisplayName = procedure.DisplayName,
  2249. //Image = (ICogImage)procedure.ToolBlock.Outputs["OriImage"].Value,
  2250. Image = (ICogImage)procedure.ToolBlock.Inputs["InputImage2"].Value,
  2251. Graphic = outputCollection["Graphic"].Value as CogGraphicCollection,
  2252. Result = false,
  2253. IsShow = true,
  2254. IsSaveImage = procedure.IsSaveImage,
  2255. SaveImageModel = procedure.SaveImageModel,
  2256. SaveImagePathModel = procedure.SaveImagePathModel,
  2257. SavePath = procedure.SavePath,
  2258. IsCompress = procedure.IsCompress,
  2259. ProceductName = procedure.Name,
  2260. ImageFileName = imgName + "image2",
  2261. Is3DModel = is3dmodel,
  2262. });
  2263. }
  2264. _eventAggregator.GetEvent<RenderUpdateNotification>().Publish(new ShowRender()
  2265. {
  2266. Id = procedure.DisplayId,
  2267. DisplayName = procedure.DisplayName,
  2268. //Image = (ICogImage)procedure.ToolBlock.Outputs["OriImage"].Value,
  2269. Image = (ICogImage)procedure.ToolBlock.Inputs["InputImage"].Value,
  2270. Graphic = new CogGraphicCollection(),
  2271. Result = false,
  2272. IsShow = true,
  2273. IsSaveImage = procedure.IsSaveImage,
  2274. SaveImageModel = procedure.SaveImageModel,
  2275. SaveImagePathModel = procedure.SaveImagePathModel,
  2276. SavePath = procedure.SavePath,
  2277. ProceductName = procedure.Name,
  2278. ImageFileName = imgName,
  2279. Is3DModel = is3dmodel
  2280. });
  2281. }
  2282. return false;
  2283. }
  2284. }
  2285. }
  2286. catch (Exception ex)
  2287. {
  2288. SendTaskMessage(ex.Message, MessageLevel.Error);
  2289. LogHelper.WriteLogError("执行相机取图并执行视觉工具组时出错!", ex);
  2290. outputCollection = null;
  2291. return false;
  2292. }
  2293. }
  2294. /// <summary>
  2295. /// 采集图像
  2296. /// </summary>
  2297. /// <param name="procedure"></param>
  2298. /// <returns></returns>
  2299. public async Task<(bool IsSucceed, ICogImage[] Image, string Msg)> ExecuteGrabImageAsync(ProcedureModel procedure, bool Is3dPhoto, SystemConfiguration sysConfig)
  2300. {
  2301. try
  2302. {
  2303. //var sysConfig = _configService.GetSystemConfiguration();
  2304. if (sysConfig.PhotosUse == true)
  2305. {
  2306. // 1. 采集图像
  2307. var camera = _cameraService.GetCamera(procedure.CameraId);
  2308. ICogImage image = null;
  2309. ICogImage image2 = null;
  2310. for (int i = 1; i <= procedure.PhotoCount; i++)
  2311. {
  2312. if (i == 1)
  2313. {
  2314. bool isSucceed = false;
  2315. //isSucceed = await _lightManagerService.SetGlobalChannelBrightnessAsync(0, procedure.Photo1Light1);
  2316. //if (!isSucceed)
  2317. //{
  2318. // LogHelper.WriteLogInfo($"设置光源通道1亮度{procedure.Photo1Light1}失败!");
  2319. //}
  2320. //isSucceed = await _lightManagerService.SetGlobalChannelBrightnessAsync(1, procedure.Photo1Light2);
  2321. //if (!isSucceed)
  2322. //{
  2323. // LogHelper.WriteLogInfo($"设置光源通道2亮度{procedure.Photo1Light2}失败!");
  2324. //}
  2325. //isSucceed = await _lightManagerService.SetGlobalChannelBrightnessAsync(2, procedure.Photo1Light3);
  2326. //if (!isSucceed)
  2327. //{
  2328. // LogHelper.WriteLogInfo($"设置光源通道3亮度{procedure.Photo1Light3}失败!");
  2329. //}
  2330. bool succed = camera.SetExposureTime(procedure.ExposureTime);
  2331. if (!succed)
  2332. {
  2333. SendTaskMessage($"相机曝光设置失败!", MessageLevel.Error);
  2334. }
  2335. succed = camera.SetGain(procedure.Gain);
  2336. if (!succed)
  2337. {
  2338. SendTaskMessage($"相机增益设置失败!", MessageLevel.Error);
  2339. }
  2340. image = camera.Grab();
  2341. //isSucceed = await _lightManagerService.TurnOffGlobalChannelAsync(0);
  2342. //if (!isSucceed)
  2343. //{
  2344. // LogHelper.WriteLogInfo($"设置光源通道0关闭失败!");
  2345. //}
  2346. //isSucceed = await _lightManagerService.TurnOffGlobalChannelAsync(1);
  2347. //if (!isSucceed)
  2348. //{
  2349. // LogHelper.WriteLogInfo($"设置光源通道1关闭失败!");
  2350. //}
  2351. //isSucceed = await _lightManagerService.TurnOffGlobalChannelAsync(2);
  2352. //if (!isSucceed)
  2353. //{
  2354. // LogHelper.WriteLogInfo($"设置光源通道2关闭失败!");
  2355. //}
  2356. }
  2357. else if (i == 2)
  2358. {
  2359. bool isSucceed = false;
  2360. //isSucceed = await _lightManagerService.SetGlobalChannelBrightnessAsync(0, procedure.Photo2Light1);
  2361. //if (!isSucceed)
  2362. //{
  2363. // LogHelper.WriteLogInfo($"设置光源通道1亮度{procedure.Photo2Light1}失败!");
  2364. //}
  2365. //isSucceed = await _lightManagerService.SetGlobalChannelBrightnessAsync(1, procedure.Photo2Light2);
  2366. //if (!isSucceed)
  2367. //{
  2368. // LogHelper.WriteLogInfo($"设置光源通道2亮度{procedure.Photo2Light2}失败!");
  2369. //}
  2370. //isSucceed = await _lightManagerService.SetGlobalChannelBrightnessAsync(2, procedure.Photo2Light3);
  2371. //if (!isSucceed)
  2372. //{
  2373. // LogHelper.WriteLogInfo($"设置光源通道3亮度{procedure.Photo2Light3}失败!");
  2374. //}
  2375. SendTaskMessage($"开始设置相机曝光!", MessageLevel.Info);
  2376. bool succed = camera.SetExposureTime(procedure.ExposureTime2);
  2377. if (!succed)
  2378. {
  2379. SendTaskMessage($"相机曝光设置失败!", MessageLevel.Error);
  2380. }
  2381. SendTaskMessage($"开始设置相机增益!", MessageLevel.Info);
  2382. succed = camera.SetGain(procedure.Gain2);
  2383. if (!succed)
  2384. {
  2385. SendTaskMessage($"相机增益设置失败!", MessageLevel.Error);
  2386. }
  2387. image2 = camera.Grab();
  2388. isSucceed = await _lightManagerService.TurnOffGlobalChannelAsync(0);
  2389. if (!isSucceed)
  2390. {
  2391. LogHelper.WriteLogInfo($"设置光源通道0关闭失败!");
  2392. }
  2393. isSucceed = await _lightManagerService.TurnOffGlobalChannelAsync(1);
  2394. if (!isSucceed)
  2395. {
  2396. LogHelper.WriteLogInfo($"设置光源通道1关闭失败!");
  2397. }
  2398. isSucceed = await _lightManagerService.TurnOffGlobalChannelAsync(2);
  2399. if (!isSucceed)
  2400. {
  2401. LogHelper.WriteLogInfo($"设置光源通道2关闭失败!");
  2402. }
  2403. }
  2404. }
  2405. DateTime nowtime = DateTime.Now;
  2406. LogHelper.WriteLogInfo("开始采集图像");
  2407. //var image = camera.Grab();
  2408. if (Is3dPhoto == true)
  2409. {
  2410. image = camera.Grab();
  2411. image2 = camera.Grab2();
  2412. LogHelper.WriteLogInfo($"采集图像完成;用时:{(DateTime.Now - nowtime).Milliseconds}ms");
  2413. if (image == null || image2 == null)
  2414. {
  2415. SendTaskMessage(Lang.图像采集失败, MessageLevel.Error);
  2416. return (false, null, "图像采集失败");
  2417. }
  2418. return (true, new ICogImage[] { image, image2 }, "成功");
  2419. }
  2420. else
  2421. {
  2422. LogHelper.WriteLogInfo($"采集图像完成;用时:{(DateTime.Now - nowtime).Milliseconds}ms");
  2423. if (image == null)
  2424. {
  2425. SendTaskMessage(Lang.图像采集失败, MessageLevel.Error);
  2426. return (false, null, "图像采集失败");
  2427. }
  2428. if (procedure.PhotoCount > 1)
  2429. {
  2430. if (image2 == null)
  2431. {
  2432. SendTaskMessage(Lang.图像采集失败, MessageLevel.Error);
  2433. return (false, null, "图像采集失败");
  2434. }
  2435. return (true, new ICogImage[] { image, image2 }, "成功");
  2436. }
  2437. return (true, new ICogImage[] { image }, "成功");
  2438. }
  2439. }
  2440. else
  2441. {
  2442. // 1. 采集图像
  2443. var camera = _cameraService.GetCamera(procedure.CameraId);
  2444. if (TempExposureTime != procedure.ExposureTime)
  2445. {
  2446. bool succed1 = camera.SetExposureTime(procedure.ExposureTime);
  2447. if (!succed1)
  2448. {
  2449. SendTaskMessage($"相机曝光设置失败!", MessageLevel.Error);
  2450. }
  2451. else
  2452. {
  2453. TempExposureTime = procedure.ExposureTime;
  2454. }
  2455. }
  2456. //else
  2457. //{
  2458. // SendTaskMessage($"相机曝光重复", MessageLevel.Error);
  2459. //}
  2460. if (TempGain != procedure.Gain)
  2461. {
  2462. bool succed2 = camera.SetGain(procedure.Gain);
  2463. if (!succed2)
  2464. {
  2465. SendTaskMessage($"相机增益设置失败!", MessageLevel.Error);
  2466. }
  2467. else
  2468. {
  2469. TempGain = procedure.Gain;
  2470. }
  2471. }
  2472. //else
  2473. //{
  2474. // SendTaskMessage($"相机增益重复", MessageLevel.Error);
  2475. //}
  2476. DateTime nowtime = DateTime.Now;
  2477. LogHelper.WriteLogInfo("开始采集图像");
  2478. //var image = camera.Grab();
  2479. if (Is3dPhoto == true)
  2480. {
  2481. var image = camera.Grab();
  2482. var image2 = camera.Grab2();
  2483. LogHelper.WriteLogInfo($"采集图像完成;用时:{(DateTime.Now - nowtime).Milliseconds}ms");
  2484. if (image == null || image2 == null)
  2485. {
  2486. SendTaskMessage(Lang.图像采集失败, MessageLevel.Error);
  2487. return (false, null, "图像采集失败");
  2488. }
  2489. return (true, new ICogImage[] { image, image2 }, "成功");
  2490. }
  2491. else
  2492. {
  2493. var image = camera.Grab();
  2494. LogHelper.WriteLogInfo($"采集图像完成;用时:{(DateTime.Now - nowtime).Milliseconds}ms");
  2495. if (image == null)
  2496. {
  2497. SendTaskMessage(Lang.图像采集失败, MessageLevel.Error);
  2498. return (false, null, "图像采集失败");
  2499. }
  2500. return (true, new ICogImage[] { image }, "成功");
  2501. }
  2502. }
  2503. }
  2504. catch (Exception ex)
  2505. {
  2506. LogHelper.WriteLogError("采集图像失败!", ex);
  2507. return (false, null, "图像采集失败");
  2508. }
  2509. }
  2510. /// <summary>
  2511. /// 执行相机拍照获取单个点位结果
  2512. /// </summary>
  2513. /// <param name="procedure"></param>
  2514. /// <param name="InputTerminal"></param>
  2515. /// <param name="robotCoord"></param>
  2516. /// <param name="cancellationToken"></param>
  2517. /// <returns></returns>
  2518. 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)
  2519. {
  2520. DateTime nowtime = DateTime.Now;
  2521. try
  2522. {
  2523. //拍照失败时,需要多次拍照
  2524. //for (int i = 0; i < procedure.FeederFailLimit; i++)
  2525. for (int i = 0; i < 1; i++)
  2526. {
  2527. SendTaskMessage(Lang.开始执行视觉流程.Replace("{0}", $"{i + 1}").Replace("{1}", procedure.Name), MessageLevel.Info);
  2528. // 1. 执行相机拍照并运行视觉工具
  2529. bool visionSucceed = ExecutePhoto(procedure, imges, InputTerminal, out CogToolBlockTerminalCollection outputCollection, is3dmodel, confThreshold, iouThreshold);
  2530. if (!visionSucceed)
  2531. {
  2532. SendTaskMessage(Lang.视觉任务执行失败, MessageLevel.Error);
  2533. continue;
  2534. }
  2535. if (!outputCollection.Contains("Found"))
  2536. {
  2537. SendTaskMessage(Lang.未找到视觉输出结果, MessageLevel.Error);
  2538. return (false, null, 0);
  2539. }
  2540. // 2. 获取视觉输出结果
  2541. //bool Found = (bool)(outputCollection["Found"].Value);
  2542. //if (!Found)
  2543. //{
  2544. // SendTaskMessage(Lang.拍照NG, MessageLevel.Debug);
  2545. // continue;
  2546. //}
  2547. //SendTaskMessage(Lang.拍照OK, MessageLevel.Debug);
  2548. int Count = (int)(outputCollection["Count"].Value);
  2549. string[] PhotoRes = new string[100];
  2550. for (int k = 1; k <= Count; k++)
  2551. {
  2552. PhotoRes[k] = (string)(outputCollection[$"dis{k}"].Value);
  2553. //PhotoRes[k] = "222";
  2554. }
  2555. // 3. 获取视觉输出结果
  2556. LogHelper.WriteLogInfo("开始获取视觉输出结果");
  2557. return (true, PhotoRes, Count);
  2558. }
  2559. SendTaskMessage(Lang.多次拍照失败, MessageLevel.Alarm);
  2560. return (false, null, 0);
  2561. }
  2562. catch (Exception ex)
  2563. {
  2564. LogHelper.WriteLogError("执行相机取图并获取单点位时出错!", ex);
  2565. return (false, null, 0);
  2566. }
  2567. finally
  2568. {
  2569. var sysConfig = _configService.GetSystemConfiguration();
  2570. if (sysConfig.TurnOffAllLightUse == false)
  2571. {
  2572. await TurnOffLightAfterPhoto(procedure);
  2573. }
  2574. }
  2575. }
  2576. /// <summary>
  2577. /// 执行相机拍照获取单个点位结果
  2578. /// </summary>
  2579. /// <param name="procedure"></param>
  2580. /// <param name="InputTerminal"></param>
  2581. /// <param name="robotCoord"></param>
  2582. /// <param name="cancellationToken"></param>
  2583. /// <returns></returns>
  2584. public async Task<(bool IsSucceed, string X, double Y, double U)> ExecutePhotoGetSinglePoint2(ProcedureModel procedure, Dictionary<string, string> InputTerminal, double[] robotCoord, CancellationToken cancellationToken)
  2585. {
  2586. DateTime nowtime = DateTime.Now;
  2587. var sysConfig = _configService.GetSystemConfiguration();
  2588. if (sysConfig.TurnOnAllLightUse == false)
  2589. {
  2590. await SetLightBeforePhoto(procedure);
  2591. }
  2592. try
  2593. {
  2594. //拍照失败时,需要多次拍照
  2595. for (int i = 0; i < procedure.FeederFailLimit; i++)
  2596. {
  2597. SendTaskMessage(Lang.开始执行视觉流程.Replace("{0}", $"{i + 1}").Replace("{1}", procedure.Name), MessageLevel.Info);
  2598. // 1. 执行相机拍照并运行视觉工具
  2599. bool visionSucceed = ExecutePhoto2(procedure, InputTerminal, out CogToolBlockTerminalCollection outputCollection);
  2600. if (!visionSucceed)
  2601. {
  2602. SendTaskMessage(Lang.视觉任务执行失败, MessageLevel.Error);
  2603. continue;
  2604. }
  2605. if (!outputCollection.Contains("Found"))
  2606. {
  2607. SendTaskMessage(Lang.未找到视觉输出结果, MessageLevel.Error);
  2608. return (false, null, 0, 0);
  2609. }
  2610. // 2. 获取视觉输出结果
  2611. bool Found = (bool)(outputCollection["Found"].Value);
  2612. if (!Found)
  2613. {
  2614. SendTaskMessage(Lang.拍照NG, MessageLevel.Debug);
  2615. continue;
  2616. }
  2617. string SnCode = (string)(outputCollection["SnCode"].Value);
  2618. SendTaskMessage(Lang.拍照OK, MessageLevel.Debug);
  2619. // 3. 获取视觉输出结果
  2620. LogHelper.WriteLogInfo("开始获取视觉输出结果");
  2621. /*
  2622. //获取相机校准
  2623. var calib = _calibrationService.GetCalibration(procedure.CalibrationId);
  2624. string points = (string)(outputCollection["Point"].Value);
  2625. string[] strpoints = points.Split(';');
  2626. //先将pos按照逗号进行分隔,拿到数组
  2627. var posParts = strpoints[0].Split(',');
  2628. double _pixel_x = double.Parse(posParts[0]);
  2629. double _pixel_y = double.Parse(posParts[1]);
  2630. double _pixel_u = double.Parse(posParts[2]);
  2631. //转换点位-像素转换成机器人绝对坐标
  2632. var calibResult = _calibrationService.ConvertPixelToPosition((_pixel_x, _pixel_y, _pixel_u), robotCoord, calib, RobotBrand.XYZ_Platform);
  2633. if (!calibResult.IsSucceed)
  2634. {
  2635. return (false, 0, 0, 0);
  2636. }
  2637. return (true, calibResult.X, calibResult.Y, calibResult.U);
  2638. */
  2639. return (true, SnCode, 0, 0);
  2640. }
  2641. SendTaskMessage(Lang.多次拍照失败, MessageLevel.Alarm);
  2642. return (false, null, 0, 0);
  2643. }
  2644. catch (Exception ex)
  2645. {
  2646. LogHelper.WriteLogError("执行相机取图并获取单点位时出错!", ex);
  2647. return (false, null, 0, 0);
  2648. }
  2649. finally
  2650. {
  2651. if (sysConfig.TurnOffAllLightUse == false)
  2652. {
  2653. await TurnOffLightAfterPhoto(procedure);
  2654. }
  2655. }
  2656. }
  2657. /// <summary>
  2658. /// 执行相机拍照并运行 ToolBlock,返回是否成功并通过 out 参数返回 Outputs、图像和图形集合。
  2659. /// </summary>
  2660. /// <param name="procedure"></param>
  2661. /// <param name="InputTerminal"></param>
  2662. /// <param name="outputCollection"></param>
  2663. /// <param name="outImage"></param>
  2664. /// <param name="outGraphicCollection"></param>
  2665. /// <returns></returns>
  2666. public bool ExecutePhotoEx(ProcedureModel procedure, Dictionary<string, string> InputTerminal, out CogToolBlockTerminalCollection outputCollection, out ICogImage outImage, out CogGraphicCollection outGraphicCollection)
  2667. {
  2668. outImage = null;
  2669. outGraphicCollection = null;
  2670. try
  2671. {
  2672. // 1. 采集图像
  2673. var camera = _cameraService.GetCamera(procedure.CameraId);
  2674. bool succed = camera.SetExposureTime(procedure.ExposureTime);
  2675. if (!succed)
  2676. {
  2677. SendTaskMessage($"相机曝光设置失败!", MessageLevel.Error);
  2678. }
  2679. succed = camera.SetGain(procedure.Gain);
  2680. if (!succed)
  2681. {
  2682. SendTaskMessage($"相机增益设置失败!", MessageLevel.Error);
  2683. }
  2684. DateTime nowtime = DateTime.Now;
  2685. LogHelper.WriteLogInfo("开始采集图像");
  2686. var image = camera.Grab();
  2687. if (image == null)
  2688. {
  2689. SendTaskMessage(Lang.图像采集失败, MessageLevel.Error);
  2690. outputCollection = null;
  2691. return false;
  2692. }
  2693. outImage = image;
  2694. procedure.ToolBlock.Inputs["InputImage"].Value = image;
  2695. LogHelper.WriteLogInfo($"采集图像完成;用时:{(DateTime.Now - nowtime).Milliseconds}ms");
  2696. // 2. 为ToolBlock传入其他输入终端
  2697. if (InputTerminal != null)
  2698. {
  2699. LogHelper.WriteLogInfo($"为ToolBlock传入输入终端");
  2700. foreach (var item in InputTerminal)
  2701. {
  2702. if (procedure.ToolBlock.Inputs.Contains(item.Key))
  2703. {
  2704. LogHelper.WriteLogInfo($"传入[{item.Key}]={item.Value}");
  2705. procedure.ToolBlock.Inputs[item.Key].Value = item.Value;
  2706. }
  2707. else
  2708. {
  2709. LogHelper.WriteLogInfo($"创建并传入[{item.Key}]={item.Value}");
  2710. procedure.ToolBlock.Inputs.Add(new CogToolBlockTerminal(item.Key, item.Value));
  2711. }
  2712. }
  2713. }
  2714. // 3. 运行视觉工具
  2715. LogHelper.WriteLogInfo("开始运行视觉工具");
  2716. procedure.ToolBlock.Run(); //运行ToolBlock
  2717. if (procedure.ToolBlock.RunStatus.Result == CogToolResultConstants.Accept)
  2718. {
  2719. SendTaskMessage(Lang.视觉流程执行耗时.Replace("{0}", procedure.Name).Replace("{1}", $"{procedure.ToolBlock.RunStatus.ProcessingTime:F1}"), MessageLevel.Info);
  2720. outputCollection = procedure.ToolBlock.Outputs; //获取输出终端集合
  2721. DatabaseHelper.AddCameraRecords(_productService.GetCurrentProduct().Name, procedure.Name, outputCollection);
  2722. ICogRecord record = null;
  2723. foreach (CogToolBlockTerminal item in outputCollection)
  2724. {
  2725. if (item.Value is ICogRecord)
  2726. record = item.Value as ICogRecord;
  2727. }
  2728. outGraphicCollection = outputCollection["Graphic"].Value as CogGraphicCollection;
  2729. return true;
  2730. }
  2731. else
  2732. {
  2733. SendTaskMessage(Lang.视觉流程执行出错耗时.Replace("{0}", procedure.Name).Replace("{1}", $"{procedure.ToolBlock.RunStatus.ProcessingTime:F1}"), MessageLevel.Error);
  2734. SendTaskMessage(procedure.ToolBlock.RunStatus.Message, MessageLevel.Error);
  2735. outputCollection = null;
  2736. outGraphicCollection = outputCollection["Graphic"].Value as CogGraphicCollection;
  2737. return false;
  2738. }
  2739. }
  2740. catch (Exception ex)
  2741. {
  2742. SendTaskMessage(ex.Message, MessageLevel.Error);
  2743. LogHelper.WriteLogError("执行相机取图并执行视觉工具组时出错!", ex);
  2744. outputCollection = null;
  2745. return false;
  2746. }
  2747. }
  2748. /// <summary>
  2749. /// 执行相机拍照获取单个点位结果
  2750. /// </summary>
  2751. /// <param name="procedure"></param>
  2752. /// <param name="InputTerminal"></param>
  2753. /// <param name="robotCoord"></param>
  2754. /// <param name="cancellationToken"></param>
  2755. /// <returns></returns>
  2756. public async Task<(bool IsSucceed, double X, double Y, double U)> ExecutePhotoGetSinglePoint(ProcedureModel procedure, Dictionary<string, string> InputTerminal, double[] robotCoord, CancellationToken cancellationToken)
  2757. {
  2758. DateTime nowtime = DateTime.Now;
  2759. await SetLightBeforePhoto(procedure);
  2760. try
  2761. {
  2762. //拍照失败时,需要多次拍照
  2763. //for (int i = 0; i < procedure.FeederFailLimit; i++)
  2764. for (int i = 0; i < 1; i++)
  2765. {
  2766. SendTaskMessage(Lang.开始执行视觉流程.Replace("{0}", $"{i + 1}").Replace("{1}", procedure.Name), MessageLevel.Info);
  2767. //1.执行相机拍照并运行视觉工具
  2768. bool visionSucceed = ExecutePhoto(procedure, InputTerminal, out CogToolBlockTerminalCollection outputCollection);
  2769. if (!visionSucceed)
  2770. {
  2771. SendTaskMessage(Lang.视觉任务执行失败, MessageLevel.Error);
  2772. continue;
  2773. }
  2774. if (!outputCollection.Contains("Found"))
  2775. {
  2776. SendTaskMessage(Lang.未找到视觉输出结果, MessageLevel.Error);
  2777. return (false, 0, 0, 0);
  2778. }
  2779. // 2. 获取视觉输出结果
  2780. bool Found = (bool)(outputCollection["Found"].Value);
  2781. if (!Found)
  2782. {
  2783. SendTaskMessage(Lang.拍照NG, MessageLevel.Debug);
  2784. continue;
  2785. }
  2786. SendTaskMessage(Lang.拍照OK, MessageLevel.Debug);
  2787. //// 3. 获取视觉输出结果
  2788. //LogHelper.WriteLogInfo("开始获取视觉输出结果");
  2789. ////获取相机校准
  2790. //var calib = _calibrationService.GetCalibration(procedure.CalibrationId);
  2791. //string points = (string)(outputCollection["Point"].Value);
  2792. //string[] strpoints = points.Split(';');
  2793. ////先将pos按照逗号进行分隔,拿到数组
  2794. //var posParts = strpoints[0].Split(',');
  2795. //double _pixel_x = double.Parse(posParts[0]);
  2796. //double _pixel_y = double.Parse(posParts[1]);
  2797. //double _pixel_u = double.Parse(posParts[2]);
  2798. ////转换点位-像素转换成机器人绝对坐标
  2799. //var calibResult = _calibrationService.ConvertPixelToPosition((_pixel_x, _pixel_y, _pixel_u), robotCoord, calib, RobotBrand.XYZ_Platform);
  2800. //if (!calibResult.IsSucceed)
  2801. //{
  2802. // return (false, 0, 0, 0);
  2803. //}
  2804. return (true, 0, 0, 0);
  2805. }
  2806. SendTaskMessage(Lang.多次拍照失败, MessageLevel.Alarm);
  2807. return (false, 0, 0, 0);
  2808. }
  2809. catch (Exception ex)
  2810. {
  2811. LogHelper.WriteLogError("执行相机取图并获取单点位时出错!", ex);
  2812. return (false, 0, 0, 0);
  2813. }
  2814. finally
  2815. {
  2816. await TurnOffLightAfterPhoto(procedure);
  2817. }
  2818. }
  2819. /// <summary>
  2820. /// 执行相机拍照获取单个点位结果
  2821. /// </summary>
  2822. /// <param name="procedure"></param>
  2823. /// <param name="InputTerminal"></param>
  2824. /// <param name="robotCoord"></param>
  2825. /// <param name="cancellationToken"></param>
  2826. /// <returns></returns>
  2827. public async Task<(bool IsSucceed, string[] Items, double Count)> ExecutePhotoGetSinglePoint1(ProcedureModel procedure, Dictionary<string, string> InputTerminal, double[] robotCoord, CancellationToken cancellationToken)
  2828. {
  2829. DateTime nowtime = DateTime.Now;
  2830. var sysConfig = _configService.GetSystemConfiguration();
  2831. if (sysConfig.TurnOnAllLightUse == false)
  2832. {
  2833. await SetLightBeforePhoto(procedure);
  2834. }
  2835. try
  2836. {
  2837. //拍照失败时,需要多次拍照
  2838. //for (int i = 0; i < procedure.FeederFailLimit; i++)
  2839. for (int i = 0; i < 1; i++)
  2840. {
  2841. SendTaskMessage(Lang.开始执行视觉流程.Replace("{0}", $"{i + 1}").Replace("{1}", procedure.Name), MessageLevel.Info);
  2842. // 1. 执行相机拍照并运行视觉工具
  2843. bool visionSucceed = ExecutePhoto(procedure, InputTerminal, out CogToolBlockTerminalCollection outputCollection);
  2844. if (!visionSucceed)
  2845. {
  2846. SendTaskMessage(Lang.视觉任务执行失败, MessageLevel.Error);
  2847. continue;
  2848. }
  2849. //if (!outputCollection.Contains("Found"))
  2850. //{
  2851. // SendTaskMessage(Lang.未找到视觉输出结果, MessageLevel.Error);
  2852. // return (false, null, 0);
  2853. //}
  2854. // 2. 获取视觉输出结果
  2855. //bool Found = (bool)(outputCollection["Found"].Value);
  2856. //if (!Found)
  2857. //{
  2858. // SendTaskMessage(Lang.拍照NG, MessageLevel.Debug);
  2859. // continue;
  2860. //}
  2861. SendTaskMessage(Lang.拍照OK, MessageLevel.Debug);
  2862. int Count = (int)(outputCollection["Count"].Value);
  2863. string[] PhotoRes = new string[100];
  2864. for (int k = 1; k <= Count; k++)
  2865. {
  2866. PhotoRes[k] = (string)(outputCollection[$"dis{k}"].Value);
  2867. //PhotoRes[k] = "222";
  2868. }
  2869. // 3. 获取视觉输出结果
  2870. LogHelper.WriteLogInfo("开始获取视觉输出结果");
  2871. /*
  2872. //获取相机校准
  2873. var calib = _calibrationService.GetCalibration(procedure.CalibrationId);
  2874. string points = (string)(outputCollection["Point"].Value);
  2875. string[] strpoints = points.Split(';');
  2876. //先将pos按照逗号进行分隔,拿到数组
  2877. var posParts = strpoints[0].Split(',');
  2878. double _pixel_x = double.Parse(posParts[0]);
  2879. double _pixel_y = double.Parse(posParts[1]);
  2880. double _pixel_u = double.Parse(posParts[2]);
  2881. //转换点位-像素转换成机器人绝对坐标
  2882. var calibResult = _calibrationService.ConvertPixelToPosition((_pixel_x, _pixel_y, _pixel_u), robotCoord, calib, RobotBrand.XYZ_Platform);
  2883. if (!calibResult.IsSucceed)
  2884. {
  2885. return (false, 0, 0, 0);
  2886. }
  2887. return (true, calibResult.X, calibResult.Y, calibResult.U);
  2888. */
  2889. return (true, PhotoRes, Count);
  2890. }
  2891. SendTaskMessage(Lang.多次拍照失败, MessageLevel.Alarm);
  2892. return (false, null, 0);
  2893. }
  2894. catch (Exception ex)
  2895. {
  2896. LogHelper.WriteLogError("执行相机取图并获取单点位时出错!", ex);
  2897. return (false, null, 0);
  2898. }
  2899. finally
  2900. {
  2901. //await TurnOffLightAfterPhoto(procedure);
  2902. }
  2903. }
  2904. /// <summary>
  2905. /// 执行相机拍照获取单个点位结果,并且返回图像和图形
  2906. /// </summary>
  2907. /// <param name="procedure"></param>
  2908. /// <param name="InputTerminal"></param>
  2909. /// <param name="robotCoord"></param>
  2910. /// <param name="cancellationToken"></param>
  2911. /// <returns></returns>
  2912. 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)
  2913. {
  2914. DateTime nowtime = DateTime.Now;
  2915. await SetLightBeforePhoto(procedure);
  2916. ICogImage outImage = null;
  2917. CogGraphicCollection outGraphicCollection = null;
  2918. try
  2919. {
  2920. //拍照失败时,需要多次拍照
  2921. for (int i = 0; i < procedure.FeederFailLimit; i++)
  2922. {
  2923. SendTaskMessage(Lang.开始执行视觉流程.Replace("{0}", $"{i + 1}").Replace("{1}", procedure.Name), MessageLevel.Info);
  2924. // 1. 执行相机拍照并运行视觉工具
  2925. bool visionSucceed = ExecutePhotoEx(procedure, InputTerminal, out CogToolBlockTerminalCollection outputCollection, out outImage, out outGraphicCollection);
  2926. if (!visionSucceed)
  2927. {
  2928. SendTaskMessage(Lang.视觉任务执行失败, MessageLevel.Error);
  2929. continue;
  2930. }
  2931. if (!outputCollection.Contains("Found"))
  2932. {
  2933. SendTaskMessage(Lang.未找到视觉输出结果, MessageLevel.Error);
  2934. return (false, 0, 0, 0, outImage, outGraphicCollection);
  2935. }
  2936. // 2. 获取视觉输出结果
  2937. bool Found = (bool)(outputCollection["Found"].Value);
  2938. if (!Found)
  2939. {
  2940. SendTaskMessage(Lang.拍照NG, MessageLevel.Debug);
  2941. continue;
  2942. }
  2943. SendTaskMessage(Lang.拍照OK, MessageLevel.Debug);
  2944. // 3. 获取视觉输出结果
  2945. LogHelper.WriteLogInfo("开始获取视觉输出结果");
  2946. //获取相机校准
  2947. var calib = _calibrationService.GetCalibration(procedure.CalibrationId);
  2948. string points = (string)(outputCollection["Point"].Value);
  2949. string[] strpoints = points.Split(';');
  2950. //先将pos按照逗号进行分隔,拿到数组
  2951. var posParts = strpoints[0].Split(',');
  2952. double _pixel_x = double.Parse(posParts[0]);
  2953. double _pixel_y = double.Parse(posParts[1]);
  2954. double _pixel_u = double.Parse(posParts[2]);
  2955. //转换点位-像素转换成机器人绝对坐标
  2956. var calibResult = _calibrationService.ConvertPixelToPosition((_pixel_x, _pixel_y, _pixel_u), robotCoord, calib, RobotBrand.XYZ_Platform);
  2957. if (!calibResult.IsSucceed)
  2958. {
  2959. return (false, 0, 0, 0, outImage, outGraphicCollection);
  2960. }
  2961. return (true, calibResult.X, calibResult.Y, calibResult.U, outImage, outGraphicCollection);
  2962. }
  2963. SendTaskMessage(Lang.多次拍照失败, MessageLevel.Alarm);
  2964. return (false, 0, 0, 0, outImage, outGraphicCollection);
  2965. }
  2966. catch (Exception ex)
  2967. {
  2968. LogHelper.WriteLogError("执行相机取图并获取单点位时出错!", ex);
  2969. return (false, 0, 0, 0, outImage, outGraphicCollection);
  2970. }
  2971. finally
  2972. {
  2973. await TurnOffLightAfterPhoto(procedure);
  2974. }
  2975. }
  2976. /// <summary>
  2977. /// 从 ToolBlock 的输出集合中根据 Procedure 配置提取需要发送的输出项并做必要的坐标转换。
  2978. /// 返回元组:是否成功、错误信息(失败时)和名称->(是否点位, 值) 的字典。
  2979. /// </summary>
  2980. public (bool IsSucceed, string ErrMsg, Dictionary<string, (bool IsPoint, object Value)> Output) GetVisionOutput(ProcedureModel procedure, CogToolBlockTerminalCollection outputCollection, double[] robotPos)
  2981. {
  2982. RobotBrand robotBrand = RobotBrand.Default;
  2983. var robot = _configService.GetRobot(procedure.RobotId);
  2984. if (robot != null)
  2985. {
  2986. robotBrand = robot.RobotBrand;
  2987. }
  2988. List<string> SendResults = new List<string>();
  2989. Dictionary<string, (bool IsPoint, object Value)> ResultCollection = new Dictionary<string, (bool IsPoint, object Value)>();
  2990. foreach (var output in procedure.ProcedureOutputs)
  2991. {
  2992. //根据输出类型进行区分输出
  2993. if (output.ValueType == typeof(string))
  2994. {
  2995. //需要点位转换时,进行点位提取
  2996. if (output.IsPointTran)
  2997. {
  2998. if (outputCollection[output.Name].Value == null || string.IsNullOrEmpty(outputCollection[output.Name].Value.ToString()))
  2999. {
  3000. //如果需要输出的项的值为空,即点位数据为空,则输出点位的个数为0
  3001. ResultCollection.Add(output.Name, (true, null));
  3002. continue;
  3003. }
  3004. string[] strpoints = outputCollection[output.Name].Value.ToString().Split(';');
  3005. //存储当前输出点位集合
  3006. List<string[]> currentPointsForFeeder = new List<string[]>();
  3007. //获取相机校准
  3008. var calib = _calibrationService.GetCalibration(procedure.CalibrationId);
  3009. if (calib == null)
  3010. {
  3011. SendTaskMessage(Lang.没有相机校准信息, MessageLevel.Alarm);
  3012. return (false, "NotCalibrations", null);
  3013. }
  3014. // 判断相机安装方式,如果是J4移动相机或者XYZ平台时,则需要判断robotPos不能为null
  3015. if ((calib.CameraMount == CameraMount.MobileJ4 || calib.CameraMount == CameraMount.MobileDown_XYPlatform) && robotPos == null)
  3016. {
  3017. SendTaskMessage(Lang.机器人当前位置不能为空, MessageLevel.Alarm);
  3018. return (false, "RobotPositionNull", null);
  3019. }
  3020. List<string> SendDtat = new List<string>();
  3021. List<string> points = new List<string>();
  3022. //遍历所有的输出点位
  3023. foreach (var pos in strpoints)
  3024. {
  3025. //先将pos按照逗号进行分隔,拿到数组,判断是否至少包含3个元素,并且前三个元素可以转换为double,确保是有效的点位数据
  3026. if (string.IsNullOrEmpty(pos))
  3027. {
  3028. continue;
  3029. }
  3030. //先将pos按照逗号进行分隔,拿到数组
  3031. var posParts = pos.Split(',');
  3032. if (posParts.Length < 3 ||
  3033. !double.TryParse(posParts[0], out double _pixel_x) ||
  3034. !double.TryParse(posParts[1], out double _pixel_y) ||
  3035. !double.TryParse(posParts[2], out double _pixel_u))
  3036. {
  3037. SendTaskMessage(string.Format(Lang.点位数据格式错误, pos), MessageLevel.Alarm);
  3038. return (false, "PointDataFormatError", null);
  3039. }
  3040. //转换点位-像素转换成机器人绝对坐标
  3041. var calibResult = _calibrationService.ConvertPixelToPosition((_pixel_x, _pixel_y, _pixel_u), robotPos, calib, robotBrand);
  3042. if (!calibResult.IsSucceed)
  3043. {
  3044. return (false, "CalibrationFailed", null);
  3045. }
  3046. //截取posParts数组从索引3开始到结尾的所有元素,得到新新的数组extraInfoArray
  3047. string[] extraInfoArray = posParts.Skip(3).ToArray();
  3048. //将rpos转换为字符串数组,保留3位小数
  3049. string[] strings = new string[] { $"{calibResult.X:F3}", $"{calibResult.Y:F3}", $"{calibResult.U:F3}" };
  3050. List<string> rposString = new List<string>(strings);
  3051. if (extraInfoArray.Length > 0)
  3052. {
  3053. rposString.AddRange(extraInfoArray);
  3054. }
  3055. currentPointsForFeeder.Add(rposString.ToArray());
  3056. }
  3057. ResultCollection[output.Name] = (true, currentPointsForFeeder);
  3058. }
  3059. //直接输出字符串
  3060. else
  3061. {
  3062. if (outputCollection[output.Name].Value == null || string.IsNullOrEmpty(outputCollection[output.Name].Value.ToString()))
  3063. {
  3064. ResultCollection.Add(output.Name, (false, null));
  3065. continue;
  3066. }
  3067. ResultCollection[output.Name] = (false, outputCollection[output.Name].Value.ToString());
  3068. }
  3069. }
  3070. else
  3071. {
  3072. if (outputCollection[output.Name].Value == null)
  3073. {
  3074. ResultCollection.Add(output.Name, (false, null));
  3075. }
  3076. else
  3077. {
  3078. ResultCollection[output.Name] = (false, outputCollection[output.Name].Value.ToString());
  3079. }
  3080. }
  3081. }
  3082. return (true, string.Empty, ResultCollection);
  3083. }
  3084. /// <summary>
  3085. /// 拍照前针对 Feeder 的准备动作:设置灯、必要时供料或振动等。
  3086. /// </summary>
  3087. public async Task ExecuteFeederForPhotoBefore(IVoiceCoilMotorFeeder Feeder, ProcedureModel procedure, bool doVibrateFirst, bool doCaptureFirst, CancellationToken cancellationToken)
  3088. {
  3089. // 1. 设置Feeder光源亮度、打开光源
  3090. if (Feeder.FeederBrand == FeederBrand.AFAG)
  3091. {
  3092. await Feeder.SetLightValueAsync((ushort)procedure.LightValue);
  3093. }
  3094. else
  3095. {
  3096. //Feeder光源亮度设置
  3097. if (procedure.LightValue > 3)
  3098. {
  3099. var light = await Feeder.GetLightBrightnessAsync();
  3100. if (procedure.LightValue != light)
  3101. {
  3102. await Feeder.SetLightValueAsync((ushort)procedure.LightValue);
  3103. }
  3104. //获取光源的超时时间
  3105. int lightTimeout = await Feeder.GetLightTimeoutAsync();
  3106. if (lightTimeout < 10000)
  3107. {
  3108. await Feeder.SetLightTimeOutAsync(10000);
  3109. }
  3110. //打开光源
  3111. await Feeder.OpenLightAsync();
  3112. }
  3113. }
  3114. if (doCaptureFirst)//如果不振动,等待光源稳定时间
  3115. {
  3116. if (procedure.WaitPhoto > 0) await Task.Delay(procedure.WaitPhoto);
  3117. return;
  3118. }
  3119. //先振后拍时
  3120. if (procedure.VibrationModel == VibrationModel.VibrationPhoto || doVibrateFirst)
  3121. {
  3122. if (procedure.FeederWorks != null && procedure.FeederWorks.FeederWorkList != null)
  3123. {
  3124. bool flog = false;
  3125. //如果上次的Blob面积小于设定的最小值,则触发供料
  3126. if (procedure.LastBlobArea <= procedure.MinArea)
  3127. {
  3128. flog = true;
  3129. SendTaskMessage(Lang.执行料仓供料, MessageLevel.Info);
  3130. await ExecuteFeederStockWorks(Feeder, procedure.FeederStockWorks, cancellationToken);
  3131. if (procedure.WaitFeederStop > 0) await Task.Delay(procedure.WaitFeederStop);
  3132. SendTaskMessage(Lang.料仓供料结束, MessageLevel.Info);
  3133. }
  3134. if (!flog)
  3135. {
  3136. //执行配置的Feeder振动任务
  3137. await ExecuteFeederWorks(Feeder, procedure.FeederWorks, cancellationToken, false);
  3138. if (procedure.WaitFeederStop > 0) await Task.Delay(procedure.WaitFeederStop);
  3139. }
  3140. }
  3141. }
  3142. else
  3143. {
  3144. if (procedure.LightValue > 3)
  3145. {
  3146. if (procedure.WaitPhoto > 0) await Task.Delay(procedure.WaitPhoto);
  3147. }
  3148. //如果上次的Blob面积小于设定的最小值,则触发供料
  3149. if (procedure.LastBlobArea <= procedure.MinArea)
  3150. {
  3151. SendTaskMessage(Lang.执行料仓供料, MessageLevel.Info);
  3152. await ExecuteFeederStockWorks(Feeder, procedure.FeederStockWorks, cancellationToken);
  3153. if (procedure.WaitFeederStop > 0) await Task.Delay(procedure.WaitFeederStop);
  3154. SendTaskMessage(Lang.料仓供料结束, MessageLevel.Info);
  3155. }
  3156. }
  3157. }
  3158. /// <summary>
  3159. /// 拍照后在 NG 情况下的 Feeder 后处理,例如供料或振动。
  3160. /// </summary>
  3161. public async Task ExecuteFeederForPhotoLater(IVoiceCoilMotorFeeder Feeder, ProcedureModel procedure, CancellationToken cancellationToken)
  3162. {
  3163. //根据斑点面积决定是否料仓供料
  3164. if (procedure.LastBlobArea <= procedure.MinArea)
  3165. {
  3166. SendTaskMessage(Lang.执行料仓供料, MessageLevel.Info);
  3167. await ExecuteFeederStockWorks(Feeder, procedure.FeederStockWorks, cancellationToken);
  3168. if (cancellationToken != null && cancellationToken.IsCancellationRequested) return;
  3169. if (procedure.WaitFeederStop > 0) await Task.Delay(procedure.WaitFeederStop, cancellationToken);
  3170. SendTaskMessage(Lang.料仓供料结束, MessageLevel.Info);
  3171. }
  3172. else
  3173. {
  3174. if (procedure.FeederWorks != null && procedure.FeederWorks.FeederWorkList != null)
  3175. {
  3176. SendTaskMessage(Lang.执行Feeder振动, MessageLevel.Info);
  3177. //执行配置的Feeder振动任务
  3178. await ExecuteFeederWorks(Feeder, procedure.FeederWorks, cancellationToken);
  3179. if (cancellationToken != null && cancellationToken.IsCancellationRequested) return;
  3180. if (procedure.WaitFeederStop > 0) await Task.Delay(procedure.WaitFeederStop, cancellationToken);
  3181. SendTaskMessage(Lang.Feeder振动结束, MessageLevel.Info);
  3182. }
  3183. }
  3184. }
  3185. /// <summary>
  3186. /// 并行执行料仓供料和振动任务。
  3187. /// </summary>
  3188. public async Task ExecuteFeederStockWorks(IVoiceCoilMotorFeeder feeder, FeederStockWorks works, CancellationToken cancellationToken, bool isUpdateParame = true)
  3189. {
  3190. //同时执行料仓供料和Feeder振动任务
  3191. var stockTask = ExecuteFeederStockWorksOnly(feeder, works.FeederStockWorkList.ToArray(), cancellationToken);
  3192. var vibrationTask = ExecuteFeederWorkOnly(feeder, works.FeederWorkList.ToArray(), cancellationToken);
  3193. await Task.WhenAll(stockTask, vibrationTask);
  3194. }
  3195. /// <summary>
  3196. /// 执行料仓振动任务序列(仅料仓相关动作)。
  3197. /// </summary>
  3198. public async Task ExecuteFeederStockWorksOnly(IVoiceCoilMotorFeeder feeder, FeederStockWork[] works, CancellationToken cancellationToken)
  3199. {
  3200. //执行配置的料仓振动任务
  3201. if (feeder.FeederBrand == FeederBrand.AFAG)
  3202. {
  3203. foreach (var stockwork in works)
  3204. {
  3205. if (stockwork.RegisterIndex == 0)
  3206. {
  3207. if (stockwork.Duration > 0) await Task.Delay(stockwork.Duration, cancellationToken);
  3208. }
  3209. else if (stockwork.RegisterIndex == 1)
  3210. {
  3211. // 保留原注释的位置给 Modbus 操作
  3212. }
  3213. if (cancellationToken != null && cancellationToken.IsCancellationRequested)
  3214. {
  3215. return;
  3216. }
  3217. }
  3218. }
  3219. else
  3220. {
  3221. foreach (var stockwork in works)
  3222. {
  3223. if (stockwork.Function == VibrationFunction.Delay)
  3224. {
  3225. if (stockwork.Duration > 0) await Task.Delay(stockwork.Duration, cancellationToken);
  3226. }
  3227. else
  3228. {
  3229. await feeder.OutputAsync(((int)stockwork.Function) + 1, stockwork.Duration);
  3230. if (stockwork.Duration > 0) await Task.Delay(stockwork.Duration, cancellationToken);
  3231. }
  3232. if (cancellationToken != null && cancellationToken.IsCancellationRequested)
  3233. {
  3234. return;
  3235. }
  3236. }
  3237. }
  3238. }
  3239. /// <summary>
  3240. /// 执行单独的 Feeder 振动动作序列(仅振动相关)。
  3241. /// </summary>
  3242. public async Task ExecuteFeederWorkOnly(IVoiceCoilMotorFeeder feeder, FeederWork[] works, CancellationToken cancellationToken, bool isUpdateParame = true)
  3243. {
  3244. if (works == null)
  3245. {
  3246. return;
  3247. }
  3248. if (feeder.FeederBrand == FeederBrand.AFAG)
  3249. {
  3250. //执行配置的Feeder振动任务
  3251. foreach (var feederwork in works)
  3252. {
  3253. if (feederwork.ConfigIndex < 0)
  3254. {
  3255. continue;
  3256. }
  3257. if (feederwork.ConfigIndex == 0)
  3258. {
  3259. if (feederwork.Duration > 0) await Task.Delay(feederwork.Duration, cancellationToken);
  3260. }
  3261. else
  3262. {
  3263. ((AfagFeeder)feeder).LoadConfiguration(feederwork.ConfigIndex);
  3264. ((AfagFeeder)feeder).SetIntensity(feederwork.Intensity);
  3265. ((AfagFeeder)feeder).SetDirection(feederwork.Direction);
  3266. if (feederwork.Duration > 0) await Task.Delay(feederwork.Duration, cancellationToken);
  3267. if (cancellationToken != null && cancellationToken.IsCancellationRequested)
  3268. {
  3269. return;
  3270. }
  3271. ((AfagFeeder)feeder).SetIntensity(0);
  3272. }
  3273. if (cancellationToken != null && cancellationToken.IsCancellationRequested)
  3274. {
  3275. return;
  3276. }
  3277. }
  3278. }
  3279. else
  3280. {
  3281. //执行配置的Feeder振动任务
  3282. foreach (var feederwork in works)
  3283. {
  3284. if (feederwork.Function == VibrationFunction.Delay)
  3285. {
  3286. if (feederwork.Duration > 0) await Task.Delay(feederwork.Duration, cancellationToken);
  3287. }
  3288. else
  3289. {
  3290. if (feederwork.SingleAction != null && isUpdateParame)
  3291. {
  3292. await feeder.SetShakeParametersAsync((int)feederwork.Function, feederwork.SingleAction);
  3293. }
  3294. await feeder.StartAction((int)feederwork.Function, feederwork.Duration);
  3295. if (feederwork.Duration > 0) await Task.Delay(feederwork.Duration, cancellationToken);
  3296. }
  3297. if (cancellationToken != null && cancellationToken.IsCancellationRequested)
  3298. {
  3299. return;
  3300. }
  3301. }
  3302. }
  3303. }
  3304. /// <summary>
  3305. /// 执行 Feeder 振动集合(逐个执行 FeederWorkList 中的动作)。
  3306. /// </summary>
  3307. public async Task ExecuteFeederWorks(IVoiceCoilMotorFeeder feeder, FeederWorks works, CancellationToken cancellationToken, bool isUpdateParame = true)
  3308. {
  3309. if (feeder.FeederBrand == FeederBrand.AFAG)
  3310. {
  3311. foreach (var feederwork in works.FeederWorkList)
  3312. {
  3313. if (feederwork.ConfigIndex < 0)
  3314. {
  3315. continue;
  3316. }
  3317. if (feederwork.ConfigIndex == 0)
  3318. {
  3319. await Task.Delay(feederwork.Duration, cancellationToken);
  3320. }
  3321. else
  3322. {
  3323. ((AfagFeeder)feeder).LoadConfiguration(feederwork.ConfigIndex);
  3324. ((AfagFeeder)feeder).SetIntensity(feederwork.Intensity);
  3325. ((AfagFeeder)feeder).SetDirection(feederwork.Direction);
  3326. await Task.Delay(feederwork.Duration, cancellationToken);
  3327. if (cancellationToken != null && cancellationToken.IsCancellationRequested)
  3328. {
  3329. return;
  3330. }
  3331. ((AfagFeeder)feeder).SetIntensity(0);
  3332. }
  3333. if (cancellationToken != null && cancellationToken.IsCancellationRequested)
  3334. {
  3335. return;
  3336. }
  3337. }
  3338. }
  3339. else
  3340. {
  3341. foreach (var feederwork in works.FeederWorkList)
  3342. {
  3343. if (feederwork.Function == VibrationFunction.Delay)
  3344. {
  3345. if (feederwork.Duration > 0) await Task.Delay(feederwork.Duration, cancellationToken);
  3346. }
  3347. else
  3348. {
  3349. if (feederwork.SingleAction != null && isUpdateParame)
  3350. {
  3351. await feeder.SetShakeParametersAsync((int)feederwork.Function, feederwork.SingleAction);
  3352. }
  3353. await feeder.StartAction((int)feederwork.Function, feederwork.Duration);
  3354. if (feederwork.Duration > 0) await Task.Delay(feederwork.Duration, cancellationToken);
  3355. }
  3356. if (cancellationToken != null && cancellationToken.IsCancellationRequested)
  3357. {
  3358. return;
  3359. }
  3360. }
  3361. }
  3362. }
  3363. /// <summary>
  3364. /// 在拍照前设置光源亮度和打开光源
  3365. /// </summary>
  3366. /// <param name="procedure">流程模型</param>
  3367. /// <returns></returns>
  3368. public async Task SetLightBeforePhoto(ProcedureModel procedure)
  3369. {
  3370. var sysConfig = _configService.GetSystemConfiguration();
  3371. if (sysConfig.LightUse == true)
  3372. {
  3373. return;
  3374. }
  3375. //判断当前流程是否启用光源控制
  3376. if (procedure.IsControlLightChannels)
  3377. {
  3378. //打开所有需要控制的光源通道
  3379. foreach (var lightChannel in procedure.LightChannels)
  3380. {
  3381. bool isSucceed = false;
  3382. isSucceed = await _lightManagerService.TurnOnGlobalChannelAsync(lightChannel.GlobalIndex);
  3383. if (!isSucceed)
  3384. {
  3385. LogHelper.WriteLogInfo($"设置光源通道{lightChannel.GlobalIndex}打开失败!");
  3386. }
  3387. isSucceed = await _lightManagerService.SetGlobalChannelBrightnessAsync(lightChannel.GlobalIndex, lightChannel.DefaultBrightness);
  3388. if (!isSucceed)
  3389. {
  3390. LogHelper.WriteLogInfo($"设置光源通道{lightChannel.GlobalIndex}亮度{lightChannel.DefaultBrightness}失败!");
  3391. }
  3392. }
  3393. }
  3394. }
  3395. /// <summary>
  3396. /// 在拍照后关闭光源
  3397. /// </summary>
  3398. /// <param name="procedure">流程模型</param>
  3399. /// <returns></returns>
  3400. public async Task TurnOffLightAfterPhoto(ProcedureModel procedure)
  3401. {
  3402. var sysConfig = _configService.GetSystemConfiguration();
  3403. if (sysConfig.LightUse == true)
  3404. {
  3405. return;
  3406. }
  3407. //判断当前流程是否启用光源控制
  3408. if (procedure.IsControlLightChannels)
  3409. {
  3410. //关闭所有需要控制的光源通道
  3411. foreach (var lightChannel in procedure.LightChannels)
  3412. {
  3413. bool isSucceed = false;
  3414. isSucceed = await _lightManagerService.TurnOffGlobalChannelAsync(lightChannel.GlobalIndex);
  3415. if (!isSucceed)
  3416. {
  3417. LogHelper.WriteLogInfo($"设置光源通道{lightChannel.GlobalIndex}关闭失败!");
  3418. }
  3419. }
  3420. }
  3421. }
  3422. #endregion
  3423. }
  3424. }