hutongqing
2024-11-20 70233af5426b0d1c343ebe87183303a34a9aaa58
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
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
using HslCommunication.Core;
using HslCommunication.LogNet;
using HslCommunication.Profinet.Omron;
using HslCommunication;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Net.NetworkInformation;
using System.Net;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.ComponentModel;
using HslCommunication.Profinet.AllenBradley;
 
namespace WIDESEAWCS_Communicator
{
    /// <summary>
    /// 罗克韦尔(AB)EtherNet/IP(CIP)
    /// </summary>
    [Description("罗克韦尔(AB)EtherNet/IP(CIP)")]
    public class AllenBrandlyEtherNetCommunicator : BaseCommunicator
    {
        #region Private Member
        /// <summary>
        /// HSLCommunication的西门子的S7协议的通讯类
        /// </summary>
        private AllenBradleyNet plc;
 
        /// <summary>
        /// 设备的IP地址。
        /// </summary>
        private string _ipAddress;
 
        /// <summary>
        /// 连接使用的端口号。
        /// </summary>
        private int _port;
 
        /// <summary>
        /// 当前通讯器是否已连接到PLC。  
        /// </summary>
        private bool _connected;
 
        /// <summary>
        /// PLC名称
        /// </summary>
        private string _name;
 
        private ILogNet _logNet;
 
        private bool _isPing = true;
        #endregion Private Member
 
        #region Public Member
        public override ILogNet LogNet => _logNet;
 
        public override string Name => _name;
 
        public override bool IsConnected => _connected;
 
        #endregion Public Member
 
        #region Constructor Function
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="ipAddress">设备的IP地址</param>
        /// <param name="port">连接使用的端口号</param>
        /// <param name="name">设备名称</param>
        public AllenBrandlyEtherNetCommunicator(string ipAddress, int port, string name)
        {
            string path = AppDomain.CurrentDomain.BaseDirectory + $"Log_PLCReadWrite\\{name}";
            _logNet = new LogNetFileSize(path, 10 * 1024 * 1024, 100);
 
            bool ipCheck = IPAddress.TryParse(ipAddress, out IPAddress? address);
            if (!ipCheck)
            {
                _logNet.WriteError(name, string.Format(CommunicationExceptionMessage.IpAddressErrorException, ipAddress));
                throw new CommunicationException(string.Format(CommunicationExceptionMessage.IpAddressErrorException, ipAddress), CommunicationErrorType.IpAddressError);
            }
 
            _ipAddress = ipAddress;//通过构造函数赋值设备的IP地址
            _port = port;//通过构造函数赋值连接使用的端口号
            _name = name;
        }
        #endregion
 
        #region Private Method
        /// <summary>
        /// 从OperateResult对象中获取读取的数据。
        /// </summary>
        /// <typeparam name="T">读取的数据类型。</typeparam>
        /// <param name="operateResult">HSLCommunication读取的OperateResult<T>对象</param>
        /// <returns>如果读取成功,返回读取结果,读取失败,抛出自定义通讯异常</returns>
        /// <exception cref="CommunicationException">自定义通讯异常类</exception>
        private object GetContent<T>(OperateResult<T> operateResult, string address)
        {
            try
            {
                if (!operateResult.IsSuccess)
                {
                    throw new CommunicationException(string.Format(CommunicationExceptionMessage.ReadFailedException, typeof(T).Name, address, operateResult.Message), CommunicationErrorType.ReadFailed);
                }
                return operateResult.Content ?? throw new CommunicationException(string.Format(CommunicationExceptionMessage.ReadDataIsNull, address), CommunicationErrorType.ReadFailed);
            }
            catch (Exception ex)
            {
                LogNet.WriteException(Name, ex.Message, ex);
                throw new CommunicationException(ex.Message, CommunicationErrorType.ReadFailed, innerException: ex);
            }
        }
 
