SiemensS7Communication.cs 15.2 KB
using DataAcquisition.Common.Enums;
using DataAcquisition.Common.Utils;
using DataAcquisition.Models;
using HslCommunication;
using HslCommunication.Core;
using HslCommunication.Profinet.Siemens;
using System.Diagnostics;
using System.Text;
using System.Text.RegularExpressions;

namespace DataAcquisition.Common.Communications
{
    /// <summary>
    /// 西门子通信
    /// </summary>
    public class SiemensS7Communication : ICommunication
    {
        public readonly SiemensS7Net Siemens = null!;
        private readonly SystemLog systemLog = SystemLog.Instance;
        private readonly ReverseBytesTransform reverseBytesTransform = new();

        public string IpAddress => Siemens.IpAddress;

        public int CommunicationId { get; set; }

        private SiemensS7Communication() { }

        public SiemensS7Communication(int communicationId, SiemensPLCS siemens, string ipAddress) : this()
        {
            CommunicationId = communicationId;
            Siemens = new SiemensS7Net(siemens, ipAddress);
            Siemens.SetPersistentConnection();
        }

        public OperateResult ConnectServer() => Siemens.ConnectServer();

        public OperateResult ConnectClose() => Siemens.ConnectClose();

        public void Read(IEnumerable<EquipmentProperty> equipmentProperties)
        {
            try
            {
                var stopwatch = Stopwatch.StartNew();
                //DB地址批量读取
                if (equipmentProperties.All(x => x.DataAddress.StartsWith("DB", StringComparison.OrdinalIgnoreCase)))
                {
                    var regex = new Regex("[0-9]+");
                    foreach (var item in equipmentProperties.GroupBy(x => x.DataAddress.Split('.').First()))
                    {
                        var amountItems = item.Select(x => Convert.ToInt32(regex.Match(x.DataAddress.Split('.')[1]).Value));
                        var amountStart = amountItems.Min();
                        var amountEnd = amountItems.Max();

                        var lastItemDataType = item.MaxBy(x => Convert.ToInt32(regex.Match(x.DataAddress.Split('.')[1]).Value))!.DataType;
                        //最后一个地址占用的Byte数量,Word类型需要加2,Real需要加4
                        var lastByteAmount = lastItemDataType switch
                        {
                            DataTypeConst.Bool => 1,
                            DataTypeConst.UInt32 => 4,
                            DataTypeConst.UInt16 => 2,
                            DataTypeConst.Int16 => 2,
                            DataTypeConst.Int32 => 4,
                            //DataTypeConst.String => throw new NotImplementedException(),
                            DataTypeConst.Real => 4,
                            _ => 1
                        };

                        var amount = (ushort)(amountEnd - amountStart + lastByteAmount);
                        var multiReadResult = Siemens.Read($"{item.Key}.{amountStart}", amount);
                        if (!multiReadResult.IsSuccess)
                        {
                            throw new Exception(multiReadResult.Message);
                        }

                        //根据数据类型按byte转换,不同数据类型字节数不同
                        foreach (var prop in item)
                        {
                            _ = int.TryParse(regex.Match(prop.DataAddress.Split('.')[1]).Value, out int currentAmountEnd);
                            _ = int.TryParse(regex.Match(prop.DataAddress.Split('.').Skip(2).FirstOrDefault() ?? "0").Value, out int bitIndex);
                            var index = currentAmountEnd - amountStart;
                            prop.Value = prop.DataType switch
                            {
                                DataTypeConst.Byte => reverseBytesTransform.TransInt32(multiReadResult.Content, index).ToString(),
                                DataTypeConst.Bool => Convert.ToBoolean(multiReadResult.Content[index] & (1 << bitIndex)).ToString(),
                                DataTypeConst.UInt32 => reverseBytesTransform.TransUInt32(multiReadResult.Content, index).ToString(),
                                DataTypeConst.UInt16 => reverseBytesTransform.TransUInt16(multiReadResult.Content, index).ToString(),
                                DataTypeConst.Int16 => reverseBytesTransform.TransInt16(multiReadResult.Content, index).ToString(),
                                DataTypeConst.Int32 => reverseBytesTransform.TransInt32(multiReadResult.Content, index).ToString(),
                                //DataTypeConst.String => reverseBytesTransform.TransString(multiReadResult.Content, index, prop.Length, Encoding.ASCII).Replace("\u0003", "").Trim(),
                                DataTypeConst.Real => reverseBytesTransform.TransSingle(multiReadResult.Content, index).ToString(),
                                _ => string.Empty
                            };
                            prop.UpdateTime = DateTime.Now;
                        }
                    }
                }
                else
                {
                    foreach (var item in equipmentProperties)
                    {
                        switch (item.DataType)
                        {
                            case DataTypeConst.Bool:
                                var boolDataResult = Siemens.ReadBool(item.DataAddress);
                                if (!boolDataResult.IsSuccess)
                                {
                                    systemLog.LogError($"读取PLC[{Siemens.IpAddress}]地址{item.DataAddress}出现异常:{boolDataResult.Message}");
                                    item.Value = string.Empty;
                                    return;
                                }
                                item.Value = boolDataResult.Content.ToString();
                                break;
                            case DataTypeConst.Byte:
                                var byteDataResult = Siemens.ReadByte(item.DataAddress);
                                if (!byteDataResult.IsSuccess)
                                {
                                    systemLog.LogError($"读取PLC[{Siemens.IpAddress}]地址{item.DataAddress}出现异常:{byteDataResult.Message}");
                                    item.Value = string.Empty;
                                    return;
                                }
                                item.Value = byteDataResult.Content.ToString();
                                break;
                            case DataTypeConst.Int16:
                                var shortDataResult = Siemens.ReadInt16(item.DataAddress);
                                if (!shortDataResult.IsSuccess)
                                {
                                    systemLog.LogError($"读取PLC[{Siemens.IpAddress}]地址{item.DataAddress}出现异常:{shortDataResult.Message}");
                                    item.Value = string.Empty;
                                    return;
                                }
                                item.Value = shortDataResult.Content.ToString();
                                break;
                            case DataTypeConst.UInt16:
                                var ushortDataResult = Siemens.ReadUInt16(item.DataAddress);
                                if (!ushortDataResult.IsSuccess)
                                {
                                    systemLog.LogError($"读取PLC[{Siemens.IpAddress}]地址{item.DataAddress}出现异常:{ushortDataResult.Message}");
                                    item.Value = string.Empty;
                                    return;
                                }
                                item.Value = ushortDataResult.Content.ToString();
                                break;
                            case DataTypeConst.Int32:
                                var intDataResult = Siemens.ReadInt32(item.DataAddress);
                                if (!intDataResult.IsSuccess)
                                {
                                    systemLog.LogError($"读取PLC[{Siemens.IpAddress}]地址{item.DataAddress}出现异常:{intDataResult.Message}");
                                    item.Value = string.Empty;
                                    return;
                                }
                                item.Value = intDataResult.Content.ToString();
                                break;
                            case DataTypeConst.UInt32:
                                var uintDataResult = Siemens.ReadUInt32(item.DataAddress);
                                if (!uintDataResult.IsSuccess)
                                {
                                    systemLog.LogError($"读取PLC[{Siemens.IpAddress}]地址{item.DataAddress}出现异常:{uintDataResult.Message}");
                                    item.Value = string.Empty;
                                    return;
                                }
                                item.Value = uintDataResult.Content.ToString();
                                break;
                            case DataTypeConst.Int64:
                                var longDataResult = Siemens.ReadInt64(item.DataAddress);
                                if (!longDataResult.IsSuccess)
                                {
                                    systemLog.LogError($"读取PLC[{Siemens.IpAddress}]地址{item.DataAddress}出现异常:{longDataResult.Message}");
                                    item.Value = string.Empty;
                                    return;
                                }
                                item.Value = longDataResult.Content.ToString();
                                break;
                            case DataTypeConst.UInt64:
                                var ulongDataResult = Siemens.ReadUInt64(item.DataAddress);
                                if (!ulongDataResult.IsSuccess)
                                {
                                    systemLog.LogError($"读取PLC[{Siemens.IpAddress}]地址{item.DataAddress}出现异常:{ulongDataResult.Message}");
                                    item.Value = string.Empty;
                                    return;
                                }
                                item.Value = string.Empty;
                                break;
                            case DataTypeConst.Real:
                                var floatDataResult = Siemens.ReadFloat(item.DataAddress);
                                if (!floatDataResult.IsSuccess)
                                {
                                    systemLog.LogError($"读取PLC[{Siemens.IpAddress}]地址{item.DataAddress}出现异常:{floatDataResult.Message}");
                                    item.Value = string.Empty;
                                    return;
                                }
                                item.Value = floatDataResult.Content.ToString();
                                break;
                            //case "double":
                            //    var doubleDataResult = Siemens.ReadDouble(item.DataAddress);
                            //    if (!doubleDataResult.IsSuccess)
                            //    {
                            //        item.Value = string.Empty;
                            //        systemLog.LogError($"读取PLC[{Siemens.IpAddress}]地址{item.DataAddress}出现异常:{doubleDataResult.Message}");
                            //        return;
                            //    }
                            //    item.Value = doubleDataResult.Content.ToString();
                            //    break;
                            case DataTypeConst.String:
                                var stringDataResult = Siemens.ReadString(item.DataAddress);
                                if (!stringDataResult.IsSuccess)
                                {
                                    item.Value = string.Empty;
                                    systemLog.LogError($"读取PLC[{Siemens.IpAddress}]地址{item.DataAddress}出现异常:{stringDataResult.Message}");
                                    return;
                                }
                                item.Value = stringDataResult.Content.ToString();
                                break;
                            default:
                                systemLog.LogError($"读取PLC[{Siemens.IpAddress}]地址{item.DataAddress}失败:不支持“{item.DataType}”数据类型");
                                return;
                        }
                        item.UpdateTime = DateTime.Now;
                    }
                }
                stopwatch.Stop();
                systemLog.LogInfo($"读取PLC[{equipmentProperties.FirstOrDefault()?.Equipment.CommunicationConfig?.IpAddress}]地址数量:{equipmentProperties.Count()},耗时:{stopwatch.Elapsed}");
            }
            catch (Exception ex)
            {
                systemLog.LogError($"读取PLC[{Siemens.IpAddress}]数据出现异常:{ex.Message}");
            }
        }

