使用S7.net读取西门子1500PLC

使用S7.net通信库,可以不使用任何功能块,直接用C# 访问西门子PLC

配置文件: 记得用ANSI格式。因为微软的库默认ANSI

[配置信息]
IP地址=192.168.1.198
CPU类型=S71500
存储周期=10
自动存储=0

读取配置文件的工具类

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;

namespace IniHelper
{
    public class IniConfigHelper
    {
        #region API函数声明

        [DllImport("kernel32")]
        private static extern long WritePrivateProfileString(string section, string key,
            string val, string filePath);

        //需要调用GetPrivateProfileString的重载
        [DllImport("kernel32", EntryPoint = "GetPrivateProfileString")]
        private static extern long GetPrivateProfileString(string section, string key,
            string def, StringBuilder retVal, int size, string filePath);

        [DllImport("kernel32", EntryPoint = "GetPrivateProfileString")]
        private static extern uint GetPrivateProfileStringA(string section, string key,
            string def, Byte[] retVal, int size, string filePath);

        #endregion

        #region 读Ini文件

        public static string ReadIniData(string Section, string Key, string NoText, string iniFilePath)
        {
            if (File.Exists(iniFilePath))
            {
                StringBuilder temp = new StringBuilder(1024);
                GetPrivateProfileString(Section, Key, NoText, temp, 1024, iniFilePath);
                return temp.ToString();
            }
            else return String.Empty;
        }

        #endregion

        #region 写Ini文件

        public static bool WriteIniData(string Section, string Key, string Value, string iniFilePath)
        {
            long OpStation = WritePrivateProfileString(Section, Key, Value, iniFilePath);
            if (OpStation == 0)
                return false;
            else return true;
        }
        #endregion

    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace IniHelper
{
    public class SettingManager
    {
        public SettingManager(string path)//ctor 构造方法快捷键
        {
            this.Path = path;
        }
        private string _path;
        SysSettings sysSettings = new SysSettings();

        public string Path { get => _path; set => _path = value; }//cirl+R+E

        public SysSettings LoadSysSettings()
        {
            
            sysSettings.IpAdress = IniConfigHelper.ReadIniData("配置信息", "IP地址", "1", _path);
            sysSettings.CpuType = IniConfigHelper.ReadIniData("配置信息", "CPU类型", "S71200", _path);
            sysSettings.StoreTime = IniConfigHelper.ReadIniData("配置信息", "存储周期", "10", _path);
            sysSettings.AutoSore = IniConfigHelper.ReadIniData("配置信息", "自动存储", "0", _path);
            return sysSettings;
            //try
            //{

            //}
            //catch (Exception)
            //{
            //    return null;
            //}//ConfigFile
        }

        //SysSettings sysSettings = new SysSettings();

        public bool SaveSysSettings(SysSettings sysSettings)
        {
            bool result = true;
            result &= IniConfigHelper.WriteIniData("配置信息","IP地址",sysSettings.IpAdress, _path);
            result &= IniConfigHelper.WriteIniData("配置信息", "CPU类型", sysSettings.CpuType, _path);
            result &= IniConfigHelper.WriteIniData("配置信息", "存储周期", sysSettings.StoreTime.ToString(), _path);
            result &= IniConfigHelper.WriteIniData("配置信息", "自动存储", sysSettings.AutoSore.ToString(), _path);
            return result;
        }
    }
}

PLC的信息类

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace IniHelper
{
    public class SysSettings
    {
        public string IpAdress { get; set; }
        public string CpuType { get; set; }
        public string StoreTime { get; set; }
        public string AutoSore { get; set; }
    }
}

定义15个ushort变量,对应1500里15个word变量

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace IniPractice
{
    public class CommunicationState
    {
        //建立15个变量,1500PLC使用word发送
        public ushort SatusValue { get; set; }
        public ushort LimitLeft { get; set; }
        public ushort RightLeft { get; set; }
        public ushort LimitOriginal { get; set; }
        public ushort RunState { get; set; }
        public ushort CurrentSpeed { get; set; }
        public ushort CurrentPosition { get; set; }
        public ushort SpeedSet1 { get; set; }
        public ushort SpeedSet2 { get; set; }
        public ushort SpeedSet3 { get; set; }
        public ushort SpeedSet4 { get; set; }
        public ushort SpeedSet5 { get; set; }
        public ushort SpeedSet6 { get; set; }
        public ushort SpeedSet7 { get; set; }
        public ushort SpeedSet8 { get; set; }


    }
}

建立通信类

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using IniHelper;
using S7.Net;
using thinger.cn.DataConvertHelper;

namespace IniPractice
{
    public class CoreLogicManager
    {
        private Plc simensS7 = null;
        //public int MyProperty { get; set; }
        public CommunicationState CurentState { get; set; } = new CommunicationState();

        private CancellationTokenSource cts = new CancellationTokenSource();
      