        /// <summary>
        /// 
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="operateResult"></param>
        /// <param name="address"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        /// <exception cref="CommunicationException"></exception>
        private bool GetResult<T>(OperateResult operateResult, string address, T value) where T : notnull
        {
            StringBuilder stringBuilder = new StringBuilder();
            try
            {
                stringBuilder.AppendLine(string.Format(CommunicationInfoMessage.WriteData, address, value));
                if (!operateResult.IsSuccess)
                {
                    throw new CommunicationException(string.Format(CommunicationExceptionMessage.WriteFailedException, typeof(T).Name, address, value, operateResult.Message), CommunicationErrorType.WriteFailed);
                }
                else
                {
                    object? obj = null;
                    for (int i = 0; i < 5; i++)
                    {
                        T readValue = Read<T>(address);
                        stringBuilder.AppendLine(string.Format(CommunicationInfoMessage.WriteAfterRead, readValue, value));
                        obj = readValue;
                        if (readValue.Equals(value))
                        {
                            stringBuilder.AppendLine(string.Format(CommunicationInfoMessage.WriteAndReadCheckSuccess, address, value, readValue));
                            return true;
                        }
                        else if (i < 4)
                        {
                            Write(address, value);
                        }
                    }
                    stringBuilder.AppendLine(string.Format(CommunicationExceptionMessage.WriteAndReadCheckFaild, address, value, obj));
                    throw new CommunicationException(stringBuilder.ToString(), CommunicationErrorType.WriteFailed);
                }
            }
            catch (Exception ex)
            {
                LogNet.WriteException(Name, ex.Message, ex);
                throw new CommunicationException(ex.Message, CommunicationErrorType.WriteFailed, innerException: ex);
            }
            finally
            {
                LogNet.WriteInfo(Name, stringBuilder.ToString());
            }
 
        }
 
        /// <summary>
        /// 写入数据
        /// </summary>
        /// <param name="address"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        /// <exception cref="CommunicationException"></exception>
        private OperateResult Write(string address, object value)
        {
            try
            {
                Type type = value.GetType();
 
                switch (Type.GetTypeCode(type))
                {
                    case TypeCode.Int32:
                        return plc.Write(address, Convert.ToInt32(value));
                    case TypeCode.UInt32:
                        return plc.Write(address, Convert.ToUInt32(value));
                    case TypeCode.Int16:
                        return plc.Write(address, Convert.ToInt16(value));
                    case TypeCode.UInt16:
                        return plc.Write(address, Convert.ToUInt16(value));
                    case TypeCode.Single:
                        return plc.Write(address, Convert.ToSingle(value));
                    case TypeCode.Boolean:
                        return plc.Write(address, Convert.ToBoolean(value));
                    case TypeCode.Byte:
                        return plc.Write(address, Convert.ToByte(value));
                    case TypeCode.String:
                        return plc.Write(address, Convert.ToString(value));
                    case TypeCode.Char:
                        return plc.Write(address, Convert.ToChar(value));
                    default:
                        throw new CommunicationException(string.Format(CommunicationExceptionMessage.DataTypeErrorException, type.Name, address), CommunicationErrorType.TypeError);
                }
            }
            catch (CommunicationException ex)
            {
                throw new CommunicationException(ex.Message, ex.ErrorType);
            }
            catch (Exception ex)
            {
                //读取异常时抛出自定义通讯异常类
                throw new CommunicationException(string.Format(CommunicationExceptionMessage.DataTypeErrorException, address, value), CommunicationErrorType.TypeError, innerException: ex);
            }
        }
 
        private object Read(string address, TypeCode typeCode)
        {
            try
            {
                switch (typeCode)
                {
                    case TypeCode.Int32:
                        return (int)GetContent(plc.ReadInt32(address), address);
                    case TypeCode.UInt32:
                        return (uint)GetContent(plc.ReadUInt32(address), address);
                    case TypeCode.Int16:
                        return (short)GetContent(plc.ReadInt16(address), address);
                    case TypeCode.UInt16:
                        return (ushort)GetContent(plc.ReadUInt16(address), address);
                    case TypeCode.Single:
                        return (float)GetContent(plc.ReadFloat(address), address);
                    case TypeCode.Boolean:
                        return (bool)GetContent(plc.ReadBool(address), address);
                    case TypeCode.Byte:
                        return (byte)GetContent(plc.ReadByte(address), address);
                    case TypeCode.String:
                        return (string)GetContent(plc.ReadString(address), address);
                    case TypeCode.Char:
                        return (char)GetContent(plc.ReadByte(address), address);
                    default:
                        throw new CommunicationException(string.Format(CommunicationExceptionMessage.DataTypeErrorException, typeCode.ToString(), address), CommunicationErrorType.TypeError);
                }
            }
            catch (CommunicationException ex)
            {
                //读取异常时抛出自定义通讯异常类
                throw new CommunicationException(ex.Message, ex.ErrorType);
            }
            catch (Exception ex)
            {
                //读取异常时抛出自定义通讯异常类
                throw new CommunicationException($"读取数据异常,错误信息:{ex.Message}", CommunicationErrorType.ReadException, innerException: ex);
            }
        }
 
