当前位置:网站首页>C # use Siemens S7 protocol to read and write PLC DB block

C # use Siemens S7 protocol to read and write PLC DB block

2022-07-07 04:21:00 Little girl

  • Teach people to use C# How to read and write Siemens conveniently and quickly DB The value of the block , Realize the upper computer and plc The process of communication
  • Siemens used PLC model ,S7 1200 

1.Nuget install s7 Drive pack

 2. Siemens plc Define a db block , This is what our upper computer needs to read and write DB

 3. According to Siemens S7 Protocol documentation

Read DB There are many ways to block , Directly according to the DB It is also OK to read and write with an offset of , But reading or writing data requires corresponding data type conversion to finally get the value or write it , I think it's too much trouble . But documentation also provides a simpler way , Is the way of reading and writing .

3.1 The principle of reading and writing class , It is processed by reflection , But we don't need to care about how it reflects , We only care about how we use .

3.2 First , You need to create a class , With Siemens DB block Entity classes with the same name

Siemens plc The establishment of a DB Block name  

 C# Establish corresponding db Class attribute of block name

 4. Class creation is complete , We read and write data through interfaces

There are two kinds of interface definitions , Common interfaces and generic interfaces . The differences and benefits of using generic interfaces and common interfaces will be introduced later

4.1 Implementation of common interface

  according to s7 file , Provides ReadClass Read method . There are many ways to provide reading , We only introduce one way , Is to pass in the established entity class . Other self research and implementation .

 public void ReadClass(object sourceClass, int db, int startByteAdr = 0)
  • sourceClass Class instances of assigned values
  • db Data blocks
  • startByteAdr Read the starting address of the font

 4.2 After we know the passed in parameters of this method , Next, you need to define the methods of the interface .

  Why should we define to return an entity , Because when we read data , You need to pass in an entity , After reading ,Plc Of Db The value of the block will be reflected in this entity , We get the latest read value through this entity . Next, we implement this interface method .

 1. The above implementation , It is equivalent to the following way of writing .

CathodeEntity testClass = new CathodeEntity();
plc.ReadClass(testClass, 5);

  It's just , In order to prevent every call, I will re new One CathodeEntity class . I'll just put this  CathodeEntity Class is designed into singleton mode . Only instantiate once forever , All we need to change is the attribute value of this class . hinder 5, The meaning is what we want to read DB block 5

 2. Single column instance class  CathodeEntity

public class CathodeEntity
    {
        public bool CathodeUp { get; set; }
        public bool EntryAllowed { get; set; }
        public bool LeaveAllowed { get; set; }
        //  Define a static variable to hold an instance of the class 
        private static CathodeEntity uniqueInstance;
        //  Define an identity to ensure thread synchronization 
        private static readonly object locker = new object();
        //  Define private constructors , Make it impossible for the outside world to create such an instance 
        private CathodeEntity()
        {

        }
        /// <summary>
        ///  Defining a public method provides a global access point , You can also define public properties to provide global access points 
        /// </summary>
        /// <returns></returns>
        public static CathodeEntity GetInstance()
        {
            //  When the first thread runs here , It will be right at this time locker object  " Lock ",
            //  When the second thread runs the method , First detected locker The object is " Lock " state , The thread will hang waiting for the first thread to unlock 
            // lock After the statement runs ( After the thread runs ) To the object " Unlock "
            if (uniqueInstance == null)
            {
                lock (locker)
                {
                    //  If an instance of the class does not exist, create , Otherwise go straight back to 
                    if (uniqueInstance == null)
                    {
                        uniqueInstance = new CathodeEntity();
                    }
                }
            }
            return uniqueInstance;
        }
    }

3. Singleton design pattern Reference resources  

4.3 Next , Call the interface , You can get plc The value of the .

  The read value is similar to Siemens PLC DB5 The value of is the same

 5. The above is the implementation of ordinary interfaces , But if we are multiple db block , According to the routine, do you have to write N Implementation methods , This is not easy to maintain , A lot of code . So we design the interface as a generic implementation .

Why can we design generics , According to this s7 agreement , Methods of reading classes , The first parameter is object type , It can also be a specific instance type .

