SiemensPLC.cs 24.4 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455
using RCS.Model.Comm;
using RCS.Model.Entity;
using RCS.Model.PLC;
using HslCommunication;
using HslCommunication.Core;
using HslCommunication.Profinet.Siemens;
using System.Text;

namespace RCS.Communication
{
    /// <summary>
    /// 西门子PLC处理类
    /// </summary>
    public class SiemensPLC : BasePLC
    {
        /// <summary>
        /// 开启批量读取的限制数目,于此相关的均需要实际测试性能情况。
        /// </summary>
        const int batchInt = 5;

        /// <summary>
        /// 读写锁,因为里面已经是多线程处理了,不许外部再进行多线程调用
        /// </summary>
        private object Lock { get; set; } = new object();

        /// <summary>
        /// 西门子PLC的S7连接
        /// </summary>
        private SiemensS7Net siemensS7Net;

        /// <summary>
        /// 转换类
        /// </summary>
        private ReverseBytesTransform reverseBytesTransform = new ReverseBytesTransform();

        /// <summary>
        /// 初始化西门子S7连接
        /// </summary>
        /// <param name="siemensPLCS">PLC型号</param>
        /// <param name="ip">IP地址</param>
        public SiemensPLC(SiemensPLCS siemensPLCS, string ip)
        {
            IP = ip;
            //siemensS7Net = new SiemensS7Net(siemensPLCS, ip);
            siemensS7Net = new SiemensS7Net(siemensPLCS, ip) { ConnectTimeOut = 1000, ReceiveTimeOut = 1000 };
            siemensS7Net.Port = 102;
        }


        /// <summary>
        /// 占用字节校验
        /// </summary>
        /// <param name="type"></param>
        /// <returns></returns>
        public static bool CheckByteSize(PLCDataType type, int byteSize)
        {
            switch (type)
            {
                case PLCDataType.BYTE:
                case PLCDataType.BOOL:
                    return byteSize == 1;
                case PLCDataType.WORD:
                case PLCDataType.INT:
                    return byteSize == 2;
                case PLCDataType.DWORD:
                case PLCDataType.DINT:
                    return byteSize == 4;
                case PLCDataType.CHAR:
                    return true;
                default:
                    return true;
            }
        }
        #region 类型转换

        /// <summary>
        /// 数据转换,byte[]到string
        /// </summary>
        /// <param name="dataType"></param>
        /// <param name="buffer"></param>
        /// <returns></returns>
        public BllResult<string> TransferBufferToString(byte[] byteBuffer, string dataType, int bitOffset)
        {
            try
            {
                if (!Enum.TryParse(dataType, out PLCDataType plcDataType))
                {
                    return BllResult<string>.Error("未识别的数据类型");
                }
                switch (plcDataType)
                {
                    case PLCDataType.BYTE:
                        //字节转成int处理
                        return BllResult<string>.Success(reverseBytesTransform.TransInt32(byteBuffer, 0).ToString(), null);
                    case PLCDataType.BOOL:
                        //对于bool类型,我们需要判断此字节中的指定位是否为0
                        return BllResult<string>.Success(GetBit(byteBuffer[0], bitOffset) == 1 ? true.ToString() : false.ToString(), null);
                    case PLCDataType.DWORD:
                        return BllResult<string>.Success(reverseBytesTransform.TransUInt32(byteBuffer, 0).ToString(), null);
                    case PLCDataType.WORD:
                        return BllResult<string>.Success(reverseBytesTransform.TransUInt16(byteBuffer, 0).ToString(), null);
                    case PLCDataType.INT:
                        return BllResult<string>.Success(reverseBytesTransform.TransInt16(byteBuffer, 0).ToString(), null);
                    case PLCDataType.DINT:
                        return BllResult<string>.Success(reverseBytesTransform.TransInt32(byteBuffer, 0).ToString(), null);
                    case PLCDataType.CHAR:
                        return BllResult<string>.Success(reverseBytesTransform.TransString(byteBuffer, 0, byteBuffer.Length, Encoding.ASCII).Replace("\u0003", "").Replace("\0", "").Trim(), null);
                    default:
                        return BllResult<string>.Success("未识别");
                }
            }
            catch (Exception ex)
            {
                return BllResult<string>.Error($"方法【TransferBufferToString】数据类型转换出现异常,原因:{ex.Message},堆栈:{ex.StackTrace}");
            }
        }

