徐孝锋 hace 8 meses
padre
commit
e09b71bb6c

+ 5 - 0
TeamAAS-VM/Core/FilePath.cs

@@ -71,5 +71,10 @@ namespace TeamAAS_VP.Core
         /// 数量参数
         /// </summary>
         public static string NumberStatisticsPath = "..//Config//NumberStatisticsParam.cfg";
+
+        /// <summary>
+        /// 扭力测量仪路径
+        /// </summary>
+        public static string SignalConfigPath = "..//Config//扭力测量仪配置文件.json";
     }
 }

+ 129 - 26
TeamAAS-VM/Core/Management.cs

@@ -53,6 +53,7 @@ using TeamAAS_VP.Resources.Languages;
 using TeamAAS_VP.Services;
 using TeamAAS_VP.ViewModels.Home;
 using TouchSocket.Core;
+using TouchSocket.SerialPorts;
 using TouchSocket.Sockets;
 using static MaterialDesignThemes.Wpf.Theme.ToolBar;
 using static Org.BouncyCastle.Math.EC.ECCurve;
@@ -80,7 +81,7 @@ namespace TeamAAS_VP.Core
 
         Timer yieldtimer;
         private DateTime StartTime = DateTime.Now;
-
+        SerialPortClient client;
         #endregion
 
         #region 属性
@@ -160,10 +161,35 @@ namespace TeamAAS_VP.Core
 
         public Dictionary<string, object> BackupObject { get; set; } = new Dictionary<string, object>();
 
+        private string _COM;
         /// <summary>
-        /// 扭力测量仪
+        /// 扭力测量仪COM
         /// </summary>
-        public Signal signalTest { get; set; }
+        public string COM
+        {
+            get { return _COM; }
+            set { SetProperty(ref _COM, value); }
+        }
+
+        private string _SignalValue;
+        /// <summary>
+        /// 扭力测量仪获取的最大值
+        /// </summary>
+        public string SignalValue
+        {
+            get { return _SignalValue; }
+            set { SetProperty(ref _SignalValue, value); }
+        }
+
+        private double _Value;
+        /// <summary>
+        /// 电批扭力值
+        /// </summary>
+        public double Value
+        {
+            get { return _Value; }
+            set { SetProperty(ref _Value, value); }
+        }
 
         private NumberStatistics _NumStatistics;
         /// <summary>
@@ -203,7 +229,6 @@ namespace TeamAAS_VP.Core
             _remoteCommandService = remoteCommandService;
             _systemDatabaseService = systemDatabaseService;
             _lightManagerService = lightManagerService;
-            signalTest = new Signal();
         }
 
         #region 读取配置参数
@@ -573,13 +598,13 @@ namespace TeamAAS_VP.Core
         {
             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;
+                ScrewDriver.SendTimeout = screwDriverConfig.SendTimeout;
+                screwDriverConfig.ReceiveTimeout = screwDriverConfig.ReceiveTimeout;
                 var isConnected = await ScrewDriver.ConnectAsync();
                 if (isConnected)
                 {
@@ -597,6 +622,58 @@ namespace TeamAAS_VP.Core
             }
         }
 
