| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032 |
- using Basler.Pylon;
- using Cognex.VisionPro;
- using Cognex.VisionPro.ImageFile;
- using Cognex.VisionPro.ToolBlock;
- using MathNet.Numerics.LinearAlgebra;
- using Microsoft.CodeAnalysis.Scripting;
- using NPOI.SS.Formula.Functions;
- using OpenCvSharp.Flann;
- using Org.BouncyCastle.Asn1.Cms;
- using Org.BouncyCastle.Tls;
- using Prism.Events;
- using Prism.Ioc;
- using Prism.Regions;
- using System;
- using System.Collections.Concurrent;
- using System.Collections.Generic;
- using System.ComponentModel;
- using System.IO;
- using System.Linq;
- using System.Reflection;
- using System.Text;
- using System.Threading;
- using System.Threading.Tasks;
- using System.Web.UI.WebControls;
- using System.Windows.Shapes;
- using Team.FFFeederService;
- using Team.FFFeederService.Interfaces;
- using TeamAAS_VP.Core;
- using TeamAAS_VP.Core.Cameras;
- using TeamAAS_VP.Data;
- using TeamAAS_VP.Enums;
- using TeamAAS_VP.Events;
- using TeamAAS_VP.Interfaces;
- using TeamAAS_VP.Models;
- using TeamAAS_VP.Models.Calibration;
- using TeamAAS_VP.Models.Feeder;
- using TeamAAS_VP.Models.Product;
- using TeamAAS_VP.Resources.Languages;
- namespace TeamAAS_VP.Services
- {
- /// <summary>
- /// 远程命令服务:
- /// 负责解析并执行外部传入的命令字符串(例如 LoadProduct、视觉流程触发、清料任务等)。
- /// 该类封装了原 Management.ExecuteRemoteCommand 的精简迁移实现,依赖于领域服务(产品、配置、校准、Feeder、相机、机器人、系统数据库等)。
- /// 线程安全:通过内部计数器和 ConcurrentDictionary 跟踪正在运行的任务。
- /// </summary>
- public class RemoteCommandService : IRemoteCommandService, INotifyPropertyChanged
- {
- // 依赖服务,由构造函数注入
- private readonly IEventAggregator _eventAggregator;
- private readonly IProductService _productService;
- private readonly IConfigService _configService;
- private readonly ICalibrationService _calibrationService;
- private readonly IFeederService _feederService;
- private readonly ICameraService _cameraService;
- private readonly IRobotService _robotService;
- private readonly IContainerProvider _container;
- private readonly IRegionManager _regionManager;
- private readonly ISystemDatabaseService _systemDatabaseService;
- private readonly ILightManagerService _lightManagerService;
- /// <summary>
- /// 节拍计时任务的取消令牌,用于 StartCycleTiming/StopCycleTiming。
- /// </summary>
- private CancellationTokenSource _cycleTimingCts;
- /// <summary>
- /// 清料任务的取消令牌字典,Key 为任务编号(TaskCode)。
- /// 当需要取消特定清料任务时,通过该字典查找并调用 Cancel。
- /// </summary>
- private readonly ConcurrentDictionary<int, CancellationTokenSource> _clearMaterialCtsDict = new ConcurrentDictionary<int, CancellationTokenSource>();
- // 内部执行状态计数器和任务跟踪集合
- private int _activeCount;
- private int _visionActiveCount;
- private readonly ConcurrentDictionary<Guid, Task> _runningTasks = new ConcurrentDictionary<Guid, Task>();
- // INotifyPropertyChanged 实现
- public event PropertyChangedEventHandler PropertyChanged;
- private void OnPropertyChanged(string name) => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
- /// <summary>
- /// 标识是否存在任意正在执行的命令(非视觉与视觉命令)。
- /// 由 TrackExecutionAsync 自动维护。
- /// </summary>
- public bool IsExecuting => Volatile.Read(ref _activeCount) > 0;
- /// <summary>
- /// 标识是否存在正在执行的视觉指令。
- /// 由 TrackExecutionAsync 在 isVision 参数为 true 时自动维护。
- /// </summary>
- public bool IsExecutingVisionCommand => Volatile.Read(ref _visionActiveCount) > 0;
- /// <summary>
- /// 当执行状态发生变化(开始/结束)时触发(便于传统事件订阅)。
- /// </summary>
- public event EventHandler ExecutionStateChanged;
- /// <summary>
- /// 节拍计时的定时回调事件,通知订阅者当前已用时。
- /// </summary>
- public event EventHandler<TimeSpan> CycleTimingTicked;
- /// <summary>
- /// 构造函数,注入必要的系统服务。
- /// </summary>
- /// <param name="eventAggregator">事件聚合器,用于发布 UI 渲染/消息等事件。</param>
- /// <param name="regionManager">区域管理器,用于 UI 区域导航(在脚本中可能使用)。</param>
- /// <param name="productService">产品服务,用于加载/查询产品信息。</param>
- /// <param name="configService">配置服务,用于读取机器人/任务/Feeder 等配置。</param>
- /// <param name="calibrationService">校准服务,用于像素到机器人坐标的转换。</param>
- /// <param name="feederService">Feeder 服务,控制料仓/振动等。</param>
- /// <param name="cameraService">相机服务,用于图像采集。</param>
- /// <param name="robotService">机器人服务,提供机器人状态码/调试模式等信息。</param>
- /// <param name="container">IOC 容器提供者,用于脚本执行时解析依赖。</param>
- /// <param name="systemDatabaseService">系统数据库服务,用于记录产量/报警等。</param>
- public RemoteCommandService(IEventAggregator eventAggregator, IRegionManager regionManager, IProductService productService, IConfigService configService, ICalibrationService calibrationService,
- IFeederService feederService, ICameraService cameraService, IRobotService robotService, IContainerProvider container, ISystemDatabaseService systemDatabaseService, ILightManagerService lightManagerService)
- {
- _eventAggregator = eventAggregator;
- _regionManager = regionManager;
- _productService = productService;
- _configService = configService;
- _calibrationService = calibrationService;
- _feederService = feederService;
- _cameraService = cameraService;
- _robotService = robotService;
- _container = container;
- _systemDatabaseService = systemDatabaseService;
- _lightManagerService = lightManagerService;
- }
- /// <summary>
- /// 占位 Dispose 方法(当前无资源释放逻辑)。
- /// </summary>
- public void Dispose() { }
- /// <summary>
- /// 通用的异步执行包装器。该方法:
- /// - 为每次执行生成唯一 id 并加入运行任务集合以便跟踪
- /// - 维护 _activeCount 和 _visionActiveCount
- /// - 在任务开始/结束时触发属性变化和 ExecutionStateChanged 事件
- /// - 返回工作 delegate 的结果
- /// </summary>
- /// <typeparam name="T">工作返回类型</typeparam>
- /// <param name="work">以 CancellationToken 为参数的异步工作委托</param>
- /// <param name="isVision">指示该工作是否为视觉命令(影响视觉计数器)</param>
- /// <param name="ct">外部取消令牌,传递给工作委托</param>
- /// <returns>工作委托的返回值</returns>
- private async Task<T> TrackExecutionAsync<T>(Func<CancellationToken, Task<T>> work, bool isVision, CancellationToken ct)
- {
- var id = Guid.NewGuid();
- Interlocked.Increment(ref _activeCount);
- if (isVision) Interlocked.Increment(ref _visionActiveCount);
- OnPropertyChanged(nameof(IsExecuting));
- OnPropertyChanged(nameof(IsExecutingVisionCommand));
- ExecutionStateChanged?.Invoke(this, EventArgs.Empty);
- try
- {
- var task = work(ct);
- _runningTasks.TryAdd(id, task);
- var result = await task.ConfigureAwait(false);
- return result;
- }
- finally
- {
- Interlocked.Decrement(ref _activeCount);
- if (isVision) Interlocked.Decrement(ref _visionActiveCount);
- _runningTasks.TryRemove(id, out _);
- OnPropertyChanged(nameof(IsExecuting));
- OnPropertyChanged(nameof(IsExecutingVisionCommand));
- ExecutionStateChanged?.Invoke(this, EventArgs.Empty);
- }
- }
- /// <summary>
- /// 解析并执行传入的命令字符串。命令以逗号分隔,第一个字段为命令名称,后续为参数。
- /// 支持多种内建命令(示例:LoadProduct、GetProductName、CycleTime、Record、StartClearMaterial 等),以及映射到产品 CameraProcedures 的自定义视觉触发命令。
- /// </summary>
- /// <param name="command">原始命令字符串</param>
- /// <param name="cancellationToken">外部取消令牌</param>
- /// <param name="callback">用于将执行结果回传(比如发送到调用方)的回调,参数为单行响应字符串</param>
- /// <returns>完成任务</returns>
- public async Task ExecuteAsync(string command, CancellationToken cancellationToken, Action<string> callback)
- {
- var items = (command ?? string.Empty).Split(new[] { ',' }, StringSplitOptions.None).Select(s => s.Trim()).ToArray();
- if (items.Length == 0) return;
- string triggerCommand = items[0];
- string[] commandParams = items.Skip(1).ToArray();
- string response = string.Empty;
- switch (triggerCommand)
- {
- case "LoadProduct":
- if (commandParams.Length < 1)
- {
- callback?.Invoke("InvalidParameters");
- return;
- }
- response = await TrackExecutionAsync(async ct =>
- {
- var ok = await LoadProductAsync(commandParams[0], ct);
- return ok ? "OK" : "NG";
- }, isVision: false, cancellationToken);
- callback?.Invoke($"LoadProduct,{response}");
- break;
- case "GetProductName":
- if (commandParams.Length < 1)
- {
- response = await TrackExecutionAsync(async ct =>
- {
- return await GetCurrentProductNameAsync(ct);
- }, isVision: false, cancellationToken);
- if (string.IsNullOrEmpty(response))
- {
- callback?.Invoke("GetProductName,NG");
- }
- else
- {
- callback?.Invoke($"GetProductName,{response}");
- }
- break;
- }
- else if (commandParams.Length == 1)
- {
- if (!int.TryParse(commandParams[0], out int productNumber))
- {
- callback?.Invoke("InvalidParameters");
- return;
- }
- response = await TrackExecutionAsync(async ct =>
- {
- return await GetProductNameByNumberAsync(productNumber, ct);
- }, isVision: false, cancellationToken);
- if (string.IsNullOrEmpty(response))
- {
- callback?.Invoke($"GetProductName,NG");
- }
- else
- {
- callback?.Invoke($"GetProductName,{response}");
- }
- break;
- }
- else
- {
- callback?.Invoke("InvalidParameters");
- return;
- }
- case "GetProductID":
- if (commandParams.Length < 1)
- {
- response = await TrackExecutionAsync(async ct =>
- {
- int productNum = await GetCurrentProductNumberAsync(ct);
- return productNum.ToString();
- }, isVision: false, cancellationToken);
- if (response == "-1")
- {
- callback?.Invoke("GetProductID,NG");
- }
- else
- {
- callback?.Invoke($"GetProductID,{response}");
- }
- break;
- }
- else if (commandParams.Length == 1)
- {
- response = await TrackExecutionAsync(async ct =>
- {
- int productNum = await GetProductNumberByNameAsync(commandParams[0], ct);
- return productNum.ToString();
- }, isVision: false, cancellationToken);
- if (response == "-1")
- {
- callback?.Invoke($"GetProductID,NG");
- }
- else
- {
- callback?.Invoke($"GetProductID,{response}");
- }
- break;
- }
- else
- {
- callback?.Invoke("InvalidParameters");
- return;
- }
- case "GetRobotPointsCountById":
- if (commandParams.Length < 2 || !int.TryParse(commandParams[0], out int robotNumber) || !int.TryParse(commandParams[1], out int pointNumber))
- {
- callback?.Invoke("InvalidParameters");
- return;
- }
- response = await TrackExecutionAsync(async ct =>
- {
- return await GetRobotPointInfoAsync(robotNumber, pointNumber, ct);
- }, isVision: false, cancellationToken);
- if (string.IsNullOrEmpty(response))
- {
- callback?.Invoke($"GetRobotPointsCountById,NG");
- }
- else
- {
- callback?.Invoke($"GetRobotPointsCountById,{response}");
- }
- break;
- case "GetPalletPoint":
- 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))
- {
- callback?.Invoke("InvalidParameters");
- return;
- }
- response = await TrackExecutionAsync(async ct =>
- {
- return await GetRobotPalletPointInfoAsync(robotNumber1, palletNumber1, pointNumber1, ct);
- }, isVision: false, cancellationToken);
- if (string.IsNullOrEmpty(response))
- {
- callback?.Invoke($"GetPalletPoint,NG");
- }
- else
- callback?.Invoke($"GetPalletPoint,{response}");
- break;
- case "CycleTime":
- if (commandParams.Length < 1)
- {
- callback?.Invoke("InvalidParameters");
- return;
- }
- if (int.Parse(commandParams[0]) == 1)
- {
- response = await TrackExecutionAsync(async ct =>
- {
- bool cycleResult = await StartCycleTimingAsync(ct);
- return cycleResult ? "OK" : "NG";
- }, isVision: false, cancellationToken);
- callback?.Invoke($"CycleTime,{response}");
- break;
- }
- else
- {
- response = await TrackExecutionAsync(async ct =>
- {
- bool cycleResult = await StopCycleTimingAsync(ct);
- return cycleResult ? "OK" : "NG";
- }, isVision: false, cancellationToken);
- callback?.Invoke($"CycleTime,{response}");
- break;
- }
- case "Record":
- if (commandParams.Length < 1)
- {
- callback?.Invoke("InvalidParameters");
- return;
- }
- response = await TrackExecutionAsync(async ct =>
- {
- bool recordResult = await CreateProductionCountAsync(commandParams[0].Trim(), ct);
- return recordResult ? "OK" : "NG";
- }, isVision: false, cancellationToken);
- callback?.Invoke($"Record,{response}");
- break;
- case "RecordQuery":
- if (commandParams.Length < 1)
- {
- callback?.Invoke("InvalidParameters");
- return;
- }
- response = await TrackExecutionAsync(async ct =>
- {
- int recordCount = await GetCurrentProductionCountAsync(commandParams[0].Trim(), ct);
- return recordCount.ToString();
- }, isVision: false, cancellationToken);
- callback?.Invoke($"RecordQuery,{response}");
- break;
- case "RecordReset":
- if (commandParams.Length < 1)
- {
- callback?.Invoke("InvalidParameters");
- return;
- }
- response = await TrackExecutionAsync(async ct =>
- {
- bool recordResetResult = await ResetProductionCountAsync(commandParams[0].Trim(), ct);
- return recordResetResult ? "OK" : "NG";
- }, isVision: false, cancellationToken);
- callback?.Invoke($"RecordReset,{response}");
- break;
- case "Err":
- if (commandParams.Length < 2)
- {
- callback?.Invoke("InvalidParameters");
- return;
- }
- response = await TrackExecutionAsync(async ct =>
- {
- bool errResult = await CreateAlarmRecordAsync(commandParams[0].Trim(), commandParams[1].Trim(), ct);
- return errResult ? "OK" : "NG";
- }, isVision: false, cancellationToken);
- callback?.Invoke($"Err,{response}");
- break;
- case "Info":
- if (commandParams.Length < 1)
- {
- callback?.Invoke("InvalidParameters");
- return;
- }
- response = await TrackExecutionAsync(async ct =>
- {
- bool infoResult = await CreateOperationLogAsync(commandParams[0].Trim(), ct);
- return infoResult ? "OK" : "NG";
- }, isVision: false, cancellationToken);
- callback?.Invoke($"Info,{response}");
- break;
- case "GetGlobalParam":
- if (commandParams.Length == 1)
- {
- response = await TrackExecutionAsync(async ct =>
- {
- return await GetGlobalParameterAsync(int.Parse(commandParams[0]), -1, ct);
- }, isVision: false, cancellationToken);
- if (string.IsNullOrEmpty(response))
- {
- callback?.Invoke("GetGlobalParam,NG");
- }
- else
- {
- callback?.Invoke($"GetGlobalParam,{response}");
- }
- break;
- }
- else if (commandParams.Length == 2)
- {
- response = await TrackExecutionAsync(async ct =>
- {
- return await GetGlobalParameterAsync(int.Parse(commandParams[0]), int.Parse(commandParams[1]), ct);
- }, isVision: false, cancellationToken);
- if (string.IsNullOrEmpty(response))
- {
- callback?.Invoke("GetGlobalParam,NG");
- }
- else
- {
- callback?.Invoke($"GetGlobalParam,{response}");
- }
- break;
- }
- else
- {
- callback?.Invoke("InvalidParameters");
- return;
- }
- case "GetSpeed":
- response = await TrackExecutionAsync(async ct =>
- {
- return await GetOperationSpeedAsync(ct);
- }, isVision: false, cancellationToken);
- if (string.IsNullOrEmpty(response))
- {
- callback?.Invoke("GetSpeed,NG");
- return;
- }
- else
- callback?.Invoke($"GetSpeed,{response}");
- break;
- case "GetToolParam":
- if (commandParams.Length < 2)
- {
- callback?.Invoke("InvalidParameters");
- return;
- }
- response = await TrackExecutionAsync(async ct =>
- {
- return await GetToolParamAsync(commandParams[0], int.Parse(commandParams[1]), ct);
- }, isVision: false, cancellationToken);
- if (string.IsNullOrEmpty(response))
- {
- callback?.Invoke("GetToolParam,NG");
- return;
- }
- else
- callback?.Invoke($"GetToolParam,{response}");
- break;
- case "GetProcedureParam":
- if (commandParams.Length < 1)
- {
- callback?.Invoke("InvalidParameters");
- return;
- }
- response = await TrackExecutionAsync(async ct =>
- {
- return await GetProcessParamAsync(commandParams[0], ct);
- }, isVision: false, cancellationToken);
- if (string.IsNullOrEmpty(response))
- {
- callback?.Invoke("GetProcedureParam,NG");
- return;
- }
- else
- callback?.Invoke($"GetProcedureParam,{response}");
- break;
- case "StartClearMaterial":
- if (commandParams.Length < 1)
- {
- callback?.Invoke("InvalidParameters");
- return;
- }
- response = await TrackExecutionAsync(async ct =>
- {
- bool startClearResult = await ExecuteClearMaterialTaskAsync(int.Parse(commandParams[0]), ct);
- return startClearResult ? "OK" : "NG";
- }, isVision: false, cancellationToken);
- callback?.Invoke($"StartClearMaterial,{response}");
- break;
- case "StopClearMaterial":
- if (commandParams.Length < 1)
- {
- callback?.Invoke("InvalidParameters");
- return;
- }
- response = await TrackExecutionAsync(async ct =>
- {
- bool stopClearResult = await StopClearMaterialTaskAsync(int.Parse(commandParams[0]), ct);
- return stopClearResult ? "OK" : "NG";
- }, isVision: false, cancellationToken);
- callback?.Invoke($"StopClearMaterial,{response}");
- break;
- case "RobotIsDebugMode":
- if (commandParams.Length < 1)
- {
- callback?.Invoke("InvalidParameters");
- return;
- }
- response = await TrackExecutionAsync(async ct =>
- {
- bool isDebugMode = await IsRobotInDebugModeAsync(int.Parse(commandParams[0]), ct);
- return isDebugMode ? "1" : "0";
- }, isVision: false, cancellationToken);
- callback?.Invoke($"RobotIsDebugMode,{response}");
- break;
- default:
- var currentProduct = _productService.GetCurrentProduct();
- if (currentProduct == null) return;
- var procedure = currentProduct.CameraProcedures
- .SelectMany(cp => cp.ProcedureModels)
- .FirstOrDefault(p => p.TriggerCommand == triggerCommand);
- if (procedure == null) return;
- var visionResult = await TrackExecutionAsync(async ct =>
- {
- var r = await ExecuteVisionTaskAsync(procedure, commandParams, ct);
- return Tuple.Create(r.IsSucceed, r.Response);
- }, isVision: true, cancellationToken);
- if (visionResult.Item1)
- {
- foreach (var item in visionResult.Item2)
- {
- callback?.Invoke($"{triggerCommand},OK,{item}");
- }
- }
- else
- {
- string msg = string.Empty;
- if (visionResult.Item2 != null && visionResult.Item2.Length > 0)
- {
- msg = visionResult.Item2[0];
- }
- callback?.Invoke($"{triggerCommand},NG,{msg}");
- }
- break;
- }
- }
- /// <summary>
- /// 根据产品名称或编号加载并设置当前产品。
- /// 若传入字符串可解析为 int,则先按编号查找产品,否则按名称查找。
- /// </summary>
- /// <param name="productName">产品名称或编号字符串</param>
- /// <param name="cancellationToken">取消令牌</param>
- /// <returns>加载成功返回 true,否则 false</returns>
- public async Task<bool> LoadProductAsync(string productName, CancellationToken cancellationToken)
- {
- bool exists = _productService.ContainsProductByName(productName);
- if (exists)
- {
- var product = _productService.GetAllProducts().FirstOrDefault(p => p.Name == productName);
- await _productService.LoadProductAsync(product.ID);
- _productService.SetCurrentProduct(product.ID);
- return true;
- }
- if (int.TryParse(productName, out int productNumber))
- {
- var product = _productService.GetAllProducts().FirstOrDefault(p => p.NumberCode == productNumber);
- if (product != null)
- {
- await _productService.LoadProductAsync(product.ID);
- _productService.SetCurrentProduct(product.ID);
- return true;
- }
- }
- return false;
- }
- /// <summary>
- /// 通过产品编号获取产品名称。
- /// </summary>
- public Task<string> GetProductNameByNumberAsync(int productNumber, CancellationToken cancellationToken)
- {
- var product = _productService.GetAllProducts().FirstOrDefault(p => p.NumberCode == productNumber);
- if (product != null)
- {
- return Task.FromResult(product.Name);
- }
- return Task.FromResult(string.Empty);
- }
- /// <summary>
- /// 获取当前被设置为活动的产品名称。如果没有则返回空字符串。
- /// </summary>
- public Task<string> GetCurrentProductNameAsync(CancellationToken cancellationToken)
- {
- var currentProduct = _productService.GetCurrentProduct();
- if (currentProduct != null)
- {
- return Task.FromResult(currentProduct.Name);
- }
- return Task.FromResult(string.Empty);
- }
- /// <summary>
- /// 通过产品名称获取其编号(NumberCode)。找不到则返回 -1。
- /// </summary>
- public Task<int> GetProductNumberByNameAsync(string productName, CancellationToken cancellationToken)
- {
- bool exists = _productService.ContainsProductByName(productName);
- if (exists)
- {
- var product = _productService.GetAllProducts().FirstOrDefault(p => p.Name == productName);
- return Task.FromResult(product.NumberCode);
- }
- return Task.FromResult(-1);
- }
- /// <summary>
- /// 获取当前产品编号(NumberCode)。找不到则返回 -1。
- /// </summary>
- public Task<int> GetCurrentProductNumberAsync(CancellationToken cancellationToken)
- {
- var currentProduct = _productService.GetCurrentProduct();
- if (currentProduct != null)
- {
- return Task.FromResult(currentProduct.NumberCode);
- }
- return Task.FromResult(-1);
- }
- /// <summary>
- /// 根据机器人编号和点位编号获取点位信息(字符串表示),查找逻辑基于当前产品的 RobotPoint 配置。
- /// </summary>
- public Task<string> GetRobotPointInfoAsync(int robotNumber, int pointNumber, CancellationToken cancellationToken)
- {
- var currentProduct = _productService.GetCurrentProduct();
- if (currentProduct == null) return Task.FromResult(string.Empty);
- var robot = _configService.GetAllRobots().FirstOrDefault(r => r.RobotNo == robotNumber);
- if (robot == null) return Task.FromResult(string.Empty);
- var robotPoint = currentProduct.RobotPoint.Robots.FirstOrDefault(rp => rp.Id == robot.Id);
- if (robotPoint == null) return Task.FromResult(string.Empty);
- var point = robotPoint.Points.FirstOrDefault(p => p.Number == pointNumber);
- if (point == null) return Task.FromResult(string.Empty);
- return Task.FromResult(point.ToString());
- }
- /// <summary>
- /// 通过机器人编号、托盘编号和点编号获取托盘点位信息,返回格式化字符串。
- /// </summary>
- public Task<string> GetRobotPalletPointInfoAsync(int robotNumber, int palletNumber, int pointNumber, CancellationToken cancellationToken)
- {
- var currentProduct = _productService.GetCurrentProduct();
- if (currentProduct == null) return Task.FromResult(string.Empty);
- var robot = _configService.GetAllRobots().FirstOrDefault(r => r.RobotNo == robotNumber);
- if (robot == null) return Task.FromResult(string.Empty);
- var robotPoint = currentProduct.RobotPoint.Robots.FirstOrDefault(rp => rp.Id == robot.Id);
- if (robotPoint == null) return Task.FromResult(string.Empty);
- var pallet = robotPoint.Pallets.FirstOrDefault(p => p.PalletNo == palletNumber);
- if (pallet == null) return Task.FromResult(string.Empty);
- PalletTool palletTool = new PalletTool(pallet);
- if (pointNumber > palletTool.Points.Length || pointNumber < 1) return Task.FromResult(string.Empty);
- var pos = palletTool.Points[pointNumber - 1];
- 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}";
- return Task.FromResult(response);
- }
- /// <summary>
- /// 开始节拍计时。返回是否成功(始终 true)。
- /// 会启动后台定时任务并周期性触发 CycleTimingTicked 事件。
- /// </summary>
- public Task<bool> StartCycleTimingAsync(CancellationToken cancellationToken)
- {
- if (_cycleTimingCts != null)
- {
- _cycleTimingCts.Cancel();
- _cycleTimingCts.Dispose();
- }
- _cycleTimingCts = new CancellationTokenSource();
- var token = _cycleTimingCts.Token;
- Task.Run(async () =>
- {
- var startTime = DateTime.UtcNow;
- while (!token.IsCancellationRequested)
- {
- var elapsed = DateTime.UtcNow - startTime;
- OnCycleTimingTicked(elapsed);
- await Task.Delay(100, token);
- }
- }, token);
- return Task.FromResult(true);
- }
- /// <summary>
- /// 停止节拍计时并清理取消令牌。
- /// </summary>
- public Task<bool> StopCycleTimingAsync(CancellationToken cancellationToken)
- {
- if (_cycleTimingCts != null)
- {
- _cycleTimingCts.Cancel();
- _cycleTimingCts.Dispose();
- _cycleTimingCts = null;
- }
- return Task.FromResult(true);
- }
- /// <summary>
- /// 新增一条生产计数记录,数量固定为 1。
- /// </summary>
- public Task<bool> CreateProductionCountAsync(string countItem, CancellationToken cancellationToken)
- {
- _systemDatabaseService.RecordProductionAsync(new ProductionRecord
- {
- Category = countItem,
- ProductName = _productService.GetCurrentProduct()?.Name ?? "Unknown",
- Quantity = 1,
- Timestamp = DateTime.UtcNow
- });
- return Task.FromResult(true);
- }
- /// <summary>
- /// 查询当前产品在指定分类下的累计产量。
- /// </summary>
- public async Task<int> GetCurrentProductionCountAsync(string countItem, CancellationToken cancellationToken)
- {
- var currentProduct = _productService.GetCurrentProduct();
- if (currentProduct == null) return 0;
- var records = _systemDatabaseService.GetProductCategoriesAsync(currentProduct.Name);
- int totalCount = await _systemDatabaseService.GetTotalProductionAsync(currentProduct.Name, new List<string> { countItem });
- return totalCount;
- }
- /// <summary>
- /// 重置当前产品的生产统计(通过系统 DB 服务)。
- /// </summary>
- public async Task<bool> ResetProductionCountAsync(string countItem, CancellationToken cancellationToken)
- {
- var currentProduct = _productService.GetCurrentProduct();
- if (currentProduct == null) return false;
- await _systemDatabaseService.ResetProductionAsync(currentProduct.Name);
- return true;
- }
- /// <summary>
- /// 记录一条报警信息到系统数据库,并通过事件发布错误级别的任务消息。
- /// </summary>
- public Task<bool> CreateAlarmRecordAsync(string alarmCode, string alarmDescription, CancellationToken cancellationToken)
- {
- SendTaskMessage(alarmDescription, MessageLevel.Error);
- _systemDatabaseService.RecordAlarmAsync(new AlarmRecord
- {
- Code = alarmCode,
- Message = alarmDescription,
- Source = "Unknown",
- Time = DateTime.UtcNow
- });
- return Task.FromResult(true);
- }
- /// <summary>
- /// 发布运行信息日志(仅消息推送,不持久化)。
- /// </summary>
- public Task<bool> CreateOperationLogAsync(string logMessage, CancellationToken cancellationToken)
- {
- SendTaskMessage(logMessage, MessageLevel.Info);
- return Task.FromResult(true);
- }
- /// <summary>
- /// 获取当前产品的全局参数,支持按索引(1-4)返回指定子项,或返回完整 ToString。
- /// </summary>
- public Task<string> GetGlobalParameterAsync(int parameterNumber, int itemIndex, CancellationToken cancellationToken)
- {
- var currentProduct = _productService.GetCurrentProduct();
- if (currentProduct == null) return Task.FromResult(string.Empty);
- if (currentProduct.GlobalParamListCollection == null) return Task.FromResult(string.Empty);
- var globalParam = currentProduct.GlobalParamListCollection.FirstOrDefault(p => p.Number == parameterNumber);
- if (globalParam == null) return Task.FromResult(string.Empty);
- string response = string.Empty;
- if (itemIndex == 1)
- {
- response = $"{globalParam.Number},{globalParam.Name},{globalParam.Param1}";
- }
- else if (itemIndex == 2)
- {
- response = $"{globalParam.Number},{globalParam.Name},{globalParam.Param2}";
- }
- else if (itemIndex == 3)
- {
- response = $"{globalParam.Number},{globalParam.Name},{globalParam.Param3}";
- }
- else if (itemIndex == 4)
- {
- response = $"{globalParam.Number},{globalParam.Name},{globalParam.Param4}";
- }
- else if (itemIndex == 5)
- {
- response = $"{globalParam.Number},{globalParam.Name},{globalParam.Param5}";
- }
- else
- {
- response = globalParam.ToString();
- }
- return Task.FromResult(response);
- }
- /// <summary>
- /// 返回当前产品的速度/加速度等运行参数的格式化字符串。
- /// </summary>
- public Task<string> GetOperationSpeedAsync(CancellationToken cancellationToken)
- {
- var currentProduct = _productService.GetCurrentProduct();
- if (currentProduct == null) return Task.FromResult(string.Empty);
- string response = $"{currentProduct.Speed},{currentProduct.Accel},{currentProduct.Speeds},{currentProduct.Accels},{Convert.ToInt16(currentProduct.Power)},{Convert.ToInt16(currentProduct.IsUserUpCamera)}";
- return Task.FromResult(response);
- }
- /// <summary>
- /// 获取某流程指定工具编号的工具参数(格式化字符串),找不到返回空字符串。
- /// </summary>
- public Task<string> GetToolParamAsync(string triggerCommand, int toolNumber, CancellationToken cancellationToken)
- {
- var currentProduct = _productService.GetCurrentProduct();
- if (currentProduct == null) return Task.FromResult(string.Empty);
- ProcedureModel procedure = currentProduct.CameraProcedures
- .SelectMany(cp => cp.ProcedureModels)
- .FirstOrDefault(p => p.TriggerCommand == triggerCommand);
- if (procedure == null || procedure.ToolInfo == null) return Task.FromResult(string.Empty);
- var tool = procedure.ToolInfo.FirstOrDefault(t => t.Number == toolNumber);
- if (tool == null) return Task.FromResult(string.Empty);
- if (tool.Tool == null) return Task.FromResult(string.Empty);
- 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}";
- return Task.FromResult(response);
- }
- /// <summary>
- /// 获取流程参数(例如 WaitPhoto 与用户自定义参数等),以逗号分隔的字符串返回。
- /// </summary>
- public Task<string> GetProcessParamAsync(string triggerCommand, CancellationToken cancellationToken)
- {
- var currentProduct = _productService.GetCurrentProduct();
- if (currentProduct == null) return Task.FromResult(string.Empty);
- ProcedureModel procedure = currentProduct.CameraProcedures
- .SelectMany(cp => cp.ProcedureModels)
- .FirstOrDefault(p => p.TriggerCommand == triggerCommand);
- if (procedure == null || procedure.ToolInfo == null) return Task.FromResult(string.Empty);
- StringBuilder response = new StringBuilder();
- response.Append($"{procedure.WaitPhoto}");
- if (procedure.UserDefineParameters != null)
- {
- foreach (var param in procedure.UserDefineParameters)
- {
- response.Append("," + param.ToString());
- }
- }
- return Task.FromResult(response.ToString());
- }
- /// <summary>
- /// 执行指定编号的清料任务(异步)。流程:
- /// - 根据配置获取任务
- /// - 检查 Feeder 连接性
- /// - 使用专用 CancellationTokenSource 跟踪任务并支持停止
- /// - 循环执行开挡板、振动、关闭挡板等步骤,检查取消状态
- /// </summary>
- public async Task<bool> ExecuteClearMaterialTaskAsync(int taskNumber, CancellationToken cancellationToken)
- {
- var feederClearWork = _configService.GetClearanceTaskByNumber(taskNumber);
- if (feederClearWork == null)
- {
- return false;
- }
- IVoiceCoilMotorFeeder Feeder = _feederService.GetFeeder(feederClearWork.FeederId);
- if (!Feeder.IsConnected)
- {
- return false;
- }
- if (_clearMaterialCtsDict.ContainsKey(feederClearWork.TaskCode))
- {
- return false;
- }
- _clearMaterialCtsDict[feederClearWork.TaskCode] = new CancellationTokenSource();
- if (cancellationToken != null)
- {
- cancellationToken.Register(() =>
- {
- if (_clearMaterialCtsDict.ContainsKey(feederClearWork.TaskCode))
- {
- _clearMaterialCtsDict[feederClearWork.TaskCode].Cancel();
- }
- });
- }
- var token = _clearMaterialCtsDict[feederClearWork.TaskCode].Token;
- for (int i = 0; i < feederClearWork.ClearCount; i++)
- {
- await Feeder.OutputAsync((int)feederClearWork.BeforeOutput + 1, 0);
- await Task.Delay(200, token);
- if ((cancellationToken != null && cancellationToken.IsCancellationRequested) || (token != null && token.IsCancellationRequested))
- {
- await Feeder.StopOutputAsync();
- if (_clearMaterialCtsDict.ContainsKey(feederClearWork.TaskCode))
- {
- _clearMaterialCtsDict[feederClearWork.TaskCode].Cancel();
- _clearMaterialCtsDict.TryRemove(feederClearWork.TaskCode, out _);
- }
- return false;
- }
- for (int j = 0; j < feederClearWork.VibrationCount; j++)
- {
- await ExecuteFeederWorks(Feeder, feederClearWork.FeederWorks, token, true);
- if ((cancellationToken != null && cancellationToken.IsCancellationRequested) || (token != null && token.IsCancellationRequested))
- {
- await Feeder.StopOutputAsync();
- if (_clearMaterialCtsDict.ContainsKey(feederClearWork.TaskCode))
- {
- _clearMaterialCtsDict[feederClearWork.TaskCode].Cancel();
- _clearMaterialCtsDict.TryRemove(feederClearWork.TaskCode, out _);
- }
- return false;
- }
- if (!await Feeder.GetOutputStatusAsync())
- {
- await Feeder.OutputAsync((int)feederClearWork.BeforeOutput + 1, 0);
- }
- if ((cancellationToken != null && cancellationToken.IsCancellationRequested) || (token != null && token.IsCancellationRequested))
- {
- await Feeder.StopOutputAsync();
- if (_clearMaterialCtsDict.ContainsKey(feederClearWork.TaskCode))
- {
- _clearMaterialCtsDict[feederClearWork.TaskCode].Cancel();
- _clearMaterialCtsDict.TryRemove(feederClearWork.TaskCode, out _);
- }
- return false;
- }
- }
- if ((cancellationToken != null && cancellationToken.IsCancellationRequested) || (token != null && token.IsCancellationRequested))
- {
- await Feeder.StopOutputAsync();
- if (_clearMaterialCtsDict.ContainsKey(feederClearWork.TaskCode))
- {
- _clearMaterialCtsDict[feederClearWork.TaskCode].Cancel();
- _clearMaterialCtsDict.TryRemove(feederClearWork.TaskCode, out _);
- }
- return false;
- }
- await Feeder.StopOutputAsync();
- await Task.Delay(300, token);
- if ((cancellationToken != null && cancellationToken.IsCancellationRequested) || (token != null && token.IsCancellationRequested))
- {
- await Feeder.StopOutputAsync();
- if (_clearMaterialCtsDict.ContainsKey(feederClearWork.TaskCode))
- {
- _clearMaterialCtsDict[feederClearWork.TaskCode].Cancel();
- _clearMaterialCtsDict.TryRemove(feederClearWork.TaskCode, out _);
- }
- return false;
- }
- }
- await Feeder.StopOutputAsync();
- await Task.Delay(300, token);
- if ((cancellationToken != null && cancellationToken.IsCancellationRequested) || (token != null && token.IsCancellationRequested))
- {
- await Feeder.StopOutputAsync();
- if (_clearMaterialCtsDict.ContainsKey(feederClearWork.TaskCode))
- {
- _clearMaterialCtsDict[feederClearWork.TaskCode].Cancel();
- _clearMaterialCtsDict.TryRemove(feederClearWork.TaskCode, out _);
- }
- return false;
- }
- if (_clearMaterialCtsDict.ContainsKey(feederClearWork.TaskCode))
- {
- _clearMaterialCtsDict[feederClearWork.TaskCode].Cancel();
- _clearMaterialCtsDict.TryRemove(feederClearWork.TaskCode, out _);
- }
- return true;
- }
- /// <summary>
- /// 停止指定编号的清料任务(如果正在运行)。
- /// </summary>
- public Task<bool> StopClearMaterialTaskAsync(int taskNumber, CancellationToken cancellationToken)
- {
- var feederClearWork = _configService.GetClearanceTaskByNumber(taskNumber);
- if (feederClearWork == null)
- {
- return Task.FromResult(false);
- }
- if (_clearMaterialCtsDict.ContainsKey(feederClearWork.TaskCode))
- {
- _clearMaterialCtsDict[feederClearWork.TaskCode].Cancel();
- _clearMaterialCtsDict.TryRemove(feederClearWork.TaskCode, out _);
- }
- return Task.FromResult(true);
- }
- /// <summary>
- /// 判断指定编号的机器人是否处于调试模式。
- /// </summary>
- public Task<bool> IsRobotInDebugModeAsync(int robotNumber, CancellationToken cancellationToken)
- {
- var robotInfo = _configService.GetAllRobots().FirstOrDefault(r => r.RobotNo == robotNumber);
- if (robotInfo == null)
- {
- return Task.FromResult(false);
- }
- var robot = _robotService.GetRobot(robotInfo.Id);
- if (robot != null) return Task.FromResult(robot.EnterDebugMode);
- return Task.FromResult(false);
- }
- /// <summary>
- /// 执行视觉任务的统一入口:
- /// - 如果为产品局部脚本存在,则调用脚本
- /// - 否则根据 procedure.FeederId 调用 Feeder 引导的视觉任务或普通视觉任务
- /// 返回是否成功以及字符串数组形式的响应(用于发送多条结果)。
- /// </summary>
- public async Task<(bool IsSucceed, string[] Response)> ExecuteVisionTaskAsync(ProcedureModel procedure, string[] items, CancellationToken cancellationToken)
- {
- var currentProduct = _productService.GetCurrentProduct();
- string scriptFilePath = FilePath.ProductsPath + "//" + currentProduct.Name + "//" + procedure.CameraName + "//" + procedure.Name + ".cs";
- if (File.Exists(scriptFilePath))
- {
- try
- {
- string script = FileHelper.ReadFile(scriptFilePath);
- SendTaskMessage(Lang.执行视觉处理脚本, MessageLevel.Debug);
- Tuple<bool, string[]> rstn = null;
- var rst1 = await ScriptHelper.ExecuteVisionScriptingAsync(script, _regionManager, _eventAggregator, _container, procedure, items, rst =>
- {
- rstn = rst;
- });
- if (!rst1.Item1)
- {
- SendTaskMessage(Lang.视觉处理脚本出错, MessageLevel.Error);
- foreach (var item in rst1.Item2)
- {
- SendTaskMessage(item, MessageLevel.Error);
- }
- return (false, new string[] { "ScriptError" });
- }
- return (rstn.Item1, rstn.Item2);
- }
- catch (Exception ex)
- {
- SendTaskMessage(ex.Message, MessageLevel.Error);
- LogHelper.WriteLogError("执行视觉处理脚本时出错!", ex);
- return (false, new string[] { "ScriptException" });
- }
- }
- else
- {
- IVoiceCoilMotorFeeder Feeder = null;
- if (procedure.FeederId != Guid.Empty)
- {
- Feeder = _feederService.GetFeeder(procedure.FeederId);
- return await ExecuteFeederVisionTaskAsync(Feeder, procedure, items, cancellationToken);
- }
- else
- {
- var result = await ExecuteNormalVisionTaskAsync(procedure, items, cancellationToken);
- return (result.IsSucceed, new string[] { result.Response });
- }
- }
- }
- /// <summary>
- /// 内部:触发节拍计时回调。
- /// </summary>
- private void OnCycleTimingTicked(TimeSpan elapsed)
- {
- CycleTimingTicked?.Invoke(this, elapsed);
- }
- /// <summary>
- /// 发布任务消息到事件聚合器(通过 UI Dispatcher 保证线程安全)。
- /// </summary>
- private void SendTaskMessage(string msg, MessageLevel level)
- {
- App.Current.Dispatcher.Invoke(() =>
- {
- _eventAggregator.GetEvent<TaskMessageNotification>().Publish(new Models.MessageStruct() { Message = msg, level = level });
- });
- }
- #region 执行视觉任务辅助方法
- /// <summary>
- /// 执行 Feeder 引导的视觉任务。负责:
- /// - 解析输入命令(是否先振动/先拍照、SetInputs)
- /// - 在拍照前后执行对应的 Feeder 操作(开灯、振动、供料等)
- /// - 多次尝试拍照并运行视觉工具,直到成功或达到失败次数上限
- /// - 返回布尔成功标记及字符串数组形式的响应项
- /// </summary>
- public async Task<(bool IsSucceed, string[] Response)> ExecuteFeederVisionTaskAsync(IVoiceCoilMotorFeeder feeder, ProcedureModel procedure, string[] items, CancellationToken cancellationToken)
- {
- // 如果输入的items中是否包含Vibration和NoVibration,这两个分别对应是否先振动和是否先拍照
- bool doVibrateFirst = items != null && items.Contains("VibrateFirst");
- bool doCaptureFirst = items != null && items.Contains("CaptureFirst");
- if (doVibrateFirst && doCaptureFirst) doCaptureFirst = false; // 如果两个都包含,则以振动优先为准
- // 触发命令传入的输入终端
- Dictionary<string, string> InputTerminal = null;
- // 解析触发命令传入的输入终端参数
- //判断传入参数中是否存在“SetInputs”
- if (items != null && items.Length > 1 && items[0] == "SetInputs")
- {
- //依次从索引1开始解析参数,格式为 key=value,直到遇到非key=value格式的参数为止
- InputTerminal = new Dictionary<string, string>();
- for (int i = 1; i < items.Length; i++)
- {
- var pair = items[i].Split('=');
- if (pair.Length == 2)
- {
- InputTerminal[pair[0]] = pair[1];
- }
- else
- {
- break; // 遇到非key=value格式的参数,停止解析
- }
- }
- }
- await SetLightBeforePhoto(procedure);
- //执行Feeder相机拍照前的任务
- await ExecuteFeederForPhotoBefore(feeder, procedure, doVibrateFirst, doCaptureFirst, cancellationToken);
- // 如果遇到取消令牌,则直接返回失败
- if (cancellationToken != null && cancellationToken.IsCancellationRequested)
- {
- await feeder.CloseLightAsync();
- return (false, new string[] { "FeederTaskCancelled" });
- }
- DateTime nowtime = DateTime.Now;
- //拍照失败时,需要多次拍照
- for (int i = 0; i < procedure.FeederFailLimit; i++)
- {
- if (cancellationToken != null && cancellationToken.IsCancellationRequested)
- {
- await feeder.CloseLightAsync();
- await TurnOffLightAfterPhoto(procedure);
- return (false, new string[] { "VisionTaskCancelled" });
- }
- SendTaskMessage(Lang.开始执行视觉流程.Replace("{0}", $"{i + 1}").Replace("{1}", procedure.Name), MessageLevel.Info);
- // 1. 执行相机拍照并运行视觉工具
- bool visionSucceed = ExecutePhoto(procedure, InputTerminal, out CogToolBlockTerminalCollection outputCollection);
- if (!visionSucceed)
- {
- SendTaskMessage(Lang.视觉任务执行失败, MessageLevel.Error);
- continue;
- }
- if (!outputCollection.Contains("Found"))
- {
- SendTaskMessage(Lang.未找到视觉输出结果, MessageLevel.Error);
- return (false, new string[] { "NoFoundOutput" });
- }
- procedure.LastBlobArea = Convert.ToDouble(outputCollection["BlobTotalArea"].Value);
- // 2. 获取视觉输出结果
- bool Found = (bool)(outputCollection["Found"].Value);
- if (!Found)
- {
- SendTaskMessage(Lang.拍照NG, MessageLevel.Debug);
- await TurnOffLightAfterPhoto(procedure);
- await ExecuteFeederForPhotoLater(feeder, procedure, cancellationToken);
- continue;
- }
- SendTaskMessage(Lang.拍照OK, MessageLevel.Debug);
- if (procedure.ProcedureOutputs == null)
- {
- SendTaskMessage(Lang.视觉流程未配置输出项, MessageLevel.Alarm);
- return (false, new string[] { "NoOutputConfigured" });
- }
- // 3. 获取视觉输出结果
- LogHelper.WriteLogInfo("开始获取视觉输出结果");
- var (IsSucceed, ErrMsg, Output) = GetVisionOutput(procedure, outputCollection, null);
- if (!IsSucceed)
- {
- SendTaskMessage(Lang.获取视觉输出结果失败, MessageLevel.Error);
- return (false, new string[] { ErrMsg });
- }
- // 4. 组织返回结果
- int outputPointCount = 0;//输出点的数量
- List<double[]> currentPoints = new List<double[]>(); //点位数据
- List<string> outputItems = new List<string>(); //多项输出结果集合
- foreach (var output in procedure.ProcedureOutputs)
- {
- if (Output.ContainsKey(output.Name))
- {
- var (IsPoint, Value) = Output[output.Name];
- if (IsPoint)
- {
- //Value是点位数据,类型:List<string[]>,string[]是一个点位,里面是X、Y,U等数据
- //将所有点位数据和单个点位数据中的坐标之间都用逗号分隔,多个点位之间用逗号分隔
- List<string[]> points = Value as List<string[]>;
- List<string> allpoints = new List<string>();
- for (int j = 0; j < points.Count; j++)
- {
- //如果当前流程开启了剔除重复点功能,则进行剔除
- if (procedure.IsExcludeNearPoint && procedure.LastRunPoints != null && procedure.LastRunPoints.Count > 0)
- {
- //当前点的坐标数据
- double px = double.Parse(points[j][0]);
- double py = double.Parse(points[j][1]);
- double pu = double.Parse(points[j][2]);
- //检查当前点是否与上次运行的点过于接近
- //使用linq来检测上一次的点位集合中,是否存在某个点与当前点的x,y,u的差值小于设定的阈值
- bool isNear = procedure.LastRunPoints.Any(lp =>
- Math.Abs(lp[0] - px) < procedure.ExcludeNearPointThreshol &&
- Math.Abs(lp[1] - py) < procedure.ExcludeNearPointThreshol &&
- Math.Abs(lp[2] - pu) < procedure.ExcludeNearPointThreshol);
- if (isNear) continue; //如果存在接近的点,则跳过当前点,不进行添加
- }
- //单个点位内坐标之间逗号分隔
- allpoints.Add(string.Join(",", points[j]));
- //如果输出模式是AllAtOnce或者BatchedUntilTerminator,则需要检查是否达到最大点位数量限制
- if (procedure.OutputPointMode == OutputPointMode.AllAtOnce || procedure.OutputPointMode == OutputPointMode.BatchedUntilTerminator)
- {
- //如果当前总点位数量已经达到最大限制,则停止添加更多点位
- if (allpoints.Count >= procedure.OutputPointCountMax)
- {
- break;
- }
- }
- currentPoints.Add(new double[] { double.Parse(points[j][0]), double.Parse(points[j][1]), double.Parse(points[j][2]) });
- }
- //多个点位之间逗号分隔
- string pointstr = allpoints.Count + "," + string.Join(",", allpoints);
- if (procedure.OutputPointMode == OutputPointMode.UntilTerminator || procedure.OutputPointMode == OutputPointMode.BatchedUntilTerminator)
- {
- outputItems.AddRange(allpoints);
- }
- else
- {
- outputItems.Add(pointstr);
- }
- outputPointCount += allpoints.Count;
- }
- else
- {
- string itemstr = Value != null ? Value.ToString() : string.Empty;
- outputItems.Add(itemstr);
- }
- }
- }
- procedure.LastRunPoints = currentPoints;
- //关闭Feeder灯光
- if (feeder.IsConnected)
- {
- await feeder.CloseLightAsync();
- }
- await TurnOffLightAfterPhoto(procedure);
- //如果输出模式是AllAtOnce或者BatchedUntilTerminator,则分次发送数据
- if (procedure.OutputPointMode == OutputPointMode.UntilTerminator || procedure.OutputPointMode == OutputPointMode.BatchedUntilTerminator)
- {
- //将outputItems按照procedure.OutputSeparator进行拼接,得到最终返回结果
- string finalResponse = string.Join(procedure.OutputSeparator, outputItems);
- return (true, outputItems.ToArray());
- }
- else
- {
- //否则,一次发送所有数据
- //将outputItems按照procedure.OutputSeparator进行拼接,得到最终返回结果
- string finalResponse = string.Join(procedure.OutputSeparator, outputItems);
- return (true, new string[] { finalResponse });
- }
- }
- //关闭Feeder灯光
- if (feeder.IsConnected)
- {
- await feeder.CloseLightAsync();
- }
- await TurnOffLightAfterPhoto(procedure);
- SendTaskMessage(Lang.多次拍照失败, MessageLevel.Alarm);
- return (false, new string[] { "VisionFailed" });
- }
- /// <summary>
- /// 执行非 Feeder 引导的普通视觉任务,返回单字符串响应。
- /// </summary>
- public async Task<(bool IsSucceed, string Response)> ExecuteNormalVisionTaskAsync(ProcedureModel procedure, string[] items, CancellationToken cancellationToken)
- {
- // 开始执行前的时间点
- DateTime startTime = DateTime.Now;
- try
- {
- await SetLightBeforePhoto(procedure);
- // 触发命令传入的输入终端
- Dictionary<string, string> InputTerminal = null;
- // 解析触发命令传入的输入终端参数
- //判断传入参数中是否存在“SetInputs”
- if (items != null && items.Length > 1 && items[0] == "SetInputs")
- {
- InputTerminal = items.Skip(1)
- .Select(x => x.Split('='))
- .Where(y => y.Length == 2)
- .ToDictionary(z => z[0], z => z[1]);
- }
- // 机器人当前坐标
- double[] currentpos = null;
- // 判断传入参数长度是否3,并且是否都是double
- 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))
- {
- currentpos = new double[] { _x, _y, _u };
- }
- //拍照失败时,需要多次拍照
- for (int i = 0; i < procedure.FeederFailLimit; i++)
- {
- if (cancellationToken != null && cancellationToken.IsCancellationRequested)
- {
- return (false, "VisionTaskCancelled");
- }
- // 1. 执行相机拍照并运行视觉工具
- LogHelper.WriteLogInfo("开始执行相机拍照并运行视觉工具");
- bool visionSucceed = ExecutePhoto(procedure, InputTerminal, out CogToolBlockTerminalCollection outputCollection);
- if (!visionSucceed)
- {
- SendTaskMessage(Lang.视觉任务执行失败, MessageLevel.Error);
- continue;
- }
- if (!outputCollection.Contains("Found"))
- {
- SendTaskMessage(Lang.未找到视觉输出结果, MessageLevel.Error);
- return (false, "NoFoundOutput");
- }
- bool Found = (bool)(outputCollection["Found"].Value);
- if (!Found)
- {
- SendTaskMessage(Lang.拍照NG, MessageLevel.Debug);
- continue;
- }
- SendTaskMessage(Lang.拍照OK, MessageLevel.Debug);
- // 2. 获取视觉输出结果
- LogHelper.WriteLogInfo("开始获取视觉输出结果");
- var (IsSucceed, ErrMsg, Output) = GetVisionOutput(procedure, outputCollection, currentpos);
- if (!IsSucceed)
- {
- SendTaskMessage(Lang.获取视觉输出结果失败, MessageLevel.Error);
- return (false, ErrMsg);
- }
- // 3. 组织返回结果
- List<string> outputItems = new List<string>(); //多项输出结果集合
- foreach (var output in procedure.ProcedureOutputs)
- {
- if (Output.ContainsKey(output.Name))
- {
- var (IsPoint, Value) = Output[output.Name];
- if (IsPoint)
- {
- List<string[]> points = Value as List<string[]>;
- List<string> allpoints = new List<string>();
- for (int j = 0; j < points.Count; j++)
- {
- allpoints.Add(string.Join(",", points[j]));
- }
- //多个点位之间逗号分隔
- string pointstr = allpoints.Count + "," + string.Join(",", allpoints);
- outputItems.Add(pointstr);
- }
- else
- {
- string itemstr = Value != null ? Value.ToString() : string.Empty;
- outputItems.Add(itemstr);
- }
- }
- }
- //将outputItems按照procedure.OutputSeparator进行拼接,得到最终返回结果
- string finalResponse = string.Join(procedure.OutputSeparator, outputItems);
- return (true, finalResponse);
- }
- return (false, "VisionFailed");
- }
- catch (Exception ex)
- {
- SendTaskMessage(ex.Message, MessageLevel.Error);
- LogHelper.WriteLogError("执行普通视觉任务时出错!", ex);
- return (false, "Exception");
- }
- finally
- {
- await TurnOffLightAfterPhoto(procedure);
- }
- }
- /// <summary>
- /// 执行相机拍照并运行 ToolBlock,返回是否成功并通过 out 参数返回 Outputs。
- /// 该方法会发布 RenderUpdateNotification 以更新 UI。
- /// </summary>
- public bool ExecutePhoto(ProcedureModel procedure, Dictionary<string, string> InputTerminal, out CogToolBlockTerminalCollection outputCollection)
- {
- try
- {
- // 1. 采集图像
- var camera = _cameraService.GetCamera(procedure.CameraId);
- bool succed = camera.SetExposureTime(procedure.ExposureTime);
- if (!succed)
- {
- SendTaskMessage($"相机曝光设置失败!", MessageLevel.Error);
- }
- succed = camera.SetGain(procedure.Gain);
- if (!succed)
- {
- SendTaskMessage($"相机增益设置失败!", MessageLevel.Error);
- }
- DateTime nowtime = DateTime.Now;
- LogHelper.WriteLogInfo("开始采集图像");
- //var image = camera.Grab();
- var image = camera.Grab();
- if (image == null)
- {
- SendTaskMessage(Lang.图像采集失败, MessageLevel.Error);
- outputCollection = null;
- return false;
- }
- procedure.ToolBlock.Inputs["InputImage"].Value = image;
- LogHelper.WriteLogInfo($"采集图像完成;用时:{(DateTime.Now - nowtime).Milliseconds}ms");
- // 2. 为ToolBlock传入其他输入终端
- if (InputTerminal != null)
- {
- LogHelper.WriteLogInfo($"为ToolBlock传入输入终端");
- foreach (var item in InputTerminal)
- {
- if (procedure.ToolBlock.Inputs.Contains(item.Key))
- {
- LogHelper.WriteLogInfo($"传入[{item.Key}]={item.Value}");
- procedure.ToolBlock.Inputs[item.Key].Value = item.Value;
- }
- else
- {
- LogHelper.WriteLogInfo($"创建并传入[{item.Key}]={item.Value}");
- procedure.ToolBlock.Inputs.Add(new CogToolBlockTerminal(item.Key, item.Value));
- }
- }
- }
- // 3. 运行视觉工具
- LogHelper.WriteLogInfo("开始运行视觉工具");
- procedure.ToolBlock.Run(); //运行ToolBlock
- if (procedure.ToolBlock.RunStatus.Result == CogToolResultConstants.Accept)
- {
- SendTaskMessage(Lang.视觉流程执行耗时.Replace("{0}", procedure.Name).Replace("{1}", $"{procedure.ToolBlock.RunStatus.ProcessingTime:F1}"), MessageLevel.Info);
- outputCollection = procedure.ToolBlock.Outputs; //获取输出终端集合
- DatabaseHelper.AddCameraRecords(_productService.GetCurrentProduct().Name, procedure.Name, outputCollection);
- ICogRecord record = null;
- foreach (CogToolBlockTerminal item in outputCollection)
- {
- if (item.Value is ICogRecord)
- record = item.Value as ICogRecord;
- }
- bool Found = (bool)(outputCollection["Found"].Value);
- //获取图片存储的图片文件名
- string imgName = string.Empty;
- if (procedure.IsSaveImage && !string.IsNullOrEmpty(procedure.ImageFileNameFormat))
- {
- // 创建模板,使用 {变量名:格式} 语法
- var template = new FileNameTemplate(procedure.ImageFileNameFormat);
- // 注册变量
- template.RegisterVariable("ProductSN", () => _productService.CurrentProductCode);
- template.RegisterVariable("CameraName", () => procedure.CameraName);
- template.RegisterVariable("ShotCount", () => 1);
- template.RegisterVariable("Result", () => Found ? "OK" : "NG");
- template.RegisterVariable("DateTime", () => DateTime.Now);
- // 生成文件名
- imgName = template.Generate();
- }
- _eventAggregator.GetEvent<RenderUpdateNotification>().Publish(new ShowRender()
- {
- Id = procedure.Id,
- DisplayName = procedure.DisplayName,
- //Image = (ICogImage)procedure.ToolBlock.Outputs["OriImage"].Value,
- //Image = (ICogImage)procedure.ToolBlock.Inputs["InputImage"].Value,
- Image = image,
- Graphic = outputCollection["Graphic"].Value as CogGraphicCollection,
- Record = record,
- Result = Found,
- IsShow = true,
- IsSaveImage = procedure.IsSaveImage,
- SaveImageModel = procedure.SaveImageModel,
- SaveImagePathModel = procedure.SaveImagePathModel,
- SavePath = procedure.SavePath,
- IsCompress = procedure.IsCompress,
- ProceductName = procedure.Name,
- ImageFileName = imgName,
- Is3DModel=true
- });
- return true;
- }
- else
- {
- SendTaskMessage(Lang.视觉流程执行出错耗时.Replace("{0}", procedure.Name).Replace("{1}", $"{procedure.ToolBlock.RunStatus.ProcessingTime:F1}"), MessageLevel.Error);
- SendTaskMessage(procedure.ToolBlock.RunStatus.Message, MessageLevel.Error);
- outputCollection = null;
- //获取图片存储的图片文件名
- string imgName = string.Empty;
- if (procedure.IsSaveImage && !string.IsNullOrEmpty(procedure.ImageFileNameFormat))
- {
- // 创建模板,使用 {变量名:格式} 语法
- var template = new FileNameTemplate(procedure.ImageFileNameFormat);
- // 注册变量
- template.RegisterVariable("ProductSN", () => _productService.CurrentProductCode);
- template.RegisterVariable("CameraName", () => procedure.CameraName);
- template.RegisterVariable("ShotCount", () => 1);
- template.RegisterVariable("Result", () => "NG");
- template.RegisterVariable("DateTime", () => DateTime.Now);
- // 生成文件名
- imgName = template.Generate();
- }
- _eventAggregator.GetEvent<RenderUpdateNotification>().Publish(new ShowRender()
- {
- Id = procedure.Id,
- DisplayName = procedure.DisplayName,
- //Image = (ICogImage)procedure.ToolBlock.Outputs["OriImage"].Value,
- //Image = (ICogImage)procedure.ToolBlock.Inputs["InputImage"].Value,
- Image = image,
- Graphic = new CogGraphicCollection(),
- Result = false,
- IsShow = true,
- IsSaveImage = procedure.IsSaveImage,
- SaveImageModel = procedure.SaveImageModel,
- SaveImagePathModel = procedure.SaveImagePathModel,
- SavePath = procedure.SavePath,
- ProceductName = procedure.Name,
- ImageFileName = imgName,
- Is3DModel = true
- });
- return false;
- }
- }
- catch (Exception ex)
- {
- SendTaskMessage(ex.Message, MessageLevel.Error);
- LogHelper.WriteLogError("执行相机取图并执行视觉工具组时出错!", ex);
- outputCollection = null;
- return false;
- }
- }
- /// <summary>
- /// 执行相机拍照并运行 ToolBlock,返回是否成功并通过 out 参数返回 Outputs。
- /// 该方法会发布 RenderUpdateNotification 以更新 UI。
- /// </summary>
- public bool ExecutePhoto2(ProcedureModel procedure, Dictionary<string, string> InputTerminal, out CogToolBlockTerminalCollection outputCollection)
- {
- try
- {
- // 1. 采集图像
- var camera = _cameraService.GetCamera(procedure.CameraId);
- bool succed = camera.SetExposureTime(procedure.ExposureTime);
- if (!succed)
- {
- SendTaskMessage($"相机曝光设置失败!", MessageLevel.Error);
- }
- succed = camera.SetGain(procedure.Gain);
- if (!succed)
- {
- SendTaskMessage($"相机增益设置失败!", MessageLevel.Error);
- }
- DateTime nowtime = DateTime.Now;
- LogHelper.WriteLogInfo("开始采集图像");
- //var image = camera.Grab();
- var image = camera.Grab();
- if (image == null)
- {
- SendTaskMessage(Lang.图像采集失败, MessageLevel.Error);
- outputCollection = null;
- return false;
- }
- procedure.ToolBlock.Inputs["InputImage"].Value = image;
- LogHelper.WriteLogInfo($"采集图像完成;用时:{(DateTime.Now - nowtime).Milliseconds}ms");
- // 2. 为ToolBlock传入其他输入终端
- if (InputTerminal != null)
- {
- LogHelper.WriteLogInfo($"为ToolBlock传入输入终端");
- foreach (var item in InputTerminal)
- {
- if (procedure.ToolBlock.Inputs.Contains(item.Key))
- {
- LogHelper.WriteLogInfo($"传入[{item.Key}]={item.Value}");
- procedure.ToolBlock.Inputs[item.Key].Value = item.Value;
- }
- else
- {
- LogHelper.WriteLogInfo($"创建并传入[{item.Key}]={item.Value}");
- procedure.ToolBlock.Inputs.Add(new CogToolBlockTerminal(item.Key, item.Value));
- }
- }
- }
- // 3. 运行视觉工具
- LogHelper.WriteLogInfo("开始运行视觉工具");
- procedure.ToolBlock.Run(); //运行ToolBlock
- if (procedure.ToolBlock.RunStatus.Result == CogToolResultConstants.Accept)
- {
- SendTaskMessage(Lang.视觉流程执行耗时.Replace("{0}", procedure.Name).Replace("{1}", $"{procedure.ToolBlock.RunStatus.ProcessingTime:F1}"), MessageLevel.Info);
- outputCollection = procedure.ToolBlock.Outputs; //获取输出终端集合
- DatabaseHelper.AddCameraRecords(_productService.GetCurrentProduct().Name, procedure.Name, outputCollection);
- ICogRecord record = null;
- foreach (CogToolBlockTerminal item in outputCollection)
- {
- if (item.Value is ICogRecord)
- record = item.Value as ICogRecord;
- }
- bool Found = (bool)(outputCollection["Found"].Value);
- //获取图片存储的图片文件名
- string imgName = string.Empty;
- if (procedure.IsSaveImage && !string.IsNullOrEmpty(procedure.ImageFileNameFormat))
- {
- // 创建模板,使用 {变量名:格式} 语法
- var template = new FileNameTemplate(procedure.ImageFileNameFormat);
- // 注册变量
- template.RegisterVariable("ProductSN", () => _productService.CurrentProductCode);
- template.RegisterVariable("CameraName", () => procedure.CameraName);
- template.RegisterVariable("ShotCount", () => 1);
- template.RegisterVariable("Result", () => Found ? "OK" : "NG");
- template.RegisterVariable("DateTime", () => DateTime.Now);
- // 生成文件名
- imgName = template.Generate();
- }
- _eventAggregator.GetEvent<RenderUpdateNotification>().Publish(new ShowRender()
- {
- Id = procedure.Id,
- DisplayName = procedure.DisplayName,
- //Image = (ICogImage)procedure.ToolBlock.Outputs["OriImage"].Value,
- Image = (ICogImage)procedure.ToolBlock.Inputs["InputImage"].Value,
- Graphic = outputCollection["Graphic"].Value as CogGraphicCollection,
- Record = record,
- Result = Found,
- IsShow = true,
- IsSaveImage = procedure.IsSaveImage,
- SaveImageModel = procedure.SaveImageModel,
- SaveImagePathModel = procedure.SaveImagePathModel,
- SavePath = procedure.SavePath,
- IsCompress = procedure.IsCompress,
- ProceductName = procedure.Name,
- ImageFileName = imgName,
- Is3DModel=false
- });
- return true;
- }
- else
- {
- SendTaskMessage(Lang.视觉流程执行出错耗时.Replace("{0}", procedure.Name).Replace("{1}", $"{procedure.ToolBlock.RunStatus.ProcessingTime:F1}"), MessageLevel.Error);
- SendTaskMessage(procedure.ToolBlock.RunStatus.Message, MessageLevel.Error);
- outputCollection = null;
- //获取图片存储的图片文件名
- string imgName = string.Empty;
- if (procedure.IsSaveImage && !string.IsNullOrEmpty(procedure.ImageFileNameFormat))
- {
- // 创建模板,使用 {变量名:格式} 语法
- var template = new FileNameTemplate(procedure.ImageFileNameFormat);
- // 注册变量
- template.RegisterVariable("ProductSN", () => _productService.CurrentProductCode);
- template.RegisterVariable("CameraName", () => procedure.CameraName);
- template.RegisterVariable("ShotCount", () => 1);
- template.RegisterVariable("Result", () => "NG");
- template.RegisterVariable("DateTime", () => DateTime.Now);
- // 生成文件名
- imgName = template.Generate();
- }
- _eventAggregator.GetEvent<RenderUpdateNotification>().Publish(new ShowRender()
- {
- Id = procedure.Id,
- DisplayName = procedure.DisplayName,
- //Image = (ICogImage)procedure.ToolBlock.Outputs["OriImage"].Value,
- Image = (ICogImage)procedure.ToolBlock.Inputs["InputImage"].Value,
- Graphic = new CogGraphicCollection(),
- Result = false,
- IsShow = true,
- IsSaveImage = procedure.IsSaveImage,
- SaveImageModel = procedure.SaveImageModel,
- SaveImagePathModel = procedure.SaveImagePathModel,
- SavePath = procedure.SavePath,
- ProceductName = procedure.Name,
- ImageFileName = imgName,
- Is3DModel=false
- });
- return false;
- }
- }
- catch (Exception ex)
- {
- SendTaskMessage(ex.Message, MessageLevel.Error);
- LogHelper.WriteLogError("执行相机取图并执行视觉工具组时出错!", ex);
- outputCollection = null;
- return false;
- }
- }
- /// <summary>
- /// 执行相机拍照并运行 ToolBlock,返回是否成功并通过 out 参数返回 Outputs。
- /// 该方法会发布 RenderUpdateNotification 以更新 UI。
- /// </summary>
- public bool ExecutePhoto(ProcedureModel procedure,ICogImage[] imges,Dictionary<string, string> InputTerminal, out CogToolBlockTerminalCollection outputCollection,bool is3dmodel)
- {
- try
- {
-
- procedure.ToolBlock.Inputs["InputImage"].Value = imges[0];
-
- // 2. 为ToolBlock传入其他输入终端
- if (InputTerminal != null)
- {
- LogHelper.WriteLogInfo($"为ToolBlock传入输入终端");
- foreach (var item in InputTerminal)
- {
- if (procedure.ToolBlock.Inputs.Contains(item.Key))
- {
- LogHelper.WriteLogInfo($"传入[{item.Key}]={item.Value}");
- procedure.ToolBlock.Inputs[item.Key].Value = item.Value;
- }
- else
- {
- LogHelper.WriteLogInfo($"创建并传入[{item.Key}]={item.Value}");
- procedure.ToolBlock.Inputs.Add(new CogToolBlockTerminal(item.Key, item.Value));
- }
- }
- }
- // 3. 运行视觉工具
- LogHelper.WriteLogInfo("开始运行视觉工具");
- procedure.ToolBlock.Run(); //运行ToolBlock
- if (procedure.ToolBlock.RunStatus.Result == CogToolResultConstants.Accept)
- {
- SendTaskMessage(Lang.视觉流程执行耗时.Replace("{0}", procedure.Name).Replace("{1}", $"{procedure.ToolBlock.RunStatus.ProcessingTime:F1}"), MessageLevel.Info);
- outputCollection = procedure.ToolBlock.Outputs; //获取输出终端集合
- DatabaseHelper.AddCameraRecords(_productService.GetCurrentProduct().Name, procedure.Name, outputCollection);
- ICogRecord record = null;
- foreach (CogToolBlockTerminal item in outputCollection)
- {
- if (item.Value is ICogRecord)
- record = item.Value as ICogRecord;
- }
- bool Found = (bool)(outputCollection["Found"].Value);
- //获取图片存储的图片文件名
- string imgName = string.Empty;
- if (procedure.IsSaveImage && !string.IsNullOrEmpty(procedure.ImageFileNameFormat))
- {
- // 创建模板,使用 {变量名:格式} 语法
- var template = new FileNameTemplate(procedure.ImageFileNameFormat);
- // 注册变量
- template.RegisterVariable("ProductSN", () => _productService.CurrentProductCode);
- template.RegisterVariable("CameraName", () => procedure.CameraName);
- template.RegisterVariable("ShotCount", () => 1);
- template.RegisterVariable("Result", () => Found ? "OK" : "NG");
- template.RegisterVariable("DateTime", () => DateTime.Now);
- // 生成文件名
- imgName = template.Generate();
- }
- if(is3dmodel==true)
- {
- _eventAggregator.GetEvent<RenderUpdateNotification>().Publish(new ShowRender()
- {
- Id = procedure.DisplayId,
- DisplayName = procedure.DisplayName,
- //Image = (ICogImage)procedure.ToolBlock.Outputs["OriImage"].Value,
- Image = (ICogImage)procedure.ToolBlock.Inputs["InputImage"].Value,
- Graphic = outputCollection["Graphic"].Value as CogGraphicCollection,
- Record = record,
- Result = Found,
- IsShow = true,
- IsSaveImage = procedure.IsSaveImage,
- SaveImageModel = procedure.SaveImageModel,
- SaveImagePathModel = procedure.SaveImagePathModel,
- SavePath = procedure.SavePath,
- IsCompress = procedure.IsCompress,
- ProceductName = procedure.Name,
- ImageFileName = imgName,
- Is3DModel = is3dmodel,
- RangeImage = (CogImage16Range)procedure.ToolBlock.Outputs["RangeImage"].Value,
- GreyImage = (CogImage16Grey)procedure.ToolBlock.Outputs["GreyImage"].Value
- });
- }
- else
- {
- _eventAggregator.GetEvent<RenderUpdateNotification>().Publish(new ShowRender()
- {
- Id = procedure.DisplayId,
- DisplayName = procedure.DisplayName,
- //Image = (ICogImage)procedure.ToolBlock.Outputs["OriImage"].Value,
- Image = (ICogImage)procedure.ToolBlock.Inputs["InputImage"].Value,
- Graphic = outputCollection["Graphic"].Value as CogGraphicCollection,
- Record = record,
- Result = Found,
- IsShow = true,
- IsSaveImage = procedure.IsSaveImage,
- SaveImageModel = procedure.SaveImageModel,
- SaveImagePathModel = procedure.SaveImagePathModel,
- SavePath = procedure.SavePath,
- IsCompress = procedure.IsCompress,
- ProceductName = procedure.Name,
- ImageFileName = imgName,
- Is3DModel = is3dmodel
-
- });
- }
- return true;
- }
- else
- {
- SendTaskMessage(Lang.视觉流程执行出错耗时.Replace("{0}", procedure.Name).Replace("{1}", $"{procedure.ToolBlock.RunStatus.ProcessingTime:F1}"), MessageLevel.Error);
- SendTaskMessage(procedure.ToolBlock.RunStatus.Message, MessageLevel.Error);
- outputCollection = null;
- //获取图片存储的图片文件名
- string imgName = string.Empty;
- if (procedure.IsSaveImage && !string.IsNullOrEmpty(procedure.ImageFileNameFormat))
- {
- // 创建模板,使用 {变量名:格式} 语法
- var template = new FileNameTemplate(procedure.ImageFileNameFormat);
- // 注册变量
- template.RegisterVariable("ProductSN", () => _productService.CurrentProductCode);
- template.RegisterVariable("CameraName", () => procedure.CameraName);
- template.RegisterVariable("ShotCount", () => 1);
- template.RegisterVariable("Result", () => "NG");
- template.RegisterVariable("DateTime", () => DateTime.Now);
- // 生成文件名
- imgName = template.Generate();
- }
- if(is3dmodel==true)
- {
- _eventAggregator.GetEvent<RenderUpdateNotification>().Publish(new ShowRender()
- {
- Id = procedure.Id,
- DisplayName = procedure.DisplayName,
- //Image = (ICogImage)procedure.ToolBlock.Outputs["OriImage"].Value,
- Image = (ICogImage)procedure.ToolBlock.Inputs["InputImage"].Value,
- Graphic = new CogGraphicCollection(),
- Result = false,
- IsShow = true,
- IsSaveImage = procedure.IsSaveImage,
- SaveImageModel = procedure.SaveImageModel,
- SaveImagePathModel = procedure.SaveImagePathModel,
- SavePath = procedure.SavePath,
- ProceductName = procedure.Name,
- ImageFileName = imgName,
- Is3DModel = is3dmodel,
- RangeImage = (CogImage16Range)procedure.ToolBlock.Outputs["RangeImage"].Value,
- GreyImage = (CogImage16Grey)procedure.ToolBlock.Outputs["GreyImage"].Value
- });
- }
- else
- {
- _eventAggregator.GetEvent<RenderUpdateNotification>().Publish(new ShowRender()
- {
- Id = procedure.Id,
- DisplayName = procedure.DisplayName,
- //Image = (ICogImage)procedure.ToolBlock.Outputs["OriImage"].Value,
- Image = (ICogImage)procedure.ToolBlock.Inputs["InputImage"].Value,
- Graphic = new CogGraphicCollection(),
- Result = false,
- IsShow = true,
- IsSaveImage = procedure.IsSaveImage,
- SaveImageModel = procedure.SaveImageModel,
- SaveImagePathModel = procedure.SaveImagePathModel,
- SavePath = procedure.SavePath,
- ProceductName = procedure.Name,
- ImageFileName = imgName,
- Is3DModel = is3dmodel
- });
- }
- return false;
- }
- }
- catch (Exception ex)
- {
- SendTaskMessage(ex.Message, MessageLevel.Error);
- LogHelper.WriteLogError("执行相机取图并执行视觉工具组时出错!", ex);
- outputCollection = null;
- return false;
- }
- }
- /// <summary>
- /// 采集图像
- /// </summary>
- /// <param name="procedure"></param>
- /// <returns></returns>
- public async Task <(bool IsSucceed, ICogImage[] Image, string Msg)> ExecuteGrabImageAsync(ProcedureModel procedure)
- {
- try
- {
- var sysConfig = _configService.GetSystemConfiguration();
- if(sysConfig.TurnOnAllLightUse==false)
- {
- await SetLightBeforePhoto(procedure);
- }
-
-
-
- // 1. 采集图像
- var camera = _cameraService.GetCamera(procedure.CameraId);
- bool succed = camera.SetExposureTime(procedure.ExposureTime);
- if (!succed)
- {
- SendTaskMessage($"相机曝光设置失败!", MessageLevel.Error);
- }
- succed = camera.SetGain(procedure.Gain);
- if (!succed)
- {
- SendTaskMessage($"相机增益设置失败!", MessageLevel.Error);
- }
- DateTime nowtime = DateTime.Now;
- LogHelper.WriteLogInfo("开始采集图像");
- //var image = camera.Grab();
- var image = camera.Grab();
- LogHelper.WriteLogInfo($"采集图像完成;用时:{(DateTime.Now - nowtime).Milliseconds}ms");
- if (image == null)
- {
- SendTaskMessage(Lang.图像采集失败, MessageLevel.Error);
- return (false,null,"图像采集失败");
- }
- return (true, new ICogImage[] { image }, "成功");
- }
- catch (Exception ex)
- {
- LogHelper.WriteLogError("采集图像失败!",ex);
- return (false, null, "图像采集失败");
- }
- }
- /// <summary>
- /// 执行相机拍照获取单个点位结果
- /// </summary>
- /// <param name="procedure"></param>
- /// <param name="InputTerminal"></param>
- /// <param name="robotCoord"></param>
- /// <param name="cancellationToken"></param>
- /// <returns></returns>
- public async Task<(bool IsSucceed, string[] Items, double Count)> ExecutePhotoGetSinglePoint1(ProcedureModel procedure, ICogImage[] imges, Dictionary<string, string> InputTerminal, double[] robotCoord, CancellationToken cancellationToken,bool is3dmodel)
- {
- DateTime nowtime = DateTime.Now;
- try
- {
- //拍照失败时,需要多次拍照
- //for (int i = 0; i < procedure.FeederFailLimit; i++)
- for (int i = 0; i < 1; i++)
- {
- SendTaskMessage(Lang.开始执行视觉流程.Replace("{0}", $"{i + 1}").Replace("{1}", procedure.Name), MessageLevel.Info);
- // 1. 执行相机拍照并运行视觉工具
- bool visionSucceed = ExecutePhoto(procedure, imges, InputTerminal, out CogToolBlockTerminalCollection outputCollection, is3dmodel);
- if (!visionSucceed)
- {
- SendTaskMessage(Lang.视觉任务执行失败, MessageLevel.Error);
- continue;
- }
- if (!outputCollection.Contains("Found"))
- {
- SendTaskMessage(Lang.未找到视觉输出结果, MessageLevel.Error);
- return (false, null, 0);
- }
- // 2. 获取视觉输出结果
- //bool Found = (bool)(outputCollection["Found"].Value);
- //if (!Found)
- //{
- // SendTaskMessage(Lang.拍照NG, MessageLevel.Debug);
- // continue;
- //}
- SendTaskMessage(Lang.拍照OK, MessageLevel.Debug);
- int Count = (int)(outputCollection["Count"].Value);
- string[] PhotoRes = new string[100];
- for (int k = 1; k <= Count; k++)
- {
- PhotoRes[k] = (string)(outputCollection[$"dis{k}"].Value);
- //PhotoRes[k] = "222";
- }
- // 3. 获取视觉输出结果
- LogHelper.WriteLogInfo("开始获取视觉输出结果");
- /*
- //获取相机校准
- var calib = _calibrationService.GetCalibration(procedure.CalibrationId);
- string points = (string)(outputCollection["Point"].Value);
- string[] strpoints = points.Split(';');
- //先将pos按照逗号进行分隔,拿到数组
- var posParts = strpoints[0].Split(',');
- double _pixel_x = double.Parse(posParts[0]);
- double _pixel_y = double.Parse(posParts[1]);
- double _pixel_u = double.Parse(posParts[2]);
- //转换点位-像素转换成机器人绝对坐标
- var calibResult = _calibrationService.ConvertPixelToPosition((_pixel_x, _pixel_y, _pixel_u), robotCoord, calib, RobotBrand.XYZ_Platform);
- if (!calibResult.IsSucceed)
- {
- return (false, 0, 0, 0);
- }
- return (true, calibResult.X, calibResult.Y, calibResult.U);
- */
- return (true, PhotoRes, Count);
- }
- SendTaskMessage(Lang.多次拍照失败, MessageLevel.Alarm);
- return (false, null, 0);
- }
- catch (Exception ex)
- {
- LogHelper.WriteLogError("执行相机取图并获取单点位时出错!", ex);
- return (false, null, 0);
- }
- finally
- {
- var sysConfig = _configService.GetSystemConfiguration();
- if (sysConfig.TurnOffAllLightUse == false)
- {
- await TurnOffLightAfterPhoto(procedure);
- }
- }
- }
- /// <summary>
- /// 执行相机拍照获取单个点位结果
- /// </summary>
- /// <param name="procedure"></param>
- /// <param name="InputTerminal"></param>
- /// <param name="robotCoord"></param>
- /// <param name="cancellationToken"></param>
- /// <returns></returns>
- public async Task<(bool IsSucceed, string X, double Y, double U)> ExecutePhotoGetSinglePoint2(ProcedureModel procedure, Dictionary<string, string> InputTerminal, double[] robotCoord, CancellationToken cancellationToken)
- {
- DateTime nowtime = DateTime.Now;
- var sysConfig = _configService.GetSystemConfiguration();
- if (sysConfig.TurnOnAllLightUse == false)
- {
- await SetLightBeforePhoto(procedure);
- }
-
- try
- {
- //拍照失败时,需要多次拍照
- for (int i = 0; i < procedure.FeederFailLimit; i++)
- {
- SendTaskMessage(Lang.开始执行视觉流程.Replace("{0}", $"{i + 1}").Replace("{1}", procedure.Name), MessageLevel.Info);
- // 1. 执行相机拍照并运行视觉工具
- bool visionSucceed = ExecutePhoto2(procedure, InputTerminal, out CogToolBlockTerminalCollection outputCollection);
- if (!visionSucceed)
- {
- SendTaskMessage(Lang.视觉任务执行失败, MessageLevel.Error);
- continue;
- }
- if (!outputCollection.Contains("Found"))
- {
- SendTaskMessage(Lang.未找到视觉输出结果, MessageLevel.Error);
- return (false, null, 0, 0);
- }
- // 2. 获取视觉输出结果
- bool Found = (bool)(outputCollection["Found"].Value);
- if (!Found)
- {
- SendTaskMessage(Lang.拍照NG, MessageLevel.Debug);
- continue;
- }
- string SnCode = (string)(outputCollection["SnCode"].Value);
- SendTaskMessage(Lang.拍照OK, MessageLevel.Debug);
- // 3. 获取视觉输出结果
- LogHelper.WriteLogInfo("开始获取视觉输出结果");
- /*
- //获取相机校准
- var calib = _calibrationService.GetCalibration(procedure.CalibrationId);
- string points = (string)(outputCollection["Point"].Value);
- string[] strpoints = points.Split(';');
- //先将pos按照逗号进行分隔,拿到数组
- var posParts = strpoints[0].Split(',');
- double _pixel_x = double.Parse(posParts[0]);
- double _pixel_y = double.Parse(posParts[1]);
- double _pixel_u = double.Parse(posParts[2]);
- //转换点位-像素转换成机器人绝对坐标
- var calibResult = _calibrationService.ConvertPixelToPosition((_pixel_x, _pixel_y, _pixel_u), robotCoord, calib, RobotBrand.XYZ_Platform);
- if (!calibResult.IsSucceed)
- {
- return (false, 0, 0, 0);
- }
- return (true, calibResult.X, calibResult.Y, calibResult.U);
- */
- return (true, SnCode, 0, 0);
- }
- SendTaskMessage(Lang.多次拍照失败, MessageLevel.Alarm);
- return (false, null, 0, 0);
- }
- catch (Exception ex)
- {
- LogHelper.WriteLogError("执行相机取图并获取单点位时出错!", ex);
- return (false, null, 0, 0);
- }
- finally
- {
- if (sysConfig.TurnOffAllLightUse == false)
- {
- await TurnOffLightAfterPhoto(procedure);
- }
- }
- }
- /// <summary>
- /// 执行相机拍照并运行 ToolBlock,返回是否成功并通过 out 参数返回 Outputs、图像和图形集合。
- /// </summary>
- /// <param name="procedure"></param>
- /// <param name="InputTerminal"></param>
- /// <param name="outputCollection"></param>
- /// <param name="outImage"></param>
- /// <param name="outGraphicCollection"></param>
- /// <returns></returns>
- public bool ExecutePhotoEx(ProcedureModel procedure, Dictionary<string, string> InputTerminal, out CogToolBlockTerminalCollection outputCollection,out ICogImage outImage,out CogGraphicCollection outGraphicCollection)
- {
- outImage = null;
- outGraphicCollection = null;
- try
- {
-
- // 1. 采集图像
- var camera = _cameraService.GetCamera(procedure.CameraId);
- bool succed = camera.SetExposureTime(procedure.ExposureTime);
- if (!succed)
- {
- SendTaskMessage($"相机曝光设置失败!", MessageLevel.Error);
- }
- succed = camera.SetGain(procedure.Gain);
- if (!succed)
- {
- SendTaskMessage($"相机增益设置失败!", MessageLevel.Error);
- }
- DateTime nowtime = DateTime.Now;
- LogHelper.WriteLogInfo("开始采集图像");
- var image = camera.Grab();
- if (image == null)
- {
- SendTaskMessage(Lang.图像采集失败, MessageLevel.Error);
- outputCollection = null;
- return false;
- }
- outImage= image;
- procedure.ToolBlock.Inputs["InputImage"].Value = image;
- LogHelper.WriteLogInfo($"采集图像完成;用时:{(DateTime.Now - nowtime).Milliseconds}ms");
- // 2. 为ToolBlock传入其他输入终端
- if (InputTerminal != null)
- {
- LogHelper.WriteLogInfo($"为ToolBlock传入输入终端");
- foreach (var item in InputTerminal)
- {
- if (procedure.ToolBlock.Inputs.Contains(item.Key))
- {
- LogHelper.WriteLogInfo($"传入[{item.Key}]={item.Value}");
- procedure.ToolBlock.Inputs[item.Key].Value = item.Value;
- }
- else
- {
- LogHelper.WriteLogInfo($"创建并传入[{item.Key}]={item.Value}");
- procedure.ToolBlock.Inputs.Add(new CogToolBlockTerminal(item.Key, item.Value));
- }
- }
- }
- // 3. 运行视觉工具
- LogHelper.WriteLogInfo("开始运行视觉工具");
- procedure.ToolBlock.Run(); //运行ToolBlock
- if (procedure.ToolBlock.RunStatus.Result == CogToolResultConstants.Accept)
- {
- SendTaskMessage(Lang.视觉流程执行耗时.Replace("{0}", procedure.Name).Replace("{1}", $"{procedure.ToolBlock.RunStatus.ProcessingTime:F1}"), MessageLevel.Info);
- outputCollection = procedure.ToolBlock.Outputs; //获取输出终端集合
- DatabaseHelper.AddCameraRecords(_productService.GetCurrentProduct().Name, procedure.Name, outputCollection);
- ICogRecord record = null;
- foreach (CogToolBlockTerminal item in outputCollection)
- {
- if (item.Value is ICogRecord)
- record = item.Value as ICogRecord;
- }
- outGraphicCollection= outputCollection["Graphic"].Value as CogGraphicCollection;
- return true;
- }
- else
- {
- SendTaskMessage(Lang.视觉流程执行出错耗时.Replace("{0}", procedure.Name).Replace("{1}", $"{procedure.ToolBlock.RunStatus.ProcessingTime:F1}"), MessageLevel.Error);
- SendTaskMessage(procedure.ToolBlock.RunStatus.Message, MessageLevel.Error);
- outputCollection = null;
- outGraphicCollection = outputCollection["Graphic"].Value as CogGraphicCollection;
- return false;
- }
- }
- catch (Exception ex)
- {
- SendTaskMessage(ex.Message, MessageLevel.Error);
- LogHelper.WriteLogError("执行相机取图并执行视觉工具组时出错!", ex);
- outputCollection = null;
- return false;
- }
- }
- /// <summary>
- /// 执行相机拍照获取单个点位结果
- /// </summary>
- /// <param name="procedure"></param>
- /// <param name="InputTerminal"></param>
- /// <param name="robotCoord"></param>
- /// <param name="cancellationToken"></param>
- /// <returns></returns>
- public async Task<(bool IsSucceed, double X, double Y, double U)> ExecutePhotoGetSinglePoint(ProcedureModel procedure, Dictionary<string, string> InputTerminal, double[] robotCoord, CancellationToken cancellationToken)
- {
- DateTime nowtime = DateTime.Now;
- await SetLightBeforePhoto(procedure);
- try
- {
- //拍照失败时,需要多次拍照
- //for (int i = 0; i < procedure.FeederFailLimit; i++)
- for (int i = 0; i < 1; i++)
- {
- SendTaskMessage(Lang.开始执行视觉流程.Replace("{0}", $"{i + 1}").Replace("{1}", procedure.Name), MessageLevel.Info);
- //1.执行相机拍照并运行视觉工具
- bool visionSucceed = ExecutePhoto(procedure, InputTerminal, out CogToolBlockTerminalCollection outputCollection);
- if (!visionSucceed)
- {
- SendTaskMessage(Lang.视觉任务执行失败, MessageLevel.Error);
- continue;
- }
- if (!outputCollection.Contains("Found"))
- {
- SendTaskMessage(Lang.未找到视觉输出结果, MessageLevel.Error);
- return (false, 0, 0, 0);
- }
- // 2. 获取视觉输出结果
- bool Found = (bool)(outputCollection["Found"].Value);
- if (!Found)
- {
- SendTaskMessage(Lang.拍照NG, MessageLevel.Debug);
- continue;
- }
- SendTaskMessage(Lang.拍照OK, MessageLevel.Debug);
- //// 3. 获取视觉输出结果
- //LogHelper.WriteLogInfo("开始获取视觉输出结果");
- ////获取相机校准
- //var calib = _calibrationService.GetCalibration(procedure.CalibrationId);
- //string points = (string)(outputCollection["Point"].Value);
- //string[] strpoints = points.Split(';');
- ////先将pos按照逗号进行分隔,拿到数组
- //var posParts = strpoints[0].Split(',');
- //double _pixel_x = double.Parse(posParts[0]);
- //double _pixel_y = double.Parse(posParts[1]);
- //double _pixel_u = double.Parse(posParts[2]);
- ////转换点位-像素转换成机器人绝对坐标
- //var calibResult = _calibrationService.ConvertPixelToPosition((_pixel_x, _pixel_y, _pixel_u), robotCoord, calib, RobotBrand.XYZ_Platform);
- //if (!calibResult.IsSucceed)
- //{
- // return (false, 0, 0, 0);
- //}
- return (true, 0,0, 0);
- }
- SendTaskMessage(Lang.多次拍照失败, MessageLevel.Alarm);
- return (false, 0, 0, 0);
- }
- catch (Exception ex)
- {
- LogHelper.WriteLogError("执行相机取图并获取单点位时出错!", ex);
- return (false, 0, 0, 0);
- }
- finally
- {
- await TurnOffLightAfterPhoto(procedure);
- }
- }
- /// <summary>
- /// 执行相机拍照获取单个点位结果
- /// </summary>
- /// <param name="procedure"></param>
- /// <param name="InputTerminal"></param>
- /// <param name="robotCoord"></param>
- /// <param name="cancellationToken"></param>
- /// <returns></returns>
- public async Task<(bool IsSucceed, string[] Items, double Count)> ExecutePhotoGetSinglePoint1(ProcedureModel procedure, Dictionary<string, string> InputTerminal, double[] robotCoord, CancellationToken cancellationToken)
- {
- DateTime nowtime = DateTime.Now;
- var sysConfig = _configService.GetSystemConfiguration();
- if (sysConfig.TurnOnAllLightUse == false)
- {
- await SetLightBeforePhoto(procedure);
- }
- try
- {
- //拍照失败时,需要多次拍照
- //for (int i = 0; i < procedure.FeederFailLimit; i++)
- for (int i = 0; i < 1; i++)
- {
- SendTaskMessage(Lang.开始执行视觉流程.Replace("{0}", $"{i + 1}").Replace("{1}", procedure.Name), MessageLevel.Info);
- // 1. 执行相机拍照并运行视觉工具
- bool visionSucceed = ExecutePhoto(procedure, InputTerminal, out CogToolBlockTerminalCollection outputCollection);
- if (!visionSucceed)
- {
- SendTaskMessage(Lang.视觉任务执行失败, MessageLevel.Error);
- continue;
- }
- //if (!outputCollection.Contains("Found"))
- //{
- // SendTaskMessage(Lang.未找到视觉输出结果, MessageLevel.Error);
- // return (false, null, 0);
- //}
- // 2. 获取视觉输出结果
- //bool Found = (bool)(outputCollection["Found"].Value);
- //if (!Found)
- //{
- // SendTaskMessage(Lang.拍照NG, MessageLevel.Debug);
- // continue;
- //}
- SendTaskMessage(Lang.拍照OK, MessageLevel.Debug);
- int Count = (int)(outputCollection["Count"].Value);
- string[] PhotoRes = new string[100];
- for (int k = 1; k <= Count; k++)
- {
- PhotoRes[k] = (string)(outputCollection[$"dis{k}"].Value);
- //PhotoRes[k] = "222";
- }
- // 3. 获取视觉输出结果
- LogHelper.WriteLogInfo("开始获取视觉输出结果");
- /*
- //获取相机校准
- var calib = _calibrationService.GetCalibration(procedure.CalibrationId);
- string points = (string)(outputCollection["Point"].Value);
- string[] strpoints = points.Split(';');
- //先将pos按照逗号进行分隔,拿到数组
- var posParts = strpoints[0].Split(',');
- double _pixel_x = double.Parse(posParts[0]);
- double _pixel_y = double.Parse(posParts[1]);
- double _pixel_u = double.Parse(posParts[2]);
- //转换点位-像素转换成机器人绝对坐标
- var calibResult = _calibrationService.ConvertPixelToPosition((_pixel_x, _pixel_y, _pixel_u), robotCoord, calib, RobotBrand.XYZ_Platform);
- if (!calibResult.IsSucceed)
- {
- return (false, 0, 0, 0);
- }
- return (true, calibResult.X, calibResult.Y, calibResult.U);
- */
- return (true, PhotoRes, Count);
- }
- SendTaskMessage(Lang.多次拍照失败, MessageLevel.Alarm);
- return (false, null, 0);
- }
- catch (Exception ex)
- {
- LogHelper.WriteLogError("执行相机取图并获取单点位时出错!", ex);
- return (false, null, 0);
- }
- finally
- {
- //await TurnOffLightAfterPhoto(procedure);
- }
- }
- /// <summary>
- /// 执行相机拍照获取单个点位结果,并且返回图像和图形
- /// </summary>
- /// <param name="procedure"></param>
- /// <param name="InputTerminal"></param>
- /// <param name="robotCoord"></param>
- /// <param name="cancellationToken"></param>
- /// <returns></returns>
- 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)
- {
- DateTime nowtime = DateTime.Now;
- await SetLightBeforePhoto(procedure);
- ICogImage outImage=null;
- CogGraphicCollection outGraphicCollection=null;
- try
- {
- //拍照失败时,需要多次拍照
- for (int i = 0; i < procedure.FeederFailLimit; i++)
- {
- SendTaskMessage(Lang.开始执行视觉流程.Replace("{0}", $"{i + 1}").Replace("{1}", procedure.Name), MessageLevel.Info);
- // 1. 执行相机拍照并运行视觉工具
- bool visionSucceed = ExecutePhotoEx(procedure, InputTerminal, out CogToolBlockTerminalCollection outputCollection, out outImage, out outGraphicCollection);
- if (!visionSucceed)
- {
- SendTaskMessage(Lang.视觉任务执行失败, MessageLevel.Error);
- continue;
- }
- if (!outputCollection.Contains("Found"))
- {
- SendTaskMessage(Lang.未找到视觉输出结果, MessageLevel.Error);
- return (false, 0, 0, 0, outImage, outGraphicCollection);
- }
- // 2. 获取视觉输出结果
- bool Found = (bool)(outputCollection["Found"].Value);
- if (!Found)
- {
- SendTaskMessage(Lang.拍照NG, MessageLevel.Debug);
- continue;
- }
- SendTaskMessage(Lang.拍照OK, MessageLevel.Debug);
- // 3. 获取视觉输出结果
- LogHelper.WriteLogInfo("开始获取视觉输出结果");
- //获取相机校准
- var calib = _calibrationService.GetCalibration(procedure.CalibrationId);
- string points = (string)(outputCollection["Point"].Value);
- string[] strpoints = points.Split(';');
- //先将pos按照逗号进行分隔,拿到数组
- var posParts = strpoints[0].Split(',');
- double _pixel_x = double.Parse(posParts[0]);
- double _pixel_y = double.Parse(posParts[1]);
- double _pixel_u = double.Parse(posParts[2]);
- //转换点位-像素转换成机器人绝对坐标
- var calibResult = _calibrationService.ConvertPixelToPosition((_pixel_x, _pixel_y, _pixel_u), robotCoord, calib, RobotBrand.XYZ_Platform);
- if (!calibResult.IsSucceed)
- {
- return (false, 0, 0, 0, outImage, outGraphicCollection);
- }
- return (true, calibResult.X, calibResult.Y, calibResult.U, outImage, outGraphicCollection);
- }
- SendTaskMessage(Lang.多次拍照失败, MessageLevel.Alarm);
- return (false, 0, 0, 0, outImage, outGraphicCollection);
- }
- catch (Exception ex)
- {
- LogHelper.WriteLogError("执行相机取图并获取单点位时出错!", ex);
- return (false, 0, 0, 0, outImage, outGraphicCollection);
- }
- finally
- {
- await TurnOffLightAfterPhoto(procedure);
- }
- }
- /// <summary>
- /// 从 ToolBlock 的输出集合中根据 Procedure 配置提取需要发送的输出项并做必要的坐标转换。
- /// 返回元组:是否成功、错误信息(失败时)和名称->(是否点位, 值) 的字典。
- /// </summary>
- public (bool IsSucceed, string ErrMsg, Dictionary<string, (bool IsPoint, object Value)> Output) GetVisionOutput(ProcedureModel procedure, CogToolBlockTerminalCollection outputCollection, double[] robotPos)
- {
- RobotBrand robotBrand = RobotBrand.Default;
- var robot = _configService.GetRobot(procedure.RobotId);
- if (robot != null)
- {
- robotBrand = robot.RobotBrand;
- }
- List<string> SendResults = new List<string>();
- Dictionary<string, (bool IsPoint, object Value)> ResultCollection = new Dictionary<string, (bool IsPoint, object Value)>();
- foreach (var output in procedure.ProcedureOutputs)
- {
- //根据输出类型进行区分输出
- if (output.ValueType == typeof(string))
- {
- //需要点位转换时,进行点位提取
- if (output.IsPointTran)
- {
- if (outputCollection[output.Name].Value == null || string.IsNullOrEmpty(outputCollection[output.Name].Value.ToString()))
- {
- //如果需要输出的项的值为空,即点位数据为空,则输出点位的个数为0
- ResultCollection.Add(output.Name, (true, null));
- continue;
- }
- string[] strpoints = outputCollection[output.Name].Value.ToString().Split(';');
- //存储当前输出点位集合
- List<string[]> currentPointsForFeeder = new List<string[]>();
- //获取相机校准
- var calib = _calibrationService.GetCalibration(procedure.CalibrationId);
- if (calib == null)
- {
- SendTaskMessage(Lang.没有相机校准信息, MessageLevel.Alarm);
- return (false, "NotCalibrations", null);
- }
- // 判断相机安装方式,如果是J4移动相机或者XYZ平台时,则需要判断robotPos不能为null
- if ((calib.CameraMount == CameraMount.MobileJ4 || calib.CameraMount == CameraMount.MobileDown_XYPlatform) && robotPos == null)
- {
- SendTaskMessage(Lang.机器人当前位置不能为空, MessageLevel.Alarm);
- return (false, "RobotPositionNull", null);
- }
- List<string> SendDtat = new List<string>();
- List<string> points = new List<string>();
- //遍历所有的输出点位
- foreach (var pos in strpoints)
- {
- //先将pos按照逗号进行分隔,拿到数组,判断是否至少包含3个元素,并且前三个元素可以转换为double,确保是有效的点位数据
- if (string.IsNullOrEmpty(pos))
- {
- continue;
- }
- //先将pos按照逗号进行分隔,拿到数组
- var posParts = pos.Split(',');
- if (posParts.Length < 3 ||
- !double.TryParse(posParts[0], out double _pixel_x) ||
- !double.TryParse(posParts[1], out double _pixel_y) ||
- !double.TryParse(posParts[2], out double _pixel_u))
- {
- SendTaskMessage(string.Format(Lang.点位数据格式错误, pos), MessageLevel.Alarm);
- return (false, "PointDataFormatError", null);
- }
- //转换点位-像素转换成机器人绝对坐标
- var calibResult = _calibrationService.ConvertPixelToPosition((_pixel_x, _pixel_y, _pixel_u), robotPos, calib, robotBrand);
- if (!calibResult.IsSucceed)
- {
- return (false, "CalibrationFailed", null);
- }
- //截取posParts数组从索引3开始到结尾的所有元素,得到新新的数组extraInfoArray
- string[] extraInfoArray = posParts.Skip(3).ToArray();
- //将rpos转换为字符串数组,保留3位小数
- string[] strings = new string[] { $"{calibResult.X:F3}", $"{calibResult.Y:F3}", $"{calibResult.U:F3}" };
- List<string> rposString = new List<string>(strings);
- if (extraInfoArray.Length > 0)
- {
- rposString.AddRange(extraInfoArray);
- }
- currentPointsForFeeder.Add(rposString.ToArray());
- }
- ResultCollection[output.Name] = (true, currentPointsForFeeder);
- }
- //直接输出字符串
- else
- {
- if (outputCollection[output.Name].Value == null || string.IsNullOrEmpty(outputCollection[output.Name].Value.ToString()))
- {
- ResultCollection.Add(output.Name, (false, null));
- continue;
- }
- ResultCollection[output.Name] = (false, outputCollection[output.Name].Value.ToString());
- }
- }
- else
- {
- if (outputCollection[output.Name].Value == null)
- {
- ResultCollection.Add(output.Name, (false, null));
- }
- else
- {
- ResultCollection[output.Name] = (false, outputCollection[output.Name].Value.ToString());
- }
- }
- }
- return (true, string.Empty, ResultCollection);
- }
- /// <summary>
- /// 拍照前针对 Feeder 的准备动作:设置灯、必要时供料或振动等。
- /// </summary>
- public async Task ExecuteFeederForPhotoBefore(IVoiceCoilMotorFeeder Feeder, ProcedureModel procedure, bool doVibrateFirst, bool doCaptureFirst, CancellationToken cancellationToken)
- {
- // 1. 设置Feeder光源亮度、打开光源
- if (Feeder.FeederBrand == FeederBrand.AFAG)
- {
- await Feeder.SetLightValueAsync((ushort)procedure.LightValue);
- }
- else
- {
- //Feeder光源亮度设置
- if (procedure.LightValue > 3)
- {
- var light = await Feeder.GetLightBrightnessAsync();
- if (procedure.LightValue != light)
- {
- await Feeder.SetLightValueAsync((ushort)procedure.LightValue);
- }
- //获取光源的超时时间
- int lightTimeout = await Feeder.GetLightTimeoutAsync();
- if (lightTimeout < 10000)
- {
- await Feeder.SetLightTimeOutAsync(10000);
- }
- //打开光源
- await Feeder.OpenLightAsync();
- }
- }
- if (doCaptureFirst)//如果不振动,等待光源稳定时间
- {
- if (procedure.WaitPhoto > 0) await Task.Delay(procedure.WaitPhoto);
- return;
- }
- //先振后拍时
- if (procedure.VibrationModel == VibrationModel.VibrationPhoto || doVibrateFirst)
- {
- if (procedure.FeederWorks != null && procedure.FeederWorks.FeederWorkList != null)
- {
- bool flog = false;
- //如果上次的Blob面积小于设定的最小值,则触发供料
- if (procedure.LastBlobArea <= procedure.MinArea)
- {
- flog = true;
- SendTaskMessage(Lang.执行料仓供料, MessageLevel.Info);
- await ExecuteFeederStockWorks(Feeder, procedure.FeederStockWorks, cancellationToken);
- if (procedure.WaitFeederStop > 0) await Task.Delay(procedure.WaitFeederStop);
- SendTaskMessage(Lang.料仓供料结束, MessageLevel.Info);
- }
- if (!flog)
- {
- //执行配置的Feeder振动任务
- await ExecuteFeederWorks(Feeder, procedure.FeederWorks, cancellationToken, false);
- if (procedure.WaitFeederStop > 0) await Task.Delay(procedure.WaitFeederStop);
- }
- }
- }
- else
- {
- if (procedure.LightValue > 3)
- {
- if (procedure.WaitPhoto > 0) await Task.Delay(procedure.WaitPhoto);
- }
- //如果上次的Blob面积小于设定的最小值,则触发供料
- if (procedure.LastBlobArea <= procedure.MinArea)
- {
- SendTaskMessage(Lang.执行料仓供料, MessageLevel.Info);
- await ExecuteFeederStockWorks(Feeder, procedure.FeederStockWorks, cancellationToken);
- if (procedure.WaitFeederStop > 0) await Task.Delay(procedure.WaitFeederStop);
- SendTaskMessage(Lang.料仓供料结束, MessageLevel.Info);
- }
- }
- }
- /// <summary>
- /// 拍照后在 NG 情况下的 Feeder 后处理,例如供料或振动。
- /// </summary>
- public async Task ExecuteFeederForPhotoLater(IVoiceCoilMotorFeeder Feeder, ProcedureModel procedure, CancellationToken cancellationToken)
- {
- //根据斑点面积决定是否料仓供料
- if (procedure.LastBlobArea <= procedure.MinArea)
- {
- SendTaskMessage(Lang.执行料仓供料, MessageLevel.Info);
- await ExecuteFeederStockWorks(Feeder, procedure.FeederStockWorks, cancellationToken);
- if (cancellationToken != null && cancellationToken.IsCancellationRequested) return;
- if (procedure.WaitFeederStop > 0) await Task.Delay(procedure.WaitFeederStop, cancellationToken);
- SendTaskMessage(Lang.料仓供料结束, MessageLevel.Info);
- }
- else
- {
- if (procedure.FeederWorks != null && procedure.FeederWorks.FeederWorkList != null)
- {
- SendTaskMessage(Lang.执行Feeder振动, MessageLevel.Info);
- //执行配置的Feeder振动任务
- await ExecuteFeederWorks(Feeder, procedure.FeederWorks, cancellationToken);
- if (cancellationToken != null && cancellationToken.IsCancellationRequested) return;
- if (procedure.WaitFeederStop > 0) await Task.Delay(procedure.WaitFeederStop, cancellationToken);
- SendTaskMessage(Lang.Feeder振动结束, MessageLevel.Info);
- }
- }
- }
- /// <summary>
- /// 并行执行料仓供料和振动任务。
- /// </summary>
- public async Task ExecuteFeederStockWorks(IVoiceCoilMotorFeeder feeder, FeederStockWorks works, CancellationToken cancellationToken, bool isUpdateParame = true)
- {
- //同时执行料仓供料和Feeder振动任务
- var stockTask = ExecuteFeederStockWorksOnly(feeder, works.FeederStockWorkList.ToArray(), cancellationToken);
- var vibrationTask = ExecuteFeederWorkOnly(feeder, works.FeederWorkList.ToArray(), cancellationToken);
- await Task.WhenAll(stockTask, vibrationTask);
- }
- /// <summary>
- /// 执行料仓振动任务序列(仅料仓相关动作)。
- /// </summary>
- public async Task ExecuteFeederStockWorksOnly(IVoiceCoilMotorFeeder feeder, FeederStockWork[] works, CancellationToken cancellationToken)
- {
- //执行配置的料仓振动任务
- if (feeder.FeederBrand == FeederBrand.AFAG)
- {
- foreach (var stockwork in works)
- {
- if (stockwork.RegisterIndex == 0)
- {
- if (stockwork.Duration > 0) await Task.Delay(stockwork.Duration, cancellationToken);
- }
- else if (stockwork.RegisterIndex == 1)
- {
- // 保留原注释的位置给 Modbus 操作
- }
- if (cancellationToken != null && cancellationToken.IsCancellationRequested)
- {
- return;
- }
- }
- }
- else
- {
- foreach (var stockwork in works)
- {
- if (stockwork.Function == VibrationFunction.Delay)
- {
- if (stockwork.Duration > 0) await Task.Delay(stockwork.Duration, cancellationToken);
- }
- else
- {
- await feeder.OutputAsync(((int)stockwork.Function) + 1, stockwork.Duration);
- if (stockwork.Duration > 0) await Task.Delay(stockwork.Duration, cancellationToken);
- }
- if (cancellationToken != null && cancellationToken.IsCancellationRequested)
- {
- return;
- }
- }
- }
- }
- /// <summary>
- /// 执行单独的 Feeder 振动动作序列(仅振动相关)。
- /// </summary>
- public async Task ExecuteFeederWorkOnly(IVoiceCoilMotorFeeder feeder, FeederWork[] works, CancellationToken cancellationToken, bool isUpdateParame = true)
- {
- if (works == null)
- {
- return;
- }
- if (feeder.FeederBrand == FeederBrand.AFAG)
- {
- //执行配置的Feeder振动任务
- foreach (var feederwork in works)
- {
- if (feederwork.ConfigIndex < 0)
- {
- continue;
- }
- if (feederwork.ConfigIndex == 0)
- {
- if (feederwork.Duration > 0) await Task.Delay(feederwork.Duration, cancellationToken);
- }
- else
- {
- ((AfagFeeder)feeder).LoadConfiguration(feederwork.ConfigIndex);
- ((AfagFeeder)feeder).SetIntensity(feederwork.Intensity);
- ((AfagFeeder)feeder).SetDirection(feederwork.Direction);
- if (feederwork.Duration > 0) await Task.Delay(feederwork.Duration, cancellationToken);
- if (cancellationToken != null && cancellationToken.IsCancellationRequested)
- {
- return;
- }
- ((AfagFeeder)feeder).SetIntensity(0);
- }
- if (cancellationToken != null && cancellationToken.IsCancellationRequested)
- {
- return;
- }
- }
- }
- else
- {
- //执行配置的Feeder振动任务
- foreach (var feederwork in works)
- {
- if (feederwork.Function == VibrationFunction.Delay)
- {
- if (feederwork.Duration > 0) await Task.Delay(feederwork.Duration, cancellationToken);
- }
- else
- {
- if (feederwork.SingleAction != null && isUpdateParame)
- {
- await feeder.SetShakeParametersAsync((int)feederwork.Function, feederwork.SingleAction);
- }
- await feeder.StartAction((int)feederwork.Function, feederwork.Duration);
- if (feederwork.Duration > 0) await Task.Delay(feederwork.Duration, cancellationToken);
- }
- if (cancellationToken != null && cancellationToken.IsCancellationRequested)
- {
- return;
- }
- }
- }
- }
- /// <summary>
- /// 执行 Feeder 振动集合(逐个执行 FeederWorkList 中的动作)。
- /// </summary>
- public async Task ExecuteFeederWorks(IVoiceCoilMotorFeeder feeder, FeederWorks works, CancellationToken cancellationToken, bool isUpdateParame = true)
- {
- if (feeder.FeederBrand == FeederBrand.AFAG)
- {
- foreach (var feederwork in works.FeederWorkList)
- {
- if (feederwork.ConfigIndex < 0)
- {
- continue;
- }
- if (feederwork.ConfigIndex == 0)
- {
- await Task.Delay(feederwork.Duration, cancellationToken);
- }
- else
- {
- ((AfagFeeder)feeder).LoadConfiguration(feederwork.ConfigIndex);
- ((AfagFeeder)feeder).SetIntensity(feederwork.Intensity);
- ((AfagFeeder)feeder).SetDirection(feederwork.Direction);
- await Task.Delay(feederwork.Duration, cancellationToken);
- if (cancellationToken != null && cancellationToken.IsCancellationRequested)
- {
- return;
- }
- ((AfagFeeder)feeder).SetIntensity(0);
- }
- if (cancellationToken != null && cancellationToken.IsCancellationRequested)
- {
- return;
- }
- }
- }
- else
- {
- foreach (var feederwork in works.FeederWorkList)
- {
- if (feederwork.Function == VibrationFunction.Delay)
- {
- if (feederwork.Duration > 0) await Task.Delay(feederwork.Duration, cancellationToken);
- }
- else
- {
- if (feederwork.SingleAction != null && isUpdateParame)
- {
- await feeder.SetShakeParametersAsync((int)feederwork.Function, feederwork.SingleAction);
- }
- await feeder.StartAction((int)feederwork.Function, feederwork.Duration);
- if (feederwork.Duration > 0) await Task.Delay(feederwork.Duration, cancellationToken);
- }
- if (cancellationToken != null && cancellationToken.IsCancellationRequested)
- {
- return;
- }
- }
- }
- }
- /// <summary>
- /// 在拍照前设置光源亮度和打开光源
- /// </summary>
- /// <param name="procedure">流程模型</param>
- /// <returns></returns>
- public async Task SetLightBeforePhoto(ProcedureModel procedure)
- {
- var sysConfig = _configService.GetSystemConfiguration();
- if (sysConfig.LightUse == true)
- {
- return;
- }
-
- //判断当前流程是否启用光源控制
- if (procedure.IsControlLightChannels)
- {
- //打开所有需要控制的光源通道
- foreach (var lightChannel in procedure.LightChannels)
- {
- bool isSucceed = false;
- isSucceed = await _lightManagerService.TurnOnGlobalChannelAsync(lightChannel.GlobalIndex);
- if (!isSucceed)
- {
- LogHelper.WriteLogInfo($"设置光源通道{lightChannel.GlobalIndex}打开失败!");
- }
- isSucceed = await _lightManagerService.SetGlobalChannelBrightnessAsync(lightChannel.GlobalIndex, lightChannel.DefaultBrightness);
- if (!isSucceed)
- {
- LogHelper.WriteLogInfo($"设置光源通道{lightChannel.GlobalIndex}亮度{lightChannel.DefaultBrightness}失败!");
- }
- }
- }
- }
- /// <summary>
- /// 在拍照后关闭光源
- /// </summary>
- /// <param name="procedure">流程模型</param>
- /// <returns></returns>
- public async Task TurnOffLightAfterPhoto(ProcedureModel procedure)
- {
- var sysConfig = _configService.GetSystemConfiguration();
- if (sysConfig.LightUse == true)
- {
- return;
- }
- //判断当前流程是否启用光源控制
- if (procedure.IsControlLightChannels)
- {
- //关闭所有需要控制的光源通道
- foreach (var lightChannel in procedure.LightChannels)
- {
- bool isSucceed = false;
- isSucceed = await _lightManagerService.TurnOffGlobalChannelAsync(lightChannel.GlobalIndex);
- if (!isSucceed)
- {
- LogHelper.WriteLogInfo($"设置光源通道{lightChannel.GlobalIndex}关闭失败!");
- }
- }
- }
- }
- #endregion
- }
- }
|