        private void Ping()
        {
            Task.Run(() =>
            {
                while (_isPing)
                {
                    try
                    {
                        IPStatus status = plc.IpAddressPing();
                        if (status == IPStatus.Success)
                            _connected = true;
                        else
                            _connected = false;
                    }
                    finally
                    {
                        Thread.Sleep(100);
                    }
                }
            });
 
        }
        #endregion
 
        #region Public Method
        public override bool Connect()
        {
            try
            {
                //实例化一个西门子的S7协议的通讯对象
                plc = new AllenBradleyNet()
                {
                    IpAddress = _ipAddress,
                    Port = _port,
                    Slot = 0
                };
                OperateResult operateResult = plc.ConnectServer();//连接PLC
                _connected = operateResult.IsSuccess;//将连接是否成功赋值给当前通讯器是否已连接到PLC
 
                if (_connected)
                    LogNet.WriteInfo(Name, string.Format(CommunicationInfoMessage.ConnectSuccess, _ipAddress, _port));
                else
                    LogNet.WriteError(Name, string.Format(CommunicationExceptionMessage.ConnectFaild, _ipAddress, _port, operateResult.Message));
                Ping();
                return operateResult.IsSuccess;
            }
            catch (Exception ex)
            {
                LogNet.WriteException(Name, string.Format(CommunicationExceptionMessage.ConnectFaild, _ipAddress, _port, ex.Message), ex);
                //连接异常时抛出自定义异常类
                throw new CommunicationException(ex.Message, CommunicationErrorType.ConnectionFailed, innerException: ex);
            }
        }
 
        public override bool Disconnect()
        {
            try
            {
                if (plc != null)
                {
                    OperateResult operateResult = plc.ConnectClose();//断开与PLC的连接
                    return operateResult.IsSuccess;
                }
                return false;
            }
            catch (Exception ex)
            {
                return false;
            }
            finally
            {
                _connected = false;
            }
        }
 
        public override void Dispose()
        {
            _isPing = false;
            Disconnect();
            plc.Dispose();
            GC.SuppressFinalize(this);
        }
 
        public override byte[] Read(string address, int length)
        {
            return (byte[])GetContent(plc.Read(address, (ushort)length), address);
        }
 
        public override T Read<T>(string address)
        {
            Type type = typeof(T);
            return (T)Read(address, Type.GetTypeCode(type));
        }
 
        public override object ReadAsObj(string address, string dataType)
        {
            return Read(address, SiemensDBDataType.GetTypeCode(dataType));
        }
 
        public override T ReadCustomer<T>(string address)
        {
            try
            {
                return plc.ReadCustomer<T>(address).Content;
            }
            catch (Exception ex)
            {
                LogNet.WriteException(Name, $"【{Name}】PLC读取异常,地址:【{address}】,错误信息:【{ex.Message}】", ex);
                throw new CommunicationException(ex.Message, CommunicationErrorType.ReadException, innerException: ex);
            }
        }
 
        public override OperateResult<TimeSpan> Wait<T>(string address, int readInterval, int waitTimeout, T value)
        {
            TypeCode typeCode = Type.GetTypeCode(typeof(T));
            switch (typeCode)
            {
                case TypeCode.Byte:
                    DateTime start = DateTime.Now;
                    while (true)
                    {
                        OperateResult<byte> read = plc.ReadByte(address);
                        if (!read.IsSuccess) return OperateResult.CreateFailedResult<TimeSpan>(read);
 
                        if (read.Content == Convert.ToByte(value)) return OperateResult.CreateSuccessResult(DateTime.Now - start);
                        if (waitTimeout > 0 && (DateTime.Now - start).TotalMilliseconds > waitTimeout)
                        {
                            return new OperateResult<TimeSpan>(StringResources.Language.CheckDataTimeout + waitTimeout);
                        }
                        HslHelper.ThreadSleep(readInterval);
                    }
                case TypeCode.Int16:
                    OperateResult<TimeSpan> operateResultShort = plc.Wait(address, Convert.ToInt16(value), readInterval, waitTimeout);
                    return operateResultShort;
                case TypeCode.Int32:
                    OperateResult<TimeSpan> operateResultInt = plc.Wait(address, Convert.ToInt16(value), readInterval, waitTimeout);
                    return operateResultInt;
                case TypeCode.UInt16:
                    OperateResult<TimeSpan> operateResultUShort = plc.Wait(address, Convert.ToInt16(value), readInterval, waitTimeout);
                    return operateResultUShort;
                case TypeCode.UInt32:
                    OperateResult<TimeSpan> operateResultUInt = plc.Wait(address, Convert.ToInt16(value), readInterval, waitTimeout);
                    return operateResultUInt;
                default:
                    throw new NotSupportedException();
            }
        }
 