        public void Read(EquipmentProperty equipmentProperty)
        {
            Read([equipmentProperty]);
        }

        public void Write(IEnumerable<EquipmentProperty> equipmentProperties)
        {
            try
            {
                var result = new OperateResult();
                var stopwatch = Stopwatch.StartNew();
                foreach (var item in equipmentProperties)
                {
                    if (item.DataType == DataTypeConst.Bool)
                    {
                        _ = bool.TryParse(item.Value, out bool val);
                        result = Siemens.Write(item.DataAddress, val);
                    }
                    else if (item.DataType == DataTypeConst.Int16)
                    {
                        _ = ushort.TryParse(item.Value, out ushort val);
                        result = Siemens.Write(item.DataAddress, val);
                    }
                    else if (item.DataType == DataTypeConst.Real)
                    {
                        _ = float.TryParse(item.Value, out var val);
                        result = Siemens.Write(item.DataAddress, val);
                    }
                    else
                    {
                        var bytes = Encoding.Default.GetBytes(item.Value ?? string.Empty);
                        result = Siemens.Write(item.DataAddress, bytes);
                    }
                    if (!result.IsSuccess)
                    {
                        systemLog.LogError($"写入PLC[{Siemens.IpAddress}]_{item.DataAddress}地址数据失败:{result.Message}");
                        return;
                    }
                }
                stopwatch.Stop();
                systemLog.LogSuccess($"写入PLC[{Siemens.IpAddress}]地址数据成功,数量{equipmentProperties.Count()},耗时:{stopwatch.Elapsed}");
            }
            catch (Exception ex)
            {
                systemLog.LogError($"写入PLC[{Siemens.IpAddress}]数据出现异常:{ex.Message}");
            }
        }

        public void Write(EquipmentProperty equipmentProperty)
        {
            Write([equipmentProperty]);
        }
    }
}