| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037 |
- using Basler.Pylon;
- using Cognex.VisionPro;
- using Cognex.VisionPro.ToolBlock;
- using CSScripting;
- using MathNet.Numerics.Distributions;
- using MathNet.Numerics.LinearAlgebra;
- using MathNet.Numerics.RootFinding;
- using NPOI.SS.Formula.Functions;
- using NPOI.Util;
- using Opc.Ua;
- using OpenCvSharp;
- using OpenCvSharp.Flann;
- using Prism.Events;
- using Prism.Ioc;
- using Prism.Mvvm;
- using Prism.Regions;
- using Prism.Services.Dialogs;
- using System;
- using System.Collections;
- using System.Collections.Generic;
- using System.Collections.ObjectModel;
- using System.ComponentModel;
- using System.Drawing;
- using System.IO;
- using System.Linq;
- using System.Net.Sockets;
- using System.Reflection.Metadata;
- using System.Security.Cryptography;
- using System.Text;
- using System.Threading;
- using System.Threading.Tasks;
- using System.Windows;
- using System.Windows.Documents;
- using System.Windows.Interop;
- using System.Windows.Media;
- using System.Windows.Media.Media3D;
- using Team.FFFeederService;
- using Team.FFFeederService.Interfaces;
- using TeamAAS_VP;
- using TeamAAS_VP.Core.PLCs;
- using TeamAAS_VP.Core.Robots;
- using TeamAAS_VP.Core.ScrewDriver;
- 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 TeamAAS_VP.Services;
- using TeamAAS_VP.ViewModels.Home;
- using TouchSocket.Core;
- using TouchSocket.Sockets;
- using static MaterialDesignThemes.Wpf.Theme.ToolBar;
- using static Org.BouncyCastle.Math.EC.ECCurve;
- using static System.Windows.Forms.AxHost;
- namespace TeamAAS_VP.Core
- {
- public class Management : BindableBase
- {
- #region 字段
- IRegionManager _regionManager;
- IEventAggregator _eventAggregator;
- IContainerProvider _container;
- IConfigService _configService;
- IRobotService _robotService;
- ICameraService _cameraService;
- IFeederService _feederService;
- IPlcService _plcService;
- ILightManagerService _lightManagerService;
- IProductService _productService;
- ICalibrationService _calibrationService;
- IRemoteCommandService _remoteCommandService;
- ISystemDatabaseService _systemDatabaseService;
- Timer yieldtimer;
- private DateTime StartTime = DateTime.Now;
- #endregion
- #region 属性
- private ObservableCollection<ShowRender> _Renders;
- /// <summary>
- /// 显示界面
- /// </summary>
- public ObservableCollection<ShowRender> Renders
- {
- get { return _Renders; }
- set { SetProperty(ref _Renders, value); }
- }
- private ProductModel _CurrentProduct;
- /// <summary>
- /// 当前产品
- /// </summary>
- public ProductModel CurrentProduct
- {
- get { return _CurrentProduct; }
- set { SetProperty(ref _CurrentProduct, value); }
- }
- public BgCommunicate BgCommunicate { get; private set; }
- public BgModbusTcpCommunicate BgModbusTcpCommunicate { get; private set; }
- private ObservableCollection<StatusInfo> _Status = new ObservableCollection<StatusInfo>();
- /// <summary>
- /// 状态栏集合
- /// </summary>
- public ObservableCollection<StatusInfo> Status
- {
- get { return _Status; }
- set { SetProperty(ref _Status, value); }
- }
- private Int64 _TotalQuantity;
- /// <summary>
- /// 总产量
- /// </summary>
- public Int64 TotalQuantity
- {
- get { return _TotalQuantity; }
- set { SetProperty(ref _TotalQuantity, value); }
- }
- private Int64 _TotalQuantityToday;
- /// <summary>
- /// 当天的总产量
- /// </summary>
- public Int64 TotalQuantityToday
- {
- get { return _TotalQuantityToday; }
- set { SetProperty(ref _TotalQuantityToday, value); }
- }
- private Int64 _CurrentUPH;
- /// <summary>
- /// 当前的UPH
- /// </summary>
- public Int64 CurrentUPH
- {
- get { return _CurrentUPH; }
- set { SetProperty(ref _CurrentUPH, value); }
- }
- private XYD_ScrewDriver _ScrewDriver;
- public XYD_ScrewDriver ScrewDriver
- {
- get { return _ScrewDriver; }
- set { SetProperty(ref _ScrewDriver, value); }
- }
- public Dictionary<string, object> BackupObject { get; set; } = new Dictionary<string, object>();
- #endregion
- #region 命令
- #endregion
- #region 事件
- #endregion
- public Management(IRegionManager regionManager, IEventAggregator ea, IContainerProvider container, IConfigService configService,
- IRobotService robotService, ICameraService cameraService, IFeederService feederService, IPlcService plcService, IProductService productService,
- ICalibrationService calibrationService, IRemoteCommandService remoteCommandService, ISystemDatabaseService systemDatabaseService, ILightManagerService lightManagerService)
- {
- _regionManager = regionManager;
- _eventAggregator = ea;
- _container = container;
- _configService = configService;
- _robotService = robotService;
- _cameraService = cameraService;
- _feederService = feederService;
- _plcService = plcService;
- _calibrationService = calibrationService;
- yieldtimer = new Timer(DoYieldTime, null, 10000, 1000);
- Renders = new ObservableCollection<ShowRender>();
- _configService = configService;
- _productService = productService;
- _remoteCommandService = remoteCommandService;
- _systemDatabaseService = systemDatabaseService;
- _lightManagerService = lightManagerService;
- }
- #region 初始化硬件模块
- /// <summary>
- /// 初始化Feeder
- /// </summary>
- /// <returns></returns>
- public async Task<(bool IsSucceed, string Msg)> InitFeeders()
- {
- var feeders = _configService.GetAllFeeders();
- StringBuilder sb = new StringBuilder();
- foreach (var item in feeders)
- {
- _feederService.CreateFeeder(item.Id, item.FeederNo, item.FeederName, item.IP, item.Port, item.FeederBrand);
- var feeder = _feederService.GetFeeder(item.Id);
- Status.Add(new StatusInfo(item.Id, item.FeederName + $"{Lang.未连接}", new SolidColorBrush(Colors.Red)));
- try
- {
- feeder.FeederConnectionStatusChanged += Management_FeederConnectionStatusChanged;
- await feeder.ConnectAsync(); //连接Feeder
- //SendTaskMessage($"{item.FeederName}已连接!", MessageLevel.Debug);
- }
- catch (Exception ex)
- {
- sb.AppendLine($"{item.FeederName}:{Lang.断开连接}![{ex.Message}]");
- SendTaskMessage($"{item.FeederName}{Lang.断开连接}!", MessageLevel.Alarm);
- }
- }
- if (sb.Length == 0)
- {
- return (true, "");
- }
- else
- {
- return (false, sb.ToString());
- }
- }
- /// <summary>
- /// 初始化机器人
- /// </summary>
- /// <returns></returns>
- public async Task<(bool IsSucceed, string Msg)> InitRobots()
- {
- var robots = _configService.GetAllRobots();
- StringBuilder sb = new StringBuilder();
- foreach (var item in robots)
- {
- _robotService.CreateRobot(item.Id, item);
- try
- {
- Status.Add(new StatusInfo(item.Id, item.RobotName + $"{Lang.未连接}", new SolidColorBrush(Colors.Red)));
- var robot = _robotService.GetRobot(item.Id);
- robot.ReceivedEvent += Management_ReceivedEvent;
- robot.SendEvent += Management_SendEvent;
- robot.ConnectedEvent += Management_ConnectedEvent;
- robot.DisconnectedEvent += Management_DisconnectedEvent;
- await robot.ConnectAsync(); //连接Robot
- SendTaskMessage($"{item.RobotName}{Lang.已连接}!", MessageLevel.Debug);
- }
- catch (Exception ex)
- {
- sb.AppendLine($"{item.RobotName}:{Lang.断开连接}![{ex.Message}]");
- SendTaskMessage($"{item.RobotName}{Lang.断开连接}!", MessageLevel.Alarm);
- }
- }
- if (sb.Length == 0)
- {
- return (true, "");
- }
- else
- {
- return (false, sb.ToString());
- }
- }
- /// <summary>
- /// 初始化PLC
- /// </summary>
- /// <returns></returns>
- public async Task<(bool IsSucceed, string Msg)> InitPlc()
- {
- var plcs = _configService.GetAllPlcs();
- StringBuilder sb = new StringBuilder();
- foreach (var item in plcs)
- {
- try
- {
- _plcService.CreatePlc(item.Id, item);
- var plc = _plcService.GetPlc(item.Id);
- Status.Add(new StatusInfo(item.Id, item.Name + $"{Lang.未连接}", new SolidColorBrush(Colors.Red)));
- plc.ConnectChangedEvent += Management_PlcConnectChangedEvent;
- await plc.ConnectAsync(); //连接PLC
- //SendTaskMessage($"{item.Name}{Lang.已连接}!", MessageLevel.Debug);
- }
- catch (Exception ex)
- {
- sb.AppendLine($"{item.Name}:{Lang.断开连接}![{ex.Message}]");
- SendTaskMessage($"{item.Name}{Lang.断开连接}!", MessageLevel.Alarm);
- }
- }
- try
- {
- await WriteSystemParameterToPlcAsync(_configService.GetSystemConfiguration());
- RegisterPlcMonitorAddress();
- }
- catch (Exception ex)
- {
- LogHelper.WriteLogError("为PLC写入系统参数和订阅变量时出错", ex);
- }
- if (sb.Length == 0)
- {
- return (true, "");
- }
- else
- {
- return (false, sb.ToString());
- }
- }
- /// <summary>
- /// 初始化相机
- /// </summary>
- /// <returns></returns>
- public async Task<(bool IsSucceed, string Msg)> InitCameras()
- {
- var cameras = _configService.GetAllCameras();
- StringBuilder sb = new StringBuilder();
- foreach (var item in cameras)
- {
- try
- {
- Renders.Add(new ShowRender() { Id = item.Id, CameraName = item.CameraName });
- _cameraService.CreateCamera(item.Id, item);
- var camera = _cameraService.GetCamera(item.Id);
- Status.Add(new StatusInfo(item.Id, item.CameraName + $"{Lang.未连接}", new SolidColorBrush(Colors.Red)));
- camera.CameraConnectChangedEvent += Management_CameraConnectChangedEvent;
- try
- {
- if (await camera.OpenDeviceAsync())
- {
- SendTaskMessage($"{item.CameraName}{Lang.已连接}!", MessageLevel.Debug);
- }
- else
- {
- SendTaskMessage($"{item.CameraName}{Lang.连接失败}!", MessageLevel.Alarm);
- sb.AppendLine($"{item.CameraName}:{Lang.连接失败}!");
- }
- }
- catch (Exception ex)
- {
- SendTaskMessage($"{item.CameraName}{ex.Message}!", MessageLevel.Alarm);
- sb.AppendLine($"{item.CameraName}:{ex.Message}!");
- }
- }
- catch (Exception ex)
- {
- SendTaskMessage($"{item.CameraName}{Lang.连接失败}!", MessageLevel.Alarm);
- sb.AppendLine($"{item.CameraName}:{Lang.连接失败}!:{ex.Message}");
- }
- }
- _container.Resolve<ShowVisionRenderViewModel>().Renders = Renders;
- if (sb.Length == 0)
- {
- return (true, "");
- }
- else
- {
- return (false, sb.ToString());
- }
- }
- /// <summary>
- /// 初始化光源控制器
- /// </summary>
- /// <returns></returns>
- public async Task<(bool IsSucceed, string Msg)> InitLightControllers()
- {
- var lightcontrollers = _configService.GetAllLightControllers();
- StringBuilder sb = new StringBuilder();
- foreach (var item in lightcontrollers)
- {
- try
- {
- var lishtCtr = await _lightManagerService.RegisterControllerAsync(item.Id, item);
- //var lightcontroller = _cameraService.GetLightController(item.Id);
- //await lightcontroller.ConnectAsync(); //连接光源控制器
- //SendTaskMessage($"{item.LightControllerName}{Lang.已连接}!", MessageLevel.Debug);
- }
- catch (Exception ex)
- {
- //sb.AppendLine($"{item.LightControllerName}:{Lang.断开连接}![{ex.Message}]");
- //SendTaskMessage($"{item.LightControllerName}{Lang.断开连接}!", MessageLevel.Alarm);
- }
- }
- if (lightcontrollers.Count > 0)
- {
- var result = await _lightManagerService.ConnectAllAsync();
- if (result)
- {
- return (true, "");
- }
- else
- {
- return (false, "Light Controller Connect Failed!");
- }
- }
- return (true, "");
- //if (sb.Length == 0)
- //{
- // return (true, "");
- //}
- //else
- //{
- // return (false, sb.ToString());
- //}
- }
- /// <summary>
- /// 初始化后台TCP服务器通讯
- /// </summary>
- public void InitBgTcp()
- {
- var config = _configService.GetBgTcp();
- try
- {
- BgCommunicate = new BgCommunicate(config);
- BgCommunicate.ConnectedEvent += BgCommunicate_ConnectedEvent;
- BgCommunicate.DisconnectedEvent += BgCommunicate_DisconnectedEvent;
- BgCommunicate.ReceivedEvent += BgCommunicate_ReceivedEvent;
- BgCommunicate.SendEvent += BgCommunicate_SendEvent;
- BgCommunicate.StartListening();
- SendTaskMessage($"{Lang.已开启监听端口}:{config.Port}", MessageLevel.Debug);
- }
- catch (Exception ex)
- {
- SendTaskMessage($"{Lang.未开启监听端口}:{config.Port}", MessageLevel.Error);
- LogHelper.WriteLogError("开启后台服务器通讯时出错!", ex);
- }
- }
- /// <summary>
- /// 初始化后台ModbusTCP从站
- /// </summary>
- public void InitModbusTcp()
- {
- try
- {
- var config = _configService.GetBgModbusTcp();
- BgModbusTcpCommunicate = new BgModbusTcpCommunicate(config);
- if (config.IsEnabled)
- {
- BgModbusTcpCommunicate.Listen();
- SendTaskMessage($"Start Modbus Tcp Slave:{BgModbusTcpCommunicate.IP}:{BgModbusTcpCommunicate.Port}:{BgModbusTcpCommunicate.SlaveID}", MessageLevel.Debug);
- }
- }
- catch (Exception ex)
- {
- SendTaskMessage($"No Start Modbus Tcp Slave:{ex.Message}", MessageLevel.Alarm);
- LogHelper.WriteLogError("开启后台Modbus TCP通讯时出错!", ex);
- }
- }
- /// <summary>
- /// 初始化后台脚本
- /// </summary>
- public void InitBackgroundcript()
- {
- try
- {
- if (!Directory.Exists(FilePath.BackgroundScriptPath))
- {
- Directory.CreateDirectory(FilePath.BackgroundScriptPath);
- }
- try
- {
- string[] files = Directory.GetFiles(FilePath.BackgroundScriptPath);
- List<string> ScriptFilesCollection = new List<string>();
- foreach (string file in files)
- {
- string fileName = Path.GetFileName(file);
- string fileExtension = Path.GetExtension(file);
- if (fileExtension == ".cs")
- {
- ScriptFilesCollection.Add(file);
- }
- }
- foreach (var item in ScriptFilesCollection)
- {
- try
- {
- string script = FileHelper.ReadFile(item);
- SendTaskMessage($"{Lang.执行脚本}:{item}", MessageLevel.Info);
- Task.Factory.StartNew(() =>
- {
- ScriptHelper.ExecuteScriptingAsync(script, _regionManager, _eventAggregator, _container, rst =>
- {
- if (!rst.Item1)
- {
- foreach (var err in rst.Item2)
- {
- SendTaskMessage($"{Lang.后台脚本出错}:{err}", MessageLevel.Error);
- }
- }
- });
- });
- }
- catch (Exception ex)
- {
- LogHelper.WriteLogError($"开启脚本时出错:{item}", ex);
- }
- }
- }
- catch (Exception ex)
- {
- LogHelper.WriteLogError("读取本地脚本文件列表时出错", ex);
- }
- }
- catch (Exception ex)
- {
- LogHelper.WriteLogError("开启后台脚本时出错!", ex);
- }
- }
- /// <summary>
- /// 初始化电批
- /// </summary>
- /// <returns></returns>
- public async Task InitScrewDriver()
- {
- try
- {
- var screwDriverConfig = _configService.GetScrewDriverConfig();
- ScrewDriver = new XYD_ScrewDriver(screwDriverConfig.IPAdress, screwDriverConfig.Port);
- Status.Add(new StatusInfo(ScrewDriver.Id, "电批未连接", new SolidColorBrush(Colors.Red)));
- ScrewDriver.ConnectStateChangedEvent += ScrewDriver_ConnectStateChangedEvent;
- ScrewDriver.SendTimeout = screwDriverConfig.SendTimeout;
- screwDriverConfig.ReceiveTimeout = screwDriverConfig.ReceiveTimeout;
- var isConnected = await ScrewDriver.ConnectAsync();
- if (isConnected)
- {
- SendTaskMessage($"电批已连接", MessageLevel.Debug);
- }
- else
- {
- SendTaskMessage($"电批连接失败", MessageLevel.Error);
- }
- }
- catch (Exception ex)
- {
- SendTaskMessage($"电批连接失败:{ex.Message}", MessageLevel.Alarm);
- LogHelper.WriteLogError("连接电批时出错!", ex);
- }
- }
- #endregion
- #region 机器人指令执行
- public Dictionary<Guid, CancellationTokenSource> RobotTCPCollection = new Dictionary<Guid, CancellationTokenSource>();
- /// <summary>
- /// 机器人TCP接收
- /// </summary>
- /// <param name="arg1"></param>
- /// <param name="arg2"></param>
- /// <param name="arg3"></param>
- private async void Management_ReceivedEvent(Guid robotid, object arg2, TouchSocket.Sockets.ReceivedDataEventArgs e)
- {
- try
- {
- if (!RobotTCPCollection.ContainsKey(robotid))
- RobotTCPCollection.Add(robotid, new CancellationTokenSource());
- else
- {
- if (RobotTCPCollection[robotid].IsCancellationRequested)
- {
- RobotTCPCollection[robotid] = new CancellationTokenSource();
- }
- }
- var robot = await _robotService.GetRobotAsync(robotid);
- //从服务器收到信息。但是一般byteBlock和requestInfo会根据适配器呈现不同的值。
- var buffer = e.ByteBlock.Span.ToString(robot.GetEncoding());
- SendTaskMessage($"{robot.Name}Received:{buffer}", MessageLevel.Info);
- var _ = _remoteCommandService.ExecuteAsync(buffer, RobotTCPCollection[robotid].Token, async msg =>
- {
- try
- {
- if (robot.ConnectType == TCPConnectType.Client)
- {
- if (robot.IsConnected)
- {
- await robot.SendAsync($"{msg}");
- }
- }
- else
- {
- var cient = (ITcpSessionClient)arg2;
- if (cient.Online)
- {
- await robot.SendAsync(cient, $"{msg}");
- }
- }
- }
- catch (Exception ex)
- {
- LogHelper.WriteLogError("TCP发送数据时出错!", ex);
- SendTaskMessage(ex.Message, MessageLevel.Alarm);
- }
- });
- }
- catch (Exception ex)
- {
- LogHelper.WriteLogError("处理机器人接收的命令时出错!", ex);
- SendTaskMessage(ex.Message, MessageLevel.Alarm);
- }
- }
- #endregion
- #region 机器人&Feeder&相机连接状态事件
- /// <summary>
- /// 机器人发送事件
- /// </summary>
- /// <param name="arg1"></param>
- /// <param name="arg2"></param>
- /// <param name="arg3"></param>
- /// <exception cref="NotImplementedException"></exception>
- private void Management_SendEvent(Guid robotid, object arg2, string arg3)
- {
- var r = _robotService.GetRobot(robotid);
- SendTaskMessage($"{r.Name}Send:{arg3}", MessageLevel.Info);
- }
- /// <summary>
- /// 机器人断开连接时
- /// </summary>
- /// <param name="arg1"></param>
- /// <param name="arg2"></param>
- /// <param name="arg3"></param>
- /// <exception cref="NotImplementedException"></exception>
- private void Management_DisconnectedEvent(Guid robotid, object arg2, ClosedEventArgs arg3)
- {
- if (RobotTCPCollection.ContainsKey(robotid))
- {
- RobotTCPCollection[robotid].Cancel();
- }
- var r = _configService.GetRobot(robotid);
- if (r.ConnectType == TCPConnectType.Server)
- {
- ITcpSessionClient socketClient = arg2 as ITcpSessionClient;
- SendTaskMessage($"{r.RobotName}[{socketClient.Id}:{socketClient.IP}]{Lang.断开连接}!", MessageLevel.Error);
- var robot = _robotService.GetRobot(robotid);
- if (robot.TcpService.Count < 1)
- {
- var sta = Status.FirstOrDefault(s => s.ID == robotid);
- App.Current.Dispatcher.Invoke(new
- Action(() =>
- {
- sta.Message = $"{r.RobotName}{Lang.未连接}";
- sta.Background = new SolidColorBrush(Colors.Red);
- }));
- }
- }
- else
- {
- SendTaskMessage($"{r.RobotName}{Lang.断开连接}!", MessageLevel.Error);
- var sta = Status.FirstOrDefault(s => s.ID == robotid);
- App.Current.Dispatcher.Invoke(new
- Action(() =>
- {
- sta.Message = $"{r.RobotName}{Lang.断开连接}";
- sta.Background = new SolidColorBrush(Colors.Red);
- }));
- }
- }
- /// <summary>
- /// 机器人连接成功时
- /// </summary>
- /// <param name="arg1"></param>
- /// <param name="arg2"></param>
- /// <param name="arg3"></param>
- /// <exception cref="NotImplementedException"></exception>
- private void Management_ConnectedEvent(Guid robotid, object arg2, ConnectedEventArgs arg3)
- {
- var r = _configService.GetRobot(robotid);
- if (r.ConnectType == TCPConnectType.Server)
- {
- ITcpSessionClient socketClient = arg2 as ITcpSessionClient;
- SendTaskMessage($"{r.RobotName}[{socketClient.Id}:{socketClient.IP}]{Lang.已连接}!", MessageLevel.Debug);
- var robot = _robotService.GetRobot(robotid);
- if (robot.TcpService.Count > 0)
- {
- var sta = Status.FirstOrDefault(s => s.ID == robotid);
- App.Current.Dispatcher.Invoke(new
- Action(() =>
- {
- sta.Message = $"{r.RobotName}{Lang.已连接}";
- sta.Background = new SolidColorBrush(Colors.Green);
- }));
- }
- }
- else
- {
- SendTaskMessage($"{r.RobotName}{Lang.已连接}!", MessageLevel.Debug);
- var sta = Status.FirstOrDefault(s => s.ID == robotid);
- App.Current.Dispatcher.Invoke(new
- Action(() =>
- {
- sta.Message = $"{r.RobotName}{Lang.已连接}";
- sta.Background = new SolidColorBrush(Colors.Green);
- }));
- }
- }
- /// <summary>
- /// Feeder连接状态改变时
- /// </summary>
- /// <param name="sender"></param>
- /// <param name="state"></param>
- private void Management_FeederConnectionStatusChanged(object sender, bool state)
- {
- IFeeder feeder = sender as IFeeder;
- var sta = Status.FirstOrDefault(s => s.ID == feeder.Id);
- if (state)
- {
- App.Current.Dispatcher.Invoke(new
- Action(() =>
- {
- sta.Message = $"{feeder.Name}{Lang.已连接}";
- sta.Background = new SolidColorBrush(Colors.Green);
- }));
- SendTaskMessage($"{feeder.Name}{Lang.已连接}!", MessageLevel.Debug);
- }
- else
- {
- App.Current.Dispatcher.Invoke(new
- Action(() =>
- {
- sta.Message = $"{feeder.Name}{Lang.未连接}";
- sta.Background = new SolidColorBrush(Colors.Red);
- }));
- SendTaskMessage($"{feeder.Name}{Lang.断开连接}!", MessageLevel.Error);
- }
- }
- /// <summary>
- /// 相机连接或者断开时
- /// </summary>
- /// <param name="id"></param>
- /// <param name="state"></param>
- private void Management_CameraConnectChangedEvent(Guid id, bool state)
- {
- var sta = Status.FirstOrDefault(s => s.ID == id);
- var camera = _configService.GetCamera(id);
- if (sta != null && camera != null)
- {
- if (state)
- {
- App.Current.Dispatcher.Invoke(new Action(() =>
- {
- sta.Message = $"{camera.CameraName}{Lang.已连接}";
- sta.Background = new SolidColorBrush(Colors.Green);
- }));
- }
- else
- {
- App.Current.Dispatcher.Invoke(new Action(() =>
- {
- sta.Message = $"{camera.CameraName}{Lang.断开连接}";
- sta.Background = new SolidColorBrush(Colors.Red);
- }));
- }
- }
- }
- /// <summary>
- /// PLC连接状态改变事件
- /// </summary>
- /// <param name="plc"></param>
- /// <param name="isconnected"></param>
- private void Management_PlcConnectChangedEvent(object sender, bool isconnected)
- {
- IPlc plc = sender as IPlc;
- var sta = Status.FirstOrDefault(s => s.ID == plc.Id);
- if (plc.IsConnected)
- {
- SendTaskMessage($"{plc.Name}{Lang.已连接}!", MessageLevel.Debug);
- if (sta == null) return;
- App.Current.Dispatcher.Invoke(new
- Action(() =>
- {
- sta.Message = $"{plc.Name}{Lang.已连接}";
- sta.Background = new SolidColorBrush(Colors.Green);
- }));
- }
- else
- {
- SendTaskMessage($"{plc.Name}{Lang.断开连接}!", MessageLevel.Error);
- if (sta == null) return;
- App.Current.Dispatcher.Invoke(new
- Action(() =>
- {
- sta.Message = $"{plc.Name}{Lang.未连接}";
- sta.Background = new SolidColorBrush(Colors.Red);
- }));
- }
- }
- /// <summary>
- /// 电批连接状态改变时
- /// </summary>
- /// <param name="screwDevice"></param>
- /// <param name="state"></param>
- private void ScrewDriver_ConnectStateChangedEvent(object screwDevice, bool state)
- {
- try
- {
- XYD_ScrewDriver screwDriver = screwDevice as XYD_ScrewDriver;
- if (state)
- {
- SendTaskMessage($"电批{Lang.已连接}!", MessageLevel.Debug);
- var sta = Status.FirstOrDefault(s => s.ID == screwDriver.Id);
- App.Current.Dispatcher.Invoke(new
- Action(() =>
- {
- sta.Message = $"电批{Lang.已连接}";
- sta.Background = new SolidColorBrush(Colors.Green);
- }));
- }
- else
- {
- SendTaskMessage($"电批{Lang.未连接}!", MessageLevel.Error);
- var sta = Status.FirstOrDefault(s => s.ID == screwDriver.Id);
- App.Current.Dispatcher.Invoke(new
- Action(() =>
- {
- sta.Message = $"电批{Lang.未连接}";
- sta.Background = new SolidColorBrush(Colors.Red);
- }));
- }
- }
- catch (Exception ex)
- {
- LogHelper.WriteLogError("电批连接状态改变时出错了", ex);
- }
- }
- #endregion
- #region 后台服务器通讯事件
- private void BgCommunicate_SendEvent(ITcpSessionClient client, string msg)
- {
- SendTaskMessage($"{Lang.服务器}[{client.ServicePort}] Send To {Lang.客户端}[{client.Id}:{client.IP}]:{msg}", MessageLevel.Info);
- }
- public Dictionary<string, CancellationTokenSource> BgCommunicateollection = new Dictionary<string, CancellationTokenSource>();
- private async void BgCommunicate_ReceivedEvent(ITcpSessionClient client, string msg)
- {
- try
- {
- if (!BgCommunicateollection.ContainsKey(client.Id))
- {
- BgCommunicateollection.Add(client.Id, new CancellationTokenSource());
- }
- SendTaskMessage($"{Lang.服务器}[{client.ServicePort}]ReceiveFor{Lang.客户端}[{client.Id}:{client.IP}]:{msg}", MessageLevel.Info);
- var _ = _remoteCommandService.ExecuteAsync(msg, BgCommunicateollection[client.Id].Token, async response =>
- {
- try
- {
- if (!client.Online)
- {
- return;
- }
- await BgCommunicate.SendAsync(client, $"{response}");
- }
- catch (Exception ex)
- {
- LogHelper.WriteLogError("后台TCP发送数据时出错!", ex);
- SendTaskMessage(ex.Message, MessageLevel.Alarm);
- }
- });
- }
- catch (Exception ex)
- {
- LogHelper.WriteLogError("处理后台服务器接收的命令时出错!", ex);
- SendTaskMessage(ex.Message, MessageLevel.Alarm);
- }
- }
- private void BgCommunicate_DisconnectedEvent(ITcpSessionClient client, ClosedEventArgs e)
- {
- SendTaskMessage($"{Lang.服务器}[{client.ServicePort}]{Lang.客户端}[{client.Id}:{client.IP}]{Lang.断开连接}!", MessageLevel.Alarm);
- if (BgCommunicateollection.ContainsKey(client.Id))
- {
- BgCommunicateollection[client.Id].Cancel();
- }
- }
- private void BgCommunicate_ConnectedEvent(ITcpSessionClient client, ConnectedEventArgs e)
- {
- SendTaskMessage($"{Lang.服务器}[{client.ServicePort}]{Lang.客户端}[{client.Id}:{client.IP}]{Lang.连接成功}!", MessageLevel.Debug);
- }
- #endregion
- #region PLC
- /// <summary>
- /// 将系统参数写入PLC
- /// </summary>
- /// <param name="systemConfiguration"></param>
- /// <returns></returns>
- public async Task WriteSystemParameterToPlcAsync(SystemConfiguration systemConfiguration)
- {
- var addressConfig = _configService.GetPlcAddresses();
- var plc = _plcService.GetPlcByNumber(addressConfig.PlcNo) as OpcUaClientPLC;
- if (plc == null || !plc.IsConnected) return;
- Dictionary<string, object> nodeValues = new Dictionary<string, object>();
- nodeValues.Add(addressConfig.Out_WorkMode.Address, (Int16)systemConfiguration.WorkMode);
- nodeValues.Add(addressConfig.Out_PickPointNum.Address, (Int16)systemConfiguration.PickPointNum);
- nodeValues.Add(addressConfig.Out_DowmCameraNum.Address, (Int16)systemConfiguration.DowmCameraNum);
- nodeValues.Add(addressConfig.Out_UpCameraPickNum.Address, (Int16)systemConfiguration.UpCameraPickNum);
- nodeValues.Add(addressConfig.Out_UpCameraPutNum.Address, (Int16)systemConfiguration.UpCameraPutNum);
- nodeValues.Add(addressConfig.Out_UPCameracheckNum.Address, (Int16)systemConfiguration.UPCameracheckNum);
- nodeValues.Add(addressConfig.Out_FixedCameraPickNum.Address, (Int16)systemConfiguration.FixedCameraPickNum);
- nodeValues.Add(addressConfig.Out_FixedCameraPutNum.Address, (Int16)systemConfiguration.FixedCameraPutNum);
- nodeValues.Add(addressConfig.Out_FixedCameracheckNum.Address, (Int16)systemConfiguration.FixedCameracheckNum);
- nodeValues.Add(addressConfig.Out_ScrewTeachNum.Address, (Int16)systemConfiguration.ScrewTeachNum);
- var res = await plc.WriteNodesAsync(nodeValues);
- }
- /// <summary>
- /// 注册需要监控的PLC地址
- /// </summary>
- public void RegisterPlcMonitorAddress()
- {
- var addressConfig = _configService.GetPlcAddresses();
- var plc = _plcService.GetPlcByNumber(addressConfig.PlcNo) as OpcUaClientPLC;
- if (plc == null || !plc.IsConnected) return;
- //PLC地址数组
- List<string> monitorNodeIds = new List<string>()
- {
- addressConfig.In_DowmCameraExe.Address,
- addressConfig.In_UpCameraPickExe.Address,
- addressConfig.In_UpCameraPutExe.Address,
- addressConfig.In_UPCameracheckExe.Address,
- addressConfig.In_FixedCameraPickExe.Address,
- addressConfig.In_FixedCameraPutExe.Address,
- addressConfig.In_FixedCameracheckExe.Address,
- addressConfig.In_WorkStart.Address,
- addressConfig.In_WorkDone.Address,
- addressConfig.In_RequestPosition.Address,
- addressConfig.In_ScrewTeachExe.Address,
- addressConfig.In_PickINC.Address,
- };
- for (int i = 0; i < 10; i++)
- {
- monitorNodeIds.Add(string.Format(addressConfig.In_MesCheck.Address, i));
- }
- //订阅PLC地址变化
- plc.SubscribeNodes("AutoSensor", monitorNodeIds, PlcCommandTrigger);
- }
- /// <summary>
- /// 写入点位信息给PLC
- /// </summary>
- /// <returns></returns>
- public async Task WritePositionToPlcAsync()
- {
- var addressConfig = _configService.GetPlcAddresses();
- var plc = _plcService.GetPlcByNumber(addressConfig.PlcNo) as OpcUaClientPLC;
- if (plc == null || !plc.IsConnected) return;
- var current = _productService.GetCurrentProduct();
- if (current == null) return;
- if (current.PickCameraPoints != null && current.PickCameraPoints.Count > 0)
- {
- foreach (var item in current.PickCameraPoints)
- {
- await item.WriteToPlcAddress(addressConfig.Out_PickCamera, plc);
- }
- }
- if (current.PickPoints != null && current.PickPoints.Count > 0)
- {
- foreach (var item in current.PickPoints)
- {
- await item.WriteToPlcAddress(addressConfig.Out_Pick, plc);
- }
- }
- if (current.SecPosCameraPoints != null && current.SecPosCameraPoints.Count > 0)
- {
- foreach (var item in current.SecPosCameraPoints)
- {
- await item.WriteToPlcAddress(addressConfig.Out_SecPosCamera, plc);
- }
- }
- if (current.ScrewCameraPoints != null && current.ScrewCameraPoints.Count > 0)
- {
- foreach (var item in current.ScrewCameraPoints)
- {
- await item.WriteToPlcAddress(addressConfig.Out_ScrewCamera, plc);
- }
- }
- if (current.ScrewPoints != null && current.ScrewPoints.Count > 0)
- {
- foreach (var item in current.ScrewPoints)
- {
- await item.WriteToPlcAddressEx(addressConfig.Out_Screw, plc);
- }
- await plc.WriteNodeAsync(addressConfig.Out_WorkNum.Address, (Int16)current.ScrewPoints.Count);
- }
- if (current.CheckCameraPoints != null && current.CheckCameraPoints.Count > 0)
- {
- foreach (var item in current.CheckCameraPoints)
- {
- await item.WriteToPlcAddress(addressConfig.Out_CheckCamera, plc);
- }
- }
- }
- /// <summary>
- /// 固定向上相机拍照结果
- /// </summary>
- OpenCvSharp.Point3f[] DowmCameraResults = new OpenCvSharp.Point3f[10];
- /// <summary>
- /// 移动向下相机拍照结果
- /// </summary>
- OpenCvSharp.Point3f[] UpCameraPutResults = new OpenCvSharp.Point3f[10];
- /// <summary>
- /// 二次定位相机的工具坐标
- /// </summary>
- PointF DownTool = new PointF();
- double _FixedUpCameraAngle = 0;
- double _MoveCameraAngle = 0;
- /// <summary>
- /// PLC命令触发时
- /// </summary>
- /// <param name="tuple"></param>
- private async void PlcCommandTrigger((string key, string nodeId, object value) tuple)
- {
- try
- {
- if (tuple.key != "AutoSensor")
- {
- return;
- }
- var addressConfig = _configService.GetPlcAddresses();
- var plc = _plcService.GetPlcByNumber(addressConfig.PlcNo) as OpcUaClientPLC;
- if (plc == null || !plc.IsConnected) return;
- // 获取当前产品
- var currentProduct = _productService.GetCurrentProduct();
- if (currentProduct == null)
- {
- return;
- }
- //获取产品编码
- _productService.CurrentProductCode = plc.ReadNode<string>(string.Format(addressConfig.In_Code.Address, 0));
- //如果产品编码为空,则以当前的时间戳作为编码
- if (string.IsNullOrEmpty(_productService.CurrentProductCode))
- {
- _productService.CurrentProductCode = DateTime.Now.ToString("yyyyMMddHHmmssfff");
- }
- bool isDryMode = plc.ReadNode<bool>(addressConfig.In_DryMode.Address);
- // 触发下相机拍照
- if (addressConfig.In_DowmCameraExe.Address.Contains(tuple.nodeId))
- {
- if (tuple.value is bool state)
- {
- if (state)
- {
- SendTaskMessage($"触发下相机拍照...", MessageLevel.Debug);
- //相机的编号
- Int16 cameraIndex = plc.ReadNode<Int16>(addressConfig.In_DowmCameraNum.Address);
- SendTaskMessage($"编号:{cameraIndex}", MessageLevel.Info);
- // 获取机器人当前坐标
- var robot = _robotService.GetAllRobots().FirstOrDefault();
- if (robot == null)
- {
- SendTaskMessage($"未找到机器人,无法执行上相机锁附/组装拍照视觉任务", MessageLevel.Alarm);
- await plc.WriteNodeAsync(addressConfig.Out_DownCameraStatus.Address, (Int16)2);
- return;
- }
- var currentPosition = robot.GetRobotPos();
- //如果下相机拍照的次数是1,则判断用时拍照的相机是几个
- int downCameraNum = _configService.GetSystemConfiguration().DowmCameraNum;
- if (downCameraNum == 1)
- {
- //如果下相机2的流程id为空,则表示只有一个下相机
- if (currentProduct.FixedUpCamera2ProcedureId == Guid.Empty)
- {
- //获取固定向上相机1的流程
- var process = _productService.GetCurrentProductProcedureModelById(currentProduct.FixedUpCamera1ProcedureId);
- if (process == null)
- {
- SendTaskMessage($"固定向上相机1视觉流程,流程ID:{currentProduct.FixedUpCamera1ProcedureId}", MessageLevel.Alarm);
- await plc.WriteNodeAsync(addressConfig.Out_DownCameraStatus.Address, (Int16)2);
- return;
- }
- // 执行视觉任务
- var _cts = new CancellationTokenSource();
- var visionResult = await _remoteCommandService.ExecutePhotoGetSinglePoint(process, null, new double[] { currentPosition.X, currentPosition.Y, currentPosition.U }, _cts.Token);
- if (isDryMode)
- {
- await plc.WriteNodeAsync(addressConfig.Out_DownCameraStatus.Address, (Int16)1);
- return;
- }
- if (visionResult.IsSucceed)
- {
- float toolX = (float)(visionResult.X - currentPosition.X);
- float toolY = (float)(visionResult.Y - currentPosition.Y);
- DowmCameraResults[cameraIndex] = new OpenCvSharp.Point3f(toolX, toolX, (float)visionResult.U);
- DownTool = new PointF(toolX, toolX);
- await plc.WriteNodeAsync(addressConfig.Out_DownCameraStatus.Address, (Int16)1);
- return;
- }
- else
- {
- await plc.WriteNodeAsync(addressConfig.Out_DownCameraStatus.Address, (Int16)2);
- return;
- }
- }
- else
- {
- //获取固定向上相机1的流程
- var process1 = _productService.GetCurrentProductProcedureModelById(currentProduct.FixedUpCamera1ProcedureId);
- if (process1 == null)
- {
- SendTaskMessage($"固定向上相机1视觉流程,流程ID:{currentProduct.FixedUpCamera1ProcedureId}", MessageLevel.Alarm);
- await plc.WriteNodeAsync(addressConfig.Out_DownCameraStatus.Address, (Int16)2);
- return;
- }
- //获取固定向上相机2的流程
- var process2 = _productService.GetCurrentProductProcedureModelById(currentProduct.FixedUpCamera2ProcedureId);
- if (process2 == null)
- {
- SendTaskMessage($"固定向上相机1视觉流程,流程ID:{currentProduct.FixedUpCamera2ProcedureId}", MessageLevel.Alarm);
- await plc.WriteNodeAsync(addressConfig.Out_DownCameraStatus.Address, (Int16)2);
- return;
- }
- // 执行视觉任务
- var _cts = new CancellationTokenSource();
- var task1 = _remoteCommandService.ExecutePhotoGetSinglePoint(process1, null, new double[] { currentPosition.X, currentPosition.Y, currentPosition.U }, _cts.Token);
- var task2 = _remoteCommandService.ExecutePhotoGetSinglePoint(process2, null, new double[] { currentPosition.X, currentPosition.Y, currentPosition.U }, _cts.Token);
- var visionResults = await Task.WhenAll(task1, task2);
- if (isDryMode)
- {
- await plc.WriteNodeAsync(addressConfig.Out_DownCameraStatus.Address, (Int16)1);
- return;
- }
- if (visionResults[0].IsSucceed && visionResults[1].IsSucceed)
- {
- float toolX = (float)(visionResults[0].X + visionResults[1].X) / 2;
- float toolY = (float)(visionResults[0].Y + visionResults[1].Y) / 2;
- _FixedUpCameraAngle = Common.CalculateAngleBetweenPointsDegrees(new PointF((float)visionResults[0].X, (float)visionResults[0].Y), new PointF((float)visionResults[1].X, (float)visionResults[1].Y));
- DowmCameraResults[cameraIndex] = new OpenCvSharp.Point3f(toolX, toolX, (float)_FixedUpCameraAngle);
- DownTool = new PointF(toolX, toolX);
- await plc.WriteNodeAsync(addressConfig.Out_DownCameraStatus.Address, (Int16)1);
- return;
- }
- else
- {
- await plc.WriteNodeAsync(addressConfig.Out_DownCameraStatus.Address, (Int16)2);
- return;
- }
- }
- }
- else if (downCameraNum == 2)
- {
- //如果下相机2的流程id为空,则表示只有一个下相机
- if (currentProduct.FixedUpCamera2ProcedureId == Guid.Empty)
- {
- //获取固定向上相机1的流程
- //var process = _productService.GetCurrentProductProcedureModelById(currentProduct.FixedUpCamera1ProcedureId);
- //if (process == null)
- //{
- // SendTaskMessage($"固定向上相机1视觉流程,流程ID:{currentProduct.FixedUpCamera1ProcedureId}", MessageLevel.Alarm);
- // await plc.WriteNodeAsync(addressConfig.Out_DownCameraStatus.Address, (Int16)2);
- // return;
- //}
- //// 执行视觉任务
- //var _cts = new CancellationTokenSource();
- //var visionResult = await _remoteCommandService.ExecutePhotoGetSinglePoint(process, null, new double[] { currentPosition.X, currentPosition.Y, currentPosition.U }, _cts.Token);
- //if (visionResult.IsSucceed)
- //{
- // float toolX = (float)(visionResult.X - currentPosition.X);
- // float toolY = (float)(visionResult.Y - currentPosition.Y);
- // DowmCameraResults[cameraIndex] = new PointF(toolX, toolX);
- // if (cameraIndex == downCameraNum)
- // {
- // //求取多个DowmCameraResults的中心点
- // DownTool = new PointF(toolX, toolX);
- // }
- // await plc.WriteNodeAsync(addressConfig.Out_DownCameraStatus.Address, (Int16)1);
- // return;
- //}
- //else
- //{
- // await plc.WriteNodeAsync(addressConfig.Out_DownCameraStatus.Address, (Int16)2);
- // return;
- //}
- //暂时没有应用场景,不支持
- await plc.WriteNodeAsync(addressConfig.Out_DownCameraStatus.Address, (Int16)2);
- return;
- }
- else
- {
- //获取固定向上相机1的流程
- var process1 = _productService.GetCurrentProductProcedureModelById(currentProduct.FixedUpCamera1ProcedureId);
- if (process1 == null)
- {
- SendTaskMessage($"固定向上相机1视觉流程,流程ID:{currentProduct.FixedUpCamera1ProcedureId}", MessageLevel.Alarm);
- await plc.WriteNodeAsync(addressConfig.Out_DownCameraStatus.Address, (Int16)2);
- return;
- }
- //获取固定向上相机2的流程
- var process2 = _productService.GetCurrentProductProcedureModelById(currentProduct.FixedUpCamera2ProcedureId);
- if (process2 == null)
- {
- SendTaskMessage($"固定向上相机1视觉流程,流程ID:{currentProduct.FixedUpCamera2ProcedureId}", MessageLevel.Alarm);
- await plc.WriteNodeAsync(addressConfig.Out_DownCameraStatus.Address, (Int16)2);
- return;
- }
- // 执行视觉任务
- var _cts = new CancellationTokenSource();
- var task1 = _remoteCommandService.ExecutePhotoGetSinglePoint(process1, null, new double[] { currentPosition.X, currentPosition.Y, currentPosition.U }, _cts.Token);
- var task2 = _remoteCommandService.ExecutePhotoGetSinglePoint(process2, null, new double[] { currentPosition.X, currentPosition.Y, currentPosition.U }, _cts.Token);
- var visionResults = await Task.WhenAll(task1, task2);
- if (isDryMode)
- {
- await plc.WriteNodeAsync(addressConfig.Out_DownCameraStatus.Address, (Int16)1);
- return;
- }
- if (visionResults[0].IsSucceed && visionResults[1].IsSucceed)
- {
- float toolX = (float)(visionResults[0].X + visionResults[1].X) / 2;
- float toolY = (float)(visionResults[0].Y + visionResults[1].Y) / 2;
- _FixedUpCameraAngle = Common.CalculateAngleBetweenPointsDegrees(new PointF((float)visionResults[0].X, (float)visionResults[0].Y), new PointF((float)visionResults[1].X, (float)visionResults[1].Y));
- DowmCameraResults[cameraIndex] = new OpenCvSharp.Point3f(toolX, toolX, (float)_FixedUpCameraAngle);
- DownTool = new PointF(toolX, toolX);
- await plc.WriteNodeAsync(addressConfig.Out_DownCameraStatus.Address, (Int16)1);
- return;
- }
- else
- {
- await plc.WriteNodeAsync(addressConfig.Out_DownCameraStatus.Address, (Int16)2);
- return;
- }
- }
- }
- else
- {
- //暂时没有应用场景,不支持
- await plc.WriteNodeAsync(addressConfig.Out_DownCameraStatus.Address, (Int16)2);
- return;
- }
- }
- else
- {
- SendTaskMessage($"触发下相机拍照信号已关闭", MessageLevel.Alarm);
- await plc.WriteNodeAsync(addressConfig.Out_DownCameraStatus.Address, (Int16)0);
- }
- }
- }
- // 触发下相机拍照披头
- if (addressConfig.In_ScrewTeachExe.Address.Contains(tuple.nodeId))
- {
- if (tuple.value is bool state)
- {
- if (state)
- {
- SendTaskMessage($"触发下相机拍照...", MessageLevel.Debug);
- //相机的编号
- Int16 cameraIndex = plc.ReadNode<Int16>(addressConfig.In_DowmCameraNum.Address);
- SendTaskMessage($"编号:{cameraIndex}", MessageLevel.Info);
- // 获取流程
- //var process = _productService.GetCurrentProductProcedureModelById(currentProduct.FixedUpCamera1ProcedureId);
- //if (process == null)
- //{
- // SendTaskMessage($"固定向上相机1视觉流程,流程ID:{currentProduct.FixedUpCamera1ProcedureId}", MessageLevel.Alarm);
- // await plc.WriteNodeAsync(addressConfig.Out_ScrewTeachOk.Address, (Int16)2);
- // return;
- //}
- //// 获取机器人当前坐标
- //var robot = _robotService.GetAllRobots().FirstOrDefault();
- //if (robot == null)
- //{
- // SendTaskMessage($"未找到机器人,无法执行上相机锁附/组装拍照视觉任务", MessageLevel.Alarm);
- // await plc.WriteNodeAsync(addressConfig.Out_ScrewTeachOk.Address, (Int16)2);
- // return;
- //}
- //var currentPosition = robot.GetRobotPos();
- //// 执行视觉任务
- //var _cts = new CancellationTokenSource();
- //var visionResult = await _remoteCommandService.ExecutePhotoGetSinglePoint(process, null, null, _cts.Token);
- //if (visionResult.IsSucceed)
- //{
- // //披头偏差
- // float offsetX = (float)(visionResult.X - currentPosition.X);
- // float offsetY = (float)(visionResult.Y - currentPosition.Y);
- // DowmCameraResults[cameraIndex] = new PointF(offsetX, offsetY);
- // await plc.WriteNodeAsync(addressConfig.Out_ScrewTeachOk.Address, (Int16)1);
- // return;
- //}
- //else
- //{
- // await plc.WriteNodeAsync(addressConfig.Out_ScrewTeachOk.Address, (Int16)2);
- // return;
- //}
- }
- else
- {
- SendTaskMessage($"触发下相机拍照信号已关闭", MessageLevel.Alarm);
- await plc.WriteNodeAsync(addressConfig.Out_ScrewTeachOk.Address, (Int16)0);
- }
- }
- }
- // 触发上相机取料拍照
- else if (addressConfig.In_UpCameraPickExe.Address.Contains(tuple.nodeId))
- {
- if (tuple.value is bool state)
- {
- if (state)
- {
- SendTaskMessage($"触发上相机取料拍照...", MessageLevel.Debug);
- //相机的编号
- Int16 cameraIndex = plc.ReadNode<Int16>(addressConfig.In_UpCameraPickNum.Address);
- SendTaskMessage($"编号:{cameraIndex}", MessageLevel.Info);
- // 获取机器人当前坐标
- var robot = _robotService.GetAllRobots().FirstOrDefault();
- if (robot == null)
- {
- SendTaskMessage($"未找到机器人,无法执行上相机锁附/组装拍照视觉任务", MessageLevel.Alarm);
- await plc.WriteNodeAsync(addressConfig.Out_DownCameraStatus.Address, (Int16)2);
- return;
- }
- var currentPosition = robot.GetRobotPos();
- //如果上相机2的流程id为空,则表示只有一个下相机
- if (currentProduct.MoveDownCamer2PickPhotoProcedureId == Guid.Empty)
- {
- //获取移动向下相机1的流程
- var process = _productService.GetCurrentProductProcedureModelById(currentProduct.MoveDownCamer1PickPhotoProcedureId);
- if (process == null)
- {
- SendTaskMessage($"移动向下相机1视觉流程,流程ID:{currentProduct.MoveDownCamer1PickPhotoProcedureId}", MessageLevel.Alarm);
- await plc.WriteNodeAsync(addressConfig.Out_UpCameraPickStatus.Address, (Int16)2);
- return;
- }
- // 执行视觉任务
- var _cts = new CancellationTokenSource();
- var visionResult = await _remoteCommandService.ExecutePhotoGetSinglePoint(process, null, new double[] { currentPosition.X, currentPosition.Y, currentPosition.U }, _cts.Token);
- if (visionResult.IsSucceed)
- {
- currentProduct.PickPoints[0].X_Position = (float)visionResult.X;
- currentProduct.PickPoints[0].Y_Position = (float)visionResult.Y;
- //currentProduct.PickPoints[0].U_Position += (float)visionResult.U;
- await currentProduct.ScrewPoints[0].WriteToPlcAddress(addressConfig.Out_Pick, plc);
- await plc.WriteNodeAsync(addressConfig.Out_UpCameraPickStatus.Address, (Int16)1);
- return;
- }
- else
- {
- await plc.WriteNodeAsync(addressConfig.Out_UpCameraPickStatus.Address, (Int16)2);
- return;
- }
- }
- else
- {
- //获取固定向上相机1的流程
- var process1 = _productService.GetCurrentProductProcedureModelById(currentProduct.MoveDownCamer1PickPhotoProcedureId);
- if (process1 == null)
- {
- SendTaskMessage($"固定向上相机1视觉流程,流程ID:{currentProduct.MoveDownCamer1PickPhotoProcedureId}", MessageLevel.Alarm);
- await plc.WriteNodeAsync(addressConfig.Out_UpCameraPickStatus.Address, (Int16)2);
- return;
- }
- //获取固定向上相机2的流程
- var process2 = _productService.GetCurrentProductProcedureModelById(currentProduct.MoveDownCamer2PickPhotoProcedureId);
- if (process2 == null)
- {
- SendTaskMessage($"固定向上相机1视觉流程,流程ID:{currentProduct.MoveDownCamer2PickPhotoProcedureId}", MessageLevel.Alarm);
- await plc.WriteNodeAsync(addressConfig.Out_UpCameraPickStatus.Address, (Int16)2);
- return;
- }
- // 执行视觉任务
- var _cts = new CancellationTokenSource();
- var task1 = _remoteCommandService.ExecutePhotoGetSinglePoint(process1, null, new double[] { currentPosition.X, currentPosition.Y, currentPosition.U }, _cts.Token);
- var task2 = _remoteCommandService.ExecutePhotoGetSinglePoint(process2, null, new double[] { currentPosition.X, currentPosition.Y, currentPosition.U }, _cts.Token);
- var visionResults = await Task.WhenAll(task1, task2);
- if (visionResults[0].IsSucceed && visionResults[1].IsSucceed)
- {
- float tool1X = (float)(visionResults[0].X - visionResults[0].X);
- float tool1Y = (float)(visionResults[0].Y - visionResults[0].Y);
- float tool2X = (float)(visionResults[1].Y - visionResults[1].Y);
- float tool2Y = (float)(visionResults[1].Y - visionResults[1].Y);
- float toolX = (tool1X + tool2X) / 2;
- float toolY = (tool1Y + tool2Y) / 2;
- //计算两个点的线角度
- currentProduct.PickPoints[0].X_Position = (float)toolX;
- currentProduct.PickPoints[0].Y_Position = (float)toolY;
- //currentProduct.PickPoints[0].U_Position += (float)visionResult.U;
- await currentProduct.ScrewPoints[0].WriteToPlcAddress(addressConfig.Out_Pick, plc);
- await plc.WriteNodeAsync(addressConfig.Out_UpCameraPickStatus.Address, (Int16)1);
- return;
- }
- else
- {
- await plc.WriteNodeAsync(addressConfig.Out_UpCameraPickStatus.Address, (Int16)2);
- return;
- }
- }
- }
- else
- {
- SendTaskMessage($"触发上相机取料拍照信号已关闭", MessageLevel.Alarm);
- await plc.WriteNodeAsync(addressConfig.Out_UpCameraPickStatus.Address, (Int16)0);
- }
- }
- }
- // 上相机锁附/组装拍照
- else if (addressConfig.In_UpCameraPutExe.Address.Contains(tuple.nodeId))
- {
- if (tuple.value is bool state)
- {
- if (state)
- {
- SendTaskMessage($"触发上相机锁附/组装拍照...", MessageLevel.Debug);
- //相机的编号
- Int16 cameraIndex = plc.ReadNode<Int16>(addressConfig.In_UpCameraPutNum.Address);
- SendTaskMessage($"编号:{cameraIndex}", MessageLevel.Info);
- // 获取机器人当前坐标
- var robot = _robotService.GetAllRobots().FirstOrDefault();
- if (robot == null)
- {
- SendTaskMessage($"未找到机器人,无法执行上相机锁附/组装拍照视觉任务", MessageLevel.Alarm);
- await plc.WriteNodeAsync(addressConfig.Out_UpCameraPutStatus.Address, (Int16)2);
- return;
- }
- var currentPosition = robot.GetRobotPos();
- //如果上相机2的流程id为空,则表示只有一个上相机
- if (currentProduct.MoveDownCamera2LockPhotoProcedureId == Guid.Empty)
- {
- //获取移动向下相机1的流程
- var process = _productService.GetCurrentProductProcedureModelById(currentProduct.MoveDownCamera1LockPhotoProcedureId);
- if (process == null)
- {
- SendTaskMessage($"移动向下相机1视觉流程,流程ID:{currentProduct.MoveDownCamera1LockPhotoProcedureId}", MessageLevel.Alarm);
- await plc.WriteNodeAsync(addressConfig.Out_UpCameraPutStatus.Address, (Int16)2);
- return;
- }
- // 执行视觉任务
- var _cts = new CancellationTokenSource();
- var visionResult = await _remoteCommandService.ExecutePhotoGetSinglePoint(process, null, new double[] { currentPosition.X, currentPosition.Y, currentPosition.U }, _cts.Token);
- if (isDryMode)
- {
- await plc.WriteNodeAsync(addressConfig.Out_UpCameraPutStatus.Address, (Int16)1);
- return;
- }
- if (visionResult.IsSucceed)
- {
- UpCameraPutResults[cameraIndex] = new OpenCvSharp.Point3f((float)visionResult.X, (float)visionResult.Y, (float)visionResult.U);
- await plc.WriteNodeAsync(addressConfig.Out_UpCameraPutStatus.Address, (Int16)1);
- return;
- }
- else
- {
- await plc.WriteNodeAsync(addressConfig.Out_UpCameraPutStatus.Address, (Int16)2);
- return;
- }
- }
- else
- {
- //获取移动向下相机1的流程
- var process1 = _productService.GetCurrentProductProcedureModelById(currentProduct.MoveDownCamera1LockPhotoProcedureId);
- if (process1 == null)
- {
- SendTaskMessage($"固定向上相机1视觉流程,流程ID:{currentProduct.MoveDownCamera1LockPhotoProcedureId}", MessageLevel.Alarm);
- await plc.WriteNodeAsync(addressConfig.Out_UpCameraPutStatus.Address, (Int16)2);
- return;
- }
- //获取移动向下相机2的流程
- var process2 = _productService.GetCurrentProductProcedureModelById(currentProduct.MoveDownCamera2LockPhotoProcedureId);
- if (process2 == null)
- {
- SendTaskMessage($"固定向上相机1视觉流程,流程ID:{currentProduct.MoveDownCamera2LockPhotoProcedureId}", MessageLevel.Alarm);
- await plc.WriteNodeAsync(addressConfig.Out_UpCameraPutStatus.Address, (Int16)2);
- return;
- }
- // 执行视觉任务
- var _cts = new CancellationTokenSource();
- var task1 = _remoteCommandService.ExecutePhotoGetSinglePoint(process1, null, new double[] { currentPosition.X, currentPosition.Y, currentPosition.U }, _cts.Token);
- var task2 = _remoteCommandService.ExecutePhotoGetSinglePoint(process2, null, new double[] { currentPosition.X, currentPosition.Y, currentPosition.U }, _cts.Token);
- var visionResults = await Task.WhenAll(task1, task2);
- if (isDryMode)
- {
- await plc.WriteNodeAsync(addressConfig.Out_UpCameraPutStatus.Address, (Int16)1);
- return;
- }
- if (visionResults[0].IsSucceed && visionResults[1].IsSucceed)
- {
- float centerX = (float)(visionResults[0].X + visionResults[1].X) / 2;
- float centerY = (float)(visionResults[0].Y + visionResults[1].Y) / 2;
- _MoveCameraAngle = Common.CalculateAngleBetweenPointsDegrees(new PointF((float)visionResults[0].X, (float)visionResults[0].Y), new PointF((float)visionResults[1].X, (float)visionResults[1].Y));
- UpCameraPutResults[cameraIndex] = new OpenCvSharp.Point3f(centerX, centerY, (float)_MoveCameraAngle);
- await plc.WriteNodeAsync(addressConfig.Out_UpCameraPutStatus.Address, (Int16)1);
- return;
- }
- else
- {
- await plc.WriteNodeAsync(addressConfig.Out_UpCameraPutStatus.Address, (Int16)2);
- return;
- }
- }
- }
- else
- {
- SendTaskMessage($"触发上相机锁附/组装拍照信号已关闭", MessageLevel.Alarm);
- await plc.WriteNodeAsync(addressConfig.Out_UpCameraPutStatus.Address, (Int16)0);
- }
- }
- }
- // 上相机检测拍照
- else if (addressConfig.In_UPCameracheckExe.Address.Contains(tuple.nodeId))
- {
- if (tuple.value is bool state)
- {
- if (state)
- {
- SendTaskMessage($"触发上相机检测拍照...", MessageLevel.Debug);
- //相机的编号
- //Int16 cameraIndex = plc.ReadNode<Int16>(addressConfig.Out_UPCameracheckNum.Address);
- await plc.WriteNodeAsync(addressConfig.Out_UPCameracheckStatus.Address, (Int16)1);
- }
- else
- {
- SendTaskMessage($"触发上相机检测拍照信号已关闭", MessageLevel.Alarm);
- await plc.WriteNodeAsync(addressConfig.Out_UPCameracheckStatus.Address, (Int16)0);
- }
- }
- }
- // 固定相机取料拍照
- else if (addressConfig.In_FixedCameraPickExe.Address.Contains(tuple.nodeId))
- {
- if (tuple.value is bool state)
- {
- if (state)
- {
- SendTaskMessage($"触发固定相机取料拍照...", MessageLevel.Debug);
- //相机的编号
- //Int16 cameraIndex = plc.ReadNode<Int16>(addressConfig.In_FixedCameraPickNum.Address);
- await plc.WriteNodeAsync(addressConfig.Out_FixedCameraPickStatus.Address, (Int16)1);
- }
- else
- {
- SendTaskMessage($"触发固定相机取料拍照信号已关闭", MessageLevel.Alarm);
- await plc.WriteNodeAsync(addressConfig.Out_FixedCameraPickStatus.Address, (Int16)0);
- }
- }
- }
- // 固定相机锁附/组装拍照
- else if (addressConfig.In_FixedCameraPutExe.Address.Contains(tuple.nodeId))
- {
- if (tuple.value is bool state)
- {
- if (state)
- {
- SendTaskMessage($"触发固定相机锁附/组装拍照...", MessageLevel.Debug);
- //相机的编号
- //Int16 cameraIndex = plc.ReadNode<Int16>(addressConfig.In_FixedCameraPutNum.Address);
- if (currentProduct.IndependentCamer1ProductProcedureId == Guid.Empty)
- {
- await plc.WriteNodeAsync(addressConfig.Out_FixedCameraPutStatus.Address, (Int16)2);
- return;
- }
- if (currentProduct.IndependentCamer2ProductProcedureId == Guid.Empty)
- {
- await plc.WriteNodeAsync(addressConfig.Out_FixedCameraPutStatus.Address, (Int16)2);
- return;
- }
- if (currentProduct.IndependentCamer3ProductProcedureId == Guid.Empty)
- {
- await plc.WriteNodeAsync(addressConfig.Out_FixedCameraPutStatus.Address, (Int16)2);
- return;
- }
- if (currentProduct.IndependentCamer4ProductProcedureId == Guid.Empty)
- {
- await plc.WriteNodeAsync(addressConfig.Out_FixedCameraPutStatus.Address, (Int16)2);
- return;
- }
- //获取四个独立相机的流程id
- var process1 = _productService.GetCurrentProductProcedureModelById(currentProduct.IndependentCamer1ProductProcedureId);
- var process2 = _productService.GetCurrentProductProcedureModelById(currentProduct.IndependentCamer2ProductProcedureId);
- var process3 = _productService.GetCurrentProductProcedureModelById(currentProduct.IndependentCamer3ProductProcedureId);
- var process4 = _productService.GetCurrentProductProcedureModelById(currentProduct.IndependentCamer4ProductProcedureId);
- // 执行视觉任务
- var _cts = new CancellationTokenSource();
- var task1 = _remoteCommandService.ExecutePhotoGetSinglePoint(process1, null, null, _cts.Token);
- var task2 = _remoteCommandService.ExecutePhotoGetSinglePoint(process2, null, null, _cts.Token);
- var task3 = _remoteCommandService.ExecutePhotoGetSinglePoint(process3, null, null, _cts.Token);
- var task4 = _remoteCommandService.ExecutePhotoGetSinglePoint(process4, null, null, _cts.Token);
- var visionResults = await Task.WhenAll(task1, task2, task3, task4);
- if (visionResults[0].IsSucceed && visionResults[1].IsSucceed && visionResults[2].IsSucceed && visionResults[3].IsSucceed)
- {
- Vector<double> p1=Vector<double>.Build.Dense(new double[] { visionResults[0].X, visionResults[0].Y });
- Vector<double> p2=Vector<double>.Build.Dense(new double[] { visionResults[1].X, visionResults[1].Y });
- Vector<double> p3=Vector<double>.Build.Dense(new double[] { visionResults[2].X, visionResults[2].Y });
- Vector<double> p4=Vector<double>.Build.Dense(new double[] { visionResults[3].X, visionResults[3].Y });
- var center = RectangleCenterCalculator.CalculateByPCAWithKnownOrder(new List<Vector<double>> { p1, p2, p4, p3 });
- UpCameraPutResults[0].X = (float)center.Center[0];
- UpCameraPutResults[0].Y = (float)center.Center[1];
- UpCameraPutResults[0].Z= (float)center.MajorAxisAngle;
- }
- else
- {
- if (isDryMode)
- {
- await plc.WriteNodeAsync(addressConfig.Out_FixedCameracheckStatus.Address, (Int16)1);
- return;
- }
- await plc.WriteNodeAsync(addressConfig.Out_FixedCameraPutStatus.Address, (Int16)2);
- return;
- }
- await plc.WriteNodeAsync(addressConfig.Out_FixedCameraPutStatus.Address, (Int16)1);
- }
- else
- {
- SendTaskMessage($"触发固定相机锁附/组装拍照信号已关闭", MessageLevel.Alarm);
- await plc.WriteNodeAsync(addressConfig.Out_FixedCameraPutStatus.Address, (Int16)0);
- }
- }
- }
- // 固定相机检测拍照
- else if (addressConfig.In_FixedCameracheckExe.Address.Contains(tuple.nodeId))
- {
- if (tuple.value is bool state)
- {
- if (state)
- {
- SendTaskMessage($"触发固定相机检测拍照...", MessageLevel.Debug);
- //相机的编号
- //Int16 cameraIndex = plc.ReadNode<Int16>(addressConfig.In_FixedCameracheckNum.Address);
- if (currentProduct.IndependentCamer1AuxProcedureId == Guid.Empty)
- {
- await plc.WriteNodeAsync(addressConfig.Out_FixedCameracheckStatus.Address, (Int16)2);
- return;
- }
- if (currentProduct.IndependentCamer2AuxProcedureId == Guid.Empty)
- {
- await plc.WriteNodeAsync(addressConfig.Out_FixedCameracheckStatus.Address, (Int16)2);
- return;
- }
- if (currentProduct.IndependentCamer3AuxProcedureId == Guid.Empty)
- {
- await plc.WriteNodeAsync(addressConfig.Out_FixedCameracheckStatus.Address, (Int16)2);
- return;
- }
- if (currentProduct.IndependentCamer4AuxProcedureId == Guid.Empty)
- {
- await plc.WriteNodeAsync(addressConfig.Out_FixedCameracheckStatus.Address, (Int16)2);
- return;
- }
- //获取四个独立相机的流程id
- var process1 = _productService.GetCurrentProductProcedureModelById(currentProduct.IndependentCamer1AuxProcedureId);
- var process2 = _productService.GetCurrentProductProcedureModelById(currentProduct.IndependentCamer2AuxProcedureId);
- var process3 = _productService.GetCurrentProductProcedureModelById(currentProduct.IndependentCamer3AuxProcedureId);
- var process4 = _productService.GetCurrentProductProcedureModelById(currentProduct.IndependentCamer4AuxProcedureId);
- // 执行视觉任务
- var _cts = new CancellationTokenSource();
- var task1 = _remoteCommandService.ExecutePhotoGetSinglePoint(process1, null, null, _cts.Token);
- var task2 = _remoteCommandService.ExecutePhotoGetSinglePoint(process2, null, null, _cts.Token);
- var task3 = _remoteCommandService.ExecutePhotoGetSinglePoint(process3, null, null, _cts.Token);
- var task4 = _remoteCommandService.ExecutePhotoGetSinglePoint(process4, null, null, _cts.Token);
- var visionResults = await Task.WhenAll(task1, task2, task3, task4);
- if (visionResults[0].IsSucceed && visionResults[1].IsSucceed && visionResults[2].IsSucceed && visionResults[3].IsSucceed)
- {
- Vector<double> p1 = Vector<double>.Build.Dense(new double[] { visionResults[0].X, visionResults[0].Y });
- Vector<double> p2 = Vector<double>.Build.Dense(new double[] { visionResults[1].X, visionResults[1].Y });
- Vector<double> p3 = Vector<double>.Build.Dense(new double[] { visionResults[2].X, visionResults[2].Y });
- Vector<double> p4 = Vector<double>.Build.Dense(new double[] { visionResults[3].X, visionResults[3].Y });
- var center = RectangleCenterCalculator.CalculateByPCAWithKnownOrder(new List<Vector<double>> { p1, p2, p4, p3 });
- UpCameraPutResults[1].X = (float)center.Center[0];
- UpCameraPutResults[1].Y = (float)center.Center[1];
- UpCameraPutResults[1].Z = (float)center.MajorAxisAngle;
- }
- else
- {
- if (isDryMode)
- {
- await plc.WriteNodeAsync(addressConfig.Out_FixedCameracheckStatus.Address, (Int16)1);
- return;
- }
- await plc.WriteNodeAsync(addressConfig.Out_FixedCameracheckStatus.Address, (Int16)2);
- return;
- }
- await plc.WriteNodeAsync(addressConfig.Out_FixedCameracheckStatus.Address, (Int16)1);
- }
- else
- {
- SendTaskMessage($"触发固定相机检测拍照信号已关闭", MessageLevel.Alarm);
- await plc.WriteNodeAsync(addressConfig.Out_FixedCameracheckStatus.Address, (Int16)0);
- }
- }
- }
- // 开始锁付
- else if (addressConfig.In_WorkStart.Address.Contains(tuple.nodeId))
- {
- if (tuple.value is Int16 state)
- {
- if (state == 1)
- {
- SendTaskMessage($"收到开始锁付信号...", MessageLevel.Debug);
- //位置编号
- Int16 positionIndex = plc.ReadNode<Int16>(addressConfig.In_ProductNum.Address);
- SendTaskMessage($"编号:{positionIndex}", MessageLevel.Info);
- }
- else
- {
- SendTaskMessage($"开始锁付信号已关闭", MessageLevel.Alarm);
- // 关闭时的处理(如需)可放在这里
- }
- }
- }
- // 停止锁付
- else if (addressConfig.In_WorkDone.Address.Contains(tuple.nodeId))
- {
- if (tuple.value is Int16 state)
- {
- if (state == 1 || state == 2)
- {
- SendTaskMessage($"收到停止锁付信号...", MessageLevel.Debug);
- //位置编号
- Int16 positionIndex = plc.ReadNode<Int16>(addressConfig.In_ProductNum.Address);
- SendTaskMessage($"编号:{positionIndex}", MessageLevel.Info);
- //获取当前锁付点
- var screwPoint = currentProduct.ScrewPoints.FirstOrDefault(p => p.Number == positionIndex);
- //获取当前的机器人点位
- var robot = _robotService.GetAllRobots().FirstOrDefault();
- var currentPosition = robot.GetRobotPos();
- //读取压力值
- float pressure = plc.ReadNode<float>(addressConfig.In_PressureValue.Address);
- await Task.Delay(60);
- //获取电批结果
- bool isSucced = ScrewDriver.GetData();
- LockResult lockResult = new LockResult();
- lockResult.ScrewdriverGetDataSucceed = isSucced;
- lockResult.Number = positionIndex;
- lockResult.LockPassed = ScrewDriver.Success;
- lockResult.ProductNumber = _productService.CurrentProductCode;
- lockResult.LockTurns = (float)ScrewDriver.Truns;
- lockResult.LockTorque = (float)ScrewDriver.TorqueValue;
- lockResult.LockDuration = (float)ScrewDriver.FinalTime;
- lockResult.ScrewdriverProgramNumber = ScrewDriver.ProgramNumber;
- lockResult.ResultDetails = ScrewDriver.ErrorInfo;
- lockResult.Pressure = pressure;
- lockResult.TargetTorque = ScrewDriver.TargetTorque;
- lockResult.TargetTurnsUpperLimit = ScrewDriver.TargetTurnsUpperLimit;
- lockResult.TargetTurnsLowerLimit = ScrewDriver.TargetTurnsLowerLimit;
- lockResult.TargetLockSpeed = ScrewDriver.TargetLockSpeed;
- lockResult.StartPositionX = currentPosition.X;
- lockResult.StartPositionY = currentPosition.Y;
- lockResult.StartPositionZ = screwPoint.Z_Position_Start;
- lockResult.EndPositionZ = currentPosition.Z;
- lockResult.LockDescentSpeed = screwPoint.Z_Velocity_Stop;
- lockResult.FeederNumber = screwPoint != null ? screwPoint.Feeder : 0;
- lockResult.NozzleNumber = "";
- lockResult.OperatorName = _systemDatabaseService.GetCurrentUser().UserName;
- lockResult.ProductImagePath = "";
- lockResult.WaveDatas = ScrewDriver.WaveDatas;
- App.Current.Dispatcher.Invoke(() =>
- {
- _eventAggregator.GetEvent<LockFinishNotification>().Publish(lockResult);
- });
- await _systemDatabaseService.RecordLockResultAsync(lockResult);
- await plc.WriteNodeAsync(addressConfig.In_WorkDone.Address, (Int16)0);
- }
- else
- {
- SendTaskMessage($"停止锁付信号已关闭", MessageLevel.Alarm);
- }
- }
- }
- // 多相机坐标合并
- else if (addressConfig.In_RequestPosition.Address.Contains(tuple.nodeId))
- {
- if (tuple.value is Int16 state)
- {
- if (state == 1)
- {
- SendTaskMessage($"收到多相机坐标合并请求,开始合并...", MessageLevel.Debug);
- if (isDryMode)
- {
- var point1 = currentProduct.ScrewPoints[0].Clone();
- SendTaskMessage($"点:1,{point1.X_Position:F3},{point1.Y_Position:F4},{point1.U_Position:F4}", MessageLevel.Info);
- await point1.WriteToPlcAddress(addressConfig.Out_Screw, plc);
- await plc.WriteNodeAsync(addressConfig.Out_WorkNum.Address, (Int16)1);
- await plc.WriteNodeAsync(addressConfig.Out_CameraDone.Address, (Int16)1);
- return;
- }
- // 获取机器人当前坐标
- var robot = _robotService.GetAllRobots().FirstOrDefault();
- if (robot == null)
- {
- SendTaskMessage($"未找到机器人,无法执行上相机锁附/组装拍照视觉任务", MessageLevel.Alarm);
- await plc.WriteNodeAsync(addressConfig.Out_DownCameraStatus.Address, (Int16)2);
- return;
- }
- var currentPosition = robot.GetRobotPos();
- //以LCD的中线创建工具坐标
- ToolCoord toolCoord = new ToolCoord();
- toolCoord.SetTool(UpCameraPutResults[1].X, UpCameraPutResults[1].Y);
-
- //计算放料角度
- double angle= currentPosition.U - DowmCameraResults[1].Z + DowmCameraResults[0].Z;
- //将产品的中心点坐标转换为Tool0下的坐标
- var point = currentProduct.ScrewPoints[0].Clone();
- var pn = Vector<double>.Build.Dense(new double[] { DowmCameraResults[0].X, DowmCameraResults[0].Y });
- var p0 = toolCoord.GetTool0Coord(pn, angle);
- point.X_Position = (float)p0[0];
- point.Y_Position = (float)p0[1];
- point.U_Position = (float)angle;
- SendTaskMessage($"点:1,{point.X_Position:F3},{point.Y_Position:F4},{point.U_Position:F4}", MessageLevel.Info);
- await point.WriteToPlcAddress(addressConfig.Out_Screw, plc);
- await plc.WriteNodeAsync(addressConfig.Out_WorkNum.Address, (Int16)1);
- await plc.WriteNodeAsync(addressConfig.Out_CameraDone.Address, (Int16)1);
- }
- else
- {
- SendTaskMessage($"多相机坐标合并请求已结束或被取消,state={state}", MessageLevel.Alarm);
- await plc.WriteNodeAsync(addressConfig.Out_CameraDone.Address, (Int16)0);
- }
- }
- }
- // 螺丝供料器螺丝递减
- else if (addressConfig.In_PickINC.Address.Contains(tuple.nodeId))
- {
- if (tuple.value is Int16 state)
- {
- if (state != 0)
- {
- SendTaskMessage($"螺丝供料器...", MessageLevel.Info);
- await plc.WriteNodeAsync(addressConfig.In_PickINC.Address, (Int16)0);
- }
- }
- }
- // 过站检查
- else
- {
- for (int i = 0; i < 10; i++)
- {
- if (string.Format(addressConfig.In_MesCheck.Address, i).Contains(tuple.nodeId))
- {
- if (tuple.value is Int16 state)
- {
- if (state == 1)
- {
- if (i == 0)
- {
- SendTaskMessage($"收到当前站过站检查请求(当站是否生产)...", MessageLevel.Debug);
- }
- else
- {
- SendTaskMessage($"收到 {i} 过站检查请求(当站是否生产)...", MessageLevel.Debug);
- }
- //产品发生改变并且供料器发生了变化时,需要通知PLC进行取料更改
- await plc.WriteNodeAsync(addressConfig.Out_ScrewFeederIsChanged.Address, (Int16)1); //不发生改变
- await plc.WriteNodeAsync(string.Format(addressConfig.Out_MesStatus.Address, i), (Int16)1);
- }
- // 上传本站数据
- else if (state == 2)
- {
- SendTaskMessage($"收到上传{i}站数据请求...", MessageLevel.Debug);
- await plc.WriteNodeAsync(string.Format(addressConfig.Out_MesStatus.Address, i), (Int16)3);
- }
- else
- {
- SendTaskMessage($"{i}过站检查信号:state={state},处理为默认状态", MessageLevel.Alarm);
- await plc.WriteNodeAsync(string.Format(addressConfig.Out_MesStatus.Address, i), (Int16)0);
- }
- }
- }
- }
- }
- }
- catch (Exception ex)
- {
- SendTaskMessage(ex.Message, MessageLevel.Error);
- }
- }
- #endregion
- #region 方法
- private void SendTaskMessage(string msg, MessageLevel level)
- {
- App.Current.Dispatcher.Invoke(() =>
- {
- _eventAggregator.GetEvent<TaskMessageNotification>().Publish(new Models.MessageStruct() { Message = msg, level = level });
- });
- }
- private async void DoYieldTime(object state)
- {
- try
- {
- if (CurrentProduct == null) return;
- //获取当前产品
- var currentproduct = _productService.GetCurrentProduct();
- TotalQuantity = await _systemDatabaseService.GetOverallProductionAsync(CurrentProduct.Name);
- TotalQuantityToday = await _systemDatabaseService.GetTodayProductionAsync(CurrentProduct.Name);
- CurrentUPH = await _systemDatabaseService.GetLastHourProductionAsync(CurrentProduct.Name);
- }
- catch (Exception)
- {
- }
- }
- #region vm启动检测
- /// <summary>
- /// 杀死所有VM有关进程
- /// </summary>
- public void KillVMProcess()
- {
- KillProcess("VisionMasterServerApp");
- KillProcess("VisionMaster");
- KillProcess("VmModuleProxy.exe");
- KillProcess("vServerApp.exe");
- }
- /// <summary>
- /// 杀死指定进程名的进程
- /// </summary>
- /// <param name="strKillName"></param>
- public void KillProcess(string strKillName)
- {
- foreach (System.Diagnostics.Process p in System.Diagnostics.Process.GetProcesses())
- {
- if (p.ProcessName.Contains(strKillName))
- {
- try
- {
- p.Kill();
- p.WaitForExit();
- }
- catch (Exception ex)
- {
- LogHelper.WriteLogError($"杀死进程:{strKillName}时失败!", ex);
- }
- }
- }
- }
- #endregion
- #endregion
- }
- }
|