        /// <summary>
        /// 数据转换,string到byte[]
        /// </summary>
        /// <param name="dataType"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        public BllResult<byte[]> TransferStringToBuffer(PLCDataType dataType, string value, int stringLength)
        {
            try
            {
                switch (dataType)
                {
                    case PLCDataType.BYTE:
                        return BllResult<byte[]>.Success(reverseBytesTransform.TransByte(Convert.ToInt32(value)));
                    case PLCDataType.BOOL:
                        return BllResult<byte[]>.Success(reverseBytesTransform.TransByte(Convert.ToBoolean(value)));
                    case PLCDataType.DWORD:
                        return BllResult<byte[]>.Success(reverseBytesTransform.TransByte(Convert.ToUInt32(value)));
                    case PLCDataType.WORD:
                        return BllResult<byte[]>.Success(reverseBytesTransform.TransByte(Convert.ToUInt16(value)));
                    case PLCDataType.INT:
                        return BllResult<byte[]>.Success(reverseBytesTransform.TransByte(Convert.ToInt16(value)));
                    case PLCDataType.DINT:
                        return BllResult<byte[]>.Success(reverseBytesTransform.TransByte(Convert.ToInt32(value)));
                    case PLCDataType.CHAR:
                        return BllResult<byte[]>.Success(reverseBytesTransform.TransByte(value.PadRight(stringLength, ' '), Encoding.ASCII));
                    case PLCDataType.Real:
                        return BllResult<byte[]>.Success(reverseBytesTransform.TransByte(float.Parse(value)));
                    default:
                        return BllResult<byte[]>.Success("未识别的数据类型");
                }
            }
            catch (Exception ex)
            {
                return BllResult<byte[]>.Error($"方法【TransferStringToBuffer】数据类型转换出现异常,原因:{ex.Message},堆栈:{ex.StackTrace}");
            }
        }

        #endregion

        #region PLC操作
        /// <summary>
        /// 对内部关联的所有PLC进行连接,存在连接失败,则连接失败
        /// </summary>
        /// <returns></returns>
        public override BllResult Connect()
        {
            try
            {
                var result = siemensS7Net.ConnectServer();
                if (!result.IsSuccess)
                {
                    //连接失败,则失败
                    return BllResult.Error($"连接PLC:{siemensS7Net.IpAddress}失败:{result.Message}");
                }
                return BllResult.Success("连接PLC成功");
            }
            catch (Exception ex)
            {
                return BllResult.Error("连接PLC出现异常,IP:" + siemensS7Net.IpAddress + ",原因:" + ex.Message + ",堆栈:" + ex.StackTrace);
            }
        }

        /// <summary>
        /// 断开所有PLC
        /// </summary>
        /// <returns></returns>
        public override BllResult DisConnect()
        {
            try
            {
                //基本不需要查看断开成功与否
                siemensS7Net.ConnectClose();

                return BllResult.Success("断开PLC成功");
            }
            catch (Exception ex)
            {
                return BllResult.Error("断开PLC出现异常,IP:" + siemensS7Net.IpAddress + ",原因:" + ex.Message + ",堆栈:" + ex.StackTrace);
            }
        }

        /// <summary>
        /// 获取连接状态
        /// 由于HSL不支持状态访问,所以这里直接返回成功,需要通过读写函数的返回值判断连接是否断开
        /// </summary>
        /// <returns></returns>
        public override BllResult GetConnectStatus()
        {
            return BllResult.Success();
        }

