lss
4 天以前 f3c8f980269b7f8fd9556c9076e06ca1461796e8
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
using EasyModbus;
using HH.WCS.JiaTong.process;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
 
namespace HH.WCS.JiaTong.device
{
    internal class PlcHelper
    {
 
        private static Dictionary<string, ModbusClient> clients = new Dictionary<string, ModbusClient>();
        private ModbusClient GetClient(string ip, int port)
        {
            ModbusClient client = null;
            LogHelper.Info($"GetClient:ip:{ip},port:{port}", "ModBus");
            if (!clients.ContainsKey(ip))
            {
                LogHelper.Info($"GetClient:ip:{ip},port:{port}.链接不存在,开始链接", "ModBus");
                client = new ModbusClient(ip, port);
                try
                {
                    client.Connect();
                    clients[ip] = client;
                    LogHelper.Info($"GetClient:ip:{ip},port:{port}.链接成功", "ModBus");
                }
                catch (Exception ex)
                {
                    LogHelper.Info($"GetClient:ip:{ip},port:{port}.链接异常:{ex.Message}", "ModBus");
                    LogHelper.Error(ex.Message, ex);
                }
            }
            return client;
        }
      
        internal static void Receive(string ip, string msg)
        {
            //处理设备信号
            DeviceProcess.Analysis(msg, ip);
        }
        internal static bool SendHex(string ip, string msg)
        {
            return TcpServer.TcpServerSend(ip, Hex2Bytes(msg));
 
        }
        internal static void SendAscii(string ip, string msg)
        {
            TcpServer.TcpServerSend(ip, Encoding.ASCII.GetBytes(msg));
        }
 
        internal static byte[] Hex2Bytes(string hexString)
        {
            hexString = hexString.Replace(" ", "");
            if ((hexString.Length % 2) != 0)
                hexString += " ";
            byte[] returnBytes = new byte[hexString.Length / 2];
            for (int i = 0; i < returnBytes.Length; i++)
                returnBytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16);
 
            return returnBytes;
        }
        internal static string Hex2Ascii(string hexString)
        {
            hexString = hexString.Replace(" ", "");
            if ((hexString.Length % 2) != 0)
                hexString += " ";
            byte[] returnBytes = new byte[hexString.Length / 2];
            for (int i = 0; i < returnBytes.Length; i++)
                returnBytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16);
 
            return Encoding.ASCII.GetString(returnBytes);
        }
 
 
       
        internal static bool[] ReadInputRegistersRtu1(int address, int qty, string ip, int port = 502)
        {
            //01 02 00 01 00 01 E8 0A 
            List<bool> res = new List<bool>();
            var hex = $"0102{address.ToString("X4")}{qty.ToString("X4")}";
            hex = hex + BitConverter.ToString(PlcHelper.CRC16LH(PlcHelper.Hex2Bytes(hex))).Replace("-", "").Replace(" ", "");
            LogHelper.Info($"电梯状态判断:{hex} ip:{ip},port{port} ", "电梯");
            var data = SendHexOnce(ip, port, hex);
            if (!string.IsNullOrEmpty(data))
            {
                string fh = data.Substring(6, 2);
                var xhw = Convert.ToString(Convert.ToInt32(fh, 16), 2);
                if (xhw.Length != 4)
                {
                    if (xhw.Length == 3)
                    {
                        xhw = '0' + xhw;
                    }
                    else if (xhw.Length == 2)
                    {
                        xhw = '0' + '0' + xhw;
                    }
                    else if (xhw.Length == 1)
                    {
                        xhw = '0' + '0' + '0' + xhw;
                    }
                }
 
                StringBuilder sb = new StringBuilder();
                for (int i = xhw.Length - 1; i >= 0; i--)
                {
                    sb.Append(xhw[i]);
                }
                foreach (var item in sb.ToString())
                {
                    if (true)
                    {
                        if (item == '1')
                        {
                            res.Add(true);
                        }
                        else
                        {
                            res.Add(false);
                        }
                    }
                }
 
            }
 
            return res.ToArray();
        }
 
      
 
        private static string SendHexOnce(string ip, int port, string hex)
        {
            var res = string.Empty;
            Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            client.Connect(ip, port);
            client.ReceiveTimeout = 2000;
            if (client.Connected)
            {
                client.Send(PlcHelper.Hex2Bytes(hex));
                byte[] buffer = new byte[1024];
                try
                {
                    var length = client.Receive(buffer, SocketFlags.None);
                    byte[] data = new byte[length];
                    Array.Copy(buffer, data, length);
                    res = BitConverter.ToString(data).Replace("-", "");
                }
                catch (Exception ex)
                {
                    LogHelper.Error(ex.Message, ex);
                }
                client.Disconnect(true);
                client.Dispose();
            }
            client = null;
            return res;
        }
     
        #region 进制转换+CRC
        internal static bool CheckCRC(string hex)
        {
            var result = false;
            var data = hex.Replace(" ", "");
            if (data.Length % 2 == 0)
            {
                var code1 = data.Substring(data.Length - 4, 4).ToLower();
                var code2 = BitConverter.ToString(CRC16LH(Hex2Bytes(data.Substring(0, data.Length - 4)))).Replace("-", "").Replace(" ", "").ToLower();
                result = code1 == code2;
            }
            return result;
        }
        internal static byte[] CRC16LH(byte[] pDataBytes)
        {
            ushort crc = 0xffff;
            ushort polynom = 0xA001;
 
            for (int i = 0; i < pDataBytes.Length; i++)
            {
                crc ^= pDataBytes[i];
                for (int j = 0; j < 8; j++)
                {
                    if ((crc & 0x01) == 0x01)
                    {
                        crc >>= 1;
                        crc ^= polynom;
                    }
                    else
                    {
                        crc >>= 1;
                    }
                }
            }
 
            byte[] result = BitConverter.GetBytes(crc);
            return result;
        }
        internal static byte[] CRC16HL(byte[] pDataBytes)
        {
            ushort crc = 0xffff;
            ushort polynom = 0xA001;
 
            for (int i = 0; i < pDataBytes.Length; i++)
            {
                crc ^= pDataBytes[i];
                for (int j = 0; j < 8; j++)
                {
                    if ((crc & 0x01) == 0x01)
                    {
                        crc >>= 1;
                        crc ^= polynom;
                    }
                    else
                    {
                        crc >>= 1;
                    }
                }
            }
 
            byte[] result = BitConverter.GetBytes(crc).Reverse().ToArray();
            return result;
        }
 
        #endregion
    }
}