RemoteCommandService.cs 185 KB

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