        /// <summary>
        /// PLC读取方法
        /// </summary>
        /// <param name="equipmentProps"></param>
        /// <returns></returns>
        public override BllResult Reads(List<Base_EquipmentProp> equipmentProps)
        {
            lock (Lock)
            {
                try
                {
                    if (equipmentProps.Count > batchInt)
                    {
                        var addressDic = new Dictionary<string, ushort>();
                        //因为1个字节有7个位,批量读取是按照字节来的,所以bool类型的属性会有大量重复,用addressDic保存不重复的地址,然后去查询PLC数据
                        foreach (var equipmentProp in equipmentProps)
                        {
                            if (!addressDic.ContainsKey(equipmentProp.BatchAddress))
                            {
                                addressDic.Add(equipmentProp.BatchAddress, equipmentProp.ByteSize);
                            }
                        }
                        //按照批量地址读取PLC的值,返回的数据都在一个byte数组中
                        OperateResult<byte[]> operateResult = siemensS7Net.Read(addressDic.Keys.ToArray(), addressDic.Values.ToArray());
                        if (!operateResult.IsSuccess)
                        {
                            return BllResult.Error("读取PLC错误,IP:" + siemensS7Net.IpAddress + ",参考信息:" + operateResult.Message?.Replace(Environment.NewLine, ""));
                        }
                        List<byte> operateContent = operateResult.Content.ToList();
                        //按照每个地址的长度,截取对应的数据转化为字符串,然后再去截取下个地址的值,一直循环整个。
                        foreach (var address in addressDic)
                        {
                            IEnumerable<byte> operateBuffer = operateContent.Take(address.Value);
                            if (operateBuffer.Count() != address.Value)
                            {
                                return BllResult.Error("读取PLC错误,IP:" + siemensS7Net.IpAddress + "获取的字节序列个数与属性需求字节个数不匹配");
                            }
                            var byteBuffer = operateBuffer.ToArray();
                            operateContent = operateContent.Skip(address.Value).ToList();
                            //查询出来的数据,根据地址取匹配设备属性,一个地址可以匹配7个bool量,然后再根据BitOffset取获取值
                            foreach (var equipmentProp in equipmentProps.Where(t => t.BatchAddress == address.Key))
                            {
                                BllResult<string> operateValue = TransferBufferToString(byteBuffer, equipmentProp.DataType, equipmentProp.BitOffset);
                                if (!operateValue.IsSuccess)
                                {
                                    return BllResult.Error("读取PLC错误,IP:" + siemensS7Net.IpAddress + ",地址" + equipmentProp.Address + ",转换数据失败:" + operateValue.Message);
                                }
                                equipmentProp.Value = operateValue.Data;
                            }
                        }

                        #region 旧写法
                        //List<string> address = new List<string>();
                        //List<ushort> length = new List<ushort>();
                        //foreach (var equipmentProp in equipmentProps)
                        //{
                        //    address.Add(equipmentProp.BatchAddress);
                        //    length.Add(equipmentProp.ByteSize);
                        //}
                        //OperateResult<byte[]> operateResult = siemensS7Net.Read(address.ToArray(), length.ToArray());
                        //if (!operateResult.IsSuccess)
                        //{
                        //    return BllResult.Error("读取PLC错误,IP:" + siemensS7Net.IpAddress + ",参考信息:" + operateResult.Message?.Replace(Environment.NewLine, ""));
                        //}
                        //List<byte> operateContent = operateResult.Content.ToList();
                        //foreach (var equipmentProp in equipmentProps)
                        //{
                        //    IEnumerable<byte> operateBuffer = operateContent.Take(equipmentProp.ByteSize);
                        //    if (operateBuffer.Count() != equipmentProp.ByteSize)
                        //    {
                        //        return BllResult.Error("读取PLC错误,IP:" + siemensS7Net.IpAddress + "获取的字节序列个数与属性需求字节个数不匹配");
                        //    }
                        //    equipmentProp.Buffer = operateBuffer.ToArray();
                        //    operateContent = operateContent.Skip(equipmentProp.ByteSize).ToList();
                        //    BllResult<string> operateValue = TransferBufferToString(equipmentProp);
                        //    if (!operateValue.Success)
                        //    {
                        //        return BllResult.Error("读取PLC错误,IP:" + siemensS7Net.IpAddress + ",地址" + equipmentProp.Address + ",转换数据失败:" + operateValue.Msg);
                        //    }
                        //    equipmentProp.Value = operateValue.Data;
                        //}
                        #endregion
                    }
                    else
                    {
                        foreach (var equipmentProp in equipmentProps)
                        {
                            if (!Enum.TryParse(equipmentProp.DataType, out PLCDataType plcDataType))
                            {
                                return BllResult.Error("读取PLC错误,未识别的数据类型");
                            }
                            switch (plcDataType)
                            {
                                case PLCDataType.BYTE:
                                    {
                                        OperateResult<byte> operateResult3 = siemensS7Net.ReadByte(equipmentProp.Address);
                                        if (!operateResult3.IsSuccess)
                                        {
                                            return BllResult.Error("读取PLC错误,IP:" + siemensS7Net.IpAddress + ",地址" + equipmentProp.Address + "发生错误:" + operateResult3.Message?.Replace(Environment.NewLine, ""));
                                        }
                                        equipmentProp.Value = ((int)operateResult3.Content).ToString();
                                        break;
                                    }
                                case PLCDataType.BOOL:
                                    {
                                        OperateResult<bool> operateResult7 = siemensS7Net.ReadBool(equipmentProp.Address);
                                        if (!operateResult7.IsSuccess)
                                        {
                                            return BllResult.Error("读取PLC错误,IP:" + siemensS7Net.IpAddress + ",地址" + equipmentProp.Address + "发生错误:" + operateResult7.Message?.Replace(Environment.NewLine, ""));
                                        }
                                        equipmentProp.Value = operateResult7.Content.ToString();
                                        break;
                                    }
                                case PLCDataType.DWORD:
                                    {
                                        OperateResult<uint> operateResult4 = siemensS7Net.ReadUInt32(equipmentProp.Address);
                                        if (!operateResult4.IsSuccess)
                                        {
                                            return BllResult.Error("读取PLC错误,IP:" + siemensS7Net.IpAddress + ",地址" + equipmentProp.Address + "发生错误:" + operateResult4.Message?.Replace(Environment.NewLine, ""));
                                        }
                                        equipmentProp.Value = operateResult4.Content.ToString();
                                        break;
                                    }
                                case PLCDataType.WORD:
                                    {
                                        OperateResult<ushort> operateResult6 = siemensS7Net.ReadUInt16(equipmentProp.Address);
                                        if (!operateResult6.IsSuccess)
                                        {
                                            return BllResult.Error("读取PLC错误,IP:" + siemensS7Net.IpAddress + ",地址" + equipmentProp.Address + "发生错误:" + operateResult6.Message?.Replace(Environment.NewLine, ""));
                                        }
                                        equipmentProp.Value = operateResult6.Content.ToString();
                                        break;
                                    }
                                case PLCDataType.INT:
                                    {
                                        OperateResult<short> operateResult8 = siemensS7Net.ReadInt16(equipmentProp.Address);
                                        if (!operateResult8.IsSuccess)
                                        {
                                            return BllResult.Error("读取PLC错误,IP:" + siemensS7Net.IpAddress + ",地址" + equipmentProp.Address + "发生错误:" + operateResult8.Message?.Replace(Environment.NewLine, ""));
                                        }
                                        equipmentProp.Value = operateResult8.Content.ToString();
                                        break;
                                    }
                                case PLCDataType.DINT:
                                    {
                                        OperateResult<int> operateResult5 = siemensS7Net.ReadInt32(equipmentProp.Address);
                                        if (!operateResult5.IsSuccess)
                                        {
                                            return BllResult.Error("读取PLC错误,IP:" + siemensS7Net.IpAddress + ",地址" + equipmentProp.Address + "发生错误:" + operateResult5.Message?.Replace(Environment.NewLine, ""));
                                        }
                                        equipmentProp.Value = operateResult5.Content.ToString();
                                        break;
                                    }
                                case PLCDataType.CHAR:
                                    {
                                        OperateResult<string> operateResult2 = siemensS7Net.ReadString(equipmentProp.Address, equipmentProp.ByteSize);
                                        if (!operateResult2.IsSuccess)
                                        {
                                            return BllResult.Error("读取PLC错误,IP:" + siemensS7Net.IpAddress + ",地址" + equipmentProp.Address + "发生错误:" + operateResult2.Message?.Replace(Environment.NewLine, ""));
                                        }
                                        equipmentProp.Value = operateResult2.Content.ToString();
                                        break;
                                    }
                                case PLCDataType.Real:
                                    {
                                        var operateResult6 = siemensS7Net.ReadFloat(equipmentProp.Address);
                                        if (!operateResult6.IsSuccess)
                                        {
                                            return BllResult.Error("读取PLC错误,IP:" + siemensS7Net.IpAddress + ",地址" + equipmentProp.Address + "发生错误:" + operateResult6.Message?.Replace(Environment.NewLine, ""));
                                        }
                                        equipmentProp.Value = operateResult6.Content.ToString();
                                        break;
                                    }
                                default:
                                    return BllResult.Error($"读取PLC错误,未识别的数据类型:{equipmentProp.DataType}");
                            }
                        }
                    }
                    return BllResult.Success();

                }
                catch (Exception ex)
                {
                    return BllResult.Error("读取PLC错误,出现异常,IP:" + siemensS7Net.IpAddress + ",原因:" + ex.Message + ",堆栈:" + ex.StackTrace);
                }
            }
        }

