| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565 |
- using Cognex.VisionPro;
- using Cognex.VisionPro.ToolBlock;
- using MathNet.Numerics.LinearAlgebra;
- using Microsoft.CodeAnalysis.Scripting;
- using NPOI.SS.Formula.Functions;
- using NPOI.SS.UserModel;
- using NPOI.XSSF.Streaming.Values;
- 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.Windows.Shapes;
- using Team.FFFeederService;
- using Team.FFFeederService.Interfaces;
- using TeamAAS_VP.Core;
- 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 =>
- {
- ImageParameters imgPara = new ImageParameters();
- imgPara.SNCode = "SN";
- var r = await ExecuteVisionTaskAsync(procedure, commandParams, ct, imgPara);
- 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.Now;
- while (!token.IsCancellationRequested)
- {
- var elapsed = DateTime.Now - 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.Now
- });
- 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.Now
- });
- 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
- {
- 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, ImageParameters imgPara)
- {
- 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(Lang.执行视觉处理脚本时出错, 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, imgPara);
- }
- else
- {
- var result = await ExecuteNormalVisionTaskAsync(procedure, items, cancellationToken, imgPara);
- 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, ImageParameters imgPara)
- {
- // 如果输入的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(i + 1, procedure, InputTerminal, out CogToolBlockTerminalCollection outputCollection, imgPara);
- 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(Lang.开始获取视觉输出结果);
- 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, ImageParameters imgPara)
- {
- // 开始执行前的时间点
- 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(Lang.开始执行相机拍照并运行视觉工具);
- bool visionSucceed = ExecutePhoto(i + 1, procedure, InputTerminal, out CogToolBlockTerminalCollection outputCollection, imgPara);
- 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(Lang.开始获取视觉输出结果);
- 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(Lang.执行普通视觉任务时出错, ex);
- return (false, "Exception");
- }
- finally
- {
- await TurnOffLightAfterPhoto(procedure);
- }
- }
- /// <summary>
- /// 执行相机拍照并运行 ToolBlock,返回是否成功并通过 out 参数返回 Outputs。
- /// 该方法会发布 RenderUpdateNotification 以更新 UI。
- /// </summary>
- public bool ExecutePhoto(int index, ProcedureModel procedure, Dictionary<string, string> InputTerminal, out CogToolBlockTerminalCollection outputCollection, ImageParameters imgPara,int ScrewNum=1)
- {
- try
- {
- // 1. 采集图像
- var camera = _cameraService.GetCamera(procedure.CameraId);
- bool succed = camera.SetExposureTime(procedure.ExposureTime);
- if (!succed)
- {
- SendTaskMessage(Lang.相机曝光设置失败, MessageLevel.Error);
- }
- succed = camera.SetGain(procedure.Gain);
- if (!succed)
- {
- SendTaskMessage(Lang.相机增益设置失败, MessageLevel.Error);
- }
- DateTime nowtime = DateTime.Now;
- LogHelper.WriteLogInfo(Lang.开始采集图像);
- var image = camera.Grab();
- if (image == null)
- {
- SendTaskMessage(Lang.图像采集失败, MessageLevel.Error);
- outputCollection = null;
- return false;
- }
- procedure.ToolBlock.Inputs["InputImage"].Value = image;
- LogHelper.WriteLogInfo(string.Format(Lang.采集图像完成用时0ms, (DateTime.Now - nowtime).Milliseconds));
- // 2. 为ToolBlock传入其他输入终端
- if (InputTerminal != null)
- {
- LogHelper.WriteLogInfo(Lang.为ToolBlock传入输入终端);
- foreach (var item in InputTerminal)
- {
- if (procedure.ToolBlock.Inputs.Contains(item.Key))
- {
- LogHelper.WriteLogInfo(string.Format(Lang.传入01, item.Key, item.Value));
- procedure.ToolBlock.Inputs[item.Key].Value = item.Value;
- }
- else
- {
- LogHelper.WriteLogInfo(string.Format(Lang.创建并传入01, item.Key, item.Value));
- procedure.ToolBlock.Inputs.Add(new CogToolBlockTerminal(item.Key, item.Value));
- }
- }
- }
- // 3. 运行视觉工具
- LogHelper.WriteLogInfo(Lang.开始运行视觉工具);
- 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", () => index);
- template.RegisterVariable("Result", () => Found ? "OK" : "NG");
- template.RegisterVariable("Number", () => ScrewNum);
- template.RegisterVariable("DateTime", () => DateTime.Now);
- // 生成文件名
- imgName = template.Generate();
- }
- _eventAggregator.GetEvent<RenderUpdateNotification>().Publish(new ShowRender()
- {
- Id = procedure.Id,
- 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,
- IsDelaySaveImage = procedure.IsDelaySaveImage,
- ImgPara = imgPara,
- ImageFileName = imgName,
- ProceductName = procedure.Name,
- });
- SendTaskMessage($"{procedure.CameraName},{procedure.CameraId}", MessageLevel.Info);
- 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", () => index);
- template.RegisterVariable("Result", () => "NG");
- template.RegisterVariable("DateTime", () => DateTime.Now);
- // 生成文件名
- imgName = template.Generate();
- }
- _eventAggregator.GetEvent<RenderUpdateNotification>().Publish(new ShowRender()
- {
- Id = procedure.Id,
- 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,
- IsCompress = procedure.IsCompress,
- IsDelaySaveImage = procedure.IsDelaySaveImage,
- ProceductName = procedure.Name,
- ImageFileName = imgName
- });
- return false;
- }
- }
- catch (Exception ex)
- {
- SendTaskMessage(ex.Message, MessageLevel.Error);
- LogHelper.WriteLogError(Lang.执行相机取图并执行视觉工具组时出错, ex);
- outputCollection = null;
- return false;
- }
- }
- /// <summary>
- /// 执行拍照二维码流程运行
- /// </summary>
- /// <param name="procedure"></param>
- /// <param name="outputCollection"></param>
- /// <returns></returns>
- public bool ExecutePhoto(int index, ProcedureModel procedure, out CogToolBlockTerminalCollection outputCollection)
- {
- try
- {
- SetLightBeforePhoto(procedure);
- // 1. 采集图像
- var camera = _cameraService.GetCamera(procedure.CameraId);
- bool succed = camera.SetExposureTime(procedure.ExposureTime);
- if (!succed)
- {
- SendTaskMessage(Lang.相机曝光设置失败, MessageLevel.Error);
- }
- succed = camera.SetGain(procedure.Gain);
- if (!succed)
- {
- SendTaskMessage(Lang.相机增益设置失败, MessageLevel.Error);
- }
- DateTime nowtime = DateTime.Now;
- LogHelper.WriteLogInfo(Lang.开始采集图像);
- var image = camera.Grab();
- if (image == null)
- {
- SendTaskMessage(Lang.图像采集失败, MessageLevel.Error);
- outputCollection = null;
- return false;
- }
- procedure.ToolBlock.Inputs["InputImage"].Value = image;
- LogHelper.WriteLogInfo(string.Format(Lang.采集图像完成用时0ms, (DateTime.Now - nowtime).Milliseconds));
- // 3. 运行视觉工具
- LogHelper.WriteLogInfo(Lang.开始运行视觉工具);
- 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", () => index);
- template.RegisterVariable("Result", () => Found ? "OK" : "NG");
- template.RegisterVariable("DateTime", () => DateTime.Now);
- // 生成文件名
- imgName = template.Generate();
- }
- _eventAggregator.GetEvent<RenderUpdateNotification>().Publish(new ShowRender()
- {
- Id = procedure.Id,
- 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,
- IsDelaySaveImage = procedure.IsDelaySaveImage,
- ProceductName = procedure.Name,
- ImageFileName = imgName,
- });
- SendTaskMessage($"{procedure.CameraName},{procedure.CameraId}", MessageLevel.Info);
- 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", () => index);
- template.RegisterVariable("Result", () => "NG");
- template.RegisterVariable("DateTime", () => DateTime.Now);
- // 生成文件名
- imgName = template.Generate();
- }
- _eventAggregator.GetEvent<RenderUpdateNotification>().Publish(new ShowRender()
- {
- Id = procedure.Id,
- 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,
- IsCompress = procedure.IsCompress,
- IsDelaySaveImage = procedure.IsDelaySaveImage,
- ProceductName = procedure.Name,
- ImageFileName = imgName
- });
- return false;
- }
- }
- catch (Exception ex)
- {
- SendTaskMessage(ex.Message, MessageLevel.Error);
- LogHelper.WriteLogError(Lang.执行相机取图并执行视觉工具组时出错, ex);
- outputCollection = null;
- return false;
- }
- }
- /// <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(Lang.相机曝光设置失败, MessageLevel.Error);
- }
- succed = camera.SetGain(procedure.Gain);
- if (!succed)
- {
- SendTaskMessage(Lang.相机增益设置失败, MessageLevel.Error);
- }
- DateTime nowtime = DateTime.Now;
- LogHelper.WriteLogInfo(Lang.开始采集图像);
- 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(string.Format(Lang.采集图像完成用时0ms, (DateTime.Now - nowtime).Milliseconds));
- // 2. 为ToolBlock传入其他输入终端
- if (InputTerminal != null)
- {
- LogHelper.WriteLogInfo(Lang.为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(Lang.开始运行视觉工具);
- 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(Lang.执行相机取图并执行视觉工具组时出错, ex);
- outputCollection = null;
- return false;
- }
- }
- /// <summary>
- /// 执行相机拍照获取单个点位结果
- /// </summary>
- /// <param name="procedure"></param>
- /// <param name="InputTerminal"></param>
- /// <param name="robotCoord"></param>
- /// <param name="cancellationToken"></param>
- /// <param name="positionIndex"></param>
- /// <param name="remark"></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, int positionIndex, string remark, ImageParameters imgPara)
- {
- DateTime nowtime = DateTime.Now;
- 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 = ExecutePhoto(i + 1, procedure, InputTerminal, out CogToolBlockTerminalCollection outputCollection, imgPara);
- if (!visionSucceed)
- {
- SendTaskMessage(Lang.视觉任务执行失败, MessageLevel.Error);
- continue;
- }
- if (!outputCollection.Contains("Found"))
- {
- SendTaskMessage(Lang.未找到视觉输出结果, MessageLevel.Error);
- await RecordPhotoCaptureAsync(procedure, robotCoord, false, new double[] { 0, 0, 0 }, new double[] { 0, 0, 0 }, string.Empty, positionIndex, remark);
- 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);
- if (procedure.CalibrationId == Guid.Empty)
- {
- //没有关联校准时,则执行检测任务
- await RecordPhotoCaptureAsync(procedure, robotCoord, true, new double[] { 0, 0, 0 }, new double[] { 0, 0, 0 }, string.Empty, positionIndex, remark);
- return (true, 0, 0, 0);
- }
- // 3. 获取视觉输出结果
- LogHelper.WriteLogInfo(Lang.开始获取视觉输出结果);
- //获取相机校准
- 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)
- {
- await RecordPhotoCaptureAsync(procedure, robotCoord, false, new double[] { _pixel_x, _pixel_y, _pixel_u }, new double[] { 0, 0, 0 }, string.Empty, positionIndex, remark);
- return (false, 0, 0, 0);
- }
- await RecordPhotoCaptureAsync(procedure, robotCoord, true, new double[] { _pixel_x, _pixel_y, _pixel_u }, new double[] { calibResult.X, calibResult.Y, calibResult.U }, string.Empty, positionIndex, remark);
- return (true, calibResult.X, calibResult.Y, calibResult.U);
- }
- SendTaskMessage(Lang.多次拍照失败, MessageLevel.Alarm);
- await RecordPhotoCaptureAsync(procedure, robotCoord, false, new double[] { 0, 0, 0 }, new double[] { 0, 0, 0 }, string.Empty, positionIndex, remark);
- return (false, 0, 0, 0);
- }
- catch (Exception ex)
- {
- LogHelper.WriteLogError(Lang.执行相机取图并获取单点位时出错, ex);
- await RecordPhotoCaptureAsync(procedure, robotCoord, false, new double[] { 0, 0, 0 }, new double[] { 0, 0, 0 }, string.Empty, positionIndex, remark);
- return (false, 0, 0, 0);
- }
- finally
- {
- await TurnOffLightAfterPhoto(procedure);
- }
- }
- /// <summary>
- /// 记录拍照结果数据至数据库
- /// </summary>
- /// <param name="procedure"></param>
- /// <param name="robotCoord"></param>
- /// <param name="isSuccess"></param>
- /// <param name="pixelPosition"></param>
- /// <param name="absolutePosition"></param>
- /// <param name="imagePath"></param>
- /// <param name="positionIndex"></param>
- /// <param name="emarks"></param>
- /// <returns></returns>
- private async Task RecordPhotoCaptureAsync(ProcedureModel procedure, double[] robotCoord, bool isSuccess, double[] pixelPosition, double[] absolutePosition, string imagePath, int positionIndex, string emarks)
- {
- try
- {
- //当前的产品配方名
- string formulaName = _productService.GetCurrentProduct().Name;
- //如果当前产品名称存在非法字符,则替换为下划线
- foreach (char c in System.IO.Path.GetInvalidFileNameChars())
- {
- formulaName = formulaName.Replace(c, '_');
- }
- //获取当前的产品SN
- string productSN = _productService.CurrentProductCode;
- if (!string.IsNullOrEmpty(productSN))
- {
- //如果产品SN存在非法字符,则替换为下划线
- foreach (char c in System.IO.Path.GetInvalidFileNameChars())
- {
- productSN = productSN.Replace(c, '_');
- }
- }
- //当前用户
- string currentUser = _systemDatabaseService.GetCurrentUser()?.UserName;
- //相机名称
- string cameraName = procedure.CameraName;
- //视觉流程名称
- string procedureName = procedure.Name;
- //如果机器人坐标为空,则获取当前机器人坐标
- if (robotCoord == null)
- {
- var robot = _robotService.GetAllRobots().FirstOrDefault();
- if (robot != null)
- {
- var pos = await robot.GetRobotPosAsync();
- robotCoord = new double[] { pos.X, pos.Y, pos.Z };
- }
- else
- {
- robotCoord = new double[] { 0, 0, 0 };
- }
- }
- PhotoCaptureRecord photoCaptureRecord = new PhotoCaptureRecord();
- photoCaptureRecord.RecipeName = formulaName;
- photoCaptureRecord.ProductSN = productSN;
- photoCaptureRecord.CameraName = cameraName;
- photoCaptureRecord.ProcessName = procedureName;
- photoCaptureRecord.RobotPosition = string.Join(",", robotCoord);
- photoCaptureRecord.IsSuccess = isSuccess;
- photoCaptureRecord.PixelPosition = string.Join(",", pixelPosition);
- photoCaptureRecord.AbsolutePosition = string.Join(",", absolutePosition);
- photoCaptureRecord.ImagePath = imagePath;
- photoCaptureRecord.Remarks = emarks;
- photoCaptureRecord.OperatorName = currentUser;
- await _systemDatabaseService.RecordPhotoCaptureAsync(photoCaptureRecord);
- }
- catch (Exception ex)
- {
- LogHelper.WriteLogError("记录拍照结果数据至数据库时出错", ex);
- }
- }
- /// <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(Lang.开始获取视觉输出结果);
- //获取相机校准
- 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(Lang.执行相机取图并获取单点位时出错, 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)
- {
- //判断当前流程是否启用光源控制
- if (procedure.IsControlLightChannels)
- {
- //打开所有需要控制的光源通道
- foreach (var lightChannel in procedure.LightChannels)
- {
- bool isSucceed = false;
- isSucceed = await _lightManagerService.TurnOnGlobalChannelAsync(lightChannel.GlobalIndex);
- if (!isSucceed)
- {
- LogHelper.WriteLogInfo(string.Format(Lang.设置光源通道0打开失败, lightChannel.GlobalIndex));
- //"设置光源通道{lightChannel.GlobalIndex}打开失败!");
- }
- isSucceed = await _lightManagerService.SetGlobalChannelBrightnessAsync(lightChannel.GlobalIndex, lightChannel.DefaultBrightness);
- if (!isSucceed)
- {
- LogHelper.WriteLogInfo(string.Format(Lang.设置光源通道0亮度1失败, lightChannel.GlobalIndex, lightChannel.DefaultBrightness));
- }
- }
- if (procedure.LightChannels.Count > 0)
- {
- await Task.Delay(50);
- }
- }
- }
- /// <summary>
- /// 在拍照后关闭光源
- /// </summary>
- /// <param name="procedure">流程模型</param>
- /// <returns></returns>
- public async Task TurnOffLightAfterPhoto(ProcedureModel procedure)
- {
- //判断当前流程是否启用光源控制
- if (procedure.IsControlLightChannels)
- {
- //关闭所有需要控制的光源通道
- foreach (var lightChannel in procedure.LightChannels)
- {
- bool isSucceed = false;
- isSucceed = await _lightManagerService.TurnOffGlobalChannelAsync(lightChannel.GlobalIndex);
- if (!isSucceed)
- {
- LogHelper.WriteLogInfo(string.Format(Lang.设置光源通道0关闭失败, lightChannel.GlobalIndex));
- }
- }
- }
- }
- #endregion
- }
- }
|