+        /// <summary>
+        /// 初始化扭力测量仪
+        /// </summary>
+        /// <returns></returns>
+        public async Task InitSignal()
+        {
+            if (File.Exists(FilePath.SignalConfigPath))
+            {
+                try
+                {
+                    var port = FileHelper.ReadJsonFile<string>(FilePath.SignalConfigPath);
+                    if (port != null)
+                    {
+                        client = new TouchSocket.SerialPorts.SerialPortClient();
+                        client.Connecting = (client1, e) => { return EasyTask.CompletedTask; };//即将连接到端口
+                        client.Connected = (client1, e) => { return EasyTask.CompletedTask; };//成功连接到端口
+                        client.Closing = (client1, e) => { return EasyTask.CompletedTask; };//即将从端口断开连接。此处仅主动断开才有效。
+                        client.Closed = (client1, e) => { return EasyTask.CompletedTask; };//从端口断开连接,当连接不成功时不会触发。
+                        client.Received = async (c, e) =>
+                        {
+                            //await Console.Out.WriteLineAsync(Encoding.UTF8.GetString(e.ByteBlock.Buffer));
+                            await Console.Out.WriteLineAsync(e.ByteBlock.Span.ToString(Encoding.ASCII));
+                        };
+                        client.Received = Sp_DataReceived;
+
+                        await client.SetupAsync(new TouchSocketConfig()
+                             .SetSerialPortOption(new SerialPortOption()
+                             {
+                                 BaudRate = 115200,//波特率
+                                 DataBits = 8,//数据位
+                                 Parity = System.IO.Ports.Parity.None,//校验位
+                                 PortName = port,//COM
+                                 StopBits = System.IO.Ports.StopBits.One//停止位
+                             })
+                             .SetSerialDataHandlingAdapter(() => new PeriodPackageAdapter() { CacheTimeout = TimeSpan.FromMilliseconds(100) })
+                             );
+
+                        await client.ConnectAsync();
+                    }
+                }
+                catch (Exception ex)
+                {
+                    LogHelper.WriteLogError("初始化扭力测量仪时出错!", ex);
+                    SendTaskMessage("初始化扭力测量仪时出错!"+ex.Message, MessageLevel.Error);
+                }
+            }
+            else
+            {
+                COM = "COM1";
+                FileHelper.WriteJsonFile(COM, FilePath.SignalConfigPath);
+            }
+        }
         #endregion
 
         #region 机器人指令执行
@@ -956,6 +1033,31 @@ namespace TeamAAS_VP.Core
         {
             SendTaskMessage($"{Lang.服务器}[{client.ServicePort}]{Lang.客户端}[{client.Id}:{client.IP}]{Lang.连接成功}!", MessageLevel.Debug);
         }
+
+        /// <summary>
+        /// 扭力测量仪接收信息
+        /// </summary>
+        /// <param name="client"></param>
+        /// <param name="e"></param>
+        /// <returns></returns>
+        private async Task Sp_DataReceived(ISerialPortClient client, ReceivedDataEventArgs e)
+        {
+            try
+            {
+                string poname = client.MainSerialPort.PortName;
+                string data = e.ByteBlock.Span.ToString(Encoding.ASCII);
+                await Console.Out.WriteLineAsync(data);
+                string response = data.Split('\r')[0];
+                SendTaskMessage($"{poname}Receive:{response}", MessageLevel.Info);
+                SignalValue = response;
+            }
+            catch (Exception ex)
+            {
+                LogHelper.WriteLogError("扭力测量仪接收信息时出错!", ex);
+                SendTaskMessage("扭力测量仪接收信息时出错!" + ex.Message, MessageLevel.Error);
+                Thread.Sleep(50);
+            }
+        }
         #endregion
 
         #region PLC
@@ -1072,9 +1174,9 @@ namespace TeamAAS_VP.Core
             }
         }
 
-        PointF[] DowmCameraResults= new PointF[10];
+        PointF[] DowmCameraResults = new PointF[10];
         PointF[] UpCameraPutResults = new PointF[10];
-        
+
 
         /// <summary>
         /// PLC命令触发时
