当前位置:网站首页>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
PLC | C# |
Bool | Bool |
Word | ushort |
Int | ushort |
Dword | uint32 |
Dint | uint |
byte | byte |
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 .
边栏推荐
- Using thread class and runnable interface to realize the difference between multithreading
- Food Chem | in depth learning accurately predicts food categories and nutritional components based on ingredient statements
- ABAP 动态内表分组循环
- Formation continue en robotique (automatisation) - 2022 -
- How do test / development programmers get promoted? From nothing, from thin to thick
- 如何编写一个程序猿另一个面试官眼前一亮的简历[通俗易懂]
- ERROR: Could not build wheels for pycocotools which use PEP 517 and cannot be installed directly
- True Global Ventures新成立的1.46亿美元后续基金关账,其中普通合伙人认缴6,200万美元以对后期阶段的Web3赢家进行投资
- Redis configuration and optimization of NoSQL
- Create commonly used shortcut icons at the top of the ad interface (menu bar)
猜你喜欢
In cooperation with the research team of the clinical trial center of the University of Hong Kong and Hong Kong Gangyi hospital, Kexing launched the clinical trial of Omicron specific inactivated vacc
【编码字体系列】OpenDyslexic字体
超越Postman,新一代国产调试工具Apifox,用起来够优雅
[team learning] [phase 34] Baidu PaddlePaddle AI talent Creation Camp
[written to the person who first published the paper] common problems in writing comprehensive scientific and Technological Papers
2022 electrician cup question B analysis of emergency materials distribution under 5g network environment
Win11图片打不开怎么办?Win11无法打开图片的修复方法
ABAP 動態內錶分組循環
[team learning] [34 issues] scratch (Level 2)
Quick completion guide of manipulator (10): accessible workspace
随机推荐
Redis source code learning (30), dictionary learning, dict.h
如何编写一个程序猿另一个面试官眼前一亮的简历[通俗易懂]
Analysis on the thinking of college mathematical modeling competition and curriculum education of the 2022a question of the China Youth Cup
buildroot的根文件系统提示“depmod:applt not found”
Pyqt5 out of focus monitoring no operation timer
vim —- 自己主动的按钮indent该命令「建议收藏」
用头像模仿天狗食月
Implementation of binary search tree
【OA】Excel 文档生成器: Openpyxl 模块
Golang compresses and decompresses zip files
ABAP 動態內錶分組循環
Kotlin compose text supports two colors
Leetcode: interview question 17.24 Maximum cumulative sum of submatrix (to be studied)
See Gardenia minor
史上最全MongoDB之初识篇
Antd comment recursive loop comment
Practice Guide for interface automation testing (middle): what are the interface testing scenarios
使用 BR 备份 TiDB 集群到 GCS
Do you choose pandas or SQL for the top 1 of data analysis in your mind?
Restore backup data on GCS with tidb lightning