RemoteCommandService.cs 177 KB

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