当前位置:网站首页>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 .
边栏推荐
- EasyCVR集群版本添加RTSP设备提示服务器ID错误,该如何解决?
- PHP 实现根据概率抽奖
- 学习使用js把两个对象合并成一个对象的方法Object.assign()
- EasyUI export excel cannot download the method that the box pops up
- [ArcGIS tutorial] thematic map production - population density distribution map - population density analysis
- Mysql-数据丢失,分析binlog日志文件
- Hongmi K40S root gameplay notes
- 英特尔David Tuhy:英特尔傲腾技术成功的原因
- leetcode 53. Maximum Subarray 最大子数组和(中等)
- NFT meta universe chain diversified ecosystem development case
猜你喜欢
Optimization of channel status offline of other server devices caused by easycvr cluster restart
EasyCVR集群重启导致其他服务器设备通道状态离线情况的优化
Win11图片打不开怎么办?Win11无法打开图片的修复方法
[team learning] [34 issues] scratch (Level 2)
cuda编程
MySQL data loss, analyze binlog log file
[on automation experience] the growth path of automated testing
ABAP Dynamic Inner table Group cycle
SSM+JSP实现企业管理系统(OA管理系统源码+数据库+文档+PPT)
C#使用西门子S7 协议读写PLC DB块
随机推荐
ABAP 動態內錶分組循環
Win11图片打不开怎么办?Win11无法打开图片的修复方法
POJ training plan 2253_ Frogger (shortest /floyd)
Win11控制面板快捷键 Win11打开控制面板的多种方法
数学分析_笔记_第10章:含参变量积分
Dab-detr: dynamic anchor boxes are better queries for Detr translation
使用 Dumpling 备份 TiDB 集群数据到 GCS
ERROR: Could not build wheels for pycocotools which use PEP 517 and cannot be installed directly
接口自动化测试实践指导(中):接口测试场景有哪些
史上最全MongoDB之部署篇
【自动化经验谈】自动化测试成长之路
2022中青杯C题城市交通思路分析
EasyCVR视频广场点击播放时,主菜单高亮效果消失问题的修复
SSM+jsp实现仓库管理系统,界面那叫一个优雅
学习使用js把两个对象合并成一个对象的方法Object.assign()
史上最全MongoDB之安全认证
1.19.11. SQL client, start SQL client, execute SQL query, environment configuration file, restart policy, user-defined functions, constructor parameters
Ssm+jsp realizes the warehouse management system, and the interface is called an elegant interface
Simple implementation of AVL tree insertion and verification operations
ABAP 动态内表分组循环