当前位置:网站首页>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 .
边栏推荐
- 【自动化经验谈】自动化测试成长之路
- Continuous learning of Robotics (Automation) - 2022-
- [leetcode]Spiral Matrix II
- 使用 Dumpling 备份 TiDB 集群数据到 GCS
- Antd comment recursive loop comment
- Allow public connections to local Ruby on Rails Development Server
- [system management] clear the icon cache of deleted programs in the taskbar
- Mongo shell, the most complete mongodb in history
- 使用 TiDB Lightning 恢复 GCS 上的备份数据
- Class constant pool and runtime constant pool
猜你喜欢

【OA】Excel 文档生成器: Openpyxl 模块

Analysis on urban transportation ideas of 2022 Zhongqing cup C

【刷题记录】2. 两数相加

Practice Guide for interface automation testing (middle): what are the interface testing scenarios
![[team learning] [phase 34] Baidu PaddlePaddle AI talent Creation Camp](/img/eb/9aed3bbbd5b6ec044ec5542297f3c6.jpg)
[team learning] [phase 34] Baidu PaddlePaddle AI talent Creation Camp

5年自动化测试,终于进字节跳动了,年薪30w其实也并非触不可及

Collection of idea gradle Lombok errors

kivy教程之设置窗体大小和背景(教程含源码)

科兴与香港大学临床试验中心研究团队和香港港怡医院合作,在中国香港启动奥密克戎特异性灭活疫苗加强剂临床试验

Implementation of map and set
随机推荐
2022中青杯C题城市交通思路分析
Quick completion guide of manipulator (10): accessible workspace
[on automation experience] the growth path of automated testing
Video fusion cloud platform easycvr video Plaza left column list style optimization
The most complete deployment of mongodb in history
2022年电工杯B 题 5G 网络环境下应急物资配送问题思路分析
kivy教程之设置窗体大小和背景(教程含源码)
EasyCVR集群重启导致其他服务器设备通道状态离线情况的优化
Antd Comment 递归循环评论
Triple half circle progress bar, you can use it directly
VM virtual machine operating system not found and NTLDR is missing
Use facet to record operation log
UltraEdit-32 warm prompt: right association, cancel bak file [easy to understand]
中青杯2022A题高校数学建模竞赛与课程教育思路分析
vim —- 自己主动的按钮indent该命令「建议收藏」
【ArcGIS教程】专题图制作-人口密度分布图——人口密度分析
[ArcGIS tutorial] thematic map production - population density distribution map - population density analysis
[team learning] [34 sessions] Alibaba cloud Tianchi online programming training camp
Zero knowledge private application platform aleo (1) what is aleo
Ggplot facet detail adjustment summary

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 .



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