5.1 We need to set the interface constraint type . Why do this , The class that we want to implement this interface , Stipulate this T type , You can't pass int or string etc. , You must pass a class to it . This prevents , When the interface is implemented , You passed the wrong parameter .

 5.2 next , We implement this generic interface , So this t, We can change it to , We follow Plc Defined data block , Establish the corresponding entity class .

for example , At present Plc There is one db block 5, We establish the corresponding entity attribute class name is CathodeEntity, When we call, we pass CathodeEntity Entities come in . If plc There are many. db block , We also need to have multiple corresponding entity classes . At this time, we can pass in different entity classes , Coming back is plc Specifically db The value of the block .

Implementation interface  

 5.3 Call interface . Instantiate first CathodeEntity Entity class , hold CathodeEntity Pass in , What you get is the corresponding Db block 5 Value . If it's something else Db block , We need to establish a relationship with plc db The entity class corresponding to the block name , And then again CathodeEntity Instead, create a new class to read . In this way, the interface method reuse is realized .

 6.  Interface call specific implementation .

 6.1 Plc Connection class , Because I only need to instantiate it once , So we should also design it into a singleton mode

    /// <summary>
    ///  Positive buffer rack plc
    /// </summary>
    internal class CathodeBufferRack
    {
        // Define static variables to save instances 
        public static volatile Plc CathodePlc;
        // Define an identity to ensure thread synchronization 
        private static object lockHelper = new object();
        // Define private variables , So that the external cannot create instances of this class 
        private CathodeBufferRack()
        {

        }
        public static Plc Instance(string DeviceIp)
        {
            if(CathodePlc == null)
            {
                lock (lockHelper)
                {
                    if (CathodePlc == null)
                    {
                        CathodePlc = new Plc(CpuType.S71200, DeviceIp, 0,1);
                        CathodePlc.Open();
                        if (!CathodePlc.IsConnected)
                        {
                            CathodePlc.Close();
                            CathodePlc = null;
                        }
                    }
                }
            }
            return CathodePlc;
        }
    }

 7. Write plc db The same is true .

7.1 Define the interface method written

7.2 Implementation interface method

 7.3 Program call

7.4  LeaveAllowed The entity is changed to true after , Pass in .plc The driver automatically reflects , Put the corresponding entity plc db The value of the block is updated directly . In this way, there is no need to operate reading and writing through offset db Block. .

If db There are different types of blocks , for example byte ,Int ,DInt , etc. , Same thing , Just create the corresponding data type .

 7.5 PLC And C# Common data type conversion

PLCC#
BoolBool
Wordushort
Intushort
Dworduint32
Dintuint
bytebyte
Real
bouble

Refer to Official website

8. Comparison between ordinary interface and generic interface .

8.1 As shown in the following example , After the ordinary interface is fixed and the entity parameters are passed in , It can only stipulate that you transfer CathodeEntity Entity class object .

Common interface methods :

But if , We are going to read the same plc, Different db block , Is this method not applicable . Then we have to redefine an interface method , Only the class parameters are different .

but plc.WriteClass() This method is suitable for writing different db The block , It is determined by the passed in parameters that it wants to write db block . So repeat the interface implementation like this , Increase the amount of code and it is not easy to maintain .


  therefore , We should learn to analyze and conceive code .

1. First , Have to analyze this plc.WriteClass() What types of parameters can be accepted . Its first parameter is object type , Is any kind of data type .( Yes, of course , Any type of this is limited , Because it is plc The method of writing classes provided by the driver , Its arbitrary data type can only be limited to classes ), That is to say, you can pass different classes to it

2. Then we know that it accepts data types , Next, whether to test the design and implementation of the filter interface . Because it stipulates , Only any class type , That is , It can't accept int or string Type . So we define a generic interface to constrain this generic interface type . Implementation of generic interface , Only class objects can be passed in , It can't be anything else .

3. So generic interface implementation , Pass in a obj

4. Then when the interface is called , What to pass on , What is the corresponding generic

  summary : This reduces the amount of code , Easy to maintain .

Let's do it first , Understand the likes collection , In case you can't find it that day .

原网站

版权声明
本文为[Little girl]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/188/202207062142338154.html