| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545 |
- using Cognex.VisionPro;
- using Cognex.VisionPro.ToolBlock;
- using MathNet.Numerics.LinearAlgebra;
- using Microsoft.CodeAnalysis.Scripting;
- using NPOI.SS.Formula.Functions;
- 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 =>
- {
- 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
- {
- 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("开始采集图像");
- Thread.Sleep(250);
- 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;
- }
- _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 = (bool)(outputCollection["Found"].Value),
- IsShow = true,
- IsSaveImage = procedure.IsSaveImage,
- SaveImageModel = procedure.SaveImageModel,
- SaveImagePathModel = procedure.SaveImagePathModel,
- SavePath = procedure.SavePath,
- IsCompress = procedure.IsCompress,
- ProceductName = procedure.Name
- });
- 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;
- _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,
- ProceductName = procedure.Name,
- });
- 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="outputCollection"></param>
- /// <returns></returns>
- public bool ExecutePhoto(ProcedureModel procedure, out CogToolBlockTerminalCollection outputCollection)
- {
- try
- {
- 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();
- if (image == null)
- {
- SendTaskMessage(Lang.图像采集失败, MessageLevel.Error);
- outputCollection = null;
- return false;
- }
- procedure.ToolBlock.Inputs["InputImage"].Value = image;
- LogHelper.WriteLogInfo(string.Format("采集图像完成用时0ms", (DateTime.Now - nowtime).Milliseconds));
- // 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;
- }
- _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 = (bool)(outputCollection["Found"].Value),
- IsShow = true,
- IsSaveImage = procedure.IsSaveImage,
- SaveImageModel = procedure.SaveImageModel,
- SaveImagePathModel = procedure.SaveImagePathModel,
- SavePath = procedure.SavePath,
- IsCompress = procedure.IsCompress,
- 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;
- _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,
- ProceductName = procedure.Name,
- });
- return false;
- }
- }
- catch (Exception ex)
- {
- SendTaskMessage(ex.Message, MessageLevel.Error);
- LogHelper.WriteLogError("执行相机取图并执行视觉工具组时出错", 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($"相机曝光设置失败!", 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>
- /// <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)
- {
- 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(procedure, InputTerminal, out CogToolBlockTerminalCollection outputCollection);
- 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("开始获取视觉输出结果");
- //获取相机校准
- 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]);
- if (calib != null)
- {
- //转换点位-像素转换成机器人绝对坐标
- 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);
- }
- else
- {
- await RecordPhotoCaptureAsync(procedure, robotCoord, true, new double[] { _pixel_x, _pixel_y, _pixel_u }, new double[] { 0, 0, 0 }, string.Empty, positionIndex, remark);
- return (true, _pixel_x, _pixel_y, _pixel_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("执行相机取图并获取单点位时出错!", 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="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, string distance)> ExecutePhotoGetDistance(ProcedureModel procedure, Dictionary<string, string> InputTerminal, double[] robotCoord, CancellationToken cancellationToken, int positionIndex, string remark)
- {
- 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(procedure, InputTerminal, out CogToolBlockTerminalCollection outputCollection);
- if (!visionSucceed)
- {
- SendTaskMessage(Lang.视觉任务执行失败, MessageLevel.Error);
- continue;
- }
- if (!outputCollection.Contains("Found"))
- {
- SendTaskMessage(Lang.未找到视觉输出结果, MessageLevel.Error);
- return (false, "");
- }
- // 2. 获取视觉输出结果
- bool Found = (bool)(outputCollection["Found"].Value);
- if (!Found)
- {
- SendTaskMessage(Lang.拍照NG, MessageLevel.Debug);
- continue;
- }
- SendTaskMessage(Lang.拍照OK, MessageLevel.Debug);
- LogHelper.WriteLogInfo("开始获取视觉输出结果");
- string dis = (string)(outputCollection["Gap"].Value);
- return (true, dis);
- }
- SendTaskMessage(Lang.多次拍照失败, MessageLevel.Alarm);
- return (false, "");
- }
- catch (Exception ex)
- {
- LogHelper.WriteLogError("执行相机取图并获取单点位时出错!", ex);
- return (false, "");
- }
- 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;
- //如果产品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("开始获取视觉输出结果");
- //获取相机校准
- 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)
- {
- //判断当前流程是否启用光源控制
- if (procedure.IsControlLightChannels)
- {
- //打开所有需要控制的光源通道
- foreach (var lightChannel in procedure.LightChannels)
- {
- bool isSucceed = false;
- isSucceed = await _lightManagerService.TurnOnGlobalChannelAsync(lightChannel.GlobalIndex);
- if (!isSucceed)
- {
- LogHelper.WriteLogInfo($"设置光源通道{lightChannel.GlobalIndex}打开失败!");
- }
- await Task.Delay(200);
- isSucceed = await _lightManagerService.SetGlobalChannelBrightnessAsync(lightChannel.GlobalIndex, lightChannel.DefaultBrightness);
- if (!isSucceed)
- {
- LogHelper.WriteLogInfo($"设置光源通道{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($"设置光源通道{lightChannel.GlobalIndex}关闭失败!");
- }
- }
- }
- }
- #endregion
- }
- }
|