        //连接
        public bool ConnectPLC(SysSettings sysSettings)
        {
            try
            {
                simensS7 = new Plc((CpuType)Enum.Parse(typeof(CpuType), sysSettings.CpuType), sysSettings.IpAdress, 0,0);
                simensS7.Open();
            }
            catch (Exception)
            {
                return false;
            }
            //采集 多线程执行
            Task.Run(() =>
            {
                PLCCommucation();
            }, cts.Token);
            return true;
        }
        private void PLCCommucation()
        {
            while (!cts.IsCancellationRequested)
            {

                byte[] result = simensS7.ReadBytes(S7.Net.DataType.DataBlock, 1, 0,30);//起始地址,数量30
                //数据解析 截取字节数组,转换为需要的值
                if (result!=null && result.Length==30)
                {
                    CurentState.SatusValue = UShortLib.GetUShortFromByteArray(result, 0);//状态值 偏移量
                    CurentState.LimitLeft = UShortLib.GetUShortFromByteArray(result, 2);//状态值
                    CurentState.RightLeft = UShortLib.GetUShortFromByteArray(result, 4);//状态值
                    CurentState.LimitOriginal = UShortLib.GetUShortFromByteArray(result, 6);//状态值
                    CurentState.RunState = UShortLib.GetUShortFromByteArray(result, 8);//状态值
                    //CurentState.SatusValue = ByteLib.GetByteFromByteArray(result,0);//状态值
                    //CurentState.LimitLeft = BitLib.GetBitFromByteArray(result, 20, 5);//20个字节第5个位
                }
            }
        }

        //断开
        private void PLCClose()
        {
            if (cts!=null)
            {
                cts.Cancel();
            }
            
            if(simensS7!=null)
            {
                simensS7.Close();
            }
        }
    }
}

主窗体

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using IniHelper;
using S7.Net;

namespace IniPractice
{
    public partial class FrmMain : Form
    {
        public FrmMain()
        {
            InitializeComponent();
            this.SetsManager = new SettingManager(Application.StartupPath + "\\config.ini");
            this.SysSets = SetsManager.LoadSysSettings();
        }
        
        //声明2个对象 
        private SysSettings _sysSets;
        private SettingManager _setsManager;

        public SysSettings SysSets { get => _sysSets; set => _sysSets = value; }
        public SettingManager SetsManager { get => _setsManager; set => _setsManager = value; }

        private void button1_Click(object sender, EventArgs e)
        {
            FrmCommonSet frmCommonSet = new FrmCommonSet(_setsManager, _sysSets);//对外传值用属性
            frmCommonSet.Show();
        }
    }
}


通信窗体

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using IniHelper;

namespace IniPractice
{
    public partial class FrmCommonSet : Form
    {
        public FrmCommonSet(SettingManager settingManager, SysSettings sysSettings)
        {
            InitializeComponent();
            this.SetsManager = settingManager;
            this.SysSets = sysSettings;

            if (sysSettings!=null)
            {
                this.txtAutoSore.Text = SysSets.AutoSore.Trim();
                this.txtIpAdress.Text = SysSets.IpAdress.Trim();
                this.txtStoreTime.Text = SysSets.StoreTime.Trim();
                this.cmbConfig.Text = SysSets.CpuType.Trim();
            }
        }

        //声明2个对象
        private SysSettings _sysSets;
        private SettingManager _setsManager;

        private CoreLogicManager PlcConnect = new CoreLogicManager();

        public SysSettings SysSets { get => _sysSets; set => _sysSets = value; }
        public SettingManager SetsManager { get => _setsManager; set => _setsManager = value; }


        private void btnSave_Click(object sender, EventArgs e)
        {
           
        }

        private void btnSet_Click(object sender, EventArgs e)
        {
            SysSets.IpAdress = this.txtIpAdress.Text.Trim();
            SysSets.CpuType = this.cmbConfig.Text.ToString();           this.cmbConfig.Text.Trim();
            SysSets.StoreTime = this.txtStoreTime.Text.Trim();
            SysSets.AutoSore = this.txtAutoSore.Text.Trim();

            bool result = SetsManager.SaveSysSettings(SysSets);
            if (result)
            {
                MessageBox.Show("配置信息存储成功!","配置存储");
            }
            else
            {
                MessageBox.Show("配置信息存储失败!", "配置存储");
            }
        }

        private void FrmCommonSet_Load(object sender, EventArgs e)
        {
            //cmbConfig.Items.Add("S7200");//0
            //cmbConfig.Items.Add("Logo0BA8");//1
            //cmbConfig.Items.Add("S7200Smart");//2
            //cmbConfig.Items.Add("S7300");//10
            //cmbConfig.Items.Add("S7400");//20
            //cmbConfig.Items.Add("S71200");//30
            //cmbConfig.Items.Add("S71500");//40
            cmbConfig.Items.AddRange(
                new string[] 
                {
                    "S7200", "Logo0BA8", "S7200Smart","S7300","S7400","S71200","S71500"
                });
        }

        private void btnConnect_Click(object sender, EventArgs e)
        {
            bool res = PlcConnect.ConnectPLC(_sysSets);
            if (res)
            {
                MessageBox.Show("PLC连接成功");
                this.label1.Text = PlcConnect.CurentState.SatusValue.ToString();
                this.label2.Text = PlcConnect.CurentState.LimitLeft.ToString();
                this.label3.Text = PlcConnect.CurentState.RightLeft.ToString();
            }
            else
            {
                MessageBox.Show("PLC连接失败");
            }
        }
    }
}

使用S7.net读取西门子1500PLC_第1张图片
使用S7.net读取西门子1500PLC_第2张图片

你可能感兴趣的:(.net,c#,microsoft)