RemoteCommandService.cs 175 KB

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