lss
3 天以前 9cba325e0d7c30644606e63e5df01faba0c42038
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
using HH.WCS.JiaTong_DCJ;
using HH.WCS.JiaTong_DCJ.device;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
 
namespace HH.WCS.JiaTong_DCJ.device {
    internal class TcpClient
    {
       
        /// <summary>
        /// 
        /// </summary>
        /// <param name="ip">127.0.0.1</param>
        /// <param name="port">8888</param>
        /// <param name="hex">01 02 00 00 00 0C 78 0F</param>
        /// <returns></returns>
        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;
        }
 
        /// <summary>
        /// 
        /// </summary>
        /// <param name="ip">127.0.0.1</param>
        /// <param name="port">8888</param>
        /// <param name="hex">01 02 00 00 00 0C 78 0F</param>
        /// <returns></returns>
        public static async Task SendHexOnce1(string ip, int port, string hex)
        {
            var res = string.Empty;
            try
            {
                Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                var connectTask = client.ConnectAsync(ip, port);
                // 设置超时但不阻塞
                var timeoutTask = Task.Delay(2000);
                var completedTask = await Task.WhenAny(connectTask, timeoutTask);
                if (completedTask != connectTask)
                {
                    LogHelper.Info("连接超时", "HosttoagvTask");
                    return;
                }
 
                client.Send(PlcHelper.Hex2Bytes(hex));
                byte[] buffer = new byte[1024];
 
                var length = client.Receive(buffer, SocketFlags.None);
                byte[] data = new byte[length];
                Array.Copy(buffer, data, length);
                res = BitConverter.ToString(data).Replace("-", "");
 
                client.Disconnect(true);
                client.Dispose();
                client = null;
            }
            catch (Exception ex)
            {
                LogHelper.Error(ex.Message, ex);
            }
        }
 
        /// <summary>
        /// 读保持寄存器,modbus rtu的封装
        /// </summary>
        /// <param name="address"></param>
        /// <param name="qty"></param>
        /// <param name="ip"></param>
        /// <param name="port"></param>
        /// <returns></returns>
        internal int[] ReadInputRegistersRtu(int address, int qty, string ip, int port = 502) {
            List<int> res = new List<int>();
            var hex = $"0103{address.ToString("X4")}{qty.ToString("X4")}";
            hex = hex + BitConverter.ToString(PlcHelper.CRC16LH(PlcHelper.Hex2Bytes(hex))).Replace("-", "").Replace(" ", "");
            var data = SendHexOnce(ip, port, hex);
            if (!string.IsNullOrEmpty(data)) {
                if (PlcHelper.CheckCRC(data)) {
                    var lenght = Convert.ToInt16(data.Substring(4, 2), 16) / 2;
                    for (int i = 0; i < lenght; i++) {
                        res[i] = Convert.ToInt16(data.Substring(6 + 4 * 1, 4), 16);
                    }
                }
            }
            return res.ToArray();
        }
 
        /// <summary>
        /// 写单个寄存器
        /// </summary>
        /// <param name="address"></param>
        /// <param name="value"></param>
        /// <param name="ip"></param>
        /// <param name="port"></param>
        internal bool WriteSingleRegisterRtu(int address, int value, string ip, int port = 502) {
            var res = false;
            var hex = $"0106{address.ToString("X4")}{value.ToString("X4")}";
            hex = hex + BitConverter.ToString(PlcHelper.CRC16LH(PlcHelper.Hex2Bytes(hex))).Replace("-", "").Replace(" ", "");
            var data = SendHexOnce(ip, port, hex);
            if (!string.IsNullOrEmpty(data)) {
                res = true;
            }
            return res;
        }
    }
}