        public override bool Write(string address, byte[] data)
        {
            try
            {
                OperateResult result = plc.Write(address, data);
                if (result.IsSuccess)
                {
                    return result.IsSuccess;
                }
                else
                {
                    //todo 写入失败
                    return false;
                }
            }
            catch (Exception ex)
            {
                //写入异常时抛出自定义通讯异常类
                throw new CommunicationException($"写入数据异常,地址:【{address}】,错误信息: {ex.Message}", CommunicationErrorType.ReadFailed, innerException: ex);
            }
        }
 
        public override bool Write<T>(string address, T value)
        {
            return GetResult(Write(address, value), address, value);
        }
 
        public override bool WriteCustomer<T>(string address, [NotNull] T value)
        {
            StringBuilder stringBuilder = new StringBuilder();
            try
            {
                OperateResult operateResult = plc.WriteCustomer(address, value);
                stringBuilder.AppendLine(string.Format(CommunicationInfoMessage.WriteData, address, JsonConvert.SerializeObject(value)));
                if (operateResult.IsSuccess)
                {
                    object? obj = null;
                    for (int i = 0; i < 5; i++)
                    {
                        T readValue = ReadCustomer<T>(address);
                        stringBuilder.AppendLine(string.Format(CommunicationInfoMessage.WriteAfterRead, address, JsonConvert.SerializeObject(readValue)));
                        obj = readValue;
                        PropertyInfo[] propertyInfos = typeof(T).GetProperties();
                        for (int j = 0; j < propertyInfos.Length; j++)
                        {
                            object? writeValueItem = propertyInfos[j].GetValue(value);
                            object? readValueItem = propertyInfos[j].GetValue(readValue);
                            if (writeValueItem.Equals(readValueItem))
                            {
                                stringBuilder.AppendLine(string.Format(CommunicationInfoMessage.WriteAndReadCheckSuccess, address, JsonConvert.SerializeObject(value), JsonConvert.SerializeObject(readValue)));
                            }
                            else
                            {
                                break;
                            }
                            if (j == propertyInfos.Length - 1)
                                return true;
                        }
 
                        plc.WriteCustomer(address, value);
                    }
                    stringBuilder.AppendLine(string.Format(CommunicationExceptionMessage.WriteAndReadCheckFaild, address, JsonConvert.SerializeObject(value), JsonConvert.SerializeObject(obj)));
                    throw new CommunicationException(string.Format(CommunicationExceptionMessage.WriteAndReadCheckFaild, address, JsonConvert.SerializeObject(value), JsonConvert.SerializeObject(obj)), CommunicationErrorType.WriteFailed);
                }
                else
                {
                    throw new CommunicationException(string.Format(CommunicationExceptionMessage.WriteFailedException, typeof(T).Name, address, JsonConvert.SerializeObject(value), operateResult.Message), CommunicationErrorType.WriteFailed);
                }
            }
            catch (Exception ex)
            {
                LogNet.WriteException(Name, ex.Message, ex);
                throw new CommunicationException(ex.Message, CommunicationErrorType.WriteFailed, innerException: ex);
            }
            finally
            {
                LogNet.WriteInfo(Name, stringBuilder.ToString());
            }
        }
 
