Browse Source

修改plc读写

user_lt 1 year ago
parent
commit
a887413942

+ 1 - 1
BlankApp1/BlankApp1/App.config

@@ -3,7 +3,7 @@
 	<appSettings>
 		<!--连接字符串 SQL Server-->
 		<add key="MySql" value="Data Source=localhost;Database=plc_point_db;User Id='root';Password='Lt,100186';port=3306;charset=utf8mb4;"/>
-		<add key="PLCIp" value="192.168.0.20"/>
+		<add key="PLCIp" value="192.168.250.1"/>
 		<add key="PLCPort" value="9600"/>
 
 	</appSettings>

+ 77 - 51
BlankApp1/BlankApp1/Common/PLCCom.cs

@@ -15,7 +15,8 @@ namespace PLCTool.Common
         private static string plcPort = ConfigurationManager.AppSettings["PLCPort"];
         private EtherNetPLC ENT;//plc连接
         private static PLCCom instance;
-        private bool isConnect = false; 
+        private static bool isConnect=false;
+       
 
         private PLCCom() 
         {
@@ -25,7 +26,7 @@ namespace PLCTool.Common
 
         public static PLCCom GetInstance()
         {
-            if (instance == null)
+            if (instance == null||(!isConnect))
             {
                instance = new PLCCom();
             }
@@ -33,6 +34,11 @@ namespace PLCTool.Common
 
         }
 
+        public bool IsConnectPLC()
+        {
+            return isConnect;
+        }
+
         private bool ConnectPLC()
         {
             ENT = new EtherNetPLC();
@@ -54,7 +60,7 @@ namespace PLCTool.Common
             string value = string.Empty; ;
             short rb;
             short reSuc = -1;
-            if (isConnect== false)
+            if (isConnect == false)
             {
                 return string.Empty;
             }
@@ -62,22 +68,35 @@ namespace PLCTool.Common
             switch (valueType)
             {
                 case VarType.Bit:
-           
-                    reSuc = ENT.GetBitState(PlcMemory.CIO, address, out rb);
-                    //读取成功
-                    if (reSuc == 0)
+                    try
+                    {
+                        reSuc = ENT.GetBitState(PlcMemory.CIO, address, out rb);
+                        //读取成功
+                        if (reSuc == 0)
+                        {
+                            value = rb.ToString();
+                        }
+                    }
+                    catch(Exception ex)
                     {
-                        value = rb.ToString();
+
                     }
                     break;
                 case VarType.Byte:
                     break;
                 case VarType.Word:
-                    reSuc = ENT.ReadWord(PlcMemory.DM, short.Parse(address), out rb);
-                    //读取成功
-                    if(reSuc==0)
+                    try
+                    {
+                        reSuc = ENT.ReadWord(PlcMemory.DM, short.Parse(address), out rb);
+                        //读取成功
+                        if (reSuc == 0)
+                        {
+                            value = rb.ToString();
+                        }
+                    }
+                    catch (Exception ex)
                     {
-                        value = rb.ToString();
+
                     }
                     break;
                 case VarType.DWord:
@@ -103,51 +122,58 @@ namespace PLCTool.Common
             {
                 return false;
             }
-
-            switch (valueType)
+            try
             {
-                case VarType.Bit:
-                    BitState bit= BitState.OFF;
-                    if(writeValue.Trim()=="1")
-                    {
-                        bit = BitState.ON;
-                    }
-                    else
-                    {
-                        if (writeValue.Trim() == "0")
+                switch (valueType)
+                {
+                    case VarType.Bit:
+                        BitState bit = BitState.OFF;
+                        if (writeValue.Trim() == "1")
                         {
-                            bit = BitState.OFF;
+                            bit = BitState.ON;
                         }
+                        else
+                        {
+                            if (writeValue.Trim() == "0")
+                            {
+                                bit = BitState.OFF;
+                            }
 
-                    }
-                    reSuc = ENT.SetBitState(PlcMemory.DM, address,bit);
-                    //写成功
-                    if (reSuc == 0)
-                    {
-                        isSuccess = true;
-                    }
-                    break;
-                case VarType.Byte:
-                    break;
-                case VarType.Word:
-                    short wValue = Convert.ToInt16(writeValue);
-                    reSuc = ENT.WriteWord(PlcMemory.DM, short.Parse(address), wValue);
-                    //写成功
-                    if (reSuc == 0)
-                    {
-                        isSuccess = true;
-                    }
-                    break;
-                case VarType.DWord:
-                    break;
-                case VarType.Int:
-                    break;
-                case VarType.DInt:
-                    break;
-                case VarType.Real:
-                    break;
+                        }
+                        reSuc = ENT.SetBitState(PlcMemory.DM, address, bit);
+                        //写成功
+                        if (reSuc == 0)
+                        {
+                            isSuccess = true;
+                        }
+                        break;
+                    case VarType.Byte:
+                        break;
+                    case VarType.Word:
+                        short wValue = Convert.ToInt16(writeValue);
+                        reSuc = ENT.WriteWord(PlcMemory.DM, short.Parse(address), wValue);
+                        //写成功
+                        if (reSuc == 0)
+                        {
+                            isSuccess = true;
+                        }
+                        break;
+                    case VarType.DWord:
+                        break;
+                    case VarType.Int:
+                        break;
+                    case VarType.DInt:
+                        break;
+                    case VarType.Real:
+                        break;
+
+                }
+            }
+            catch(Exception ex )
+            {
 
             }
+            
             return isSuccess;
         }
 

+ 27 - 0
BlankApp1/BlankApp1/Controls/Convert/Bool2ColorConverter.cs

@@ -0,0 +1,27 @@
+using System;
+using System.Collections.Generic;
+using System.Globalization;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+using System.Windows.Data;
+using System.Windows.Media;
+
+namespace PLCTool.Controls.Convert
+{
+    public class Bool2ColorConverter : IValueConverter
+    {
+        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
+        {
+            if (value == null || value.ToString() == "")
+                return "";
+            bool isOpen = (bool)value;
+            return isOpen ? new SolidColorBrush((Color)ColorConverter.ConvertFromString("#11D71B")) : new SolidColorBrush((Color)ColorConverter.ConvertFromString("#D1D1D1"));
+        }
+
+        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
+        {
+            throw new NotImplementedException();
+        }
+    }
+}

+ 42 - 0
BlankApp1/BlankApp1/ViewModels/MainWindowViewModel.cs

@@ -3,13 +3,18 @@ using BizService;
 using BlankApp1.Common;
 using BlankApp1.Views;
 using Microsoft.Extensions.Logging;
+using Model.Dto;
+using PLCTool.Common;
 using Prism.Commands;
 using Prism.Mvvm;
 using Prism.Regions;
 
 using System;
 using System.Collections.Generic;
+using System.Collections.ObjectModel;
 using System.IO;
+using System.Threading.Tasks;
+using System.Windows;
 
 namespace BlankApp1.ViewModels
 {
@@ -36,6 +41,7 @@ namespace BlankApp1.ViewModels
             ButtonNavigateCommand = new DelegateCommand<string>(ButtonNavigate);
             BackCommand = new DelegateCommand(GoBack);
             NextCommand = new DelegateCommand(GoNext);
+            JudgePLC();
             logger.LogInformation("info");
             logger.LogError("error");
             //_regionManager.Regions["MeunRegion"].RequestNavigate("TreeMenuView");
@@ -43,6 +49,7 @@ namespace BlankApp1.ViewModels
 
         }
 
+
         private void GoNext()
         {
             if(journal.CanGoForward)
@@ -77,11 +84,46 @@ namespace BlankApp1.ViewModels
             _regionManager.Regions["MenuRegion"].RequestNavigate("TreeMenuView");
             _regionManager.Regions["ContentRegion"].RequestNavigate("StatisticsView");
 
+        }
+        /// <summary>
+        /// 连接PLC
+        /// </summary>
+        private void JudgePLC()
+        {
+            
+                Task.Run(async () =>
+                {
+                    while (true)
+                    {
+                       
+                        //更新界面上的值
+                        Application.Current.Dispatcher.Invoke(() =>
+                        {
+                            PLCIsConnect = PLCCom.GetInstance().IsConnectPLC();
+
+
+                        });
+
+                        await Task.Delay(5000);
+                    }
+
+                });
+            
         }
         #region 命令绑定
         public DelegateCommand<string> ButtonNavigateCommand { set; get; }
         public DelegateCommand NextCommand { set; get; }
         public DelegateCommand BackCommand { set; get; }
         #endregion
+        #region 数据绑定
+
+
+        private bool plcIsConnect = false;
+        public bool PLCIsConnect
+        {
+            get { return plcIsConnect; }
+            set { plcIsConnect = value; RaisePropertyChanged(); }
+        }
+        #endregion
     }
 }

