schangxiang@126.com
2025-07-23 ba449717184ae09590aaead8a7240103b26cec5e
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
using System;
using S7.Net;
using iWareCommon.Utils;
using HslCommunication.Profinet.Siemens;
using HslCommunication;
 
using iWareCommon;
using iWareModel;
namespace iWareSda
{
    /// <summary>
    /// 西么子PLC
    /// </summary>
    public class Siemens_HslCommunicationService : PLCService
    {
        private SiemensS7Net siemensTcpNet = null;
        private readonly SiemensPLCS _cpu;
        private readonly string _ip;
        private readonly int _port;
        public Siemens_HslCommunicationService(HslCommunicationParam hslcpParam)
        {
            _cpu = hslcpParam.cpu;
            _ip = hslcpParam.ip;
            _port = hslcpParam.port;
 
            _LogType = LogType.HslCommunicationService;
        }
        /// <summary>
        /// 打开连接
        /// </summary>
        /// <returns></returns>
        public override MessageModel OpenService()
        {
            MessageModel fre = new MessageModel();
            try
            {
                //创建连接对象
                siemensTcpNet = new SiemensS7Net(_cpu, _ip);
                siemensTcpNet.IpAddress = _ip;
                siemensTcpNet.Port = Convert.ToInt16(_port);
                //siemensTcpNet.Rack = Convert.ToInt16(tb_Rack.Text);
                //siemensTcpNet
                //不记录日志!!!!否则文件太大导致问题!
                //siemensTcpNet.LogNet = new HslCommunication.LogNet.LogNetSingle("Siemens_HslCommunicationService_logs.txt");
 
                OperateResult operateResult = siemensTcpNet.ConnectServer();
                if (operateResult.IsSuccess)
                {
                    base.IsConnected = true;
                    fre.result = true;
                    return fre;
                }
                base.IsConnected = false;
                fre.result = false;
                fre.resMsg = "打开失败," + operateResult.Message;
                return fre;
            }
            catch (Exception ex)
            {
                base.IsConnected = false;
                Log4NetHelper.WriteErrorLog(_LogType, "初始化西门子PLC出现异常", ex);
                throw ex;
            }
        }
 
        /// <summary>
        /// 写入
        /// </summary>
        /// <param name="address">地址</param>
        /// <param name="value">值</param>
        /// <returns></returns>
        public override MessageModel WriteValuePoint(string dbNumber, string offset, object value, Object proObj)
        {//此方法不再使用西门子PLC
            if (dbNumber.IndexOf(WareSdaStruct.PLCDBADDRESS_SEPARATE.ToString()) > -1)
            {
                throw new Exception("参数不正确,不应该带" + WareSdaStruct.PLCDBADDRESS_SEPARATE.ToString());
            }
            MessageModel fre = new MessageModel();
            OperateResult operateResult = null;
            Type proObjType = proObj.GetType();
            var address = GetAddress(dbNumber, offset, value.GetType());
            try
            {
                if (proObjType == typeof(bool))
                {//布尔类型
                    bool myData = Convert.ToBoolean(value);
                    operateResult = siemensTcpNet.Write(address, myData);
                }
                //浮点
                else if (proObjType == typeof(double) || proObjType == typeof(float))
                {
                    double MyData = Convert.ToDouble(value);
                    operateResult = siemensTcpNet.Write(address, MyData);
 
                }
                //整数
                else if (proObjType == typeof(Int16) || proObjType == typeof(short))
                {
                    short MyData = Convert.ToInt16(value);
                    operateResult = siemensTcpNet.Write(address, MyData.ConvertToUshort());
                }
                //双整数
                else if (proObjType == typeof(Int32))
                {
                    int myData = Convert.ToInt32(value);
                    operateResult = siemensTcpNet.Write(address, myData);
                }
                //Char
                else if (proObjType == typeof(Char))
                {//char要转换成int类型,写给PLC
                    int myData = Convert.ToInt32(value);
                    byte b = (byte)myData;
                    operateResult = siemensTcpNet.Write(address, b);
                }
                //String
                else if (proObjType == typeof(String))
                {
                    operateResult = siemensTcpNet.Write(address, value.ToString());
                }
                else
                {
                    operateResult = siemensTcpNet.Write(address, value.ToString());
                }
                if (!operateResult.IsSuccess)
                {
                    Log4NetHelper.WriteErrorLog(_LogType, String.Format("写入出现异常:" + operateResult.Message + ",地址:{0},值:{1}", address, value.ToString()), null);
                    fre.result = false;
                    fre.resMsg = "写入失败:" + operateResult.Message;
                }
                else
                {
                    fre.result = true;
                    Log4NetHelper.WriteInfoLog(_LogType, String.Format("写入成功,写入地址:{0},值:{1}", address, value.ToString()));
                }
            }
            catch (Exception ex)
            {
                Log4NetHelper.WriteErrorLog(_LogType, String.Format("写入出现异常:" + ex.Message + ",地址:{0},值:{1}", address, value.ToString()), ex);
                fre.result = false;
                fre.resMsg = "写入失败:" + ex.Message;
            }
            return fre;
        }
 