        public override bool WriteObj(string address, string dataType, object value)
        {
            bool obj = false;
            switch (dataType.ToLower())
            {
                case SiemensDBDataType.DataType_DInt:
                    {
                        int writeVal;
                        try
                        {
                            writeVal = Convert.ToInt32(value);
                        }
                        catch (Exception ex)
                        {
                            throw new CommunicationException(string.Format(CommunicationExceptionMessage.TypeConvertError, dataType, address, value, ex.Message), CommunicationErrorType.TypeError, innerException: ex);
                        }
                        obj = GetResult(Write(address, writeVal), address, writeVal);
                    }
                    break;
                case SiemensDBDataType.DataType_DW:
                    {
                        uint writeVal;
                        try
                        {
                            writeVal = Convert.ToUInt32(value);
                        }
                        catch (Exception ex)
                        {
                            throw new CommunicationException(string.Format(CommunicationExceptionMessage.TypeConvertError, dataType, address, value, ex.Message), CommunicationErrorType.TypeError, innerException: ex);
                        }
                        obj = GetResult(Write(address, writeVal), address, writeVal);
                    }
                    break;
                case SiemensDBDataType.DataType_Int:
                    {
                        short writeVal;
                        try
                        {
                            writeVal = Convert.ToInt16(value);
                        }
                        catch (Exception ex)
                        {
                            throw new CommunicationException(string.Format(CommunicationExceptionMessage.TypeConvertError, dataType, address, value, ex.Message), CommunicationErrorType.TypeError, innerException: ex);
                        }
                        obj = GetResult(Write(address, writeVal), address, writeVal);
                    }
                    break;
                case SiemensDBDataType.DataType_W:
                    {
                        ushort writeVal;
                        try
                        {
                            writeVal = Convert.ToUInt16(value);
                        }
                        catch (Exception ex)
                        {
                            throw new CommunicationException(string.Format(CommunicationExceptionMessage.TypeConvertError, dataType, address, value, ex.Message), CommunicationErrorType.TypeError, innerException: ex);
                        }
                        obj = GetResult(Write(address, writeVal), address, writeVal);
                    }
                    break;
                case SiemensDBDataType.DataType_Float:
                    {
                        float writeVal;
                        try
                        {
                            writeVal = Convert.ToSingle(value);
                        }
                        catch (Exception ex)
                        {
                            throw new CommunicationException(string.Format(CommunicationExceptionMessage.TypeConvertError, dataType, address, value, ex.Message), CommunicationErrorType.TypeError, innerException: ex);
                        }
                        obj = GetResult(Write(address, writeVal), address, writeVal);
                    }
                    break;
                case SiemensDBDataType.DataType_Bool:
                    {
                        bool writeVal;
                        try
                        {
                            writeVal = Convert.ToBoolean(value);
                        }
                        catch (Exception ex)
                        {
                            throw new CommunicationException(string.Format(CommunicationExceptionMessage.TypeConvertError, dataType, address, value, ex.Message), CommunicationErrorType.TypeError, innerException: ex);
                        }
                        obj = GetResult(Write(address, writeVal), address, writeVal);
                    }
                    break;
                case SiemensDBDataType.DataType_Byte:
                    {
                        byte writeVal;
                        try
                        {
                            writeVal = Convert.ToByte(value);
                        }
                        catch (Exception ex)
                        {
                            throw new CommunicationException(string.Format(CommunicationExceptionMessage.TypeConvertError, dataType, address, value, ex.Message), CommunicationErrorType.TypeError, innerException: ex);
                        }
                        obj = GetResult(Write(address, writeVal), address, writeVal);
                    }
                    break;
                case SiemensDBDataType.DataType_String:
                    {
                        string writeVal;
                        try
                        {
                            writeVal = value.ToString();
                        }
                        catch (Exception ex)
                        {
                            throw new CommunicationException(string.Format(CommunicationExceptionMessage.TypeConvertError, dataType, address, value, ex.Message), CommunicationErrorType.TypeError, innerException: ex);
                        }
                        obj = GetResult(Write(address, writeVal), address, writeVal);
                    }
 
                    break;
                case SiemensDBDataType.DataType_Char:
 
                    break;
                default:
                    throw new CommunicationException(string.Format(CommunicationExceptionMessage.DataTypeErrorException, dataType, address), CommunicationErrorType.TypeError);
            }
            return obj;
        }
        #endregion
 
        #region Destruction Function
        /// <summary>
        /// 析构函数,确保在不再需要时关闭连接  
        /// </summary>
        ~AllenBrandlyEtherNetCommunicator()
        {
            Dispose();
        }
        #endregion
    }
}