wenxiangchao
3 天以前 b544d5cccd76735e034c8055918a50927b437474
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
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
using ConnectionUtil;
using LT.Utils.Json;
using Newtonsoft.Json;
using SuperSocketServer.Common;
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
 
namespace OPCConnection
{
    public class OPCClient : SCADAApi
    {
        private Socket ClientSocket = null;
 
        /// <summary>
        /// 连接超时事件ms
        /// </summary>
        public int _ConnectTimeout = 20000;
        private int Size = 0x989680;
        private Dictionary<int, string> paraMPairs = new Dictionary<int, string>();
 
 
        /// <summary>
        /// IP连接Scada服务器
        /// </summary>
        /// <param name="IP">MES服务器IP</param>
        /// <param name="Port"> MES服务器Port口</param>
        /// <param name="LocalIP">本地连接IP</param>
        /// <param name="LocalPort">本地连接端口</param>
        /// <returns></returns>
        public bool Connect(string IP, int Port, string LocalIP, int LocalPort)
        {
            try
            {
                this.ClientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                IPAddress address = IPAddress.Parse(IP);
                IPEndPoint point = new IPEndPoint(IPAddress.Parse(LocalIP), LocalPort);
                IPEndPoint remoteEP = new IPEndPoint(address, Port);
                this.ClientSocket.Connect(remoteEP);
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }
 
        /// <summary>
        /// 连接Scada管理服务器
        /// </summary>
        /// <param name="IP"> Scada服务器IP</param>
        /// <param name="Port">ScadPort口</param>
        /// <param name="LocalPort">本地连接端口</param>
        /// <param name="errMsg"></param>
        /// <param name="socket"></param>
        /// <returns></returns>
        public bool Connect2(string IP, int Port, int LocalPort, out string errMsg, Socket socket = null)
        {
            try
            {
                errMsg = string.Empty;
                if (!this.TcpPing(IP, Port, out errMsg))
                {
                    throw new Exception(errMsg);
                }
                if (socket != null)
                {
                    this.ClientSocket = socket;
                }
                else
                {
                    this.ClientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                }
                IPAddress address = IPAddress.Parse(IP);
                this.ClientSocket.Connect(address, Port);
                if (!this.DoLogin("admin", "LT123456", out string str))
                {
                    throw new Exception(str);
                }
                return true;
            }
            catch (Exception exception)
            {
                errMsg = "连接SCADA服务失败:" + exception.Message;
                return false;
            }
        }
 
        /// <summary>
        ///  连接Scada管理服务器
        /// </summary>
        /// <param name="IP">ScadaManagerIP</param>
        /// <param name="Port">ScadaManagerPort口</param>
        /// <param name="LocalPort">本地连接端口</param>
        /// <param name="errMsg"></param>
        /// <returns></returns>
        public bool ConnectManager(string IP, int Port, int LocalPort, out string errMsg)
        {
            try
            {
                errMsg = string.Empty;
                if (!this.TcpPing(IP, Port, out errMsg))
                {
                    throw new Exception(errMsg);
                }
                this.ClientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                IPAddress address = IPAddress.Parse(IP);
                this.ClientSocket.Connect(address, Port);
                return true;
            }
            catch (Exception exception)
            {
                errMsg = "连接SCADA服务失败:" + exception.Message;
                return false;
            }
        }
 
        /// <summary>
        /// 断开服务器连接
        /// </summary>
        public void DisConnect()
        {
            try
            {
                if (this.ClientSocket != null)
                {
                    //this.ClientSocket.Shutdown(SocketShutdown.Both);
                    this.ClientSocket.Close();
                }
            }
            catch (Exception exception)
            {
                throw new Exception("断开SCADA服务器失败:" + exception.Message);
            }
        }
 
        /// <summary>
        /// 释放资源
        /// </summary>
        public void Dispose()
        {
            if (this.ClientSocket != null)
            {
                this.ClientSocket.Dispose();
            }
        }
 
        /// <summary>
        /// 批量写增加参数
        /// </summary>
        /// <param name="id"></param>
        /// <param name="par"></param>
        /// <returns></returns>
        public bool DoAddParWriteMultiple(int id, string par)
        {
            if (this.paraMPairs.ContainsKey(id))
            {
                return false;
            }
            this.paraMPairs.Add(id, par);
            return true;
        }
 
        /// <summary>
        /// 换型
        /// </summary>
        /// <param name="_ProductLineName"></param>
        /// <param name="_ProductName"></param>
        /// <param name="errMsg"></param>
        /// <param name="_WorkStationName"></param>
        /// <returns></returns>
        public bool DoDoChangeModel(string _ProductLineName, string _ProductName, out string errMsg, string _WorkStationName = null)
        {
            try
            {
                var type = new
                {
                    command = 7,
                    ProductLineName = _ProductLineName,
                    ProductName = _ProductName,
                    WorkStationName = _WorkStationName
                };
                string resquestStr = this.SendSocketMessage(JsonExtensions.ToJson(type, false, false, false));
                return this.ResquestResult(resquestStr, out _, out errMsg);
            }
            catch (Exception exception)
            {
                errMsg = exception.Message;
                return false;
            }
        }
 
        /// <summary>
        /// 批量读值
        /// </summary>
        /// <param name="_Id"></param>
        /// <returns></returns>
        public string[,] DoFctReadMultiple(int[] _Id)
        {
            string[,] strArray2;
            try
            {
                var type = new
                {
                    command = 2,
                    comefrom = 1,
                    paraM = _Id
                };
                string resquestStr = this.SendSocketMessage(JsonExtensions.ToJson(type, false, false, false));
                if (this.ResquestResult(resquestStr, out Result result, out _))
                {
                    Dictionary<string, string> dictionary = JsonUtil.ToObject<Dictionary<string, string>>(result.result.ToString());
                    string[,] strArray = new string[dictionary.Count, 2];
                    int num = 0;
                    foreach (KeyValuePair<string, string> pair in dictionary)
                    {
                        strArray[num, 0] = pair.Key;
                        strArray[num, 1] = pair.Value;
                        num++;
                    }
                    return strArray;
                }
                strArray2 = null;
            }
            catch (Exception exception)
            {
                throw new Exception(exception.Message);
            }
            return strArray2;
        }
 
        /// <summary>
        /// 单一读值
        /// </summary>
        /// <param name="_name"></param>
        /// <param name="result"></param>
        /// <param name="errMsg"></param>
        /// <returns></returns>
        public bool DoFctReadSingle(string _name, out string result, out string errMsg)
        {
            result = string.Empty;
            try
            {
                var type = new
                {
                    command = 0x31,
                    id = _name,
                    comefrom = 1
                };
                string resquestStr = this.SendSocketMessage(JsonExtensions.ToJson(type, false, false, false));
                if (this.ResquestResult(resquestStr, out Result result2, out errMsg))
                {
                    result = result2.result?.ToString();
                    return true;
                }
                return false;
            }
            catch (Exception exception)
            {
                errMsg = exception.Message;
                return false;
            }
            finally
            {
                GC.Collect();
            }
        }
 
        /// <summary>
        /// 单一写值
        /// </summary>
        /// <param name="errMsg"></param>
        /// <returns></returns>
        public bool DoFctWriteMultiple(out string errMsg)
        {
            bool flag2;
            errMsg = string.Empty;
            try
            {
                if (this.ToFctWriteMultiple(this.paraMPairs, out errMsg))
                {
                    return true;
                }
                flag2 = false;
            }
            catch (Exception exception)
            {
                errMsg = exception.Message;
                flag2 = false;
            }
            finally
            {
                this.InitParWriteMultiple();
            }
            return flag2;
        }
 
        /// <summary>
        /// 写单一值
        /// </summary>
        /// <param name="_name"></param>
        /// <param name="_value"></param>
        /// <param name="errMsg"></param>
        /// <returns></returns>
        public bool DoFctWriteSingle(string _name, string _value, out string errMsg)
        {
            try
            {
                var type = new
                {
                    command = 5,
                    id = _name,
                    value = _value
                };
                string resquestStr = this.SendSocketMessage(JsonExtensions.ToJson(type, false, false, false));
                return this.ResquestResult(resquestStr, out _, out errMsg);
            }
            catch (Exception exception)
            {
                errMsg = exception.Message;
                return false;
            }
        }
 
        /// <summary>
        /// mqtt发布消息
        /// </summary>
        /// <param name="topic">主题</param>
        /// <param name="_value">值</param>
        /// <param name="errMsg">错误信息></param>
        /// <returns></returns>
        public bool DoMqttPublish(string topic, string _value, out string errMsg)
        {
            try
            {
                var type = new
                {
                    command = 12,
                    Tag = topic,
                    value = _value
                };
                string resquestStr = this.SendSocketMessage(JsonExtensions.ToJson(type, false, false, false));
                return this.ResquestResult(resquestStr, out _, out errMsg);
            }
            catch (Exception exception)
            {
                errMsg = exception.Message;
                return false;
            }
        }
 
        /// <summary>
        /// 
        /// </summary>
        /// <param name="_user"></param>
        /// <param name="_password"></param>
        /// <param name="errMsg"></param>
        /// <returns></returns>
        public bool DoLogin(string _user, string _password, out string errMsg)
        {
            try
            {
                var type = new
                {
                    command = 11,
                    user = _user,
                    password = _password
                };
                string resquestStr = this.SendSocketMessage(JsonExtensions.ToJson(type, false, false, false));
                return this.ResquestResult(resquestStr, out _, out errMsg);
            }
            catch (Exception exception)
            {
                errMsg = exception.Message;
                return false;
            }
        }
 
        /// <summary>
        /// 重启DataServer服务器
        /// </summary>
        /// <param name="errMsg"></param>
        /// <returns></returns>
        public bool DoReSETDataServer(out string errMsg)
        {
            try
            {
                var type = new
                {
                    command = 10
                };
                string resquestStr = this.SendSocketMessage(JsonExtensions.ToJson(type, false, false, false));
                return this.ResquestResult(resquestStr, out _, out errMsg);
            }
            catch (Exception exception)
            {
                errMsg = exception.Message;
                return false;
            }
        }
 
        /// <summary>
        ///  获取动态IP
        /// </summary>
        /// <returns></returns>
        public string getLocalIP()
        {
            string str2 = null;
            IPHostEntry hostByName = Dns.GetHostByName(Dns.GetHostName());
            int length = hostByName.AddressList.Length;
            for (int i = 0; i < length; i++)
            {
                IPAddress address = hostByName.AddressList[i];
                str2 = Convert.ToString(address);
                if (str2.Substring(0, 5) == "10.10")
                {
                    return str2;
                }
            }
            return str2;
        }
 
        /// <summary>
        /// 
        /// </summary>
        /// <param name="_paraMPairs"></param>
        /// <param name="errMsg"></param>
        /// <returns></returns>
        public short[,] GetLowerComputerStatus(short[] _paraMPairs, out string errMsg)
        {
            try
            {
                var type = new
                {
                    command = 9,
                    paraM = _paraMPairs
                };
                string resquestStr = this.SendSocketMessage(JsonExtensions.ToJson(type, false, false, false));
                if (this.ResquestResult(resquestStr, out Result result, out errMsg))
                {
                    Dictionary<short, short> dictionary = JsonUtil.ToObject<Dictionary<short, short>>(result.result.ToString());
                    short[,] numArray = new short[dictionary.Count, 2];
                    int num = 0;
                    foreach (KeyValuePair<short, short> pair in dictionary)
                    {
                        numArray[num, 0] = pair.Key;
                        numArray[num, 1] = pair.Value;
                        num++;
                    }
                    return numArray;
                }
                return null;
            }
            catch (Exception exception)
            {
                errMsg = exception.Message;
                return null;
            }
        }
 
        /// <summary>
        /// 初始化批量写参数
        /// </summary>
        public void InitParWriteMultiple()
        {
            this.paraMPairs.Clear();
        }
 
        /// <summary>
        /// 检查与LTSCADA是否断开连接了
        /// </summary>
        /// <param name="errMsg"></param>
        /// <returns></returns>
        public bool IsConnected(out string errMsg)
        {
            try
            {
                var type = new
                {
                    command = 6
                };
                string resquestStr = this.SendSocketMessage(JsonExtensions.ToJson(type, false, false, false));
                return this.ResquestResult(resquestStr, out _, out errMsg);
            }
            catch (Exception exception)
            {
                errMsg = exception.Message;
                return false;
            }
        }
 
        /// <summary>
        /// 
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="Pars"></param>
        /// <returns></returns>
        private static string ParsToString<T>(T Pars) =>
            null;
 
        /// <summary>
        /// 返回请求信息
        /// </summary>
        /// <param name="ResquestStr"></param>
        /// <param name="JResult"></param>
        /// <param name="errMsg"></param>
        /// <returns></returns>
        private bool ResquestResult(string ResquestStr, out Result JResult, out string errMsg)
        {
            errMsg = string.Empty;
            JResult = null;
            try
            {
                JResult = JsonConvert.DeserializeObject<Result>(ResquestStr);
                if (!JResult.success)
                {
                    errMsg = "请求失败:" + JResult.message;
                    return false;
                }
                return true;
            }
            catch (Exception exception)
            {
                errMsg = JResult?.message + " --- " + exception.Message;
                return false;
            }
        }
 
 
        /// <summary>
        /// 接收数据超时时间
        /// </summary>
        public uint TimeRecOut { set; get; } = 20000;
 
        /// <summary>
        /// 线程锁
        /// </summary>
        private readonly object objLock = new object();
 
        /// <summary>
        /// 发送请求信息
        /// </summary>
        /// <param name="Cmd"></param>
        /// <returns></returns>
        private string SendSocketMessage(string Cmd)
        {
            string str2;
            try
            {
                string str = "";
                byte[] bytes = Encoding.UTF8.GetBytes(Cmd + "\r\n");
                lock (objLock)
                {
                    int available = this.ClientSocket.Available;
                    if (available > 0)
                    {
                        byte[] buffer2 = new byte[available];
                        this.ClientSocket.Receive(buffer2, 0, available, SocketFlags.None);
                    }
                    this.ClientSocket.Send(bytes);
                    bool flag = false;
                    int tickCount = Environment.TickCount;
                    int size = this.ClientSocket.Available;
                    bool flag2 = false;
                    while (((size < this.Size) && !flag) && !(flag2 = str.Contains("\r\n")))
                    {
                        Thread.Sleep(2);
                        size = this.ClientSocket.Available;
                        if ((size > this.Size) || (str.Length > this.Size))
                        {
                            throw new Exception($"接收数据超过设定值{this.Size}BYTE!");
                        }
                        flag = (Environment.TickCount - tickCount) > TimeRecOut;
                        if (flag)
                        {
                            if (size > 0)
                            {
                                byte[] buffer3 = new byte[size];
                                this.ClientSocket.Receive(buffer3, 0, size, SocketFlags.None);
                            }
                            throw new Exception("接收数据超时!");
                        }
                        if (!flag && (size > 0))
                        {
                            byte[] buffer4 = new byte[size];
                            this.ClientSocket.Receive(buffer4, 0, size, SocketFlags.None);
                            str = str + Encoding.UTF8.GetString(buffer4);
                        }
                    }
                }
                str2 = str;
            }
            catch (Exception exception)
            {
                throw new Exception(exception.Message);
            }
            return str2;
        }
 
        /// <summary>
        /// TcpPing
        /// </summary>
        /// <param name="Host"></param>
        /// <param name="Port"></param>
        /// <param name="errMsg"></param>
        /// <returns></returns>
        private bool TcpPing(string Host, int Port, out string errMsg)
        {
            bool flag = false;
            errMsg = string.Empty;
            Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            try
            {
                bool flag2 = socket.BeginConnect(Host, Port, null, null).AsyncWaitHandle.WaitOne(this._ConnectTimeout, true);
                if (!flag2)
                {
                    errMsg = "errTCPConnectionFailed";
                }
                flag = flag2;
            }
            catch
            {
                errMsg = "errTCPConnectionFailed";
                flag = false;
            }
            socket.Close();
            return flag;
        }
 
        /// <summary>
        /// 批量写
        /// </summary>
        /// <param name="_paraMPairs">参数列表</param>
        /// <param name="errMsg">错误信息</param>
        /// <returns>处理结果</returns>
        public bool ToFctWriteMultiple(Dictionary<int, string> _paraMPairs, out string errMsg)
        {
            try
            {
                var type = new
                {
                    command = 15,
                    paraM = _paraMPairs
                };
                string resquestStr = this.SendSocketMessage(JsonExtensions.ToJson(type, false, false, false));
                return this.ResquestResult(resquestStr, out _, out errMsg);
            }
            catch (Exception exception)
            {
                errMsg = exception.Message;
                return false;
            }
        }
 
        public bool Connect(object config, out string errMsg)
        {
            errMsg = null;
            return false;
        }
    }
}