AMEZING77

View the Project on GitHub AMEZING77/AMEZING77

概述

基于HslCommunication.dll进行西门子S71200的通讯开发,涉及到DB块的读写操作;

开发环境

  1. VS2022
  2. .NET Framework 4.7.0
  3. WPF
  4. HslCommunication.dll 12.0.2

开发内容

涉及点位

alt text alt text

西门子地址的详解

alt text alt text

通讯协议

HslCommunication.Profinet.Siemens.SiemensS7Net plc = new HslCommunication.Profinet.Siemens.SiemensS7Net( HslCommunication.Profinet.Siemens.SiemensPLCS.S1200 );
plc.Rack = 0;
plc.Slot = 0;
plc.CommunicationPipe = new HslCommunication.Core.Pipe.PipeTcpNet("127.0.0.1", 102)
{
    ConnectTimeOut = 5000,    // 连接超时时间,单位毫秒
    ReceiveTimeOut = 10000,    // 接收设备数据反馈的超时时间
    SleepTime = 0,
    SocketKeepAliveTime = -1,
    IsPersistentConnection = true,
};

读写DB块

PLC设置

数据结构体与Byte[]的转换

 private static byte[] StructToBytes<T>(T structObj, out int size)
 {
     size = Marshal.SizeOf(structObj);
     byte[] bytes = new byte[size];
     GCHandle pinnedArray = GCHandle.Alloc(bytes, GCHandleType.Pinned);
     try
     {
         IntPtr pointer = pinnedArray.AddrOfPinnedObject();
         //将结构体拷到分配好的内存空间
         Marshal.StructureToPtr(structObj, pointer, false);
     }
     finally { pinnedArray.Free(); }
     return bytes;
 }

 private static T BytesToStuct<T>(byte[] bytes) where T : struct
 {
     int size = Marshal.SizeOf(typeof(T));
     //byte数组长度小于结构体的大小
     if (size > bytes.Length)
     {
         throw new ArgumentException($"输入的Buffer长度{bytes.Length}小于结构体{typeof(T).Name}的大小");
     }
     GCHandle pinnedArray = GCHandle.Alloc(bytes, GCHandleType.Pinned);
     try
     {
         IntPtr pointer = pinnedArray.AddrOfPinnedObject();
         //将内存空间转换为目标结构体
         return Marshal.PtrToStructure<T>(pointer);
     }
     finally { pinnedArray.Free(); }
 }

单Byte转换8位读取为Bool[]

alt text