@@ -1084,7 +1186,7 @@ namespace TeamAAS_VP.Core
         {
             try
             {
-                if (tuple.key!= "AutoSensor")
+                if (tuple.key != "AutoSensor")
                 {
                     return;
                 }
@@ -1094,7 +1196,7 @@ namespace TeamAAS_VP.Core
                 if (plc == null || !plc.IsConnected) return;
                 // 获取当前产品
                 var currentProduct = _productService.GetCurrentProduct();
-                if (currentProduct==null)
+                if (currentProduct == null)
                 {
                     return;
                 }
@@ -1141,7 +1243,7 @@ namespace TeamAAS_VP.Core
 
                             // 执行视觉任务
                             var _cts = new CancellationTokenSource();
-                            var visionResult =await _remoteCommandService.ExecutePhotoGetSinglePoint(process, null,null, _cts.Token);
+                            var visionResult = await _remoteCommandService.ExecutePhotoGetSinglePoint(process, null, null, _cts.Token);
                             if (visionResult.IsSucceed)
                             {
                                 //披头偏差
@@ -1278,12 +1380,12 @@ namespace TeamAAS_VP.Core
 
                             // 执行视觉任务
                             var _cts = new CancellationTokenSource();
-                            var visionResult =await _remoteCommandService.ExecutePhotoGetSinglePoint(process, null, new double[] { currentPosition.X , currentPosition.Y, currentPosition.U}, _cts.Token);
+                            var visionResult = await _remoteCommandService.ExecutePhotoGetSinglePoint(process, null, new double[] { currentPosition.X, currentPosition.Y, currentPosition.U }, _cts.Token);
                             if (visionResult.IsSucceed)
                             {
-                                UpCameraPutResults[cameraIndex]=new PointF((float)visionResult.X, (float)visionResult.Y);
+                                UpCameraPutResults[cameraIndex] = new PointF((float)visionResult.X, (float)visionResult.Y);
+
 
-                                
                                 await plc.WriteNodeAsync(addressConfig.Out_UpCameraPutStatus.Address, (Int16)1);
                             }
                             else
@@ -1389,7 +1491,7 @@ namespace TeamAAS_VP.Core
                 {
                     if (tuple.value is Int16 state)
                     {
-                        if (state==1)
+                        if (state == 1)
                         {
                             SendTaskMessage($"收到开始锁付信号...", MessageLevel.Debug);
                             //位置编号
@@ -1408,7 +1510,7 @@ namespace TeamAAS_VP.Core
                 {
                     if (tuple.value is Int16 state)
                     {
-                        if (state==1 || state == 2)
+                        if (state == 1 || state == 2)
                         {
                             SendTaskMessage($"收到停止锁付信号...", MessageLevel.Debug);
                             //位置编号
@@ -1425,7 +1527,7 @@ namespace TeamAAS_VP.Core
 
                             await Task.Delay(60);
                             //获取电批结果
-                            bool isSucced= ScrewDriver.GetData();
+                            bool isSucced = ScrewDriver.GetData();
                             LockResult lockResult = new LockResult();
                             lockResult.ScrewdriverGetDataSucceed = isSucced;
                             lockResult.Number = positionIndex;
@@ -1458,6 +1560,7 @@ namespace TeamAAS_VP.Core
                             await _systemDatabaseService.RecordLockResultAsync(lockResult);
                             await plc.WriteNodeAsync(addressConfig.In_WorkDone.Address, (Int16)0);
 
+                            Value = lockResult.LockTorque;
                             //电批吸嘴报警
                             NumStatistics.HeaderNum++;//批头数量
                             NumStatistics.NozzleNum++;//吸嘴数量
@@ -1490,7 +1593,7 @@ namespace TeamAAS_VP.Core
                             //拍1打1 
                             if (systemConfig.WorkMode == 1)
                             {
-                                currentProduct.ScrewPoints[0].X_Position = UpCameraPutResults[1].X+ DowmCameraResults[0].X;
+                                currentProduct.ScrewPoints[0].X_Position = UpCameraPutResults[1].X + DowmCameraResults[0].X;
                                 currentProduct.ScrewPoints[0].Y_Position = UpCameraPutResults[1].Y + DowmCameraResults[0].Y;
                                 await currentProduct.ScrewPoints[0].WriteToPlcAddress(addressConfig.Out_Screw, plc);
                             }
@@ -1498,16 +1601,16 @@ namespace TeamAAS_VP.Core
                             else if (systemConfig.WorkMode == 2)
                             {
                                 //根据UpCameraPutResults[]中的索引1、2,和拍照点对应的Local下的坐标,从创建Local坐标系
-                                PointF worldP1=new PointF(UpCameraPutResults[1].X, UpCameraPutResults[1].Y);
-                                PointF worldP2= new PointF(UpCameraPutResults[2].X, UpCameraPutResults[2].Y);
-                                PointF localP1= new PointF(currentProduct.ScrewCameraLocalPos1.X_Position, currentProduct.ScrewCameraLocalPos1.Y_Position);
-                                PointF localP2= new PointF(currentProduct.ScrewCameraLocalPos2.X_Position, currentProduct.ScrewCameraLocalPos2.Y_Position);
-                                CoordinateTransformer local= new CoordinateTransformer(worldP1, worldP2, localP1, localP2);
+                                PointF worldP1 = new PointF(UpCameraPutResults[1].X, UpCameraPutResults[1].Y);
+                                PointF worldP2 = new PointF(UpCameraPutResults[2].X, UpCameraPutResults[2].Y);
+                                PointF localP1 = new PointF(currentProduct.ScrewCameraLocalPos1.X_Position, currentProduct.ScrewCameraLocalPos1.Y_Position);
+                                PointF localP2 = new PointF(currentProduct.ScrewCameraLocalPos2.X_Position, currentProduct.ScrewCameraLocalPos2.Y_Position);
+                                CoordinateTransformer local = new CoordinateTransformer(worldP1, worldP2, localP1, localP2);
 
                                 for (int i = 0; i < currentProduct.ScrewPoints.Count; i++)
                                 {
                                     var localPoint = new PointF(currentProduct.ScrewPoints[i].X_Position, currentProduct.ScrewPoints[i].Y_Position);
-                                    var worldPoint= local.ToOldCoord(localPoint.X, localPoint.Y);
+                                    var worldPoint = local.ToOldCoord(localPoint.X, localPoint.Y);
                                     var point = currentProduct.ScrewPoints[i].Clone();
                                     point.X_Position = (float)worldPoint[0];
                                     point.Y_Position = (float)worldPoint[1];
@@ -1557,7 +1660,7 @@ namespace TeamAAS_VP.Core
                 {
                     if (tuple.value is Int16 state)
                     {
-                        if (state!=0)
+                        if (state != 0)
                         {
                             SendTaskMessage($"螺丝供料器...", MessageLevel.Info);
                             await plc.WriteNodeAsync(addressConfig.In_PickINC.Address, (Int16)0);

+ 0 - 182
TeamAAS-VM/Core/Signal.cs

@@ -1,182 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Collections.ObjectModel;
-using System.IO;
-using System.IO.Ports;
-using System.Linq;
-using System.Text;
-using System.Threading;
-using System.Threading.Tasks;
-using System.Windows;
-using TouchSocket.SerialPorts;
-
-namespace TeamAAS_VP.Core
-{
-    /// <summary>
-    /// 扭力测量仪
-    /// </summary>
-    public class Signal
-    {
-        //public static List<TouchSocket.SerialPorts.SerialPortClient> sp = new List<TouchSocket.SerialPorts.SerialPortClient>();
-        SerialPortClient client;
-        public static string BGSignalConfigPath = "..//Config//扭力测量仪配置文件.json";
-        SignalRS232Config _bGModbus;
-        public static string com;
-        public static string baudRate = "9600";
-        public static int parity = 0;
-        public static string dataBits = "8";
-        public static string stopBites = "1";
-        public static int readTimeOut = 1000;
-        public static bool isopen;
-
-        private static SerialPort sp = new SerialPort();
-        public async Task InitSignal()
-        {
-            if (File.Exists(BGSignalConfigPath))
-            {
-                try
-                {
-                    var res = FileHelper.ReadJsonFile<SignalRS232Config>(BGSignalConfigPath);
-                    if (res != null)
-                    {
-                        foreach (var port in res.PortName)
-                        {
-                            com = port;
-                            OpenSerial(port, baudRate, parity, dataBits, stopBites, readTimeOut);
-                        }
-                    }
-                }
-                catch (Exception ex)
-                {
-                    LogHelper.WriteLogError("读取后台ModbusTCP通讯文件时出错!", ex);
-                }
-            }
-            else
-            {
-                _bGModbus = new SignalRS232Config();
-                _bGModbus.PortName.Add("COM4");
-                FileHelper.WriteJsonFile(_bGModbus, BGSignalConfigPath);
-            }
-        }
-        private static bool OpenSerial(string strPortName, string strBaudRate, int parity, string strDataBits, string strStopBits, int ReadTimeout)
-        {
-            try
-            {
-                sp.PortName = strPortName;
-                sp.BaudRate = int.Parse(strBaudRate);
-                sp.DataBits = int.Parse(strDataBits);
-                sp.StopBits = (StopBits)int.Parse(strStopBits);
-                sp.ReadTimeout = ReadTimeout;
-                sp.Parity = (Parity)parity;
-                sp.Open();
-                return isopen = true;
-            }
-            catch (Exception ex)
-            {
-                LogHelper.WriteLogError("扭力测量仪连接失败", ex);
-                return isopen = false;
-            }
-        }
-
-        public static string SerialPortSendAndRecive(string strPortName, string strBaudRate, int parity, string strDataBits, string strStopBits, int ReadTimeout, string Sendstring)
-        {
-            try
-            {
-                if (isopen)
-                {
-                    string result = SendAndRecive(Sendstring);
-                    return result;
-                }
-                return "Open SerialPort Fail";
-            }
-            catch (Exception ex)
-            {
-                return "Send Fail" + ex.Message;
-            }
-        }
-
-        private static string SendAndRecive(string str)
-        {
-            try
-            {
-                byte[] array = strToHexByte(str.Trim());
-                sp.Write(array, 0, array.Length);
-                Thread.Sleep(100);
-                int bytesToRead = sp.BytesToRead;
-                byte[] array2 = new byte[bytesToRead];
-                sp.Read(array2, 0, bytesToRead);
-                string text = byteToHexStr(array2);
-                return text;
-
-            }
-            catch (Exception ex)
-            {
-                return "EOROR" + ex.Message;
-            }
-        }
-        public static string byteToHexStr(byte[] bytes)
-        {
-            string text = "";
-            if (bytes != null)
-            {
-                for (int i = 0; i < bytes.Length; i++)
-                {
-                    text = text + bytes[i].ToString("X2") + " ";
-                }
-            }
-
-            return text;
-        }
-        private static byte[] strToHexByte(string hexString)
-        {
-            hexString = hexString.Replace(" ", "");
-            if (hexString.Length % 2 != 0)
-            {
-                hexString += " ";
-            }
-
-            byte[] array = new byte[hexString.Length / 2];
-            for (int i = 0; i < array.Length; i++)
-            {
-                array[i] = Convert.ToByte(hexString.Substring(i * 2, 2).Replace(" ", ""), 16);
-            }
-
-            return array;
-        }
-
-        public double SendAndReceive()
-        {
-            try
-            {
-                var data = SerialPortSendAndRecive(com, baudRate, parity, dataBits, stopBites, readTimeOut, "01 04 00 00 00 01 31 CA");
-                if (data == "Open SerialPort Fail")
-                {
-                    MessageBox.Show("扭力测量仪连接失败");
-                }
-                else if (data.Contains("Send Fail"))
-                {
-                    MessageBox.Show("扭力测量发送数据失败");
-                }
-                string[] parts = data.Split(' ');
-                string mystr = string.Join(" ", parts, 3, 4);
-                string hex = mystr.Replace(" ", ""); // 16 进制字符串
-                int decimalValue = Convert.ToInt32(hex, 16); // 转换为 10 进制整数
-                double response = decimalValue / 100.0;
-                return response;
-            }
-            catch (Exception ex)
-            {
-                LogHelper.WriteLogError("扭力测量仪接收信息时出错!", ex);
-                return 0;
-            }
-        }
-    }
-    public class SignalRS232Config
-    {
-        public ObservableCollection<string> PortName { get; set; }
-        public SignalRS232Config()
-        {
-            PortName = new ObservableCollection<string>();
-        }
-    }
-}

+ 3 - 0
TeamAAS-VM/Models/TorqueTest.cs

@@ -14,6 +14,9 @@ namespace TeamAAS_VP.Models
         public double Xpoint { get; set; }
         public double Ypoint { get; set; }
         public double Zpoint { get; set; }
+        /// <summary>
+        /// 扭力阈值
+        /// </summary>
         public double TorqueValue { get; set; }
     }
 }

+ 0 - 1
TeamAAS-VM/TeamAAS-VP.csproj

@@ -526,7 +526,6 @@
     <Compile Include="Controls\FeederSystemParam.xaml.cs">
       <DependentUpon>FeederSystemParam.xaml</DependentUpon>
     </Compile>
-    <Compile Include="Core\Signal.cs" />
     <Compile Include="Events\MainTabSwitchNotification.cs" />
     <Compile Include="Models\Feeder\ScrewFeederInfo.cs" />
     <Compile Include="Models\NumberStatistics.cs" />

+ 43 - 21
TeamAAS-VM/ViewModels/Home/TorqueCheckViewModel.cs

@@ -12,6 +12,7 @@ using System.Text;
 using System.Threading.Tasks;
 using System.Windows;
 using TeamAAS_VP.Core;
+using TeamAAS_VP.Enums;
 using TeamAAS_VP.Events;
 using TeamAAS_VP.Interfaces;
 using TeamAAS_VP.Models;
@@ -91,30 +92,28 @@ namespace TeamAAS_VP.ViewModels.Home
             set { SetProperty(ref _torqueValue, value); }
         }
 
-        private double _TValue;
-        public double TValue
+        private string _TValue;
+        public string TValue
         {
             get { return _TValue; }
-            set 
-            { 
+            set
+            {
                 SetProperty(ref _TValue, value);
-                SubValue = TValue - PValue;
             }
         }
 
-        private double _PValue;
-        public double PValue
+        private string _PValue;
+        public string PValue
         {
             get { return _PValue; }
-            set 
-            { 
+            set
+            {
                 SetProperty(ref _PValue, value);
-                SubValue = TValue - PValue;
             }
         }
 
-        private double _SubValue;
-        public double SubValue
+        private string _SubValue;
+        public string SubValue
         {
             get { return _SubValue; }
             set { SetProperty(ref _SubValue, value); }
@@ -167,7 +166,7 @@ namespace TeamAAS_VP.ViewModels.Home
         #endregion
 
         #region 方法
-        public TorqueCheckViewModel(IEventAggregator ea, IConfigService configService,IContainerProvider container)
+        public TorqueCheckViewModel(IEventAggregator ea, IConfigService configService, IContainerProvider container)
         {
             _eventAggregator = ea;
             _configService = configService;
@@ -318,21 +317,44 @@ namespace TeamAAS_VP.ViewModels.Home
         {
             try
             {
-                TValue = management.signalTest.SendAndReceive();
-                if (Result=="OK")
+                TValue = management.SignalValue;
+                double tvalue = double.Parse(TValue.Split(' ')[0]);
+                PValue = $"{management.Value} N·m";
+                double pvalue = management.Value;
+                SubValue = $"{Math.Abs(tvalue - pvalue)} N·m";
+                double sub = Math.Abs(tvalue - pvalue);
+
+                var res = FileHelper.ReadJsonFile<TorqueTest>(FilePath.TorqueCheckPath);
+                if (res != null)
                 {
-                    FontColor = "Green";
-                    Result = "OK";
+                    if (sub <= res.TorqueValue)
+                    {
+                        FontColor = "Green";
+                        Result = "OK";
+                    }
+                    else
+                    {
+                        FontColor = "Red";
+                        Result = "NG";
+                    }
                 }
                 else
                 {
-                    FontColor = "Red";
-                    Result = "NG";
+                    if (sub <= torqueValue)
+                    {
+                        FontColor = "Green";
+                        Result = "OK";
+                    }
+                    else
+                    {
+                        FontColor = "Red";
+                        Result = "NG";
+                    }
                 }
             }
-            catch (Exception)
+            catch (Exception ex)
             {
-
+                LogHelper.WriteLogError("执行点检时出错!", ex);
             }
         }
         #endregion

+ 1 - 1
TeamAAS-VM/ViewModels/MainWindowViewModel.cs

@@ -385,7 +385,7 @@ namespace TeamAAS_VP.ViewModels
             {
                 _eventAggregator.GetEvent<ProgressNotification>().Publish(new UProgressBar.ProgressParameter { Maximum = max, Minimum = 0, SubTitle = $"{Lang.初始化中}...", Message = $"{Lang.正在开启}...", Value = curvalue });
             }));
-            await management.signalTest.InitSignal();
+            await management.InitSignal();
             management.ReadConfig();
 
             //当前日期