        /// <summary>
        /// PLC写入方法
        /// </summary>
        /// <param name="equipmentProps"></param>
        /// <returns></returns>
        public override BllResult<List<string>> Writes(List<Base_EquipmentProp> equipmentProps)
        {
            lock (Lock)
            {
                List<string> messageList = new List<string>();
                try
                {
                    foreach (var equipmentProp in equipmentProps)
                    {
                        if (!Enum.TryParse(equipmentProp.DataType, out PLCDataType plcDataType))
                        {
                            return BllResult<List<string>>.Error("写入PLC失败,未识别的数据类型");
                        }
                        BllResult<byte[]> bllResult = TransferStringToBuffer(plcDataType, equipmentProp.Value, equipmentProp.ByteSize);
                        if (!bllResult.IsSuccess)
                        {
                            return BllResult<List<string>>.Error("写入PLC失败,转换到PLC数据类型失败,IP:" + siemensS7Net.IpAddress + ",地址:" + equipmentProp.Address + ":" + bllResult.Message);
                        }
                        byte[] data = bllResult.Data;
                        OperateResult operateResult = null;
                        if (equipmentProp.DataType == PLCDataType.BOOL.ToString())
                        {
                            operateResult = siemensS7Net.Write(equipmentProp.Address, bool.Parse(equipmentProp.Value));
                        }
                        else
                        {
                            operateResult = siemensS7Net.Write(equipmentProp.Address, data);
                        }
                        if (!operateResult.IsSuccess)
                        {
                            var message = $"写入PLC【{siemensS7Net.IpAddress}】失败,失败原因:【{operateResult.Message?.Replace(Environment.NewLine, "")}】,设备:【{equipmentProp.Equipment.Name}】";
                            messageList.Add(message + $",设备属性:【{ equipmentProp.Code}】【{ equipmentProp.Name}】,地址:【{ equipmentProp.Address}】,数据:【{ equipmentProp.Value}】");
                            return BllResult<List<string>>.Error(messageList, message);
                        }
                        else if (equipmentProp.Code != EnumPLC.RCSHuaHengProps.RCSHeart.ToString())
                        {
                            messageList.Add($"写入PLC【{siemensS7Net.IpAddress}】成功,设备:【{equipmentProp.Equipment.Name}】,设备属性:【{equipmentProp.Code}】【{equipmentProp.Name}】,地址:【{equipmentProp.Address}】,数据:【{equipmentProp.Value}】");
                        }
                    }
                    return BllResult<List<string>>.Success(messageList, "写入PLC成功!");
                }
                catch (Exception ex)
                {
                    var message = $"写入PLC【{siemensS7Net.IpAddress}】失败,异常原因:{ex.Message}";
                    messageList.Add(message + ",堆栈:" + ex.StackTrace);
                    return BllResult<List<string>>.Error(messageList, message);
                }
            }
        }

        #endregion
    }
}