| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989 |
- using Cognex.VisionPro;
- using Cognex.VisionPro.ToolBlock;
- using MathNet.Numerics.LinearAlgebra;
- using Microsoft.CodeAnalysis.Scripting;
- using Org.BouncyCastle.Tls;
- using Prism.Events;
- using Prism.Ioc;
- using Prism.Regions;
- using System;
- using System.Collections.Generic;
- 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;
- using System.ComponentModel;
- using System.Collections.Concurrent;
- namespace TeamAAS_VP.Services
- {
- /// <summary>
- /// Lightweight migration of Management.ExecuteRemoteCommand into a dedicated service.
- /// This service depends on existing domain services and will call into them.
- /// Only the core helpers used by the old ExecuteRemoteCommand are migrated (LoadProduct, GetCurrentProductName, GetCurrentProductID, GetCurrentProductSpeed, etc.).
- /// </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;
- /// <summary>
- /// 计时器任务取消令牌
- /// </summary>
- private CancellationTokenSource _cycleTimingCts;
- /// <summary>
- /// 清料任务取消令牌字典,Key为任务编号
- /// </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));
- // 公开属性(只读)
- public bool IsExecuting => Volatile.Read(ref _activeCount) > 0;
- public bool IsExecutingVisionCommand => Volatile.Read(ref _visionActiveCount) > 0;
- // 可选事件(如果不想用 INotifyPropertyChanged)
- public event EventHandler ExecutionStateChanged;
- /// <summary>
- /// 计时器计时通知事件
- /// </summary>
- public event EventHandler<TimeSpan> CycleTimingTicked;
- public RemoteCommandService(IEventAggregator eventAggregator, IRegionManager regionManager, IProductService productService, IConfigService configService, ICalibrationService calibrationService,
- IFeederService feederService, ICameraService cameraService, IRobotService robotService, IContainerProvider container, ISystemDatabaseService systemDatabaseService)
- {
- _eventAggregator = eventAggregator;
- _regionManager = regionManager;
- _productService = productService;
- _configService = configService;
- _calibrationService = calibrationService;
- _feederService = feederService;
- _cameraService = cameraService;
- _robotService = robotService;
- _container = container;
- _systemDatabaseService = systemDatabaseService;
- }
- public void Dispose() { }
- // 通用包裹器:包装并追踪任意异步工作
- private async Task<T> TrackExecutionAsync<T>(Func<CancellationToken, Task<T>> work, bool isVision, CancellationToken ct)
- {
- // create id for this run (可用于日志/诊断)
- 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
- {
- // 记录 task(便于外部查询)
- 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);
- }
- }
- 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;
- // 假设 ExecuteFeederVisionTaskAsync 返回 (bool, string[])
- var visionResult = await TrackExecutionAsync(async ct =>
- {
- var r = await ExecuteVisionTaskAsync(procedure, commandParams, ct);
- // 如果需要转换类型,包装成 Tuple<bool, string[]>
- 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;
- }
- }
- //加载产品
- 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;
- }
- //通过产品编号获取产品名称
- 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);
- }
- //获取当前的产品名称
- public Task<string> GetCurrentProductNameAsync(CancellationToken cancellationToken)
- {
- var currentProduct = _productService.GetCurrentProduct();
- if (currentProduct != null)
- {
- return Task.FromResult(currentProduct.Name);
- }
- return Task.FromResult(string.Empty);
- }
- //通过产品名称获取产品编号
- 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);
- }
- //获取当前的产品编号
- public Task<int> GetCurrentProductNumberAsync(CancellationToken cancellationToken)
- {
- var currentProduct = _productService.GetCurrentProduct();
- if (currentProduct != null)
- {
- return Task.FromResult(currentProduct.NumberCode);
- }
- return Task.FromResult(-1);
- }
- //通过机器人编号和点位编号获取机器人点位信息
- 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>
- /// <param name="robotNumber">机器人编号</param>
- /// <param name="palletNumber">托盘编号</param>
- /// <param name="pointNumber">点编号</param>
- /// <param name="cancellationToken"></param>
- /// <returns></returns>
- 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);
- }
- //开始节拍计时
- public Task<bool> StartCycleTimingAsync(CancellationToken cancellationToken)
- {
- //TODO: 实现节拍计时开始逻辑
- //如果当前已经在计时,则取消之前的计时,然后重新开始计时
- 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); // 每100毫秒更新一次
- }
- }, token);
- return Task.FromResult(true);
- }
- //停止节拍计时
- public Task<bool> StopCycleTimingAsync(CancellationToken cancellationToken)
- {
- if (_cycleTimingCts != null)
- {
- _cycleTimingCts.Cancel();
- _cycleTimingCts.Dispose();
- _cycleTimingCts = null;
- }
- return Task.FromResult(true);
- }
- //创建一条生产计数,传入计数项
- 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);
- }
- //获取当前生产计数
- 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;
- }
- //重置生产计数
- 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;
- }
- //创建一条报警记录
- 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);
- }
- //创建一条运行信息记录
- public Task<bool> CreateOperationLogAsync(string logMessage, CancellationToken cancellationToken)
- {
- SendTaskMessage(logMessage, MessageLevel.Info);
- return Task.FromResult(true);
- }
- //获取当前产品指定编号的全局参数
- 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);
- }
- //获取当前产品的运行速度
- 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);
- }
- //获取末端工具信息,传入流程触发命令和工具编号
- 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);
- }
- //获取流程参数信息,传入流程触发命令
- 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());
- }
- //执行清料任务
- 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++)
- {
- //1.Feeder振动之前,打开挡板
- 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;
- }
- //2.执行配置的Feeder振动任务
- 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;
- }
- //3.Feeder振动之后,关闭挡板
- 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;
- }
- }
- //3.Feeder振动之后,关闭挡板
- 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;
- }
- //终止清料任务
- 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>
- /// <param name="cancellationToken"></param>
- /// <returns></returns>
- 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>
- /// 执行视觉任务
- /// </summary>
- /// <param name="triggerCommand">流程触发命令</param>
- /// <param name="doVibrateFirst">是否先振动</param>
- /// <param name="doCaptureFirst">是否先拍照</param>
- /// <param name="robotCurrentPosition">机器人当前点位</param>
- /// <param name="visionToolInputParams">视觉工具输入参数</param>
- /// <param name="cancellationToken"></param>
- /// <returns></returns>
- 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>
- /// <param name="elapsed"></param>
- private void OnCycleTimingTicked(TimeSpan elapsed)
- {
- CycleTimingTicked?.Invoke(this, elapsed);
- }
- 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视觉引导任务
- /// </summary>
- /// <param name="Feeder"></param>
- /// <param name="procedure"></param>
- /// <param name="items"></param>
- /// <param name="cancellationToken"></param>
- /// <returns></returns>
- 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格式的参数,停止解析
- }
- }
- }
- //执行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();
- 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 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();
- }
- //如果输出模式是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();
- }
- SendTaskMessage(Lang.多次拍照失败, MessageLevel.Alarm);
- return (false, new string[] { "VisionFailed" });
- }
- /// <summary>
- /// 执行普通视觉任务
- /// </summary>
- /// <param name="procedure"></param>
- /// <param name="items"></param>
- /// <param name="cancellationToken"></param>
- /// <returns></returns>
- public async Task<(bool IsSucceed, string Response)> ExecuteNormalVisionTaskAsync(ProcedureModel procedure, string[] items, CancellationToken cancellationToken)
- {
- // 开始执行前的时间点
- DateTime startTime = DateTime.Now;
- try
- {
- // 触发命令传入的输入终端
- 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)
- {
- //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++)
- {
- //单个点位内坐标之间逗号分隔
- 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");
- }
- }
- /// <summary>
- /// 执行相机拍照
- /// </summary>
- /// <param name="procedure"></param>
- /// <param name="InputTerminal">输入终端参数</param>
- /// <param name="outputCollection">输出终端结果</param>
- /// <returns></returns>
- public bool ExecutePhoto(ProcedureModel procedure, Dictionary<string, string> InputTerminal, out CogToolBlockTerminalCollection outputCollection)
- {
- try
- {
- // 1. 采集图像
- var camera = _cameraService.GetCamera(procedure.CameraId);
- bool succed = camera.SetExposureTime(procedure.ExposureTime);
- if (!succed)
- {
- SendTaskMessage($"相机曝光设置失败!", MessageLevel.Error);
- }
- succed = camera.SetGain(procedure.Gain);
- if (!succed)
- {
- SendTaskMessage($"相机增益设置失败!", MessageLevel.Error);
- }
- DateTime nowtime = DateTime.Now;
- LogHelper.WriteLogInfo("开始采集图像");
- var image = camera.Grab();
- 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()
- {
- CameraName = procedure.CameraName,
- Id = procedure.CameraId,
- 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,
- });
- 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()
- {
- CameraName = procedure.CameraName,
- Id = procedure.CameraId,
- 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
- });
- 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>
- /// <param name="IsCheckLastPoints"></param>
- /// <returns>是否成功,错误返回内容,<项的名称,<是否是点位数据,值>></returns>
- 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拍照前,执行Feeder
- /// </summary>
- /// <param name="Feeder">Feeder</param>
- /// <param name="procedure">流程</param>
- /// <param name="doVibrateFirst">是否先振动</param>
- /// <param name="doCaptureFirst">是否先拍照</param>
- /// <param name="cancellationToken"></param>
- /// <returns></returns>
- 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>
- /// Feeder拍照后,拍照失败时,执行Feeder
- /// </summary>
- /// <param name="Feeder"></param>
- /// <param name="procedure"></param>
- /// <returns></returns>
- 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>
- /// 执行Feeder料仓供料及振动集合
- /// </summary>
- /// <param name="feeder"></param>
- /// <param name="works"></param>
- /// <returns></returns>
- 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>
- /// <param name="feeder"></param>
- /// <param name="works"></param>
- /// <param name="cancellationToken"></param>
- /// <returns></returns>
- 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)
- {
- //if (BgModbusTcpCommunicate != null)
- //{
- // BgModbusTcpCommunicate.Slave.DataStore.HoldingRegisters[stockwork.Address] = 1;
- // await Task.Delay(stockwork.Duration);
- // BgModbusTcpCommunicate.Slave.DataStore.HoldingRegisters[stockwork.Address] = 0;
- //}
- }
- 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>
- /// <param name="feeder"></param>
- /// <param name="feederwork"></param>
- /// <param name="cancellationToken"></param>
- /// <param name="isUpdateParame"></param>
- /// <returns></returns>
- 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振动集合
- /// </summary>
- /// <param name="feeder"></param>
- /// <param name="works"></param>
- /// <param name="cancellationToken"></param>
- /// <param name="isUpdateParame"></param>
- /// <returns></returns>
- public async Task ExecuteFeederWorks(IVoiceCoilMotorFeeder feeder, FeederWorks works, CancellationToken cancellationToken, bool isUpdateParame = true)
- {
- //执行配置的Feeder振动任务
- 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;
- }
- }
- }
- }
- #endregion
- }
- }
|