        //public override MessageModel WriteValuePoint(string fullAddress, object value, object proObj)
        //{
        //    if (string.IsNullOrEmpty(fullAddress))
        //    {
        //        return new MessageModel() { result = false, resMsg = "地址为空" };
        //    }
        //    var arr = fullAddress.Split(WareSdaStruct.PLCDBADDRESS_SEPARATE);
        //    string dbNumber = arr[0];
        //    string offset = arr[1];
        //    return WriteValuePoint(dbNumber, offset, value, proObj);
        //}
 
        /// <summary>
        /// 写入方法(需要验证是否真正写入了) 【Editby shaocx,2025-07-16】
        /// </summary>
        /// <param name="fullAddress"></param>
        /// <param name="value"></param>
        /// <param name="proObj"></param>
        /// <returns></returns>
        public override MessageModel WriteValuePoint(string fullAddress, object value, object proObj)
        {
            return WriteValuePointForReValidateWriteSucess(fullAddress, value, proObj);
        }
        /// <summary>
        /// 写入(需要验证是否真正写入了)
        /// </summary>
        /// <param name="fullAddress"></param>
        /// <param name="value"></param>
        /// <param name="proObj"></param>
        /// <returns></returns>
        public override MessageModel WriteValuePointForReValidateWriteSucess(string fullAddress, object value, object proObj)
        {
            if (string.IsNullOrEmpty(fullAddress)) return new MessageModel()
            {
                result = false,
                resMsg = "地址是空的"
            };
            var arr = fullAddress.Split(WareSdaStruct.PLCDBADDRESS_SEPARATE);
            string dbNumber = arr[0];
            string offset = arr[1];
            var ret = WriteValuePoint(dbNumber, offset, value, proObj);
            if (ret.result == false) return ret;
 
            //需要重新读取下
            var readRet = ReadValuePoint(dbNumber, offset, proObj.GetType());
            if (readRet?.ToString() != value?.ToString())
            {
                return new MessageModel()
                {
                    result = false,
                    resMsg = $"写入的值{value}跟读取的值{readRet}不符,dbNumber:{dbNumber},offset:{offset}"
                };
            }
            return ret;
        }
 
        /// <summary>
        /// 读取
        /// </summary>
        /// <param name="dbNumber">DB块名</param>
        /// <param name="offset">偏移量</param>
        /// <param name="type"></param>
        /// <returns></returns>
        public override object ReadValuePoint(string dbNumber, string offset, Type type = default(Type))
        {
            if (dbNumber.IndexOf(WareSdaStruct.PLCDBADDRESS_SEPARATE.ToString()) > -1)
            {
                throw new Exception("参数不正确,不应该带" + WareSdaStruct.PLCDBADDRESS_SEPARATE.ToString());
            }
            var address = GetAddress(dbNumber, offset, type);
            try
            {
                if (type == typeof(bool))
                {//布尔要转换成1和0写入
                    bool MyPlcData = siemensTcpNet.ReadBool(address).Content;
                    return MyPlcData;
                }
                //浮点
                else if (type == typeof(double) || type == typeof(float))
                {
                    var MyPlcData = siemensTcpNet.ReadFloat(address).Content;
                    return MyPlcData;
 
                }
                //整数
                else if (type == typeof(short))
                {
                    int MyPlcData = siemensTcpNet.ReadInt16(address).Content;
                    return MyPlcData;
                }
                //双整数
                else if (type == typeof(Int32))
                {
                    long MyPlcData = siemensTcpNet.ReadInt32(address).Content;
                    return MyPlcData;
                }
                //Char
                else if (type == typeof(Char))
                {//char要转换成int类型,写给PLC
                    char MyPlcData = (char)(siemensTcpNet.ReadByte(address).Content);
                    return MyPlcData.ToString();
                }
                //String
                else if (type == typeof(String))
                {
                    var MyPlcData = siemensTcpNet.ReadString(address).Content;
                    return MyPlcData == null ? "" : MyPlcData.ToString();
                }
                else
                {
                    var MyPlcData = siemensTcpNet.ReadString(address).Content;
                    return MyPlcData == null ? "" : MyPlcData.ToString();
                }
            }
            catch (Exception ex)
            {
                Log4NetHelper.WriteErrorLog(_LogType, String.Format("读取出现异常:" + ex.Message + ",地址:{0}", address), ex);
                throw;
            }
        }
 
        public override object ReadValuePoint(string fullAddress, Type type = default(Type))
        {
            var arr = fullAddress.Split(WareSdaStruct.PLCDBADDRESS_SEPARATE);
            string dbNumber = arr[0];
            string offset = arr[1];
            return ReadValuePoint(dbNumber, offset, type);
        }
 
 
        public override string GetAddress(string dbNumber, string offset, Type type = default(Type))
        {
            return "DB" + dbNumber + "." + offset;
        }
 
        public override void Close()
        {
            if (siemensTcpNet != null)
                siemensTcpNet.ConnectClose();
        }
    }
}