+ 7 - 2
BlankApp1/BlankApp1/ViewModels/MonitorManageViewModel/PLCReadViewModel.cs

@@ -57,12 +57,17 @@ namespace PLCTool.ViewModels.MonitorManageViewModel
                 Task.Run(async () =>
                 {
                     while(true)
-                    { 
+                    {
                         //更新界面上的值
                         Application.Current.Dispatcher.Invoke(() =>
                         {
                             foreach (var item in PLCItemList)
                             {
+                                //没有连接 plc,直接退出
+                                if(!PLCCom.GetInstance().IsConnectPLC())
+                                {
+                                    break;
+                                }
                                 string plcAddr = item.PlcAddress;
                                 string plcAddType = item.PlcAddType;
                                 switch (plcAddType)
@@ -83,7 +88,7 @@ namespace PLCTool.ViewModels.MonitorManageViewModel
 
                             }
                         });
-                     
+
                         await Task.Delay(5000);
                     }
 

+ 5 - 0
BlankApp1/BlankApp1/ViewModels/MonitorManageViewModel/PLCWriteViewModel.cs

@@ -37,6 +37,11 @@ namespace PLCTool.ViewModels.MonitorManageViewModel
         {
             foreach (var item in PLCItemList)
             {
+                //没有连接 plc,直接退出
+                if (!PLCCom.GetInstance().IsConnectPLC())
+                {
+                    break;
+                }
                 string plcAddr = item.PlcAddress;
                 string plcAddType = item.PlcAddType;
                 switch (plcAddType)

+ 13 - 2
BlankApp1/BlankApp1/Views/MainWindow.xaml

@@ -2,9 +2,10 @@
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:prism="http://prismlibrary.com/"
-         Title="MainWindow" 
+        xmlns:convt="clr-namespace:PLCTool.Controls.Convert"
+        Title="MainWindow" 
         prism:ViewModelLocator.AutoWireViewModel="True"
-          Height="600"
+        Height="600"
   Width="800"
   WindowStartupLocation="CenterScreen"
   MouseMove="Window_MouseMove"
@@ -78,6 +79,7 @@
                 </Trigger>
             </Style.Triggers>
         </Style>
+        <convt:Bool2ColorConverter x:Key="boolToColorConvert"/>
     </Window.Resources>
     <Grid>
         <Grid.RowDefinitions>
@@ -139,6 +141,15 @@
                     </Path.Data>
                 </Path>
 
+                <TextBlock Text="PLC连接:" Style="{StaticResource txtHeadStyle}" Width="60" Margin="30,0,12,0"/>
+                <!--圆型-->
+                <Path  Stroke="Transparent"  Fill="{Binding PLCIsConnect ,Converter={StaticResource boolToColorConvert}}" StrokeThickness="1" HorizontalAlignment="Center" VerticalAlignment="Center" >
+                    <Path.Data >
+                        <EllipseGeometry Center="2,5" RadiusX="4" RadiusY="4" >
+                        </EllipseGeometry>
+                    </Path.Data>
+                </Path>
+
             </StackPanel>
           
         </Border>